@melt-js/libs-core 2026.11.14 → 2026.11.15-1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,180 @@
1
+ #!/usr/bin/env node
2
+ // Package-local publication artifacts. Never searches the workspace or builds siblings.
3
+ import fs from 'node:fs'
4
+ import path from 'node:path'
5
+ import { createRequire } from 'node:module'
6
+ import { pathToFileURL, fileURLToPath } from 'node:url'
7
+ import { spawnSync } from 'node:child_process'
8
+ import ts from 'typescript'
9
+ import { build } from 'esbuild'
10
+
11
+ const slash = value => value.replaceAll('\\', '/')
12
+ const walk = dir => fs.existsSync(dir) ? fs.readdirSync(dir, { withFileTypes: true }).flatMap(entry => entry.isDirectory() && entry.name !== 'node_modules' ? walk(path.join(dir, entry.name)) : entry.isFile() ? [path.join(dir, entry.name)] : []) : []
13
+ const write = (file, content) => { fs.mkdirSync(path.dirname(file), { recursive: true }); fs.writeFileSync(file, content) }
14
+ const copy = (from, to) => { fs.mkdirSync(path.dirname(to), { recursive: true }); fs.copyFileSync(from, to) }
15
+
16
+ export function cleanDeclarationStyles(directory) {
17
+ for (const file of walk(directory).filter(file => /\.d\.(ts|mts)$/.test(file))) {
18
+ const text = fs.readFileSync(file, 'utf8')
19
+ fs.writeFileSync(file, text.replace(/^\s*import\s*['"][^'"\n]+\.(?:css|scss|less)['"];?\s*$/gm, ''))
20
+ }
21
+ }
22
+
23
+ export async function buildPackageArtifacts(root = process.cwd()) {
24
+ root = path.resolve(root)
25
+ const pkg = JSON.parse(fs.readFileSync(path.join(root, 'package.json'), 'utf8'))
26
+ const config = pkg.releaseArtifacts
27
+ if (!config) throw new Error(`${pkg.name}: 缺少 releaseArtifacts 配置`)
28
+ const src = path.join(root, 'src')
29
+ const out = path.resolve(root, config.outDir)
30
+ if (!out.startsWith(root + path.sep)) throw new Error('产物必须位于包目录内')
31
+ const localRequire = createRequire(path.join(root, 'package.json'))
32
+
33
+ if (config.mode === 'declarations') { cleanDeclarationStyles(out); return }
34
+
35
+ if (config.mode === 'adapter') {
36
+ for (const file of walk(src)) {
37
+ const dest = path.join(out, path.relative(src, file))
38
+ if (/\.mjs$/.test(file)) await build({ entryPoints: [file], outfile: dest, minify: true, target: 'es2019', format: 'esm', sourcemap: false })
39
+ else if (/\.d\.(ts|mts)$/.test(file)) copy(file, dest)
40
+ }
41
+ return
42
+ }
43
+
44
+ const typeOut = path.join(out, 'types')
45
+ const previousOutputs = config.mode === 'library' ? [out] : ['types', 'assets', 'subpaths'].map(dir => path.join(out, dir))
46
+ if (previousOutputs.some(dir => walk(dir).length)) {
47
+ const history = path.join(root, '.tmp/release-artifact-history', Date.now() + '-' + process.pid)
48
+ fs.mkdirSync(history, { recursive: true })
49
+ // File-by-file moves also work when a Windows editor holds the directory open.
50
+ for (const file of previousOutputs.flatMap(walk)) {
51
+ const archived = path.join(history, path.relative(out, file))
52
+ fs.mkdirSync(path.dirname(archived), { recursive: true })
53
+ fs.renameSync(file, archived)
54
+ }
55
+ }
56
+ const sourceConfig = path.join(root, 'tsconfig.json')
57
+ const parsed = fs.existsSync(sourceConfig) ? ts.getParsedCommandLineOfConfigFile(sourceConfig, {}, { ...ts.sys, onUnRecoverableConfigFileDiagnostic: diagnostic => { throw new Error(ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')) } }) : { options: {} }
58
+ const compilerOptions = {
59
+ ...parsed.options, rootDir: src, outDir: typeOut, noEmit: false, declaration: true,
60
+ emitDeclarationOnly: true, declarationMap: false, sourceMap: false, noCheck: true,
61
+ composite: false, incremental: false, allowJs: true, skipLibCheck: true, preserveSymlinks: true,
62
+ }
63
+ delete compilerOptions.tsBuildInfoFile
64
+ const allDeclarations = walk(src).filter(file => /\.d\.(ts|mts)$/.test(file))
65
+ const entryTypes = String(pkg.types || '').replace(/^\.?\/?hel_proxy_es\/types\//, 'src/')
66
+ const sourceTypes = path.resolve(root, entryTypes)
67
+ const typeEntry = fs.existsSync(sourceTypes) ? sourceTypes : sourceTypes.replace(/\.d\.ts$/, '.ts')
68
+ const inputs = config.mode === 'library'
69
+ ? [...Object.values(config.entries).map(file => path.resolve(root, file)), ...allDeclarations]
70
+ : config.declarationDir ? [] : [...(pkg.types ? [typeEntry] : []), ...Object.values(config.proxies || {}).map(entry => path.resolve(root, entry.source)), ...allDeclarations]
71
+ if (config.vue && inputs.length) {
72
+ const tempConfig = path.join(root, '.tmp/release-tsconfig.json')
73
+ write(tempConfig, JSON.stringify({ extends: fs.existsSync(sourceConfig) ? sourceConfig : undefined,
74
+ compilerOptions: { rootDir: src, outDir: typeOut, noEmit: false, declaration: true, emitDeclarationOnly: true,
75
+ declarationMap: false, sourceMap: false, noCheck: true, composite: false, incremental: false, allowJs: true, preserveSymlinks: true },
76
+ files: inputs.map(slash), include: [],
77
+ exclude: ['**/node_modules/**'],
78
+ }, null, 2))
79
+ const require = createRequire(import.meta.url)
80
+ const result = spawnSync(process.execPath, [require.resolve('vue-tsc/bin/vue-tsc.js'), '-p', tempConfig], { cwd: root, stdio: 'inherit' })
81
+ if (result.status !== 0) throw new Error(`${pkg.name}: 声明生成失败`)
82
+ } else if (inputs.length) {
83
+ const program = ts.createProgram(inputs, compilerOptions)
84
+ const result = program.emit()
85
+ if (result.emitSkipped || result.diagnostics.length) throw new Error(ts.formatDiagnosticsWithColorAndContext(result.diagnostics, { getCurrentDirectory: () => root, getCanonicalFileName: x => x, getNewLine: () => '\n' }))
86
+ }
87
+ // Declaration inputs are not copied by tsc. Preserve their dependency closure.
88
+ if (!config.declarationDir) for (const file of allDeclarations) copy(file, path.join(typeOut, path.relative(src, file)))
89
+ if (config.declarationDir) {
90
+ for (const file of walk(path.join(root, config.declarationDir))) copy(file, path.join(typeOut, path.relative(path.join(root, config.declarationDir), file)))
91
+ }
92
+ cleanDeclarationStyles(typeOut)
93
+ // Resolve package-local aliases in emitted declarations to the published tree.
94
+ for (const file of walk(typeOut).filter(file => /\.d\.(ts|mts)$/.test(file))) {
95
+ const relative = path.relative(typeOut, file).replace(/\.d\.ts$/, '.ts')
96
+ const source = path.join(src, relative)
97
+ const text = fs.readFileSync(file, 'utf8').replace(/(['"])([^'"\n]+)\1/g, (match, quote, specifier) => {
98
+ if (specifier.startsWith('.') || (!specifier.startsWith('#') && !specifier.startsWith('@/') && !specifier.startsWith(pkg.name + '/'))) return match
99
+ const resolved = ts.resolveModuleName(specifier, source, parsed.options, ts.sys).resolvedModule?.resolvedFileName
100
+ if (!resolved || !resolved.startsWith(src + path.sep)) {
101
+ if (specifier.startsWith(pkg.name + '/')) return match
102
+ throw new Error(`${file}: 无法解析本包类型别名 ${specifier}`)
103
+ }
104
+ let target = slash(path.relative(path.dirname(file), path.join(typeOut, path.relative(src, resolved))))
105
+ target = target.replace(/(?:\.d)?\.tsx?$/, '.js')
106
+ return quote + (target.startsWith('.') ? target : './' + target) + quote
107
+ })
108
+ const portable = text.replace(/(['"])(\.[^'"\n]+)\1/g, (match, quote, specifier) => {
109
+ if (/\.(?:[cm]?js|[cm]?ts|tsx|vue|json)$/.test(specifier)) return match
110
+ const target = path.resolve(path.dirname(file), specifier)
111
+ if (fs.existsSync(target + '.d.ts')) return quote + specifier + '.js' + quote
112
+ if (fs.existsSync(path.join(target, 'index.d.ts'))) return quote + specifier.replace(/\/$/, '') + '/index.js' + quote
113
+ return match
114
+ })
115
+ fs.writeFileSync(file, portable)
116
+ }
117
+ // Schemas and style resources are data, never a reason to ship implementation sources.
118
+ for (const file of walk(src).filter(file => config.mode === 'library' || config.styles
119
+ ? /\.(json|css|scss|less|svg|woff2?|ttf|png|jpe?g|gif)$/.test(file)
120
+ : /propsSchema\.json$/.test(file))) {
121
+ copy(file, path.join(out, 'assets', path.relative(src, file)))
122
+ if (/\.json$/.test(file)) copy(file, path.join(typeOut, path.relative(src, file)))
123
+ }
124
+
125
+ if (config.mode === 'library') {
126
+ const entries = config.entries
127
+ if (config.vite) {
128
+ const { build: viteBuild } = await import(pathToFileURL(localRequire.resolve('vite')).href)
129
+ const { default: vue } = await import(pathToFileURL(localRequire.resolve('@vitejs/plugin-vue')).href)
130
+ const plugins = [vue()]
131
+ if (config.tailwind) {
132
+ const { default: tailwind } = await import(pathToFileURL(localRequire.resolve('@tailwindcss/vite')).href)
133
+ plugins.push(tailwind())
134
+ }
135
+ await viteBuild({ configFile: false, root, plugins, css: { postcss: { plugins: [] } },
136
+ build: { outDir: out, emptyOutDir: false, minify: true, sourcemap: false, target: 'es2020',
137
+ lib: { entry: Object.fromEntries(Object.entries(entries).map(([key, value]) => [key, path.join(root, value)])), formats: ['es'], fileName: (_format, name) => name + '.js' },
138
+ rollupOptions: { external: id => !id.startsWith('.') && !path.isAbsolute(id) && !id.startsWith('\0') },
139
+ },
140
+ })
141
+ // Vite library CSS is extracted. Preserve the original design side effect.
142
+ if (entries.design) fs.appendFileSync(path.join(out, 'design.js'), `\nimport './${pkg.name.split('/').at(-1)}.css'\n`)
143
+ } else {
144
+ await build({ absWorkingDir: root, entryPoints: entries, outdir: out, bundle: true, packages: 'external', format: 'esm', platform: 'neutral', target: 'es2022', minify: true, sourcemap: false })
145
+ }
146
+ if (config.bin) {
147
+ await build({ absWorkingDir: root, entryPoints: [config.bin], outfile: path.join(out, 'cli.mjs'), bundle: true, packages: 'external', platform: 'node', format: 'esm', target: 'node22', minify: true, banner: { js: '#!/usr/bin/env node' } })
148
+ }
149
+ }
150
+ if (config.resolver) {
151
+ await build({ absWorkingDir: root, entryPoints: [config.resolver], outfile: path.join(out, 'resolver.js'), bundle: true, packages: 'external', platform: 'node', format: 'esm', minify: true,
152
+ plugins: [{ name: 'package-name', setup(builder) { builder.onLoad({ filter: /resolver\.ts$/ }, args => ({ loader: 'ts', contents: fs.readFileSync(args.path, 'utf8').replace("createRequire(import.meta.url)('./package.json').name", JSON.stringify(pkg.name)) })) } }],
153
+ })
154
+ const program = ts.createProgram([path.join(root, config.resolver)], { ...compilerOptions, rootDir: root, outDir: path.join(typeOut, '__tools') })
155
+ if (program.emit().emitSkipped) throw new Error('resolver 声明生成失败')
156
+ }
157
+ if (config.proxies) {
158
+ const program = ts.createProgram(inputs, { ...parsed.options, noCheck: true })
159
+ const checker = program.getTypeChecker()
160
+ for (const [name, entry] of Object.entries(config.proxies)) {
161
+ const source = program.getSourceFile(path.join(root, entry.source))
162
+ const symbol = source && checker.getSymbolAtLocation(source)
163
+ if (!symbol) throw new Error(`${pkg.name}: 无法读取子路径 ${entry.source}`)
164
+ const names = checker.getExportsOfModule(symbol).filter(symbol => {
165
+ const declarations = symbol.declarations || []
166
+ if (declarations.every(d => ts.isInterfaceDeclaration(d) || ts.isTypeAliasDeclaration(d) || (ts.isExportSpecifier(d) && (d.isTypeOnly || d.parent.parent.isTypeOnly)))) return false
167
+ const target = symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol
168
+ return Boolean(target.flags & ts.SymbolFlags.Value)
169
+ }).map(symbol => symbol.name)
170
+ const body = [`import lib from '../entry.js'`, `const namespace = lib[${JSON.stringify(entry.namespace)}]`]
171
+ for (const key of names) body.push(key === 'default'
172
+ ? `export default namespace["default"]`
173
+ : `export const ${key} = namespace[${JSON.stringify(key)}]`)
174
+ write(path.join(out, 'subpaths', name + '.js'), body.join('\n') + '\n')
175
+ }
176
+ }
177
+ console.log(`[package-artifacts] ${pkg.name}: ${out}`)
178
+ }
179
+
180
+ if (process.argv[1] && fs.realpathSync(process.argv[1]) === fileURLToPath(import.meta.url)) await buildPackageArtifacts()
@@ -1,180 +1,193 @@
1
- const fs = require('node:fs')
2
- const path = require('node:path')
3
- const { createRequire } = require('node:module')
4
- const dotenv = require('dotenv')
5
- const { expand } = require('dotenv-expand')
6
- const { packageRef, packageUrl } = require('../src/remote-address.cjs')
7
-
8
- const PUBLIC_ENV_KEYS = ['SFTP_PUBLIC_URL', 'GITHUB_PUBLIC_URL', 'UNPKG_PUBLIC_URL']
9
- const TARGETS = ['local', 'sftp', 'github', 'unpkg']
10
- const trim = value => String(value || '').trim().replace(/\/+$/, '')
11
-
12
- function readEnvFile(file) {
13
- return fs.existsSync(file) ? dotenv.parse(fs.readFileSync(file)) : {}
14
- }
15
-
16
- function readPackageFiles(cwd, mode) {
17
- // The root orchestrator copies only public bases here. Never read a parent directory.
18
- return Object.assign({}, ...[
19
- '.env.defaults', '.env.workspace.local', '.env', '.env.local', `.env.${mode}`, `.env.${mode}.local`,
20
- ].map(name => readEnvFile(path.join(cwd, name))))
21
- }
22
-
23
- function remoteSlots(env) {
24
- return Object.keys(env).filter(key => /^[A-Z][A-Z\d_]*_PACKAGE$/.test(key) && !/^(?:DEPLOY_|VITE_|VUE_APP_|REACT_APP_|HEL_)/.test(key))
25
- .map(key => key.slice(0, -8))
26
- }
27
-
28
- function resolveTarget(value, mode) {
29
- const target = String(value || 'auto').toLowerCase()
30
- if (target === 'auto') return ['development', 'mock'].includes(mode) ? 'local' : 'unpkg'
31
- if (!TARGETS.includes(target)) throw new Error(`[hel-env] Unknown remote target: ${target}`)
32
- return target
33
- }
34
-
35
- // Resolve metadata from an installed dependency, never from a sibling/source checkout.
36
- function installedVersion(cwd, packageName) {
37
- const fromPackage = createRequire(path.join(cwd, 'package.json'))
38
- try {
39
- return JSON.parse(fs.readFileSync(fromPackage.resolve(packageName + '/package.json'), 'utf8')).version
40
- } catch (error) {
41
- if (!['ERR_PACKAGE_PATH_NOT_EXPORTED', 'MODULE_NOT_FOUND'].includes(error.code)) throw error
42
- }
43
- let directory = path.dirname(fromPackage.resolve(packageName))
44
- for (;;) {
45
- const manifest = path.join(directory, 'package.json')
46
- if (fs.existsSync(manifest)) {
47
- const pkg = JSON.parse(fs.readFileSync(manifest, 'utf8'))
48
- if (pkg.name === packageName) return pkg.version
49
- }
50
- const parent = path.dirname(directory)
51
- if (parent === directory) throw new Error(`[hel-env] Cannot resolve installed version of ${packageName}; set the dependency's VERSION explicitly`)
52
- directory = parent
53
- }
54
- }
55
-
56
- function resolveRemoteUrl(env, slot, target) {
57
- const packageName = env[`${slot}_PACKAGE`]
58
- if (target === 'local') {
59
- const url = trim(env[`${slot}_LOCAL_URL`])
60
- if (!url) throw new Error(`[hel-env] ${slot}_LOCAL_URL is required for local development`)
61
- return url
62
- }
63
- const base = trim(env[`${target.toUpperCase()}_PUBLIC_URL`])
64
- let version = env[`DEPLOY_${slot}_VERSION`] || env[`${slot}_VERSION`] || 'latest'
65
- if (target === 'unpkg' && version === 'installed') version = installedVersion(env.HEL_ENV_PACKAGE || process.cwd(), packageName)
66
- const output = env[`${slot}_OUTPUT_DIR`] || 'hel_dist'
67
- const entry = env[`${slot}_ENTRY`] || 'hel-meta.json'
68
- try {
69
- const parsed = packageRef(packageName)
70
- parsed.version = version
71
- const url = packageUrl(parsed, {
72
- type: target === 'sftp' ? 'custom' : target, base,
73
- projectName: target === 'unpkg' ? undefined : env[`${slot}_PROJECT`],
74
- // Static deployments update project directories; unpkg versions are npm versions.
75
- versioned: target === 'unpkg',
76
- })
77
- url.pathname += '/' + output + '/' + entry
78
- return url.href
79
- } catch (error) { throw new Error(`[hel-env] ${slot}: ${error.message}`) }
80
- }
81
-
82
- function assertSameOrigin(url, base, slot) {
83
- if (new URL(url).origin !== new URL(base).origin) {
84
- throw new Error(`[hel-env] ${slot} must use the deployment origin ${new URL(base).origin}: ${url}`)
85
- }
86
- }
87
-
88
- function loadPackageEnv({ cwd = process.cwd(), mode = 'development', env = process.env, target, localBuild = false } = {}) {
89
- const inherited = { ...env }
90
- // Recompute our own defaults on reload, but preserve values changed by cross-env.
91
- const generated = JSON.parse(inherited.HEL_ENV_GENERATED || '{}')
92
- for (const [key, value] of Object.entries(generated)) {
93
- if (inherited[key] === value) delete inherited[key]
94
- }
95
- delete inherited.HEL_ENV_GENERATED
96
- delete inherited.HEL_ENV_DERIVED_KEYS
97
- delete inherited.HEL_ENV_PACKAGE
98
- const values = Object.assign({}, readPackageFiles(cwd, mode), inherited)
99
- values.HEL_ENV_PACKAGE = path.resolve(cwd)
100
- expand({ parsed: values, processEnv: { ...values } })
101
- values.UNPKG_PUBLIC_URL ||= 'https://unpkg.com'
102
- const derived = new Set()
103
- const put = (key, value) => {
104
- if (!value) return
105
- if (!values[key]) { values[key] = String(value); derived.add(key) }
106
- }
107
- const deployTarget = values.HEL_DEPLOY_TARGET
108
- const runtimeMode = values.NODE_ENV || mode
109
- const selected = resolveTarget(deployTarget || target || values.REMOTE_TARGET, runtimeMode)
110
- localBuild ||= values.HEL_LOCAL_BUILD === '1'
111
- const port = inherited.PORT || inherited.DEV_PORT || inherited.VITE_PORT || values.PORT || values.DEV_PORT
112
- const previewPort = values.PREVIEW_PORT || port
113
- if (port && (!/^\d+$/.test(String(port)) || +port < 1 || +port > 65535)) throw new Error('[hel-env] DEV_PORT must be between 1 and 65535')
114
- if (port) values.DEV_PORT = String(port)
115
- put('PORT', port)
116
- put('VITE_PORT', port)
117
- put('VUE_APP_PORT', port)
118
- put('REACT_APP_PORT', port)
119
- put('VITE_PREVIEW_PORT', previewPort)
120
- put('VUE_APP_PREVIEW_PORT', previewPort)
121
- put('VITE_DEV_ORIGIN', values.DEV_ORIGIN || (port ? `http://localhost:${port}` : ''))
122
- put('VUE_APP_DEV_ORIGIN', values.VITE_DEV_ORIGIN)
123
- for (const key of PUBLIC_ENV_KEYS) {
124
- // Only these public bases are exposed to browser code, never SFTP credentials.
125
- put(`VITE_${key}`, values[key])
126
- put(`VUE_APP_${key}`, values[key])
127
- }
128
- for (const slot of remoteSlots(values)) {
129
- const slotTarget = resolveTarget(deployTarget || target || values[`${slot}_TARGET`] || selected, runtimeMode)
130
- const keys = [`VITE_${slot}_HOST`, `VUE_APP_${slot}_HOST`, `REACT_APP_${slot}_HOST`, `HEL_${slot}_HOST`]
131
- const overrides = [...keys, `VUE_APP_${slot}_ENTRY`, `VITE_${slot}_ENTRY`, `${slot}_URL`]
132
- .map(key => values[key]).filter(Boolean)
133
- if (new Set(overrides).size > 1) throw new Error(`[hel-env] Conflicting ${slot} address overrides`)
134
- const explicit = overrides[0]
135
- const expected = !explicit || deployTarget
136
- ? localBuild && !deployTarget && values[`${slot}_BUNDLED_PATH`]
137
- ? './' + values[`${slot}_BUNDLED_PATH`]
138
- : resolveRemoteUrl(values, slot, slotTarget)
139
- : explicit
140
- const resolved = explicit || expected
141
- if (deployTarget) {
142
- assertSameOrigin(resolved, values[`${deployTarget.toUpperCase()}_PUBLIC_URL`] || expected, slot)
143
- if (resolved !== expected) throw new Error(`[hel-env] ${slot} must match the deployment package/version URL: ${expected}`)
144
- }
145
- for (const key of keys) put(key, resolved)
146
- if (values[`${slot}_ENTRY`] === 'index.html') {
147
- put(`VUE_APP_${slot}_ENTRY`, resolved)
148
- put(`VITE_${slot}_ENTRY`, resolved)
149
- }
150
- put(`VITE_${slot}_LOCAL_URL`, values[`${slot}_LOCAL_URL`])
151
- put(`VUE_APP_${slot}_LOCAL_URL`, values[`${slot}_LOCAL_URL`])
152
- }
153
- if (localBuild && values.VITE_DEV_ORIGIN) put('HEL_APP_HOME_PAGE', values.VITE_DEV_ORIGIN)
154
- if (deployTarget) put('VUE_APP_PUBLISH_MODE', deployTarget)
155
- values.HEL_ENV_PACKAGE = path.resolve(cwd)
156
- const computed = Object.fromEntries(Object.entries(values).filter(([key, value]) => !key.startsWith('HEL_ENV_') && inherited[key] !== value))
157
- values.HEL_ENV_DERIVED_KEYS = Object.keys(computed).join(',')
158
- values.HEL_ENV_GENERATED = JSON.stringify(computed)
159
- return values
160
- }
161
-
162
- function inferMode(env = process.env, argv = process.argv) {
163
- const modeIndex = argv.indexOf('--mode')
164
- const inline = argv.find(arg => arg.startsWith('--mode='))
165
- if (modeIndex >= 0 && argv[modeIndex + 1]) return argv[modeIndex + 1]
166
- if (inline) return inline.slice(7)
167
- if (env.HEL_ENV_MODE) return env.HEL_ENV_MODE
168
- if (env.NODE_ENV) return env.NODE_ENV
169
- return /^(?:build|preview|prepublish)/.test(env.npm_lifecycle_event || '') ? 'production' : 'development'
170
- }
171
-
172
- function applyPackageEnv({ cwd = process.cwd(), mode = inferMode() } = {}) {
173
- const values = loadPackageEnv({ cwd, mode })
174
- const preview = /^(?:preview|serve:dist)/.test(process.env.npm_lifecycle_event || '')
175
- if (preview && !process.env.PORT && values.PREVIEW_PORT) values.PORT = values.PREVIEW_PORT
176
- Object.assign(process.env, values)
177
- return values
178
- }
179
-
180
- module.exports = { applyPackageEnv, inferMode, PUBLIC_ENV_KEYS, readEnvFile, readPackageFiles, remoteSlots, resolveTarget, resolveRemoteUrl, loadPackageEnv }
1
+ const fs = require('node:fs')
2
+ const path = require('node:path')
3
+ const { createRequire } = require('node:module')
4
+ const dotenv = require('dotenv')
5
+ const { expand } = require('dotenv-expand')
6
+ const { packageRef, packageUrl } = require('./remote-address.cjs')
7
+
8
+ const PUBLIC_ENV_KEYS = ['SFTP_PUBLIC_URL', 'GITHUB_PUBLIC_URL', 'UNPKG_PUBLIC_URL']
9
+ const WORKSPACE_ENV_KEYS = [...PUBLIC_ENV_KEYS, 'HEL_RELATIVE_PATH']
10
+ const TARGETS = ['local', 'sftp', 'github', 'unpkg']
11
+ const trim = value => String(value || '').trim().replace(/\/+$/, '')
12
+
13
+ function readEnvFile(file) {
14
+ return fs.existsSync(file) ? dotenv.parse(fs.readFileSync(file)) : {}
15
+ }
16
+
17
+ function readPackageFiles(cwd, mode) {
18
+ // The root orchestrator copies only public bases here. Never read a parent directory.
19
+ return Object.assign({}, ...[
20
+ '.env.defaults', '.env.workspace.local', '.env', '.env.local', `.env.${mode}`, `.env.${mode}.local`,
21
+ ].map(name => readEnvFile(path.join(cwd, name))))
22
+ }
23
+
24
+ function remoteSlots(env) {
25
+ return Object.keys(env).filter(key => /^[A-Z][A-Z\d_]*_PACKAGE$/.test(key) && !/^(?:DEPLOY_|VITE_|VUE_APP_|REACT_APP_|HEL_)/.test(key))
26
+ .map(key => key.slice(0, -8))
27
+ }
28
+
29
+ function resolveTarget(value, mode) {
30
+ const target = String(value || 'auto').toLowerCase()
31
+ if (target === 'auto') return ['development', 'mock'].includes(mode) ? 'local' : 'unpkg'
32
+ if (!TARGETS.includes(target)) throw new Error(`[hel-env] Unknown remote target: ${target}`)
33
+ return target
34
+ }
35
+
36
+ // Resolve metadata from an installed dependency, never from a sibling/source checkout.
37
+ function installedVersion(cwd, packageName) {
38
+ const fromPackage = createRequire(path.join(cwd, 'package.json'))
39
+ try {
40
+ return JSON.parse(fs.readFileSync(fromPackage.resolve(packageName + '/package.json'), 'utf8')).version
41
+ } catch (error) {
42
+ if (!['ERR_PACKAGE_PATH_NOT_EXPORTED', 'MODULE_NOT_FOUND'].includes(error.code)) throw error
43
+ }
44
+ let directory = path.dirname(fromPackage.resolve(packageName))
45
+ for (;;) {
46
+ const manifest = path.join(directory, 'package.json')
47
+ if (fs.existsSync(manifest)) {
48
+ const pkg = JSON.parse(fs.readFileSync(manifest, 'utf8'))
49
+ if (pkg.name === packageName) return pkg.version
50
+ }
51
+ const parent = path.dirname(directory)
52
+ if (parent === directory) throw new Error(`[hel-env] Cannot resolve installed version of ${packageName}; set the dependency's VERSION explicitly`)
53
+ directory = parent
54
+ }
55
+ }
56
+
57
+ function resolveRemoteUrl(env, slot, target) {
58
+ const packageName = env[`${slot}_PACKAGE`]
59
+ if (target === 'local') {
60
+ const url = trim(env[`${slot}_LOCAL_URL`])
61
+ if (!url) throw new Error(`[hel-env] ${slot}_LOCAL_URL is required for local development`)
62
+ return url
63
+ }
64
+ const base = trim(env[`${target.toUpperCase()}_PUBLIC_URL`])
65
+ let version = env[`DEPLOY_${slot}_VERSION`] || env[`${slot}_VERSION`] || 'latest'
66
+ if (target === 'unpkg' && version === 'installed') version = installedVersion(env.HEL_ENV_PACKAGE || process.cwd(), packageName)
67
+ const output = env[`${slot}_OUTPUT_DIR`] || 'hel_dist'
68
+ const entry = env[`${slot}_ENTRY`] || 'hel-meta.json'
69
+ try {
70
+ const parsed = packageRef(packageName)
71
+ parsed.version = version
72
+ const url = packageUrl(parsed, {
73
+ type: target === 'sftp' ? 'custom' : target, base,
74
+ projectName: target === 'unpkg' ? undefined : env[`${slot}_PROJECT`],
75
+ // Static deployments update project directories; unpkg versions are npm versions.
76
+ versioned: target === 'unpkg',
77
+ })
78
+ url.pathname += '/' + output + '/' + entry
79
+ return url.href
80
+ } catch (error) { throw new Error(`[hel-env] ${slot}: ${error.message}`) }
81
+ }
82
+
83
+ function assertSameOrigin(url, base, slot) {
84
+ if (new URL(url).origin !== new URL(base).origin) {
85
+ throw new Error(`[hel-env] ${slot} must use the deployment origin ${new URL(base).origin}: ${url}`)
86
+ }
87
+ }
88
+
89
+ // Keep the deployment directory while allowing the same static files on another origin.
90
+ function resolveBuildHomePage(env, homePage = env.HEL_APP_HOME_PAGE) {
91
+ if (env.HEL_RELATIVE_PATH !== '1') return homePage
92
+ if (/^(?:https?:)?\/\//i.test(homePage || '')) return new URL(homePage, 'https://hel.invalid').pathname
93
+ return homePage || '/'
94
+ }
95
+
96
+ function loadPackageEnv({ cwd = process.cwd(), mode = 'development', env = process.env, target, localBuild = false } = {}) {
97
+ const inherited = { ...env }
98
+ // Recompute our own defaults on reload, but preserve values changed by cross-env.
99
+ const generated = JSON.parse(inherited.HEL_ENV_GENERATED || '{}')
100
+ for (const [key, value] of Object.entries(generated)) {
101
+ if (inherited[key] === value) delete inherited[key]
102
+ }
103
+ delete inherited.HEL_ENV_GENERATED
104
+ delete inherited.HEL_ENV_DERIVED_KEYS
105
+ delete inherited.HEL_ENV_PACKAGE
106
+ const values = Object.assign({}, readPackageFiles(cwd, mode), inherited)
107
+ values.HEL_ENV_PACKAGE = path.resolve(cwd)
108
+ expand({ parsed: values, processEnv: { ...values } })
109
+ values.UNPKG_PUBLIC_URL ||= 'https://unpkg.com'
110
+ const derived = new Set()
111
+ const put = (key, value) => {
112
+ if (!value) return
113
+ if (!values[key]) { values[key] = String(value); derived.add(key) }
114
+ }
115
+ const deployTarget = values.HEL_DEPLOY_TARGET
116
+ const runtimeMode = values.NODE_ENV || mode
117
+ const selected = resolveTarget(deployTarget || target || values.REMOTE_TARGET, runtimeMode)
118
+ localBuild ||= values.HEL_LOCAL_BUILD === '1'
119
+ const port = inherited.PORT || inherited.DEV_PORT || inherited.VITE_PORT || values.PORT || values.DEV_PORT
120
+ const previewPort = values.PREVIEW_PORT || port
121
+ if (port && (!/^\d+$/.test(String(port)) || +port < 1 || +port > 65535)) throw new Error('[hel-env] DEV_PORT must be between 1 and 65535')
122
+ if (port) values.DEV_PORT = String(port)
123
+ put('PORT', port)
124
+ put('VITE_PORT', port)
125
+ put('VUE_APP_PORT', port)
126
+ put('REACT_APP_PORT', port)
127
+ put('VITE_PREVIEW_PORT', previewPort)
128
+ put('VUE_APP_PREVIEW_PORT', previewPort)
129
+ put('VITE_DEV_ORIGIN', values.DEV_ORIGIN || (port ? `http://localhost:${port}` : ''))
130
+ put('VUE_APP_DEV_ORIGIN', values.VITE_DEV_ORIGIN)
131
+ for (const key of PUBLIC_ENV_KEYS) {
132
+ // Only these public bases are exposed to browser code, never SFTP credentials.
133
+ put(`VITE_${key}`, values[key])
134
+ put(`VUE_APP_${key}`, values[key])
135
+ }
136
+ for (const slot of remoteSlots(values)) {
137
+ const slotTarget = resolveTarget(deployTarget || target || values[`${slot}_TARGET`] || selected, runtimeMode)
138
+ const keys = [`VITE_${slot}_HOST`, `VUE_APP_${slot}_HOST`, `REACT_APP_${slot}_HOST`, `HEL_${slot}_HOST`]
139
+ const overrides = [...keys, `VUE_APP_${slot}_ENTRY`, `VITE_${slot}_ENTRY`, `${slot}_URL`]
140
+ .map(key => values[key]).filter(Boolean)
141
+ if (new Set(overrides).size > 1) throw new Error(`[hel-env] Conflicting ${slot} address overrides`)
142
+ const explicit = overrides[0]
143
+ const expected = !explicit || deployTarget
144
+ ? localBuild && !deployTarget && values[`${slot}_BUNDLED_PATH`]
145
+ ? './' + values[`${slot}_BUNDLED_PATH`]
146
+ : resolveRemoteUrl(values, slot, slotTarget)
147
+ : explicit
148
+ const resolved = explicit || expected
149
+ if (deployTarget) {
150
+ assertSameOrigin(resolved, values[`${deployTarget.toUpperCase()}_PUBLIC_URL`] || expected, slot)
151
+ if (resolved !== expected) throw new Error(`[hel-env] ${slot} must match the deployment package/version URL: ${expected}`)
152
+ }
153
+ for (const key of keys) put(key, resolved)
154
+ if (values[`${slot}_ENTRY`] === 'index.html') {
155
+ put(`VUE_APP_${slot}_ENTRY`, resolved)
156
+ put(`VITE_${slot}_ENTRY`, resolved)
157
+ }
158
+ put(`VITE_${slot}_LOCAL_URL`, values[`${slot}_LOCAL_URL`])
159
+ put(`VUE_APP_${slot}_LOCAL_URL`, values[`${slot}_LOCAL_URL`])
160
+ }
161
+ if (localBuild && values.VITE_DEV_ORIGIN) put('HEL_APP_HOME_PAGE', values.VITE_DEV_ORIGIN)
162
+ if (runtimeMode === 'production' && !localBuild) {
163
+ const homePage = resolveBuildHomePage(values)
164
+ if (homePage) values.HEL_APP_HOME_PAGE = homePage
165
+ }
166
+ if (deployTarget) put('VUE_APP_PUBLISH_MODE', deployTarget)
167
+ values.HEL_ENV_PACKAGE = path.resolve(cwd)
168
+ const computed = Object.fromEntries(Object.entries(values).filter(([key, value]) =>
169
+ !key.startsWith('HEL_ENV_') && inherited[key] !== value && !(key === 'HEL_APP_HOME_PAGE' && inherited[key])))
170
+ values.HEL_ENV_DERIVED_KEYS = Object.keys(computed).join(',')
171
+ values.HEL_ENV_GENERATED = JSON.stringify(computed)
172
+ return values
173
+ }
174
+
175
+ function inferMode(env = process.env, argv = process.argv) {
176
+ const modeIndex = argv.indexOf('--mode')
177
+ const inline = argv.find(arg => arg.startsWith('--mode='))
178
+ if (modeIndex >= 0 && argv[modeIndex + 1]) return argv[modeIndex + 1]
179
+ if (inline) return inline.slice(7)
180
+ if (env.HEL_ENV_MODE) return env.HEL_ENV_MODE
181
+ if (env.NODE_ENV) return env.NODE_ENV
182
+ return /^(?:build|preview|prepublish)/.test(env.npm_lifecycle_event || '') ? 'production' : 'development'
183
+ }
184
+
185
+ function applyPackageEnv({ cwd = process.cwd(), mode = inferMode() } = {}) {
186
+ const values = loadPackageEnv({ cwd, mode })
187
+ const preview = /^(?:preview|serve:dist)/.test(process.env.npm_lifecycle_event || '')
188
+ if (preview && !process.env.PORT && values.PREVIEW_PORT) values.PORT = values.PREVIEW_PORT
189
+ Object.assign(process.env, values)
190
+ return values
191
+ }
192
+
193
+ module.exports = { applyPackageEnv, inferMode, PUBLIC_ENV_KEYS, WORKSPACE_ENV_KEYS, readEnvFile, readPackageFiles, remoteSlots, resolveTarget, resolveRemoteUrl, resolveBuildHomePage, loadPackageEnv }
@@ -15,18 +15,14 @@ import path from 'node:path'
15
15
  // 这里显式跑一次,避免绕过 comps-* / libs-* 的发布前检查。
16
16
 
17
17
  const pkg = JSON.parse(fs.readFileSync('package.json', 'utf8'))
18
+ const args = process.argv.slice(2)
19
+ if (args.some(arg => arg !== '--dry-run')) throw new Error('用法:hel-publish-stage [--dry-run]')
20
+ const dryRun = args.includes('--dry-run')
18
21
  if (pkg.private) {
19
22
  throw new Error('[publish:stage] 当前 package.json 是 private,请在要发布的包目录里执行')
20
23
  }
21
24
  const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'hel-stage-'))
22
25
  const run = (command) => execSync(command, { stdio: 'inherit' })
23
- let npmStage = 'npm'
24
- try {
25
- execSync('npm stage --help', { stdio: 'ignore' })
26
- } catch {
27
- npmStage = 'pnpm --registry=https://registry.npmjs.org --package=npm@11 dlx npm'
28
- }
29
-
30
26
  try {
31
27
  if (pkg.scripts && pkg.scripts.prepublishOnly) {
32
28
  run('pnpm run prepublishOnly')
@@ -35,11 +31,23 @@ try {
35
31
  run(`pnpm pack --pack-destination "${tmp}"`)
36
32
  const tgz = fs.readdirSync(tmp).find((file) => file.endsWith('.tgz'))
37
33
  if (!tgz) throw new Error('pnpm pack 没有产出 tarball')
34
+
35
+ if (dryRun) {
36
+ console.log(`[publish:stage] dry-run: ${pkg.name}@${pkg.version} packed; 未上传或修改版本。保留产物:${path.join(tmp, tgz)}`)
37
+ process.exitCode = 0
38
+ } else {
39
+ let npmStage = 'npm'
40
+ try {
41
+ execSync('npm stage --help', { stdio: 'ignore' })
42
+ } catch {
43
+ npmStage = 'pnpm --registry=https://registry.npmjs.org --package=npm@11 dlx npm'
44
+ }
38
45
 
39
- run(
46
+ run(
40
47
  `${npmStage} stage publish "${path.join(tmp, tgz)}" --registry=https://registry.npmjs.org --access public`,
41
48
  )
42
- console.log(`[publish:stage] ${pkg.name}@${pkg.version} staged`)
49
+ console.log(`[publish:stage] ${pkg.name}@${pkg.version} staged`)
50
+ }
43
51
  } finally {
44
- fs.rmSync(tmp, { recursive: true, force: true })
52
+ if (!dryRun) fs.rmSync(tmp, { recursive: true, force: true })
45
53
  }