@mulmoclaude/core 7.3.1 → 7.5.0

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 (57) hide show
  1. package/README.md +1 -1
  2. package/dist/{root-CqxPNSyK.js → atomic-C3NMg6-j.js} +2 -20
  3. package/dist/atomic-C3NMg6-j.js.map +1 -0
  4. package/dist/{root-9lRFeXbm.cjs → atomic-cqafMWEI.cjs} +1 -25
  5. package/dist/atomic-cqafMWEI.cjs.map +1 -0
  6. package/dist/collection/registry/server/index.cjs +4 -4
  7. package/dist/collection/registry/server/index.cjs.map +1 -1
  8. package/dist/collection/registry/server/index.js +3 -3
  9. package/dist/collection/server/index.cjs +3 -3
  10. package/dist/collection/server/index.js +3 -3
  11. package/dist/collection-watchers/index.cjs +3 -3
  12. package/dist/collection-watchers/index.js +3 -3
  13. package/dist/{discovery-RyuhNKjx.js → discovery-CImpaG95.js} +3 -2
  14. package/dist/{discovery-RyuhNKjx.js.map → discovery-CImpaG95.js.map} +1 -1
  15. package/dist/{discovery-DxmMcpFo.cjs → discovery-CY4pvgo9.cjs} +4 -3
  16. package/dist/{discovery-DxmMcpFo.cjs.map → discovery-CY4pvgo9.cjs.map} +1 -1
  17. package/dist/feeds/server/index.cjs +3 -3
  18. package/dist/feeds/server/index.js +3 -3
  19. package/dist/files/index.cjs +8 -13
  20. package/dist/files/index.cjs.map +1 -1
  21. package/dist/files/index.js +3 -8
  22. package/dist/files/index.js.map +1 -1
  23. package/dist/google/index.cjs +3 -3
  24. package/dist/google/index.cjs.map +1 -1
  25. package/dist/google/index.js +2 -2
  26. package/dist/json-BGdV2cz6.cjs +16 -0
  27. package/dist/json-BGdV2cz6.cjs.map +1 -0
  28. package/dist/json-BizOSThv.js +11 -0
  29. package/dist/json-BizOSThv.js.map +1 -0
  30. package/dist/root-Ccgd3H5S.cjs +29 -0
  31. package/dist/root-Ccgd3H5S.cjs.map +1 -0
  32. package/dist/root-s0MUUMQU.js +22 -0
  33. package/dist/root-s0MUUMQU.js.map +1 -0
  34. package/dist/runtime-plugins/containment.d.ts +5 -0
  35. package/dist/runtime-plugins/download.d.ts +12 -0
  36. package/dist/runtime-plugins/extract.d.ts +19 -0
  37. package/dist/runtime-plugins/fetchPackage.d.ts +52 -0
  38. package/dist/runtime-plugins/index.cjs +1060 -0
  39. package/dist/runtime-plugins/index.cjs.map +1 -0
  40. package/dist/runtime-plugins/index.d.ts +11 -0
  41. package/dist/runtime-plugins/index.js +1020 -0
  42. package/dist/runtime-plugins/index.js.map +1 -0
  43. package/dist/runtime-plugins/inspect.d.ts +18 -0
  44. package/dist/runtime-plugins/install.d.ts +48 -0
  45. package/dist/runtime-plugins/installSource.d.ts +34 -0
  46. package/dist/runtime-plugins/ledger.d.ts +17 -0
  47. package/dist/runtime-plugins/ledgerWrite.d.ts +17 -0
  48. package/dist/runtime-plugins/load.d.ts +77 -0
  49. package/dist/runtime-plugins/npmBuiltinNames.d.ts +1 -0
  50. package/dist/runtime-plugins/packageJson.d.ts +29 -0
  51. package/dist/{server-xdXBsiba.js → server-B5TZjZN9.js} +3 -3
  52. package/dist/{server-xdXBsiba.js.map → server-B5TZjZN9.js.map} +1 -1
  53. package/dist/{server-ZKTtI8_W.cjs → server-BXtSbL-b.cjs} +6 -6
  54. package/dist/{server-ZKTtI8_W.cjs.map → server-BXtSbL-b.cjs.map} +1 -1
  55. package/package.json +7 -1
  56. package/dist/root-9lRFeXbm.cjs.map +0 -1
  57. package/dist/root-CqxPNSyK.js.map +0 -1
