@mostra/runtime 0.14.0 → 0.15.1

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 (61) hide show
  1. package/dist/bin.js +1 -1
  2. package/dist/child-protocol-CPXR6pMu.js +13 -0
  3. package/dist/child-protocol-CPXR6pMu.js.map +1 -0
  4. package/dist/index.d.ts.map +1 -1
  5. package/dist/index.js +1 -1
  6. package/dist/{instance-CFTw3g-c.js → instance-Bw1BxctF.js} +2581 -189
  7. package/dist/instance-Bw1BxctF.js.map +1 -0
  8. package/dist/plugins/child/host.d.ts +1 -0
  9. package/dist/plugins/child/host.js +165 -0
  10. package/dist/plugins/child/host.js.map +1 -0
  11. package/dist/reference/cli.md +147 -5
  12. package/dist/reference/diagnostics.json +234 -0
  13. package/dist/reference/errors/MOSTRA_LICENSE_ACCEPT_INVALID.md +23 -0
  14. package/dist/reference/errors/MOSTRA_LICENSE_MISMATCH.md +23 -0
  15. package/dist/reference/errors/MOSTRA_LICENSE_UNACCEPTED.md +23 -0
  16. package/dist/reference/errors/MOSTRA_LICENSE_UNDECLARED.md +23 -0
  17. package/dist/reference/errors/MOSTRA_PACK_ADDRESS_INVALID.md +23 -0
  18. package/dist/reference/errors/MOSTRA_PACK_CSS_UNIMPORTED.md +23 -0
  19. package/dist/reference/errors/MOSTRA_PACK_FETCH_FAILED.md +23 -0
  20. package/dist/reference/errors/MOSTRA_PACK_FILE_EXISTS.md +23 -0
  21. package/dist/reference/errors/MOSTRA_PACK_ITEM_INVALID.md +23 -0
  22. package/dist/reference/errors/MOSTRA_PACK_ITEM_NOT_FOUND.md +23 -0
  23. package/dist/reference/errors/MOSTRA_PACK_NOT_APPLIED.md +23 -0
  24. package/dist/reference/errors/MOSTRA_PACK_OFFLINE.md +23 -0
  25. package/dist/reference/errors/MOSTRA_PACK_TARGET_INVALID.md +23 -0
  26. package/dist/reference/errors/MOSTRA_PLUGIN_CONFLICT.md +23 -0
  27. package/dist/reference/errors/MOSTRA_PLUGIN_CONTRACT_UNSUPPORTED.md +23 -0
  28. package/dist/reference/errors/MOSTRA_PLUGIN_ENTRY_INVALID.md +23 -0
  29. package/dist/reference/errors/MOSTRA_PLUGIN_EXPORTER_UNKNOWN.md +23 -0
  30. package/dist/reference/errors/MOSTRA_PLUGIN_FAILED.md +23 -0
  31. package/dist/reference/errors/MOSTRA_PLUGIN_MANIFEST_INVALID.md +23 -0
  32. package/dist/reference/errors/MOSTRA_PLUGIN_MANIFEST_WARNING.md +23 -0
  33. package/dist/reference/errors/MOSTRA_PLUGIN_NOT_A_PLUGIN.md +23 -0
  34. package/dist/reference/errors/MOSTRA_PLUGIN_NOT_INSTALLED.md +23 -0
  35. package/dist/reference/errors/MOSTRA_PLUGIN_OPTIONS_INVALID.md +23 -0
  36. package/dist/reference/errors/MOSTRA_PLUGIN_PLATFORM_UNSUPPORTED.md +23 -0
  37. package/dist/reference/errors/MOSTRA_PLUGIN_SCOPE_INVALID.md +23 -0
  38. package/dist/reference/errors/MOSTRA_PLUGIN_SHADOWED.md +23 -0
  39. package/dist/skill/SKILL.md +4 -2
  40. package/dist/skill/references/mcp.md +2 -2
  41. package/dist/skill/references/plugins.md +51 -0
  42. package/package.json +10 -7
  43. package/src/deps/index.ts +407 -90
  44. package/src/deps/installer.ts +53 -10
  45. package/src/deps/lock.ts +74 -2
  46. package/src/home/settings.ts +3 -0
  47. package/src/instance/index.ts +57 -0
  48. package/src/packs/index.ts +7 -0
  49. package/src/packs/methods.ts +49 -0
  50. package/src/packs/packs.ts +706 -0
  51. package/src/packs/read.ts +759 -0
  52. package/src/platform/index.ts +1 -0
  53. package/src/platform/shell.ts +14 -0
  54. package/src/plugins/child/host.ts +231 -0
  55. package/src/plugins/child-protocol.ts +68 -0
  56. package/src/plugins/index.ts +7 -0
  57. package/src/plugins/location.ts +109 -0
  58. package/src/plugins/methods.ts +269 -0
  59. package/src/plugins/plugins.ts +1396 -0
  60. package/src/publish/publisher.ts +71 -3
  61. package/dist/instance-CFTw3g-c.js.map +0 -1
@@ -1,17 +1,19 @@
1
1
  import { C as STAGING_FILES, S as LIVE_DECLARATION, _ as DEV_METHOD, a as nameKey, c as removeTree, d as replaceDirectoryLink, f as samePath, g as DEV_CHANGED_METHOD, h as BUILD_METHOD, i as linkTarget, l as renamePath, m as sealTree, o as pathKey, p as sealPlaced, r as linkDirectory, s as realPath, t as fsyncPath, u as renamePathSync, v as DEV_RELOAD_METHOD, y as DEV_SECRET_HEADER } from "./files-DGeWuE4I.js";
2
2
  import { a as pathsOf, c as currentUserSid, d as runtimeRoot$1, f as serviceLauncherPath, i as ownedDirectory, l as helperPath, n as WINDOWS, o as runtimeDirFor, p as stopServiceLauncher, r as defaultHome, s as socketPathLimit, t as OS, u as runHelperAsync } from "./directories-BLJjeSPD.js";
3
+ import { n as INSPECT_METHOD, t as EXPORT_METHOD } from "./child-protocol-CPXR6pMu.js";
3
4
  import { builtinModules, createRequire } from "node:module";
4
5
  import { accessSync, appendFileSync, chmodSync, closeSync, constants, createReadStream, createWriteStream, existsSync, fsyncSync, linkSync, mkdirSync, openSync, readFileSync, readdirSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, watch, writeFileSync, writeSync } from "node:fs";
5
- import { basename, delimiter, dirname, extname, isAbsolute, join, relative, resolve, sep, win32 } from "node:path";
6
+ import { basename, delimiter, dirname, extname, isAbsolute, join, posix, relative, resolve, sep, win32 } from "node:path";
6
7
  import { fileURLToPath } from "node:url";
7
- import { ACTION_ARGS_MAX, ACTION_RESULT_MAX, ALL_SCOPES, ARTIFACT_MANIFEST_KEYS, ARTIFACT_PROGRESS, ArtifactId, ArtifactManifest, BROWSER_PROTOCOL_REVISION, BROWSER_PROTOCOL_REVISIONS, BUNDLE_NAME, CLI_CLIENT_NAME, CallRequest, ChooseRequest, DEFAULT_TEAM_VISIBILITY, DEFAULT_WORKER_LIMITS, DEV_NOTIFY, DeliveryId, EVENTS_NOTIFY, EnterRequest, FRAME_SESSION_HEADER, FieldsRequest, FollowRequest, HOST_PROTOCOL_REVISIONS, LIVE_RING_DEFAULT, LIVE_RING_MAX, LIVE_VALUE_MAX, LineSplitter, LinkId, LiveRequest, MAX_LINE_LENGTH, MutationId, PUBLIC_SHARE_DEFAULT_TTL, PUBLIC_SHARE_MAX_TTL_MS, PresenceRequest, RESULTS_LIST_MAX, ROSTER_MAX, RUN_LOG_MAX, RUN_LOG_TRUNCATED, RespondentsRequest, RpcError, RpcPeer, RunAttachRequest, RunCancelRequest, RunId, RunRequest, SECRET_NAME_PATTERN, SECRET_VALUE_MAX, SHELL_SESSION_HEADER, SIGNAL_NAME_PATTERN, SIGNAL_PAYLOAD_MAX_BYTES, ServerEmitParams, ServerLiveValueParams, ServerSecretParams, ServerSignalParams, ServerStateGetParams, ServerStatePatchParams, ShareId, ShellSubmitRequest, SignalRequest, StreamTicketRequest, SubmissionEnvelope, SubmissionId, SubmissionPolicy, SubmitRequest, TALLY_LIVE_PREFIX, TokenId, VERIFY_RUNNER_METHODS, VerifyVerdict, VersionId, ViewId, ViewerId, WORKER_METHODS, WorkerBatchParams, WorkerCallOutcome, WorkerPingResult, WorkerStartResult, ariaSummary, artifactCreateMethod, artifactExportMethod, artifactGetMethod, artifactImportMethod, artifactListMethod, artifactPauseMethod, artifactPublishMethod, artifactVerifyMethod, canonicalJson, checkArgumentFrames, checkRequest, createDiagnostic, depsAddMethod, devStartMethod, devStopMethod, durationMs, encodeLine, estimateImageTokens, eventsAckMethod, eventsReadMethod, eventsSubscribeMethod, eventsUnsubscribeMethod, fromBase64, gcRunMethod, hostedPushMethod, hostedSubmissionMethod, instanceCheckMethod, instanceStatusMethod, isFieldId, isFinalRunStatus, livePushMethod, manifestProblem, mostraInitializeMethod, mostraShutdownMethod, negotiateRevision, normalizeScopes, parseParams, portAddressingExternalBaseMethod, portDraftsMirrorMethod, portIdentityResolveMethod, portRelayAuthorMethod, portRelayCallMethod, portRelayCancelMethod, portRelayLiveMethod, portRelayReconcileMethod, portRelayRunMethod, portSecretsGetMethod, portSubmissionsDeliverMethod, portTrustedControlsActivatedMethod, portTrustedControlsPolicyMethod, refusal, relayCallBatchMethod, relayEffectMethod, relayLiveValueMethod, relayRunUpdateMethod, remoteLinkMethod, remoteLoginMethod, remoteLoginWaitMethod, remoteLogoutMethod, remoteStatusMethod, remoteTokenMethod, resultsGetMethod, resultsListMethod, rosterAddMethod, rosterGetMethod, rosterRemoveMethod, safeEqual, safePath, scopeAllows, secretDeleteMethod, secretListMethod, secretSetMethod, serializeAll, shareListMethod, shareStartMethod, shareStopMethod, stateGetMethod, statePatchMethod, toBase64, viewDefaultMethod, viewLaunchMethod, viewRevokeMethod, viewRotateMethod, viewUrlMethod, viewportsFor, waitMethod } from "@mostra/protocol";
8
+ import { ACTION_ARGS_MAX, ACTION_RESULT_MAX, ALL_SCOPES, ARTIFACT_MANIFEST_KEYS, ARTIFACT_PROGRESS, ArtifactId, ArtifactManifest, BROWSER_PROTOCOL_REVISION, BROWSER_PROTOCOL_REVISIONS, BUNDLE_NAME, CLI_CLIENT_NAME, CallRequest, ChooseRequest, DEFAULT_TEAM_VISIBILITY, DEFAULT_WORKER_LIMITS, DEV_NOTIFY, DeliveryId, EVENTS_NOTIFY, EnterRequest, FRAME_SESSION_HEADER, FieldsRequest, FollowRequest, HOST_PROTOCOL_REVISIONS, LIVE_RING_DEFAULT, LIVE_RING_MAX, LIVE_VALUE_MAX, LineSplitter, LinkId, LiveRequest, MAX_LINE_LENGTH, MutationId, PUBLIC_SHARE_DEFAULT_TTL, PUBLIC_SHARE_MAX_TTL_MS, PresenceRequest, RESULTS_LIST_MAX, ROSTER_MAX, RUN_LOG_MAX, RUN_LOG_TRUNCATED, RespondentsRequest, RpcError, RpcPeer, RunAttachRequest, RunCancelRequest, RunId, RunRequest, SECRET_NAME_PATTERN, SECRET_VALUE_MAX, SHELL_SESSION_HEADER, SIGNAL_NAME_PATTERN, SIGNAL_PAYLOAD_MAX_BYTES, ServerEmitParams, ServerLiveValueParams, ServerSecretParams, ServerSignalParams, ServerStateGetParams, ServerStatePatchParams, ShareId, ShellSubmitRequest, SignalRequest, StreamTicketRequest, SubmissionEnvelope, SubmissionId, SubmissionPolicy, SubmitRequest, TALLY_LIVE_PREFIX, TokenId, VERIFY_RUNNER_METHODS, VerifyVerdict, VersionId, ViewId, ViewerId, WORKER_METHODS, WorkerBatchParams, WorkerCallOutcome, WorkerPingResult, WorkerStartResult, ariaSummary, artifactCreateMethod, artifactExportMethod, artifactGetMethod, artifactImportMethod, artifactListMethod, artifactPauseMethod, artifactPublishMethod, artifactVerifyMethod, canonicalJson, checkArgumentFrames, checkArtifactPath, checkRequest, createDiagnostic, depsAddMethod, devStartMethod, devStopMethod, durationMs, encodeLine, estimateImageTokens, eventsAckMethod, eventsReadMethod, eventsSubscribeMethod, eventsUnsubscribeMethod, fromBase64, gcRunMethod, hostedPushMethod, hostedSubmissionMethod, instanceCheckMethod, instanceStatusMethod, isFieldId, isFinalRunStatus, livePushMethod, manifestProblem, mostraInitializeMethod, mostraShutdownMethod, negotiateRevision, normalizeScopes, packAddMethod, parseParams, pluginAddMethod, pluginCommandsMethod, pluginExportMethod, pluginListMethod, pluginRemoveMethod, pluginValidateMethod, portAddressingExternalBaseMethod, portDraftsMirrorMethod, portIdentityResolveMethod, portRelayAuthorMethod, portRelayCallMethod, portRelayCancelMethod, portRelayLiveMethod, portRelayReconcileMethod, portRelayRunMethod, portSecretsGetMethod, portSubmissionsDeliverMethod, portTrustedControlsActivatedMethod, portTrustedControlsPolicyMethod, refusal, relayCallBatchMethod, relayEffectMethod, relayLiveValueMethod, relayRunUpdateMethod, remoteLinkMethod, remoteLoginMethod, remoteLoginWaitMethod, remoteLogoutMethod, remoteStatusMethod, remoteTokenMethod, resultsGetMethod, resultsListMethod, rosterAddMethod, rosterGetMethod, rosterRemoveMethod, safeEqual, safePath, scopeAllows, secretDeleteMethod, secretListMethod, secretSetMethod, serializeAll, shareListMethod, shareStartMethod, shareStopMethod, stateGetMethod, statePatchMethod, toBase64, viewDefaultMethod, viewLaunchMethod, viewRevokeMethod, viewRotateMethod, viewUrlMethod, viewportsFor, waitMethod } from "@mostra/protocol";
8
9
  import { createHash, createHmac, randomBytes, randomInt, randomUUID } from "node:crypto";
9
10
  import { connect, createConnection, createServer, isIP } from "node:net";
10
11
  import { execFile, execFileSync, spawn } from "node:child_process";
11
12
  import { Duplex, PassThrough, Readable, Writable } from "node:stream";
12
- import { access, chmod, copyFile, cp, lstat, mkdir, mkdtemp, open, readFile, readdir, realpath, rm, stat, unlink, utimes, writeFile } from "node:fs/promises";
13
+ import { access, chmod, copyFile, cp, lstat, mkdir, mkdtemp, open, readFile, readdir, realpath, rename, rm, rmdir, stat, unlink, utimes, writeFile } from "node:fs/promises";
13
14
  import { homedir, hostname, networkInterfaces } from "node:os";
14
15
  import semver from "semver";
16
+ import { ACKNOWLEDGED_CLASSES, BUILT_IN_EXPORTERS, CONTRACT_NAMES, PLUGIN_CONTRACTS, RegistryItemSchema, RegistrySchema, checkPluginManifest, formatLicenseExpression, isLicenseRef, licenseTerms, manifestScopes, packageLicense, packageLicenseTerms, parseLicenseExpression, parsePackAddress, spdxLicense, stampServed } from "@mostra/protocol/plugin";
15
17
  import { createInterface } from "node:readline";
16
18
  import * as z from "zod";
17
19
  import { parse as parse$1, parseDocument } from "yaml";
@@ -26,6 +28,7 @@ import { AsyncLocalStorage } from "node:async_hooks";
26
28
  import { defaultWorkspaceRoot, localWorkspace } from "@mostra/mcp";
27
29
  import { WebSocket } from "ws";
28
30
  import { request as request$1 } from "node:https";
31
+ import { EnvHttpProxyAgent, fetch as fetch$1 } from "undici";
29
32
  import { Resolver } from "node:dns/promises";
30
33
  //#region src/log.ts
31
34
  /**
@@ -1782,6 +1785,20 @@ function baseEnvironment(env) {
1782
1785
  return result;
1783
1786
  }
1784
1787
  //#endregion
1788
+ //#region src/platform/shell.ts
1789
+ /**
1790
+ * A value as one word of a command a diagnostic's fix names (`mostra add … --artifact <path>`),
1791
+ * for the shell an agent pastes it into: POSIX quoting, or on Windows the double quotes PowerShell
1792
+ * and `cmd` both read (a Windows path holds no `"`). A plain word stays as it is: letters, digits
1793
+ * and `@%+=:,./-`, a backslash on Windows, and a `~` that doesn't start the word (a short Windows
1794
+ * name such as `RUNNER~1`; a leading one would be a POSIX shell's home).
1795
+ */
1796
+ /** `value` as one shell word. */
1797
+ function shellWord(value) {
1798
+ if (WINDOWS) return /^[\w@%+=:,./\\~-]+$/.test(value) ? value : `"${value}"`;
1799
+ return /^(?!~)[\w@%+=:,./~-]+$/.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;
1800
+ }
1801
+ //#endregion
1785
1802
  //#region src/platform/tools.ts
1786
1803
  /**
1787
1804
  * Where this system keeps the tunnel tools a share drives (D158 item 4): `tailscale` and
@@ -1930,7 +1947,7 @@ function versionOf(dir) {
1930
1947
  return JSON.parse(readFileSync(join(dir, "package.json"), "utf8")).version;
1931
1948
  }
1932
1949
  /** The builder child's entry: the compiled one beside the compiled supervisor, else the source. */
