@mulmoclaude/core 7.4.0 → 7.6.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.
- package/dist/{root-CqxPNSyK.js → atomic-C3NMg6-j.js} +2 -20
- package/dist/atomic-C3NMg6-j.js.map +1 -0
- package/dist/{root-9lRFeXbm.cjs → atomic-cqafMWEI.cjs} +1 -25
- package/dist/atomic-cqafMWEI.cjs.map +1 -0
- package/dist/collection/index.cjs +3 -3
- package/dist/collection/index.js +3 -3
- package/dist/collection/registry/server/index.cjs +5 -5
- package/dist/collection/registry/server/index.cjs.map +1 -1
- package/dist/collection/registry/server/index.js +4 -4
- package/dist/collection/server/index.cjs +3 -3
- package/dist/collection/server/index.js +3 -3
- package/dist/collection-watchers/index.cjs +5 -5
- package/dist/collection-watchers/index.js +5 -5
- package/dist/{discovery-DxmMcpFo.cjs → discovery-BSvWBOGB.cjs} +7 -6
- package/dist/discovery-BSvWBOGB.cjs.map +1 -0
- package/dist/{discovery-RyuhNKjx.js → discovery-DEhLlDVW.js} +6 -5
- package/dist/discovery-DEhLlDVW.js.map +1 -0
- package/dist/{dist-BmO4oSQy.js → dist--searOB5.js} +2 -2
- package/dist/dist--searOB5.js.map +1 -0
- package/dist/{dist-734JaRYi.cjs → dist-CdSEjlVx.cjs} +2 -2
- package/dist/dist-CdSEjlVx.cjs.map +1 -0
- package/dist/errorMessage-B-iVKe5R.cjs +1 -0
- package/dist/errorMessage-D-HWCI2W.js +1 -0
- package/dist/{errors-B9mCEVG9.cjs → errors-B7ShVbIB.cjs} +2 -2
- package/dist/{errors-B9mCEVG9.cjs.map → errors-B7ShVbIB.cjs.map} +1 -1
- package/dist/{errors-0QwjDxsv.js → errors-BbH5CeKm.js} +2 -2
- package/dist/{errors-0QwjDxsv.js.map → errors-BbH5CeKm.js.map} +1 -1
- package/dist/feeds/server/index.cjs +6 -6
- package/dist/feeds/server/index.cjs.map +1 -1
- package/dist/feeds/server/index.js +6 -6
- package/dist/feeds/server/index.js.map +1 -1
- package/dist/files/index.cjs +8 -13
- package/dist/files/index.cjs.map +1 -1
- package/dist/files/index.js +3 -8
- package/dist/files/index.js.map +1 -1
- package/dist/google/index.cjs +5 -5
- package/dist/google/index.cjs.map +1 -1
- package/dist/google/index.js +4 -4
- package/dist/json-BGdV2cz6.cjs +16 -0
- package/dist/json-BGdV2cz6.cjs.map +1 -0
- package/dist/json-BizOSThv.js +11 -0
- package/dist/json-BizOSThv.js.map +1 -0
- package/dist/{listen-uiEnXcW9.js → listen-Bm8N0g9o.js} +2 -2
- package/dist/{listen-uiEnXcW9.js.map → listen-Bm8N0g9o.js.map} +1 -1
- package/dist/{listen-OmfLDX1l.cjs → listen-OGOFPIdk.cjs} +2 -2
- package/dist/{listen-OmfLDX1l.cjs.map → listen-OGOFPIdk.cjs.map} +1 -1
- package/dist/notifier/index.cjs +1 -1
- package/dist/notifier/index.js +1 -1
- package/dist/{notifier-CRTk34EC.cjs → notifier-8R05SHLj.cjs} +2 -2
- package/dist/{notifier-CRTk34EC.cjs.map → notifier-8R05SHLj.cjs.map} +1 -1
- package/dist/{notifier-htdf4ekH.js → notifier-D7TmVus0.js} +2 -2
- package/dist/{notifier-htdf4ekH.js.map → notifier-D7TmVus0.js.map} +1 -1
- package/dist/plugin-vue/index.cjs +1 -1
- package/dist/plugin-vue/index.cjs.map +1 -1
- package/dist/plugin-vue/index.js +1 -1
- package/dist/plugin-vue/index.js.map +1 -1
- package/dist/prompt-files/index.cjs +1 -1
- package/dist/prompt-files/index.js +1 -1
- package/dist/{promptSafety-CjxafW2b.cjs → promptSafety-CF6OCtor.cjs} +2 -2
- package/dist/{promptSafety-CjxafW2b.cjs.map → promptSafety-CF6OCtor.cjs.map} +1 -1
- package/dist/{promptSafety-B8LECAkY.js → promptSafety-CYU_kLUL.js} +2 -2
- package/dist/{promptSafety-B8LECAkY.js.map → promptSafety-CYU_kLUL.js.map} +1 -1
- package/dist/remote-host/index.cjs +1 -1
- package/dist/remote-host/index.js +1 -1
- package/dist/remote-host/server/index.cjs +4 -4
- package/dist/remote-host/server/index.js +4 -4
- package/dist/{remote-host-TiMhcW1o.js → remote-host-BiCg_ioB.js} +2 -2
- package/dist/{remote-host-TiMhcW1o.js.map → remote-host-BiCg_ioB.js.map} +1 -1
- package/dist/{remote-host-11euEZKP.cjs → remote-host-neXWDACl.cjs} +2 -2
- package/dist/{remote-host-11euEZKP.cjs.map → remote-host-neXWDACl.cjs.map} +1 -1
- package/dist/remote-view/index.cjs +1 -1
- package/dist/remote-view/index.js +1 -1
- package/dist/root-Ccgd3H5S.cjs +29 -0
- package/dist/root-Ccgd3H5S.cjs.map +1 -0
- package/dist/root-s0MUUMQU.js +22 -0
- package/dist/root-s0MUUMQU.js.map +1 -0
- package/dist/runtime-plugins/containment.d.ts +5 -0
- package/dist/runtime-plugins/download.d.ts +12 -0
- package/dist/runtime-plugins/fetchPackage.d.ts +65 -0
- package/dist/runtime-plugins/index.cjs +810 -5
- package/dist/runtime-plugins/index.cjs.map +1 -1
- package/dist/runtime-plugins/index.d.ts +7 -0
- package/dist/runtime-plugins/index.js +786 -8
- package/dist/runtime-plugins/index.js.map +1 -1
- package/dist/runtime-plugins/inspect.d.ts +18 -0
- package/dist/runtime-plugins/install.d.ts +48 -0
- package/dist/runtime-plugins/installSource.d.ts +37 -0
- package/dist/runtime-plugins/ledger.d.ts +3 -0
- package/dist/runtime-plugins/ledgerWrite.d.ts +17 -0
- package/dist/runtime-plugins/load.d.ts +2 -2
- package/dist/runtime-plugins/npmBuiltinNames.d.ts +1 -0
- package/dist/scheduler/index.cjs +2 -2
- package/dist/scheduler/index.js +2 -2
- package/dist/{server-ZKTtI8_W.cjs → server-BxwOUg_l.cjs} +9 -9
- package/dist/{server-ZKTtI8_W.cjs.map → server-BxwOUg_l.cjs.map} +1 -1
- package/dist/{server-xdXBsiba.js → server-C3HNV-PG.js} +6 -6
- package/dist/{server-xdXBsiba.js.map → server-C3HNV-PG.js.map} +1 -1
- package/dist/utils/index.cjs +2 -2
- package/dist/utils/index.js +2 -2
- package/dist/whisper/index.cjs +2 -2
- package/dist/whisper/index.js +2 -2
- package/dist/wiki/index.cjs +1 -1
- package/dist/wiki/index.js +1 -1
- package/dist/workspace-setup/index.js +1 -1
- package/dist/workspace-setup/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/discovery-DxmMcpFo.cjs.map +0 -1
- package/dist/discovery-RyuhNKjx.js.map +0 -1
- package/dist/dist-734JaRYi.cjs.map +0 -1
- package/dist/dist-BmO4oSQy.js.map +0 -1
- package/dist/errorMessage-D0kR547_.cjs +0 -1
- package/dist/errorMessage-TpKxrmeo.js +0 -1
- package/dist/root-9lRFeXbm.cjs.map +0 -1
- package/dist/root-CqxPNSyK.js.map +0 -1
|
@@ -1,12 +1,18 @@
|
|
|
1
|
-
import { c as isRecord, i as hasStringProp } from "../dist
|
|
2
|
-
import { n as isWithinRoot } from "../containment-D_vAa6eT.js";
|
|
1
|
+
import { c as isRecord, i as hasStringProp } from "../dist--searOB5.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";
|
|
3
5
|
import { isPluginFactory } from "gui-chat-protocol";
|
|
4
|
-
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
6
|
+
import { existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
5
7
|
import path from "node:path";
|
|
8
|
+
import { createHash } from "node:crypto";
|
|
9
|
+
import { constants as constants$1, mkdir, mkdtemp, open, readFile, rm, writeFile } from "node:fs/promises";
|
|
6
10
|
import { execFileSync } from "node:child_process";
|
|
7
11
|
import { pathToFileURL } from "node:url";
|
|
12
|
+
import { createGunzip } from "node:zlib";
|
|
8
13
|
// src/runtime-plugins/ledger.ts
|
|
9
|
-
var
|
|
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);
|
|
10
16
|
/** The well-formed entries of a parsed ledger; anything that is not an array reads as empty. */
|
|
11
17
|
var parseLedger = (raw) => {
|
|
12
18
|
if (!Array.isArray(raw)) return [];
|
|
@@ -90,6 +96,13 @@ var EXTRACT_MARKER = ".extract-complete";
|
|
|
90
96
|
function isCacheValid(cachePath) {
|
|
91
97
|
return existsSync(path.join(cachePath, EXTRACT_MARKER));
|
|
92
98
|
}
|
|
99
|
+
function writeMarker(markerPath) {
|
|
100
|
+
rmSync(markerPath, {
|
|
101
|
+
recursive: true,
|
|
102
|
+
force: true
|
|
103
|
+
});
|
|
104
|
+
writeFileSync(markerPath, "", { flag: "wx" });
|
|
105
|
+
}
|
|
93
106
|
/** Run `tar xzf` to extract a tgz into the version-keyed cache slot.
|
|
94
107
|
* `--strip-components=1` drops the `package/` prefix that npm packs
|
|
95
108
|
* add. `execFileSync` (not `execSync`) so paths bypass shell parsing
|
|
@@ -115,7 +128,7 @@ function extractTgz(tgzAbs, destDir) {
|
|
|
115
128
|
destDir,
|
|
116
129
|
"--strip-components=1"
|
|
117
130
|
], { stdio: "pipe" });
|
|
118
|
-
|
|
131
|
+
writeMarker(path.join(destDir, EXTRACT_MARKER));
|
|
119
132
|
} catch (err) {
|
|
120
133
|
try {
|
|
121
134
|
rmSync(destDir, {
|
|
@@ -126,6 +139,24 @@ function extractTgz(tgzAbs, destDir) {
|
|
|
126
139
|
throw err;
|
|
127
140
|
}
|
|
128
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
|
+
}
|
|
129
160
|
// src/runtime-plugins/load.ts
|
|
130
161
|
var isToolDefinition = (value) => {
|
|
131
162
|
if (!isRecord(value)) return false;
|
|
@@ -217,6 +248,13 @@ async function loadPluginFromCacheDir(name, version, cachePath, deps) {
|
|
|
217
248
|
return null;
|
|
218
249
|
}
|
|
219
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
|
+
}
|
|
220
258
|
try {
|
|
221
259
|
const mod = await import(pathToFileURL(entryAbs).href);
|
|
222
260
|
if (!isRecord(mod)) {
|
|
@@ -264,8 +302,8 @@ async function loadPluginFromCacheDir(name, version, cachePath, deps) {
|
|
|
264
302
|
* touch the disk. The asset route trusts registry membership, so a
|
|
265
303
|
* registered cachePath that escaped the base would expose arbitrary
|
|
266
304
|
* files via the unauthenticated GET — this check is the first
|
|
267
|
-
* line of defence
|
|
268
|
-
* symlink-escape backstop
|
|
305
|
+
* line of defence; `loadPluginFromCacheDir` checks the entry's realpath
|
|
306
|
+
* after extraction as the symlink-escape backstop. */
|
|
269
307
|
function ensureInsideBase(candidate, base) {
|
|
270
308
|
return isWithinRoot(path.resolve(base), path.resolve(candidate));
|
|
271
309
|
}
|
|
@@ -311,6 +349,746 @@ function prepareLedgerEntry(entry, roots, log) {
|
|
|
311
349
|
}
|
|
312
350
|
return cachePath;
|
|
313
351
|
}
|
|
314
|
-
|
|
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 FILE_PREFIX = "file:";
|
|
441
|
+
var PACKAGE_FILE_SUFFIX = ".tgz";
|
|
442
|
+
var refuse$1 = (error) => ({
|
|
443
|
+
ok: false,
|
|
444
|
+
error
|
|
445
|
+
});
|
|
446
|
+
function isNpmNameShape(name) {
|
|
447
|
+
if (!name.startsWith("@")) return NPM_UNSCOPED_NAME.test(name);
|
|
448
|
+
const slash = name.indexOf("/");
|
|
449
|
+
return slash > 1 && NPM_SCOPED_SEGMENT.test(name.slice(1, slash)) && NPM_SCOPED_SEGMENT.test(name.slice(slash + 1));
|
|
450
|
+
}
|
|
451
|
+
var NPM_EXCLUDED_NAMES = /* @__PURE__ */ new Set(["node_modules", "favicon.ico"]);
|
|
452
|
+
var isNpmReservedName = (name) => NPM_EXCLUDED_NAMES.has(name) || NPM_BUILTIN_MODULE_NAMES.has(name);
|
|
453
|
+
var isNpmPackageName = (name) => name.length <= MAX_NPM_NAME_LENGTH && isNpmNameShape(name) && !isNpmReservedName(name);
|
|
454
|
+
var isVersionCore = (core) => {
|
|
455
|
+
const parts = core.split(".");
|
|
456
|
+
return parts.length === 3 && parts.every((part) => NUMERIC_IDENTIFIER.test(part));
|
|
457
|
+
};
|
|
458
|
+
var isLabel = (label, prerelease) => label.split(".").every((part) => ALPHANUMERIC_IDENTIFIER.test(part) && (!prerelease || !ALL_DIGITS.test(part) || NUMERIC_IDENTIFIER.test(part)));
|
|
459
|
+
/** `major.minor.patch`, then an optional `-prerelease` and an optional `+build`, as semver 2.0.0 defines them. */
|
|
460
|
+
function isSemverShape(version) {
|
|
461
|
+
const plus = version.indexOf("+");
|
|
462
|
+
const build = plus === -1 ? null : version.slice(plus + 1);
|
|
463
|
+
const withoutBuild = plus === -1 ? version : version.slice(0, plus);
|
|
464
|
+
const dash = withoutBuild.indexOf("-");
|
|
465
|
+
const core = dash === -1 ? withoutBuild : withoutBuild.slice(0, dash);
|
|
466
|
+
const prerelease = dash === -1 ? null : withoutBuild.slice(dash + 1);
|
|
467
|
+
return isVersionCore(core) && (prerelease === null || isLabel(prerelease, true)) && (build === null || isLabel(build, false));
|
|
468
|
+
}
|
|
469
|
+
/** A version npm can install as asked: an exact version or a dist-tag. A range is refused, because
|
|
470
|
+
* what it resolves to would change between the confirmation and the next install. */
|
|
471
|
+
var isNpmVersionSpec = (spec) => isSemverShape(spec) || DIST_TAG.test(spec);
|
|
472
|
+
/** An exact version — what a package's own `version` must be, since it becomes part of a file name
|
|
473
|
+
* and a cache folder. */
|
|
474
|
+
var isExactVersion = (version) => isSemverShape(version);
|
|
475
|
+
function parseNpm(input) {
|
|
476
|
+
const specAt = input.lastIndexOf("@");
|
|
477
|
+
const hasSpec = specAt > 0;
|
|
478
|
+
const name = hasSpec ? input.slice(0, specAt) : input;
|
|
479
|
+
const spec = hasSpec ? input.slice(specAt + 1) : null;
|
|
480
|
+
if (!isNpmPackageName(name)) return refuse$1(`not an npm package name: ${JSON.stringify(name)}`);
|
|
481
|
+
if (spec !== null && !isNpmVersionSpec(spec)) return refuse$1(`not an exact version or a dist-tag: ${JSON.stringify(spec)} (a range is not accepted)`);
|
|
482
|
+
return {
|
|
483
|
+
ok: true,
|
|
484
|
+
source: {
|
|
485
|
+
kind: "npm",
|
|
486
|
+
name,
|
|
487
|
+
spec
|
|
488
|
+
}
|
|
489
|
+
};
|
|
490
|
+
}
|
|
491
|
+
var isGithubTag = (tag) => tag.length <= MAX_TAG_LENGTH && GITHUB_TAG.test(tag) && !tag.split("/").some((part) => part === "" || part === "." || part === "..");
|
|
492
|
+
function parseGithub(rest) {
|
|
493
|
+
const hash = rest.indexOf("#");
|
|
494
|
+
const ownerRepo = hash === -1 ? rest : rest.slice(0, hash);
|
|
495
|
+
const tag = hash === -1 ? null : rest.slice(hash + 1);
|
|
496
|
+
const [owner = "", repo = "", ...extra] = ownerRepo.split("/");
|
|
497
|
+
if (extra.length > 0 || !GITHUB_OWNER.test(owner)) return refuse$1(`not a GitHub owner/repo: ${JSON.stringify(ownerRepo)}`);
|
|
498
|
+
if (!GITHUB_REPO.test(repo) || repo === "." || repo === "..") return refuse$1(`not a GitHub owner/repo: ${JSON.stringify(ownerRepo)}`);
|
|
499
|
+
if (tag !== null && !isGithubTag(tag)) return refuse$1(`not a release tag: ${JSON.stringify(tag)}`);
|
|
500
|
+
return {
|
|
501
|
+
ok: true,
|
|
502
|
+
source: {
|
|
503
|
+
kind: "github",
|
|
504
|
+
owner,
|
|
505
|
+
repo,
|
|
506
|
+
tag
|
|
507
|
+
}
|
|
508
|
+
};
|
|
509
|
+
}
|
|
510
|
+
function parseFile(rest) {
|
|
511
|
+
if (rest === "") return refuse$1("a file: source names no file");
|
|
512
|
+
if (rest.includes("\0")) return refuse$1("a file: source contains a NUL byte");
|
|
513
|
+
if (!path.isAbsolute(rest)) return refuse$1(`a file: source must be an absolute path: ${JSON.stringify(rest)}`);
|
|
514
|
+
if (!rest.endsWith(PACKAGE_FILE_SUFFIX)) return refuse$1(`a file: source must name a ${PACKAGE_FILE_SUFFIX} package file: ${JSON.stringify(rest)}`);
|
|
515
|
+
return {
|
|
516
|
+
ok: true,
|
|
517
|
+
source: {
|
|
518
|
+
kind: "file",
|
|
519
|
+
path: path.normalize(rest)
|
|
520
|
+
}
|
|
521
|
+
};
|
|
522
|
+
}
|
|
523
|
+
function parseInstallSource(input) {
|
|
524
|
+
if (typeof input !== "string") return refuse$1("an install source is a string");
|
|
525
|
+
const trimmed = input.trim();
|
|
526
|
+
if (trimmed === "") return refuse$1("an install source is empty");
|
|
527
|
+
if (trimmed.startsWith(GITHUB_PREFIX)) return parseGithub(trimmed.slice(7));
|
|
528
|
+
if (trimmed.startsWith(FILE_PREFIX)) return parseFile(trimmed.slice(5));
|
|
529
|
+
return parseNpm(trimmed);
|
|
530
|
+
}
|
|
531
|
+
/** The ledger's `source` field for what was actually installed: the resolved version or tag. */
|
|
532
|
+
function sourceLabel(source, resolved) {
|
|
533
|
+
if (source.kind === "npm") return `npm:${source.name}@${resolved}`;
|
|
534
|
+
if (source.kind === "github") return `github:${source.owner}/${source.repo}#${resolved}`;
|
|
535
|
+
return `${FILE_PREFIX}${source.path}`;
|
|
536
|
+
}
|
|
537
|
+
/** The file name `npm pack` gives the package — `@scope/name` 1.2.3 → `scope-name-1.2.3.tgz`. */
|
|
538
|
+
var packageFileName = (name, version) => `${name.replace(/^@/, "").replaceAll("/", "-")}-${version}.tgz`;
|
|
539
|
+
var CONTENT_ID_LENGTH = 12;
|
|
540
|
+
/** `npm pack`'s name with a short hash of the bytes before `.tgz` — `scope-name-1.2.3-0123456789ab.tgz`.
|
|
541
|
+
* Two different packages with one name and version (a GitHub tag published again) then get different
|
|
542
|
+
* files. The hash is short, so the install also refuses to write over an existing file whose bytes
|
|
543
|
+
* differ: that is what keeps a file an entry points at from changing. */
|
|
544
|
+
var installedFileName = (name, version, sha256Hex) => packageFileName(name, version).replace(/\.tgz$/, `-${sha256Hex.slice(0, CONTENT_ID_LENGTH)}.tgz`);
|
|
545
|
+
// src/runtime-plugins/ledgerWrite.ts
|
|
546
|
+
var isEntryNamed = (value, name) => isRecord(value) && Object.hasOwn(value, "name") && value.name === name;
|
|
547
|
+
/** The ledger with `entry` in it, exactly once: it takes the place of the first entry of the same
|
|
548
|
+
* name, any further ones are dropped (each would load another copy), and with none it is appended. */
|
|
549
|
+
function withLedgerEntry(raw, entry) {
|
|
550
|
+
const first = raw.findIndex((value) => isEntryNamed(value, entry.name));
|
|
551
|
+
if (first === -1) return [...raw, entry];
|
|
552
|
+
return raw.flatMap((value, index) => {
|
|
553
|
+
if (index === first) return [entry];
|
|
554
|
+
return isEntryNamed(value, entry.name) ? [] : [value];
|
|
555
|
+
});
|
|
556
|
+
}
|
|
557
|
+
/** The ledger without any entry named `name`; everything else is kept as it was. */
|
|
558
|
+
var withoutLedgerEntry = (raw, name) => raw.filter((value) => !isEntryNamed(value, name));
|
|
559
|
+
async function readLedgerText(ledgerPath) {
|
|
560
|
+
try {
|
|
561
|
+
return {
|
|
562
|
+
ok: true,
|
|
563
|
+
text: await readFile(ledgerPath, "utf-8")
|
|
564
|
+
};
|
|
565
|
+
} catch (err) {
|
|
566
|
+
if (isRecord(err) && err.code === "ENOENT") return {
|
|
567
|
+
ok: true,
|
|
568
|
+
text: null
|
|
569
|
+
};
|
|
570
|
+
return {
|
|
571
|
+
ok: false,
|
|
572
|
+
error: `cannot read the plugin ledger ${ledgerPath}: ${String(err)}`
|
|
573
|
+
};
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
function parseLedgerText(ledgerPath, text) {
|
|
577
|
+
try {
|
|
578
|
+
const parsed = JSON.parse(text);
|
|
579
|
+
return Array.isArray(parsed) ? {
|
|
580
|
+
ok: true,
|
|
581
|
+
raw: parsed
|
|
582
|
+
} : {
|
|
583
|
+
ok: false,
|
|
584
|
+
error: `the plugin ledger ${ledgerPath} is not a JSON array; fix it before installing`
|
|
585
|
+
};
|
|
586
|
+
} catch (err) {
|
|
587
|
+
return {
|
|
588
|
+
ok: false,
|
|
589
|
+
error: `the plugin ledger ${ledgerPath} is not valid JSON; fix it before installing: ${String(err)}`
|
|
590
|
+
};
|
|
591
|
+
}
|
|
592
|
+
}
|
|
593
|
+
/** The ledger as an array to edit: a missing file is an empty ledger; a file that is not a JSON
|
|
594
|
+
* array is refused rather than overwritten, since writing over it would lose what the user wrote. */
|
|
595
|
+
async function readLedgerForWrite(ledgerPath) {
|
|
596
|
+
const read = await readLedgerText(ledgerPath);
|
|
597
|
+
if (!read.ok) return read;
|
|
598
|
+
return read.text === null ? {
|
|
599
|
+
ok: true,
|
|
600
|
+
raw: []
|
|
601
|
+
} : parseLedgerText(ledgerPath, read.text);
|
|
602
|
+
}
|
|
603
|
+
var writeLedger = (ledgerPath, raw) => writeJsonAtomic(ledgerPath, raw);
|
|
604
|
+
// src/runtime-plugins/download.ts
|
|
605
|
+
var DownloadError = class extends Error {};
|
|
606
|
+
async function readCapped(body, url, maxBytes, signal) {
|
|
607
|
+
const reader = body.getReader();
|
|
608
|
+
const onAbort = () => {
|
|
609
|
+
reader.cancel(signal.reason).catch(() => void 0);
|
|
610
|
+
};
|
|
611
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
612
|
+
try {
|
|
613
|
+
return await collectChunks(reader, url, maxBytes, signal);
|
|
614
|
+
} finally {
|
|
615
|
+
signal.removeEventListener("abort", onAbort);
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
async function collectChunks(reader, url, maxBytes, signal) {
|
|
619
|
+
const chunks = [];
|
|
620
|
+
let received = 0;
|
|
621
|
+
for (;;) {
|
|
622
|
+
const { done, value } = await reader.read();
|
|
623
|
+
if (signal.aborted) throw signal.reason;
|
|
624
|
+
if (done) return Buffer.concat(chunks);
|
|
625
|
+
received += value.byteLength;
|
|
626
|
+
if (received > maxBytes) {
|
|
627
|
+
reader.cancel().catch(() => void 0);
|
|
628
|
+
throw new DownloadError(`${url} is larger than ${maxBytes} bytes`);
|
|
629
|
+
}
|
|
630
|
+
chunks.push(value);
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
/** The response's body once it is known to be a success within the cap. */
|
|
634
|
+
function refuseResponse(res, message) {
|
|
635
|
+
res.body?.cancel().catch(() => void 0);
|
|
636
|
+
throw new DownloadError(message);
|
|
637
|
+
}
|
|
638
|
+
function acceptedBody(res, url, maxBytes) {
|
|
639
|
+
if (!res.ok) refuseResponse(res, `${url} answered HTTP ${res.status}`);
|
|
640
|
+
const declared = Number(res.headers.get("content-length"));
|
|
641
|
+
if (Number.isFinite(declared) && declared > maxBytes) refuseResponse(res, `${url} is ${declared} bytes, more than ${maxBytes}`);
|
|
642
|
+
if (!res.body) throw new DownloadError(`${url} answered with no body`);
|
|
643
|
+
return res.body;
|
|
644
|
+
}
|
|
645
|
+
function settlesByDeadline(pending, signal) {
|
|
646
|
+
return new Promise((resolve, reject) => {
|
|
647
|
+
const onAbort = () => reject(signal.reason);
|
|
648
|
+
if (signal.aborted) onAbort();
|
|
649
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
650
|
+
pending.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
|
|
651
|
+
});
|
|
652
|
+
}
|
|
653
|
+
async function downloadBytes(fetchFn, url, headers, limits) {
|
|
654
|
+
const controller = new AbortController();
|
|
655
|
+
const timer = setTimeout(() => controller.abort(new DownloadError(`${url} did not finish within ${limits.timeoutMs}ms`)), limits.timeoutMs);
|
|
656
|
+
try {
|
|
657
|
+
return await readCapped(acceptedBody(await settlesByDeadline(fetchFn(url, {
|
|
658
|
+
headers,
|
|
659
|
+
signal: controller.signal,
|
|
660
|
+
redirect: "follow"
|
|
661
|
+
}), controller.signal), url, limits.maxBytes), url, limits.maxBytes, controller.signal);
|
|
662
|
+
} catch (err) {
|
|
663
|
+
if (err instanceof DownloadError) throw err;
|
|
664
|
+
const reason = controller.signal.aborted ? controller.signal.reason : err;
|
|
665
|
+
throw reason instanceof DownloadError ? reason : new DownloadError(`${url} could not be downloaded: ${String(reason)}`);
|
|
666
|
+
} finally {
|
|
667
|
+
clearTimeout(timer);
|
|
668
|
+
}
|
|
669
|
+
}
|
|
670
|
+
async function downloadJson(fetchFn, url, headers, limits) {
|
|
671
|
+
const bytes = await downloadBytes(fetchFn, url, headers, limits);
|
|
672
|
+
try {
|
|
673
|
+
return JSON.parse(bytes.toString("utf-8"));
|
|
674
|
+
} catch {
|
|
675
|
+
throw new DownloadError(`${url} did not answer with JSON`);
|
|
676
|
+
}
|
|
677
|
+
}
|
|
678
|
+
var SRI = /^(sha512|sha384|sha256)-([A-Za-z0-9+/=]+)$/;
|
|
679
|
+
/** Whether `bytes` match an npm `dist.integrity` (Subresource Integrity, possibly several space-
|
|
680
|
+
* separated hashes) — the strongest algorithm present must match. False when none is recognised. */
|
|
681
|
+
function matchesIntegrity(bytes, integrity) {
|
|
682
|
+
const hashes = integrity.split(/\s+/).map((part) => SRI.exec(part)).filter((match) => match !== null);
|
|
683
|
+
const strongest = [
|
|
684
|
+
"sha512",
|
|
685
|
+
"sha384",
|
|
686
|
+
"sha256"
|
|
687
|
+
].find((algorithm) => hashes.some((match) => match[1] === algorithm));
|
|
688
|
+
if (strongest === void 0) return false;
|
|
689
|
+
const actual = createHash(strongest).update(bytes).digest("base64");
|
|
690
|
+
return hashes.some((match) => match[1] === strongest && match[2] === actual);
|
|
691
|
+
}
|
|
692
|
+
// src/runtime-plugins/fetchPackage.ts
|
|
693
|
+
var NPM_REGISTRY = "https://registry.npmjs.org";
|
|
694
|
+
var GITHUB_API = "https://api.github.com";
|
|
695
|
+
var ONE_SECOND_MS = 1e3;
|
|
696
|
+
var ONE_MIB$1 = 1048576;
|
|
697
|
+
var METADATA_LIMITS = {
|
|
698
|
+
timeoutMs: 30 * ONE_SECOND_MS,
|
|
699
|
+
maxBytes: 32 * ONE_MIB$1
|
|
700
|
+
};
|
|
701
|
+
var PACKAGE_LIMITS = {
|
|
702
|
+
timeoutMs: 120 * ONE_SECOND_MS,
|
|
703
|
+
maxBytes: 50 * ONE_MIB$1
|
|
704
|
+
};
|
|
705
|
+
var USER_AGENT = "mulmo-runtime-plugins";
|
|
706
|
+
var stringOrNull = (value) => typeof value === "string" ? value : null;
|
|
707
|
+
var fail = (error) => ({
|
|
708
|
+
ok: false,
|
|
709
|
+
error
|
|
710
|
+
});
|
|
711
|
+
var isHttpsUrl = (value) => value.startsWith("https://");
|
|
712
|
+
function resolveNpmVersion(packument, versions, spec) {
|
|
713
|
+
const tags = isRecord(packument["dist-tags"]) ? packument["dist-tags"] : {};
|
|
714
|
+
if (spec !== null && Object.hasOwn(versions, spec)) return {
|
|
715
|
+
ok: true,
|
|
716
|
+
value: spec
|
|
717
|
+
};
|
|
718
|
+
const tag = spec ?? "latest";
|
|
719
|
+
const fromTag = Object.hasOwn(tags, tag) ? stringOrNull(tags[tag]) : null;
|
|
720
|
+
if (fromTag !== null) return {
|
|
721
|
+
ok: true,
|
|
722
|
+
value: fromTag
|
|
723
|
+
};
|
|
724
|
+
return fail(spec === null ? "the package has no latest version" : `no version or dist-tag ${JSON.stringify(spec)}`);
|
|
725
|
+
}
|
|
726
|
+
function releaseOf(versions, version) {
|
|
727
|
+
const entry = Object.hasOwn(versions, version) ? versions[version] : void 0;
|
|
728
|
+
const dist = isRecord(entry) && isRecord(entry.dist) ? entry.dist : null;
|
|
729
|
+
const tarball = dist ? stringOrNull(dist.tarball) : null;
|
|
730
|
+
if (dist === null || tarball === null || !isHttpsUrl(tarball)) return fail(`version ${version} has no https tarball`);
|
|
731
|
+
return {
|
|
732
|
+
ok: true,
|
|
733
|
+
value: {
|
|
734
|
+
version,
|
|
735
|
+
tarball,
|
|
736
|
+
integrity: stringOrNull(dist.integrity)
|
|
737
|
+
}
|
|
738
|
+
};
|
|
739
|
+
}
|
|
740
|
+
/** The version a packument resolves `spec` to — exact, a dist-tag, or `latest` when absent. */
|
|
741
|
+
function resolveNpmRelease(packument, spec) {
|
|
742
|
+
if (!isRecord(packument) || !isRecord(packument.versions)) return fail("the registry did not answer with a package");
|
|
743
|
+
const version = resolveNpmVersion(packument, packument.versions, spec);
|
|
744
|
+
return version.ok ? releaseOf(packument.versions, version.value) : version;
|
|
745
|
+
}
|
|
746
|
+
/** Whether the downloaded bytes are the ones the registry published, by its strongest hash. */
|
|
747
|
+
function verifyNpmBytes(bytes, release) {
|
|
748
|
+
if (release.integrity === null) return `the registry publishes no sha512/sha384/sha256 integrity for ${release.version}, so the tarball cannot be checked`;
|
|
749
|
+
return matchesIntegrity(bytes, release.integrity) ? null : `the tarball does not match the registry's integrity for ${release.version}`;
|
|
750
|
+
}
|
|
751
|
+
var assetsOf = (release) => Array.isArray(release.assets) ? release.assets.filter(isRecord) : [];
|
|
752
|
+
/** The release's one `.tgz` asset. None, or several, is refused: guessing which file is the plugin
|
|
753
|
+
* is exactly what a user should not have to trust. */
|
|
754
|
+
function resolveGithubAsset(release) {
|
|
755
|
+
if (!isRecord(release) || typeof release.tag_name !== "string") return fail("GitHub did not answer with a release");
|
|
756
|
+
const assets = assetsOf(release);
|
|
757
|
+
const tgz = assets.filter((asset) => typeof asset.name === "string" && asset.name.endsWith(".tgz"));
|
|
758
|
+
const names = assets.map((asset) => String(asset.name)).join(", ") || "none";
|
|
759
|
+
if (tgz.length !== 1) return fail(`release ${release.tag_name} has ${tgz.length} .tgz assets (assets: ${names}); exactly one is needed`);
|
|
760
|
+
const [asset] = tgz;
|
|
761
|
+
const downloadUrl = stringOrNull(asset?.browser_download_url);
|
|
762
|
+
const apiUrl = stringOrNull(asset?.url);
|
|
763
|
+
if (downloadUrl === null || apiUrl === null || !isHttpsUrl(downloadUrl) || !isHttpsUrl(apiUrl)) return fail(`release ${release.tag_name}'s .tgz asset has no https download URL`);
|
|
764
|
+
return {
|
|
765
|
+
ok: true,
|
|
766
|
+
value: {
|
|
767
|
+
tag: release.tag_name,
|
|
768
|
+
name: String(asset?.name),
|
|
769
|
+
downloadUrl,
|
|
770
|
+
apiUrl,
|
|
771
|
+
digest: stringOrNull(asset?.digest)
|
|
772
|
+
}
|
|
773
|
+
};
|
|
774
|
+
}
|
|
775
|
+
var SHA256_DIGEST = /^sha256:([0-9a-f]{64})$/;
|
|
776
|
+
/** Whether the bytes are the asset GitHub recorded. An asset with no digest is accepted — older
|
|
777
|
+
* uploads carry none, and the bytes still came over https from GitHub — but a digest that is present
|
|
778
|
+
* must be a sha256 and must match. */
|
|
779
|
+
function verifyGithubBytes(bytes, asset) {
|
|
780
|
+
if (asset.digest === null) return null;
|
|
781
|
+
const expected = SHA256_DIGEST.exec(asset.digest.toLowerCase())?.[1];
|
|
782
|
+
if (expected === void 0) return `release ${asset.tag}'s asset has an unrecognised digest ${JSON.stringify(asset.digest)}`;
|
|
783
|
+
return createHash("sha256").update(bytes).digest("hex") === expected ? null : `the asset does not match GitHub's recorded digest for ${asset.tag}`;
|
|
784
|
+
}
|
|
785
|
+
function httpsBase(base, what) {
|
|
786
|
+
if (!isHttpsUrl(base)) throw new DownloadError(`${what} must be an https URL, not ${JSON.stringify(base)}`);
|
|
787
|
+
return base.endsWith("/") ? base.slice(0, -1) : base;
|
|
788
|
+
}
|
|
789
|
+
var packumentUrl = (registry, name) => `${registry}/${name.replaceAll("/", "%2f")}`;
|
|
790
|
+
async function fetchNpm(source, deps) {
|
|
791
|
+
const accept = {
|
|
792
|
+
accept: "application/vnd.npm.install-v1+json",
|
|
793
|
+
"user-agent": USER_AGENT
|
|
794
|
+
};
|
|
795
|
+
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);
|
|
796
|
+
if (!resolved.ok) throw new DownloadError(`${source.name}: ${resolved.error}`);
|
|
797
|
+
const release = resolved.value;
|
|
798
|
+
const bytes = await downloadBytes(deps.fetch, release.tarball, { "user-agent": USER_AGENT }, PACKAGE_LIMITS);
|
|
799
|
+
const mismatch = verifyNpmBytes(bytes, release);
|
|
800
|
+
if (mismatch !== null) throw new DownloadError(`${source.name}: ${mismatch}`);
|
|
801
|
+
return {
|
|
802
|
+
bytes,
|
|
803
|
+
resolved: release.version
|
|
804
|
+
};
|
|
805
|
+
}
|
|
806
|
+
function githubHeaders(deps, accept) {
|
|
807
|
+
const headers = {
|
|
808
|
+
accept,
|
|
809
|
+
"user-agent": USER_AGENT
|
|
810
|
+
};
|
|
811
|
+
if (deps.githubToken) headers.authorization = `Bearer ${deps.githubToken}`;
|
|
812
|
+
return headers;
|
|
813
|
+
}
|
|
814
|
+
function assetUrl(asset, deps, apiBase) {
|
|
815
|
+
if (!deps.githubToken) return asset.downloadUrl;
|
|
816
|
+
if (new URL(asset.apiUrl).origin !== new URL(apiBase).origin) throw new DownloadError(`release ${asset.tag}'s asset URL is not on ${apiBase}`);
|
|
817
|
+
return asset.apiUrl;
|
|
818
|
+
}
|
|
819
|
+
async function fetchGithub(source, deps) {
|
|
820
|
+
const repo = `${encodeURIComponent(source.owner)}/${encodeURIComponent(source.repo)}`;
|
|
821
|
+
const which = source.tag === null ? "latest" : `tags/${encodeURIComponent(source.tag)}`;
|
|
822
|
+
const apiBase = httpsBase(deps.githubApi ?? "https://api.github.com", "the GitHub API");
|
|
823
|
+
const releaseUrl = `${apiBase}/repos/${repo}/releases/${which}`;
|
|
824
|
+
const resolved = resolveGithubAsset(await downloadJson(deps.fetch, releaseUrl, githubHeaders(deps, "application/vnd.github+json"), METADATA_LIMITS));
|
|
825
|
+
if (!resolved.ok) throw new DownloadError(`${source.owner}/${source.repo}: ${resolved.error}`);
|
|
826
|
+
const asset = resolved.value;
|
|
827
|
+
const bytes = await downloadBytes(deps.fetch, assetUrl(asset, deps, apiBase), githubHeaders(deps, "application/octet-stream"), PACKAGE_LIMITS);
|
|
828
|
+
const mismatch = verifyGithubBytes(bytes, asset);
|
|
829
|
+
if (mismatch !== null) throw new DownloadError(`${source.owner}/${source.repo}: ${mismatch}`);
|
|
830
|
+
return {
|
|
831
|
+
bytes,
|
|
832
|
+
resolved: asset.tag
|
|
833
|
+
};
|
|
834
|
+
}
|
|
835
|
+
var errorCode = (err) => err instanceof Error && "code" in err && typeof err.code === "string" ? err.code : String(err);
|
|
836
|
+
var READ_FLAGS = constants$1.O_RDONLY | (constants$1.O_NONBLOCK ?? 0);
|
|
837
|
+
var READ_CHUNK_BYTES = 65536;
|
|
838
|
+
/** Reads to the end, refusing as soon as more than `maxBytes` arrive: never holds more than one chunk past it.
|
|
839
|
+
* Once `signal` aborts, no further read is started. */
|
|
840
|
+
async function readAtMost(reader, maxBytes, what, signal) {
|
|
841
|
+
const chunks = [];
|
|
842
|
+
let received = 0;
|
|
843
|
+
for (;;) {
|
|
844
|
+
if (signal?.aborted) throw new DownloadError(`${what}: reading stopped at the deadline`);
|
|
845
|
+
const chunk = Buffer.alloc(READ_CHUNK_BYTES);
|
|
846
|
+
const { bytesRead } = await reader.read(chunk, 0, READ_CHUNK_BYTES, null);
|
|
847
|
+
if (bytesRead === 0) return Buffer.concat(chunks, received);
|
|
848
|
+
received += bytesRead;
|
|
849
|
+
if (received > maxBytes) throw new DownloadError(`${what} is larger than ${maxBytes} bytes`);
|
|
850
|
+
chunks.push(chunk.subarray(0, bytesRead));
|
|
851
|
+
}
|
|
852
|
+
}
|
|
853
|
+
/** Rejects with a DownloadError once `timeoutMs` pass, and aborts the signal `work` was given so it starts
|
|
854
|
+
* nothing more. A read already stuck in the kernel cannot be cancelled from Node — closing its handle waits
|
|
855
|
+
* for it — so at most that one read stays in flight, and its handle closes once it returns. */
|
|
856
|
+
function withDeadline(work, timeoutMs, what) {
|
|
857
|
+
const controller = new AbortController();
|
|
858
|
+
let timer;
|
|
859
|
+
const late = new Promise((_resolve, reject) => {
|
|
860
|
+
timer = setTimeout(() => {
|
|
861
|
+
controller.abort();
|
|
862
|
+
reject(new DownloadError(`${what} took longer than ${timeoutMs} ms to read`));
|
|
863
|
+
}, timeoutMs);
|
|
864
|
+
});
|
|
865
|
+
return Promise.race([work(controller.signal), late]).finally(() => clearTimeout(timer));
|
|
866
|
+
}
|
|
867
|
+
async function readPackageFile(file, maxBytes, signal) {
|
|
868
|
+
const handle = await open(file, READ_FLAGS).catch((err) => {
|
|
869
|
+
throw new DownloadError(`${file} could not be read (${errorCode(err)})`);
|
|
870
|
+
});
|
|
871
|
+
try {
|
|
872
|
+
const info = await handle.stat();
|
|
873
|
+
if (!info.isFile()) throw new DownloadError(`${file} is not a file`);
|
|
874
|
+
if (info.size > maxBytes) throw new DownloadError(`${file} is larger than ${maxBytes} bytes`);
|
|
875
|
+
return await readAtMost(handle, maxBytes, file, signal);
|
|
876
|
+
} finally {
|
|
877
|
+
await handle.close().catch(() => void 0);
|
|
878
|
+
}
|
|
879
|
+
}
|
|
880
|
+
async function fetchFile(source) {
|
|
881
|
+
return {
|
|
882
|
+
bytes: await withDeadline((signal) => readPackageFile(source.path, PACKAGE_LIMITS.maxBytes, signal), PACKAGE_LIMITS.timeoutMs, source.path),
|
|
883
|
+
resolved: source.path
|
|
884
|
+
};
|
|
885
|
+
}
|
|
886
|
+
function fetchPackage(source, deps) {
|
|
887
|
+
if (source.kind === "npm") return fetchNpm(source, deps);
|
|
888
|
+
if (source.kind === "github") return fetchGithub(source, deps);
|
|
889
|
+
return fetchFile(source);
|
|
890
|
+
}
|
|
891
|
+
// src/runtime-plugins/inspect.ts
|
|
892
|
+
var TEMP_PREFIX = ".inspect-";
|
|
893
|
+
var MAX_UNPACKED_BYTES = 268435456;
|
|
894
|
+
/** Whether the gzip stream expands to at most `maxBytes`, counted while it is inflated so a hostile
|
|
895
|
+
* archive is stopped at the limit rather than after it has been written out. */
|
|
896
|
+
function inflatesWithin(bytes, maxBytes) {
|
|
897
|
+
return new Promise((resolve, reject) => {
|
|
898
|
+
const gunzip = createGunzip();
|
|
899
|
+
let inflated = 0;
|
|
900
|
+
gunzip.on("data", (chunk) => {
|
|
901
|
+
inflated += chunk.length;
|
|
902
|
+
if (inflated <= maxBytes) return;
|
|
903
|
+
gunzip.destroy();
|
|
904
|
+
resolve(false);
|
|
905
|
+
});
|
|
906
|
+
gunzip.on("end", () => resolve(true));
|
|
907
|
+
gunzip.on("error", reject);
|
|
908
|
+
gunzip.end(bytes);
|
|
909
|
+
});
|
|
910
|
+
}
|
|
911
|
+
var UNPARSABLE = Symbol("unparsable");
|
|
912
|
+
function parseJsonFile(file) {
|
|
913
|
+
try {
|
|
914
|
+
return JSON.parse(readFileSync(file, "utf-8"));
|
|
915
|
+
} catch {
|
|
916
|
+
return UNPARSABLE;
|
|
917
|
+
}
|
|
918
|
+
}
|
|
919
|
+
var refuse = (error) => ({
|
|
920
|
+
ok: false,
|
|
921
|
+
error
|
|
922
|
+
});
|
|
923
|
+
function readPackage(dir) {
|
|
924
|
+
const outward = linkLeadingOut(dir);
|
|
925
|
+
if (outward !== null) return refuse(`the package holds a link that leads outside it: ${outward}`);
|
|
926
|
+
const pkgPath = path.join(dir, "package.json");
|
|
927
|
+
if (!existsSync(pkgPath)) return refuse("the package has no package.json");
|
|
928
|
+
const parsed = parseJsonFile(pkgPath);
|
|
929
|
+
if (parsed === UNPARSABLE) return refuse("the package's package.json is not valid JSON");
|
|
930
|
+
const pkg = toPackageJson(parsed);
|
|
931
|
+
if (pkg?.name === void 0 || pkg.version === void 0) return refuse("the package's package.json has no name or version");
|
|
932
|
+
const entrySpec = resolveEntrySpecifier(pkg);
|
|
933
|
+
if (entrySpec === null) return refuse("the package's package.json names no server entry (exports, module or main)");
|
|
934
|
+
const entryAbs = path.join(dir, entrySpec);
|
|
935
|
+
if (!ensureInsideBase(entryAbs, dir) || !resolvesInside(entryAbs, dir)) return refuse(`the package's server entry ${entrySpec} is not in it`);
|
|
936
|
+
if (!statSync(entryAbs).isFile()) return refuse(`the package's server entry ${entrySpec} is not a file`);
|
|
937
|
+
return {
|
|
938
|
+
ok: true,
|
|
939
|
+
value: {
|
|
940
|
+
name: pkg.name,
|
|
941
|
+
version: pkg.version,
|
|
942
|
+
entrySpec
|
|
943
|
+
}
|
|
944
|
+
};
|
|
945
|
+
}
|
|
946
|
+
/** What the package file says it is, or why it is not a package this loader can use. */
|
|
947
|
+
async function inspectPackage(bytes, pluginsDir) {
|
|
948
|
+
const withinLimit = await inflatesWithin(bytes, MAX_UNPACKED_BYTES).catch(() => null);
|
|
949
|
+
if (withinLimit === null) return refuse("the file is not a gzip package");
|
|
950
|
+
if (!withinLimit) return refuse(`the package expands to more than ${MAX_UNPACKED_BYTES} bytes`);
|
|
951
|
+
const work = await mkdtemp(path.join(pluginsDir, TEMP_PREFIX));
|
|
952
|
+
try {
|
|
953
|
+
const tgz = path.join(work, "package.tgz");
|
|
954
|
+
await writeFile(tgz, bytes);
|
|
955
|
+
const unpacked = path.join(work, "unpacked");
|
|
956
|
+
try {
|
|
957
|
+
extractTgz(tgz, unpacked);
|
|
958
|
+
} catch (err) {
|
|
959
|
+
return refuse(`the file could not be unpacked as a package: ${String(err)}`);
|
|
960
|
+
}
|
|
961
|
+
return readPackage(unpacked);
|
|
962
|
+
} finally {
|
|
963
|
+
await rm(work, {
|
|
964
|
+
recursive: true,
|
|
965
|
+
force: true
|
|
966
|
+
});
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
// src/runtime-plugins/install.ts
|
|
970
|
+
var InstallError = class extends Error {};
|
|
971
|
+
function checkIdentity(source, resolved, name, version) {
|
|
972
|
+
if (!isNpmPackageName(name)) throw new InstallError(`the package's name ${JSON.stringify(name)} is not an npm package name`);
|
|
973
|
+
if (!isExactVersion(version)) throw new InstallError(`the package's version ${JSON.stringify(version)} is not an exact version`);
|
|
974
|
+
if (source.kind !== "npm") return;
|
|
975
|
+
if (name !== source.name) throw new InstallError(`asked for ${source.name}, but the package is ${name}`);
|
|
976
|
+
if (version !== resolved) throw new InstallError(`asked for ${source.name}@${resolved}, but the package is version ${version}`);
|
|
977
|
+
}
|
|
978
|
+
async function preparePlan(source, deps) {
|
|
979
|
+
await mkdir(deps.paths.pluginsDir, { recursive: true });
|
|
980
|
+
const ledger = await readLedgerForWrite(deps.paths.ledgerPath);
|
|
981
|
+
if (!ledger.ok) throw new InstallError(ledger.error);
|
|
982
|
+
const fetched = await fetchPackage(source, deps);
|
|
983
|
+
const inspection = await inspectPackage(fetched.bytes, deps.paths.pluginsDir);
|
|
984
|
+
if (!inspection.ok) throw new InstallError(inspection.error);
|
|
985
|
+
const inspected = inspection.value;
|
|
986
|
+
checkIdentity(source, fetched.resolved, inspected.name, inspected.version);
|
|
987
|
+
const replaces = parseLedger(ledger.raw).find((entry) => entry.name === inspected.name) ?? null;
|
|
988
|
+
const tgz = installedFileName(inspected.name, inspected.version, createHash("sha256").update(fetched.bytes).digest("hex"));
|
|
989
|
+
return {
|
|
990
|
+
plan: {
|
|
991
|
+
name: inspected.name,
|
|
992
|
+
version: inspected.version,
|
|
993
|
+
source: sourceLabel(source, fetched.resolved),
|
|
994
|
+
tgz,
|
|
995
|
+
replaces
|
|
996
|
+
},
|
|
997
|
+
bytes: fetched.bytes,
|
|
998
|
+
raw: ledger.raw
|
|
999
|
+
};
|
|
1000
|
+
}
|
|
1001
|
+
async function dropStaleCache(plan, raw, paths) {
|
|
1002
|
+
const sameVersion = parseLedger(raw).filter((entry) => entry.name === plan.name && entry.version === plan.version);
|
|
1003
|
+
if (sameVersion.length > 0 && sameVersion.every((entry) => entry.tgz === plan.tgz)) return;
|
|
1004
|
+
const cacheDir = paths.cacheDir ?? path.join(paths.pluginsDir, ".cache");
|
|
1005
|
+
const stale = path.join(cacheDir, plan.name, plan.version);
|
|
1006
|
+
if (ensureInsideBase(stale, cacheDir)) await rm(stale, {
|
|
1007
|
+
recursive: true,
|
|
1008
|
+
force: true
|
|
1009
|
+
});
|
|
1010
|
+
}
|
|
1011
|
+
async function writePackageFile(plan, bytes, pluginsDir) {
|
|
1012
|
+
const tgzPath = path.join(pluginsDir, plan.tgz);
|
|
1013
|
+
const fileWasThere = existsSync(tgzPath);
|
|
1014
|
+
if (fileWasThere && !(await readFile(tgzPath)).equals(bytes)) throw new InstallError(`${plan.tgz} already exists with different bytes; not overwritten`);
|
|
1015
|
+
if (!fileWasThere) await writeFileAtomic(tgzPath, bytes);
|
|
1016
|
+
return {
|
|
1017
|
+
tgzPath,
|
|
1018
|
+
fileWasThere
|
|
1019
|
+
};
|
|
1020
|
+
}
|
|
1021
|
+
async function commit(plan, bytes, raw, deps) {
|
|
1022
|
+
const { tgzPath, fileWasThere } = await writePackageFile(plan, bytes, deps.paths.pluginsDir);
|
|
1023
|
+
const installedAt = (deps.now ?? (() => /* @__PURE__ */ new Date()))().toISOString();
|
|
1024
|
+
const entry = {
|
|
1025
|
+
name: plan.name,
|
|
1026
|
+
version: plan.version,
|
|
1027
|
+
tgz: plan.tgz,
|
|
1028
|
+
installedAt,
|
|
1029
|
+
source: plan.source
|
|
1030
|
+
};
|
|
1031
|
+
try {
|
|
1032
|
+
await dropStaleCache(plan, raw, deps.paths);
|
|
1033
|
+
await writeLedger(deps.paths.ledgerPath, withLedgerEntry(raw, entry));
|
|
1034
|
+
} catch (err) {
|
|
1035
|
+
if (!fileWasThere) await rm(tgzPath, { force: true });
|
|
1036
|
+
throw err;
|
|
1037
|
+
}
|
|
1038
|
+
return entry;
|
|
1039
|
+
}
|
|
1040
|
+
var failure = (err, action) => {
|
|
1041
|
+
if (err instanceof InstallError || err instanceof DownloadError) return {
|
|
1042
|
+
status: "failed",
|
|
1043
|
+
error: err.message
|
|
1044
|
+
};
|
|
1045
|
+
return {
|
|
1046
|
+
status: "failed",
|
|
1047
|
+
error: `${action} failed: ${err instanceof Error ? err.message : String(err)}`
|
|
1048
|
+
};
|
|
1049
|
+
};
|
|
1050
|
+
/** Install what `input` names (`<npm name>[@<version or dist-tag>]`, `github:<owner>/<repo>[#<tag>]`, or `file:<absolute path>.tgz`). */
|
|
1051
|
+
async function installRuntimePlugin(input, deps) {
|
|
1052
|
+
const parsed = parseInstallSource(input);
|
|
1053
|
+
if (!parsed.ok) return {
|
|
1054
|
+
status: "failed",
|
|
1055
|
+
error: parsed.error
|
|
1056
|
+
};
|
|
1057
|
+
try {
|
|
1058
|
+
const { plan, bytes, raw } = await preparePlan(parsed.source, deps);
|
|
1059
|
+
if (!await deps.confirm(plan)) return {
|
|
1060
|
+
status: "cancelled",
|
|
1061
|
+
plan
|
|
1062
|
+
};
|
|
1063
|
+
return {
|
|
1064
|
+
status: "installed",
|
|
1065
|
+
entry: await commit(plan, bytes, raw, deps),
|
|
1066
|
+
replaced: plan.replaces
|
|
1067
|
+
};
|
|
1068
|
+
} catch (err) {
|
|
1069
|
+
return failure(err, "install");
|
|
1070
|
+
}
|
|
1071
|
+
}
|
|
1072
|
+
/** Take `name` out of the ledger. Its package file, unpacked copy and data folders are left in place. */
|
|
1073
|
+
async function uninstallRuntimePlugin(name, paths) {
|
|
1074
|
+
const ledger = await readLedgerForWrite(paths.ledgerPath);
|
|
1075
|
+
if (!ledger.ok) return {
|
|
1076
|
+
status: "failed",
|
|
1077
|
+
error: ledger.error
|
|
1078
|
+
};
|
|
1079
|
+
const entry = parseLedger(ledger.raw).find((candidate) => candidate.name === name) ?? null;
|
|
1080
|
+
const remaining = withoutLedgerEntry(ledger.raw, name);
|
|
1081
|
+
if (remaining.length === ledger.raw.length) return { status: "not-installed" };
|
|
1082
|
+
try {
|
|
1083
|
+
await writeLedger(paths.ledgerPath, remaining);
|
|
1084
|
+
} catch (err) {
|
|
1085
|
+
return failure(err, "uninstall");
|
|
1086
|
+
}
|
|
1087
|
+
return {
|
|
1088
|
+
status: "removed",
|
|
1089
|
+
entry
|
|
1090
|
+
};
|
|
1091
|
+
}
|
|
1092
|
+
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 };
|
|
315
1093
|
|
|
316
1094
|
//# sourceMappingURL=index.js.map
|