@melt-js/libs-core 2026.11.15 → 2026.11.16-2

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.
Files changed (85) hide show
  1. package/README.md +73 -16
  2. package/dist/browser.d.mts +3 -0
  3. package/dist/browser.mjs +1 -50
  4. package/dist/browser.mjs.gz +0 -0
  5. package/dist/cdn/browser.umd.cjs +2 -0
  6. package/dist/cdn/browser.umd.cjs.gz +0 -0
  7. package/dist/cdn/demo-browser.umd.cjs +2 -0
  8. package/dist/cdn/demo-browser.umd.cjs.gz +0 -0
  9. package/dist/cdn/demo.umd.cjs +2 -0
  10. package/dist/cdn/demo.umd.cjs.gz +0 -0
  11. package/dist/cdn/example-esm.html +1 -0
  12. package/dist/cdn/example-umd.html +1 -0
  13. package/dist/cdn/index.umd.cjs +2 -0
  14. package/dist/cdn/index.umd.cjs.gz +0 -0
  15. package/dist/cdn/manifest.json +141 -0
  16. package/dist/cdn/vendor.umd.cjs +16 -0
  17. package/dist/cdn/vendor.umd.cjs.gz +0 -0
  18. package/dist/cdn.d.mts +3 -0
  19. package/dist/cdn.mjs +1 -0
  20. package/dist/demo/browser.d.mts +1 -0
  21. package/dist/demo/browser.mjs +1 -0
  22. package/dist/demo/browser.mjs.gz +0 -0
  23. package/dist/demo/clipboard.d.mts +6 -0
  24. package/dist/demo/clipboard.mjs +1 -0
  25. package/{src → dist}/demo/docs.d.mts +3 -0
  26. package/dist/demo/docs.mjs +1 -0
  27. package/dist/demo/docs.mjs.gz +0 -0
  28. package/{src → dist}/demo/download.d.mts +10 -2
  29. package/dist/demo/download.mjs +1 -0
  30. package/dist/demo/download.mjs.gz +0 -0
  31. package/dist/demo/fullscreen.mjs +1 -0
  32. package/dist/demo/highlight.d.mts +2 -0
  33. package/dist/demo/highlight.mjs +1 -0
  34. package/dist/demo/index.d.mts +10 -0
  35. package/dist/demo/index.mjs +1 -0
  36. package/dist/demo/model.mjs +1 -0
  37. package/dist/demo/remote-debug.d.mts +9 -0
  38. package/dist/demo/remote-debug.mjs +1 -0
  39. package/{src → dist}/demo/runtime.mjs +92 -104
  40. package/dist/demo/split-pane.d.mts +8 -0
  41. package/dist/demo/split-pane.mjs +1 -0
  42. package/dist/demo/standalone.d.mts +12 -0
  43. package/dist/demo/standalone.mjs +1 -0
  44. package/dist/demo/standalone.mjs.gz +0 -0
  45. package/dist/demo/tabs.d.mts +15 -0
  46. package/dist/demo/tabs.mjs +1 -0
  47. package/{src/index.ts → dist/index.d.ts} +1 -1
  48. package/dist/loading.mjs +1 -0
  49. package/dist/loading.mjs.gz +0 -0
  50. package/dist/remote-address.cjs +2 -0
  51. package/{src → dist}/remote.d.mts +20 -2
  52. package/dist/remote.mjs +1 -0
  53. package/dist/remote.mjs.gz +0 -0
  54. package/dist/vendor/hel-runtime.mjs +16 -0
  55. package/dist/vendor/hel-runtime.mjs.gz +0 -0
  56. package/package.json +41 -25
  57. package/scripts/browser-formats.mjs +357 -0
  58. package/scripts/build-browser.mjs +59 -13
  59. package/scripts/build-protected-esm.mjs +54 -0
  60. package/scripts/cdn-runtime.cjs +30 -0
  61. package/scripts/check-tdz.mjs +327 -324
  62. package/scripts/client-build-security.cjs +48 -0
  63. package/scripts/comps-bundle-obfuscation.cjs +269 -262
  64. package/scripts/comps-obfuscator-options.cjs +7 -1
  65. package/scripts/hel-build-paths.cjs +49 -48
  66. package/scripts/obfuscator-split-strings.cjs +22 -0
  67. package/scripts/package-artifacts.mjs +206 -0
  68. package/scripts/package-env.cjs +156 -193
  69. package/scripts/publish-stage.mjs +50 -42
  70. package/scripts/webpack-bundle-obfuscation.cjs +125 -121
  71. package/demo/index.js +0 -1
  72. package/dist/hel-deployment.json +0 -8
  73. package/src/browser.d.mts +0 -2
  74. package/src/browser.mjs +0 -3
  75. package/src/demo/docs.mjs +0 -75
  76. package/src/demo/download.mjs +0 -118
  77. package/src/demo/fullscreen.mjs +0 -80
  78. package/src/demo/index.d.mts +0 -4
  79. package/src/demo/index.mjs +0 -4
  80. package/src/demo/model.mjs +0 -203
  81. package/src/remote.mjs +0 -286
  82. package/tsconfig.json +0 -13
  83. /package/{src → dist}/demo/fullscreen.d.mts +0 -0
  84. /package/{src → dist}/demo/model.d.mts +0 -0
  85. /package/{src → scripts}/remote-address.cjs +0 -0
