@melt-js/libs-core 0.0.0-stage → 2026.11.14

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 (40) hide show
  1. package/README.md +187 -3
  2. package/package.json +50 -3
  3. package/scripts/check-tdz.mjs +325 -0
  4. package/scripts/comps-bundle-obfuscation.cjs +262 -0
  5. package/scripts/comps-no-sourcemaps.cjs +18 -0
  6. package/scripts/comps-obfuscator-options.cjs +39 -0
  7. package/scripts/comps-source-obfuscation-loader.cjs +11 -0
  8. package/scripts/comps-source-obfuscation.cjs +114 -0
  9. package/scripts/package-env.cjs +180 -0
  10. package/scripts/publish-stage.mjs +45 -0
  11. package/scripts/vdoc-parser/NOTICE.md +14 -0
  12. package/scripts/vdoc-parser/constants.mjs +3 -0
  13. package/scripts/vdoc-parser/index.d.mts +35 -0
  14. package/scripts/vdoc-parser/index.mjs +2 -0
  15. package/scripts/vdoc-parser/parsers/index.mjs +14 -0
  16. package/scripts/vdoc-parser/parsers/parseCode.mjs +42 -0
  17. package/scripts/vdoc-parser/parsers/parseCommentBlock.mjs +9 -0
  18. package/scripts/vdoc-parser/parsers/parseComponentOptions.mjs +12 -0
  19. package/scripts/vdoc-parser/parsers/parseDefaultValue.mjs +57 -0
  20. package/scripts/vdoc-parser/parsers/parseDefineProps.mjs +33 -0
  21. package/scripts/vdoc-parser/parsers/parseExport.mjs +93 -0
  22. package/scripts/vdoc-parser/parsers/parseFile.mjs +22 -0
  23. package/scripts/vdoc-parser/parsers/parseFileSync.mjs +22 -0
  24. package/scripts/vdoc-parser/parsers/parsePropType.mjs +32 -0
  25. package/scripts/vdoc-parser/parsers/parseProps.mjs +90 -0
  26. package/scripts/vdoc-parser/parsers/parseSetupScript.mjs +14 -0
  27. package/scripts/vdoc-parser/parsers/parseSfc.mjs +21 -0
  28. package/scripts/vdoc-parser/parsers/parseTSTypeLiteral.mjs +48 -0
  29. package/scripts/vdoc-parser/parsers/parseTypes.mjs +53 -0
  30. package/scripts/vdoc-parser/parsers/parseTypesFile.mjs +22 -0
  31. package/scripts/vdoc-parser/parsers/parseTypesFileSync.mjs +22 -0
  32. package/scripts/vdoc-parser/resolvers/index.mjs +2 -0
  33. package/scripts/vdoc-parser/resolvers/resolveSpreadElements.mjs +51 -0
  34. package/scripts/vdoc-parser/utils.mjs +52 -0
  35. package/scripts/webpack-bundle-obfuscation.cjs +121 -0
  36. package/src/index.ts +1 -0
  37. package/src/remote-address.cjs +30 -0
  38. package/src/remote.d.mts +95 -0
  39. package/src/remote.mjs +249 -0
  40. package/tsconfig.json +13 -0
