#!/usr/bin/env node /** * 打包半自动兑换助手。 * * 作用:把 order_site 后台管理域写进 manifest.content_scripts.matches,避免把生产域名 * 硬编码进仓库,也避免扩展在非白名单站点上生效。 * * 用法: * node build.mjs # 只带仓库内的开发域,用于本地加载 * ADMIN_ORIGINS="https://order.example.com" node build.mjs * node build.mjs --env-file /srv/order-site/.env # 从部署环境文件读 CADDY_SITE_ADDR * * 产物:dist/(Chrome「加载已解压的扩展程序」选这个目录) */ import fs from 'node:fs' import path from 'node:path' import process from 'node:process' import { fileURLToPath } from 'node:url' const SOURCE_DIR = path.dirname(fileURLToPath(import.meta.url)) const DIST_DIR = path.join(SOURCE_DIR, 'dist') const COPY_FILES = ['relay.js', 'background.js', 'icon16.png', 'icon48.png', 'icon128.png'] /** 从 `--env-file` 或 `ADMIN_ENV_FILE` 读取部署环境里的后台域名。 */ function readAdminOriginsFromEnvFile() { const args = process.argv.slice(2) const flagIndex = args.indexOf('--env-file') const envPath = flagIndex >= 0 ? args[flagIndex + 1] : String(process.env.ADMIN_ENV_FILE || '').trim() if (!envPath) return '' const raw = fs.readFileSync(path.resolve(envPath), 'utf8') for (const line of raw.split(/\r?\n/)) { const trimmed = line.trim() if (!trimmed || trimmed.startsWith('#')) continue const match = /^(?:export\s+)?CADDY_SITE_ADDR\s*=\s*(.*)$/.exec(trimmed) if (!match) continue return match[1].trim().replace(/^['"]/, '').replace(/['"]$/, '') } return '' } function parseOrigins(raw) { return String(raw || '') .split(',') .map((item) => item.trim()) .filter(Boolean) .map((item) => { let url try { url = new URL(item) } catch (e) { throw new Error(`ADMIN_ORIGINS 里的地址无法解析:${item}`) } if (url.protocol !== 'http:' && url.protocol !== 'https:') { throw new Error(`ADMIN_ORIGINS 只接受 http/https:${item}`) } return `${url.origin}/*` }) } function main() { const manifest = JSON.parse(fs.readFileSync(path.join(SOURCE_DIR, 'manifest.json'), 'utf8')) const envFileOrigin = readAdminOriginsFromEnvFile() const combined = [process.env.ADMIN_ORIGINS || '', envFileOrigin].filter(Boolean).join(',') const extraMatches = parseOrigins(combined) const contentScripts = (manifest.content_scripts || []).map((entry) => ({ ...entry, matches: [...new Set([...(entry.matches || []), ...extraMatches])], })) const output = { ...manifest, content_scripts: contentScripts } fs.rmSync(DIST_DIR, { recursive: true, force: true }) fs.mkdirSync(DIST_DIR, { recursive: true }) fs.writeFileSync( path.join(DIST_DIR, 'manifest.json'), `${JSON.stringify(output, null, 2)}\n`, 'utf8', ) for (const file of COPY_FILES) { const from = path.join(SOURCE_DIR, file) if (!fs.existsSync(from)) continue fs.copyFileSync(from, path.join(DIST_DIR, file)) } const matches = contentScripts.flatMap((entry) => entry.matches || []) console.log(`[build-extension] 已生成 ${path.relative(process.cwd(), DIST_DIR)}`) console.log(`[build-extension] 生效站点:${matches.join(', ') || '(无)'}`) if (extraMatches.length === 0) { console.log( '[build-extension] 未提供后台域名(ADMIN_ORIGINS 或 --env-file),当前产物只适用于本地开发页', ) } } main()