@@ -0,0 +1,1020 @@
1
+ import { c as isRecord, i as hasStringProp } from "../dist-BmO4oSQy.js";
2
+ import { n as isWithinRoot, r as realpathSyncOrNull, t as isInsideRoot } from "../containment-D_vAa6eT.js";
3
+ import { t as writeJsonAtomic } from "../json-BizOSThv.js";
4
+ import { n as writeFileAtomic } from "../atomic-C3NMg6-j.js";
5
+ import { isPluginFactory } from "gui-chat-protocol";
6
+ import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
7
+ import path from "node:path";
8
+ import { createHash } from "node:crypto";
9
+ import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
10
+ import { execFileSync } from "node:child_process";
11
+ import { pathToFileURL } from "node:url";
12
+ import { createGunzip } from "node:zlib";
13
+ // src/runtime-plugins/ledger.ts
14
+ var hasValidSource = (value) => !Object.hasOwn(value, "source") || typeof value.source === "string";
15
+ var isLedgerEntry = (value) => hasStringProp(value, "name") && hasStringProp(value, "version") && hasStringProp(value, "tgz") && hasStringProp(value, "installedAt") && hasValidSource(value);
16
+ /** The well-formed entries of a parsed ledger; anything that is not an array reads as empty. */
17
+ var parseLedger = (raw) => {
18
+ if (!Array.isArray(raw)) return [];
19
+ return raw.filter(isLedgerEntry);
20
+ };
21
+ // src/runtime-plugins/packageJson.ts
22
+ var optionalString = (value) => typeof value === "string" ? value : void 0;
23
+ /** Rebuild the fields the loader reads from arbitrary parsed JSON.
24
+ * Field-by-field rather than a predicate, so a plugin shipping a
25
+ * non-string `main` can't reach `path.join` as if it were one.
26
+ * Returns null when the parsed value isn't an object at all. */
27
+ function toPackageJson(value) {
28
+ if (!isRecord(value)) return null;
29
+ return {
30
+ name: optionalString(value.name),
31
+ version: optionalString(value.version),
32
+ exports: value.exports,
33
+ main: optionalString(value.main),
34
+ module: optionalString(value.module)
35
+ };
36
+ }
37
+ /** Resolve the entry-point path from a plugin's `package.json`. Covers
38
+ * the four legal `exports` shapes per the Node.js spec, then falls
39
+ * through to `module` / `main` for legacy packages.
40
+ *
41
+ * Legal `exports` forms (Node.js docs):
42
+ * 1. String sugar: `"exports": "./index.js"`
43
+ * 2. Conditional root: `"exports": { "import": "./esm.js", … }`
44
+ * 3. Subpath map: `"exports": { ".": "./index.js", "./util": "./util.js", … }`
45
+ * 4. Subpath + cond.: `"exports": { ".": { "import": "./esm.js", "require": "./cjs.js" } }`
46
+ *
47
+ * Earlier the loader only matched form (4) and fell straight through
48
+ * to `module` / `main`. Real npm packages using forms (1)-(3) failed
49
+ * to load (#1077 review). */
50
+ function resolveEntrySpecifier(pkg) {
51
+ const fromExports = resolveExportsField(pkg.exports);
52
+ if (fromExports) return fromExports;
53
+ if (typeof pkg.module === "string") return pkg.module;
54
+ if (typeof pkg.main === "string") return pkg.main;
55
+ return null;
56
+ }
57
+ function resolveExportsField(exportsField) {
58
+ const root = pickExportsTarget(exportsField);
59
+ if (root) return root;
60
+ if (isRecord(exportsField)) return pickExportsTarget(exportsField["."]);
61
+ return null;
62
+ }
63
+ /** Walk a Node.js `exports` value and return the first string entry
64
+ * point this ESM loader can use. Handles every legal target shape:
65
+ *
66
+ * - string: return it directly.
67
+ * - array: try each element in order; first resolvable wins.
68
+ * Per the spec arrays are a fallback chain — Node tries each
69
+ * until one resolves on disk. We don't probe disk here, so
70
+ * "first string-or-resolvable-condition" approximates that.
71
+ * - condition object: prefer `import` (ESM-specific), then
72
+ * `default` (universal fallback).
73
+ * - everything else (e.g. only `require`, only nested arrays of
74
+ * condition objects with no string targets): null. */
75
+ function pickExportsTarget(value) {
76
+ if (typeof value === "string") return value;
77
+ if (Array.isArray(value)) {
78
+ for (const entry of value) {
79
+ const resolved = pickExportsTarget(entry);
80
+ if (resolved) return resolved;
81
+ }
82
+ return null;
83
+ }
84
+ if (!isRecord(value)) return null;
85
+ const fromImport = pickExportsTarget(value.import);
86
+ if (fromImport) return fromImport;
87
+ return pickExportsTarget(value.default);
88
+ }
89
+ // src/runtime-plugins/extract.ts
90
+ /** Sentinel file written at the end of a successful extract. The
91
+ * loader uses its presence (not just `existsSync(cachePath)`) as the
92
+ * cache-validity check, so a partial extract (interrupted tar, ENOSPC
93
+ * half-write) is detected and re-extracted on the next boot instead
94
+ * of becoming a permanent broken state. */
95
+ var EXTRACT_MARKER = ".extract-complete";
96
+ function isCacheValid(cachePath) {
97
+ return existsSync(path.join(cachePath, EXTRACT_MARKER));
98
+ }
99
+ function writeMarker(markerPath) {
100
+ rmSync(markerPath, {
101
+ recursive: true,
102
+ force: true
103
+ });
104
+ writeFileSync(markerPath, "", { flag: "wx" });
105
+ }
106
+ /** Run `tar xzf` to extract a tgz into the version-keyed cache slot.
107
+ * `--strip-components=1` drops the `package/` prefix that npm packs
108
+ * add. `execFileSync` (not `execSync`) so paths bypass shell parsing
109
+ * and never trip on metacharacters in workspace paths. Synchronous
110
+ * because boot is single-threaded and the alternative (a stream
111
+ * pipeline) adds dependencies for no benefit.
112
+ *
113
+ * On failure, the partial directory is removed so the next boot
114
+ * re-extracts cleanly (no sticky broken state). The completion
115
+ * marker is written ONLY after tar exits 0 — readers should test
116
+ * `isCacheValid()`, not `existsSync(cachePath)`. */
117
+ function extractTgz(tgzAbs, destDir) {
118
+ if (existsSync(destDir)) rmSync(destDir, {
119
+ recursive: true,
120
+ force: true
121
+ });
122
+ mkdirSync(destDir, { recursive: true });
123
+ try {
124
+ execFileSync("tar", [
125
+ "-xzf",
126
+ tgzAbs,
127
+ "-C",
128
+ destDir,
129
+ "--strip-components=1"
130
+ ], { stdio: "pipe" });
131
+ writeMarker(path.join(destDir, EXTRACT_MARKER));
132
+ } catch (err) {
133
+ try {
134
+ rmSync(destDir, {
135
+ recursive: true,
136
+ force: true
137
+ });
138
+ } catch {}
139
+ throw err;
140
+ }
141
+ }
142
+ // src/runtime-plugins/containment.ts
143
+ /** True when `file` exists and, with every link followed, is inside `root`. */
144
+ function resolvesInside(file, root) {
145
+ const rootReal = realpathSyncOrNull(root);
146
+ const fileReal = realpathSyncOrNull(file);
147
+ return rootReal !== null && fileReal !== null && isInsideRoot(rootReal, fileReal);
148
+ }
149
+ /** The first symlink under `root` that leads outside it (or nowhere), relative to `root`; null when
150
+ * every link stays inside. */
151
+ function linkLeadingOut(root, dir = root) {
152
+ for (const item of readdirSync(dir, { withFileTypes: true })) {
153
+ const full = path.join(dir, item.name);
154
+ if (item.isSymbolicLink() && !resolvesInside(full, root)) return path.relative(root, full);
155
+ const nested = item.isDirectory() ? linkLeadingOut(root, full) : null;
156
+ if (nested !== null) return nested;
157
+ }
158
+ return null;
159
+ }
160
+ // src/runtime-plugins/load.ts
161
+ var isToolDefinition = (value) => {
162
+ if (!isRecord(value)) return false;
163
+ return typeof value.name === "string" && typeof value.description === "string";
164
+ };
165
+ function readPackageJson(cachePath, log) {
166
+ const pkgPath = path.join(cachePath, "package.json");
167
+ try {
168
+ const pkg = toPackageJson(JSON.parse(readFileSync(pkgPath, "utf-8")));
169
+ if (!pkg) log.warn("package.json is not an object — skipping", { path: pkgPath });
170
+ return pkg;
171
+ } catch (err) {
172
+ log.warn("package.json read/parse failed", {
173
+ path: pkgPath,
174
+ error: String(err)
175
+ });
176
+ return null;
177
+ }
178
+ }
179
+ /** Two carrier shapes (#1110 backward compatibility):
180
+ *
181
+ * 1. **Factory** (`export default definePlugin(setup)`) — `mod.default`
182
+ * is a function. Call it with the plugin's runtime; the return
183
+ * value carries `TOOL_DEFINITION` and the handler keyed by
184
+ * `TOOL_DEFINITION.name`. Closure over runtime gives the handler
185
+ * access to scoped pubsub / files / log without per-call context
186
+ * threading.
187
+ * 2. **Legacy** (`export const TOOL_DEFINITION = ...; export async
188
+ * function <name>(context, args) ...`) — `mod.TOOL_DEFINITION` and
189
+ * `mod[<name>]` directly. Continues to work; existing
190
+ * @gui-chat-plugin packages don't need to migrate.
191
+ */
192
+ function resolveCarrier(name, mod, deps) {
193
+ const defaultExport = mod.default;
194
+ if (isPluginFactory(defaultExport)) return {
195
+ carrier: defaultExport(deps.runtimeFor(name)),
196
+ usingFactory: true
197
+ };
198
+ return {
199
+ carrier: mod,
200
+ usingFactory: false
201
+ };
202
+ }
203
+ /** Callability is the whole of what a dynamically imported export can be
204
+ * proved to have, so parameters and result stay `unknown` — the loader
205
+ * never inspects either. */
206
+ var isPluginHandler = (value) => typeof value === "function";
207
+ /** Pull the executable from a carrier. Factory-shape handlers take
208
+ * `(args)` only (runtime is closed over) so we wrap to discard the
209
+ * legacy `context` arg the dispatch route passes. Legacy-shape
210
+ * handlers keep the `(context, args)` signature unchanged. Returns
211
+ * null when no function is exported under `definition.name` — the
212
+ * plugin still appears in `tools/list` but dispatch logs + 500s. */
213
+ function resolveExecute(carrier, definitionName, usingFactory) {
214
+ const handler = Object.hasOwn(carrier, definitionName) ? carrier[definitionName] : void 0;
215
+ if (!isPluginHandler(handler)) return null;
216
+ if (usingFactory) return (_context, args) => handler(args);
217
+ return handler;
218
+ }
219
+ /** Read the optional `OAUTH_CALLBACK_ALIAS` named export. Validated
220
+ * against `^[a-z0-9][a-z0-9-]{0,30}$` — short, lowercase,
221
+ * URL-friendly, can't be `..` or contain `/`. A bad alias is logged
222
+ * and ignored (the plugin still loads; just skips the OAuth route
223
+ * registration). */
224
+ var OAUTH_CALLBACK_ALIAS_RE = /^[a-z0-9][a-z0-9-]{0,30}$/;
225
+ function resolveOauthCallbackAlias(name, mod, log) {
226
+ const raw = mod.OAUTH_CALLBACK_ALIAS;
227
+ if (raw === void 0) return null;
228
+ if (typeof raw !== "string" || !OAUTH_CALLBACK_ALIAS_RE.test(raw)) {
229
+ log.warn("OAUTH_CALLBACK_ALIAS export is not a valid alias — ignoring", {
230
+ name,
231
+ raw: String(raw)
232
+ });
233
+ return null;
234
+ }
235
+ return raw;
236
+ }
237
+ /** Load a plugin from an already-extracted cache directory. Accepts
238
+ * paths explicitly, so tests don't need a real workspace. Returns
239
+ * null on any structural failure (missing package.json, missing
240
+ * TOOL_DEFINITION, broken import); the caller treats nulls as "skip". */
241
+ async function loadPluginFromCacheDir(name, version, cachePath, deps) {
242
+ const { log } = deps;
243
+ const pkg = readPackageJson(cachePath, log);
244
+ if (!pkg) return null;
245
+ const entrySpec = resolveEntrySpecifier(pkg);
246
+ if (!entrySpec) {
247
+ log.warn("no entry specifier in package.json — skipping", { name });
248
+ return null;
249
+ }
250
+ const entryAbs = path.join(cachePath, entrySpec);
251
+ if (!resolvesInside(entryAbs, cachePath)) {
252
+ log.warn("plugin entry is missing or leads outside its folder — skipping", {
253
+ name,
254
+ entrySpec
255
+ });
256
+ return null;
257
+ }
258
+ try {
259
+ const mod = await import(pathToFileURL(entryAbs).href);
260
+ if (!isRecord(mod)) {
261
+ log.warn("plugin module namespace is not an object — skipping", {
262
+ name,
263
+ entrySpec
264
+ });
265
+ return null;
266
+ }
267
+ const { carrier, usingFactory } = resolveCarrier(name, mod, deps);
268
+ const definition = carrier.TOOL_DEFINITION;
269
+ if (!isToolDefinition(definition)) {
270
+ log.warn("no TOOL_DEFINITION export — skipping", {
271
+ name,
272
+ entrySpec,
273
+ shape: usingFactory ? "factory" : "legacy"
274
+ });
275
+ return null;
276
+ }
277
+ const execute = resolveExecute(carrier, definition.name, usingFactory);
278
+ if (!execute) log.warn("no execute handler matching TOOL_DEFINITION.name — dispatch will fail", {
279
+ name,
280
+ expectedExport: definition.name,
281
+ shape: usingFactory ? "factory" : "legacy"
282
+ });
283
+ return {
284
+ name,
285
+ version,
286
+ cachePath,
287
+ definition,
288
+ execute,
289
+ oauthCallbackAlias: resolveOauthCallbackAlias(name, mod, log)
290
+ };
291
+ } catch (err) {
292
+ log.error("import failed", {
293
+ name,
294
+ entrySpec,
295
+ error: String(err)
296
+ });
297
+ return null;
298
+ }
299
+ }
300
+ /** Lexical anchor: confirm `candidate` resolves inside `base`. Catches
301
+ * malformed ledger entries (`name` containing `../../etc`) before we
302
+ * touch the disk. The asset route trusts registry membership, so a
303
+ * registered cachePath that escaped the base would expose arbitrary
304
+ * files via the unauthenticated GET — this check is the first
305
+ * line of defence; `loadPluginFromCacheDir` checks the entry's realpath
306
+ * after extraction as the symlink-escape backstop. */
307
+ function ensureInsideBase(candidate, base) {
308
+ return isWithinRoot(path.resolve(base), path.resolve(candidate));
309
+ }
310
+ /** Make a ledger entry's cache directory ready to load: both of its paths anchored inside their
311
+ * roots, its tgz present, and the tgz extracted unless a complete extract is already there.
312
+ * Returns the cache directory, or null (logged) when the entry cannot be loaded. */
313
+ function prepareLedgerEntry(entry, roots, log) {
314
+ const tgzAbs = path.join(roots.pluginsDir, entry.tgz);
315
+ const cachePath = path.join(roots.cacheDir, entry.name, entry.version);
316
+ if (!ensureInsideBase(tgzAbs, roots.pluginsDir)) {
317
+ log.warn("ledger entry tgz escapes plugins root — skipping", {
318
+ name: entry.name,
319
+ tgz: entry.tgz
320
+ });
321
+ return null;
322
+ }
323
+ if (!ensureInsideBase(cachePath, roots.cacheDir)) {
324
+ log.warn("ledger entry escapes plugin cache root — skipping", {
325
+ name: entry.name,
326
+ version: entry.version
327
+ });
328
+ return null;
329
+ }
330
+ if (!existsSync(tgzAbs)) {
331
+ log.warn("tgz missing — skipping", {
332
+ name: entry.name,
333
+ tgz: entry.tgz
334
+ });
335
+ return null;
336
+ }
337
+ if (!isCacheValid(cachePath)) try {
338
+ extractTgz(tgzAbs, cachePath);
339
+ log.info("extracted", {
340
+ name: entry.name,
341
+ version: entry.version
342
+ });
343
+ } catch (err) {
344
+ log.error("extract failed", {
345
+ name: entry.name,
346
+ error: String(err)
347
+ });
348
+ return null;
349
+ }
350
+ return cachePath;
351
+ }
352
+ // src/runtime-plugins/npmBuiltinNames.ts
353
+ var NPM_BUILTIN_MODULE_NAMES = /* @__PURE__ */ new Set([
354
+ "_http_agent",
355
+ "_http_client",
356
+ "_http_common",
357
+ "_http_incoming",
358
+ "_http_outgoing",
359
+ "_http_server",
360
+ "_stream_duplex",
361
+ "_stream_passthrough",
362
+ "_stream_readable",
363
+ "_stream_transform",
364
+ "_stream_wrap",
365
+ "_stream_writable",
366
+ "_tls_common",
367
+ "_tls_wrap",
368
+ "assert",
369
+ "assert/strict",
370
+ "async_hooks",
371
+ "buffer",
372
+ "child_process",
373
+ "cluster",
374
+ "console",
375
+ "constants",
376
+ "crypto",
377
+ "dgram",
378
+ "diagnostics_channel",
379
+ "dns",
380
+ "dns/promises",
381
+ "domain",
382
+ "events",
383
+ "fs",
384
+ "fs/promises",
385
+ "http",
386
+ "http2",
387
+ "https",
388
+ "inspector",
389
+ "inspector/promises",
390
+ "module",
391
+ "net",
392
+ "os",
393
+ "path",
394
+ "path/posix",
395
+ "path/win32",
396
+ "perf_hooks",
397
+ "process",
398
+ "punycode",
399
+ "querystring",
400
+ "readline",
401
+ "readline/promises",
402
+ "repl",
403
+ "stream",
404
+ "stream/consumers",
405
+ "stream/promises",
406
+ "stream/web",
407
+ "string_decoder",
408
+ "sys",
409
+ "timers",
410
+ "timers/promises",
411
+ "tls",
412
+ "trace_events",
413
+ "tty",
414
+ "url",
415
+ "util",
416
+ "util/types",
417
+ "v8",
418
+ "vm",
419
+ "wasi",
420
+ "worker_threads",
421
+ "zlib",
422
+ "node:sea",
423
+ "node:sqlite",
424
+ "node:test",
425
+ "node:test/reporters"
426
+ ]);
427
+ // src/runtime-plugins/installSource.ts
428
+ var MAX_NPM_NAME_LENGTH = 214;
429
+ var MAX_TAG_LENGTH = 255;
430
+ var NPM_UNSCOPED_NAME = /^[a-z0-9][a-z0-9\-._]*$/;
431
+ var NPM_SCOPED_SEGMENT = /^[a-z0-9\-_][a-z0-9\-._]*$/;
432
+ var NUMERIC_IDENTIFIER = /^(?:0|[1-9]\d*)$/;
433
+ var ALPHANUMERIC_IDENTIFIER = /^[0-9A-Za-z-]+$/;
434
+ var ALL_DIGITS = /^\d+$/;
435
+ var DIST_TAG = /^[A-Za-z][A-Za-z0-9._-]*$/;
436
+ var GITHUB_OWNER = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/;
437
+ var GITHUB_REPO = /^[A-Za-z0-9._-]{1,100}$/;
438
+ var GITHUB_TAG = /^[A-Za-z0-9._+/-]+$/;
439
+ var GITHUB_PREFIX = "github:";
440
+ var refuse$1 = (error) => ({
441
+ ok: false,
442
+ error
443
+ });
444
+ function isNpmNameShape(name) {
445
+ if (!name.startsWith("@")) return NPM_UNSCOPED_NAME.test(name);
446
+ const slash = name.indexOf("/");
447
+ return slash > 1 && NPM_SCOPED_SEGMENT.test(name.slice(1, slash)) && NPM_SCOPED_SEGMENT.test(name.slice(slash + 1));
448
+ }
449
+ var NPM_EXCLUDED_NAMES = /* @__PURE__ */ new Set(["node_modules", "favicon.ico"]);
450
+ var isNpmReservedName = (name) => NPM_EXCLUDED_NAMES.has(name) || NPM_BUILTIN_MODULE_NAMES.has(name);
451
+ var isNpmPackageName = (name) => name.length <= MAX_NPM_NAME_LENGTH && isNpmNameShape(name) && !isNpmReservedName(name);
452
+ var isVersionCore = (core) => {
453
+ const parts = core.split(".");
454
+ return parts.length === 3 && parts.every((part) => NUMERIC_IDENTIFIER.test(part));
455
+ };
456
+ var isLabel = (label, prerelease) => label.split(".").every((part) => ALPHANUMERIC_IDENTIFIER.test(part) && (!prerelease || !ALL_DIGITS.test(part) || NUMERIC_IDENTIFIER.test(part)));
457
+ /** `major.minor.patch`, then an optional `-prerelease` and an optional `+build`, as semver 2.0.0 defines them. */
458
+ function isSemverShape(version) {
459
+ const plus = version.indexOf("+");
460
+ const build = plus === -1 ? null : version.slice(plus + 1);
461
+ const withoutBuild = plus === -1 ? version : version.slice(0, plus);
462
+ const dash = withoutBuild.indexOf("-");
463
+ const core = dash === -1 ? withoutBuild : withoutBuild.slice(0, dash);
464
+ const prerelease = dash === -1 ? null : withoutBuild.slice(dash + 1);
465
+ return isVersionCore(core) && (prerelease === null || isLabel(prerelease, true)) && (build === null || isLabel(build, false));
466
+ }
467
+ /** A version npm can install as asked: an exact version or a dist-tag. A range is refused, because
468
+ * what it resolves to would change between the confirmation and the next install. */
469
+ var isNpmVersionSpec = (spec) => isSemverShape(spec) || DIST_TAG.test(spec);
470
+ /** An exact version — what a package's own `version` must be, since it becomes part of a file name
471
+ * and a cache folder. */
472
+ var isExactVersion = (version) => isSemverShape(version);
473
+ function parseNpm(input) {
474
+ const specAt = input.lastIndexOf("@");
475
+ const hasSpec = specAt > 0;
476
+ const name = hasSpec ? input.slice(0, specAt) : input;
477
+ const spec = hasSpec ? input.slice(specAt + 1) : null;
478
+ if (!isNpmPackageName(name)) return refuse$1(`not an npm package name: ${JSON.stringify(name)}`);
479
+ if (spec !== null && !isNpmVersionSpec(spec)) return refuse$1(`not an exact version or a dist-tag: ${JSON.stringify(spec)} (a range is not accepted)`);
480
+ return {
481
+ ok: true,
482
+ source: {
483
+ kind: "npm",
484
+ name,
485
+ spec
486
+ }
487
+ };
488
+ }
489
+ var isGithubTag = (tag) => tag.length <= MAX_TAG_LENGTH && GITHUB_TAG.test(tag) && !tag.split("/").some((part) => part === "" || part === "." || part === "..");
490
+ function parseGithub(rest) {
491
+ const hash = rest.indexOf("#");
492
+ const path = hash === -1 ? rest : rest.slice(0, hash);
493
+ const tag = hash === -1 ? null : rest.slice(hash + 1);
494
+ const [owner = "", repo = "", ...extra] = path.split("/");
495
+ if (extra.length > 0 || !GITHUB_OWNER.test(owner)) return refuse$1(`not a GitHub owner/repo: ${JSON.stringify(path)}`);
496
+ if (!GITHUB_REPO.test(repo) || repo === "." || repo === "..") return refuse$1(`not a GitHub owner/repo: ${JSON.stringify(path)}`);
497
+ if (tag !== null && !isGithubTag(tag)) return refuse$1(`not a release tag: ${JSON.stringify(tag)}`);
498
+ return {
499
+ ok: true,
500
+ source: {
501
+ kind: "github",
502
+ owner,
503
+ repo,
504
+ tag
505
+ }
506
+ };
507
+ }
508
+ function parseInstallSource(input) {
509
+ if (typeof input !== "string") return refuse$1("an install source is a string");
510
+ const trimmed = input.trim();
511
+ if (trimmed === "") return refuse$1("an install source is empty");
512
+ return trimmed.startsWith(GITHUB_PREFIX) ? parseGithub(trimmed.slice(7)) : parseNpm(trimmed);
513
+ }
514
+ /** The ledger's `source` field for what was actually installed: the resolved version or tag. */
515
+ function sourceLabel(source, resolved) {
516
+ return source.kind === "npm" ? `npm:${source.name}@${resolved}` : `github:${source.owner}/${source.repo}#${resolved}`;
517
+ }
518
+ /** The file name `npm pack` gives the package — `@scope/name` 1.2.3 → `scope-name-1.2.3.tgz`. */
519
+ var packageFileName = (name, version) => `${name.replace(/^@/, "").replaceAll("/", "-")}-${version}.tgz`;
520
+ var CONTENT_ID_LENGTH = 12;
521
+ /** `npm pack`'s name with a short hash of the bytes before `.tgz` — `scope-name-1.2.3-0123456789ab.tgz`.
522
+ * Two different packages with one name and version (a GitHub tag published again) then get different
523
+ * files. The hash is short, so the install also refuses to write over an existing file whose bytes
524
+ * differ: that is what keeps a file an entry points at from changing. */
525
+ var installedFileName = (name, version, sha256Hex) => packageFileName(name, version).replace(/\.tgz$/, `-${sha256Hex.slice(0, CONTENT_ID_LENGTH)}.tgz`);
526
+ // src/runtime-plugins/ledgerWrite.ts
527
+ var isEntryNamed = (value, name) => isRecord(value) && Object.hasOwn(value, "name") && value.name === name;
528
+ /** The ledger with `entry` in it, exactly once: it takes the place of the first entry of the same
529
+ * name, any further ones are dropped (each would load another copy), and with none it is appended. */
530
+ function withLedgerEntry(raw, entry) {
531
+ const first = raw.findIndex((value) => isEntryNamed(value, entry.name));
532
+ if (first === -1) return [...raw, entry];
533
+ return raw.flatMap((value, index) => {
534
+ if (index === first) return [entry];
535
+ return isEntryNamed(value, entry.name) ? [] : [value];
536
+ });
537
+ }
538
+ /** The ledger without any entry named `name`; everything else is kept as it was. */
539
+ var withoutLedgerEntry = (raw, name) => raw.filter((value) => !isEntryNamed(value, name));
540
+ async function readLedgerText(ledgerPath) {
541
+ try {
542
+ return {
543
+ ok: true,
544
+ text: await readFile(ledgerPath, "utf-8")
545
+ };
546
+ } catch (err) {
547
+ if (isRecord(err) && err.code === "ENOENT") return {
548
+ ok: true,
549
+ text: null
550
+ };
551
+ return {
552
+ ok: false,
553
+ error: `cannot read the plugin ledger ${ledgerPath}: ${String(err)}`
554
+ };
555
+ }
556
+ }
557
+ function parseLedgerText(ledgerPath, text) {
558
+ try {
559
+ const parsed = JSON.parse(text);
560
+ return Array.isArray(parsed) ? {
561
+ ok: true,
562
+ raw: parsed
563
+ } : {
564
+ ok: false,
565
+ error: `the plugin ledger ${ledgerPath} is not a JSON array; fix it before installing`
566
+ };
567
+ } catch (err) {
568
+ return {
569
+ ok: false,
570
+ error: `the plugin ledger ${ledgerPath} is not valid JSON; fix it before installing: ${String(err)}`
571
+ };
572
+ }
573
+ }
574
+ /** The ledger as an array to edit: a missing file is an empty ledger; a file that is not a JSON
575
+ * array is refused rather than overwritten, since writing over it would lose what the user wrote. */
576
+ async function readLedgerForWrite(ledgerPath) {
577
+ const read = await readLedgerText(ledgerPath);
578
+ if (!read.ok) return read;
579
+ return read.text === null ? {
580
+ ok: true,
581
+ raw: []
582
+ } : parseLedgerText(ledgerPath, read.text);
583
+ }
584
+ var writeLedger = (ledgerPath, raw) => writeJsonAtomic(ledgerPath, raw);
585
+ // src/runtime-plugins/download.ts
586
+ var DownloadError = class extends Error {};
587
+ async function readCapped(body, url, maxBytes, signal) {
588
+ const reader = body.getReader();
589
+ const onAbort = () => {
590
+ reader.cancel(signal.reason).catch(() => void 0);
591
+ };
592
+ signal.addEventListener("abort", onAbort, { once: true });
593
+ try {
594
+ return await collectChunks(reader, url, maxBytes, signal);
595
+ } finally {
596
+ signal.removeEventListener("abort", onAbort);
597
+ }
598
+ }
599
+ async function collectChunks(reader, url, maxBytes, signal) {
600
+ const chunks = [];
601
+ let received = 0;
602
+ for (;;) {
603
+ const { done, value } = await reader.read();
604
+ if (signal.aborted) throw signal.reason;
605
+ if (done) return Buffer.concat(chunks);
606
+ received += value.byteLength;
607
+ if (received > maxBytes) {
608
+ reader.cancel().catch(() => void 0);
609
+ throw new DownloadError(`${url} is larger than ${maxBytes} bytes`);
610
+ }
611
+ chunks.push(value);
612
+ }
613
+ }
614
+ /** The response's body once it is known to be a success within the cap. */
615
+ function refuseResponse(res, message) {
616
+ res.body?.cancel().catch(() => void 0);
617
+ throw new DownloadError(message);
618
+ }
619
+ function acceptedBody(res, url, maxBytes) {
620
+ if (!res.ok) refuseResponse(res, `${url} answered HTTP ${res.status}`);
621
+ const declared = Number(res.headers.get("content-length"));
622
+ if (Number.isFinite(declared) && declared > maxBytes) refuseResponse(res, `${url} is ${declared} bytes, more than ${maxBytes}`);
623
+ if (!res.body) throw new DownloadError(`${url} answered with no body`);
624
+ return res.body;
625
+ }
626
+ function settlesByDeadline(pending, signal) {
627
+ return new Promise((resolve, reject) => {
628
+ const onAbort = () => reject(signal.reason);
629
+ if (signal.aborted) onAbort();
630
+ signal.addEventListener("abort", onAbort, { once: true });
631
+ pending.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
632
+ });
633
+ }
634
+ async function downloadBytes(fetchFn, url, headers, limits) {
635
+ const controller = new AbortController();
636
+ const timer = setTimeout(() => controller.abort(new DownloadError(`${url} did not finish within ${limits.timeoutMs}ms`)), limits.timeoutMs);
637
+ try {
638
+ return await readCapped(acceptedBody(await settlesByDeadline(fetchFn(url, {
639
+ headers,
640
+ signal: controller.signal,
641
+ redirect: "follow"
642
+ }), controller.signal), url, limits.maxBytes), url, limits.maxBytes, controller.signal);
643
+ } catch (err) {
644
+ if (err instanceof DownloadError) throw err;
645
+ const reason = controller.signal.aborted ? controller.signal.reason : err;
646
+ throw reason instanceof DownloadError ? reason : new DownloadError(`${url} could not be downloaded: ${String(reason)}`);
647
+ } finally {
648
+ clearTimeout(timer);
649
+ }
650
+ }
651
+ async function downloadJson(fetchFn, url, headers, limits) {
652
+ const bytes = await downloadBytes(fetchFn, url, headers, limits);
653
+ try {
654
+ return JSON.parse(bytes.toString("utf-8"));
655
+ } catch {
656
+ throw new DownloadError(`${url} did not answer with JSON`);
657
+ }
658
+ }
659
+ var SRI = /^(sha512|sha384|sha256)-([A-Za-z0-9+/=]+)$/;
660
+ /** Whether `bytes` match an npm `dist.integrity` (Subresource Integrity, possibly several space-
661
+ * separated hashes) — the strongest algorithm present must match. False when none is recognised. */
662
+ function matchesIntegrity(bytes, integrity) {
663
+ const hashes = integrity.split(/\s+/).map((part) => SRI.exec(part)).filter((match) => match !== null);
664
+ const strongest = [
665
+ "sha512",
666
+ "sha384",
667
+ "sha256"
668
+ ].find((algorithm) => hashes.some((match) => match[1] === algorithm));
669
+ if (strongest === void 0) return false;
670
+ const actual = createHash(strongest).update(bytes).digest("base64");
671
+ return hashes.some((match) => match[1] === strongest && match[2] === actual);
672
+ }
673
+ // src/runtime-plugins/fetchPackage.ts
674
+ var NPM_REGISTRY = "https://registry.npmjs.org";
675
+ var GITHUB_API = "https://api.github.com";
676
+ var ONE_SECOND_MS = 1e3;
677
+ var ONE_MIB$1 = 1048576;
678
+ var METADATA_LIMITS = {
679
+ timeoutMs: 30 * ONE_SECOND_MS,
680
+ maxBytes: 32 * ONE_MIB$1
681
+ };
682
+ var PACKAGE_LIMITS = {
683
+ timeoutMs: 120 * ONE_SECOND_MS,
684
+ maxBytes: 50 * ONE_MIB$1
685
+ };
686
+ var USER_AGENT = "mulmo-runtime-plugins";
687
+ var stringOrNull = (value) => typeof value === "string" ? value : null;
688
+ var fail = (error) => ({
689
+ ok: false,
690
+ error
691
+ });
692
+ var isHttpsUrl = (value) => value.startsWith("https://");
693
+ function resolveNpmVersion(packument, versions, spec) {
694
+ const tags = isRecord(packument["dist-tags"]) ? packument["dist-tags"] : {};
695
+ if (spec !== null && Object.hasOwn(versions, spec)) return {
696
+ ok: true,
697
+ value: spec
698
+ };
699
+ const tag = spec ?? "latest";
700
+ const fromTag = Object.hasOwn(tags, tag) ? stringOrNull(tags[tag]) : null;
701
+ if (fromTag !== null) return {
702
+ ok: true,
703
+ value: fromTag
704
+ };
705
+ return fail(spec === null ? "the package has no latest version" : `no version or dist-tag ${JSON.stringify(spec)}`);
706
+ }
707
+ function releaseOf(versions, version) {
708
+ const entry = Object.hasOwn(versions, version) ? versions[version] : void 0;
709
+ const dist = isRecord(entry) && isRecord(entry.dist) ? entry.dist : null;
710
+ const tarball = dist ? stringOrNull(dist.tarball) : null;
711
+ if (dist === null || tarball === null || !isHttpsUrl(tarball)) return fail(`version ${version} has no https tarball`);
712
+ return {
713
+ ok: true,
714
+ value: {
715
+ version,
716
+ tarball,
717
+ integrity: stringOrNull(dist.integrity)
718
+ }
719
+ };
720
+ }
721
+ /** The version a packument resolves `spec` to — exact, a dist-tag, or `latest` when absent. */
722
+ function resolveNpmRelease(packument, spec) {
723
+ if (!isRecord(packument) || !isRecord(packument.versions)) return fail("the registry did not answer with a package");
724
+ const version = resolveNpmVersion(packument, packument.versions, spec);
725
+ return version.ok ? releaseOf(packument.versions, version.value) : version;
726
+ }
727
+ /** Whether the downloaded bytes are the ones the registry published, by its strongest hash. */
728
+ function verifyNpmBytes(bytes, release) {
729
+ if (release.integrity === null) return `the registry publishes no sha512/sha384/sha256 integrity for ${release.version}, so the tarball cannot be checked`;
730
+ return matchesIntegrity(bytes, release.integrity) ? null : `the tarball does not match the registry's integrity for ${release.version}`;
731
+ }
732
+ var assetsOf = (release) => Array.isArray(release.assets) ? release.assets.filter(isRecord) : [];
733
+ /** The release's one `.tgz` asset. None, or several, is refused: guessing which file is the plugin
734
+ * is exactly what a user should not have to trust. */
735
+ function resolveGithubAsset(release) {
736
+ if (!isRecord(release) || typeof release.tag_name !== "string") return fail("GitHub did not answer with a release");
737
+ const assets = assetsOf(release);
738
+ const tgz = assets.filter((asset) => typeof asset.name === "string" && asset.name.endsWith(".tgz"));
739
+ const names = assets.map((asset) => String(asset.name)).join(", ") || "none";
740
+ if (tgz.length !== 1) return fail(`release ${release.tag_name} has ${tgz.length} .tgz assets (assets: ${names}); exactly one is needed`);
741
+ const [asset] = tgz;
742
+ const downloadUrl = stringOrNull(asset?.browser_download_url);
743
+ const apiUrl = stringOrNull(asset?.url);
744
+ if (downloadUrl === null || apiUrl === null || !isHttpsUrl(downloadUrl) || !isHttpsUrl(apiUrl)) return fail(`release ${release.tag_name}'s .tgz asset has no https download URL`);
745
+ return {
746
+ ok: true,
747
+ value: {
748
+ tag: release.tag_name,
749
+ name: String(asset?.name),
750
+ downloadUrl,
751
+ apiUrl,
752
+ digest: stringOrNull(asset?.digest)
753
+ }
754
+ };
755
+ }
756
+ var SHA256_DIGEST = /^sha256:([0-9a-f]{64})$/;
757
+ /** Whether the bytes are the asset GitHub recorded. An asset with no digest is accepted — older
758
+ * uploads carry none, and the bytes still came over https from GitHub — but a digest that is present
759
+ * must be a sha256 and must match. */
760
+ function verifyGithubBytes(bytes, asset) {
761
+ if (asset.digest === null) return null;
762
+ const expected = SHA256_DIGEST.exec(asset.digest.toLowerCase())?.[1];
763
+ if (expected === void 0) return `release ${asset.tag}'s asset has an unrecognised digest ${JSON.stringify(asset.digest)}`;
764
+ return createHash("sha256").update(bytes).digest("hex") === expected ? null : `the asset does not match GitHub's recorded digest for ${asset.tag}`;
765
+ }
766
+ function httpsBase(base, what) {
767
+ if (!isHttpsUrl(base)) throw new DownloadError(`${what} must be an https URL, not ${JSON.stringify(base)}`);
768
+ return base.endsWith("/") ? base.slice(0, -1) : base;
769
+ }
770
+ var packumentUrl = (registry, name) => `${registry}/${name.replaceAll("/", "%2f")}`;
771
+ async function fetchNpm(source, deps) {
772
+ const accept = {
773
+ accept: "application/vnd.npm.install-v1+json",
774
+ "user-agent": USER_AGENT
775
+ };
776
+ const resolved = resolveNpmRelease(await downloadJson(deps.fetch, packumentUrl(httpsBase(deps.npmRegistry ?? "https://registry.npmjs.org", "the npm registry"), source.name), accept, METADATA_LIMITS), source.spec);
777
+ if (!resolved.ok) throw new DownloadError(`${source.name}: ${resolved.error}`);
778
+ const release = resolved.value;
779
+ const bytes = await downloadBytes(deps.fetch, release.tarball, { "user-agent": USER_AGENT }, PACKAGE_LIMITS);
780
+ const mismatch = verifyNpmBytes(bytes, release);
781
+ if (mismatch !== null) throw new DownloadError(`${source.name}: ${mismatch}`);
782
+ return {
783
+ bytes,
784
+ resolved: release.version
785
+ };
786
+ }
787
+ function githubHeaders(deps, accept) {
788
+ const headers = {
789
+ accept,
790
+ "user-agent": USER_AGENT
791
+ };
792
+ if (deps.githubToken) headers.authorization = `Bearer ${deps.githubToken}`;
793
+ return headers;
794
+ }
795
+ function assetUrl(asset, deps, apiBase) {
796
+ if (!deps.githubToken) return asset.downloadUrl;
797
+ if (new URL(asset.apiUrl).origin !== new URL(apiBase).origin) throw new DownloadError(`release ${asset.tag}'s asset URL is not on ${apiBase}`);
798
+ return asset.apiUrl;
799
+ }
800
+ async function fetchGithub(source, deps) {
801
+ const repo = `${encodeURIComponent(source.owner)}/${encodeURIComponent(source.repo)}`;
802
+ const which = source.tag === null ? "latest" : `tags/${encodeURIComponent(source.tag)}`;
803
+ const apiBase = httpsBase(deps.githubApi ?? "https://api.github.com", "the GitHub API");
804
+ const releaseUrl = `${apiBase}/repos/${repo}/releases/${which}`;
805
+ const resolved = resolveGithubAsset(await downloadJson(deps.fetch, releaseUrl, githubHeaders(deps, "application/vnd.github+json"), METADATA_LIMITS));
806
+ if (!resolved.ok) throw new DownloadError(`${source.owner}/${source.repo}: ${resolved.error}`);
807
+ const asset = resolved.value;
808
+ const bytes = await downloadBytes(deps.fetch, assetUrl(asset, deps, apiBase), githubHeaders(deps, "application/octet-stream"), PACKAGE_LIMITS);
809
+ const mismatch = verifyGithubBytes(bytes, asset);
810
+ if (mismatch !== null) throw new DownloadError(`${source.owner}/${source.repo}: ${mismatch}`);
811
+ return {
812
+ bytes,
813
+ resolved: asset.tag
814
+ };
815
+ }
816
+ var fetchPackage = (source, deps) => source.kind === "npm" ? fetchNpm(source, deps) : fetchGithub(source, deps);
817
+ // src/runtime-plugins/inspect.ts
818
+ var TEMP_PREFIX = ".inspect-";
819
+ var MAX_UNPACKED_BYTES = 268435456;
820
+ /** Whether the gzip stream expands to at most `maxBytes`, counted while it is inflated so a hostile
821
+ * archive is stopped at the limit rather than after it has been written out. */
822
+ function inflatesWithin(bytes, maxBytes) {
823
+ return new Promise((resolve, reject) => {
824
+ const gunzip = createGunzip();
825
+ let inflated = 0;
826
+ gunzip.on("data", (chunk) => {
827
+ inflated += chunk.length;
828
+ if (inflated <= maxBytes) return;
829
+ gunzip.destroy();
830
+ resolve(false);
831
+ });
832
+ gunzip.on("end", () => resolve(true));
833
+ gunzip.on("error", reject);
834
+ gunzip.end(bytes);
835
+ });
836
+ }
837
+ var UNPARSABLE = Symbol("unparsable");
838
+ function parseJsonFile(file) {
839
+ try {
840
+ return JSON.parse(readFileSync(file, "utf-8"));
841
+ } catch {
842
+ return UNPARSABLE;
843
+ }
844
+ }
845
+ var refuse = (error) => ({
846
+ ok: false,
847
+ error
848
+ });
849
+ function readPackage(dir) {
850
+ const outward = linkLeadingOut(dir);
851
+ if (outward !== null) return refuse(`the package holds a link that leads outside it: ${outward}`);
852
+ const pkgPath = path.join(dir, "package.json");
853
+ if (!existsSync(pkgPath)) return refuse("the package has no package.json");
854
+ const parsed = parseJsonFile(pkgPath);
855
+ if (parsed === UNPARSABLE) return refuse("the package's package.json is not valid JSON");
856
+ const pkg = toPackageJson(parsed);
857
+ if (pkg?.name === void 0 || pkg.version === void 0) return refuse("the package's package.json has no name or version");
858
+ const entrySpec = resolveEntrySpecifier(pkg);
859
+ if (entrySpec === null) return refuse("the package's package.json names no server entry (exports, module or main)");
860
+ const entryAbs = path.join(dir, entrySpec);
861
+ if (!ensureInsideBase(entryAbs, dir) || !resolvesInside(entryAbs, dir)) return refuse(`the package's server entry ${entrySpec} is not in it`);
862
+ if (!statSync(entryAbs).isFile()) return refuse(`the package's server entry ${entrySpec} is not a file`);
863
+ return {
864
+ ok: true,
865
+ value: {
866
+ name: pkg.name,
867
+ version: pkg.version,
868
+ entrySpec
869
+ }
870
+ };
871
+ }
872
+ /** What the package file says it is, or why it is not a package this loader can use. */
873
+ async function inspectPackage(bytes, pluginsDir) {
874
+ const withinLimit = await inflatesWithin(bytes, MAX_UNPACKED_BYTES).catch(() => null);
875
+ if (withinLimit === null) return refuse("the file is not a gzip package");
876
+ if (!withinLimit) return refuse(`the package expands to more than ${MAX_UNPACKED_BYTES} bytes`);
877
+ const work = await mkdtemp(path.join(pluginsDir, TEMP_PREFIX));
878
+ try {
879
+ const tgz = path.join(work, "package.tgz");
880
+ await writeFile(tgz, bytes);
881
+ const unpacked = path.join(work, "unpacked");
882
+ try {
883
+ extractTgz(tgz, unpacked);
884
+ } catch (err) {
885
+ return refuse(`the file could not be unpacked as a package: ${String(err)}`);
886
+ }
887
+ return readPackage(unpacked);
888
+ } finally {
889
+ await rm(work, {
890
+ recursive: true,
891
+ force: true
892
+ });
893
+ }
894
+ }
895
+ // src/runtime-plugins/install.ts
896
+ var InstallError = class extends Error {};
897
+ function checkIdentity(source, resolved, name, version) {
898
+ if (!isNpmPackageName(name)) throw new InstallError(`the package's name ${JSON.stringify(name)} is not an npm package name`);
899
+ if (!isExactVersion(version)) throw new InstallError(`the package's version ${JSON.stringify(version)} is not an exact version`);
900
+ if (source.kind !== "npm") return;
901
+ if (name !== source.name) throw new InstallError(`asked for ${source.name}, but the package is ${name}`);
902
+ if (version !== resolved) throw new InstallError(`asked for ${source.name}@${resolved}, but the package is version ${version}`);
903
+ }
904
+ async function preparePlan(source, deps) {
905
+ await mkdir(deps.paths.pluginsDir, { recursive: true });
906
+ const ledger = await readLedgerForWrite(deps.paths.ledgerPath);
907
+ if (!ledger.ok) throw new InstallError(ledger.error);
908
+ const fetched = await fetchPackage(source, deps);
909
+ const inspection = await inspectPackage(fetched.bytes, deps.paths.pluginsDir);
910
+ if (!inspection.ok) throw new InstallError(inspection.error);
911
+ const inspected = inspection.value;
912
+ checkIdentity(source, fetched.resolved, inspected.name, inspected.version);
913
+ const replaces = parseLedger(ledger.raw).find((entry) => entry.name === inspected.name) ?? null;
914
+ const tgz = installedFileName(inspected.name, inspected.version, createHash("sha256").update(fetched.bytes).digest("hex"));
915
+ return {
916
+ plan: {
917
+ name: inspected.name,
918
+ version: inspected.version,
919
+ source: sourceLabel(source, fetched.resolved),
920
+ tgz,
921
+ replaces
922
+ },
923
+ bytes: fetched.bytes,
924
+ raw: ledger.raw
925
+ };
926
+ }
927
+ async function dropStaleCache(plan, raw, paths) {
928
+ const sameVersion = parseLedger(raw).filter((entry) => entry.name === plan.name && entry.version === plan.version);
929
+ if (sameVersion.length > 0 && sameVersion.every((entry) => entry.tgz === plan.tgz)) return;
930
+ const cacheDir = paths.cacheDir ?? path.join(paths.pluginsDir, ".cache");
931
+ const stale = path.join(cacheDir, plan.name, plan.version);
932
+ if (ensureInsideBase(stale, cacheDir)) await rm(stale, {
933
+ recursive: true,
934
+ force: true
935
+ });
936
+ }
937
+ async function writePackageFile(plan, bytes, pluginsDir) {
938
+ const tgzPath = path.join(pluginsDir, plan.tgz);
939
+ const fileWasThere = existsSync(tgzPath);
940
+ if (fileWasThere && !(await readFile(tgzPath)).equals(bytes)) throw new InstallError(`${plan.tgz} already exists with different bytes; not overwritten`);
941
+ if (!fileWasThere) await writeFileAtomic(tgzPath, bytes);
942
+ return {
943
+ tgzPath,
944
+ fileWasThere
945
+ };
946
+ }
947
+ async function commit(plan, bytes, raw, deps) {
948
+ const { tgzPath, fileWasThere } = await writePackageFile(plan, bytes, deps.paths.pluginsDir);
949
+ const installedAt = (deps.now ?? (() => /* @__PURE__ */ new Date()))().toISOString();
950
+ const entry = {
951
+ name: plan.name,
952
+ version: plan.version,
953
+ tgz: plan.tgz,
954
+ installedAt,
955
+ source: plan.source
956
+ };
957
+ try {
958
+ await dropStaleCache(plan, raw, deps.paths);
959
+ await writeLedger(deps.paths.ledgerPath, withLedgerEntry(raw, entry));
960
+ } catch (err) {
961
+ if (!fileWasThere) await rm(tgzPath, { force: true });
962
+ throw err;
963
+ }
964
+ return entry;
965
+ }
966
+ var failure = (err, action) => {
967
+ if (err instanceof InstallError || err instanceof DownloadError) return {
968
+ status: "failed",
969
+ error: err.message
970
+ };
971
+ return {
972
+ status: "failed",
973
+ error: `${action} failed: ${err instanceof Error ? err.message : String(err)}`
974
+ };
975
+ };
976
+ /** Install what `input` names (`<npm name>[@<version or dist-tag>]` or `github:<owner>/<repo>[#<tag>]`). */
977
+ async function installRuntimePlugin(input, deps) {
978
+ const parsed = parseInstallSource(input);
979
+ if (!parsed.ok) return {
980
+ status: "failed",
981
+ error: parsed.error
982
+ };
983
+ try {
984
+ const { plan, bytes, raw } = await preparePlan(parsed.source, deps);
985
+ if (!await deps.confirm(plan)) return {
986
+ status: "cancelled",
987
+ plan
988
+ };
989
+ return {
990
+ status: "installed",
991
+ entry: await commit(plan, bytes, raw, deps),
992
+ replaced: plan.replaces
993
+ };
994
+ } catch (err) {
995
+ return failure(err, "install");
996
+ }
997
+ }
998
+ /** Take `name` out of the ledger. Its package file, unpacked copy and data folders are left in place. */
999
+ async function uninstallRuntimePlugin(name, paths) {
1000
+ const ledger = await readLedgerForWrite(paths.ledgerPath);
1001
+ if (!ledger.ok) return {
1002
+ status: "failed",
1003
+ error: ledger.error
1004
+ };
1005
+ const entry = parseLedger(ledger.raw).find((candidate) => candidate.name === name) ?? null;
1006
+ const remaining = withoutLedgerEntry(ledger.raw, name);
1007
+ if (remaining.length === ledger.raw.length) return { status: "not-installed" };
1008
+ try {
1009
+ await writeLedger(paths.ledgerPath, remaining);
1010
+ } catch (err) {
1011
+ return failure(err, "uninstall");
1012
+ }
1013
+ return {
1014
+ status: "removed",
1015
+ entry
1016
+ };
1017
+ }
1018
+ export { DownloadError, EXTRACT_MARKER, GITHUB_API, NPM_REGISTRY, downloadBytes, downloadJson, ensureInsideBase, extractTgz, fetchPackage, inspectPackage, installRuntimePlugin, installedFileName, isCacheValid, isExactVersion, isLedgerEntry, isNpmPackageName, isNpmVersionSpec, linkLeadingOut, loadPluginFromCacheDir, matchesIntegrity, packageFileName, parseInstallSource, parseLedger, prepareLedgerEntry, readLedgerForWrite, resolveEntrySpecifier, resolveExecute, resolveGithubAsset, resolveNpmRelease, resolvesInside, sourceLabel, toPackageJson, uninstallRuntimePlugin, verifyGithubBytes, verifyNpmBytes, withLedgerEntry, withoutLedgerEntry, writeLedger };
1019
+
1020
+ //# sourceMappingURL=index.js.map