package/README.md CHANGED
@@ -1,3 +1,187 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
1
+ # @melt-js/libs-core
2
+
3
+ Hel 远程依赖工具箱与可独立安装的共享构建工具。不维护具体项目的依赖清单,也不构建成远程组件。
4
+
5
+ ## 运行时工具
6
+
7
+ 框架无关的地址协议、分批预加载、按需加载、请求复用、全局串行调度、导出校验和统一错误都在本包。
8
+ 浏览器入口使用可直接执行的 ESM,并保留 TypeScript 类型,Vue CLI / Vite 消费方不需要编译本包的 TS。
9
+
10
+ ```js
11
+ import { preloadHelLibs, loadHelLib } from '@melt-js/libs-core'
12
+
13
+ // 先绑定宿主的 Vue / React 共享运行时。
14
+ await preloadHelLibs({
15
+ type: 'custom',
16
+ base: 'http://82.156.212.243',
17
+ deps: [
18
+ '@melt-js/comps-vue3',
19
+ 'https://xxx.com/xxx-melt-js/comps-vue3-antd@1.1.1',
20
+ 'libs-xxx@1.1.1',
21
+ '/@melt-js/comps-vue3',
22
+ ],
23
+ })
24
+ await import('./loadApp') // 此后业务代码可以普通 import 已安装的组件代理包。
25
+
26
+ // 低频包放在页面或交互中调用,调用前不会下载。
27
+ const charts = await loadHelLib('@example/comps-charts@1.1.1', { type: 'github' })
28
+ ```
29
+
30
+ 以上地址与包名用于说明协议,不保证示例服务器已发布对应资源。
31
+
32
+ | type | 默认 base | 短包名路径 |
33
+ | --- | --- | --- |
34
+ | `unpkg`(默认) | `https://unpkg.com` | `/包引用[@版本]/hel_dist/hel-meta.json`;不补 scope |
35
+ | `github` | `@owner/pkg` 推导 `https://owner.github.io`;无 scope 时需传 `base` | `/包名[@版本]/hel_dist/hel-meta.json` |
36
+ | `custom` | 相对包引用时必须传入 | `/包引用[@版本]/hel_dist/hel-meta.json` |
37
+
38
+ 公共库没有默认组织或 scope。`@melt-js/libs-xxx@1.1.1` 和 `libs-xxx@1.1.1` 在 unpkg 是两个不同的 npm 包,分别保留原路径;其他 scope 也一样。GitHub 从显式 scope 推导 owner;npm scope 与 GitHub owner 不同或使用自定义域名时,传 `base` 覆盖。
39
+
40
+ SFTP 的 base 只配置站点根 `http://82.156.212.243`。`@melt-js/comps-vue3`、`@other/comps-vue3`、`comps-vue3` 分别解析到 `/@melt-js/comps-vue3`、`/@other/comps-vue3`、`/comps-vue3`,不会自动补 scope。为兼容带命名空间的旧 base,完整 scoped 引用会替换 base 末尾的 `/@scope`,避免重复。
41
+
42
+ - `type` 选择默认 base 和拼接逻辑,`base` 可以覆盖预设;完整 HTTP(S) URL 保持自己的域名与目录。
43
+ - `/comps-vue3` 与 `comps-vue3` 都相对 base 目录;不会丢失 `/@melt-js` 等前缀。
44
+ - `@版本` 固定版本;不写版本或写 `@latest` 使用不带版本的最新入口。完整 URL 的路径不被重写版本。
45
+ - 组件/远程库地址自动补齐 `/hel_dist/hel-meta.json`;`tpl-*` / `demo-*` 或显式 `dist` 地址使用 `/dist/index.html`。已有产物目录、元数据或 `index.html` 不重复拼接,查询参数保留。地址可解析不代表普通应用已提供 Hel 模块注册。
46
+ - custom / GitHub 固定版本要求部署端存在 `包名@版本` 目录;当前根部署脚本发布到不带版本的项目目录,只提供该目录最新产物,本 API 不会静默忽略指定版本。
47
+ - `preloadHelLibs` 按 `libs-* → comps-* → 其他` 三批阻塞加载,同批按声明顺序串行。任一步失败,后续依赖停止。返回以 Hel 组名为键的模块对象。
48
+ - 同一模块的相同请求复用;失败请求清理后允许调用方显式重试,不自动重试。一个平台的同一组名配置不同地址/版本会报 `HelLoadError`,避免代理读到另一版本。
49
+ - 默认 `loadHelLib` 和 `preloadHelLibs` 共用队列;`createHelLoader` 可注入底层加载函数,独立实例之间不共享队列或缓存。
50
+ - 本地开发入口、不同于目录名的组名、导出要求等使用 `{ name, host, appGroupName?, platform?, requiredExports? }`。`host` 是完整入口,保持原样,不追加 `hel_dist`。
51
+ - `resolveHelDep` / `resolveHelDeps` 只解析配置,不发网络请求;`HEL_BASES` 仅暴露无需组织配置的 unpkg 站点。`loadHelLibsSerial` 和 `resolveHelHost` 保留兼容,前者保留调用方显式顺序,后者同样按 SFTP 完整包名、GitHub 项目名解析无版本部署目录。
52
+
53
+ `loadHelComponent({ dep, exportName, type?, base? })` 选择并检查组件导出;也可传 `loader` 替代 `dep`,用于宿主先注入运行时再返回模块对象。`createHelComponentResource` 统一管理加载、错误、手动重试和卸载后的晚到响应,不取消共享请求。
54
+
55
+ 预加载与懒加载的 `type` / `base` / 包引用规则完全一致。`preloadHelLibs({ deps: [] })` 是空操作。字符串引用沿用包的末段作为 Hel 注册组名;若两个 npm 包末段同名且地址不同,会在加载前报组名冲突,需要提供方使用不同组名,并通过显式 `{ name, appGroupName, host }` 配置。
56
+
57
+ `libs-core-vue2` / `libs-core-vue3` / `libs-core-react` 已提供统一 `defineHelComponent`,包含加载提示、错误提示、渲染错误兜底和手动重试,可自定义 UI。超时、网络取消与自动重试未内置。custom 对应 SFTP 的公共 HTTP 站点,base 由消费方从公共环境变量传入;核心不读取业务 env 或部署凭据。
58
+
59
+ ## 共享构建工具
60
+
61
+ 在使用工具的包中直接声明 `@melt-js/libs-core`,不要引用仓库根目录的 `../scripts`。
62
+ 只有构建/发布使用时放 `devDependencies`;运行时也需要 Hel 加载器则放 `dependencies`。
63
+
64
+ ```js
65
+ // ESM(Vite / Rollup)
66
+ import obfuscatorOptions from '@melt-js/libs-core/scripts/comps-obfuscator-options.cjs'
67
+ import noSourceMaps from '@melt-js/libs-core/scripts/comps-no-sourcemaps.cjs'
68
+ ```
69
+
70
+ ```js
71
+ // CommonJS(Vue CLI / webpack)
72
+ const obfuscatorOptions = require('@melt-js/libs-core/scripts/comps-obfuscator-options.cjs')
73
+ ```
74
+
75
+ ```json
76
+ {
77
+ "scripts": {
78
+ "check:tdz": "hel-check-tdz",
79
+ "publish:stage": "pnpm run build && hel-publish-stage"
80
+ },
81
+ "devDependencies": {
82
+ "@melt-js/libs-core": "workspace:*"
83
+ }
84
+ }
85
+ ```
86
+
87
+ - `hel-check-tdz [目录或文件...]`:默认检查调用方当前目录的 `hel_dist/assets`。
88
+ AST 解析依赖 `acorn` 由本包显式携带;离开 workspace 也不会跳过检查。
89
+ - `hel-publish-stage`:在调用方当前目录执行发布前检查、`pnpm pack`,再提交 tarball 至 npm stage。
90
+ `pnpm pack` 用于改写 workspace 协议。此命令会真实提交发布请求,不属于验证命令。
91
+ - 共享 `.cjs` 配置同时支持 `import` 和 `require`,无需加载运行时 TypeScript 入口。
92
+ - `scripts/` 被包含在发布包中;不存在依赖仓库父目录的配置查找。
93
+
94
+ ## 独立使用与检查
95
+
96
+ 复制某个包到仓库外后,将其 `workspace:*` 依赖换成包含相应入口的已发布版本,再安装依赖。
97
+ 本次新增的共享脚本必须先随新版 `libs-core` 发布,不能用未包含这些入口的旧版本替代。
98
+ 不要只安装生产依赖后尝试执行需要开发工具的构建命令。
99
+
100
+ 根目录提供 `pnpm run check:package-boundaries` 和 `pnpm run ci`,检查越界路径、
101
+ 硬编码的虚拟仓库路径以及共享工具依赖声明,并执行回归测试。
102
+ 批量构建依赖属于根目录编排(例如 `pnpm run bag:build:libs`),不应放进子包的 `build` 中。
103
+
104
+ ## comps 源码级混淆
105
+
106
+ `@melt-js/libs-core/scripts/comps-source-obfuscation.cjs` 同时导出 Vite 插件与 Webpack post-loader 规则工厂。
107
+ 消费包必须直接声明 `@melt-js/libs-core` 与 `javascript-obfuscator`,由消费包传入混淆器,避免依赖提升。
108
+
109
+ ```js
110
+ import JavaScriptObfuscator from 'javascript-obfuscator'
111
+ import sourceObfuscation from '@melt-js/libs-core/scripts/comps-source-obfuscation.cjs'
112
+
113
+ // 放在 plugins 中;仅 build 生效,Vue/TS/JSX 编译后、打包前处理。
114
+ sourceObfuscation.sourceObfuscatorPlugin({ obfuscate: JavaScriptObfuscator.obfuscate })
115
+ ```
116
+
117
+ ```js
118
+ const path = require('node:path')
119
+ const { sourceObfuscationRule } = require('@melt-js/libs-core/scripts/comps-source-obfuscation.cjs')
120
+
121
+ // 放在 module.rules 顶层(不能放进 oneOf),仅在生产混淆开关开启时添加。
122
+ sourceObfuscationRule({
123
+ sourceRoot: path.resolve(__dirname, 'src'),
124
+ obfuscatorPath: require.resolve('javascript-obfuscator'),
125
+ })
126
+ ```
127
+
128
+ 默认只允许当前包 `src` 下的 JS/TS/JSX/TSX/Vue 模块,不处理第三方依赖、其他 workspace 包、
129
+ 虚拟模块、样式、raw/url/worker 资源;也不对最终 bundle 再做二次混淆。
130
+ 因此拆分的 vendor chunk 和仍与本包代码同块的第三方代码均只参与正常压缩。
131
+
132
+ 混淆强度:`renameGlobals: true` 会改写模块内部顶层函数/变量及嵌套绑定;ESM 导出名、
133
+ 远程组件对象键、props/emits、宿主注入的外部全局引用保持不变,`renameProperties` 仍关闭。
134
+ 源码工具通过 AST 显式保留声明导出(含数组/对象解构导出),不依赖混淆器自动猜测公开名字。
135
+ 普通字符串进入字符串数组的阈值从 0.3 提高到 0.8,并使用 base64 编码(提高阅读成本,不是加密)。
136
+ 图片 data URL 保留原样;`ignoreImports: true` 保留 import()/require() 模块路径,
137
+ 并额外保护 new URL 的资源路径,避免打包器漏依赖。import/export 路径、部分接口键及未抽中的字符串仍可能可读。
138
+ 不启用控制流平坦化、死代码注入、反调试或 RC4,避免组件初始化和渲染引入过高开销。
139
+ 不要依赖内部函数的 `.name` 或通过 `eval` 用原变量名反射访问;这不属于稳定的远程接口契约。
140
+
141
+ 保留现有拆包和宿主共享运行时策略,不能为拆 vendor 把 UMD 的 `inlineDynamicImports` 改成 `manualChunks`。
142
+
143
+ 新增了共享脚本公开入口,发版时必须先发布包含该入口的新版 `libs-core`,再发布消费它的 comps 包;
144
+ 不能把本地 workspace 的新增入口当成 registry 上旧版本已经支持的入口。
145
+
146
+ ## 包内环境解析(原生命令兼容)
147
+
148
+ 公开入口:`@melt-js/libs-core/scripts/package-env.cjs`。该脚本的 dotenv 运行时依赖由本包直接声明。
149
+ 消费包需要直接声明 `@melt-js/libs-core`,不能依赖根依赖提升。
150
+
151
+ ```js
152
+ // 消费包根目录 env.config.cjs
153
+ const { applyPackageEnv } = require('@melt-js/libs-core/scripts/package-env.cjs')
154
+ module.exports = applyPackageEnv({ cwd: __dirname })
155
+ ```
156
+
157
+ ```js
158
+ // 消费包根目录 env.config.mjs(适用于 Vite 等原生 ESM 配置加载器)
159
+ import { fileURLToPath } from 'node:url'
160
+ import packageEnv from '@melt-js/libs-core/scripts/package-env.cjs'
161
+ export default packageEnv.applyPackageEnv({ cwd: fileURLToPath(new URL('.', import.meta.url)) })
162
+ ```
163
+
164
+ Vite / Vue CLI / CRA / Umi 配置先导入本包 bootstrap,原 `dev` / `build` 命令无需统一包装。
165
+ 仅加载指定 `cwd` 下的 env 文件,进程变量最高优先级;不会向上搜索工作区或跨包读取源码。
166
+ `loadPackageEnv({ cwd, mode, env, target })` 为无进程写入的解析接口,`applyPackageEnv` 将结果写入进程环境。
167
+ `REMOTE_TARGET` 支持 `auto/local/sftp/github/unpkg`;每个 `*_PACKAGE` 可单独使用 `*_TARGET` / `*_URL` 覆盖。
168
+ `*_VERSION=installed` 通过已安装依赖的公开入口解析其包版本;显式版本与 `latest` 也受支持。
169
+ 未配置工作区时可独立 localhost 开发、unpkg 构建;私有 SFTP/GitHub 地址由消费包 `.env.local` 或进程变量提供。
170
+ 只有公共地址会生成 `VITE_` / `VUE_APP_` 等前端变量,不复制 SFTP 凭据。
171
+
172
+ 发布顺序:先发布包含该入口的新版 `libs-core`,再发布/交付使用它的包。
173
+
174
+ ## Vue props / JSDoc 解析(Node)
175
+
176
+ `vdoc-parser@1.2.0` 的解析源码已内置,不需要安装外部 `vdoc-parser` 包:
177
+
178
+ ```js
179
+ import { parseFileSync, parseCode } from '@melt-js/libs-core/vdoc-parser'
180
+
181
+ const props = parseFileSync('/absolute/path/to/Component.vue')
182
+ const inlineProps = parseCode('export default { props: { title: String } }')
183
+ ```
184
+
185
+ 提供同步/异步文件解析、源码解析与 TypeScript 类型提取,供 Vue 2 / Vue 3 leva 的 schema CLI 共用。此子路径是 Node 专用工具,不改变默认浏览器入口;Babel、SFC 编译器和 JSDoc 解析依赖由本包携带。
186
+
187
+ CLI 发布后也会调用本包,因此 leva 包将 `@melt-js/libs-core` 声明在 `dependencies`,而非仅放在 `devDependencies`。发布时先发布包含此子路径的新版 `libs-core`,再发布依赖它的 leva 包,不能让新 CLI 引用尚无此入口的旧版 core。源码出处与适配记录见 `scripts/vdoc-parser/NOTICE.md`。
package/package.json CHANGED
@@ -1,6 +1,53 @@
1
1
  {
2
2
  "name": "@melt-js/libs-core",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "2026.11.14",
4
+ "type": "module",
5
+ "main": "src/remote.mjs",
6
+ "module": "src/remote.mjs",
7
+ "types": "src/index.ts",
8
+ "publishConfig": {
9
+ "access": "public",
10
+ "registry": "https://registry.npmjs.org",
11
+ "tag": "latest"
12
+ },
13
+ "dependencies": {
14
+ "hel-micro": "4.15.3",
15
+ "acorn": "8.19.0",
16
+ "dotenv": "16.6.1",
17
+ "dotenv-expand": "12.0.3",
18
+ "@babel/core": "7.29.13",
19
+ "@babel/generator": "7.29.13",
20
+ "@babel/parser": "7.29.13",
21
+ "@babel/types": "7.29.11",
22
+ "@vue/compiler-sfc": "2.7.14",
23
+ "doctrine": "3.0.0"
24
+ },
25
+ "devDependencies": {
26
+ "typescript": "5.9.3"
27
+ },
28
+ "exports": {
29
+ ".": {
30
+ "types": "./src/index.ts",
31
+ "default": "./src/remote.mjs"
32
+ },
33
+ "./src/*": "./src/*",
34
+ "./scripts/*": "./scripts/*",
35
+ "./package.json": "./package.json",
36
+ "./vdoc-parser": "./scripts/vdoc-parser/index.mjs"
37
+ },
38
+ "files": [
39
+ "src",
40
+ "scripts",
41
+ "tsconfig.json",
42
+ "README.md"
43
+ ],
44
+ "bin": {
45
+ "hel-publish-stage": "./scripts/publish-stage.mjs",
46
+ "hel-check-tdz": "./scripts/check-tdz.mjs"
47
+ },
48
+ "scripts": {
49
+ "typecheck": "tsc --noEmit",
50
+ "test": "node --test tests/*.test.mjs",
51
+ "publish:stage": "node scripts/publish-stage.mjs"
52
+ }
6
53
  }