@@ -0,0 +1,48 @@
1
+ // Deployment configuration is a Node build input, never a browser environment API.
2
+ const deploymentKey = /^(?:(?:VITE|VUE_APP|REACT_APP)_)?(?:(?:SFTP|GITHUB|UNPKG)_PUBLIC_URL|SFTP_[A-Z\d_]+|DEPLOY_[A-Z\d_]+)$/
3
+
4
+ function stripDeploymentEnv(values) {
5
+ for (const key of Object.keys(values || {})) {
6
+ if (deploymentKey.test(key)) delete values[key]
7
+ }
8
+ }
9
+
10
+ function applyWebpackClientSecurity(config) {
11
+ if (process.env.NODE_ENV !== 'production' && config.mode !== 'production') return config
12
+ config.devtool = false
13
+ for (const plugin of config.plugins || []) {
14
+ if (plugin?.constructor?.name !== 'DefinePlugin') continue
15
+ const definitions = plugin.definitions || {}
16
+ stripDeploymentEnv(definitions['process.env'])
17
+ for (const key of Object.keys(definitions)) {
18
+ if (deploymentKey.test(key.replace(/^process\.env\./, ''))) delete definitions[key]
19
+ }
20
+ }
21
+ return config
22
+ }
23
+
24
+ function clientBuildSecurity({ loadEnv }) {
25
+ return {
26
+ // Vite 6 snapshots env while constructing its define plugin, before configResolved.
27
+ // Select client keys before that snapshot rather than filtering only afterwards.
28
+ name: 'hel:client-build-security', apply: 'build', enforce: 'pre',
29
+ config(config, { mode }) {
30
+ const path = require('node:path')
31
+ const root = path.resolve(config.root || process.cwd())
32
+ const envDir = path.resolve(root, config.envDir || '.')
33
+ const prefixes = [config.envPrefix || 'VITE_'].flat()
34
+ const values = loadEnv(mode, envDir, prefixes)
35
+ stripDeploymentEnv(values)
36
+ return { envPrefix: Object.keys(values), build: { sourcemap: false } }
37
+ },
38
+ configResolved(config) {
39
+ config.build.sourcemap = false
40
+ stripDeploymentEnv(config.env)
41
+ for (const key of Object.keys(config.define || {})) {
42
+ if (deploymentKey.test(key.replace(/^import\.meta\.env\./, ''))) delete config.define[key]
43
+ }
44
+ },
45
+ }
46
+ }
47
+
48
+ module.exports = { stripDeploymentEnv, applyWebpackClientSecurity, clientBuildSecurity }
@@ -1,262 +1,269 @@
1
- const { createHash } = require('node:crypto')
2
- const fs = require('node:fs')
3
- const path = require('node:path')
4
- const defaults = require('./comps-obfuscator-options.cjs')
5
-
6
- const normalize = value => value.replaceAll('\\', '/')
7
- const RUNTIME_ID = '\0hel:shared-vue-runtime'
8
- let buildSequence = 0
9
- const excludedChunks = /(?:^|\/)(?:vendor|shared-runtime|rolldown-runtime|__vite-browser-external)(?:[-.]|\/)/
10
-
11
- /** Follow installed packages / workspace symlinks, never infer ownership from a .pnpm parent name. */
12
- function createModuleClassifier(root) {
13
- const realRoot = normalize(fs.realpathSync(root)).replace(/\/$/, '')
14
- const rootName = JSON.parse(fs.readFileSync(path.join(realRoot, 'package.json'), 'utf8')).name || ''
15
- const scope = /^(@[^/]+)\//.exec(rootName)?.[1]
16
- const owners = new Map()
17
- const ownerOf = directory => {
18
- if (owners.has(directory)) return owners.get(directory)
19
- const manifest = path.join(directory, 'package.json')
20
- let owner
21
- if (fs.existsSync(manifest)) {
22
- owner = { root: normalize(directory), name: JSON.parse(fs.readFileSync(manifest, 'utf8')).name || '' }
23
- } else {
24
- const parent = path.dirname(directory)
25
- // A nested node_modules must never inherit its containing package's ownership.
26
- owner = parent === directory || path.basename(directory) === 'node_modules' ? null : ownerOf(parent)
27
- }
28
- owners.set(directory, owner)
29
- return owner
30
- }
31
- return id => {
32
- if (id === RUNTIME_ID || id.startsWith('\0hel:shared-runtime:') || /(?:^|\0)plugin-vue:export-helper$/.test(id)) return 'runtime'
33
- const filename = normalize(id.replace(/^\0/, '')).split('?', 1)[0]
34
- if (!path.isAbsolute(filename) || !fs.existsSync(filename)) return 'generated'
35
- const realFile = normalize(fs.realpathSync(filename))
36
- // Embedded upstream source manifests are metadata, not installed dependencies.
37
- if (realFile.startsWith(realRoot + '/') && !realFile.slice(realRoot.length + 1).split('/').includes('node_modules')) return 'own'
38
- const owner = ownerOf(path.dirname(realFile))
39
- if (owner?.root === realRoot) return 'own'
40
- if (scope && owner?.name.startsWith(scope + '/')) return 'related'
41
- return 'thirdParty'
42
- }
43
- }
44
-
45
- /** ESM imports remain hoisted; no in-place import-to-const rewriting and no second Vue runtime. */
46
- function sharedVueRuntimePlugin(exportNames) {
47
- if (!exportNames.length || exportNames.some(name => !/^[$A-Z_a-z][$\w]*$/.test(name))) {
48
- throw new TypeError('Pass the named exports of the consuming package\'s installed vue runtime')
49
- }
50
- return {
51
- name: 'hel:shared-vue-runtime',
52
- enforce: 'pre',
53
- apply: 'build',
54
- resolveId(id) { if (id === 'vue' || id === 'vue-demi') return RUNTIME_ID },
55
- load(id) {
56
- if (id !== RUNTIME_ID) return null
57
- return `const runtime = globalThis.Vue;
58
- if (!runtime) throw new Error('Bind the host Vue runtime before loading remote components');
59
- ${exportNames.map(name => `export const ${name} = runtime[${JSON.stringify(name)}];`).join('\n')}
60
- export default runtime;`
61
- },
62
- }
63
- }
64
-
65
- /**
66
- * Explicit ESM bridges for host-owned runtimes. Each import declares real named
67
- * exports, so both Rollup and Rolldown work without syntheticNamedExports.
68
- * Namespace imports use the host object itself; ESM imports remain hoisted.
69
- * This plugin never changes the consuming package's build/externals/output config.
70
- */
71
- function sharedRuntimePlugin(globals) {
72
- const prefix = '\0hel:shared-runtime:'
73
- const bridges = new Map()
74
- const bridgeId = (source, names = []) => {
75
- const id = prefix + JSON.stringify([source, [...new Set(names)].sort()])
76
- bridges.set(id, { source, names: [...new Set(names)].sort() })
77
- return id
78
- }
79
- return {
80
- name: 'hel:shared-runtime', apply: 'build', enforce: 'post',
81
- buildStart() { bridges.clear() },
82
- resolveId(id) {
83
- if (bridges.has(id)) return id
84
- if (Object.hasOwn(globals, id)) return bridgeId(id)
85
- },
86
- transform(code, id) {
87
- if (id.startsWith(prefix) || !Object.keys(globals).some(source => code.includes(source))) return null
88
- let ast
89
- try { ast = this.parse(code) } catch { return null } // Non-JavaScript assets.
90
- const edits = []
91
- for (const node of ast.body) {
92
- if (!node.source || !Object.hasOwn(globals, node.source.value)) continue
93
- if (node.type === 'ExportAllDeclaration' && node.exported) {
94
- edits.push([node.start, node.end, 'export { default as ' + node.exported.name + ' } from ' + JSON.stringify(bridgeId(node.source.value)) + ';'])
95
- continue
96
- }
97
- if (node.type === 'ExportAllDeclaration') {
98
- this.error('Use explicit named re-exports for shared runtime ' + node.source.value + ' in ' + id)
99
- }
100
- if (!['ImportDeclaration', 'ExportNamedDeclaration'].includes(node.type)) continue
101
- const names = []
102
- for (const specifier of node.specifiers) {
103
- if (specifier.type === 'ImportSpecifier') names.push(specifier.imported.name ?? specifier.imported.value)
104
- if (specifier.type === 'ExportSpecifier') names.push(specifier.local.name ?? specifier.local.value)
105
- if (specifier.type === 'ImportNamespaceSpecifier') {
106
- edits.push([specifier.start, specifier.end, '{ default as ' + specifier.local.name + ' }'])
107
- }
108
- }
109
- edits.push([node.source.start, node.source.end, JSON.stringify(bridgeId(node.source.value, names))])
110
- }
111
- const visit = node => {
112
- if (!node || typeof node !== 'object') return
113
- if (node.type === 'ImportExpression' && Object.hasOwn(globals, node.source?.value)) {
114
- edits.push([node.start, node.end, 'import(' + JSON.stringify(bridgeId(node.source.value)) + ').then(module => module.default)'])
115
- return
116
- }
117
- for (const value of Object.values(node)) {
118
- if (Array.isArray(value)) value.forEach(visit)
119
- else if (value && typeof value === 'object') visit(value)
120
- }
121
- }
122
- visit(ast)
123
- if (!edits.length) return null
124
- for (const [start, end, replacement] of edits.sort((a, b) => b[0] - a[0])) {
125
- code = code.slice(0, start) + replacement + code.slice(end)
126
- }
127
- return { code, map: null }
128
- },
129
- load(id) {
130
- const bridge = bridges.get(id)
131
- if (!bridge) return null
132
- const name = globals[bridge.source]
133
- const access = name.split('.').filter(part => !['window', 'globalThis', 'global'].includes(part))
134
- .map(part => '[' + JSON.stringify(part) + ']').join('')
135
- return 'const runtime = globalThis' + access + ';\n'
136
- + 'if (runtime == null) throw new Error(' + JSON.stringify('Bind shared runtime before loading remote package: ' + name) + ');\n'
137
- + 'export default runtime;\n'
138
- + bridge.names.filter(name => name !== 'default').map((name, index) =>
139
- 'const binding' + index + ' = runtime[' + JSON.stringify(name) + ']; export { binding' + index + ' as ' + (/^[$A-Z_a-z][$\w]*$/.test(name) ? name : JSON.stringify(name)) + ' };').join('\n')
140
- },
141
- }
142
- }
143
-
144
- function gzipPlugin() {
145
- return { name: 'hel:final-gzip', apply: 'build', enforce: 'post', generateBundle: { order: 'post', handler(_output, bundle) {
146
- if (process.env.HEL_GZIP === '0') return
147
- const { gzipSync } = require('node:zlib')
148
- for (const item of Object.values(bundle)) {
149
- if (!/\.(?:[cm]?js|css)$/i.test(item.fileName)) continue
150
- const source = item.type === 'chunk' ? item.code : item.source
151
- if (Buffer.byteLength(source) < 10240) continue
152
- this.emitFile({ type: 'asset', fileName: item.fileName + '.gz', source: gzipSync(source) })
153
- }
154
- } } }
155
- }
156
-
157
- /**
158
- * Vite split ESM apps and ES/CJS library outputs.
159
- * Invoke the official app hook after Vite's final dependency/preload rewrites, on minified chunks.
160
- * Its automatic node_modules exclusion is OFF: dependencies in the consumer's scope are protected.
161
- */
162
- function bundleObfuscationPlugins({ root, obfuscatorPlugin, enabled = true, options = {}, library = false, rolldown = false }) {
163
- const classify = createModuleClassifier(root)
164
- const settings = { ...defaults, ...options, seed: options.seed ?? 1, renameProperties: false, sourceMap: false }
165
- const reports = []
166
- let currentReports = []
167
- let runId
168
- const api = { classify, reports }
169
- const guard = {
170
- name: 'hel:bundle-obfuscation-boundaries',
171
- apply: 'build',
172
- api,
173
- buildStart() { reports.length = 0; runId = ++buildSequence },
174
- config() {
175
- return { build: { rollupOptions: { output: {
176
- ...(library ? {} : { format: 'es' }),
177
- ...(rolldown ? {
178
- strictExecutionOrder: true,
179
- codeSplitting: { minSize: 0, includeDependenciesRecursively: false, groups: [
180
- { name: 'shared-runtime', test: id => classify(id) === 'runtime', priority: 100 },
181
- { name: 'vendor', test: id => classify(id) === 'thirdParty' || id.includes('commonjs'), priority: 90 },
182
- { name: 'standalone', test: id => classify(id) === 'own' && normalize(id).includes('/src/standalone/'), priority: 80 },
183
- { name: 'components', test: id => ['own', 'related'].includes(classify(id)), priority: 70 },
184
- ] },
185
- } : {
186
- onlyExplicitManualChunks: true,
187
- manualChunks(id) {
188
- const kind = classify(id)
189
- if (kind === 'runtime') return 'shared-runtime'
190
- if (kind === 'own' && normalize(id).includes('/src/standalone/')) return 'standalone'
191
- if (kind === 'own' || kind === 'related') return 'components'
192
- if (kind === 'thirdParty' || id.includes('commonjs')) return 'vendor'
193
- },
194
- }),
195
- } } } }
196
- },
197
- // The official app plugin runs after Rollup hashes chunks. Include its settings in cache keys.
198
- augmentChunkHash(chunk) {
199
- if (excludedChunks.test(chunk.name + '.js')) return
200
- return createHash('sha256').update(JSON.stringify({ pipeline: 'final-generate-bundle-v2', enabled, settings })).digest('hex')
201
- },
202
- generateBundle(_output, bundle) {
203
- currentReports = []
204
- for (const chunk of Object.values(bundle)) {
205
- if (chunk.type !== 'chunk') continue
206
- const modules = Object.keys(chunk.modules).map(id => ({ id: normalize(id), kind: classify(id) }))
207
- const protectedModules = modules.filter(item => ['own', 'related'].includes(item.kind))
208
- const vendors = modules.filter(item => item.kind === 'thirdParty')
209
- if (protectedModules.length && vendors.length) {
210
- this.error(`Mixed business/vendor chunk cannot be safely obfuscated: ${chunk.fileName}`)
211
- }
212
- const excluded = excludedChunks.test(chunk.fileName)
213
- if (vendors.length && !excluded) this.error(`Third-party chunk is not excluded: ${chunk.fileName}`)
214
- if (protectedModules.length && excluded) this.error(`Protected source leaked into excluded chunk: ${chunk.fileName}`)
215
- const report = { format: _output.format, fileName: chunk.fileName, modules, protectedModules: protectedModules.length,
216
- thirdPartyModules: vendors.length, excluded, beforeHash: createHash('sha256').update(chunk.code).digest('hex') }
217
- reports.push(report)
218
- currentReports.push(report)
219
- }
220
- },
221
- }
222
- const plugin = obfuscatorPlugin({ apply: 'build', enable: enabled, log: true, threadPool: false,
223
- autoExcludeNodeModules: false, excludes: [excludedChunks], options: settings })
224
- const hook = plugin.transformIndexHtml
225
- if (typeof hook?.handler !== 'function' || hook.order !== 'post') {
226
- throw new Error('Expected vite-plugin-bundle-obfuscator post transformIndexHtml hook')
227
- }
228
- // HTML hooks run inside vite:build-html, before Vite finalizes dynamic preload maps.
229
- // Keep the official implementation, but invoke its app hook once at the final output stage.
230
- // Otherwise late Vite rewrites change bytes after our audit and escape obfuscation.
231
- plugin.enforce = 'post'
232
- // The library renderChunk hook otherwise obfuscates before minification.
233
- plugin.renderChunk = undefined
234
- const generateBundle = plugin.generateBundle
235
- plugin.transformIndexHtml = { ...hook, handler: html => html }
236
- plugin.generateBundle = { order: 'post', async handler(output, bundle) {
237
- if (typeof generateBundle === 'function') await generateBundle.call(this, output, bundle)
238
- else if (generateBundle?.handler) await generateBundle.handler.call(this, output, bundle)
239
- const html = Object.values(bundle).find(item => item.type === 'asset' && item.fileName.endsWith('.html'))
240
- for (const report of currentReports) {
241
- report.beforeHash = createHash('sha256').update(bundle[report.fileName].code).digest('hex')
242
- }
243
- // The upstream plugin keeps a process-wide filename registry. Unique lookup keys
244
- // prevent silently skipping a subsequent/watch build without altering output URLs.
245
- const finalBundle = Object.fromEntries(Object.entries(bundle).map(([name, chunk]) => [`__hel_${runId}_${output.format}__/${name}`, chunk]))
246
- await hook.handler.call(this, html ? String(html.source) : '', { bundle: finalBundle })
247
- for (const report of currentReports) {
248
- const code = bundle[report.fileName].code
249
- report.afterHash = createHash('sha256').update(code).digest('hex')
250
- report.identifiers = (code.match(/\b_0x[\da-f]+\b/g) || []).length
251
- report.obfuscated = report.beforeHash !== report.afterHash
252
- if (report.excluded && report.obfuscated) throw new Error(`Excluded chunk changed: ${report.fileName}`)
253
- if (enabled && report.protectedModules && (!report.obfuscated || !report.identifiers)) {
254
- throw new Error(`Final business chunk is not obfuscated: ${report.fileName}`)
255
- }
256
- console.log(`[hel:bundle] ${report.fileName}: ${report.obfuscated ? 'obfuscated' : 'unchanged'}, _0x identifiers=${report.identifiers}, own/related=${report.protectedModules}, third-party=${report.thirdPartyModules}`)
257
- }
258
- } }
259
- return [guard, plugin]
260
- }
261
-
262
- module.exports = { bundleObfuscationPlugins, createModuleClassifier, sharedVueRuntimePlugin, sharedRuntimePlugin, gzipPlugin }
1
+ const { createHash } = require('node:crypto')
2
+ const fs = require('node:fs')
3
+ const path = require('node:path')
4
+ const defaults = require('./comps-obfuscator-options.cjs')
5
+ const { splitStringsChunkLength } = require('./obfuscator-split-strings.cjs')
6
+
7
+ const normalize = value => value.replaceAll('\\', '/')
8
+ const RUNTIME_ID = '\0hel:shared-vue-runtime'
9
+ let buildSequence = 0
10
+ const excludedChunks = /(?:^|\/)(?:vendor|shared-runtime|rolldown-runtime|__vite-browser-external)(?:[-.]|\/)/
11
+
12
+ /** Follow installed packages / workspace symlinks, never infer ownership from a .pnpm parent name. */
13
+ function createModuleClassifier(root) {
14
+ const realRoot = normalize(fs.realpathSync(root)).replace(/\/$/, '')
15
+ const rootName = JSON.parse(fs.readFileSync(path.join(realRoot, 'package.json'), 'utf8')).name || ''
16
+ const scope = /^(@[^/]+)\//.exec(rootName)?.[1]
17
+ const owners = new Map()
18
+ const ownerOf = directory => {
19
+ if (owners.has(directory)) return owners.get(directory)
20
+ const manifest = path.join(directory, 'package.json')
21
+ let owner
22
+ if (fs.existsSync(manifest)) {
23
+ owner = { root: normalize(directory), name: JSON.parse(fs.readFileSync(manifest, 'utf8')).name || '' }
24
+ } else {
25
+ const parent = path.dirname(directory)
26
+ // A nested node_modules must never inherit its containing package's ownership.
27
+ owner = parent === directory || path.basename(directory) === 'node_modules' ? null : ownerOf(parent)
28
+ }
29
+ owners.set(directory, owner)
30
+ return owner
31
+ }
32
+ return id => {
33
+ if (id === RUNTIME_ID || id.startsWith('\0hel:shared-runtime:') || /(?:^|\0)plugin-vue:export-helper$/.test(id)) return 'runtime'
34
+ const filename = normalize(id.replace(/^\0/, '')).split('?', 1)[0]
35
+ if (!path.isAbsolute(filename) || !fs.existsSync(filename)) return 'generated'
36
+ const realFile = normalize(fs.realpathSync(filename))
37
+ // Embedded upstream source manifests are metadata, not installed dependencies.
38
+ if (realFile.startsWith(realRoot + '/') && !realFile.slice(realRoot.length + 1).split('/').includes('node_modules')) return 'own'
39
+ const owner = ownerOf(path.dirname(realFile))
40
+ if (owner?.root === realRoot) return 'own'
41
+ if (scope && owner?.name.startsWith(scope + '/')) return 'related'
42
+ return 'thirdParty'
43
+ }
44
+ }
45
+
46
+ /** ESM imports remain hoisted; no in-place import-to-const rewriting and no second Vue runtime. */
47
+ function sharedVueRuntimePlugin(exportNames) {
48
+ if (!exportNames.length || exportNames.some(name => !/^[$A-Z_a-z][$\w]*$/.test(name))) {
49
+ throw new TypeError('Pass the named exports of the consuming package\'s installed vue runtime')
50
+ }
51
+ return {
52
+ name: 'hel:shared-vue-runtime',
53
+ enforce: 'pre',
54
+ apply: 'build',
55
+ resolveId(id) { if (id === 'vue' || id === 'vue-demi') return RUNTIME_ID },
56
+ load(id) {
57
+ if (id !== RUNTIME_ID) return null
58
+ return `const runtime = globalThis.Vue;
59
+ if (!runtime) throw new Error('Bind the host Vue runtime before loading remote components');
60
+ ${exportNames.map(name => `export const ${name} = runtime[${JSON.stringify(name)}];`).join('\n')}
61
+ export default runtime;`
62
+ },
63
+ }
64
+ }
65
+
66
+ /**
67
+ * Explicit ESM bridges for host-owned runtimes. Each import declares real named
68
+ * exports, so both Rollup and Rolldown work without syntheticNamedExports.
69
+ * Namespace imports use the host object itself; ESM imports remain hoisted.
70
+ * This plugin never changes the consuming package's build/externals/output config.
71
+ */
72
+ function sharedRuntimePlugin(globals) {
73
+ const prefix = '\0hel:shared-runtime:'
74
+ const bridges = new Map()
75
+ const bridgeId = (source, names = []) => {
76
+ const id = prefix + JSON.stringify([source, [...new Set(names)].sort()])
77
+ bridges.set(id, { source, names: [...new Set(names)].sort() })
78
+ return id
79
+ }
80
+ return {
81
+ name: 'hel:shared-runtime', apply: 'build', enforce: 'post',
82
+ buildStart() { bridges.clear() },
83
+ resolveId(id) {
84
+ if (bridges.has(id)) return id
85
+ if (Object.hasOwn(globals, id)) return bridgeId(id)
86
+ },
87
+ transform(code, id) {
88
+ if (id.startsWith(prefix) || !Object.keys(globals).some(source => code.includes(source))) return null
89
+ let ast
90
+ try { ast = this.parse(code) } catch { return null } // Non-JavaScript assets.
91
+ const edits = []
92
+ for (const node of ast.body) {
93
+ if (!node.source || !Object.hasOwn(globals, node.source.value)) continue
94
+ if (node.type === 'ExportAllDeclaration' && node.exported) {
95
+ edits.push([node.start, node.end, 'export { default as ' + node.exported.name + ' } from ' + JSON.stringify(bridgeId(node.source.value)) + ';'])
96
+ continue
97
+ }
98
+ if (node.type === 'ExportAllDeclaration') {
99
+ this.error('Use explicit named re-exports for shared runtime ' + node.source.value + ' in ' + id)
100
+ }
101
+ if (!['ImportDeclaration', 'ExportNamedDeclaration'].includes(node.type)) continue
102
+ const names = []
103
+ for (const specifier of node.specifiers) {
104
+ if (specifier.type === 'ImportSpecifier') names.push(specifier.imported.name ?? specifier.imported.value)
105
+ if (specifier.type === 'ExportSpecifier') names.push(specifier.local.name ?? specifier.local.value)
106
+ if (specifier.type === 'ImportNamespaceSpecifier') {
107
+ edits.push([specifier.start, specifier.end, '{ default as ' + specifier.local.name + ' }'])
108
+ }
109
+ }
110
+ edits.push([node.source.start, node.source.end, JSON.stringify(bridgeId(node.source.value, names))])
111
+ }
112
+ const visit = node => {
113
+ if (!node || typeof node !== 'object') return
114
+ if (node.type === 'ImportExpression' && Object.hasOwn(globals, node.source?.value)) {
115
+ edits.push([node.start, node.end, 'import(' + JSON.stringify(bridgeId(node.source.value)) + ').then(module => module.default)'])
116
+ return
117
+ }
118
+ for (const value of Object.values(node)) {
119
+ if (Array.isArray(value)) value.forEach(visit)
120
+ else if (value && typeof value === 'object') visit(value)
121
+ }
122
+ }
123
+ visit(ast)
124
+ if (!edits.length) return null
125
+ for (const [start, end, replacement] of edits.sort((a, b) => b[0] - a[0])) {
126
+ code = code.slice(0, start) + replacement + code.slice(end)
127
+ }
128
+ return { code, map: null }
129
+ },
130
+ load(id) {
131
+ const bridge = bridges.get(id)
132
+ if (!bridge) return null
133
+ const name = globals[bridge.source]
134
+ const access = name.split('.').filter(part => !['window', 'globalThis', 'global'].includes(part))
135
+ .map(part => '[' + JSON.stringify(part) + ']').join('')
136
+ return 'const runtime = globalThis' + access + ';\n'
137
+ + 'if (runtime == null) throw new Error(' + JSON.stringify('Bind shared runtime before loading remote package: ' + name) + ');\n'
138
+ + 'export default runtime;\n'
139
+ + bridge.names.filter(name => name !== 'default').map((name, index) =>
140
+ 'const binding' + index + ' = runtime[' + JSON.stringify(name) + ']; export { binding' + index + ' as ' + (/^[$A-Z_a-z][$\w]*$/.test(name) ? name : JSON.stringify(name)) + ' };').join('\n')
141
+ },
142
+ }
143
+ }
144
+
145
+ function gzipPlugin() {
146
+ return { name: 'hel:final-gzip', apply: 'build', enforce: 'post', generateBundle: { order: 'post', handler(_output, bundle) {
147
+ if (process.env.HEL_GZIP === '0') return
148
+ const { gzipSync } = require('node:zlib')
149
+ for (const item of Object.values(bundle)) {
150
+ if (!/\.(?:[cm]?js|css)$/i.test(item.fileName)) continue
151
+ const source = item.type === 'chunk' ? item.code : item.source
152
+ if (Buffer.byteLength(source) < 10240) continue
153
+ this.emitFile({ type: 'asset', fileName: item.fileName + '.gz', source: gzipSync(source) })
154
+ }
155
+ } } }
156
+ }
157
+
158
+ /**
159
+ * Vite split ESM apps and ES/CJS library outputs.
160
+ * Invoke the official app hook after Vite's final dependency/preload rewrites, on minified chunks.
161
+ * Its automatic node_modules exclusion is OFF: dependencies in the consumer's scope are protected.
162
+ */
163
+ function bundleObfuscationPlugins({ root, obfuscatorPlugin, enabled = true, options = {}, library = false, rolldown = false }) {
164
+ const classify = createModuleClassifier(root)
165
+ // Split granularity follows the package family; an explicit `options.splitStringsChunkLength` still wins.
166
+ const settings = { ...defaults, ...options, splitStringsChunkLength: options.splitStringsChunkLength ?? splitStringsChunkLength(root),
167
+ seed: options.seed ?? 1, renameProperties: false, sourceMap: false }
168
+ const reports = []
169
+ let currentReports = []
170
+ let runId
171
+ const api = { classify, reports }
172
+ const guard = {
173
+ name: 'hel:bundle-obfuscation-boundaries',
174
+ apply: 'build',
175
+ api,
176
+ buildStart() { reports.length = 0; runId = ++buildSequence },
177
+ config() {
178
+ return { build: { rollupOptions: { output: {
179
+ ...(library ? {} : { format: 'es' }),
180
+ ...(rolldown ? {
181
+ strictExecutionOrder: true,
182
+ // Rolldown rejects includeDependenciesRecursively=false with strict library entries.
183
+ codeSplitting: { minSize: 0, ...(library ? {} : { includeDependenciesRecursively: false }), groups: [
184
+ { name: 'shared-runtime', test: id => classify(id) === 'runtime', priority: 100 },
185
+ { name: 'vendor', test: id => classify(id) === 'thirdParty' || id.includes('commonjs'), priority: 90 },
186
+ { name: 'standalone', test: id => classify(id) === 'own' && normalize(id).includes('/src/standalone/'), priority: 80 },
187
+ { name: 'components', test: id => ['own', 'related'].includes(classify(id)), priority: 70 },
188
+ ] },
189
+ } : {
190
+ onlyExplicitManualChunks: true,
191
+ manualChunks(id) {
192
+ const kind = classify(id)
193
+ if (kind === 'runtime') return 'shared-runtime'
194
+ if (kind === 'own' && normalize(id).includes('/src/standalone/')) return 'standalone'
195
+ if (kind === 'own' || kind === 'related') return 'components'
196
+ if (kind === 'thirdParty' || id.includes('commonjs')) return 'vendor'
197
+ },
198
+ }),
199
+ } } } }
200
+ },
201
+ // The official app plugin runs after Rollup hashes chunks. Include its settings in cache keys.
202
+ augmentChunkHash(chunk) {
203
+ if (excludedChunks.test(chunk.name + '.js')) return
204
+ return createHash('sha256').update(JSON.stringify({ pipeline: 'final-generate-bundle-v2', enabled, settings })).digest('hex')
205
+ },
206
+ generateBundle(_output, bundle) {
207
+ currentReports = []
208
+ for (const chunk of Object.values(bundle)) {
209
+ if (chunk.type !== 'chunk') continue
210
+ const modules = Object.keys(chunk.modules).map(id => ({ id: normalize(id), kind: classify(id) }))
211
+ const protectedModules = modules.filter(item => ['own', 'related'].includes(item.kind))
212
+ if (protectedModules.some(item => /\.(?:vue|tsx?|jsx?|mjs|cjs)\?(?:[^#]*&)?raw(?:&|$)/.test(item.id))) {
213
+ this.error(`Raw protected source cannot be distributed: ${chunk.fileName}`)
214
+ }
215
+ const vendors = modules.filter(item => item.kind === 'thirdParty')
216
+ if (protectedModules.length && vendors.length) {
217
+ this.error(`Mixed business/vendor chunk cannot be safely obfuscated: ${chunk.fileName}`)
218
+ }
219
+ const excluded = excludedChunks.test(chunk.fileName)
220
+ if (vendors.length && !excluded) this.error(`Third-party chunk is not excluded: ${chunk.fileName}`)
221
+ if (protectedModules.length && excluded) this.error(`Protected source leaked into excluded chunk: ${chunk.fileName}`)
222
+ const report = { format: _output.format, fileName: chunk.fileName, modules, protectedModules: protectedModules.length,
223
+ thirdPartyModules: vendors.length, excluded, beforeHash: createHash('sha256').update(chunk.code).digest('hex') }
224
+ reports.push(report)
225
+ currentReports.push(report)
226
+ }
227
+ },
228
+ }
229
+ const plugin = obfuscatorPlugin({ apply: 'build', enable: enabled, log: true, threadPool: false,
230
+ autoExcludeNodeModules: false, excludes: [excludedChunks], options: settings })
231
+ const hook = plugin.transformIndexHtml
232
+ if (typeof hook?.handler !== 'function' || hook.order !== 'post') {
233
+ throw new Error('Expected vite-plugin-bundle-obfuscator post transformIndexHtml hook')
234
+ }
235
+ // HTML hooks run inside vite:build-html, before Vite finalizes dynamic preload maps.
236
+ // Keep the official implementation, but invoke its app hook once at the final output stage.
237
+ // Otherwise late Vite rewrites change bytes after our audit and escape obfuscation.
238
+ plugin.enforce = 'post'
239
+ // The library renderChunk hook otherwise obfuscates before minification.
240
+ plugin.renderChunk = undefined
241
+ const generateBundle = plugin.generateBundle
242
+ plugin.transformIndexHtml = { ...hook, handler: html => html }
243
+ plugin.generateBundle = { order: 'post', async handler(output, bundle) {
244
+ if (typeof generateBundle === 'function') await generateBundle.call(this, output, bundle)
245
+ else if (generateBundle?.handler) await generateBundle.handler.call(this, output, bundle)
246
+ const html = Object.values(bundle).find(item => item.type === 'asset' && item.fileName.endsWith('.html'))
247
+ for (const report of currentReports) {
248
+ report.beforeHash = createHash('sha256').update(bundle[report.fileName].code).digest('hex')
249
+ }
250
+ // The upstream plugin keeps a process-wide filename registry. Unique lookup keys
251
+ // prevent silently skipping a subsequent/watch build without altering output URLs.
252
+ const finalBundle = Object.fromEntries(Object.entries(bundle).map(([name, chunk]) => [`__hel_${runId}_${output.format}__/${name}`, chunk]))
253
+ await hook.handler.call(this, html ? String(html.source) : '', { bundle: finalBundle })
254
+ for (const report of currentReports) {
255
+ const code = bundle[report.fileName].code
256
+ report.afterHash = createHash('sha256').update(code).digest('hex')
257
+ report.identifiers = (code.match(/\b_0x[\da-f]+\b/g) || []).length
258
+ report.obfuscated = report.beforeHash !== report.afterHash
259
+ if (report.excluded && report.obfuscated) throw new Error(`Excluded chunk changed: ${report.fileName}`)
260
+ if (enabled && report.protectedModules && (!report.obfuscated || !report.identifiers)) {
261
+ throw new Error(`Final business chunk is not obfuscated: ${report.fileName}`)
262
+ }
263
+ console.log(`[hel:bundle] ${report.fileName}: ${report.obfuscated ? 'obfuscated' : 'unchanged'}, _0x identifiers=${report.identifiers}, own/related=${report.protectedModules}, third-party=${report.thirdPartyModules}`)
264
+ }
265
+ } }
266
+ return [guard, plugin]
267
+ }
268
+
269
+ module.exports = { bundleObfuscationPlugins, createModuleClassifier, sharedVueRuntimePlugin, sharedRuntimePlugin, gzipPlugin }