1933
- function childEntry$1(root) {
1950
+ function childEntry$2(root) {
1934
1951
  return fileURLToPath(import.meta.url).endsWith(".ts") ? join(root, "src/builder/child/main.ts") : join(root, "dist/builder/child/main.js");
1935
1952
  }
1936
1953
  /** The SPA render mode (D19): every build in its own builder child. */
@@ -1972,7 +1989,7 @@ function createSpaRenderMode(options) {
1972
1989
  kind: "builder",
1973
1990
  ownerRef: request.root,
1974
1991
  command: process.execPath,
1975
- args: [childEntry$1(root)],
1992
+ args: [childEntry$2(root)],
1976
1993
  cwd: request.root,
1977
1994
  env: {
1978
1995
  ...childEnv,
@@ -2018,7 +2035,7 @@ function createSpaRenderMode(options) {
2018
2035
  kind: "builder",
2019
2036
  ownerRef: request.stagingDir,
2020
2037
  command: process.execPath,
2021
- args: [childEntry$1(root)],
2038
+ args: [childEntry$2(root)],
2022
2039
  cwd: request.stagingDir,
2023
2040
  env: childEnv,
2024
2041
  ipc: {}
@@ -3756,7 +3773,7 @@ function packageNamed(record, message) {
3756
3773
  return /(?:for|resolve|GET \S+?\/)(@?[^\s@/:]+(?:\/[^\s@/:]+)?)/.exec(message)?.[1];
3757
3774
  }
3758
3775
  /** The install child's entry: the compiled one beside the compiled supervisor, else the source. */
3759
- function childEntry() {
3776
+ function childEntry$1() {
3760
3777
  return fileURLToPath(import.meta.url).endsWith(".ts") ? join(runtimeRoot$1(), "src/deps/child/install.ts") : join(runtimeRoot$1(), "dist/deps/child/install.js");
3761
3778
  }
3762
3779
  /** Finds pnpm 10 beside the runtime; anything else is refused (D94). */
@@ -3778,20 +3795,26 @@ function locatePnpm() {
3778
3795
  dir = parent;
3779
3796
  }
3780
3797
  }
3781
- /** The project settings of a run: the release age, and the packages named exactly (D95). */
3798
+ /**
3799
+ * The extension contracts' packages, which the release age never holds back (D173): Mostra's own
3800
+ * release pipeline publishes them beside the runtime that runs them, so a plugin built on a
3801
+ * contract released today installs today, wherever in its tree the contract is.
3802
+ */
3803
+ const RELEASE_AGE_EXEMPT = Object.values(PLUGIN_CONTRACTS).map((contract) => contract.package);
3804
+ /**
3805
+ * The project settings of a run: the release age, the packages named exactly and the extension
3806
+ * contracts' packages, which it doesn't hold back (D95, D173).
3807
+ */
3782
3808
  function workspaceSettings(releaseAge) {
3783
3809
  if (releaseAge === false) return "minimumReleaseAge: 0\n";
3784
- const lines = [`minimumReleaseAge: ${MINIMUM_RELEASE_AGE_MINUTES}`];
3785
- if (releaseAge.exempt.length > 0) {
3786
- lines.push("minimumReleaseAgeExclude:");
3787
- for (const name of [...new Set(releaseAge.exempt)].sort()) lines.push(` - ${JSON.stringify(name)}`);
3788
- }
3810
+ const lines = [`minimumReleaseAge: ${MINIMUM_RELEASE_AGE_MINUTES}`, "minimumReleaseAgeExclude:"];
3811
+ for (const name of [.../* @__PURE__ */ new Set([...RELEASE_AGE_EXEMPT, ...releaseAge.exempt])].sort()) lines.push(` - ${JSON.stringify(name)}`);
3789
3812
  return `${lines.join("\n")}\n`;
3790
3813
  }
3791
3814
  /** Creates the installer. */
3792
3815
  function createInstaller(options) {
3793
3816
  const pnpm = locatePnpm();
3794
- const entry = childEntry();
3817
+ const entry = childEntry$1();
3795
3818
  const timeoutMs = options.timeoutMs ?? 3e5;
3796
3819
  const env = artifactEnvironment(options.env);
3797
3820
  /** The arguments every pnpm run takes; `network` is absent for a store command. */
@@ -3813,7 +3836,7 @@ function createInstaller(options) {
3813
3836
  ...spec.network ? [spec.network] : [],
3814
3837
  "--config.update-notifier=false",
3815
3838
  "--config.dangerously-allow-all-builds=true",
3816
- "--config.ignore-scripts=false",
3839
+ `--config.ignore-scripts=${spec.scripts === false ? "true" : "false"}`,
3817
3840
  "--config.auto-install-peers=true",
3818
3841
  "--config.strict-peer-dependencies=false",
3819
3842
  "--config.node-linker=isolated",
@@ -3893,13 +3916,25 @@ function createInstaller(options) {
3893
3916
  command: run.command,
3894
3917
  dir: run.dir,
3895
3918
  cacheDir: options.dirs.cache,
3896
- network: run.offline ? "--offline" : "--prefer-offline"
3919
+ network: run.offline ? "--offline" : "--prefer-offline",
3920
+ ...run.scripts === false ? { scripts: false } : {}
3897
3921
  }),
3898
3922
  dir: run.dir,
3899
3923
  cwd: run.cwd,
3900
3924
  releaseAge: run.releaseAge,
3901
3925
  ownerRef: run.ownerRef
3902
3926
  }),
3927
+ rebuild: (input) => execute({
3928
+ args: argsFor({
3929
+ command: ["rebuild"],
3930
+ dir: input.dir,
3931
+ cacheDir: options.dirs.cache
3932
+ }),
3933
+ dir: input.dir,
3934
+ cwd: input.cwd,
3935
+ releaseAge: false,
3936
+ ownerRef: input.ownerRef
3937
+ }),
3903
3938
  prune: (input) => execute({
3904
3939
  args: argsFor({
3905
3940
  command: ["store", "prune"],
@@ -3923,7 +3958,7 @@ function diagnose(errors, scriptLines, stderr) {
3923
3958
  if (first.code === "ERR_PNPM_NO_OFFLINE_META" || first.code === "ERR_PNPM_NO_OFFLINE_TARBALL") return createDiagnostic("MOSTRA_DEP_OFFLINE", { message: `Mostra is offline and the home's package store doesn't hold ${subject}.` });
3924
3959
  if (UNREACHABLE.test(first.message)) return createDiagnostic("MOSTRA_DEP_OFFLINE", { message: `The package registry can't be reached, so ${subject} can't be installed: ${first.message}` });
3925
3960
  if (first.code === "ERR_PNPM_FETCH_404" || first.code === "ERR_PNPM_NO_MATCHING_VERSION" || first.code === "ERR_PNPM_NO_MATURE_MATCHING_VERSION") {
3926
- const mature = first.code === "ERR_PNPM_FETCH_404" ? "" : " Without an exact version, only releases at least a day old match; a release less than a day old installs when named exactly.";
3961
+ const mature = first.code === "ERR_PNPM_FETCH_404" ? "" : " Without an exact version, only releases at least a day old match: a release less than a day old installs when it is named exactly, and, when it is a dependency of what was named, once it is a day old.";
3927
3962
  return createDiagnostic("MOSTRA_DEP_NOT_FOUND", { message: `The registry has no match for ${subject}: ${first.message}.${mature}` });
3928
3963
  }
3929
3964
  return createDiagnostic("MOSTRA_DEP_INSTALL_FAILED", { message: `Installing ${subject} failed: ${first.message}${output ? `\n${output}` : ""}` });
@@ -3934,8 +3969,11 @@ function diagnose(errors, scriptLines, stderr) {
3934
3969
  * The lockfile (`lock.yaml`, D20, D95): what a version was built with, frozen at publish, and the
3935
3970
  * form of every artifact's working lockfile. WP-03's form lists the warm set; an artifact with
3936
3971
  * on-demand packages adds `packages` (each direct one at its exact version) and `pnpm` (the
3937
- * installer's lockfile, which pins the whole graph). `lockDigest` is the SHA-256 of the text, so
3938
- * any change to either changes `envDigest` and the version (DP-03).
3972
+ * installer's lockfile, which pins the whole graph). WP-16 adds, additively, `plugins` (the
3973
+ * artifact's plugins in load order, ROUND-3 §6.4) and `licenses` (the licenses acknowledged for
3974
+ * them and for packs, D31, each with its class, who accepted it and when). `lockDigest` is the
3975
+ * SHA-256 of the text, so any change to any of them changes `envDigest` and the version (DP-03);
3976
+ * a lockfile without plugins or acknowledgments keeps its earlier form byte for byte.
3939
3977
  */
3940
3978
  const HEADER = "# Mostra lockfile: the packages this version was built with. Frozen at publish.";
3941
3979
  const sorted = (record) => Object.entries(record).sort(([a], [b]) => a < b ? -1 : 1);
@@ -3956,6 +3994,19 @@ function lockText(lock) {
3956
3994
  const pnpm = lock.pnpm.replace(/\s+$/, "");
3957
3995
  for (const line of pnpm.split("\n")) lines.push(line === "" ? "" : ` ${line}`);
3958
3996
  }
3997
+ if ((lock.plugins?.length ?? 0) > 0) {
3998
+ lines.push("plugins:");
3999
+ for (const name of lock.plugins ?? []) lines.push(` - ${JSON.stringify(name)}`);
4000
+ }
4001
+ const licenses = Object.entries(lock.licenses ?? {}).sort(([a], [b]) => a < b ? -1 : 1);
4002
+ if (licenses.length > 0) {
4003
+ lines.push("licenses:");
4004
+ for (const [id, license] of licenses) {
4005
+ lines.push(` ${JSON.stringify(id)}:`);
4006
+ lines.push(` class: ${JSON.stringify(license.class)}`);
4007
+ lines.push(` by: ${JSON.stringify(license.by)}`);
4008
+ }
4009
+ }
3959
4010
  const text = `${lines.join("\n")}\n`;
3960
4011
  const back = parseLock(text);
3961
4012
  if (packages.length > 0 && back.pnpm !== `${lock.pnpm?.replace(/\s+$/, "")}\n`) throw new Error("The pnpm lockfile doesn't round-trip through lock.yaml.");
@@ -3967,7 +4018,12 @@ function parseLock(text) {
3967
4018
  return {
3968
4019
  warm: data.warm ?? {},
3969
4020
  packages: data.packages ?? {},
3970
- ...typeof data.pnpm === "string" ? { pnpm: data.pnpm } : {}
4021
+ ...typeof data.pnpm === "string" ? { pnpm: data.pnpm } : {},
4022
+ ...Array.isArray(data.plugins) && data.plugins.length > 0 ? { plugins: data.plugins } : {},
4023
+ ...data.licenses && Object.keys(data.licenses).length > 0 ? { licenses: Object.fromEntries(Object.entries(data.licenses).map(([id, license]) => [id, {
4024
+ class: license.class,
4025
+ by: license.by === "host" ? "host" : "flag"
4026
+ }])) } : {}
3971
4027
  };
3972
4028
  }
3973
4029
  /** The SHA-256 of a lockfile's text, as lowercase hex. */
@@ -3988,6 +4044,30 @@ function pinnedPackages(pnpm) {
3988
4044
  }
3989
4045
  return result;
3990
4046
  }
4047
+ /** `lock` with the plugins and acknowledgments of `from` (a working lockfile), which a resolution keeps. */
4048
+ function withExtras(lock, from) {
4049
+ const { plugins: _plugins, licenses: _licenses, ...rest } = lock;
4050
+ const plugins = from?.plugins ?? [];
4051
+ const licenses = from?.licenses ?? {};
4052
+ return {
4053
+ ...rest,
4054
+ ...plugins.length > 0 ? { plugins } : {},
4055
+ ...Object.keys(licenses).length > 0 ? { licenses } : {}
4056
+ };
4057
+ }
4058
+ /**
4059
+ * The key of the layout a lockfile builds against (`deps/locks/<key>`): the digest of its
4060
+ * packages alone, without its plugins and acknowledgments, which change what a version records
4061
+ * but not what it installs. For a lockfile without either it is its `lockDigest`, so layouts made
4062
+ * before WP-16 keep their names.
4063
+ */
4064
+ function layoutKey(lock) {
4065
+ return lockDigest(lockText({
4066
+ warm: lock.warm,
4067
+ packages: lock.packages,
4068
+ ...lock.pnpm ? { pnpm: lock.pnpm } : {}
4069
+ }));
4070
+ }
3991
4071
  //#endregion
3992
4072
  //#region src/deps/specifier.ts
3993
4073
  /**
@@ -4335,15 +4415,6 @@ function isOffline(env) {
4335
4415
  if (flag !== void 0 && flag !== "" && !/^(?:0|false|no)$/i.test(flag)) return true;
4336
4416
  return !Object.values(networkInterfaces()).some((addresses) => (addresses ?? []).some((address) => !address.internal && !address.address.startsWith("169.254.") && !/^fe[89ab]/i.test(address.address)));
4337
4417
  }
4338
- /**
4339
- * A shell-safe rendering of `value`, for the commands in diagnostics: POSIX shell quoting, or on
4340
- * Windows the double quotes PowerShell and `cmd` both read (a Windows path holds no `"`), and a
4341
- * plain path with backslashes as it is.
4342
- */
4343
- function shellQuote(value) {
4344
- if (WINDOWS) return /^[\w@%+=:,./\\-]+$/.test(value) ? value : `"${value}"`;
4345
- return /^[\w@%+=:,./-]+$/.test(value) ? value : `'${value.replaceAll("'", `'\\''`)}'`;
4346
- }
4347
4418
  /** Serializes work per key; one supervisor, so in-process order is the order. */
4348
4419
  var KeyedQueue$1 = class {
4349
4420
  #tails = /* @__PURE__ */ new Map();
@@ -4357,7 +4428,7 @@ var KeyedQueue$1 = class {
4357
4428
  return next;
4358
4429
  }
4359
4430
  };
4360
- const fail = (code, message) => new RpcError(createDiagnostic(code, { message }));
4431
+ const fail$2 = (code, message) => new RpcError(createDiagnostic(code, { message }));
4361
4432
  /** Creates the dependencies of one instance. */
4362
4433
  function createDependencies(options) {
4363
4434
  const { ledger, log, warm } = options;
@@ -4397,9 +4468,6 @@ function createDependencies(options) {
4397
4468
  added: JSON.parse(row.added_json)
4398
4469
  } : void 0;
4399
4470
  };
4400
- const writeWorking = (key, text, added) => {
4401
- ledger.write((db) => db.run("INSERT INTO dependency_lock (key, lock_text, added_json, updated_at) VALUES (?, ?, ?, ?) ON CONFLICT(key) DO UPDATE SET lock_text = excluded.lock_text, added_json = excluded.added_json, updated_at = excluded.updated_at", key, text, JSON.stringify([...new Set(added)].sort()), (/* @__PURE__ */ new Date()).toISOString()));
4402
- };
4403
4471
  /** A working lockfile's stored text, or `null` without one. */
4404
4472
  const rowText = (key) => ledger.read((db) => db.get("SELECT lock_text FROM dependency_lock WHERE key = ?", key)?.lock_text ?? null);
4405
4473
  /** Versions of `name` the home's store holds, from the store index. */
@@ -4416,7 +4484,7 @@ function createDependencies(options) {
4416
4484
  if (isOff) for (const spec of additions) {
4417
4485
  const versions = stored(spec.name);
4418
4486
  const range = spec.range !== void 0 && semver.validRange(spec.range) ? spec.range : "*";
4419
- if (semver.maxSatisfying(versions, range) === null) throw fail("MOSTRA_DEP_OFFLINE", `Mostra is offline and the home's package store doesn't hold ${spec.name}${spec.range ? `@${spec.range}` : ""}.`);
4487
+ if (semver.maxSatisfying(versions, range) === null) throw fail$2("MOSTRA_DEP_OFFLINE", `Mostra is offline and the home's package store doesn't hold ${spec.name}${spec.range ? `@${spec.range}` : ""}.`);
4420
4488
  }
4421
4489
  await mkdir(dirs.tmp, { recursive: true });
4422
4490
  const work = join(dirs.tmp, `resolve-${randomBytes(6).toString("hex")}`);
@@ -4439,6 +4507,7 @@ function createDependencies(options) {
4439
4507
  dir: work,
4440
4508
  cwd: input.artifactDir,
4441
4509
  offline: isOff,
4510
+ scripts: false,
4442
4511
  releaseAge: { exempt: additions.filter((spec) => spec.exact !== void 0).map((spec) => spec.name) },
4443
4512
  ownerRef: input.key
4444
4513
  });
@@ -4468,22 +4537,49 @@ function createDependencies(options) {
4468
4537
  if (target !== void 0 && samePath(target, warm.nodeModules)) return;
4469
4538
  await replaceDirectoryLink(warm.nodeModules, link);
4470
4539
  };
4540
+ /** A layout's marker, or `undefined` when it has none or it can't be read. */
4541
+ const markerOf = async (dir) => {
4542
+ try {
4543
+ return JSON.parse(await readFile(join(dir, LAYOUT_MARKER), "utf8"));
4544
+ } catch {
4545
+ return;
4546
+ }
4547
+ };
4471
4548
  /**
4472
4549
  * The layout of `lock`, installed from the store (and the registry for what the store lacks)
4473
4550
  * into `deps/locks/<lockDigest>` unless it is already complete.
4474
4551
  */
4475
- const ensureLayout = (lock, digest, target) => byLayout.run(digest, async () => {
4552
+ const ensureLayout = (lock, digest, target, scripts = true) => byLayout.run(digest, async () => {
4476
4553
  const dir = join(dirs.locks, digest);
4477
4554
  const nodeModules = join(dir, "node_modules");
4478
4555
  if (existsSync(join(dir, LAYOUT_MARKER))) {
4479
4556
  await relinkWarm(dir);
4557
+ if (scripts && (await markerOf(dir))?.scripts === "pending") {
4558
+ const outcome = await install().rebuild({
4559
+ dir,
4560
+ cwd: target.artifactDir,
4561
+ ownerRef: target.key
4562
+ });
4563
+ if (!outcome.ok) {
4564
+ await rm(dir, {
4565
+ recursive: true,
4566
+ force: true
4567
+ });
4568
+ throw new RpcError(outcome.diagnostic);
4569
+ }
4570
+ await writeFile(join(dir, LAYOUT_MARKER), `${JSON.stringify({
4571
+ lockDigest: digest,
4572
+ installer: install().version
4573
+ })}\n`);
4574
+ log.info("deps.layout_scripts_ran", { lockDigest: digest });
4575
+ }
4480
4576
  return nodeModules;
4481
4577
  }
4482
4578
  const pnpm = lock.pnpm;
4483
4579
  const isOff = offline();
4484
4580
  if (isOff) {
4485
4581
  const missing = pinnedPackages(pnpm).find(({ name, version }) => !stored(name).includes(version));
4486
- if (missing) throw fail("MOSTRA_DEP_OFFLINE", `Mostra is offline and the home's package store doesn't hold ${missing.name}@${missing.version}.`);
4582
+ if (missing) throw fail$2("MOSTRA_DEP_OFFLINE", `Mostra is offline and the home's package store doesn't hold ${missing.name}@${missing.version}.`);
4487
4583
  }
4488
4584
  await rm(dir, {
4489
4585
  recursive: true,
@@ -4500,7 +4596,8 @@ function createDependencies(options) {
4500
4596
  cwd: target.artifactDir,
4501
4597
  offline: isOff,
4502
4598
  releaseAge: false,
4503
- ownerRef: target.key
4599
+ ownerRef: target.key,
4600
+ ...scripts ? {} : { scripts: false }
4504
4601
  });
4505
4602
  if (!outcome.ok) throw new RpcError(outcome.diagnostic);
4506
4603
  const now = (/* @__PURE__ */ new Date()).toISOString();
@@ -4510,7 +4607,8 @@ function createDependencies(options) {
4510
4607
  faults.at("deps:before-marker");
4511
4608
  await writeFile(join(dir, LAYOUT_MARKER), `${JSON.stringify({
4512
4609
  lockDigest: digest,
4513
- installer: install().version
4610
+ installer: install().version,
4611
+ ...scripts ? {} : { scripts: "pending" }
4514
4612
  })}\n`);
4515
4613
  } catch (error) {
4516
4614
  await rm(dir, {
@@ -4543,7 +4641,7 @@ function createDependencies(options) {
4543
4641
  const isOff = offline();
4544
4642
  if (isOff) {
4545
4643
  const missing = drifted.find((pkg) => !stored(pkg).includes(lock.warm[pkg]));
4546
- if (missing) throw fail("MOSTRA_DEP_OFFLINE", `Mostra is offline, and this version's server code needs ${missing}@${lock.warm[missing]}, which the warm set no longer holds and the home's package store doesn't.`);
4644
+ if (missing) throw fail$2("MOSTRA_DEP_OFFLINE", `Mostra is offline, and this version's server code needs ${missing}@${lock.warm[missing]}, which the warm set no longer holds and the home's package store doesn't.`);
4547
4645
  }
4548
4646
  await rm(dir, {
4549
4647
  recursive: true,
@@ -4595,19 +4693,17 @@ function createDependencies(options) {
4595
4693
  });
4596
4694
  };
4597
4695
  /** Settles a lockfile: its text, digest and layout. */
4598
- const settle = async (lock, target) => {
4696
+ const settle = async (lock, target, scripts = true) => {
4599
4697
  const text = lockText(lock);
4600
- const digest = lockDigest(text);
4601
4698
  return {
4602
4699
  lock: text,
4603
- lockDigest: digest,
4604
- nodeModules: Object.keys(lock.packages).length === 0 ? warm.nodeModules : await ensureLayout(lock, digest, target)
4700
+ lockDigest: lockDigest(text),
4701
+ nodeModules: Object.keys(lock.packages).length === 0 ? warm.nodeModules : await ensureLayout(lock, layoutKey(lock), target, scripts)
4605
4702
  };
4606
4703
  };
4607
4704
  const runtimeModules = async (target) => {
4608
- const text = await readFile(join(target.versionDir, "lock.yaml"), "utf8");
4609
- const lock = parseLock(text);
4610
- const digest = lockDigest(text);
4705
+ const lock = parseLock(await readFile(join(target.versionDir, "lock.yaml"), "utf8"));
4706
+ const digest = layoutKey(lock);
4611
4707
  const where = {
4612
4708
  key: target.artifactId,
4613
4709
  artifactDir: target.sourceDir ?? target.versionDir
@@ -4620,7 +4716,10 @@ function createDependencies(options) {
4620
4716
  /** gc's part (D140 item 14); see {@link Dependencies.collect}. */
4621
4717
  const collect = async (input) => {
4622
4718
  const texts = [...ledger.read((db) => db.all("SELECT lock_text FROM dependency_lock").map((row) => row.lock_text)), ...input.keep];
4623
- const named = new Set(texts.map((text) => lockDigest(text)));
4719
+ const named = /* @__PURE__ */ new Set();
4720
+ for (const text of texts) try {
4721
+ named.add(layoutKey(parseLock(text)));
4722
+ } catch {}
4624
4723
  const needed = /* @__PURE__ */ new Set();
4625
4724
  const need = (pnpm) => {
4626
4725
  if (pnpm === void 0) return;
@@ -4716,7 +4815,7 @@ function createDependencies(options) {
4716
4815
  if (missing.length > 0 && options.policy() === "explicit") {
4717
4816
  const first = missing[0];
4718
4817
  const site = imports.get(first);
4719
- const command = `mostra add ${missing.join(" ")} --artifact ${shellQuote(target.artifactPath)}`;
4818
+ const command = `mostra add ${missing.join(" ")} --artifact ${shellWord(target.artifactPath)}`;
4720
4819
  throw new RpcError(createDiagnostic("MOSTRA_DEP_MISSING", {
4721
4820
  message: `${missing.join(", ")} ${missing.length === 1 ? "isn't" : "aren't"} in the warm set or the artifact's lockfile, and this home's dependency policy is explicit.`,
4722
4821
  ...site ? { location: site } : {},
@@ -4740,7 +4839,10 @@ function createDependencies(options) {
4740
4839
  additions: missing.map((name) => ({ name })),
4741
4840
  previous: working?.lock.pnpm
4742
4841
  });
4743
- const resolved = await settle(lock, target);
4842
+ lock = withExtras(lock, working?.lock);
4843
+ const resolved = await admitted(target, lock, working?.lock, [], () => {
4844
+ return `mostra plugin add ${(lock.plugins ?? []).map(shellWord).join(" ")} --artifact ${shellWord(target.artifactPath)}`;
4845
+ });
4744
4846
  const seen = rowText(target.key);
4745
4847
  return {
4746
4848
  ...resolved,
@@ -4756,55 +4858,190 @@ function createDependencies(options) {
4756
4858
  const request = target.request;
4757
4859
  const recorded = request === void 0 ? void 0 : ledger.read((db) => recordedResult(db, request));
4758
4860
  if (recorded !== void 0) return recorded;
4759
- const specs = [];
4760
- for (const text of target.packages) {
4761
- const spec = parseSpec(text);
4762
- if (!spec) throw fail("MOSTRA_DEP_SPEC_INVALID", `"${text}" isn't a registry package spec (name, name@version, name@range or name@tag).`);
4763
- specs.push(spec);
4764
- }
4765
- for (const spec of specs) {
4766
- const version = warm.packages[spec.name];
4767
- if (version === void 0 || spec.range === void 0) continue;
4768
- if (!(semver.validRange(spec.range) ? semver.satisfies(version, spec.range) : spec.range === "latest")) throw fail("MOSTRA_DEP_WARM_CONFLICT", `${spec.name} is in the warm set at ${version}, which every artifact uses; ${spec.name}@${spec.range} can't replace it.`);
4769
- }
4770
- const working = readWorking(target.key);
4771
- const pinned = working?.lock.packages ?? {};
4772
- const onDemand = specs.filter((spec) => !(spec.name in warm.packages));
4773
- const additions = onDemand.filter((spec) => spec.range !== void 0 || pinned[spec.name] === void 0);
4774
- const additionNames = new Set(additions.map((spec) => spec.name));
4775
- const pins = Object.fromEntries(Object.entries(pinned).filter(([name]) => !additionNames.has(name) && !(name in warm.packages)));
4776
- const lock = additions.length === 0 && working !== void 0 && sameRecord(working.lock.warm, warm.packages) ? working.lock : Object.keys(pins).length === 0 && additions.length === 0 ? {
4777
- warm: warm.packages,
4778
- packages: {}
4779
- } : await resolveLock({
4780
- key: target.key,
4781
- artifactDir: target.artifactDir,
4782
- pins,
4783
- additions,
4784
- previous: working?.lock.pnpm
4785
- });
4786
- const resolved = await settle(lock, target);
4787
- const added = [...working?.added ?? [], ...onDemand.map((spec) => spec.name)];
4788
- writeWorking(target.key, resolved.lock, added);
4861
+ const plugins = (readWorking(target.key)?.lock.plugins ?? []).length > 0;
4862
+ const staged = await stage(target, target.packages, [], !plugins);
4863
+ const resolved = await admitted(target, staged.lock, staged.working?.lock, target.accept ?? [], () => `mostra add ${target.packages.map(shellWord).join(" ")} --artifact ${shellWord(target.artifactPath)}`);
4789
4864
  const result = {
4790
- packages: specs.map((spec) => {
4791
- const warmVersion = warm.packages[spec.name];
4792
- return warmVersion !== void 0 ? {
4793
- name: spec.name,
4794
- version: warmVersion,
4795
- warm: true
4796
- } : {
4797
- name: spec.name,
4798
- version: lock.packages[spec.name],
4799
- warm: false
4800
- };
4801
- }),
4865
+ packages: staged.packages,
4802
4866
  lockDigest: resolved.lockDigest
4803
4867
  };
4804
- if (request !== void 0) ledger.write((db) => recordResult(db, request, result));
4868
+ ledger.write((db) => {
4869
+ writeRow(db, target.key, resolved.lock, staged.names);
4870
+ if (request !== void 0) recordResult(db, request, result);
4871
+ });
4805
4872
  return result;
4806
- })
4873
+ }),
4874
+ change: (target, inspect) => byArtifact.run(target.key, async () => {
4875
+ const request = target.request;
4876
+ if (request !== void 0) {
4877
+ const recorded = ledger.read((db) => recordedResult(db, request));
4878
+ if (recorded !== void 0) return recorded;
4879
+ }
4880
+ const staged = await stage(target, target.add, target.remove ?? [], false);
4881
+ let ready;
4882
+ const complete = () => ready ??= settle(staged.lock, target).then(() => void 0);
4883
+ const outcome = await inspect({
4884
+ lock: staged.lock,
4885
+ nodeModules: staged.resolved.nodeModules,
4886
+ added: staged.packages,
4887
+ ready: complete,
4888
+ ...staged.working ? { previous: staged.working.lock } : {}
4889
+ });
4890
+ await complete();
4891
+ const text = lockText(withOutcome(staged.lock, outcome));
4892
+ const result = outcome.result(lockDigest(text));
4893
+ const written = await outcome.write?.();
4894
+ try {
4895
+ ledger.write((db) => {
4896
+ writeRow(db, target.key, text, staged.names);
4897
+ if (request !== void 0) recordResult(db, request, result);
4898
+ });
4899
+ } catch (problem) {
4900
+ await written?.rollback();
4901
+ throw problem;
4902
+ }
4903
+ await written?.commit();
4904
+ return result;
4905
+ }),
4906
+ working: async (target, workingOptions) => {
4907
+ const working = readWorking(target.key);
4908
+ if (working === void 0) return void 0;
4909
+ const base = {
4910
+ lock: working.lock,
4911
+ added: [],
4912
+ ready: async () => void 0,
4913
+ previous: working.lock
4914
+ };
4915
+ if (workingOptions?.install === false) {
4916
+ const nodeModules = await installedLayout(working.lock);
4917
+ return nodeModules !== void 0 ? {
4918
+ ...base,
4919
+ nodeModules
4920
+ } : base;
4921
+ }
4922
+ const resolved = await settle(working.lock, target);
4923
+ return {
4924
+ ...base,
4925
+ nodeModules: resolved.nodeModules
4926
+ };
4927
+ }
4807
4928
  };
4929
+ /**
4930
+ * Settles `lock` for use: a lockfile without plugins as it always settled; one with plugins with
4931
+ * its scripts held, through the plugin gate, which runs them once it admitted the plugins, and
4932
+ * with the plugins and acknowledgments the gate answers (a host's pre-acceptance is recorded
4933
+ * there). Without a gate (an instance with no plugins module) it fails closed.
4934
+ */
4935
+ async function admitted(target, lock, previous, accept, command) {
4936
+ if ((lock.plugins ?? []).length === 0) return settle(lock, target);
4937
+ const gate = options.plugins?.();
4938
+ if (gate === void 0) throw fail$2("MOSTRA_PLUGIN_FAILED", "This lockfile names plugins, and this instance has no plugins module to check them.");
4939
+ const held = await settle(lock, target, false);
4940
+ let ready;
4941
+ const runScripts = () => {
4942
+ ready ??= settle(lock, target).then(() => void 0);
4943
+ return ready;
4944
+ };
4945
+ const outcome = await gate.admit({
4946
+ target,
4947
+ staged: {
4948
+ lock,
4949
+ nodeModules: held.nodeModules,
4950
+ added: [],
4951
+ ready: runScripts,
4952
+ ...previous !== void 0 ? { previous } : {}
4953
+ },
4954
+ accept,
4955
+ command: command()
4956
+ });
4957
+ await runScripts();
4958
+ const text = lockText(withOutcome(lock, outcome));
4959
+ return {
4960
+ lock: text,
4961
+ lockDigest: lockDigest(text),
4962
+ nodeModules: held.nodeModules
4963
+ };
4964
+ }
4965
+ /** `lock`'s packages with an outcome's plugins and acknowledgments. */
4966
+ function withOutcome(lock, outcome) {
4967
+ const { plugins: _plugins, licenses: _licenses, ...packages } = lock;
4968
+ const plugins = [...outcome.plugins ?? []];
4969
+ const licenses = { ...outcome.licenses ?? {} };
4970
+ return {
4971
+ ...packages,
4972
+ ...plugins.length > 0 ? { plugins } : {},
4973
+ ...Object.keys(licenses).length > 0 ? { licenses } : {}
4974
+ };
4975
+ }
4976
+ /** The `node_modules` of `lock` when it is installed complete, scripts run; else `undefined`. */
4977
+ async function installedLayout(lock) {
4978
+ if (Object.keys(lock.packages).length === 0) return warm.nodeModules;
4979
+ const dir = join(dirs.locks, layoutKey(lock));
4980
+ const marker = await markerOf(dir);
4981
+ if (marker === void 0 || marker.scripts === "pending") return void 0;
4982
+ return join(dir, "node_modules");
4983
+ }
4984
+ /**
4985
+ * Resolves a change of a working lockfile without recording it: `add` (npm specs) resolve, the
4986
+ * packages in `remove` leave it (they stay only where the source imports them, at the next
4987
+ * resolution), and the layout is installed.
4988
+ */
4989
+ async function stage(target, add, remove, scripts = true) {
4990
+ const specs = [];
4991
+ for (const text of add) {
4992
+ const spec = parseSpec(text);
4993
+ if (!spec) throw fail$2("MOSTRA_DEP_SPEC_INVALID", `"${text}" isn't a registry package spec (name, name@version, name@range or name@tag).`);
4994
+ specs.push(spec);
4995
+ }
4996
+ for (const spec of specs) {
4997
+ const version = warm.packages[spec.name];
4998
+ if (version === void 0 || spec.range === void 0) continue;
4999
+ if (!(semver.validRange(spec.range) ? semver.satisfies(version, spec.range) : spec.range === "latest")) throw fail$2("MOSTRA_DEP_WARM_CONFLICT", `${spec.name} is in the warm set at ${version}, which every artifact uses; ${spec.name}@${spec.range} can't replace it.`);
5000
+ }
5001
+ const working = readWorking(target.key);
5002
+ const pinned = working?.lock.packages ?? {};
5003
+ const dropped = new Set(remove);
5004
+ const onDemand = specs.filter((spec) => !(spec.name in warm.packages));
5005
+ const additions = onDemand.filter((spec) => spec.range !== void 0 || pinned[spec.name] === void 0);
5006
+ const additionNames = new Set(additions.map((spec) => spec.name));
5007
+ const pins = Object.fromEntries(Object.entries(pinned).filter(([name]) => !additionNames.has(name) && !(name in warm.packages) && !dropped.has(name)));
5008
+ let lock = additions.length === 0 && !Object.keys(pinned).some((name) => dropped.has(name)) && working !== void 0 && sameRecord(working.lock.warm, warm.packages) && working !== void 0 ? working.lock : Object.keys(pins).length === 0 && additions.length === 0 ? {
5009
+ warm: warm.packages,
5010
+ packages: {}
5011
+ } : await resolveLock({
5012
+ key: target.key,
5013
+ artifactDir: target.artifactDir,
5014
+ pins,
5015
+ additions,
5016
+ previous: working?.lock.pnpm
5017
+ });
5018
+ lock = withExtras(lock, working?.lock);
5019
+ const resolved = await settle(lock, target, scripts);
5020
+ const names = [...(working?.added ?? []).filter((name) => !dropped.has(name)), ...onDemand.map((spec) => spec.name)];
5021
+ const packages = specs.map((spec) => {
5022
+ const warmVersion = warm.packages[spec.name];
5023
+ return warmVersion !== void 0 ? {
5024
+ name: spec.name,
5025
+ version: warmVersion,
5026
+ warm: true
5027
+ } : {
5028
+ name: spec.name,
5029
+ version: lock.packages[spec.name],
5030
+ warm: false
5031
+ };
5032
+ });
5033
+ return {
5034
+ lock,
5035
+ resolved,
5036
+ packages,
5037
+ names,
5038
+ working
5039
+ };
5040
+ }
5041
+ /** Writes a working lockfile's row inside a transaction. */
5042
+ function writeRow(db, key, text, added) {
5043
+ db.run("INSERT INTO dependency_lock (key, lock_text, added_json, updated_at) VALUES (?, ?, ?, ?) ON CONFLICT(key) DO UPDATE SET lock_text = excluded.lock_text, added_json = excluded.added_json, updated_at = excluded.updated_at", key, text, JSON.stringify([...new Set(added)].sort()), (/* @__PURE__ */ new Date()).toISOString());
5044
+ }
4808
5045
  }
4809
5046
  /** The bytes of the files under `dir` that nothing else links to (a layout's own files). */
4810
5047
  async function unsharedBytes(dir) {
@@ -17410,7 +17647,7 @@ function headingText(title) {
17410
17647
  const line = title.replace(/\s+/g, " ").trim();
17411
17648
  return line === "" ? "Mostra artifact" : line;
17412
17649
  }
17413
- function agents({ title, version }) {
17650
+ function agents$1({ title, version }) {
17414
17651
  return [
17415
17652
  `# ${headingText(title)}`,
17416
17653
  "",
@@ -17442,7 +17679,7 @@ function agents({ title, version }) {
17442
17679
  function scaffoldFiles(input) {
17443
17680
  return /* @__PURE__ */ new Map([
17444
17681
  ["index.tsx", entry(input)],
17445
- ["AGENTS.md", agents(input)],
17682
+ ["AGENTS.md", agents$1(input)],
17446
17683
  ["CLAUDE.md", "@AGENTS.md\n"]
17447
17684
  ]);
17448
17685
  }
@@ -18053,7 +18290,7 @@ function createPublisher(options) {
18053
18290
  try {
18054
18291
  ready = await prepare(path, source, provisional, identityKnown, staging);
18055
18292
  } catch (error) {
18056
- if (error instanceof RpcError && /^MOSTRA_(MANIFEST|DEP|ARTIFACT|BUILD)_/.test(error.diagnostic.code)) return failedVerdict(path, error.diagnostic);
18293
+ if (error instanceof RpcError && /^MOSTRA_(MANIFEST|DEP|ARTIFACT|BUILD|PLUGIN|LICENSE)_/.test(error.diagnostic.code)) return failedVerdict(path, error.diagnostic);
18057
18294
  throw error;
18058
18295
  }
18059
18296
  ledger.write((db) => ready.deps.save(db, lockKey(ready.prepared.manifest.id ?? registry.artifactAt(source.bindingPath), source.bindingPath)));
@@ -18187,9 +18424,27 @@ function createPublisher(options) {
18187
18424
  create: (params) => queue.run("create", () => create(params)),
18188
18425
  addDependencies: (params) => gated(() => addDependencies(params)),
18189
18426
  exportBundle: (params) => gated(() => exportBundle(params)),
18190
- importBundle: (params) => gated(() => idempotent(requestKey("artifact/import", params), () => importBundle(params)))
18427
+ importBundle: (params) => gated(() => idempotent(requestKey("artifact/import", params), () => importBundle(params))),
18428
+ exportable: (params) => gated(() => exportable(params)),
18429
+ withHome: (task) => gated(task),
18430
+ withArtifact: (ref, task) => gated(async () => {
18431
+ const path = pathOf(ref);
18432
+ const source = await resolveSource(path);
18433
+ return queue.run(`path:${source.bindingPath}`, async () => {
18434
+ const manifestId = extractManifest(source.entry, await readEntry(source)).manifest?.id;
18435
+ return task({
18436
+ target: {
18437
+ key: lockKey(manifestId ?? registry.artifactAt(source.bindingPath), source.bindingPath),
18438
+ artifactDir: source.root,
18439
+ artifactPath: path
18440
+ },
18441
+ source
18442
+ });
18443
+ });
18444
+ })
18191
18445
  };
18192
- async function exportBundle(params) {
18446
+ /** A published version of an artifact, checked whole: what an export reads. */
18447
+ async function exportable(params) {
18193
18448
  const detail = registry.get(params.artifact);
18194
18449
  const wanted = params.version;
18195
18450
  const summary = wanted === void 0 ? detail.latestVersion : detail.versions.find((version) => typeof wanted === "number" ? version.number === wanted : version.id === wanted);
@@ -18198,6 +18453,14 @@ function createPublisher(options) {
18198
18453
  const versionDir = registry.store.versionDir(summary.id);
18199
18454
  const damage = await versionDamage(versionDir);
18200
18455
  if (damage !== void 0) throw new RpcError(createDiagnostic("MOSTRA_HOME_INTEGRITY", { message: `Version ${summary.number} of ${detail.title} is damaged: ${damage}.` }));
18456
+ return {
18457
+ detail,
18458
+ summary,
18459
+ versionDir
18460
+ };
18461
+ }
18462
+ async function exportBundle(params) {
18463
+ const { detail, summary, versionDir } = await exportable(params);
18201
18464
  const files = await writeBundle({
18202
18465
  versionDir,
18203
18466
  snapshot: registry.store.snapshotPath(detail.id, summary.sourceDigest),
@@ -18288,6 +18551,7 @@ function createPublisher(options) {
18288
18551
  artifactDir: source.root,
18289
18552
  artifactPath: path,
18290
18553
  packages: params.packages,
18554
+ ...params.acceptLicenses !== void 0 ? { accept: params.acceptLicenses } : {},
18291
18555
  request: requestKey("deps/add", params)
18292
18556
  });
18293
18557
  });
@@ -19507,7 +19771,8 @@ const Settings = z.looseObject({
19507
19771
  hostConfigured: z.object({
19508
19772
  client: z.string(),
19509
19773
  at: z.string()
19510
- }).optional()
19774
+ }).optional(),
19775
+ licenses: z.object({ accept: z.array(z.string()) }).optional()
19511
19776
  });
19512
19777
  /** The settings file of a home. */
19513
19778
  const SETTINGS_FILE = "config.json";
@@ -21389,102 +21654,2193 @@ function createLink(options) {
21389
21654
  return self;
21390
21655
  }
21391
21656
  //#endregion
21392
- //#region src/secrets/index.ts
21657
+ //#region src/packs/methods.ts
21658
+ /**
21659
+ * `pack/add` (INTERFACES §14, D172 item 10): shadcn registry items, and npm packages beside them,
21660
+ * into an artifact, in its source path's queue as its publishes and `deps/add` run.
21661
+ */
21662
+ /** The handler of `pack/add`. */
21663
+ function packMethods(options) {
21664
+ return [handler(packAddMethod, async (params) => {
21665
+ const result = await options.publisher().withArtifact(params.artifact, ({ target, source }) => options.packs().add({
21666
+ target,
21667
+ root: source.root,
21668
+ kind: source.kind,
21669
+ entry: source.entry,
21670
+ specs: params.specs.map((spec) => {
21671
+ const address = parsePackAddress(spec);
21672
+ return address?.kind === "file" && !isAbsolute(address.path) ? resolve(source.root, address.path) : spec;
21673
+ }),
21674
+ overwrite: params.overwrite === true,
21675
+ accept: params.acceptLicenses ?? [],
21676
+ request: requestKey("pack/add", {
21677
+ ...params,
21678
+ environment: void 0
21679
+ }),
21680
+ cwd: source.root,
21681
+ environment: params.environment ?? {}
21682
+ }));
21683
+ options.dependenciesChanged?.(params.artifact);
21684
+ return result;
21685
+ })];
21686
+ }
21687
+ //#endregion
21688
+ //#region src/packs/read.ts
21393
21689
  /**
21394
- * Secrets (D44, AC-06): named values server code reads with `secret(name)`, kept outside artifact
21395
- * source in the home's owner-only store, `secrets/<scope>/<name>` (mode 0600, directories 0700),
21396
- * where the scope is `home` for a secret every artifact shares or the artifact's ID for its own.
21397
- * A host may supply secrets through its `secrets` port instead (a host's own credential store).
21690
+ * Reading source pack items (D30, EX-03): shadcn registry items, by any of shadcn's address forms,
21691
+ * with their registry dependencies, read before anything is written. Every remote read is bounded
21692
+ * (30 s, 8 MiB), `https:` (or `http:` to this machine), and offline fails at once.
21398
21693
  *
21399
- * Every value Mostra holds or hands out is registered with the instance's redactor, so it never
21400
- * reaches a log, a run log, an event, a diagnostic or a report. Nothing derived from a value is
21401
- * ever written to the ledger.
21402
- */
21403
- const HOME_SCOPE = "home";
21404
- const ARTIFACT_SCOPE = /^art_[0-9A-HJKMNP-TV-Z]{26}$/;
21405
- function missing$1(name, detail) {
21406
- return new RpcError(createDiagnostic("MOSTRA_SECRET_MISSING", {
21407
- message: `No secret named ${name} is set${detail ? ` (${detail})` : ""}.`,
21408
- hint: `Set it with \`mostra secret set ${name}\`, reading the value from stdin.`
21409
- }));
21410
- }
21411
- function invalidName(name) {
21412
- return new RpcError(createDiagnostic("MOSTRA_HOST_INVALID_PARAMS", { message: `${JSON.stringify(name).slice(0, 80)} isn't a secret name: a letter or "_", then up to 127 letters, digits, "_", "." and "-".` }));
21694
+ * - a URL: the item's JSON;
21695
+ * - a file: a local item, its files' `path`s read beside it when they carry no `content`;
21696
+ * - GitHub (`owner/repo/item[#ref]`): the ref resolved to a commit, the repository's root
21697
+ * `registry.json` (and its `include`s) at that commit, the item found by name, each file read
21698
+ * at that commit; anonymously, or with `GH_TOKEN` or `GITHUB_TOKEN` for a repository that isn't
21699
+ * public, sent only to GitHub's API;
21700
+ * - `@namespace/item`: through the artifact's `components.json` `registries`, a URL template
21701
+ * (`{name}`, `{style}`) or `{ url, params, headers }` with `${VAR}` read from the environment;
21702
+ * - a bare name (in `registryDependencies`): shadcn's own registry (`REGISTRY_URL`, as shadcn
21703
+ * reads it, else `https://ui.shadcn.com/r`), at the style `components.json` names
21704
+ * (`new-york-v4` when it names none);
21705
+ * - `plugin:<package>/<item>`: a pack an installed plugin carries (`contributes.packs`).
21706
+ */
21707
+ /** How long one read may take. */
21708
+ const FETCH_TIMEOUT_MS = 3e4;
21709
+ /** The most items one `mostra add` may install, its registry dependencies included. */
21710
+ const ITEM_LIMIT = 200;
21711
+ /**
21712
+ * `text` without the slashes it ends in. A loop, not `/\/+$/`, which backtracks polynomially on a
21713
+ * string of many slashes (CodeQL js/polynomial-redos), and a registry's URL comes from the caller.
21714
+ */
21715
+ function withoutTrailingSlashes(text) {
21716
+ let end = text.length;
21717
+ while (end > 0 && text[end - 1] === "/") end -= 1;
21718
+ return text.slice(0, end);
21719
+ }
21720
+ /** `inner` is `outer` or inside it (both real paths), by whole segments. */
21721
+ function isInside$1(outer, inner) {
21722
+ const from = relative(outer, inner);
21723
+ return from === "" || from !== ".." && !from.startsWith(`..${sep}`) && !isAbsolute(from);
21724
+ }
21725
+ const SHADCN_REGISTRY = "https://ui.shadcn.com/r";
21726
+ const DEFAULT_STYLE = "new-york-v4";
21727
+ const fail$1 = (code, message) => new RpcError(createDiagnostic(code, { message }));
21728
+ /** Whether a URL names this machine. */
21729
+ function isLoopback(url) {
21730
+ return url.hostname === "localhost" || url.hostname === "[::1]" || /^127(?:\.\d{1,3}){3}$/.test(url.hostname);
21731
+ }
21732
+ /** Whether a URL may be read: `https:`, or `http:` to this machine. */
21733
+ function readable(url) {
21734
+ if (url.protocol === "https:") return true;
21735
+ return url.protocol === "http:" && isLoopback(url);
21736
+ }
21737
+ /**
21738
+ * Whether a read of `first` may follow a redirect to `next`: `next` is readable, and a registry
21739
+ * elsewhere never sends a read to this machine (WP-16 review, R01's addendum): only an address
21740
+ * the caller named on this machine leads to another one here.
21741
+ */
21742
+ function mayFollow(first, next) {
21743
+ return readable(next) && (!isLoopback(next) || isLoopback(first));
21744
+ }
21745
+ const agents = /* @__PURE__ */ new Map();
21746
+ /** The proxy agent for the environment's `HTTPS_PROXY`, `HTTP_PROXY` and `NO_PROXY`. */
21747
+ function agentFor(env) {
21748
+ const pick = (name) => env[name.toLowerCase()] ?? env[name];
21749
+ const httpsProxy = pick("HTTPS_PROXY");
21750
+ const httpProxy = pick("HTTP_PROXY");
21751
+ const noProxy = pick("NO_PROXY");
21752
+ const key = JSON.stringify([
21753
+ httpsProxy,
21754
+ httpProxy,
21755
+ noProxy
21756
+ ]);
21757
+ let agent = agents.get(key);
21758
+ if (agent === void 0) {
21759
+ agent = new EnvHttpProxyAgent({
21760
+ ...httpsProxy !== void 0 ? { httpsProxy } : {},
21761
+ ...httpProxy !== void 0 ? { httpProxy } : {},
21762
+ ...noProxy !== void 0 ? { noProxy } : {}
21763
+ });
21764
+ agents.set(key, agent);
21765
+ }
21766
+ return agent;
21413
21767
  }
21414
- /** Opens the home's secret store, registering every stored value with the redactor. */
21415
- function openSecrets(options) {
21416
- const root = join(options.home, "secrets");
21417
- mkdirSync(root, {
21418
- recursive: true,
21419
- mode: 448
21420
- });
21421
- chmodSync(root, 448);
21422
- const dirOf = (scope) => join(root, scope.kind === "home" ? HOME_SCOPE : scope.artifactId);
21423
- const read = (dir, name) => {
21768
+ /** Reads a URL's text, bounded; 404 is `undefined`, anything else that fails throws. */
21769
+ async function readUrl(text, context, headers = {}) {
21770
+ let url;
21771
+ try {
21772
+ url = new URL(text);
21773
+ } catch {
21774
+ throw fail$1("MOSTRA_PACK_ADDRESS_INVALID", `"${text}" isn't a URL.`);
21775
+ }
21776
+ if (!readable(url)) throw fail$1("MOSTRA_PACK_ADDRESS_INVALID", `${url.origin} isn't https: Mostra reads registry items over https, or http from this machine.`);
21777
+ if (context.offline) throw fail$1("MOSTRA_PACK_OFFLINE", `Mostra is offline, so it can't read ${redactUrl(url)}.`);
21778
+ const deadline = AbortSignal.timeout(FETCH_TIMEOUT_MS);
21779
+ let response;
21780
+ let current = url;
21781
+ for (let hop = 0;; hop += 1) {
21424
21782
  try {
21425
- return readFileSync(join(dir, name), "utf8");
21783
+ response = await fetch$1(current, {
21784
+ headers: {
21785
+ accept: "application/json, text/plain;q=0.9, */*;q=0.1",
21786
+ ...current.origin === url.origin ? headers : {}
21787
+ },
21788
+ signal: deadline,
21789
+ redirect: "manual",
21790
+ dispatcher: agentFor(context.env)
21791
+ });
21426
21792
  } catch (error) {
21427
- if (error.code === "ENOENT") return void 0;
21428
- throw error;
21429
- }
21430
- };
21431
- for (const scope of existsSync(root) ? readdirSync(root) : []) {
21432
- if (scope !== HOME_SCOPE && !ARTIFACT_SCOPE.test(scope)) continue;
21433
- for (const name of readdirSync(join(root, scope))) {
21434
- if (!SECRET_NAME_PATTERN.test(name)) continue;
21435
- const value = read(join(root, scope), name);
21436
- if (value !== void 0) options.redactor.protectSecret(value);
21793
+ throw fail$1("MOSTRA_PACK_FETCH_FAILED", `Reading ${redactUrl(current)} failed: ${reasonOf(error)}.`);
21794
+ }
21795
+ const location = response.headers.get("location");
21796
+ if (response.status < 300 || response.status >= 400 || location === null) break;
21797
+ await response.body?.cancel();
21798
+ const next = new URL(location, current);
21799
+ if (!mayFollow(url, next)) throw fail$1("MOSTRA_PACK_FETCH_FAILED", `${redactUrl(url)} redirected to ${isLoopback(next) ? "this machine" : "an address that isn't https"}, which Mostra doesn't follow.`);
21800
+ if (hop >= 4) throw fail$1("MOSTRA_PACK_FETCH_FAILED", `${redactUrl(url)} redirected more than five times.`);
21801
+ current = next;
21802
+ }
21803
+ if (response.status === 404) {
21804
+ await response.body?.cancel();
21805
+ return;
21806
+ }
21807
+ if (!response.ok) {
21808
+ await response.body?.cancel();
21809
+ throw fail$1("MOSTRA_PACK_FETCH_FAILED", `${redactUrl(url)} answered ${response.status} ${response.statusText}.`);
21810
+ }
21811
+ if (Number(response.headers.get("content-length") ?? "0") > 8388608) {
21812
+ await response.body?.cancel();
21813
+ throw fail$1("MOSTRA_PACK_FETCH_FAILED", `${redactUrl(url)} is larger than 8 MiB.`);
21814
+ }
21815
+ const chunks = [];
21816
+ let size = 0;
21817
+ try {
21818
+ for await (const chunk of response.body ?? []) {
21819
+ size += chunk.byteLength;
21820
+ if (size > 8388608) throw fail$1("MOSTRA_PACK_FETCH_FAILED", `${redactUrl(url)} sent more than 8 MiB.`);
21821
+ chunks.push(chunk);
21437
21822
  }
21823
+ } catch (error) {
21824
+ if (error instanceof RpcError) throw error;
21825
+ throw fail$1("MOSTRA_PACK_FETCH_FAILED", `Reading ${redactUrl(url)} failed: ${reasonOf(error)}.`);
21438
21826
  }
21439
- const entry = (dir, name, scope) => ({
21440
- name,
21441
- scope: scope.kind,
21442
- ...scope.kind === "artifact" ? { artifactId: scope.artifactId } : {},
21443
- updatedAt: statSync(join(dir, name)).mtime.toISOString()
21444
- });
21445
- const listScope = (scope) => {
21446
- const dir = dirOf(scope);
21447
- if (!existsSync(dir)) return [];
21448
- return readdirSync(dir).filter((name) => SECRET_NAME_PATTERN.test(name)).sort().map((name) => entry(dir, name, scope));
21827
+ return Buffer.concat(chunks).toString("utf8");
21828
+ }
21829
+ /** Why a request failed, in words. */
21830
+ function reasonOf(error) {
21831
+ if (error instanceof Error && (error.name === "TimeoutError" || error.name === "AbortError")) return `it didn't answer within ${FETCH_TIMEOUT_MS / 1e3} s`;
21832
+ if (error instanceof Error) return error.cause instanceof Error ? error.cause.message : error.message;
21833
+ return String(error);
21834
+ }
21835
+ /** A URL without its credentials or query, for messages. */
21836
+ function redactUrl(url) {
21837
+ return `${url.origin}${url.pathname}`;
21838
+ }
21839
+ /** Parses an item's JSON, refusing anything shadcn's schema (and Mostra's block) refuses. */
21840
+ function parseItem(text, where) {
21841
+ let data;
21842
+ try {
21843
+ data = JSON.parse(text);
21844
+ } catch {
21845
+ throw fail$1("MOSTRA_PACK_ITEM_INVALID", `${where} isn't JSON.`);
21846
+ }
21847
+ const parsed = RegistryItemSchema.safeParse(data);
21848
+ if (!parsed.success) {
21849
+ const first = parsed.error.issues[0];
21850
+ throw fail$1("MOSTRA_PACK_ITEM_INVALID", `${where} isn't a registry item: ${first ? `${first.path.join(".") || "(top)"}: ${first.message}` : "its shape is wrong"}.`);
21851
+ }
21852
+ for (const [index, file] of (parsed.data.files ?? []).entries()) if ((file.type === "registry:file" || file.type === "registry:page") && file.target === void 0) throw fail$1("MOSTRA_PACK_ITEM_INVALID", `${where}: files[${index}] is a ${file.type}, which needs a target.`);
21853
+ return parsed.data;
21854
+ }
21855
+ /** `${VAR}` in `text`, from the environment (shadcn's registry headers and params). */
21856
+ function expand(text, env) {
21857
+ return text.replace(/\$\{([A-Za-z_][A-Za-z0-9_]*)\}/g, (_, name) => env[name] ?? "");
21858
+ }
21859
+ /**
21860
+ * Reads every item `specs` name, with their registry dependencies, depth first, each once (by
21861
+ * address), dependencies before the items that need them.
21862
+ */
21863
+ async function readItems(specs, context, cwd) {
21864
+ const done = /* @__PURE__ */ new Map();
21865
+ const order = [];
21866
+ const visiting = /* @__PURE__ */ new Set();
21867
+ const github = context.github ?? {
21868
+ api: "https://api.github.com",
21869
+ raw: "https://raw.githubusercontent.com"
21870
+ };
21871
+ const shas = /* @__PURE__ */ new Map();
21872
+ const registries = /* @__PURE__ */ new Map();
21873
+ const githubToken = () => context.env["GH_TOKEN"] || context.env["GITHUB_TOKEN"] || void 0;
21874
+ /** A ref of a repository as its commit SHA (a full SHA as it is). */
21875
+ const commitOf = async (owner, repo, ref) => {
21876
+ if (ref !== void 0 && /^[0-9a-f]{40}$/.test(ref)) return ref;
21877
+ const key = `${owner}/${repo}#${ref ?? ""}`;
21878
+ const known = shas.get(key);
21879
+ if (known !== void 0) return known;
21880
+ const token = githubToken();
21881
+ const sha = (await readUrl(`${github.api}/repos/${owner}/${repo}/commits/${encodeURIComponent(ref ?? "HEAD")}`, context, {
21882
+ accept: "application/vnd.github.sha",
21883
+ ...token !== void 0 ? { authorization: `Bearer ${token}` } : {}
21884
+ }).catch((error) => {
21885
+ if (error instanceof RpcError && /answered 422/.test(error.diagnostic.message)) return void 0;
21886
+ throw error;
21887
+ }))?.trim();
21888
+ if (sha === void 0 || !/^[0-9a-f]{40}$/.test(sha)) throw fail$1("MOSTRA_PACK_ITEM_NOT_FOUND", `GitHub has no ${ref === void 0 ? "default branch" : `ref "${ref}"`} in ${owner}/${repo}${token === void 0 ? " that it shows without a token (set GH_TOKEN for a repository that isn't public)" : ""}.`);
21889
+ shas.set(key, sha);
21890
+ return sha;
21891
+ };
21892
+ /** A file of a repository at a commit: raw anonymously, else the API with a token. */
21893
+ const repoFile = async (owner, repo, sha, path) => {
21894
+ const clean = posix.normalize(path).replace(/^\/+/, "");
21895
+ if (clean.startsWith("..")) throw fail$1("MOSTRA_PACK_ITEM_INVALID", `${path} leaves ${owner}/${repo}.`);
21896
+ const encoded = clean.split("/").map(encodeURIComponent).join("/");
21897
+ const anonymous = await readUrl(`${github.raw}/${owner}/${repo}/${sha}/${encoded}`, context);
21898
+ if (anonymous !== void 0) return anonymous;
21899
+ const token = githubToken();
21900
+ if (token === void 0) return void 0;
21901
+ return readUrl(`${github.api}/repos/${owner}/${repo}/contents/${encoded}?ref=${sha}`, context, {
21902
+ accept: "application/vnd.github.raw+json",
21903
+ authorization: `Bearer ${token}`
21904
+ });
21449
21905
  };
21450
- return {
21451
- set(name, value, scope) {
21452
- if (!SECRET_NAME_PATTERN.test(name)) throw invalidName(name);
21453
- if (value.length === 0 || Buffer.byteLength(value, "utf8") > SECRET_VALUE_MAX) throw new RpcError(createDiagnostic("MOSTRA_HOST_INVALID_PARAMS", { message: `The value of the secret ${name} must be 1 byte to 64 KiB of UTF-8.` }));
21454
- options.redactor.protectSecret(value);
21455
- const dir = dirOf(scope);
21456
- mkdirSync(dir, {
21457
- recursive: true,
21458
- mode: 448
21459
- });
21460
- chmodSync(dir, 448);
21461
- const temporary = join(dir, `.${name}.${process.pid}.tmp`);
21462
- writeFileSync(temporary, value, {
21463
- mode: 384,
21464
- flag: "w"
21465
- });
21466
- chmodSync(temporary, 384);
21467
- renamePathSync(temporary, join(dir, name));
21468
- options.log.info("secret.set", {
21469
- name,
21470
- scope: scope.kind
21906
+ /**
21907
+ * A repository's registry, its `include`s read in, each item with the directory it came from;
21908
+ * read once per commit for every item of the call.
21909
+ */
21910
+ const registryOf = (owner, repo, sha) => {
21911
+ const key = `${owner}/${repo}@${sha}`;
21912
+ let known = registries.get(key);
21913
+ if (known === void 0) {
21914
+ known = readRegistry(owner, repo, sha);
21915
+ registries.set(key, known);
21916
+ }
21917
+ return known;
21918
+ };
21919
+ const readRegistry = async (owner, repo, sha) => {
21920
+ const found = [];
21921
+ const seen = /* @__PURE__ */ new Set();
21922
+ const visit = async (path) => {
21923
+ if (seen.has(path) || seen.size > 50) return;
21924
+ seen.add(path);
21925
+ const text = await repoFile(owner, repo, sha, path);
21926
+ if (text === void 0) {
21927
+ if (path === "registry.json") throw fail$1("MOSTRA_PACK_ITEM_NOT_FOUND", `${owner}/${repo} has no registry.json at its root (commit ${sha.slice(0, 12)}).`);
21928
+ throw fail$1("MOSTRA_PACK_ITEM_NOT_FOUND", `${owner}/${repo}'s ${path} isn't there.`);
21929
+ }
21930
+ let data;
21931
+ try {
21932
+ data = JSON.parse(text);
21933
+ } catch {
21934
+ throw fail$1("MOSTRA_PACK_ITEM_INVALID", `${owner}/${repo}'s ${path} isn't JSON.`);
21935
+ }
21936
+ const registry = RegistrySchema.safeParse(data);
21937
+ if (!registry.success) throw fail$1("MOSTRA_PACK_ITEM_INVALID", `${owner}/${repo}'s ${path} isn't a registry.`);
21938
+ const base = posix.dirname(path);
21939
+ for (const raw of data.items ?? []) found.push({
21940
+ item: raw,
21941
+ base
21471
21942
  });
21472
- return entry(dir, name, scope);
21473
- },
21474
- list(artifactId) {
21475
- return [...listScope({ kind: "home" }), ...artifactId ? listScope({
21476
- kind: "artifact",
21477
- artifactId
21478
- }) : []];
21479
- },
21480
- delete(name, scope) {
21481
- if (!SECRET_NAME_PATTERN.test(name)) throw invalidName(name);
21482
- const file = join(dirOf(scope), name);
21483
- if (!existsSync(file)) return false;
21484
- rmSync(file, { force: true });
21485
- options.log.info("secret.deleted", {
21486
- name,
21487
- scope: scope.kind
21943
+ for (const include of registry.data.include ?? []) await visit(posix.join(base, include));
21944
+ };
21945
+ await visit("registry.json");
21946
+ return found;
21947
+ };
21948
+ /** Reads one address into an item and its files' contents. */
21949
+ const read = async (address, text, from) => {
21950
+ if (address.kind === "file") {
21951
+ const path = isAbsolute(address.path) ? address.path : from?.base !== void 0 ? resolve(from.base, address.path) : resolve(cwd, address.path);
21952
+ let body;
21953
+ try {
21954
+ body = await readFile(path, "utf8");
21955
+ } catch {
21956
+ throw fail$1("MOSTRA_PACK_ITEM_NOT_FOUND", `There's no item at ${path}.`);
21957
+ }
21958
+ const item = parseItem(body, path);
21959
+ const contents = [];
21960
+ const dir = realpathSync(dirname(path));
21961
+ for (const file of item.files ?? []) if (file.content !== void 0) contents.push(file.content);
21962
+ else {
21963
+ let real;
21964
+ try {
21965
+ real = realpathSync(resolve(dir, file.path));
21966
+ } catch {
21967
+ throw fail$1("MOSTRA_PACK_ITEM_INVALID", `${path}'s file ${file.path} has no content and isn't beside the item.`);
21968
+ }
21969
+ if (!isInside$1(dir, real)) throw fail$1("MOSTRA_PACK_ITEM_INVALID", `${path}'s file ${file.path} is outside the item's directory, which Mostra doesn't read from.`);
21970
+ contents.push(await readFile(real, "utf8"));
21971
+ }
21972
+ return {
21973
+ item,
21974
+ source: path,
21975
+ contents,
21976
+ context: { base: dirname(path) }
21977
+ };
21978
+ }
21979
+ if (address.kind === "plugin") {
21980
+ const file = await context.pluginItem(address.package, address.item);
21981
+ if (file === void 0) throw fail$1("MOSTRA_PACK_ITEM_NOT_FOUND", `No installed plugin ${address.package} carries a pack "${address.item}".`);
21982
+ return read({
21983
+ kind: "file",
21984
+ path: file
21985
+ }, file, void 0);
21986
+ }
21987
+ if (address.kind === "repo-file") {
21988
+ const body = await repoFile(address.owner, address.repo, address.sha, address.path);
21989
+ const where = `${address.owner}/${address.repo}/${address.path}@${address.sha.slice(0, 12)}`;
21990
+ if (body === void 0) throw fail$1("MOSTRA_PACK_ITEM_NOT_FOUND", `There's no item ${where}.`);
21991
+ const item = parseItem(body, where);
21992
+ const contents = [];
21993
+ for (const file of item.files ?? []) {
21994
+ if (file.content !== void 0) {
21995
+ contents.push(file.content);
21996
+ continue;
21997
+ }
21998
+ const fileBody = await repoFile(address.owner, address.repo, address.sha, posix.join(posix.dirname(address.path), file.path));
21999
+ if (fileBody === void 0) throw fail$1("MOSTRA_PACK_ITEM_INVALID", `${where}: ${file.path} isn't in the repository.`);
22000
+ contents.push(fileBody);
22001
+ }
22002
+ return {
22003
+ item,
22004
+ source: `https://github.com/${address.owner}/${address.repo}/blob/${address.sha}/${address.path}`,
22005
+ contents,
22006
+ context: {
22007
+ github: {
22008
+ owner: address.owner,
22009
+ repo: address.repo,
22010
+ sha: address.sha
22011
+ },
22012
+ githubBase: posix.dirname(address.path)
22013
+ }
22014
+ };
22015
+ }
22016
+ if (address.kind === "github") {
22017
+ const sha = await commitOf(address.owner, address.repo, address.ref);
22018
+ const entry = (await registryOf(address.owner, address.repo, sha)).find((candidate) => typeof candidate.item === "object" && candidate.item !== null && candidate.item.name === address.item);
22019
+ if (entry === void 0) throw fail$1("MOSTRA_PACK_ITEM_NOT_FOUND", `${address.owner}/${address.repo}'s registry has no item "${address.item}" (commit ${sha.slice(0, 12)}).`);
22020
+ const where = `${address.owner}/${address.repo}/${address.item}@${sha.slice(0, 12)}`;
22021
+ const item = parseItem(JSON.stringify(entry.item), where);
22022
+ const contents = [];
22023
+ for (const file of item.files ?? []) {
22024
+ if (file.content !== void 0) {
22025
+ contents.push(file.content);
22026
+ continue;
22027
+ }
22028
+ const body = await repoFile(address.owner, address.repo, sha, posix.join(entry.base, file.path));
22029
+ if (body === void 0) throw fail$1("MOSTRA_PACK_ITEM_INVALID", `${where}: ${file.path} isn't in the repository.`);
22030
+ contents.push(body);
22031
+ }
22032
+ return {
22033
+ item,
22034
+ source: `https://github.com/${address.owner}/${address.repo}/tree/${sha}`,
22035
+ contents,
22036
+ context: {
22037
+ github: {
22038
+ owner: address.owner,
22039
+ repo: address.repo,
22040
+ sha
22041
+ },
22042
+ githubBase: entry.base
22043
+ }
22044
+ };
22045
+ }
22046
+ let url;
22047
+ let headers = {};
22048
+ if (address.kind === "url") url = address.url;
22049
+ else if (address.kind === "namespace") {
22050
+ const registry = context.components?.registries?.[address.namespace];
22051
+ if (registry === void 0) throw fail$1("MOSTRA_PACK_ADDRESS_INVALID", `The artifact's components.json registers no ${address.namespace} registry; add it to "registries" ("${address.namespace}": "https://…/{name}.json").`);
22052
+ const template = typeof registry === "string" ? registry : registry.url;
22053
+ const origin = /^[a-z][a-z0-9+.-]*:\/\/[^/?#]*/i.exec(template)?.[0] ?? template;
22054
+ if (origin.includes("${")) throw fail$1("MOSTRA_PACK_ADDRESS_INVALID", `The artifact's components.json names the ${address.namespace} registry's host through a variable (${origin}); write the host itself, and keep variables to its params and headers.`);
22055
+ const style = context.components?.style ?? DEFAULT_STYLE;
22056
+ const target = new URL(expand(template, context.env).replaceAll("{name}", address.item).replaceAll("{style}", style));
22057
+ if (typeof registry !== "string") {
22058
+ for (const [name, value] of Object.entries(registry.params ?? {})) target.searchParams.set(name, expand(value, context.env));
22059
+ headers = Object.fromEntries(Object.entries(registry.headers ?? {}).map(([name, value]) => [name, expand(value, context.env)]));
22060
+ }
22061
+ url = target.href;
22062
+ } else {
22063
+ const style = context.components?.style ?? DEFAULT_STYLE;
22064
+ url = `${withoutTrailingSlashes(context.env["REGISTRY_URL"] || SHADCN_REGISTRY)}/styles/${encodeURIComponent(style)}/${encodeURIComponent(address.name)}.json`;
22065
+ }
22066
+ const body = await readUrl(url, context, headers);
22067
+ if (body === void 0) throw fail$1("MOSTRA_PACK_ITEM_NOT_FOUND", `There's no item ${text} (${new URL(url).origin}${new URL(url).pathname} answered 404).`);
22068
+ const item = parseItem(body, text);
22069
+ const contents = [];
22070
+ for (const file of item.files ?? []) {
22071
+ if (file.content === void 0) throw fail$1("MOSTRA_PACK_ITEM_INVALID", `${text}: ${file.path} has no content; an item read from a URL carries its files' content.`);
22072
+ contents.push(file.content);
22073
+ }
22074
+ return {
22075
+ item,
22076
+ source: redactUrl(new URL(url)),
22077
+ contents,
22078
+ context: { url }
22079
+ };
22080
+ };
22081
+ /**
22082
+ * A registry dependency's address, read as shadcn reads it. A relative item file is relative to
22083
+ * the item that names it: beside a local item, in a GitHub item's repository at its commit,
22084
+ * under a URL item's URL. A remote item never names a file on this machine.
22085
+ */
22086
+ const dependencyAddress = (text, from) => {
22087
+ const parsed = parsePackAddress(text);
22088
+ if (parsed !== void 0) {
22089
+ if (parsed.kind === "file" && (from?.github !== void 0 || from?.url !== void 0)) {
22090
+ if (isAbsolute(parsed.path)) throw fail$1("MOSTRA_PACK_ADDRESS_INVALID", `A remote item names "${text}", a file on this machine, which Mostra doesn't read for it.`);
22091
+ if (from.github !== void 0) {
22092
+ const path = posix.normalize(posix.join(from.githubBase ?? ".", parsed.path));
22093
+ if (path.startsWith("..")) throw fail$1("MOSTRA_PACK_ADDRESS_INVALID", `"${text}" leaves the item's repository.`);
22094
+ return {
22095
+ kind: "repo-file",
22096
+ ...from.github,
22097
+ path
22098
+ };
22099
+ }
22100
+ return {
22101
+ kind: "url",
22102
+ url: new URL(parsed.path, from.url).href
22103
+ };
22104
+ }
22105
+ if (parsed.kind === "file" && from?.base !== void 0 && !isAbsolute(parsed.path)) return {
22106
+ kind: "file",
22107
+ path: resolve(from.base, parsed.path)
22108
+ };
22109
+ return parsed;
22110
+ }
22111
+ if (/^[a-z0-9][a-z0-9._-]*$/i.test(text)) return {
22112
+ kind: "name",
22113
+ name: text
22114
+ };
22115
+ throw fail$1("MOSTRA_PACK_ADDRESS_INVALID", `"${text}" isn't a registry item address.`);
22116
+ };
22117
+ const visit = async (text, address, requiredBy, from) => {
22118
+ const key = address.kind === "file" ? `file:${address.path}` : address.kind === "repo-file" ? `repo-file:${address.owner}/${address.repo}@${address.sha}/${address.path}` : address.kind === "url" ? `url:${address.url}` : `${address.kind}:${text}`;
22119
+ if (done.has(key) || visiting.has(key)) return;
22120
+ if (done.size >= ITEM_LIMIT) throw fail$1("MOSTRA_PACK_ITEM_INVALID", `More than ${ITEM_LIMIT} items: their registry dependencies don't end.`);
22121
+ visiting.add(key);
22122
+ const read_ = await read(address, text, from);
22123
+ for (const dependency of read_.item.registryDependencies ?? []) await visit(dependency, dependencyAddress(dependency, read_.context), read_.item.name, read_.context);
22124
+ visiting.delete(key);
22125
+ const entry = {
22126
+ item: read_.item,
22127
+ address: text,
22128
+ source: read_.source,
22129
+ ...requiredBy !== void 0 ? { requiredBy } : {},
22130
+ contents: read_.contents
22131
+ };
22132
+ done.set(key, entry);
22133
+ order.push(entry);
22134
+ };
22135
+ for (const spec of specs) {
22136
+ const address = parsePackAddress(spec);
22137
+ if (address === void 0) throw fail$1("MOSTRA_PACK_ADDRESS_INVALID", `"${spec}" isn't a registry item address.`);
22138
+ await visit(spec, address, void 0, void 0);
22139
+ }
22140
+ return order;
22141
+ }
22142
+ /** The artifact's `components.json`, when it has one Mostra can read. */
22143
+ async function readComponentsJson(root) {
22144
+ let text;
22145
+ try {
22146
+ text = await readFile(join(root, "components.json"), "utf8");
22147
+ } catch {
22148
+ return;
22149
+ }
22150
+ try {
22151
+ const data = JSON.parse(text);
22152
+ return typeof data === "object" && data !== null ? data : void 0;
22153
+ } catch {
22154
+ throw fail$1("MOSTRA_PACK_ITEM_INVALID", `${join(root, "components.json")} isn't JSON.`);
22155
+ }
22156
+ }
22157
+ //#endregion
22158
+ //#region src/packs/packs.ts
22159
+ /**
22160
+ * Source packs (D30, ROUND-3 §6.3, EX-03): `pack/add`, which `mostra add` calls. It copies shadcn
22161
+ * registry items (with or without a `mostra` block) into an artifact's source, as shadcn's own
22162
+ * `add` would into a project, so any shadcn item installs unchanged:
22163
+ *
22164
+ * 1. every item is read with its registry dependencies (`read.ts`), before anything is written;
22165
+ * 2. each file's place is found as shadcn finds it (`target`, `~/`, the `@components/`, `@ui/`,
22166
+ * `@lib/` and `@hooks/` aliases, else the directory of its type), checked against the artifact
22167
+ * (`checkArtifactPath`, no link out of it, no name differing from another only in case), and
22168
+ * `@/registry/<style>/…` imports point at the aliases;
22169
+ * 3. CSS (`cssVars`, `css`) joins one stylesheet in a block per item, replaced when the item is
22170
+ * added again: `components.json`'s `tailwind.css`, else a stylesheet the entry imports, else a
22171
+ * new `styles.css`;
22172
+ * 4. npm packages (the items' `dependencies` and any plain specs) are added as `deps/add` adds
22173
+ * them in one change of the working lockfile, which passes the plugin gate: the artifact's
22174
+ * plugins as they stand, and the licenses the items' packages and the items themselves
22175
+ * (`mostra.license`) bring, disclosed and acknowledged as a plugin's are (D31), before any
22176
+ * of the packages' scripts run;
22177
+ * 5. only once the layout is complete are the files written, each through a temporary file
22178
+ * renamed into place, checked again for clashes just before; every one is restored when any
22179
+ * fails or the lockfile can't be recorded.
22180
+ *
22181
+ * What an artifact has no place for (`envVars`, Tailwind 3's `tailwind.config`, `next/font`, a
22182
+ * design system's `registry:base`) is listed as notes, never applied half-way.
22183
+ */
22184
+ /** The default aliases, as `npx shadcn init` writes them, with `@/` the artifact's root. */
22185
+ const DEFAULT_ALIASES = {
22186
+ components: "components",
22187
+ ui: "components/ui",
22188
+ lib: "lib",
22189
+ hooks: "hooks",
22190
+ utils: "lib/utils"
22191
+ };
22192
+ /** Names a pack never writes: the artifact's packages and Mostra's own state. */
22193
+ const RESERVED = /* @__PURE__ */ new Set([
22194
+ "node_modules",
22195
+ ".mostra",
22196
+ ".git"
22197
+ ]);
22198
+ const fail = (code, message) => new RpcError(createDiagnostic(code, { message }));
22199
+ /** An alias of `components.json` as a path inside the artifact (`@/components/ui` → `components/ui`). */
22200
+ function aliasPath(value, fallback) {
22201
+ if (value === void 0) return fallback;
22202
+ return withoutTrailingSlashes(value.replace(/^@\//, "").replace(/^~\//, "")) || fallback;
22203
+ }
22204
+ /** Where a file of an item goes, as shadcn's `resolveFilePath` places it (shadcn 4.23.0). */
22205
+ function placeFile(file, aliases, pages = true) {
22206
+ const target = file.target;
22207
+ if (target !== void 0) {
22208
+ if (target.startsWith("~/")) return target.slice(2);
22209
+ const alias = /^@(components|ui|lib|hooks)\/(.+)$/.exec(target);
22210
+ if (alias) {
22211
+ const root = aliases[alias[1]];
22212
+ const placed = posix.normalize(posix.join(root, alias[2]));
22213
+ if (placed !== root && !placed.startsWith(`${root}/`)) throw fail("MOSTRA_PACK_TARGET_INVALID", `The target ${target} leaves the ${alias[1]} alias's directory.`);
22214
+ return placed;
22215
+ }
22216
+ const plain = target.replace(/^@([^/]+)\//, "$1/").replace(/^src\//, "");
22217
+ if (file.type === "registry:page") {
22218
+ if (!pages) return void 0;
22219
+ return plain.replace(/^app\//, "pages/").replace(/\/page(\.[jt]sx?)$/, "$1");
22220
+ }
22221
+ return plain;
22222
+ }
22223
+ const dir = file.type === "registry:ui" ? aliases.ui : file.type === "registry:lib" ? aliases.lib : file.type === "registry:hook" ? aliases.hooks : aliases.components;
22224
+ const segments = file.path.replace(/^\/|\/$/g, "").split("/");
22225
+ const last = dir.split("/").at(-1);
22226
+ const at = segments.indexOf(last ?? "");
22227
+ const rest = at === -1 ? segments.at(-1) : segments.slice(at + 1).join("/");
22228
+ return posix.join(dir, rest);
22229
+ }
22230
+ /** Points `@/registry/<style>/<kind>/…` imports at the artifact's aliases, as shadcn rewrites them. */
22231
+ function rewriteImports(content, aliases, placed = /* @__PURE__ */ new Map()) {
22232
+ return content.replace(/(["'])@\/(registry\/[^"']+)(["'])/g, (whole, open, path, close) => {
22233
+ const target = placed.get(path.replace(/\.[jt]sx?$/, ""));
22234
+ return target === void 0 ? whole : `${open}@/${target.replace(/\.[jt]sx?$/, "")}${close}`;
22235
+ }).replace(/(["'])@\/registry\/[^/"']+\/(ui|lib|hooks|components|blocks|examples)\//g, (_, quote, kind) => {
22236
+ return `${quote}@/${kind === "ui" ? aliases.ui : kind === "lib" ? aliases.lib : kind === "hooks" ? aliases.hooks : aliases.components}/`;
22237
+ });
22238
+ }
22239
+ /** Serializes an item's `css` the way shadcn writes it into a stylesheet. */
22240
+ function cssText(css, indent = "") {
22241
+ const lines = [];
22242
+ for (const [key, value] of Object.entries(css)) if (typeof value === "string") lines.push(`${indent}${key}: ${value};`);
22243
+ else if (Array.isArray(value)) for (const entry of value) if (typeof entry === "string") lines.push(`${indent}${key}: ${entry};`);
22244
+ else {
22245
+ lines.push(`${indent}${key} {`);
22246
+ lines.push(cssText(entry, `${indent} `));
22247
+ lines.push(`${indent}}`);
22248
+ }
22249
+ else if (Object.keys(value).length === 0 && key.startsWith("@")) lines.push(`${indent}${key};`);
22250
+ else {
22251
+ lines.push(`${indent}${key} {`);
22252
+ lines.push(cssText(value, `${indent} `));
22253
+ lines.push(`${indent}}`);
22254
+ }
22255
+ return lines.filter((line) => line !== "").join("\n");
22256
+ }
22257
+ /** The CSS an item adds: its variables and its rules. */
22258
+ function itemCss(item) {
22259
+ const parts = [];
22260
+ const declarations = (record) => Object.entries(record).map(([name, value]) => ` --${name.replace(/^--/, "")}: ${value};`);
22261
+ const light = item.cssVars?.light ?? {};
22262
+ const dark = item.cssVars?.dark ?? {};
22263
+ const theme = { ...item.cssVars?.theme ?? {} };
22264
+ for (const name of /* @__PURE__ */ new Set([...Object.keys(light), ...Object.keys(dark)])) {
22265
+ const bare = name.replace(/^--/, "");
22266
+ const value = light[name] ?? dark[name] ?? "";
22267
+ if (bare === "radius") Object.assign(theme, RADIUS_SCALE);
22268
+ else if (isColour(value)) {
22269
+ const key = bare === "sidebar-background" ? "color-sidebar" : `color-${bare}`;
22270
+ theme[key] ??= bare === "sidebar-background" ? "var(--sidebar)" : `var(--${bare})`;
22271
+ }
22272
+ }
22273
+ if (Object.keys(dark).length > 0) parts.push("@custom-variant dark (&:is(.dark *));");
22274
+ if (Object.keys(theme).length > 0) parts.push(`@theme inline {\n${declarations(theme).join("\n")}\n}`);
22275
+ if (Object.keys(light).length > 0) parts.push(`:root {\n${declarations(light).join("\n")}\n}`);
22276
+ if (Object.keys(dark).length > 0) parts.push(`.dark {\n${declarations(dark).join("\n")}\n}`);
22277
+ if (item.css !== void 0 && Object.keys(item.css).length > 0) parts.push(cssText(item.css));
22278
+ return parts.length > 0 ? parts.join("\n\n") : void 0;
22279
+ }
22280
+ /** The radius scale shadcn derives from `radius`. */
22281
+ const RADIUS_SCALE = {
22282
+ "radius-sm": "calc(var(--radius) * 0.6)",
22283
+ "radius-md": "calc(var(--radius) * 0.8)",
22284
+ "radius-lg": "var(--radius)",
22285
+ "radius-xl": "calc(var(--radius) * 1.4)",
22286
+ "radius-2xl": "calc(var(--radius) * 1.8)",
22287
+ "radius-3xl": "calc(var(--radius) * 2.2)",
22288
+ "radius-4xl": "calc(var(--radius) * 2.6)"
22289
+ };
22290
+ /** Whether a variable's value is a colour, as shadcn judges it. */
22291
+ function isColour(value) {
22292
+ if (/^(?:hsl|rgb|#|oklch)/.test(value) || value.includes("--color-")) return true;
22293
+ const parts = value.split(" ");
22294
+ return parts.length === 3 && parts.slice(1).every((part) => part.includes("%"));
22295
+ }
22296
+ /** `css` with the block of `item` set to `block` (added at the end the first time). */
22297
+ function withCssBlock(css, item, block) {
22298
+ const begin = `/* mostra add ${item}: begin */`;
22299
+ const end = `/* mostra add ${item}: end */`;
22300
+ const text = `${begin}\n${block}\n${end}`;
22301
+ const start = css.indexOf(begin);
22302
+ const stop = css.indexOf(end);
22303
+ if (start !== -1 && stop > start) return `${css.slice(0, start)}${text}${css.slice(stop + end.length)}`;
22304
+ return `${css.trimEnd()}${css.trim() === "" ? "" : "\n\n"}${text}\n`;
22305
+ }
22306
+ /** The stylesheets an entry imports, relative to the root (`import "./styles.css"`). */
22307
+ function importedStylesheets(entryText, entry) {
22308
+ const found = [];
22309
+ for (const match of entryText.matchAll(/import\s+(?:[^"';]+\s+from\s+)?["']([^"']+\.css)["']/g)) {
22310
+ const specifier = match[1];
22311
+ if (specifier.startsWith("./") || specifier.startsWith("../")) found.push(posix.normalize(posix.join(posix.dirname(entry), specifier)));
22312
+ else if (specifier.startsWith("@/")) found.push(specifier.slice(2));
22313
+ }
22314
+ return found;
22315
+ }
22316
+ /** Creates the packs of one instance. */
22317
+ function createPacks(options) {
22318
+ const { dependencies, plugins, log } = options;
22319
+ return { async add(input) {
22320
+ const components = input.kind === "dir" ? await readComponentsJson(input.root) : void 0;
22321
+ const isItem = (spec) => {
22322
+ const address = parsePackAddress(spec);
22323
+ if (address === void 0) return false;
22324
+ if (address.kind !== "namespace") return true;
22325
+ return components?.registries?.[address.namespace] !== void 0;
22326
+ };
22327
+ const itemSpecs = input.specs.filter(isItem);
22328
+ const plainSpecs = input.specs.filter((spec) => !isItem(spec));
22329
+ if (input.kind === "file" && itemSpecs.length > 0) throw fail("MOSTRA_PACK_TARGET_INVALID", `${input.target.artifactPath} is a single-file artifact, which holds no other files: move it into a directory (as index.tsx) to add ${itemSpecs.join(", ")} to it.`);
22330
+ const env = {
22331
+ ...options.env,
22332
+ ...input.environment ?? {}
22333
+ };
22334
+ const items = itemSpecs.length === 0 ? [] : await readItems(itemSpecs, {
22335
+ ...components !== void 0 ? { components } : {},
22336
+ env,
22337
+ offline: isOffline(options.env),
22338
+ pluginItem: (pkg, name) => plugins.packItem(input.target, pkg, name),
22339
+ ...options.github !== void 0 ? { github: options.github } : {}
22340
+ }, input.cwd);
22341
+ const aliases = {
22342
+ components: aliasPath(components?.aliases?.["components"], DEFAULT_ALIASES.components),
22343
+ ui: aliasPath(components?.aliases?.["ui"], DEFAULT_ALIASES.ui),
22344
+ lib: aliasPath(components?.aliases?.["lib"], DEFAULT_ALIASES.lib),
22345
+ hooks: aliasPath(components?.aliases?.["hooks"], DEFAULT_ALIASES.hooks)
22346
+ };
22347
+ const notes = [];
22348
+ const note = (message) => notes.push(createDiagnostic("MOSTRA_PACK_NOT_APPLIED", { message }));
22349
+ const planned = /* @__PURE__ */ new Map();
22350
+ const hasPages = existsSync(join(input.root, "pages"));
22351
+ const places = [];
22352
+ const placedByRegistryPath = /* @__PURE__ */ new Map();
22353
+ for (const read of items) (read.item.files ?? []).forEach((file, index) => {
22354
+ const placed = placeFile(file, aliases, hasPages);
22355
+ if (placed === void 0) {
22356
+ note(`${read.item.name}'s page ${file.target ?? file.path} wasn't written: the artifact has no pages/ (D57). Add pages/ to make it multi-page, then add the item again.`);
22357
+ return;
22358
+ }
22359
+ const check = checkArtifactPath(placed);
22360
+ if (!check.ok) throw fail("MOSTRA_PACK_TARGET_INVALID", check.reason === "outside" ? `${read.item.name}'s file ${file.path} would land at ${placed}, outside the artifact.` : `${read.item.name}'s file ${file.path} would land at ${placed}, whose name "${check.segment}" not every system can hold.`);
22361
+ const top = check.path.split("/")[0];
22362
+ if (RESERVED.has(top)) throw fail("MOSTRA_PACK_TARGET_INVALID", `${read.item.name}'s file ${file.path} would land in ${top}/, which an artifact's source never holds.`);
22363
+ places.push({
22364
+ read,
22365
+ index,
22366
+ path: check.path
22367
+ });
22368
+ placedByRegistryPath.set(file.path.replace(/^\//, "").replace(/\.[jt]sx?$/, ""), check.path);
22369
+ });
22370
+ for (const { read, index, path } of places) {
22371
+ const file = (read.item.files ?? [])[index];
22372
+ const content = file.type === "registry:file" || file.type === "registry:item" ? read.contents[index] : rewriteImports(read.contents[index], aliases, placedByRegistryPath);
22373
+ const key = path.toLowerCase();
22374
+ const earlier = planned.get(key);
22375
+ if (earlier !== void 0 && earlier.path !== path) throw fail("MOSTRA_PACK_TARGET_INVALID", `${earlier.path} and ${path} differ only in case, which not every system can hold apart.`);
22376
+ planned.set(key, {
22377
+ path,
22378
+ content,
22379
+ item: read.item.name
22380
+ });
22381
+ }
22382
+ for (const read of items) {
22383
+ if (read.item.envVars !== void 0 && Object.keys(read.item.envVars).length > 0) note(`${read.item.name} asks for environment variables (${Object.keys(read.item.envVars).join(", ")}); an artifact's server code reads secrets instead: mostra secret set NAME --artifact <path>.`);
22384
+ if (read.item.tailwind !== void 0 && Object.keys(read.item.tailwind).length > 0) note(`${read.item.name} carries a Tailwind 3 configuration (tailwind.config), which Tailwind 4 doesn't read; move its theme into your stylesheet's @theme.`);
22385
+ if (read.item.font !== void 0) note(`${read.item.name} installs the font ${read.item.font.family} through ${read.item.font.provider}; load it yourself (${read.item.font.dependency ?? "a @fontsource package"}) and set ${read.item.font.variable}.`);
22386
+ if (read.item.type === "registry:base" || read.item.type === "registry:style") note(`${read.item.name} is a ${read.item.type}, a project configuration an artifact doesn't take; its CSS and files were added.`);
22387
+ }
22388
+ const cssBlocks = items.map((read) => ({
22389
+ name: read.item.name,
22390
+ css: itemCss(read.item)
22391
+ })).filter((entry) => entry.css !== void 0);
22392
+ let stylesheet;
22393
+ if (cssBlocks.length > 0) {
22394
+ const imported = importedStylesheets(await readFile(join(input.root, input.entry), "utf8").catch(() => ""), input.entry);
22395
+ const configured = components?.tailwind?.css;
22396
+ const path = configured ? aliasPath(configured, configured).replace(/^\.\//, "") : imported[0] ?? "styles.css";
22397
+ const check = checkArtifactPath(path);
22398
+ if (!check.ok) throw fail("MOSTRA_PACK_TARGET_INVALID", `The stylesheet ${path} isn't a path inside the artifact.`);
22399
+ const before = await readFile(join(input.root, check.path), "utf8").catch(() => void 0);
22400
+ let after = before ?? "@import \"tailwindcss\";\n";
22401
+ for (const block of cssBlocks) after = withCssBlock(after, block.name, block.css);
22402
+ stylesheet = {
22403
+ path: check.path,
22404
+ before,
22405
+ after
22406
+ };
22407
+ if (!imported.includes(check.path)) notes.push(createDiagnostic("MOSTRA_PACK_CSS_UNIMPORTED", { message: `The items' CSS is in ${check.path}, which ${input.entry} doesn't import yet: add import "./${check.path}"; to it.` }));
22408
+ }
22409
+ for (const file of planned.values()) if (stylesheet !== void 0 && file.path === stylesheet.path) throw fail("MOSTRA_PACK_TARGET_INVALID", `${file.item} writes ${file.path}, the stylesheet the items' CSS joins.`);
22410
+ const command = `mostra add ${input.specs.map(shellWord).join(" ")} --artifact ${shellWord(input.target.artifactPath)}`;
22411
+ const judge = async () => {
22412
+ const changes = [];
22413
+ const clashes = [];
22414
+ for (const file of planned.values()) {
22415
+ await checkPlace(input.root, file.path);
22416
+ const existing = await readFile(join(input.root, file.path), "utf8").catch(() => void 0);
22417
+ if (existing === void 0) changes.push({
22418
+ path: file.path,
22419
+ action: "created",
22420
+ content: file.content
22421
+ });
22422
+ else if (existing === file.content) changes.push({
22423
+ path: file.path,
22424
+ action: "unchanged",
22425
+ content: file.content
22426
+ });
22427
+ else if (input.overwrite) changes.push({
22428
+ path: file.path,
22429
+ action: "overwritten",
22430
+ content: file.content
22431
+ });
22432
+ else clashes.push(file.path);
22433
+ }
22434
+ if (clashes.length > 0) throw new RpcError(createDiagnostic("MOSTRA_PACK_FILE_EXISTS", {
22435
+ message: `The artifact already has ${clashes.join(", ")}, with other content. Nothing was written.`,
22436
+ fix: {
22437
+ kind: "command",
22438
+ command: `${command} --overwrite`
22439
+ }
22440
+ }));
22441
+ if (stylesheet !== void 0) {
22442
+ await checkPlace(input.root, stylesheet.path);
22443
+ const now = await readFile(join(input.root, stylesheet.path), "utf8").catch(() => void 0);
22444
+ let after = now ?? "@import \"tailwindcss\";\n";
22445
+ for (const block of cssBlocks) after = withCssBlock(after, block.name, block.css);
22446
+ if (now !== after) changes.push({
22447
+ path: stylesheet.path,
22448
+ action: now === void 0 ? "created" : "updated",
22449
+ content: after
22450
+ });
22451
+ }
22452
+ return changes;
22453
+ };
22454
+ const firstLook = await judge();
22455
+ const itemPackages = [...new Set(items.flatMap((read) => [...read.item.dependencies ?? []]))];
22456
+ const packages = [.../* @__PURE__ */ new Set([...itemPackages, ...plainSpecs])];
22457
+ const summaries = items.map((read) => ({
22458
+ name: read.item.name,
22459
+ type: read.item.type,
22460
+ address: read.address,
22461
+ source: read.source,
22462
+ ...read.requiredBy !== void 0 ? { requiredBy: read.requiredBy } : {},
22463
+ ...read.item.mostra?.fields !== void 0 ? { fields: [...read.item.mostra.fields] } : {}
22464
+ }));
22465
+ const devDependencies = [...new Set(items.flatMap((read) => [...read.item.devDependencies ?? []]))];
22466
+ if (devDependencies.length > 0) note(`The items name development packages (${devDependencies.join(", ")}), which an artifact's build doesn't use; add any the page imports with mostra add.`);
22467
+ const names = itemPackages.map(packageName);
22468
+ const itemLicenses = items.flatMap((read) => read.item.mostra?.license !== void 0 ? [{
22469
+ name: read.item.name,
22470
+ license: read.item.mostra.license,
22471
+ ...read.item.mostra.licenseClass !== void 0 ? { class: read.item.mostra.licenseClass } : {}
22472
+ }] : []);
22473
+ let changes = firstLook;
22474
+ return dependencies.change({
22475
+ ...input.target,
22476
+ add: packages,
22477
+ request: input.request
22478
+ }, async (staged) => {
22479
+ const admitted = await plugins.admitChange({
22480
+ kind: "artifact",
22481
+ target: input.target
22482
+ }, {
22483
+ staged,
22484
+ packages: names,
22485
+ items: itemLicenses,
22486
+ accept: input.accept,
22487
+ command
22488
+ });
22489
+ return {
22490
+ plugins: admitted.plugins,
22491
+ licenses: admitted.licenses,
22492
+ write: async () => {
22493
+ changes = await judge();
22494
+ const written = await writeAll(input.root, changes);
22495
+ log.info("packs.added", {
22496
+ items: summaries.map((item) => item.name),
22497
+ files: changes.length,
22498
+ packages: staged.added.map((pkg) => pkg.name)
22499
+ });
22500
+ return written;
22501
+ },
22502
+ result: (lockDigest) => ({
22503
+ items: summaries,
22504
+ files: changes.map(({ path, action }) => ({
22505
+ path,
22506
+ action
22507
+ })),
22508
+ packages: [...staged.added],
22509
+ licenses: [...admitted.disclosures],
22510
+ lockDigest,
22511
+ notes
22512
+ })
22513
+ };
22514
+ });
22515
+ } };
22516
+ }
22517
+ /** An npm spec's package name (`@scope/name@1` → `@scope/name`). */
22518
+ function packageName(spec) {
22519
+ const at = spec.indexOf("@", spec.startsWith("@") ? 1 : 0);
22520
+ return at === -1 ? spec : spec.slice(0, at);
22521
+ }
22522
+ /**
22523
+ * Refuses a place that leads out of the artifact or onto something that isn't a file: a link or
22524
+ * a file where a directory is needed, a link or a directory where the file goes, or a name that
22525
+ * differs from one already there only in case.
22526
+ */
22527
+ async function checkPlace(root, path) {
22528
+ const segments = path.split("/");
22529
+ let at = root;
22530
+ for (const [index, segment] of segments.entries()) {
22531
+ let entries;
22532
+ try {
22533
+ entries = await readdir(at);
22534
+ } catch {
22535
+ return;
22536
+ }
22537
+ const exact = entries.includes(segment);
22538
+ const folded = entries.find((entry) => entry !== segment && entry.toLowerCase() === segment.toLowerCase());
22539
+ if (!exact && folded !== void 0) throw fail("MOSTRA_PACK_TARGET_INVALID", `${path} differs only in case from ${[...segments.slice(0, index), folded].join("/")}, which the artifact already has.`);
22540
+ at = join(at, segment);
22541
+ if (!exact) return;
22542
+ const info = await lstat(at);
22543
+ const last = index === segments.length - 1;
22544
+ if (info.isSymbolicLink()) throw fail("MOSTRA_PACK_TARGET_INVALID", `${segments.slice(0, index + 1).join("/")} is a link; a pack writes only inside the artifact.`);
22545
+ if (last ? !info.isFile() : !info.isDirectory()) throw fail("MOSTRA_PACK_TARGET_INVALID", `${segments.slice(0, index + 1).join("/")} is ${last ? "not a file" : "a file, not a folder"}.`);
22546
+ }
22547
+ }
22548
+ /**
22549
+ * Writes every change, each through a temporary file; restores everything when one fails. The
22550
+ * replaced files stay aside until `commit` (the lockfile was recorded) or `rollback` (it wasn't).
22551
+ */
22552
+ async function writeAll(root, changes) {
22553
+ const token = randomBytes(6).toString("hex");
22554
+ const done = [];
22555
+ const createdDirs = [];
22556
+ try {
22557
+ for (const change of changes) {
22558
+ if (change.action === "unchanged") continue;
22559
+ const file = join(root, ...change.path.split("/"));
22560
+ let dir = dirname(file);
22561
+ const missing = [];
22562
+ while (!existsSync(dir) && dir.length > root.length) {
22563
+ missing.unshift(dir);
22564
+ dir = dirname(dir);
22565
+ }
22566
+ for (const created of missing) {
22567
+ await mkdir(created);
22568
+ createdDirs.push(created);
22569
+ }
22570
+ const temporary = join(dirname(file), `.${basename(file)}.mostra-${token}.tmp`);
22571
+ await writeFile(temporary, change.content);
22572
+ let backup;
22573
+ if (existsSync(file)) {
22574
+ backup = join(dirname(file), `.${basename(file)}.mostra-${token}.old`);
22575
+ await rename(file, backup);
22576
+ }
22577
+ try {
22578
+ await rename(temporary, file);
22579
+ } catch (error) {
22580
+ if (backup !== void 0) await rename(backup, file);
22581
+ await rm(temporary, { force: true });
22582
+ throw error;
22583
+ }
22584
+ done.push({
22585
+ path: file,
22586
+ ...backup !== void 0 ? { backup } : {}
22587
+ });
22588
+ }
22589
+ } catch (error) {
22590
+ await restore();
22591
+ throw fail("MOSTRA_PACK_TARGET_INVALID", `Writing the items' files failed (${error instanceof Error ? error.message : String(error)}); nothing was changed.`);
22592
+ }
22593
+ async function restore() {
22594
+ for (const entry of [...done].reverse()) {
22595
+ await rm(entry.path, { force: true });
22596
+ if (entry.backup !== void 0) await rename(entry.backup, entry.path);
22597
+ }
22598
+ for (const created of [...createdDirs].reverse()) await rm(created, {
22599
+ recursive: true,
22600
+ force: true
22601
+ });
22602
+ }
22603
+ return {
22604
+ commit: async () => {
22605
+ for (const entry of done) if (entry.backup !== void 0) await rm(entry.backup, { force: true });
22606
+ },
22607
+ rollback: restore
22608
+ };
22609
+ }
22610
+ //#endregion
22611
+ //#region src/plugins/methods.ts
22612
+ /**
22613
+ * The plugin system's methods of the host protocol (INTERFACES §14): `plugin/validate`,
22614
+ * `plugin/add`, `plugin/list`, `plugin/remove`, `plugin/export` and `plugin/commands`
22615
+ * (`pack/add` is the packs module's). Each that names an artifact runs in its source path's queue, as its publishes and
22616
+ * `deps/add` do, through the publisher; the home's own plugins have one queue of their own (the
22617
+ * working lockfile `home:plugins`).
22618
+ */
22619
+ const usage = (message) => new RpcError(createDiagnostic("MOSTRA_PLUGIN_SCOPE_INVALID", { message }));
22620
+ /** The handlers of the plugin system's methods. */
22621
+ function pluginMethods(options) {
22622
+ /** Runs `task` in the scope the params name: exactly one of `artifact` and `home`. */
22623
+ const inScope = (params, task) => {
22624
+ if (params.artifact === void 0 === (params.home !== true)) throw usage("Name exactly one of an artifact (--artifact) and the home (--global).");
22625
+ if (params.home === true) return options.publisher().withHome(() => task({ kind: "home" }));
22626
+ return options.publisher().withArtifact(params.artifact, ({ target }) => task({
22627
+ kind: "artifact",
22628
+ target
22629
+ }));
22630
+ };
22631
+ return [
22632
+ handler(pluginValidateMethod, (params) => options.plugins().validate(params.path, params.acceptLicenses ?? [])),
22633
+ handler(pluginAddMethod, async (params) => {
22634
+ const result = await inScope(params, (scope) => options.plugins().add(scope, {
22635
+ packages: params.packages,
22636
+ accept: params.acceptLicenses ?? [],
22637
+ request: requestKey("plugin/add", params)
22638
+ }));
22639
+ if (params.artifact !== void 0) options.dependenciesChanged?.(params.artifact);
22640
+ return result;
22641
+ }),
22642
+ handler(pluginListMethod, (params) => inScope(params, (scope) => options.plugins().list(scope))),
22643
+ handler(pluginRemoveMethod, async (params) => {
22644
+ const result = await inScope(params, (scope) => options.plugins().remove(scope, {
22645
+ packages: params.packages,
22646
+ request: requestKey("plugin/remove", params)
22647
+ }));
22648
+ if (params.artifact !== void 0) options.dependenciesChanged?.(params.artifact);
22649
+ return result;
22650
+ }),
22651
+ handler(pluginCommandsMethod, async (params) => {
22652
+ if (params.artifact === void 0) return { commands: await options.plugins().commands(void 0) };
22653
+ return options.publisher().withArtifact(params.artifact, async ({ target }) => ({ commands: await options.plugins().commands(target) })).catch(async (error) => {
22654
+ if (error instanceof RpcError && error.diagnostic.code.startsWith("MOSTRA_ARTIFACT_")) return { commands: await options.plugins().commands(void 0) };
22655
+ throw error;
22656
+ });
22657
+ }),
22658
+ handler(pluginExportMethod, async (params) => {
22659
+ const { detail, summary, versionDir } = await options.publisher().exportable({
22660
+ ...params,
22661
+ artifact: canonicalRef(params.artifact)
22662
+ });
22663
+ const exporters = await options.plugins().exporters({
22664
+ artifactId: detail.id,
22665
+ versionDir,
22666
+ ...detail.source !== void 0 ? { sourceDir: detail.source } : {}
22667
+ });
22668
+ const exporter = exporters.find((candidate) => candidate.id === params.exporter);
22669
+ if (exporter === void 0) throw new RpcError(createDiagnostic("MOSTRA_PLUGIN_EXPORTER_UNKNOWN", { message: `No plugin of ${detail.title}'s version ${summary.number} or of the home contributes the exporter "${params.exporter}"; the exporters available are bundle${exporters.map((candidate) => `, ${candidate.id}`).join("")}.` }));
22670
+ if (!isAbsolute(params.out)) throw new RpcError(createDiagnostic("MOSTRA_HOST_INVALID_PARAMS", { message: "out must be an absolute path." }));
22671
+ const existing = await stat(params.out).catch(() => void 0);
22672
+ if (existing !== void 0 && (!existing.isDirectory() || (await readdir(params.out)).length > 0)) throw new RpcError(createDiagnostic("MOSTRA_ARTIFACT_DIR_NOT_EMPTY", { message: `${params.out} already exists${existing.isDirectory() ? " and isn't empty" : ""}.` }));
22673
+ const registry = await readFile(join(versionDir, "registry.json"), "utf8").then((text) => JSON.parse(text)).catch(() => ({}));
22674
+ const answer = await options.plugins().runExport({
22675
+ exporter,
22676
+ versionDir,
22677
+ version: {
22678
+ artifactId: detail.id,
22679
+ versionId: summary.id,
22680
+ number: summary.number,
22681
+ title: detail.title,
22682
+ ...detail.description !== void 0 ? { description: detail.description } : {},
22683
+ manifest: detail.manifest ?? {},
22684
+ registry,
22685
+ server: existsSync(join(versionDir, "server", "entry.mjs")),
22686
+ publishedAt: summary.publishedAt
22687
+ },
22688
+ options: params.options ?? {}
22689
+ });
22690
+ const fail = (reason) => new RpcError(createDiagnostic("MOSTRA_PLUGIN_FAILED", { message: `The exporter ${exporter.id} (${exporter.package}) ${reason}. Nothing was written.` }));
22691
+ const planned = [];
22692
+ const seen = /* @__PURE__ */ new Set();
22693
+ for (const file of answer.files) {
22694
+ const check = checkArtifactPath(file.path);
22695
+ if (!check.ok) throw fail(`returned the file "${file.path.slice(0, 200)}", which isn't a path inside its output`);
22696
+ if (seen.has(check.path.toLowerCase())) throw fail(`returned the file "${check.path}" twice`);
22697
+ seen.add(check.path.toLowerCase());
22698
+ planned.push({
22699
+ path: check.path,
22700
+ data: "text" in file ? file.text : Buffer.from(file.base64, "base64")
22701
+ });
22702
+ }
22703
+ for (const file of planned) {
22704
+ const segments = file.path.toLowerCase().split("/");
22705
+ for (let length = 1; length < segments.length; length += 1) if (seen.has(segments.slice(0, length).join("/"))) throw fail(`returned both "${segments.slice(0, length).join("/")}" and "${file.path}", a file where a directory must be`);
22706
+ }
22707
+ if (answer.output.layout === "file" && planned.length !== 1) throw fail(`writes one file (its output's layout is "file"), and returned ${planned.length}`);
22708
+ const scratch = `${params.out}.mostra-${randomBytes(6).toString("hex")}.tmp`;
22709
+ const written = [];
22710
+ try {
22711
+ if (answer.output.layout === "file") {
22712
+ const only = planned[0];
22713
+ await mkdir(dirname(params.out), { recursive: true });
22714
+ await writeFile(scratch, only.data);
22715
+ if (existing !== void 0) await rmdir(params.out);
22716
+ await renamePath(scratch, params.out);
22717
+ written.push(params.out);
22718
+ } else {
22719
+ for (const file of planned) {
22720
+ const path = join(scratch, ...file.path.split("/"));
22721
+ await mkdir(dirname(path), { recursive: true });
22722
+ await writeFile(path, file.data);
22723
+ written.push(join(params.out, ...file.path.split("/")));
22724
+ }
22725
+ await mkdir(dirname(params.out), { recursive: true });
22726
+ if (existing !== void 0) await rmdir(params.out);
22727
+ await renamePath(scratch, params.out);
22728
+ }
22729
+ } catch (problem) {
22730
+ await removeTree(scratch).catch(() => void 0);
22731
+ throw fail(`couldn't be written (${problem instanceof Error ? problem.message : String(problem)})`);
22732
+ }
22733
+ options.log.info("plugins.exported", {
22734
+ artifactId: detail.id,
22735
+ versionId: summary.id,
22736
+ exporter: exporter.id,
22737
+ files: written.length
22738
+ });
22739
+ const findings = answer.findings.flatMap((value) => {
22740
+ const finding = value;
22741
+ if (typeof finding.code !== "string" || typeof finding.message !== "string") return [];
22742
+ return [{
22743
+ code: finding.code.slice(0, 64),
22744
+ severity: finding.severity === "error" || finding.severity === "hint" ? finding.severity : "warning",
22745
+ message: finding.message,
22746
+ ...typeof finding.hint === "string" ? { hint: finding.hint } : {}
22747
+ }];
22748
+ });
22749
+ const entry = answer.output.layout === "file" ? params.out : answer.entry !== void 0 && seen.has(answer.entry.toLowerCase()) ? join(params.out, ...answer.entry.split("/")) : void 0;
22750
+ return {
22751
+ files: written,
22752
+ ...entry !== void 0 ? { entry } : {},
22753
+ versionId: summary.id,
22754
+ exporter: {
22755
+ id: exporter.id,
22756
+ package: exporter.package
22757
+ },
22758
+ findings
22759
+ };
22760
+ })
22761
+ ];
22762
+ }
22763
+ //#endregion
22764
+ //#region src/plugins/location.ts
22765
+ /**
22766
+ * Where a JSON path sits in a JSON text, so a diagnostic about a manifest field points at its line
22767
+ * and column in `package.json` (INTERFACES §13's location). A small scanner over the text as it
22768
+ * is: it never reformats or reparses it into something else.
22769
+ */
22770
+ /** The 1-based line and column of the value at `path` (or of the closest ancestor found). */
22771
+ function jsonLocation(text, path) {
22772
+ let at = 0;
22773
+ const skip = () => {
22774
+ while (at < text.length && /\s/.test(text[at])) at += 1;
22775
+ };
22776
+ const string = () => {
22777
+ let value = "";
22778
+ at += 1;
22779
+ while (at < text.length && text[at] !== "\"") if (text[at] === "\\") {
22780
+ value += text.slice(at, at + 2);
22781
+ at += 2;
22782
+ } else {
22783
+ value += text[at];
22784
+ at += 1;
22785
+ }
22786
+ at += 1;
22787
+ try {
22788
+ return JSON.parse(`"${value}"`);
22789
+ } catch {
22790
+ return value;
22791
+ }
22792
+ };
22793
+ const skipValue = () => {
22794
+ skip();
22795
+ const open = text[at];
22796
+ if (open === "\"") {
22797
+ string();
22798
+ return;
22799
+ }
22800
+ if (open === "{" || open === "[") {
22801
+ let depth = 0;
22802
+ while (at < text.length) {
22803
+ const char = text[at];
22804
+ if (char === "\"") {
22805
+ string();
22806
+ continue;
22807
+ }
22808
+ if (char === "{" || char === "[") depth += 1;
22809
+ if (char === "}" || char === "]") depth -= 1;
22810
+ at += 1;
22811
+ if (depth === 0) return;
22812
+ }
22813
+ return;
22814
+ }
22815
+ while (at < text.length && !/[,}\]\s]/.test(text[at])) at += 1;
22816
+ };
22817
+ let found = 0;
22818
+ skip();
22819
+ for (const part of path) {
22820
+ skip();
22821
+ const open = text[at];
22822
+ if (open === "{" && typeof part === "string") {
22823
+ at += 1;
22824
+ let hit = false;
22825
+ for (;;) {
22826
+ skip();
22827
+ if (text[at] === "}" || at >= text.length) break;
22828
+ const keyAt = at;
22829
+ const key = string();
22830
+ skip();
22831
+ at += 1;
22832
+ if (key === part) {
22833
+ skip();
22834
+ found = keyAt;
22835
+ hit = true;
22836
+ break;
22837
+ }
22838
+ skipValue();
22839
+ skip();
22840
+ if (text[at] === ",") at += 1;
22841
+ }
22842
+ if (!hit) break;
22843
+ } else if (open === "[" && typeof part === "number") {
22844
+ at += 1;
22845
+ let index = 0;
22846
+ let hit = false;
22847
+ for (;;) {
22848
+ skip();
22849
+ if (text[at] === "]" || at >= text.length) break;
22850
+ if (index === part) {
22851
+ found = at;
22852
+ hit = true;
22853
+ break;
22854
+ }
22855
+ skipValue();
22856
+ skip();
22857
+ if (text[at] === ",") at += 1;
22858
+ index += 1;
22859
+ }
22860
+ if (!hit) break;
22861
+ } else break;
22862
+ }
22863
+ const lines = text.slice(0, found).split("\n");
22864
+ return {
22865
+ line: lines.length,
22866
+ column: (lines.at(-1)?.length ?? 0) + 1
22867
+ };
22868
+ }
22869
+ //#endregion
22870
+ //#region src/plugins/plugins.ts
22871
+ /**
22872
+ * Plugins (D30, D31, INTERFACES §14; EX-01, EX-02, EX-04): npm packages with a `"mostra"`
22873
+ * manifest, installed for one artifact (recorded in its working lockfile, frozen into each
22874
+ * version's `lock.yaml`) or for the whole home (exporters and CLI commands, ROUND-3 §6.4).
22875
+ *
22876
+ * Every lockfile that names plugins passes one gate (`admit`, D172 items 5, 7 and 8), whoever
22877
+ * changes or uses it: `plugin/add` and `plugin/remove`, `pack/add`, `deps/add`, and the resolution
22878
+ * of `verify` and `publish` (the deps module calls it). In this order, each refusing before the
22879
+ * next starts:
22880
+ * 1. each manifest (`checkPluginManifest`), its contract ranges against what this release
22881
+ * implements, the scope it is installed in, and conflicts within the scope (two plugins with
22882
+ * one ID, a command that begins another's, an ID Mostra builds in);
22883
+ * 2. the licenses of everything the change brings, classed (D31), while the install's lifecycle
22884
+ * scripts are held: one that needs an acknowledgment and has none refuses before any of the
22885
+ * packages' code or scripts have run;
22886
+ * 3. the held scripts, then each Node.js entry, loaded in a plugin child (never the supervisor,
22887
+ * RT-02), which must export a definition stamped with its contract on a line this release
22888
+ * serves.
22889
+ *
22890
+ * ```ts
22891
+ * const plugins = createPlugins({ home, dependencies, processes, log, env, policy });
22892
+ * await plugins.add({ kind: "artifact", target }, { packages: ["mostra-pdf"], accept: [] });
22893
+ * createDependencies({ …, plugins: () => plugins }); // verify, publish and deps/add pass the gate
22894
+ * ```
22895
+ */
22896
+ /**
22897
+ * `MOSTRA_TEST_CONTRACT_VERSIONS` (tests only): JSON naming, by contract, the versions a runtime
22898
+ * stood in for serves, `{"exporter":["0.0.0"]}`; the others keep this release's.
22899
+ */
22900
+ function testContractVersions(text) {
22901
+ const parsed = JSON.parse(text);
22902
+ return (contract) => parsed[contract] ?? PLUGIN_CONTRACTS[contract].implements;
22903
+ }
22904
+ /** The key of the home's own working lockfile. */
22905
+ const HOME_KEY = "home:plugins";
22906
+ /** The plugin child's entry: the compiled one beside the compiled supervisor, else the source. */
22907
+ function childEntry() {
22908
+ return fileURLToPath(import.meta.url).endsWith(".ts") ? join(runtimeRoot$1(), "src/plugins/child/host.ts") : join(runtimeRoot$1(), "dist/plugins/child/host.js");
22909
+ }
22910
+ /** `inner` is `outer` or inside it (both real paths). */
22911
+ function isInside(outer, inner) {
22912
+ const from = relative(outer, inner);
22913
+ return from === "" || !from.startsWith(`..${sep}`) && from !== ".." && !isAbsolute(from);
22914
+ }
22915
+ const error = (code, message) => new RpcError(createDiagnostic(code, { message }));
22916
+ /** Creates the plugins of one instance. */
22917
+ function createPlugins(options) {
22918
+ const implementedOf = (contract) => options.implemented?.(contract) ?? PLUGIN_CONTRACTS[contract].implements;
22919
+ const { dependencies, log } = options;
22920
+ const homeTarget = {
22921
+ key: HOME_KEY,
22922
+ artifactDir: join(options.home, "plugins"),
22923
+ artifactPath: "--global"
22924
+ };
22925
+ const childTimeoutMs = options.childTimeoutMs ?? 12e4;
22926
+ const targetOf = async (scope) => {
22927
+ if (scope.kind === "artifact") return scope.target;
22928
+ await mkdir(homeTarget.artifactDir, { recursive: true });
22929
+ return homeTarget;
22930
+ };
22931
+ /** Reads a package directory's `package.json` and manifest. */
22932
+ const readPackage = async (dir, scope) => {
22933
+ const real = realpathSync(dir);
22934
+ const packageFile = join(real, "package.json");
22935
+ const text = await readFile(packageFile, "utf8");
22936
+ let json;
22937
+ try {
22938
+ json = JSON.parse(text);
22939
+ } catch {
22940
+ throw new RpcError(createDiagnostic("MOSTRA_PLUGIN_MANIFEST_INVALID", {
22941
+ message: `${packageFile} isn't JSON.`,
22942
+ location: {
22943
+ file: packageFile,
22944
+ line: 1,
22945
+ column: 1
22946
+ }
22947
+ }));
22948
+ }
22949
+ const name = typeof json["name"] === "string" ? json["name"] : "";
22950
+ const version = typeof json["version"] === "string" ? json["version"] : "0.0.0";
22951
+ const issues = [];
22952
+ let manifest;
22953
+ if (json["mostra"] !== void 0) {
22954
+ const check = checkPluginManifest(json["mostra"]);
22955
+ manifest = check.manifest;
22956
+ for (const issue of check.issues) issues.push(createDiagnostic(issue.severity === "error" ? "MOSTRA_PLUGIN_MANIFEST_INVALID" : "MOSTRA_PLUGIN_MANIFEST_WARNING", {
22957
+ message: `${issue.path.join(".")}: ${issue.message}`,
22958
+ location: {
22959
+ file: packageFile,
22960
+ ...jsonLocation(text, issue.path)
22961
+ }
22962
+ }));
22963
+ }
22964
+ return {
22965
+ name,
22966
+ version,
22967
+ dir: real,
22968
+ packageFile,
22969
+ text,
22970
+ json,
22971
+ ...manifest ? { manifest } : {},
22972
+ issues,
22973
+ scope
22974
+ };
22975
+ };
22976
+ const at = (plugin, path) => ({
22977
+ file: plugin.packageFile,
22978
+ ...jsonLocation(plugin.text, ["mostra", ...path])
22979
+ });
22980
+ /** The checks of one set of plugins that need no code to run: ranges, scope, files, platform. */
22981
+ const staticChecks = (plugin) => {
22982
+ const found = [...plugin.issues];
22983
+ const manifest = plugin.manifest;
22984
+ if (manifest === void 0) {
22985
+ if (plugin.json["mostra"] === void 0) found.push(createDiagnostic("MOSTRA_PLUGIN_NOT_A_PLUGIN", {
22986
+ message: `${plugin.name || plugin.dir} has no "mostra" key in its package.json, so it isn't a Mostra plugin.`,
22987
+ location: {
22988
+ file: plugin.packageFile,
22989
+ line: 1,
22990
+ column: 1
22991
+ }
22992
+ }));
22993
+ return found;
22994
+ }
22995
+ for (const [contract, range] of Object.entries(manifest.contracts)) {
22996
+ const valid = semver.validRange(range);
22997
+ const implemented = implementedOf(contract);
22998
+ if (valid === null) found.push(createDiagnostic("MOSTRA_PLUGIN_MANIFEST_INVALID", {
22999
+ message: `contracts.${contract}: "${range}" isn't a semver range.`,
23000
+ location: at(plugin, ["contracts", contract])
23001
+ }));
23002
+ else if (!implemented.some((version) => semver.satisfies(version, range))) found.push(createDiagnostic("MOSTRA_PLUGIN_CONTRACT_UNSUPPORTED", {
23003
+ message: `${plugin.name}@${plugin.version} needs the ${contract} contract at ${range}; this Mostra implements ${PLUGIN_CONTRACTS[contract].package} ${implemented.join(", ")}.`,
23004
+ location: at(plugin, ["contracts", contract])
23005
+ }));
23006
+ }
23007
+ if (!manifestScopes(manifest).includes(plugin.scope)) found.push(createDiagnostic("MOSTRA_PLUGIN_SCOPE_INVALID", {
23008
+ message: `${plugin.name} contributes more than exporters and CLI commands, so it is installed for an artifact, not for the home.`,
23009
+ location: at(plugin, ["contributes"])
23010
+ }));
23011
+ for (const name of CONTRACT_NAMES) {
23012
+ const key = PLUGIN_CONTRACTS[name].key;
23013
+ (manifest.contributes[key] ?? []).forEach((entry, index) => {
23014
+ const file = resolve(plugin.dir, entry.entry);
23015
+ if (!existsSync(file) || !isInside(plugin.dir, realpathSync(file))) found.push(createDiagnostic("MOSTRA_PLUGIN_ENTRY_INVALID", {
23016
+ message: `contributes.${key}[${index}]: ${entry.entry} isn't a file of ${plugin.name}.`,
23017
+ location: at(plugin, [
23018
+ "contributes",
23019
+ key,
23020
+ index,
23021
+ "entry"
23022
+ ])
23023
+ }));
23024
+ });
23025
+ }
23026
+ (manifest.contributes.packs ?? []).forEach((pack, index) => {
23027
+ const file = resolve(plugin.dir, pack.item);
23028
+ if (!existsSync(file) || !isInside(plugin.dir, realpathSync(file))) found.push(createDiagnostic("MOSTRA_PLUGIN_ENTRY_INVALID", {
23029
+ message: `contributes.packs[${index}]: ${pack.item} isn't a file of ${plugin.name}.`,
23030
+ location: at(plugin, [
23031
+ "contributes",
23032
+ "packs",
23033
+ index,
23034
+ "item"
23035
+ ])
23036
+ }));
23037
+ });
23038
+ if (manifest.platforms !== void 0 && !manifest.platforms.includes(OS)) found.push(createDiagnostic("MOSTRA_PLUGIN_PLATFORM_UNSUPPORTED", {
23039
+ message: `${plugin.name} names ${manifest.platforms.join(", ")}, not ${OS}.`,
23040
+ location: at(plugin, ["platforms"])
23041
+ }));
23042
+ return found;
23043
+ };
23044
+ /** Every contribution of a manifest, with its contract and position. */
23045
+ const contributionsOf = (manifest) => {
23046
+ const all = [];
23047
+ for (const name of CONTRACT_NAMES) {
23048
+ const key = PLUGIN_CONTRACTS[name].key;
23049
+ (manifest.contributes[key] ?? []).forEach((entry, index) => {
23050
+ all.push({
23051
+ contract: name,
23052
+ id: "command" in entry ? entry.command : entry.id,
23053
+ entry: entry.entry,
23054
+ export: entry.export ?? "default",
23055
+ path: [
23056
+ "contributes",
23057
+ key,
23058
+ index
23059
+ ]
23060
+ });
23061
+ });
23062
+ }
23063
+ return all;
23064
+ };
23065
+ /**
23066
+ * Conflicts within `set`: two plugins contributing one ID of a contract, a CLI command whose
23067
+ * words begin another's (`foo` and `foo bar`: the longer would swallow the shorter's arguments),
23068
+ * an exporter ID Mostra builds in. Those refuse. Against `others` (the home's plugins, when
23069
+ * `set` is an artifact's) a shared exporter or command is a warning: the artifact's own wins in
23070
+ * the artifact (D172 item 5), so a home install never breaks an artifact.
23071
+ */
23072
+ const conflicts = (set, others) => {
23073
+ const found = /* @__PURE__ */ new Map();
23074
+ const add = (plugin, diagnostic) => {
23075
+ found.set(plugin, [...found.get(plugin) ?? [], diagnostic]);
23076
+ };
23077
+ const owner = /* @__PURE__ */ new Map();
23078
+ const commands = [];
23079
+ for (const plugin of set) for (const item of plugin.manifest ? contributionsOf(plugin.manifest) : []) {
23080
+ if (item.contract === "exporter" && BUILT_IN_EXPORTERS.includes(item.id)) {
23081
+ add(plugin, createDiagnostic("MOSTRA_PLUGIN_CONFLICT", {
23082
+ message: `${plugin.name} contributes the exporter "${item.id}", which Mostra builds in.`,
23083
+ location: at(plugin, [...item.path, "id"])
23084
+ }));
23085
+ continue;
23086
+ }
23087
+ const key = `${item.contract}:${item.id}`;
23088
+ const first = owner.get(key);
23089
+ if (first !== void 0 && first !== plugin) {
23090
+ add(plugin, createDiagnostic("MOSTRA_PLUGIN_CONFLICT", {
23091
+ message: `${plugin.name} and ${first.name} both contribute the ${item.contract} "${item.id}"; nothing is overridden: remove one.`,
23092
+ location: at(plugin, item.path)
23093
+ }));
23094
+ continue;
23095
+ }
23096
+ owner.set(key, plugin);
23097
+ if (item.contract !== "cli-command") continue;
23098
+ const words = item.id.split(" ");
23099
+ const prefix = commands.find((other) => other.plugin !== plugin && other.words.length !== words.length && other.words.slice(0, Math.min(other.words.length, words.length)).every((word, index) => word === words[index]));
23100
+ if (prefix !== void 0) add(plugin, createDiagnostic("MOSTRA_PLUGIN_CONFLICT", {
23101
+ message: `${plugin.name}'s command "${item.id}" and ${prefix.plugin.name}'s "${prefix.words.join(" ")}" begin with the same words, so one would take the other's arguments: remove one.`,
23102
+ location: at(plugin, item.path)
23103
+ }));
23104
+ else commands.push({
23105
+ words,
23106
+ plugin
23107
+ });
23108
+ }
23109
+ for (const other of others) for (const item of other.manifest ? contributionsOf(other.manifest) : []) {
23110
+ if (item.contract !== "exporter" && item.contract !== "cli-command") continue;
23111
+ const mine = owner.get(`${item.contract}:${item.id}`);
23112
+ if (mine === void 0) continue;
23113
+ add(mine, createDiagnostic("MOSTRA_PLUGIN_SHADOWED", { message: `${mine.name} and the home's ${other.name} both contribute the ${item.contract} "${item.id}"; this artifact uses ${mine.name}'s.` }));
23114
+ }
23115
+ return found;
23116
+ };
23117
+ /** Loads the Node.js entries of plugins whose static checks passed, in one plugin child. */
23118
+ const inspectEntries = async (set, cwd) => {
23119
+ const found = /* @__PURE__ */ new Map();
23120
+ const jobs = [];
23121
+ for (const plugin of set) for (const item of plugin.manifest ? contributionsOf(plugin.manifest) : []) {
23122
+ if (PLUGIN_CONTRACTS[item.contract].runs !== "node") continue;
23123
+ jobs.push({
23124
+ plugin,
23125
+ item,
23126
+ file: realpathSync(resolve(plugin.dir, item.entry))
23127
+ });
23128
+ }
23129
+ if (jobs.length === 0) return found;
23130
+ const answers = await inChild(cwd, "plugins", (child) => child.request(INSPECT_METHOD, { entries: jobs.map((job) => ({
23131
+ file: job.file,
23132
+ export: job.item.export
23133
+ })) }, { timeoutMs: childTimeoutMs }));
23134
+ jobs.forEach((job, index) => {
23135
+ const answer = answers[index];
23136
+ const where = at(job.plugin, [...job.item.path, "entry"]);
23137
+ const problem = (message, code = "MOSTRA_PLUGIN_ENTRY_INVALID") => found.set(job.plugin, [...found.get(job.plugin) ?? [], createDiagnostic(code, {
23138
+ message,
23139
+ location: where
23140
+ })]);
23141
+ const label = `${job.plugin.name}'s ${job.item.contract} "${job.item.id}" (${job.item.entry}${job.item.export === "default" ? "" : `#${job.item.export}`})`;
23142
+ if (answer === void 0 || !answer.ok) {
23143
+ problem(`${label} didn't load: ${answer && !answer.ok ? answer.error : "no answer"}.`);
23144
+ return;
23145
+ }
23146
+ const stamp = answer.stamp;
23147
+ if (stamp === null || typeof stamp !== "object" || typeof stamp.name !== "string") {
23148
+ problem(`${label} exports no stamped definition: export what ${PLUGIN_CONTRACTS[job.item.contract].package}'s define function returns.`);
23149
+ return;
23150
+ }
23151
+ if (stamp.name !== job.item.contract) {
23152
+ problem(`${label} exports a ${stamp.name} definition, not a ${job.item.contract}.`);
23153
+ return;
23154
+ }
23155
+ if (!stampServed(stamp, job.item.contract, implementedOf(job.item.contract))) {
23156
+ problem(`${label} was built with ${PLUGIN_CONTRACTS[job.item.contract].package} ${String(stamp.version)}, of another line than the ${implementedOf(job.item.contract).join(", ")} this Mostra serves.`, "MOSTRA_PLUGIN_CONTRACT_UNSUPPORTED");
23157
+ return;
23158
+ }
23159
+ const id = job.item.contract === "cli-command" ? answer.path?.join(" ") : answer.id;
23160
+ if (id !== job.item.id) problem(`${label}'s definition is "${id ?? "(none)"}", not "${job.item.id}" as the manifest says.`);
23161
+ });
23162
+ return found;
23163
+ };
23164
+ /** Runs a plugin child for one task and stops it. */
23165
+ const inChild = async (cwd, ownerRef, task) => {
23166
+ const child = await options.processes.spawn({
23167
+ kind: "plugin",
23168
+ ownerRef,
23169
+ command: process.execPath,
23170
+ args: [childEntry()],
23171
+ cwd,
23172
+ env: artifactEnvironment(options.env),
23173
+ ipc: {}
23174
+ });
23175
+ try {
23176
+ return await task(child);
23177
+ } catch (problem) {
23178
+ if (problem instanceof RpcError && /^MOSTRA_(PLUGIN|LICENSE)_/.test(problem.diagnostic.code)) throw problem;
23179
+ const reason = problem instanceof RpcError ? `${problem.diagnostic.code}: ${problem.diagnostic.message}` : problem instanceof Error ? problem.message : String(problem);
23180
+ throw error("MOSTRA_PLUGIN_FAILED", `A plugin's child (${ownerRef}) failed: ${reason}`);
23181
+ } finally {
23182
+ await child.stop(2e3);
23183
+ }
23184
+ };
23185
+ /** Reads a scope's plugins from its working lockfile and layout. */
23186
+ const installedOf = async (lock, nodeModules, scope) => {
23187
+ const found = [];
23188
+ for (const name of lock?.plugins ?? []) {
23189
+ const dir = nodeModules ? join(nodeModules, name) : void 0;
23190
+ if (dir === void 0 || !existsSync(join(dir, "package.json"))) throw error("MOSTRA_PLUGIN_NOT_INSTALLED", `The lockfile names the plugin ${name}, which its layout doesn't hold.`);
23191
+ found.push(await readPackage(dir, scope));
23192
+ }
23193
+ return found;
23194
+ };
23195
+ /**
23196
+ * The home's own plugins as they stand, for the shadow warnings and the home's exporters and
23197
+ * commands; `install: false` reads only a layout already installed (nothing starts).
23198
+ */
23199
+ const homePlugins = async (install) => {
23200
+ const staged = await dependencies.working(homeTarget, { install }).catch(() => void 0);
23201
+ if (staged?.nodeModules === void 0) return [];
23202
+ return installedOf(staged.lock, staged.nodeModules, "home").catch(() => []);
23203
+ };
23204
+ /**
23205
+ * Every package a plugin's code can reach at run time, the plugin included: its dependencies,
23206
+ * optional dependencies, peer dependencies (the installer installs them, `auto-install-peers`)
23207
+ * and bundled dependencies, as Node resolves each from the package's real directory.
23208
+ */
23209
+ const closure = async (root) => {
23210
+ const seen = /* @__PURE__ */ new Map();
23211
+ const names = (value) => Array.isArray(value) ? value.filter((name) => typeof name === "string") : typeof value === "object" && value !== null ? Object.keys(value) : [];
23212
+ const visit = async (dir) => {
23213
+ const real = realpathSync(dir);
23214
+ if (seen.has(real)) return;
23215
+ const json = JSON.parse(await readFile(join(real, "package.json"), "utf8"));
23216
+ seen.set(real, {
23217
+ name: String(json["name"] ?? ""),
23218
+ version: String(json["version"] ?? ""),
23219
+ dir: real,
23220
+ json
23221
+ });
23222
+ const deps = /* @__PURE__ */ new Set([
23223
+ ...names(json["dependencies"]),
23224
+ ...names(json["optionalDependencies"]),
23225
+ ...names(json["peerDependencies"]),
23226
+ ...names(json["bundleDependencies"]),
23227
+ ...names(json["bundledDependencies"])
23228
+ ]);
23229
+ for (const dep of [...deps].sort()) {
23230
+ const found = locate(real, dep);
23231
+ if (found !== void 0) await visit(found);
23232
+ }
23233
+ };
23234
+ await visit(root);
23235
+ return [...seen.values()];
23236
+ };
23237
+ /** Node's resolution of a package directory from `from` (pnpm's isolated layout puts it beside). */
23238
+ const locate = (from, name) => {
23239
+ let dir = from;
23240
+ for (;;) {
23241
+ if (!dir.endsWith(`${sep}node_modules`)) {
23242
+ const candidate = join(dir, "node_modules", name);
23243
+ if (existsSync(join(candidate, "package.json"))) return candidate;
23244
+ }
23245
+ const parent = dirname(dir);
23246
+ if (parent === dir) return void 0;
23247
+ dir = parent;
23248
+ }
23249
+ };
23250
+ /**
23251
+ * Every license an install brings, classed, with where its acknowledgment stands, and the
23252
+ * acknowledgments it makes: each plugin's whole closure, each other package's (a pack's npm
23253
+ * dependencies), and each pack item's own `mostra.license`. A license that needs an
23254
+ * acknowledgment is accepted by an earlier one of the same class, by `accept`, or by the
23255
+ * home's policy (D31).
23256
+ *
23257
+ * What a plugin declares (`bundledLicenses`) describes a package whose own license field Mostra
23258
+ * can't read, and only ever as a license that needs an acknowledgment: no declaration makes a
23259
+ * package OSI-licensed (D172 item 7).
23260
+ */
23261
+ const disclose = async (input) => {
23262
+ const closures = /* @__PURE__ */ new Map();
23263
+ const byId = /* @__PURE__ */ new Map();
23264
+ const entry = (id, licenseClass) => {
23265
+ const found = byId.get(id) ?? {
23266
+ class: licenseClass,
23267
+ packages: /* @__PURE__ */ new Map()
23268
+ };
23269
+ byId.set(id, found);
23270
+ return found;
23271
+ };
23272
+ const warnings = /* @__PURE__ */ new Map();
23273
+ const warn = (owner, diagnostic) => warnings.set(owner, [...warnings.get(owner) ?? [], diagnostic]);
23274
+ const policy = options.policy()?.accept ?? [];
23275
+ for (const owner of [...input.plugins, ...input.packages ?? []]) {
23276
+ const isPlugin = input.plugins.includes(owner);
23277
+ const declared = new Map((owner.manifest?.bundledLicenses ?? []).map((bundled) => [bundled.package, bundled]));
23278
+ const classOf = (id) => [...declared.values()].find((bundled) => bundled.license === id)?.class;
23279
+ const packages = await closure(owner.dir);
23280
+ closures.set(owner, new Set(packages.map((pkg) => pkg.name)));
23281
+ for (const pkg of packages) {
23282
+ const field = packageLicense(pkg.json);
23283
+ const bundled = declared.get(pkg.name);
23284
+ let terms;
23285
+ let shown;
23286
+ if (field !== void 0 && field !== "UNLICENSED" && isReadable(field)) {
23287
+ terms = packageLicenseTerms(pkg.name, field, classOf);
23288
+ shown = field;
23289
+ if (bundled !== void 0 && !sameExpression(bundled.license, field)) warn(owner, createDiagnostic("MOSTRA_LICENSE_MISMATCH", { message: `${owner.name} declares ${pkg.name} as ${bundled.license}; ${pkg.name}@${pkg.version} itself says ${field}, which is what Mostra shows.` }));
23290
+ } else {
23291
+ const unreadable = packageLicenseTerms(pkg.name, field, classOf);
23292
+ const declaredTerms = bundled !== void 0 && isReadable(bundled.license) ? licenseTerms(parseLicenseExpression(bundled.license), classOf) : void 0;
23293
+ if (declaredTerms?.every((term) => ACKNOWLEDGED_CLASSES.has(term.class))) {
23294
+ terms = declaredTerms ?? unreadable;
23295
+ shown = bundled?.license ?? "";
23296
+ } else {
23297
+ terms = unreadable;
23298
+ shown = field ?? "(none)";
23299
+ if (declaredTerms !== void 0) warn(owner, createDiagnostic("MOSTRA_LICENSE_MISMATCH", { message: `${owner.name} declares ${pkg.name} as ${bundled?.license}, which Mostra can't confirm: ${pkg.name}@${pkg.version}'s own license field is ${field === void 0 ? "absent" : `"${field}"`}, so it is shown as ${unreadable.map((term) => term.id).join(" AND ")} (${unreadable.map((term) => term.class).join(", ")}).` }));
23300
+ }
23301
+ }
23302
+ if (isPlugin && pkg.dir !== owner.dir && bundled === void 0 && terms.some((term) => ACKNOWLEDGED_CLASSES.has(term.class))) warn(owner, createDiagnostic("MOSTRA_LICENSE_UNDECLARED", { message: `${owner.name} brings ${pkg.name}@${pkg.version} (${shown}) without declaring it in bundledLicenses.` }));
23303
+ for (const term of terms) {
23304
+ const slot = entry(term.id, term.class);
23305
+ slot.packages.set(`${pkg.name}@${pkg.version}`, {
23306
+ name: pkg.name,
23307
+ version: pkg.version,
23308
+ license: shown
23309
+ });
23310
+ const describing = [...declared.values()].find((item) => item.license === term.id);
23311
+ if (describing?.summary !== void 0) slot.summary = describing.summary;
23312
+ if (describing?.url !== void 0) slot.url = describing.url;
23313
+ }
23314
+ }
23315
+ if (isPlugin && owner.manifest !== void 0) {
23316
+ const own = packageLicense(owner.json);
23317
+ if (own !== void 0 && !sameExpression(own, owner.manifest.license)) warn(owner, createDiagnostic("MOSTRA_LICENSE_MISMATCH", {
23318
+ message: `${owner.name}'s manifest says ${owner.manifest.license}; its package.json says ${own}, which is what Mostra shows.`,
23319
+ location: at(owner, ["license"])
23320
+ }));
23321
+ }
23322
+ }
23323
+ for (const item of input.items ?? []) {
23324
+ const terms = (() => {
23325
+ try {
23326
+ return licenseTerms(parseLicenseExpression(item.license), (id) => isLicenseRef(id) ? item.class : void 0);
23327
+ } catch {
23328
+ return [{
23329
+ id: unreadableItemRef(item.name),
23330
+ class: "unknown"
23331
+ }];
23332
+ }
23333
+ })();
23334
+ for (const term of terms) entry(term.id, term.class).packages.set(`item:${item.name}`, {
23335
+ name: item.name,
23336
+ license: item.license,
23337
+ item: true
23338
+ });
23339
+ }
23340
+ const now = (/* @__PURE__ */ new Date()).toISOString();
23341
+ const disclosures = [];
23342
+ const record = {};
23343
+ const missing = [];
23344
+ for (const [id, found] of [...byId.entries()].sort(([a], [b]) => a < b ? -1 : 1)) {
23345
+ const base = {
23346
+ id,
23347
+ class: found.class,
23348
+ packages: [...found.packages.values()].sort((a, b) => a.name < b.name ? -1 : 1),
23349
+ ...found.summary !== void 0 ? { summary: found.summary } : {},
23350
+ ...found.url !== void 0 ? { url: found.url } : {}
23351
+ };
23352
+ if (!ACKNOWLEDGED_CLASSES.has(found.class)) {
23353
+ disclosures.push({
23354
+ ...base,
23355
+ acknowledgment: "not-needed"
23356
+ });
23357
+ continue;
23358
+ }
23359
+ const earlier = input.previous?.[id]?.class === found.class ? input.previous[id] : void 0;
23360
+ const accepted = earlier ?? (input.accept.includes(id) || input.accept.includes("*") ? {
23361
+ class: found.class,
23362
+ by: "flag"
23363
+ } : policy.includes(id) || policy.includes("*") ? {
23364
+ class: found.class,
23365
+ by: "host"
23366
+ } : void 0);
23367
+ if (accepted === void 0) {
23368
+ const disclosure = {
23369
+ ...base,
23370
+ acknowledgment: "missing"
23371
+ };
23372
+ disclosures.push(disclosure);
23373
+ missing.push(disclosure);
23374
+ continue;
23375
+ }
23376
+ record[id] = accepted;
23377
+ if (earlier === void 0) log.info("plugins.license_accepted", {
23378
+ license: id,
23379
+ class: found.class,
23380
+ by: accepted.by,
23381
+ packages: base.packages.map((pkg) => pkg.version ? `${pkg.name}@${pkg.version}` : pkg.name)
23382
+ });
23383
+ disclosures.push({
23384
+ ...base,
23385
+ acknowledgment: accepted.by === "host" ? "host" : "accepted",
23386
+ ...earlier === void 0 ? { acceptedAt: now } : {}
23387
+ });
23388
+ }
23389
+ return {
23390
+ disclosures,
23391
+ record,
23392
+ missing,
23393
+ warnings,
23394
+ closures
23395
+ };
23396
+ };
23397
+ /** Summarizes a loaded plugin. */
23398
+ const summary = (plugin, diagnostics) => {
23399
+ const manifest = plugin.manifest;
23400
+ const contributions = manifest ? contributionsOf(manifest).map((item) => ({
23401
+ contract: item.contract,
23402
+ id: item.id
23403
+ })) : [];
23404
+ return {
23405
+ package: plugin.name,
23406
+ version: plugin.version,
23407
+ name: manifest?.name ?? plugin.name,
23408
+ ...manifest?.title !== void 0 ? { title: manifest.title } : {},
23409
+ ...manifest?.description !== void 0 ? { description: manifest.description } : {},
23410
+ scope: plugin.scope,
23411
+ contracts: { ...manifest?.contracts ?? {} },
23412
+ contributions,
23413
+ packs: (manifest?.contributes.packs ?? []).map((pack) => pack.item),
23414
+ effects: [...manifest?.effects ?? []],
23415
+ license: manifest?.license ?? String(plugin.json["license"] ?? ""),
23416
+ ...manifest?.platforms !== void 0 ? { platforms: [...manifest.platforms] } : {},
23417
+ status: diagnostics.some((diagnostic) => diagnostic.severity === "error") ? "error" : "ok",
23418
+ diagnostics: [...diagnostics]
23419
+ };
23420
+ };
23421
+ /** Static checks and conflicts of a set: everything that needs no code to run. */
23422
+ const statics = (set, others) => {
23423
+ const found = new Map(set.map((plugin) => [plugin, staticChecks(plugin)]));
23424
+ for (const [plugin, list] of conflicts(set, others)) found.set(plugin, [...found.get(plugin) ?? [], ...list]);
23425
+ return found;
23426
+ };
23427
+ const merged = (set, ...maps) => new Map(set.map((plugin) => [plugin, maps.flatMap((map) => [...map.get(plugin) ?? []])]));
23428
+ const firstError = (found, prefer = []) => {
23429
+ for (const plugin of [...prefer, ...found.keys()]) {
23430
+ const hit = found.get(plugin)?.find((diagnostic) => diagnostic.severity === "error");
23431
+ if (hit !== void 0) return hit;
23432
+ }
23433
+ };
23434
+ const unacceptedError = (missing, command) => new RpcError(createDiagnostic("MOSTRA_LICENSE_UNACCEPTED", {
23435
+ message: `This install brings ${missing.length === 1 ? "a license" : "licenses"} that need an acknowledgment: ${missing.map((license) => `${license.id} (${license.class}; ${license.packages.map((pkg) => pkg.version ? `${pkg.name}@${pkg.version}` : `the item ${pkg.name}`).join(", ")})${license.summary ? `: ${license.summary}` : ""}${license.url ? ` ${license.url}` : ""}`).join("; ")}. Nothing was installed, and nothing of it ran.`,
23436
+ fix: {
23437
+ kind: "command",
23438
+ command: `${command} ${missing.map((license) => `--accept-license ${shellWord(license.id)}`).join(" ")}`
23439
+ }
23440
+ }));
23441
+ const checkAccepted = (accept) => {
23442
+ for (const id of accept) {
23443
+ if (id === "*" || isLicenseRef(id) || spdxLicense(id) !== void 0) continue;
23444
+ throw error("MOSTRA_LICENSE_ACCEPT_INVALID", `"${id}" isn't an SPDX license ID, a LicenseRef- reference or *.`);
23445
+ }
23446
+ };
23447
+ const scopeOf = (target) => target.key === HOME_KEY ? "home" : "artifact";
23448
+ const scopeFlag = (scope) => scope.kind === "home" ? "--global" : `--artifact ${shellWord(scope.target.artifactPath)}`;
23449
+ /**
23450
+ * The gate (D172 items 5, 7 and 8): admits a staged lockfile's plugins, `order` in load order,
23451
+ * with the licenses of everything the change brings. In this order, each refusing before the
23452
+ * next starts: the static checks and conflicts; the licenses (nothing of the packages has run,
23453
+ * their scripts are held); then `staged.ready()` runs the held scripts, and the Node.js
23454
+ * entries load in a plugin child. Answers the lockfile's plugins and its acknowledgments after
23455
+ * the change: every earlier one, and the ones this change made.
23456
+ */
23457
+ const admitSet = async (input) => {
23458
+ checkAccepted(input.accept);
23459
+ const set = await installedOf({
23460
+ ...input.staged.lock,
23461
+ plugins: [...input.order]
23462
+ }, input.staged.nodeModules, input.scope);
23463
+ const fresh = set.filter((plugin) => input.fresh?.includes(plugin.name));
23464
+ const others = input.scope === "artifact" ? await homePlugins(false) : [];
23465
+ const checked = statics(set, others);
23466
+ const refusal = firstError(checked, fresh);
23467
+ if (refusal !== void 0) throw new RpcError(refusal);
23468
+ const extra = [];
23469
+ for (const name of input.packages ?? []) {
23470
+ const dir = join(input.staged.nodeModules, name);
23471
+ if (existsSync(join(dir, "package.json"))) extra.push(await readPackage(dir, "artifact"));
23472
+ }
23473
+ const licenses = await disclose({
23474
+ plugins: set,
23475
+ packages: extra,
23476
+ ...input.items !== void 0 ? { items: input.items } : {},
23477
+ previous: input.staged.previous?.licenses,
23478
+ accept: input.accept
23479
+ });
23480
+ if (licenses.missing.length > 0) throw unacceptedError(licenses.missing, input.command);
23481
+ await input.staged.ready();
23482
+ const entries = await inspectEntries(set, input.target.artifactDir);
23483
+ const loaded = merged(set, checked, entries, licenses.warnings);
23484
+ const broken = firstError(loaded, fresh);
23485
+ if (broken !== void 0) throw new RpcError(broken);
23486
+ return {
23487
+ set,
23488
+ fresh,
23489
+ loaded,
23490
+ licenses,
23491
+ plugins: [...input.order],
23492
+ record: {
23493
+ ...input.staged.previous?.licenses ?? {},
23494
+ ...licenses.record
23495
+ }
23496
+ };
23497
+ };
23498
+ return {
23499
+ async admit(input) {
23500
+ const scope = scopeOf(input.target);
23501
+ const admitted = await admitSet({
23502
+ scope,
23503
+ target: input.target,
23504
+ staged: input.staged,
23505
+ order: input.staged.lock.plugins ?? [],
23506
+ accept: input.accept,
23507
+ command: input.command
23508
+ });
23509
+ return {
23510
+ plugins: admitted.plugins,
23511
+ licenses: admitted.record
23512
+ };
23513
+ },
23514
+ async admitChange(scope, input) {
23515
+ const target = scope.kind === "artifact" ? scope.target : homeTarget;
23516
+ const admitted = await admitSet({
23517
+ scope: scope.kind,
23518
+ target,
23519
+ staged: input.staged,
23520
+ order: input.staged.previous?.plugins ?? [],
23521
+ ...input.packages !== void 0 ? { packages: input.packages } : {},
23522
+ ...input.items !== void 0 ? { items: input.items } : {},
23523
+ accept: input.accept,
23524
+ command: input.command
23525
+ });
23526
+ return {
23527
+ plugins: admitted.plugins,
23528
+ licenses: admitted.record,
23529
+ disclosures: admitted.licenses.disclosures.filter((license) => license.packages.some((pkg) => pkg.item === true || [...admitted.licenses.closures.entries()].some(([owner, names]) => !admitted.set.includes(owner) && names.has(pkg.name))))
23530
+ };
23531
+ },
23532
+ async validate(path, accept) {
23533
+ checkAccepted(accept);
23534
+ const diagnostics = [];
23535
+ if (!existsSync(join(path, "package.json"))) throw error("MOSTRA_PLUGIN_NOT_A_PLUGIN", `${path} has no package.json.`);
23536
+ const plugin = await readPackage(path, "artifact");
23537
+ const checked = statics([plugin], []);
23538
+ diagnostics.push(...checked.get(plugin) ?? []);
23539
+ let blocked = false;
23540
+ if (plugin.manifest !== void 0) {
23541
+ const licenses = await disclose({
23542
+ plugins: [plugin],
23543
+ previous: void 0,
23544
+ accept
23545
+ }).catch((problem) => {
23546
+ log.warn("plugins.validate_licenses", { message: String(problem) });
23547
+ });
23548
+ diagnostics.push(...licenses?.warnings.get(plugin) ?? []);
23549
+ if (licenses !== void 0 && licenses.missing.length > 0) {
23550
+ blocked = true;
23551
+ const refusal = unacceptedError(licenses.missing, `mostra plugin validate ${shellWord(path)}`).diagnostic;
23552
+ diagnostics.push({
23553
+ ...refusal,
23554
+ message: `${plugin.name} brings ${licenses.missing.map((license) => license.id).join(", ")}, which need an acknowledgment; its entries weren't loaded.`
23555
+ });
23556
+ }
23557
+ }
23558
+ if (!blocked && firstError(checked) === void 0) diagnostics.push(...(await inspectEntries([plugin], plugin.dir)).get(plugin) ?? []);
23559
+ return {
23560
+ valid: !diagnostics.some((diagnostic) => diagnostic.severity === "error"),
23561
+ ...plugin.manifest !== void 0 ? { plugin: summary(plugin, diagnostics) } : {},
23562
+ diagnostics
23563
+ };
23564
+ },
23565
+ async add(scope, input) {
23566
+ const target = await targetOf(scope);
23567
+ return dependencies.change({
23568
+ ...target,
23569
+ add: input.packages,
23570
+ request: input.request
23571
+ }, async (staged) => {
23572
+ const names = staged.added.map((pkg) => pkg.name);
23573
+ const previous = staged.previous?.plugins ?? [];
23574
+ const admitted = await admitSet({
23575
+ scope: scope.kind,
23576
+ target,
23577
+ staged,
23578
+ order: [...previous, ...names.filter((name) => !previous.includes(name))],
23579
+ fresh: names,
23580
+ accept: input.accept,
23581
+ command: `mostra plugin add ${input.packages.map(shellWord).join(" ")} ${scopeFlag(scope)}`
23582
+ });
23583
+ log.info("plugins.added", {
23584
+ scope: scope.kind,
23585
+ plugins: names,
23586
+ licenses: Object.keys(admitted.licenses.record)
23587
+ });
23588
+ return {
23589
+ plugins: admitted.plugins,
23590
+ licenses: admitted.record,
23591
+ result: (lockDigest) => ({
23592
+ plugins: admitted.set.map((plugin) => summary(plugin, admitted.loaded.get(plugin) ?? [])),
23593
+ added: names,
23594
+ licenses: admitted.licenses.disclosures.filter((license) => license.packages.some((pkg) => admitted.fresh.some((plugin) => admitted.licenses.closures.get(plugin)?.has(pkg.name)))),
23595
+ lockDigest
23596
+ })
23597
+ };
23598
+ });
23599
+ },
23600
+ async list(scope) {
23601
+ const target = await targetOf(scope);
23602
+ const staged = await dependencies.working(target);
23603
+ const set = await installedOf(staged?.lock, staged?.nodeModules, scope.kind);
23604
+ const others = scope.kind === "artifact" ? await homePlugins(false) : [];
23605
+ const checked = statics(set, others);
23606
+ const licenses = await disclose({
23607
+ plugins: set,
23608
+ previous: staged?.lock.licenses,
23609
+ accept: []
23610
+ });
23611
+ return {
23612
+ plugins: set.map((plugin) => summary(plugin, [...checked.get(plugin) ?? [], ...licenses.warnings.get(plugin) ?? []])),
23613
+ licenses: licenses.disclosures
23614
+ };
23615
+ },
23616
+ async remove(scope, input) {
23617
+ const target = await targetOf(scope);
23618
+ return dependencies.change({
23619
+ ...target,
23620
+ add: [],
23621
+ remove: input.packages,
23622
+ request: input.request
23623
+ }, async (staged) => {
23624
+ const plugins = staged.previous?.plugins ?? [];
23625
+ for (const name of input.packages) if (!plugins.includes(name)) throw error("MOSTRA_PLUGIN_NOT_INSTALLED", `${name} isn't a plugin of ${scope.kind === "home" ? "the home" : scope.target.artifactPath}; it has ${plugins.length > 0 ? plugins.join(", ") : "none"}.`);
23626
+ const order = plugins.filter((name) => !input.packages.includes(name));
23627
+ const set = await installedOf({
23628
+ ...staged.lock,
23629
+ plugins: order
23630
+ }, staged.nodeModules, scope.kind);
23631
+ const others = scope.kind === "artifact" ? await homePlugins(false) : [];
23632
+ const checked = statics(set, others);
23633
+ return {
23634
+ plugins: order,
23635
+ licenses: { ...staged.previous?.licenses ?? {} },
23636
+ result: (lockDigest) => ({
23637
+ removed: [...input.packages],
23638
+ plugins: set.map((plugin) => summary(plugin, checked.get(plugin) ?? [])),
23639
+ lockDigest
23640
+ })
23641
+ };
23642
+ });
23643
+ },
23644
+ async packItem(target, pkg, item) {
23645
+ const staged = await dependencies.working(target).catch(() => void 0);
23646
+ const own = await installedOf(staged?.lock, staged?.nodeModules, "artifact");
23647
+ for (const plugin of [...own, ...await homePlugins(true)]) {
23648
+ if (plugin.name !== pkg) continue;
23649
+ for (const pack of plugin.manifest?.contributes.packs ?? []) {
23650
+ const file = resolve(plugin.dir, pack.item);
23651
+ if (!existsSync(file) || !isInside(plugin.dir, realpathSync(file))) continue;
23652
+ try {
23653
+ if (JSON.parse(await readFile(file, "utf8")).name === item) return realpathSync(file);
23654
+ } catch {}
23655
+ }
23656
+ }
23657
+ },
23658
+ async commands(target) {
23659
+ const own = target === void 0 ? [] : await (async () => {
23660
+ const staged = await dependencies.working(target, { install: false }).catch(() => void 0);
23661
+ if (staged?.nodeModules === void 0) return [];
23662
+ return installedOf(staged.lock, staged.nodeModules, "artifact").catch(() => []);
23663
+ })();
23664
+ const found = [];
23665
+ for (const plugin of [...own, ...await homePlugins(false)]) for (const item of plugin.manifest ? contributionsOf(plugin.manifest) : []) {
23666
+ if (item.contract !== "cli-command") continue;
23667
+ if (found.some((command) => command.command === item.id)) continue;
23668
+ const file = resolve(plugin.dir, item.entry);
23669
+ if (!existsSync(file)) continue;
23670
+ found.push({
23671
+ command: item.id,
23672
+ package: plugin.name,
23673
+ version: plugin.version,
23674
+ scope: plugin.scope,
23675
+ file: realpathSync(file),
23676
+ export: item.export
23677
+ });
23678
+ }
23679
+ return found;
23680
+ },
23681
+ async exporters(input) {
23682
+ const lock = parseLock(await readFile(join(input.versionDir, "lock.yaml"), "utf8"));
23683
+ const own = (lock.plugins ?? []).length === 0 ? [] : await installedOf(lock, await dependencies.runtimeModules({
23684
+ artifactId: input.artifactId,
23685
+ versionDir: input.versionDir,
23686
+ ...input.sourceDir !== void 0 ? { sourceDir: input.sourceDir } : {}
23687
+ }), "artifact");
23688
+ const home = await homePlugins(true);
23689
+ const found = [];
23690
+ for (const plugin of [...own, ...home]) {
23691
+ const problem = staticChecks(plugin).find((diagnostic) => diagnostic.severity === "error");
23692
+ for (const item of plugin.manifest ? contributionsOf(plugin.manifest) : []) {
23693
+ if (item.contract !== "exporter") continue;
23694
+ if (found.some((exporter) => exporter.id === item.id)) continue;
23695
+ found.push({
23696
+ id: item.id,
23697
+ package: plugin.name,
23698
+ scope: plugin.scope,
23699
+ file: realpathSync(resolve(plugin.dir, item.entry)),
23700
+ export: item.export,
23701
+ dir: plugin.dir,
23702
+ ...problem !== void 0 ? { problem } : {}
23703
+ });
23704
+ }
23705
+ }
23706
+ return found;
23707
+ },
23708
+ async runExport(input) {
23709
+ if (input.exporter.problem !== void 0) throw new RpcError(input.exporter.problem);
23710
+ const request = {
23711
+ file: input.exporter.file,
23712
+ export: input.exporter.export,
23713
+ id: input.exporter.id,
23714
+ implemented: implementedOf("exporter"),
23715
+ versionDir: input.versionDir,
23716
+ version: input.version,
23717
+ options: input.options,
23718
+ mostraVersion: options.runtimeVersion
23719
+ };
23720
+ const answer = await inChild(input.exporter.dir, `export:${input.exporter.id}`, (child) => child.request(EXPORT_METHOD, request, { timeoutMs: childTimeoutMs }));
23721
+ if ("refused" in answer) throw error(answer.refused.code, `The exporter "${input.exporter.id}" (${input.exporter.package}) wasn't run: ${answer.refused.message}.`);
23722
+ return answer;
23723
+ }
23724
+ };
23725
+ }
23726
+ /** The reference an item's unreadable license is shown as. */
23727
+ function unreadableItemRef(name) {
23728
+ return `LicenseRef-item-${name.replace(/[^A-Za-z0-9.-]/g, "-")}`;
23729
+ }
23730
+ /** Whether `text` parses as a license expression. */
23731
+ function isReadable(text) {
23732
+ try {
23733
+ parseLicenseExpression(text);
23734
+ return true;
23735
+ } catch {
23736
+ return false;
23737
+ }
23738
+ }
23739
+ /** Whether two license expressions are the same once canonical. */
23740
+ function sameExpression(a, b) {
23741
+ try {
23742
+ return formatLicenseExpression(parseLicenseExpression(a)) === formatLicenseExpression(parseLicenseExpression(b));
23743
+ } catch {
23744
+ return a.trim() === b.trim();
23745
+ }
23746
+ }
23747
+ //#endregion
23748
+ //#region src/secrets/index.ts
23749
+ /**
23750
+ * Secrets (D44, AC-06): named values server code reads with `secret(name)`, kept outside artifact
23751
+ * source in the home's owner-only store, `secrets/<scope>/<name>` (mode 0600, directories 0700),
23752
+ * where the scope is `home` for a secret every artifact shares or the artifact's ID for its own.
23753
+ * A host may supply secrets through its `secrets` port instead (a host's own credential store).
23754
+ *
23755
+ * Every value Mostra holds or hands out is registered with the instance's redactor, so it never
23756
+ * reaches a log, a run log, an event, a diagnostic or a report. Nothing derived from a value is
23757
+ * ever written to the ledger.
23758
+ */
23759
+ const HOME_SCOPE = "home";
23760
+ const ARTIFACT_SCOPE = /^art_[0-9A-HJKMNP-TV-Z]{26}$/;
23761
+ function missing$1(name, detail) {
23762
+ return new RpcError(createDiagnostic("MOSTRA_SECRET_MISSING", {
23763
+ message: `No secret named ${name} is set${detail ? ` (${detail})` : ""}.`,
23764
+ hint: `Set it with \`mostra secret set ${name}\`, reading the value from stdin.`
23765
+ }));
23766
+ }
23767
+ function invalidName(name) {
23768
+ return new RpcError(createDiagnostic("MOSTRA_HOST_INVALID_PARAMS", { message: `${JSON.stringify(name).slice(0, 80)} isn't a secret name: a letter or "_", then up to 127 letters, digits, "_", "." and "-".` }));
23769
+ }
23770
+ /** Opens the home's secret store, registering every stored value with the redactor. */
23771
+ function openSecrets(options) {
23772
+ const root = join(options.home, "secrets");
23773
+ mkdirSync(root, {
23774
+ recursive: true,
23775
+ mode: 448
23776
+ });
23777
+ chmodSync(root, 448);
23778
+ const dirOf = (scope) => join(root, scope.kind === "home" ? HOME_SCOPE : scope.artifactId);
23779
+ const read = (dir, name) => {
23780
+ try {
23781
+ return readFileSync(join(dir, name), "utf8");
23782
+ } catch (error) {
23783
+ if (error.code === "ENOENT") return void 0;
23784
+ throw error;
23785
+ }
23786
+ };
23787
+ for (const scope of existsSync(root) ? readdirSync(root) : []) {
23788
+ if (scope !== HOME_SCOPE && !ARTIFACT_SCOPE.test(scope)) continue;
23789
+ for (const name of readdirSync(join(root, scope))) {
23790
+ if (!SECRET_NAME_PATTERN.test(name)) continue;
23791
+ const value = read(join(root, scope), name);
23792
+ if (value !== void 0) options.redactor.protectSecret(value);
23793
+ }
23794
+ }
23795
+ const entry = (dir, name, scope) => ({
23796
+ name,
23797
+ scope: scope.kind,
23798
+ ...scope.kind === "artifact" ? { artifactId: scope.artifactId } : {},
23799
+ updatedAt: statSync(join(dir, name)).mtime.toISOString()
23800
+ });
23801
+ const listScope = (scope) => {
23802
+ const dir = dirOf(scope);
23803
+ if (!existsSync(dir)) return [];
23804
+ return readdirSync(dir).filter((name) => SECRET_NAME_PATTERN.test(name)).sort().map((name) => entry(dir, name, scope));
23805
+ };
23806
+ return {
23807
+ set(name, value, scope) {
23808
+ if (!SECRET_NAME_PATTERN.test(name)) throw invalidName(name);
23809
+ if (value.length === 0 || Buffer.byteLength(value, "utf8") > SECRET_VALUE_MAX) throw new RpcError(createDiagnostic("MOSTRA_HOST_INVALID_PARAMS", { message: `The value of the secret ${name} must be 1 byte to 64 KiB of UTF-8.` }));
23810
+ options.redactor.protectSecret(value);
23811
+ const dir = dirOf(scope);
23812
+ mkdirSync(dir, {
23813
+ recursive: true,
23814
+ mode: 448
23815
+ });
23816
+ chmodSync(dir, 448);
23817
+ const temporary = join(dir, `.${name}.${process.pid}.tmp`);
23818
+ writeFileSync(temporary, value, {
23819
+ mode: 384,
23820
+ flag: "w"
23821
+ });
23822
+ chmodSync(temporary, 384);
23823
+ renamePathSync(temporary, join(dir, name));
23824
+ options.log.info("secret.set", {
23825
+ name,
23826
+ scope: scope.kind
23827
+ });
23828
+ return entry(dir, name, scope);
23829
+ },
23830
+ list(artifactId) {
23831
+ return [...listScope({ kind: "home" }), ...artifactId ? listScope({
23832
+ kind: "artifact",
23833
+ artifactId
23834
+ }) : []];
23835
+ },
23836
+ delete(name, scope) {
23837
+ if (!SECRET_NAME_PATTERN.test(name)) throw invalidName(name);
23838
+ const file = join(dirOf(scope), name);
23839
+ if (!existsSync(file)) return false;
23840
+ rmSync(file, { force: true });
23841
+ options.log.info("secret.deleted", {
23842
+ name,
23843
+ scope: scope.kind
21488
23844
  });
21489
23845
  return true;
21490
23846
  },
@@ -23208,10 +25564,33 @@ async function assemble(home, options) {
23208
25564
  warm: locateWarmSet(environment),
23209
25565
  policy: () => readHomeSettings(home.path).dependencies ?? "auto",
23210
25566
  faults,
25567
+ plugins: () => getPlugins(),
23211
25568
  ...Number(environment["MOSTRA_TEST_INSTALL_TIMEOUT_MS"]) > 0 ? { installTimeoutMs: Number(environment["MOSTRA_TEST_INSTALL_TIMEOUT_MS"]) } : {}
23212
25569
  });
23213
25570
  const unverifiedPublish = Boolean(environment["MOSTRA_TEST_UNVERIFIED_PUBLISH"]);
23214
25571
  if (unverifiedPublish) log.warn("instance.test_unverified_publish", {});
25572
+ let plugins;
25573
+ const getPlugins = () => plugins ??= createPlugins({
25574
+ home: home.path,
25575
+ dependencies: getDependencies(),
25576
+ processes: manager,
25577
+ log,
25578
+ env: environment,
25579
+ policy: () => readHomeSettings(home.path).licenses,
25580
+ runtimeVersion: runtimeVersion(),
25581
+ ...environment["MOSTRA_TEST_CONTRACT_VERSIONS"] ? { implemented: testContractVersions(environment["MOSTRA_TEST_CONTRACT_VERSIONS"]) } : {}
25582
+ });
25583
+ let packs;
25584
+ const getPacks = () => packs ??= createPacks({
25585
+ dependencies: getDependencies(),
25586
+ plugins: getPlugins(),
25587
+ log,
25588
+ env: environment,
25589
+ ...environment["MOSTRA_TEST_GITHUB_API"] && environment["MOSTRA_TEST_GITHUB_RAW"] ? { github: {
25590
+ api: environment["MOSTRA_TEST_GITHUB_API"],
25591
+ raw: environment["MOSTRA_TEST_GITHUB_RAW"]
25592
+ } } : {}
25593
+ });
23215
25594
  let publisher;
23216
25595
  const getPublisher = () => {
23217
25596
  if (publisher) return publisher;
@@ -23624,7 +26003,8 @@ async function assemble(home, options) {
23624
26003
  ...config.dependencies !== void 0 ? { dependencies: config.dependencies } : {},
23625
26004
  ...config.submission !== void 0 ? { submission: config.submission } : {},
23626
26005
  ...config.ports !== void 0 ? { expectedPorts } : {},
23627
- ...config.submitChannels !== void 0 ? { submitChannels: [...new Set(config.submitChannels)].sort() } : {}
26006
+ ...config.submitChannels !== void 0 ? { submitChannels: [...new Set(config.submitChannels)].sort() } : {},
26007
+ ...config.licenses !== void 0 ? { licenses: { accept: [...new Set(config.licenses.accept)].sort() } } : {}
23628
26008
  };
23629
26009
  if (Object.keys(change).length === 0) return;
23630
26010
  writeHomeSettings(home.path, change);
@@ -23633,7 +26013,8 @@ async function assemble(home, options) {
23633
26013
  ...config.dependencies !== void 0 ? { dependencies: config.dependencies } : {},
23634
26014
  ...config.submission !== void 0 ? { submission: config.submission } : {},
23635
26015
  ...config.ports !== void 0 ? { ports: config.ports } : {},
23636
- ...config.submitChannels !== void 0 ? { submitChannels: config.submitChannels } : {}
26016
+ ...config.submitChannels !== void 0 ? { submitChannels: config.submitChannels } : {},
26017
+ ...config.licenses !== void 0 ? { licenses: config.licenses.accept } : {}
23637
26018
  });
23638
26019
  },
23639
26020
  markHostConfigured: (client) => {
@@ -23662,6 +26043,17 @@ async function assemble(home, options) {
23662
26043
  },
23663
26044
  dependenciesAdded: (artifact) => dev.dependenciesChanged(artifact)
23664
26045
  }),
26046
+ ...pluginMethods({
26047
+ plugins: getPlugins,
26048
+ publisher: getPublisher,
26049
+ log,
26050
+ dependenciesChanged: (artifact) => dev.dependenciesChanged(artifact)
26051
+ }),
26052
+ ...packMethods({
26053
+ packs: getPacks,
26054
+ publisher: getPublisher,
26055
+ dependenciesChanged: (artifact) => dev.dependenciesChanged(artifact)
26056
+ }),
23665
26057
  ...dev.methods(),
23666
26058
  ...forwardHosted(link, (ref) => registry.get(canonicalRef(ref)).id, gateway.methods()),
23667
26059
  ...shares.methods(),
@@ -23893,4 +26285,4 @@ function sourceDirectory(path) {
23893
26285
  //#endregion
23894
26286
  export { readProcess as $, themePageCsp as A, appendEvent as B, jsonResponse as C, defaultPages as D, THEME_BASE as E, finishRun as F, ProtocolServer as G, MAX_FRAME_BYTES as H, markRunning as I, openLedger as J, handler as K, markUnknown as L, createInteraction as M, createEphemeralBus as N, refusalDocument as O, appendRunOutput as P, readServerFunctions as Q, markWaiting as R, isRefusal as S, MADE_WITH_HREF as T, serveWebSocket as U, BINDING_SUBPROTOCOL as V, attachInProcess as W, noFaults as X, faultsFrom as Y, readFieldCoverage as Z, resetOnClose as _, uninstallService as a, BASE_HEADERS as b, resolveHomePath as c, versionIdFor as d, coverageMatcher as et, createLive as f, shellAssetResponse as g, locateShell as h, serviceStatus as i, openRegistry as j, serverPages as k, canonicalRef as l, createGateway as m, startInstance as n, checkPlatform as o, liveMethods as p, holdLock as q, installService as r, platformName as s, runtimeVersion as t, openFileLog as tt, listingDigest as u, Capabilities as v, readJsonObject as w, documentHeaders as x, capabilityKey as y, runState as z };
23895
26287
 
23896
- //# sourceMappingURL=instance-CFTw3g-c.js.map
26288
+ //# sourceMappingURL=instance-Bw1BxctF.js.map