@@ -0,0 +1,325 @@
1
+ #!/usr/bin/env node
2
+ /*
3
+ |--------------------------------------------------------------------------
4
+ |
5
+ | 产物 TDZ 守卫:扫描构建产物,拦住「先引用、后声明」的 let / const / class。
6
+ |
7
+ | 背景(真实踩过的坑):vite-plugin-externals 在构建期把 import 就地改写成
8
+ | `const X = window.X`,而 ESM 的 import 是提升的(写在哪一行都先于模块体执行)。
9
+ | 一旦依赖产物把 import 写在模块体后面(tsup 输出常见),改写后就变成:
10
+ |
11
+ | __reExport(ns, vueNs); const vueNs = window.Vue // ← TDZ
12
+ |
13
+ | 浏览器加载即抛 `Cannot access 'xxx' before initialization`;混淆后变量名变成
14
+ | `_0x2bee8b` 之类,很难看出真因。这个脚本在 build 阶段直接拦下这类产物。
15
+ |
16
+ | 判定口径:引用位置早于声明位置,且两者之间没有跨函数边界(即加载期就会执行到)。
17
+ | 跨了函数的「延后引用」不算——那是正常写法(函数体在模块求值完成后才调用)。
18
+ |
19
+ | 用法:
20
+ | hel-check-tdz # 默认扫当前目录的 hel_dist/assets
21
+ | hel-check-tdz dist bundle.js # 也可指定目录 / 文件
22
+ | 退出码:发现 immediate TDZ → 1
23
+ |
24
+ |--------------------------------------------------------------------------
25
+ */
26
+ import fs from 'node:fs'
27
+ import path from 'node:path'
28
+ import { parse } from 'acorn'
29
+
30
+ const FUNCTION_TYPES = new Set([
31
+ 'FunctionDeclaration',
32
+ 'FunctionExpression',
33
+ 'ArrowFunctionExpression',
34
+ ])
35
+ const CLASS_TYPES = new Set(['ClassDeclaration', 'ClassExpression'])
36
+ const SKIP_KEYS = new Set(['type', 'start', 'end', 'loc', 'range', '__parent'])
37
+
38
+ const isNode = v => !!v && typeof v === 'object' && typeof v.type === 'string'
39
+
40
+ /** 通用 AST 遍历,顺手挂 __parent,方便判断标识符的语法角色 */
41
+ function walk(node, enter) {
42
+ enter(node)
43
+ for (const key of Object.keys(node)) {
44
+ if (SKIP_KEYS.has(key)) continue
45
+ const value = node[key]
46
+ if (Array.isArray(value)) {
47
+ for (const item of value) {
48
+ if (isNode(item)) {
49
+ item.__parent = node
50
+ walk(item, enter)
51
+ }
52
+ }
53
+ } else if (isNode(value)) {
54
+ value.__parent = node
55
+ walk(value, enter)
56
+ }
57
+ }
58
+ }
59
+
60
+ class Scope {
61
+ constructor(kind, parent, isFunction) {
62
+ this.kind = kind
63
+ this.parent = parent
64
+ this.isFunction = isFunction
65
+ /** name -> { start, kind } */
66
+ this.lexical = new Map()
67
+ }
68
+ }
69
+
70
+ function collectPatternNames(node, cb) {
71
+ if (!node) return
72
+ if (node.type === 'Identifier') return cb(node)
73
+ if (node.type === 'AssignmentPattern') return collectPatternNames(node.left, cb)
74
+ if (node.type === 'RestElement') return collectPatternNames(node.argument, cb)
75
+ if (node.type === 'ArrayPattern') {
76
+ for (const el of node.elements) collectPatternNames(el, cb)
77
+ return
78
+ }
79
+ if (node.type === 'ObjectPattern') {
80
+ for (const prop of node.properties) {
81
+ if (prop.type === 'RestElement') collectPatternNames(prop.argument, cb)
82
+ else collectPatternNames(prop.value, cb)
83
+ }
84
+ }
85
+ }
86
+
87
+ /** 标识符是否处于「声明位置」(绑定名),是则不算引用 */
88
+ function isDeclarationIdentifier(node) {
89
+ const p = node.__parent
90
+ if (!p) return true
91
+ if (p.type === 'VariableDeclarator' && p.id === node) return true
92
+ if (FUNCTION_TYPES.has(p.type) && p.id === node) return true
93
+ if (CLASS_TYPES.has(p.type) && p.id === node) return true
94
+ if (p.type === 'CatchClause' && p.param === node) return true
95
+ if (
96
+ p.type === 'ImportSpecifier' ||
97
+ p.type === 'ImportDefaultSpecifier' ||
98
+ p.type === 'ImportNamespaceSpecifier'
99
+ )
100
+ return true
101
+ if (
102
+ p.type === 'ArrayPattern' ||
103
+ p.type === 'ObjectPattern' ||
104
+ p.type === 'RestElement' ||
105
+ p.type === 'AssignmentPattern' ||
106
+ p.type === 'Property'
107
+ ) {
108
+ let cur = node
109
+ let up = cur.__parent
110
+ while (
111
+ up &&
112
+ (up.type === 'ArrayPattern' ||
113
+ up.type === 'ObjectPattern' ||
114
+ up.type === 'RestElement' ||
115
+ up.type === 'AssignmentPattern' ||
116
+ up.type === 'Property')
117
+ ) {
118
+ if (up.type === 'AssignmentPattern' && up.left === cur && up.right === node) return false
119
+ cur = up
120
+ up = up.__parent
121
+ }
122
+ return !!(
123
+ up &&
124
+ ((up.type === 'VariableDeclarator' && up.id === cur) ||
125
+ FUNCTION_TYPES.has(up.type) ||
126
+ (up.type === 'CatchClause' && up.param === cur))
127
+ )
128
+ }
129
+ return false
130
+ }
131
+
132
+ /** 引用是否属于「不是变量引用」的语法位置(属性名、label 等) */
133
+ function isNonReferencePosition(node) {
134
+ const p = node.__parent
135
+ if (!p) return true
136
+ if (p.type === 'MemberExpression' && p.property === node && !p.computed) return true
137
+ if (p.type === 'Property' && p.key === node && !p.computed) return true
138
+ if (p.type === 'MethodDefinition' && p.key === node && !p.computed) return true
139
+ if (p.type === 'PropertyDefinition' && p.key === node && !p.computed) return true
140
+ if (p.type === 'LabeledStatement' || p.type === 'BreakStatement' || p.type === 'ContinueStatement')
141
+ return true
142
+ if (p.type === 'ExportSpecifier' || p.type === 'ImportSpecifier') return true
143
+ return false
144
+ }
145
+
146
+ function analyzeCode(code, filename) {
147
+ let ast
148
+ try {
149
+ ast = parse(code, {
150
+ ecmaVersion: 'latest',
151
+ sourceType: 'script',
152
+ allowHashBang: true,
153
+ allowReturnOutsideFunction: true,
154
+ })
155
+ } catch (err) {
156
+ // 少数产物是 ESM,按 module 再解析一次
157
+ ast = parse(code, {
158
+ ecmaVersion: 'latest',
159
+ sourceType: 'module',
160
+ allowHashBang: true,
161
+ })
162
+ }
163
+
164
+ walk(ast, () => {}) // 只为建立 __parent
165
+
166
+ const scopeByNode = new Map()
167
+ /** 绑定标识符(函数参数 / catch 参数等)本身,不参与「引用早于声明」判断 */
168
+ const bindingByNode = new Map()
169
+ const root = new Scope('program', null, false)
170
+
171
+ const build = (node, scope) => {
172
+ let current = scope
173
+ if (FUNCTION_TYPES.has(node.type)) {
174
+ current = new Scope('function', scope, true)
175
+ } else if (node.type === 'BlockStatement' || node.type === 'StaticBlock') {
176
+ current = new Scope('block', scope, false)
177
+ } else if (node.type === 'CatchClause') {
178
+ current = new Scope('catch', scope, false)
179
+ } else if (
180
+ // for (let x of/in ...) 的循环变量属于 for 语句自己的作用域,不是外层;
181
+ // 压缩产物里 `for(let e in t)` 很常见,不单独建作用域会把它误判成外层 let
182
+ node.type === 'ForStatement' ||
183
+ node.type === 'ForInStatement' ||
184
+ node.type === 'ForOfStatement' ||
185
+ // switch 的 case 共用同一个块级作用域
186
+ node.type === 'SwitchStatement'
187
+ ) {
188
+ current = new Scope('block', scope, false)
189
+ } else if (CLASS_TYPES.has(node.type)) {
190
+ current = new Scope('class', scope, false)
191
+ }
192
+ scopeByNode.set(node, current)
193
+
194
+ const declare = (id, kind) => {
195
+ if (!current.lexical.has(id.name)) current.lexical.set(id.name, { start: id.start, kind })
196
+ // 参数 / 循环变量 / catch 参数也属于「声明位置」,后续引用不应被当成外层同名变量
197
+ if (!bindingByNode.has(id)) bindingByNode.set(id, { scope: current, kind, start: id.start })
198
+ }
199
+
200
+ // 函数参数与 catch 参数也是绑定:不登记的话,压缩产物里形参名和模块级 let 同名时会大面积误报
201
+ if (FUNCTION_TYPES.has(node.type)) {
202
+ for (const param of node.params || []) collectPatternNames(param, id => declare(id, 'param'))
203
+ }
204
+ if (node.type === 'CatchClause' && node.param) {
205
+ collectPatternNames(node.param, id => declare(id, 'catch'))
206
+ }
207
+
208
+ if (node.type === 'VariableDeclaration' && (node.kind === 'let' || node.kind === 'const')) {
209
+ for (const decl of node.declarations) {
210
+ collectPatternNames(decl.id, id => declare(id, node.kind))
211
+ }
212
+ }
213
+ if (node.type === 'ClassDeclaration' && node.id) {
214
+ // 类声明:类名在「类自身作用域」和「外层作用域」都可见
215
+ const outer = scopeByNode.get(node.__parent) || scope
216
+ if (!outer.lexical.has(node.id.name))
217
+ outer.lexical.set(node.id.name, { start: node.id.start, kind: 'class' })
218
+ declare(node.id, 'class')
219
+ } else if (node.type === 'ClassExpression' && node.id) {
220
+ // 类表达式(如压缩产物里的 `var Y = class e extends Error {}`)的类名只在本类内部可见,
221
+ // 不能登记到外层作用域,否则会把外层同名引用误判成 TDZ
222
+ declare(node.id, 'class')
223
+ }
224
+ if (node.type === 'ImportDeclaration') {
225
+ for (const spec of node.specifiers) declare(spec.local, 'import')
226
+ }
227
+
228
+ for (const key of Object.keys(node)) {
229
+ if (SKIP_KEYS.has(key)) continue
230
+ const value = node[key]
231
+ if (Array.isArray(value)) {
232
+ for (const item of value) if (isNode(item)) build(item, current)
233
+ } else if (isNode(value)) build(value, current)
234
+ }
235
+ }
236
+ build(ast, root)
237
+
238
+ const problems = []
239
+ walk(ast, node => {
240
+ if (node.type !== 'Identifier') return
241
+ if (bindingByNode.has(node)) return
242
+ if (isDeclarationIdentifier(node)) return
243
+ if (isNonReferencePosition(node)) return
244
+
245
+ let scope = scopeByNode.get(node)
246
+ let hit = null
247
+ while (scope) {
248
+ if (scope.lexical.has(node.name)) {
249
+ hit = { scope, info: scope.lexical.get(node.name) }
250
+ break
251
+ }
252
+ scope = scope.parent
253
+ }
254
+ if (!hit) return
255
+ if (node.start > hit.info.start) return // 正常顺序
256
+
257
+ // 引用到声明之间是否跨了函数:跨了说明是延后执行(不是加载期 TDZ)
258
+ let crossings = 0
259
+ let cur = scopeByNode.get(node)
260
+ while (cur && cur !== hit.scope) {
261
+ if (cur.isFunction) crossings++
262
+ cur = cur.parent
263
+ }
264
+ if (crossings > 0) return
265
+
266
+ problems.push({
267
+ name: node.name,
268
+ start: node.start,
269
+ declStart: hit.info.start,
270
+ declKind: hit.info.kind,
271
+ snippet: code.slice(Math.max(0, node.start - 70), node.start + 90).replace(/\s+/g, ' '),
272
+ })
273
+ })
274
+
275
+ return problems.map(p => ({ ...p, file: filename }))
276
+ }
277
+
278
+ function collectFiles(target) {
279
+ const stat = fs.statSync(target, { throwIfNoEntry: false })
280
+ if (!stat) return []
281
+ if (stat.isFile()) return [target]
282
+ return fs
283
+ .readdirSync(target, { withFileTypes: true })
284
+ .flatMap(entry => {
285
+ const full = path.join(target, entry.name)
286
+ if (entry.isDirectory()) return collectFiles(full)
287
+ return entry.isFile() && /\.m?js$/.test(entry.name) ? [full] : []
288
+ })
289
+ }
290
+
291
+ const targets = process.argv.slice(2)
292
+ const defaultTarget = 'hel_dist/assets'
293
+ const files = (targets.length ? targets : [defaultTarget]).flatMap(collectFiles)
294
+
295
+ if (!files.length) {
296
+ console.warn(`[check-tdz] 没有找到可检查的产物(目标:${targets.join(', ') || defaultTarget})`)
297
+ process.exit(0)
298
+ }
299
+
300
+ let failed = false
301
+ for (const file of files) {
302
+ const code = fs.readFileSync(file, 'utf8')
303
+ const problems = analyzeCode(code, file)
304
+ const size = (code.length / 1024).toFixed(0)
305
+ if (!problems.length) {
306
+ console.log(`[check-tdz] OK ${file} (${size}KB)`)
307
+ continue
308
+ }
309
+ failed = true
310
+ console.error(`[check-tdz] FAIL ${file} (${size}KB) —— 发现 ${problems.length} 处加载期 TDZ 风险`)
311
+ for (const p of problems.slice(0, 10)) {
312
+ console.error(` · ${p.declKind} '${p.name}' 引用@${p.start} 早于声明@${p.declStart}`)
313
+ console.error(` ...${p.snippet}...`)
314
+ }
315
+ }
316
+
317
+ if (failed) {
318
+ console.error(
319
+ '\n[check-tdz] 产物里有「先引用、后声明」的 let/const/class,浏览器加载即抛 ' +
320
+ "ReferenceError: Cannot access 'xxx' before initialization。\n" +
321
+ '常见原因:构建期用了 vite-plugin-externals(把 import 就地改写成 const,破坏 ESM 提升),' +
322
+ '或打包产物把 import 写在了模块体后面。',
323
+ )
324
+ }
325
+ process.exitCode = failed ? 1 : 0