@modusensus/dsh-mneme 0.7.30 → 0.7.32

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 (86) hide show
  1. package/README.md +25 -7
  2. package/lib/api.js +79 -6
  3. package/lib/client.js +217 -30
  4. package/lib/commands.js +6 -2
  5. package/lib/config.js +80 -14
  6. package/lib/dream/decisions.js +147 -14
  7. package/lib/dream/sleep.js +84 -34
  8. package/lib/dream.js +250 -60
  9. package/lib/embedding.js +22 -2
  10. package/lib/index.js +68 -37
  11. package/lib/inject.js +16 -9
  12. package/lib/lang.js +156 -0
  13. package/lib/local-embedder.js +23 -9
  14. package/lib/mirror.js +17 -14
  15. package/lib/reranker.js +23 -8
  16. package/lib/runtime/adopt.js +176 -0
  17. package/lib/runtime/closure.js +172 -0
  18. package/lib/runtime/download.js +247 -0
  19. package/lib/runtime/layout.js +235 -0
  20. package/lib/runtime/loader.js +249 -0
  21. package/lib/runtime/provision.js +237 -0
  22. package/lib/runtime/tarball.js +130 -0
  23. package/lib/runtime/verify.js +191 -0
  24. package/lib/service.js +102 -8
  25. package/lib/settings.js +36 -2
  26. package/lib/store.js +26 -8
  27. package/lib/summarize.js +108 -35
  28. package/lib/tools.js +119 -0
  29. package/package.json +11 -6
  30. package/runtime-manifest.json +596 -0
  31. package/scripts/build-runtime-manifest.mjs +217 -0
  32. package/scripts/mneme-runtime.mjs +277 -0
  33. package/src/api.js +79 -6
  34. package/src/commands.js +6 -2
  35. package/src/config.js +80 -14
  36. package/src/dream/decisions.js +147 -14
  37. package/src/dream/sleep.js +84 -34
  38. package/src/dream.js +250 -60
  39. package/src/embedding.js +22 -2
  40. package/src/index.js +68 -37
  41. package/src/inject.js +16 -9
  42. package/src/lang.js +156 -0
  43. package/src/local-embedder.js +23 -9
  44. package/src/mirror.js +17 -14
  45. package/src/reranker.js +23 -8
  46. package/src/runtime/adopt.js +176 -0
  47. package/src/runtime/closure.js +172 -0
  48. package/src/runtime/download.js +247 -0
  49. package/src/runtime/layout.js +235 -0
  50. package/src/runtime/loader.js +249 -0
  51. package/src/runtime/provision.js +237 -0
  52. package/src/runtime/tarball.js +130 -0
  53. package/src/runtime/verify.js +191 -0
  54. package/src/service.js +102 -8
  55. package/src/settings.js +36 -2
  56. package/src/store.js +26 -8
  57. package/src/summarize.js +108 -35
  58. package/src/tools.js +119 -0
  59. package/test/api.test.js +89 -9
  60. package/test/client.test.js +94 -10
  61. package/test/config.test.js +17 -1
  62. package/test/dream-candidate-hybrid.test.js +281 -0
  63. package/test/dream.test.js +172 -0
  64. package/test/embedding-ready.test.js +196 -0
  65. package/test/helpers/runtime-source.js +60 -0
  66. package/test/helpers/tar-builder.js +80 -0
  67. package/test/inject.test.js +37 -1
  68. package/test/lang.test.js +87 -0
  69. package/test/quality-filter.test.js +68 -0
  70. package/test/reasoning-effort.test.js +106 -15
  71. package/test/reindex-backfill.test.js +62 -0
  72. package/test/runtime-adopt.test.js +206 -0
  73. package/test/runtime-cli.test.js +89 -0
  74. package/test/runtime-closure.test.js +193 -0
  75. package/test/runtime-download.test.js +302 -0
  76. package/test/runtime-layout.test.js +163 -0
  77. package/test/runtime-loader.test.js +237 -0
  78. package/test/runtime-manifest.test.js +158 -0
  79. package/test/runtime-provision.test.js +101 -0
  80. package/test/runtime-tarball.test.js +82 -0
  81. package/test/runtime-verify.test.js +214 -0
  82. package/test/sleep-action-set.test.js +422 -0
  83. package/test/store.test.js +14 -0
  84. package/test/summarize.test.js +224 -0
  85. package/test/tools.test.js +30 -5
  86. package/test/webServer-optional.test.js +34 -1
@@ -0,0 +1,237 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { existsSync, mkdirSync, mkdtempSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { isAbsolute, join } from "node:path";
6
+ import { fileURLToPath } from "node:url";
7
+ import { describeLocalRuntime, loadTransformers, publicRuntimeStatus, resolveRuntimeEntry } from "../src/runtime/loader.js";
8
+ import { TRANSFORMERS_ENTRY, defaultRuntimeDir, payloadDir, payloadId } from "../src/runtime/layout.js";
9
+
10
+ // 三层解析(issue #131 / PR-A)。这里守的是两条容易出错的承诺:
11
+ // ① 自管运行时优先,且能用绝对 file URL 真的加载起来;
12
+ // ② 降级路径不许静默 —— 「自管那份坏了」和「本机根本没有」必须能分辨。
13
+ // 第 ② 层(宿主裸 specifier)是 PR-A 期间老用户不断线的保障,必须真的会退回去。
14
+
15
+ /** 造一份结构合法的 payload。 */
16
+ function makePayload(runtimeDir, { version = "4.2.0", platform = "win32", arch = "x64", withEntry = true } = {}) {
17
+ const dir = payloadDir(runtimeDir, payloadId({ version, platform, arch: "x64" }));
18
+ const write = (rel, body) => {
19
+ const full = join(dir, rel);
20
+ mkdirSync(join(full, ".."), { recursive: true });
21
+ writeFileSync(full, body);
22
+ };
23
+ for (const name of ["@huggingface/transformers", "onnxruntime-node", "sharp"]) {
24
+ write(join("node_modules", name, "package.json"), JSON.stringify({ name, version: name === "@huggingface/transformers" ? version : "1.0.0" }));
25
+ }
26
+ if (withEntry) write(TRANSFORMERS_ENTRY, "export const source = 'runtime';\n");
27
+ mkdirSync(join(dir, "node_modules", "onnxruntime-node", "bin", "napi-v6", platform, arch), { recursive: true });
28
+ return dir;
29
+ }
30
+
31
+ const emptyRuntime = () => mkdtempSync(join(tmpdir(), "mneme-loader-rt-"));
32
+
33
+ test("第 ① 层:自管运行时可用时优先用它,并报出来源与 payloadId", async () => {
34
+ const runtimeDir = emptyRuntime();
35
+ const dir = makePayload(runtimeDir);
36
+ const loaded = await loadTransformers({
37
+ runtimeDir,
38
+ platform: "win32", arch: "x64",
39
+ importModule: async (specifier) => ({ loadedFrom: specifier })
40
+ });
41
+ assert.equal(loaded.source, "runtime");
42
+ assert.equal(loaded.payloadId, "transformers-4.2.0-node-win32-x64");
43
+ assert.equal(loaded.version, "4.2.0");
44
+ assert.ok(loaded.entryUrl.startsWith("file:///"), "必须是绝对 file URL,否则内部裸导入解析不到同目录的包");
45
+ // 断言「URL 反解回来就是那个入口文件」,而不是拿 URL 字符串去 includes 一个 OS 路径字符串:
46
+ // 后者会被 pathToFileURL 的百分号编码打败(路径含空格等字符时必误报,实测 CI Windows 上就挂了)。
47
+ assert.equal(
48
+ fileURLToPath(loaded.entryUrl),
49
+ join(dir, TRANSFORMERS_ENTRY),
50
+ `entryUrl=${loaded.entryUrl} dir=${dir}`
51
+ );
52
+ });
53
+
54
+ test("第 ② 层:没有自管运行时时退回宿主裸 specifier(PR-A 期间老用户靠这层不断线)", async () => {
55
+ const seen = [];
56
+ const loaded = await loadTransformers({
57
+ runtimeDir: emptyRuntime(),
58
+ importModule: async (specifier) => {
59
+ seen.push(specifier);
60
+ return { loadedFrom: specifier };
61
+ }
62
+ });
63
+ assert.equal(loaded.source, "host");
64
+ assert.deepEqual(seen, ["@huggingface/transformers"]);
65
+ });
66
+
67
+ test("降级不许静默:自管那份坏了要回调出来,同时仍然退到宿主", async () => {
68
+ const runtimeDir = emptyRuntime();
69
+ makePayload(runtimeDir);
70
+ const failures = [];
71
+ const loaded = await loadTransformers({
72
+ runtimeDir,
73
+ platform: "win32", arch: "x64",
74
+ onFailure: (m) => failures.push(m),
75
+ importModule: async (specifier) => {
76
+ if (specifier.startsWith("file:///")) throw new Error("Cannot find package 'onnxruntime-node'");
77
+ return { loadedFrom: "host" };
78
+ }
79
+ });
80
+ assert.equal(loaded.source, "host");
81
+ assert.equal(failures.length, 1);
82
+ assert.match(failures[0], /自管运行时 transformers-4.2.0-node-win32-x64 加载失败/);
83
+ assert.match(failures[0], /onnxruntime-node/);
84
+ });
85
+
86
+ test("第 ② 层版本门禁:宿主装到 v5 就不静默使用,落到第 ③ 层的可操作提示", async () => {
87
+ await assert.rejects(
88
+ () =>
89
+ loadTransformers({
90
+ runtimeDir: emptyRuntime(),
91
+ importModule: async () => ({ env: { version: "5.0.0" } })
92
+ }),
93
+ (error) => {
94
+ assert.equal(error.code, "MNEME_RUNTIME_UNAVAILABLE");
95
+ // transformers 把版本挂在 env 上(顶层没有 version,实测 4.2.0 的 Node 构建),
96
+ // 所以门禁两个位置都看;越界时那句原因要能被人看懂。
97
+ assert.match(error.message, /版本越界:5\.0\.0/);
98
+ return true;
99
+ }
100
+ );
101
+ });
102
+
103
+ test("第 ② 层版本门禁:区间内放行并报出版本;拿不到版本时不拦", async () => {
104
+ const inRange = await loadTransformers({
105
+ runtimeDir: emptyRuntime(),
106
+ importModule: async () => ({ env: { version: "4.2.0" } })
107
+ });
108
+ assert.equal(inRange.source, "host");
109
+ assert.equal(inRange.version, "4.2.0");
110
+
111
+ // 拿不到版本 = 无法判断,不拦:否则这层会对某些打包形态整体失效,
112
+ // 而它正是老用户收编完成前的不断线保障。
113
+ const unknown = await loadTransformers({
114
+ runtimeDir: emptyRuntime(),
115
+ importModule: async () => ({})
116
+ });
117
+ assert.equal(unknown.source, "host");
118
+ assert.equal(unknown.version, undefined);
119
+ });
120
+
121
+ test("第 ③ 层:两层都没有时给出可操作提示,并列出每一层为什么失败", async () => {
122
+ const runtimeDir = emptyRuntime();
123
+ makePayload(runtimeDir);
124
+ await assert.rejects(
125
+ () =>
126
+ loadTransformers({
127
+ runtimeDir,
128
+ platform: "win32", arch: "x64",
129
+ importModule: async (specifier) => {
130
+ throw new Error(specifier.startsWith("file:///") ? "payload broken" : "Cannot find module");
131
+ }
132
+ }),
133
+ (error) => {
134
+ assert.equal(error.code, "MNEME_RUNTIME_UNAVAILABLE");
135
+ assert.match(error.message, /本地推理运行时不可用/);
136
+ assert.match(error.message, /mneme-runtime\.mjs/, "提示要指向真实存在的入口,而不是一个不存在的子命令");
137
+ // 提示里给的入口脚本必须真的存在。这条踩过:提示指向了一个并不存在的子命令,
138
+ // 用户照着敲只会得到「command not found」,比不给提示更糟。
139
+ const script = /node "([^"]+mneme-runtime\.mjs)"/.exec(error.message);
140
+ assert.ok(script, "提示要带出入口脚本的绝对路径");
141
+ assert.ok(existsSync(script[1]), `提示指向的脚本不存在:${script[1]}`);
142
+ assert.match(error.message, /adopt --from/, "要给出可执行的下一步,而不是一句 module not found");
143
+ assert.match(error.message, /payload broken/, "自管那层的失败原因要带出来");
144
+ assert.match(error.message, /Cannot find module/, "宿主那层的失败原因也要带出来");
145
+ assert.equal(error.failures.length, 2);
146
+ return true;
147
+ }
148
+ );
149
+ });
150
+
151
+ test("resolveRuntimeEntry:跳过结构不合法的 payload,取到可用的那份;全不合规则返回 null", () => {
152
+ const runtimeDir = emptyRuntime();
153
+ makePayload(runtimeDir, { version: "4.2.0", withEntry: false }); // 缺入口 → 不合法
154
+ assert.equal(resolveRuntimeEntry({ runtimeDir, platform: "win32", arch: "x64" }), null, "结构不合法的不能被选中");
155
+
156
+ makePayload(runtimeDir, { version: "4.3.0" });
157
+ const picked = resolveRuntimeEntry({ runtimeDir, platform: "win32", arch: "x64" });
158
+ assert.equal(picked.payloadId, "transformers-4.3.0-node-win32-x64");
159
+ assert.equal(picked.version, "4.3.0");
160
+ });
161
+
162
+ test("resolveRuntimeEntry:运行时根目录不存在时返回 null(不是抛错)", () => {
163
+ assert.equal(resolveRuntimeEntry({ runtimeDir: join(tmpdir(), "mneme-nope-" + Date.now()), platform: "win32", arch: "x64" }), null);
164
+ });
165
+
166
+ test("publicRuntimeStatus:只放行白名单字段,绝对路径与原始错误一律不进 HTTP", () => {
167
+ // /api/dsh-mneme/semantic 是刻意不鉴权的只读端点。完整状态里有 runtimeDir(绝对路径)、
168
+ // hint(内嵌脚本绝对路径)以及 reason/reasons(原始错误文本里带完整文件路径),
169
+ // 发给任何能连上该端口的人就是信息泄漏(CWE-200)。用精确白名单守住这件事:
170
+ // 将来谁往里加字段,这条测试就会红。
171
+ const EXPECTED = ["functional", "integrity", "materialize", "payloadId", "procedure", "status", "version"];
172
+
173
+ const missing = describeLocalRuntime({ runtimeDir: join(tmpdir(), `mneme-secret-${Date.now()}`), platform: "win32", arch: "x64" });
174
+ const pubMissing = publicRuntimeStatus(missing);
175
+ assert.deepEqual(Object.keys(pubMissing).sort(), EXPECTED);
176
+ assert.equal(pubMissing.status, "missing");
177
+ // 完整状态里确实带着这些敏感字段 —— 否则这条测试就没在测东西。
178
+ assert.ok(missing.runtimeDir.startsWith(tmpdir()));
179
+ assert.ok(missing.hint.includes("mneme-runtime.mjs"));
180
+
181
+ const runtimeDir = emptyRuntime();
182
+ const dir = makePayload(runtimeDir);
183
+ writeFileSync(join(dir, "mneme-runtime.json"), JSON.stringify({ procedure: "adopted", materialize: { mode: "hardlink" } }));
184
+ const pubAvailable = publicRuntimeStatus(describeLocalRuntime({ runtimeDir, platform: "win32", arch: "x64" }));
185
+ assert.deepEqual(Object.keys(pubAvailable).sort(), EXPECTED);
186
+ assert.equal(pubAvailable.status, "available");
187
+ assert.equal(pubAvailable.payloadId, "transformers-4.2.0-node-win32-x64");
188
+ assert.equal(pubAvailable.procedure, "adopted");
189
+ assert.equal(pubAvailable.materialize, "hardlink");
190
+ // 整份投影里不能出现本机路径的任何形态。
191
+ const text = JSON.stringify(pubAvailable);
192
+ assert.equal(text.includes(runtimeDir), false);
193
+ assert.equal(text.includes(runtimeDir.replace(/\\/g, "/")), false);
194
+ });
195
+
196
+ test("describeLocalRuntime:可用时报出 payload 与来源,且不假装验过", () => {
197
+ const runtimeDir = emptyRuntime();
198
+ const dir = makePayload(runtimeDir);
199
+ // 收编来的 payload 会带一份清单,验证来源/物化方式确实被带出来。
200
+ writeFileSync(
201
+ join(dir, "mneme-runtime.json"),
202
+ JSON.stringify({ procedure: "adopted", materialize: { mode: "hardlink" } })
203
+ );
204
+ const report = describeLocalRuntime({ runtimeDir, platform: "win32", arch: "x64" });
205
+ assert.equal(report.status, "available");
206
+ assert.equal(report.payloadId, "transformers-4.2.0-node-win32-x64");
207
+ assert.equal(report.version, "4.2.0");
208
+ assert.equal(report.procedure, "adopted");
209
+ assert.equal(report.materialize, "hardlink");
210
+ // 结构检查是 GET 端点能负担的;功能验证要真加载原生模块跑推理,状态探针不做 ——
211
+ // 如实说「不知道」,而不是把「文件都在」说成「验过了」。
212
+ assert.equal(report.functional, "unknown");
213
+ assert.equal(report.integrity, "unverified");
214
+ assert.match(report.hint, /mneme-runtime\.mjs/);
215
+ });
216
+
217
+ test("describeLocalRuntime:没有 payload 时报 missing,而不是报坏掉", () => {
218
+ const report = describeLocalRuntime({ runtimeDir: emptyRuntime(), platform: "win32", arch: "x64" });
219
+ assert.equal(report.status, "missing");
220
+ });
221
+
222
+ test("describeLocalRuntime:有目录但缺件时报 broken 并点名缺了什么", () => {
223
+ const runtimeDir = emptyRuntime();
224
+ makePayload(runtimeDir, { withEntry: false });
225
+ const report = describeLocalRuntime({ runtimeDir, platform: "win32", arch: "x64" });
226
+ assert.equal(report.status, "broken");
227
+ assert.deepEqual(report.missing, [TRANSFORMERS_ENTRY]);
228
+ });
229
+
230
+ test("describeLocalRuntime:空 runtimeDir 走默认目录,不能把空串当相对路径", () => {
231
+ // 配置项 runtimeDir 的默认值就是空串。原样传下去 readdirSync("") 会失败,
232
+ // 「没配」会被误报成「坏了」—— 这条守的就是它。
233
+ const report = describeLocalRuntime({ runtimeDir: " ", platform: "win32", arch: "x64" });
234
+ assert.equal(report.runtimeDir, defaultRuntimeDir());
235
+ assert.ok(isAbsolute(report.runtimeDir));
236
+ assert.notEqual(report.status, "unreadable");
237
+ });
@@ -0,0 +1,158 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { readFileSync } from "node:fs";
4
+ import { join } from "node:path";
5
+ import { fileURLToPath } from "node:url";
6
+ import {
7
+ COVERED_PLATFORMS,
8
+ build,
9
+ closureFromLockfile,
10
+ isExcluded,
11
+ nameOfPath,
12
+ packagesForPlatform,
13
+ relOfPath,
14
+ resolveCandidates
15
+ } from "../scripts/build-runtime-manifest.mjs";
16
+ import { REQUIRED_PACKAGES, payloadId } from "../src/runtime/layout.js";
17
+
18
+ // PR-C 的清单层,守四件事:
19
+ // ① 剔除规则按**子树**生效 —— 只按包名会漏掉 onnxruntime-web/node_modules/... 这类嵌套条目,
20
+ // 而那个位置根本不会被取回来(第一版真踩过)。
21
+ // ② 从 lockfile 解析依赖的走位正确(Node 的向上查找语义;嵌套重复版本就靠它)。
22
+ // ③ 清单**平台无关**:六个常见平台都能过滤出完整的必需包,并各拿到自己的平台二进制。
23
+ // 这是「mac / linux 用户不会卡住」的唯一结构性保证 —— 我在本机没法真跑那些平台,
24
+ // 至少要钉住「过滤之后是完整的」。
25
+ // ④ 已提交的清单必须就是生成器的输出:它随包发布,漂移了就等于发了一份错的哈希。
26
+
27
+ const ROOT = fileURLToPath(new URL("..", import.meta.url));
28
+
29
+ test("isExcluded:按包名与子树一起判定,嵌套条目不能漏", () => {
30
+ assert.equal(isExcluded({ name: "onnxruntime-web", rel: "onnxruntime-web" }), true);
31
+ // 这一条就是漏网的形态:包名不是被剔除的那个,但位置在被剔除包的子树里。
32
+ assert.equal(
33
+ isExcluded({ name: "onnxruntime-common", rel: "onnxruntime-web/node_modules/onnxruntime-common" }),
34
+ true
35
+ );
36
+ // 同名但位于别处(顶层那份)必须保留。
37
+ assert.equal(isExcluded({ name: "onnxruntime-common", rel: "onnxruntime-common" }), false);
38
+ assert.equal(isExcluded({ name: "onnxruntime-node", rel: "onnxruntime-node" }), false);
39
+ });
40
+
41
+ test("nameOfPath / relOfPath:取最后一段 node_modules 之后的部分", () => {
42
+ assert.equal(nameOfPath("node_modules/@huggingface/transformers"), "@huggingface/transformers");
43
+ assert.equal(nameOfPath("node_modules/a/node_modules/b"), "b");
44
+ assert.equal(relOfPath("node_modules/a/node_modules/b"), "a/node_modules/b");
45
+ assert.equal(relOfPath("node_modules/sharp"), "sharp");
46
+ });
47
+
48
+ test("resolveCandidates:按 Node 语义由近到远,最后兜底到根部", () => {
49
+ assert.deepEqual(resolveCandidates("node_modules/a", "x"), ["node_modules/a/node_modules/x", "node_modules/x"]);
50
+ assert.deepEqual(resolveCandidates("node_modules/a/node_modules/b", "x"), [
51
+ "node_modules/a/node_modules/b/node_modules/x",
52
+ "node_modules/a/node_modules/x",
53
+ "node_modules/x"
54
+ ]);
55
+ });
56
+
57
+ test("closureFromLockfile:被剔除包的(孤儿)依赖不会再进闭包", () => {
58
+ // 这正是第一版的真实缺陷:按包名剔除了 onnxruntime-web,却把它那 16 个传递依赖留在了清单里。
59
+ const lock = {
60
+ packages: {
61
+ "node_modules/@huggingface/transformers": {
62
+ version: "4.2.0",
63
+ integrity: "sha512-T",
64
+ dependencies: { dep: "^1.0.0" }
65
+ },
66
+ "node_modules/dep": { version: "1.0.0", integrity: "sha512-D", dependencies: { "onnxruntime-web": "^1.0.0" } },
67
+ "node_modules/onnxruntime-web": {
68
+ version: "1.0.0",
69
+ integrity: "sha512-W",
70
+ dependencies: { orphan: "^1.0.0", nested: "^1.0.0" }
71
+ },
72
+ "node_modules/onnxruntime-web/node_modules/nested": { version: "1.0.0", integrity: "sha512-N" },
73
+ "node_modules/orphan": { version: "1.0.0", integrity: "sha512-O" }
74
+ }
75
+ };
76
+ const { packages, missing } = closureFromLockfile(lock);
77
+ assert.deepEqual(packages.map((pkg) => pkg.rel), ["@huggingface/transformers", "dep"]);
78
+ assert.deepEqual(missing, [], "被剔除的包不该算成「解析不到」");
79
+ });
80
+
81
+ test("closureFromLockfile:解析不到的依赖如实记下来,不静默少一个包", () => {
82
+ const lock = {
83
+ packages: {
84
+ "node_modules/@huggingface/transformers": {
85
+ version: "4.2.0",
86
+ integrity: "sha512-T",
87
+ dependencies: { "does-not-exist": "^1.0.0" }
88
+ }
89
+ }
90
+ };
91
+ const { packages, missing } = closureFromLockfile(lock);
92
+ assert.deepEqual(packages.map((pkg) => pkg.rel), ["@huggingface/transformers"]);
93
+ assert.equal(missing.length, 1);
94
+ assert.match(missing[0], /does-not-exist/);
95
+ });
96
+
97
+ test("build:平台无关,六个常见平台都能过滤出完整的必需包与各自的平台二进制", () => {
98
+ const built = build();
99
+ assert.equal(built.manifestVersion, 2);
100
+ assert.equal(built.entry, "@huggingface/transformers");
101
+ assert.match(built.transformersVersion, /^\d+\.\d+\.\d+/);
102
+ assert.ok(built.packages.length > 40, `闭包太小:${built.packages.length}`);
103
+
104
+ for (const pkg of built.packages) {
105
+ assert.match(pkg.integrity, /^sha512-/, `${pkg.rel} 缺 sha512`);
106
+ assert.match(pkg.tarball, /^https:\/\//, `${pkg.rel} 的地址不可取`);
107
+ assert.equal(isExcluded(pkg), false, `${pkg.rel} 不该出现在清单里`);
108
+ }
109
+ const rels = built.packages.map((pkg) => pkg.rel);
110
+ assert.equal(new Set(rels).size, rels.length, "rel 有重复,落盘会互相覆盖");
111
+
112
+ for (const [platform, arch] of COVERED_PLATFORMS) {
113
+ const set = packagesForPlatform(built, platform, arch);
114
+ for (const required of REQUIRED_PACKAGES) {
115
+ assert.ok(
116
+ set.some((pkg) => pkg.rel === required),
117
+ `${platform}-${arch} 过滤后缺必需包 ${required}`
118
+ );
119
+ }
120
+ // 各平台必须拿到**自己**的 sharp 原生包,且不能混进别的平台的(否则下载器会拉错二进制)。
121
+ const native = set.filter((pkg) => pkg.name.startsWith("@img/sharp-"));
122
+ assert.ok(native.length > 0, `${platform}-${arch} 没有 sharp 平台包`);
123
+ for (const pkg of native) {
124
+ assert.ok((pkg.os ?? []).includes(platform), `${platform}-${arch} 混进了 ${pkg.rel}`);
125
+ }
126
+ // payloadId 由「版本 + 平台」算出来(v2 清单里不再存它)。
127
+ assert.equal(
128
+ payloadId({ version: built.transformersVersion, platform, arch }),
129
+ `transformers-4.2.0-node-${platform}-${arch}`
130
+ );
131
+ }
132
+ });
133
+
134
+ test("libc 过滤:确认 glibc 时剔掉 musl 变体,拿不到证据时一个都不剔", () => {
135
+ const built = build();
136
+ const all = packagesForPlatform(built, "linux", "x64");
137
+ const onGlibc = packagesForPlatform(built, "linux", "x64", "glibc");
138
+ const dropped = all.filter((pkg) => !onGlibc.includes(pkg));
139
+ // linux-x64 上那两套 musl 变体(sharp 与 libvips)就是这条过滤的全部收益,十几 MB。
140
+ assert.ok(dropped.length >= 2, `应当剔掉 musl 变体,实际剔了 ${dropped.length}`);
141
+ for (const pkg of dropped) assert.deepEqual(pkg.libc, ["musl"], `${pkg.rel} 不该被剔`);
142
+ // 必需包绝不能因 libc 被剔 —— 否则下载会在「缺必需包」处直接失败,用户拿不到出路。
143
+ for (const required of REQUIRED_PACKAGES) {
144
+ assert.ok(onGlibc.some((pkg) => pkg.rel === required), `确认 glibc 后缺必需包 ${required}`);
145
+ }
146
+ // 没有证据 = 与过滤前完全一致(默认路径必须是它)。
147
+ assert.deepEqual(packagesForPlatform(built, "linux", "x64", null), all);
148
+ // 别的平台没有 libc 变体,给不给证据都一样。
149
+ assert.deepEqual(
150
+ packagesForPlatform(built, "darwin", "arm64", "glibc"),
151
+ packagesForPlatform(built, "darwin", "arm64")
152
+ );
153
+ });
154
+
155
+ test("已提交的 runtime-manifest.json 就是生成器的输出(漂移 = 发布错的哈希)", () => {
156
+ const committed = JSON.parse(readFileSync(join(ROOT, "runtime-manifest.json"), "utf8"));
157
+ assert.deepEqual(committed, build(), "清单与 package-lock.json 不一致,请重跑 scripts/build-runtime-manifest.mjs");
158
+ });
@@ -0,0 +1,101 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { tmpdir } from "node:os";
4
+ import { join, sep } from "node:path";
5
+ import { pathToFileURL } from "node:url";
6
+ import { adoptHostRuntime, hostModulesDir, provisionRuntime } from "../src/runtime/provision.js";
7
+ import { makeEmptyModules, makeSourceModules } from "./helpers/runtime-source.js";
8
+
9
+ // PR-C:面板「一键收编」的服务层。守两件事:
10
+ // ① 源目录由插件自身路径推出 —— 面板不传参,也不把「从任意目录收编」变成对外能力;
11
+ // ② ok 必须同时看「结构完整」与「闭包无缺口」—— 与 CLI 退出码同一条判据,
12
+ // 否则面板会把「入口一 import 就炸」的收编显示成成功。
13
+
14
+ test("hostModulesDir:从插件自身位置往上三级就是宿主 node_modules", () => {
15
+ const fake = pathToFileURL(
16
+ join(tmpdir(), "proj", "node_modules", "@modusensus", "dsh-mneme", "lib", "api.js")
17
+ ).href;
18
+ assert.equal(hostModulesDir(fake), join(tmpdir(), "proj", "node_modules"));
19
+ });
20
+
21
+ test("adoptHostRuntime:源里没有入口包时返回失败结论,不抛异常(曾经抛 TypeError)", () => {
22
+ const src = makeEmptyModules();
23
+ const result = adoptHostRuntime({ hostModulesDir: src.nm, runtimeDir: src.runtimeDir });
24
+ assert.equal(result.ok, false);
25
+ assert.equal(result.status, "failed");
26
+ assert.match(result.reason, /入口包/);
27
+ });
28
+
29
+ test("adoptHostRuntime:闭包缺件必须 ok:false(结构通过不等于可用)", () => {
30
+ const src = makeSourceModules({ withMissingDep: true });
31
+ const result = adoptHostRuntime({ hostModulesDir: src.nm, runtimeDir: src.runtimeDir });
32
+ assert.equal(result.ok, false, JSON.stringify(result));
33
+ assert.equal(result.status, "incomplete");
34
+ assert.deepEqual(result.gaps, ["definitely-not-installed-pkg"]);
35
+ // 结构检查本身是通过的 —— 缺口只有闭包计划知道,这正是要守的那条缝。
36
+ assert.deepEqual(result.missing, []);
37
+ assert.equal(result.packages, 3);
38
+ });
39
+
40
+ test("adoptHostRuntime:闭包完整时报出结论与规模", () => {
41
+ const src = makeSourceModules();
42
+ const result = adoptHostRuntime({ hostModulesDir: src.nm, runtimeDir: src.runtimeDir });
43
+ assert.equal(result.ok, true, JSON.stringify(result));
44
+ assert.equal(result.status, "adopted");
45
+ assert.match(result.payloadId, /^transformers-4\.2\.0-node-/);
46
+ assert.equal(result.gaps.length, 0);
47
+ assert.equal(result.packages, 3);
48
+ assert.ok(result.files > 0 && result.bytes > 0);
49
+ assert.ok(["hardlink", "copy", "mixed"].includes(result.materialize), result.materialize);
50
+ });
51
+
52
+ test("adoptHostRuntime:目标已存在默认不覆盖,带 overwrite 才重建(面板据此区分「缺」与「坏」)", () => {
53
+ const src = makeSourceModules();
54
+ assert.equal(adoptHostRuntime({ hostModulesDir: src.nm, runtimeDir: src.runtimeDir }).ok, true);
55
+
56
+ const again = adoptHostRuntime({ hostModulesDir: src.nm, runtimeDir: src.runtimeDir });
57
+ assert.equal(again.ok, false);
58
+ assert.match(again.reason, /目标已存在/);
59
+
60
+ const forced = adoptHostRuntime({ hostModulesDir: src.nm, runtimeDir: src.runtimeDir, overwrite: true });
61
+ assert.equal(forced.ok, true, JSON.stringify(forced));
62
+ });
63
+
64
+ test("provisionRuntime:本机有可收编的源时走收编,不联网", async () => {
65
+ const src = makeSourceModules();
66
+ const result = await provisionRuntime({
67
+ hostModulesDir: src.nm,
68
+ runtimeDir: src.runtimeDir,
69
+ // 一旦它去下载就会命中这个必抛的 fetch —— 从而证明这次确实没有联网。
70
+ fetchImpl: () => {
71
+ throw new Error("不该联网");
72
+ }
73
+ });
74
+ assert.equal(result.ok, true, result.reason);
75
+ assert.equal(result.strategy, "adopt", "有源时应当走收编而不是下载");
76
+ assert.ok(result.packages > 0);
77
+ });
78
+
79
+ test("adoptHostRuntime:收编结果不完整时也必须带 reason(不能是 undefined)", () => {
80
+ const src = makeSourceModules({ withMissingDep: true });
81
+ const result = adoptHostRuntime({ hostModulesDir: src.nm, runtimeDir: src.runtimeDir });
82
+ assert.equal(result.ok, false);
83
+ assert.equal(result.status, "incomplete");
84
+ // 评审指出的正是这条:缺 reason 时,给用户的话会变成「收编失败:undefined」。
85
+ assert.match(result.reason, /收编结果不完整/);
86
+ assert.match(result.reason, /缺依赖/);
87
+ });
88
+
89
+ test("provisionRuntime:同一个目录的不同写法必须共用一把锁(否则仍会被并发写)", async () => {
90
+ const src = makeSourceModules();
91
+ // 尾部分隔符是最常见的等价写法(配置里手填、或别处 join 出来的形态);
92
+ // 归一化之前它与 src.runtimeDir 是两个键,于是第二次会重跑一遍收编,
93
+ // 撞上「目标已存在」—— 用户看到的是「取件失败」,而不是接上正在进行的那次。
94
+ const sameDirOtherSpelling = src.runtimeDir + sep;
95
+ const [a, b] = await Promise.all([
96
+ provisionRuntime({ hostModulesDir: src.nm, runtimeDir: src.runtimeDir }),
97
+ provisionRuntime({ hostModulesDir: src.nm, runtimeDir: sameDirOtherSpelling })
98
+ ]);
99
+ assert.equal(a.ok, true, a.reason);
100
+ assert.equal(a, b, "等价路径应当复用同一次取件(同一个结论对象)");
101
+ });
@@ -0,0 +1,82 @@
1
+ import test from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { gzipSync } from "node:zlib";
4
+ import { sha512Base64, stripPackagePrefix, verifyIntegrity, walkTar, walkTgz } from "../src/runtime/tarball.js";
5
+ import { tarFile, tarHeader, tarMeta, tarPax } from "./helpers/tar-builder.js";
6
+
7
+ // PR-C 下载通道的归档读取层。这里是整条链里最该被单独守住的一块:它读的是别人产出的字节,
8
+ // 一旦读错,我们就会把「缺文件/文件截断」的运行时当成完整的搬进 payload,而那种错误
9
+ // 要到第一次 import 原生模块时才现形。
10
+ //
11
+ // 合成归档在测试里现造(不引 tar 库),另外单独用 npm pack 产出的真实 .tgz 做过一次交叉核对
12
+ // (见 PR 描述里的验证记录)——合成归档只能证明读取器与规范一致,真实产物才能证明它与 npm 一致。
13
+
14
+ const END = [Buffer.alloc(512), Buffer.alloc(512)];
15
+
16
+ function collect(buffer) {
17
+ const seen = [];
18
+ const stats = walkTar(buffer, (entry) => seen.push([entry.path, entry.data.toString("utf8")]));
19
+ return { seen, stats };
20
+ }
21
+
22
+ test("walkTar:普通文件、目录、prefix 长路径、符号链接跳过、归档结束块都能处理", () => {
23
+ const archive = Buffer.concat([
24
+ ...tarFile("package/package.json", '{"name":"x"}\n'),
25
+ ...tarMeta("package/lib", "5"),
26
+ ...tarFile("api.js", "export const x = 1;\n", { prefix: "package/a/very/long/nested/path" }),
27
+ ...tarMeta("package/link", "2"),
28
+ ...END
29
+ ]);
30
+
31
+ const { seen, stats } = collect(archive);
32
+ assert.deepEqual(seen, [
33
+ ["package/package.json", '{"name":"x"}\n'],
34
+ ["package/a/very/long/nested/path/api.js", "export const x = 1;\n"]
35
+ ]);
36
+ assert.equal(stats.files, 2);
37
+ assert.equal(stats.bytes, Buffer.byteLength('{"name":"x"}\n') + Buffer.byteLength("export const x = 1;\n"));
38
+ // 符号链接不能假装搬过来了 —— 如实记下,让上层去判断要不要失败。
39
+ assert.equal(stats.skipped.length, 1);
40
+ assert.match(stats.skipped[0], /package\/link/);
41
+ });
42
+
43
+ test("walkTar:pax 的 path 覆盖下一条目(超过 ustar 字段长度的深层路径靠它)", () => {
44
+ const long = `package/${"d".repeat(120)}/${"e".repeat(120)}/file.js`;
45
+ const archive = Buffer.concat([...tarPax(long), ...tarFile("truncated-name", "ok\n"), ...END]);
46
+ const { seen } = collect(archive);
47
+ assert.deepEqual(seen.map(([p]) => p), [long]);
48
+ });
49
+
50
+ test("walkTar:没有结束块也能读完(registry 产物有,但别依赖它)", () => {
51
+ const { seen } = collect(Buffer.concat([...tarFile("package/a.txt", "a\n")]));
52
+ assert.deepEqual(seen, [["package/a.txt", "a\n"]]);
53
+ });
54
+
55
+ test("walkTgz:gzip 包装的归档走同一条路", () => {
56
+ const inner = Buffer.concat([...tarFile("package/package.json", "{}\n"), ...END]);
57
+ // 未压缩那份用 walkTar 读,压缩那份用 walkTgz 读,两者结论必须一致。
58
+ const plain = collect(inner).seen;
59
+ const viaGzip = [];
60
+ const stats = walkTgz(gzipSync(inner), (entry) => viaGzip.push([entry.path, entry.data.toString("utf8")]));
61
+ assert.deepEqual(viaGzip, plain);
62
+ assert.equal(stats.files, 1);
63
+ });
64
+
65
+ test("stripPackagePrefix:只去 npm 那一层前缀", () => {
66
+ assert.equal(stripPackagePrefix("package/lib/index.js"), "lib/index.js");
67
+ assert.equal(stripPackagePrefix("package"), "package");
68
+ assert.equal(stripPackagePrefix("lib/index.js"), "lib/index.js");
69
+ });
70
+
71
+ test("verifyIntegrity:只认 sha512,且不匹配就是不匹配", () => {
72
+ const good = Buffer.from("hello tarball");
73
+ const integrity = `sha512-${sha512Base64(good)}`;
74
+ assert.equal(verifyIntegrity(good, integrity), true);
75
+
76
+ const tampered = Buffer.from("hello tarbal!");
77
+ assert.equal(verifyIntegrity(tampered, integrity), false, "差一个字节也必须失败");
78
+ // 不认识的算法不能放行:那等于把「没校验」说成「校验通过」。
79
+ assert.equal(verifyIntegrity(good, "md5-YWJj"), false);
80
+ assert.equal(verifyIntegrity(good, ""), false);
81
+ assert.equal(verifyIntegrity(good, "sha512-"), false);
82
+ });