@crvouga/mockingbird-service-wholescripts 3.5.0 → 3.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,22 +1,39 @@
1
1
  import {
2
+ DEFAULT_CATALOG,
2
3
  createClock,
3
4
  createRuntime,
5
+ mergeCatalog,
4
6
  normalizeBootControls,
5
7
  normalizeControls,
8
+ normalizeIdBase,
6
9
  ownedTransport,
10
+ parseCatalogDocument,
7
11
  parseDuration,
8
12
  parseFaultHeader,
9
13
  resolveAdminPrefix,
10
14
  restoreClock
11
- } from "./chunk-T6P2TKQO.js";
15
+ } from "./chunk-4BLJLSNN.js";
16
+
17
+ // src/server.ts
18
+ import { readFileSync } from "node:fs";
12
19
 
13
20
  // ../../adapters/node/dist/cli.js
14
21
  import { readFile as readFile5 } from "node:fs/promises";
15
- import { createRequire as createRequire3 } from "node:module";
16
- import { resolve as resolve3 } from "node:path";
17
- import { pathToFileURL } from "node:url";
18
22
  import { parseArgs } from "node:util";
19
23
 
24
+ // ../../adapters/node/dist/boot-settings.js
25
+ var checkSettings = (target, settings, label) => {
26
+ if (!target.parseSettings)
27
+ throw new Error(`${label}: ${target.name} takes no boot settings`);
28
+ try {
29
+ return target.parseSettings(settings);
30
+ } catch (error) {
31
+ throw new Error(`${label}: ${error instanceof Error ? error.message : String(error)}`, {
32
+ cause: error
33
+ });
34
+ }
35
+ };
36
+
20
37
  // ../../adapters/node/dist/fleet.js
21
38
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
22
39
  import { createHash as createHash4, randomUUID as randomUUID4 } from "node:crypto";
@@ -28,6 +45,31 @@ import { createHash as createHash3, randomBytes, randomUUID as randomUUID3 } fro
28
45
 
29
46
  // ../../adapters/node/dist/fleet-archive.js
30
47
  import { createHash } from "node:crypto";
48
+ function validateCompatibilityTags(tags) {
49
+ if (!tags || typeof tags !== "object" || Array.isArray(tags))
50
+ throw new Error("invalid archive compatibility tags");
51
+ const entries = Object.entries(tags);
52
+ if (entries.length > 32 || entries.some(([key, value]) => !/^[A-Za-z0-9_.-]{1,64}$/.test(key) || typeof value !== "string" || value.length < 1 || value.length > 256 || [...value].some((character) => character.charCodeAt(0) < 32 || character.charCodeAt(0) === 127)))
53
+ throw new Error("invalid archive compatibility tags");
54
+ }
55
+ function assertCompatibilityTags(tags, policy) {
56
+ if (tags !== void 0)
57
+ validateCompatibilityTags(tags);
58
+ if (!policy)
59
+ return;
60
+ validateCompatibilityTags(policy.tags);
61
+ if (policy.missing !== void 0 && !["allow", "reject"].includes(policy.missing))
62
+ throw new Error("invalid missing compatibility policy");
63
+ if (tags === void 0 && policy.missing === "allow")
64
+ return;
65
+ if (canonical(tags) !== canonical(policy.tags))
66
+ throw new Error("application archive compatibility mismatch");
67
+ }
68
+ function assertArchiveCompatibility(input, policy) {
69
+ const archive = validateArchive(input);
70
+ assertCompatibilityTags(archive.compatibility, policy);
71
+ return archive;
72
+ }
31
73
  var canonical = (value) => {
32
74
  if (Array.isArray(value))
33
75
  return `[${value.map(canonical).join(",")}]`;
@@ -47,6 +89,8 @@ function validateArchive(value) {
47
89
  const { sha256, ...content } = doc;
48
90
  if (doc.format !== "mockingbird.fleet/v1" || typeof doc.sourceId !== "string" || typeof doc.createdAt !== "string" || !doc.namespaces || typeof doc.namespaces !== "object" || Array.isArray(doc.namespaces) || sha256 !== digest(content))
49
91
  throw new Error("unsupported or corrupt fleet archive");
92
+ if (doc.compatibility !== void 0)
93
+ validateCompatibilityTags(doc.compatibility);
50
94
  for (const [namespace, entry] of Object.entries(doc.namespaces)) {
51
95
  if (!/^[A-Za-z0-9_.-]{1,64}$/.test(namespace) || !entry || !Number.isFinite(entry.clock?.now) || typeof entry.clock?.frozen !== "boolean" || !entry.services || !Object.keys(entry.services).length)
52
96
  throw new Error("invalid archive namespace");
@@ -62,6 +106,7 @@ function inspectArchive(input) {
62
106
  format: archive.format,
63
107
  createdAt: archive.createdAt,
64
108
  sha256: archive.sha256,
109
+ ...archive.compatibility ? { compatibility: archive.compatibility } : {},
65
110
  namespaces: Object.fromEntries(Object.entries(archive.namespaces).map(([name, ns]) => [
66
111
  name,
67
112
  {
@@ -704,11 +749,28 @@ var ingressSupport = {
704
749
  streaming: true,
705
750
  signing: "vendor request signing is not used; webhook signatures remain payload based"
706
751
  },
752
+ cognito: {
753
+ publicOrigin: true,
754
+ pathPrefix: true,
755
+ namespaces: "path-or-header",
756
+ streaming: true,
757
+ signing: "JWT issuer and JWKS use the configured public namespace; SigV4 verification is not modelled"
758
+ },
759
+ medplum: {
760
+ publicOrigin: true,
761
+ pathPrefix: true,
762
+ namespaces: "path-or-header",
763
+ streaming: true,
764
+ signing: "FHIR, OAuth and storage URLs use the configured public namespace"
765
+ },
707
766
  other: {
708
767
  publicOrigin: false,
709
768
  reason: "host/path-sensitive signing and hosted URL rewriting are not certified; use a direct endpoint"
710
769
  }
711
770
  };
771
+ function supportsPublicIngress(service) {
772
+ return service === "stripe" || service === "cognito" || service === "medplum";
773
+ }
712
774
  function advertisedHttpBase(entry) {
713
775
  if (entry.publicPath !== void 0 && !entry.publicOrigin)
714
776
  throw new Error("publicPath requires publicOrigin");
@@ -1247,7 +1309,7 @@ data: ${JSON.stringify(data)}
1247
1309
  {
1248
1310
  protocol: c.protocol,
1249
1311
  coverage: c.coverage,
1250
- ingress: c.targetName === "stripe" ? ingressSupport.stripe : ingressSupport.other,
1312
+ ingress: supportsPublicIngress(c.targetName ?? "") ? ingressSupport[c.targetName] : ingressSupport.other,
1251
1313
  target: c.targetName,
1252
1314
  outboundPolicy: c.outboundPolicy ?? "unsupported",
1253
1315
  version: 1,
@@ -2331,11 +2393,12 @@ data: ${JSON.stringify(data)}
2331
2393
  format: "mockingbird.fleet/v1",
2332
2394
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
2333
2395
  sourceId: this.ctx.id,
2396
+ ...this.ctx.options.archiveCompatibility ? { compatibility: structuredClone(this.ctx.options.archiveCompatibility.tags) } : {},
2334
2397
  namespaces: contents
2335
2398
  });
2336
2399
  }
2337
2400
  async restoreArchive(input, selectedNamespace) {
2338
- const archive = validateArchive(input);
2401
+ const archive = assertArchiveCompatibility(input, this.ctx.options.archiveCompatibility);
2339
2402
  const entries = Object.entries(archive.namespaces).filter(([ns]) => selectedNamespace === void 0 || ns === selectedNamespace);
2340
2403
  if (!entries.length)
2341
2404
  throw new Error("selected namespace absent from archive");
@@ -2620,6 +2683,9 @@ var fleet_config_schema_default = {
2620
2683
  adminControls: {
2621
2684
  $ref: "#/$defs/controls"
2622
2685
  },
2686
+ idBase: {
2687
+ $ref: "#/$defs/idBase"
2688
+ },
2623
2689
  namespace: {
2624
2690
  type: "string",
2625
2691
  pattern: "^[A-Za-z0-9_.-]{1,64}$"
@@ -2709,6 +2775,12 @@ var fleet_config_schema_default = {
2709
2775
  adminControls: {
2710
2776
  $ref: "#/$defs/controls"
2711
2777
  },
2778
+ idBase: {
2779
+ $ref: "#/$defs/idBase"
2780
+ },
2781
+ settings: {
2782
+ type: "object"
2783
+ },
2712
2784
  fixtures: {
2713
2785
  type: "object"
2714
2786
  },
@@ -2755,6 +2827,18 @@ var fleet_config_schema_default = {
2755
2827
  }
2756
2828
  }
2757
2829
  },
2830
+ idBase: {
2831
+ anyOf: [
2832
+ {
2833
+ type: "integer",
2834
+ minimum: 0
2835
+ },
2836
+ {
2837
+ type: "string",
2838
+ pattern: "^(boot|[0-9]+)$"
2839
+ }
2840
+ ]
2841
+ },
2758
2842
  controls: {
2759
2843
  type: "object",
2760
2844
  additionalProperties: false,
@@ -2904,6 +2988,8 @@ async function preflightFleet(config, options) {
2904
2988
  throw new Error("protected archive policy requires a protected repository; configure its protector before startup");
2905
2989
  resolveAdminPrefix(config.adminPrefix);
2906
2990
  normalizeBootControls(config.adminControls);
2991
+ if (config.idBase !== void 0)
2992
+ normalizeIdBase(config.idBase, "idBase");
2907
2993
  const targets = /* @__PURE__ */ new Map();
2908
2994
  const ports = /* @__PURE__ */ new Set();
2909
2995
  for (const [name, entry] of Object.entries(config.services)) {
@@ -2919,7 +3005,7 @@ async function preflightFleet(config, options) {
2919
3005
  if (entry.target !== void 0 && !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(entry.target))
2920
3006
  throw new Error("target must name a supported service suffix");
2921
3007
  const service = entry.target ?? name;
2922
- if (advertisedHttpBase(entry) && service !== "stripe")
3008
+ if (advertisedHttpBase(entry) && !supportsPublicIngress(service))
2923
3009
  throw new Error(`public ingress unsupported for ${service}; use a direct endpoint to preserve signed targets`);
2924
3010
  const target = await options.load(service);
2925
3011
  const protocol = "protocol" in target ? target.protocol : "http";
@@ -2935,6 +3021,13 @@ async function preflightFleet(config, options) {
2935
3021
  throw new Error("invalid protocol namespace selector");
2936
3022
  }
2937
3023
  }
3024
+ if (entry.idBase !== void 0)
3025
+ normalizeIdBase(entry.idBase, "idBase");
3026
+ if (entry.settings !== void 0) {
3027
+ if (protocol !== "http" || !("create" in target))
3028
+ throw new Error("settings: only HTTP services take boot settings");
3029
+ checkSettings(target, entry.settings, "settings");
3030
+ }
2938
3031
  const port = entry.port ?? target.defaultPort;
2939
3032
  if (port !== 0) {
2940
3033
  const key = `${entry.host ?? "127.0.0.1"}:${port}`;
@@ -2970,7 +3063,7 @@ async function preflightFleet(config, options) {
2970
3063
  break;
2971
3064
  }
2972
3065
  }
2973
- targets.set(name, { ...target, packageVersion: packageVersion ?? "3.5.0" });
3066
+ targets.set(name, { ...target, packageVersion: packageVersion ?? "3.7.0" });
2974
3067
  } catch (error) {
2975
3068
  throw new Error(`service ${name}: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
2976
3069
  }
@@ -3014,6 +3107,11 @@ async function preflightFleet(config, options) {
3014
3107
  return ordered;
3015
3108
  }
3016
3109
  function validateFleetPolicies(options) {
3110
+ if (options.archiveCompatibility) {
3111
+ validateCompatibilityTags(options.archiveCompatibility.tags);
3112
+ if (options.archiveCompatibility.missing !== void 0 && !["allow", "reject"].includes(options.archiveCompatibility.missing))
3113
+ throw new Error("archiveCompatibility.missing must be allow or reject");
3114
+ }
3017
3115
  if (options.journal && !options.repository)
3018
3116
  throw new Error("durable operation journal requires an archive repository");
3019
3117
  if (options.cors) {
@@ -3285,6 +3383,7 @@ var httpChild = async (target, entry, options, admission, generation, privateAcc
3285
3383
  options.onLog?.(entry2);
3286
3384
  },
3287
3385
  ...entry.adminControls !== void 0 ? { adminControls: entry.adminControls } : {},
3386
+ ...entry.settings !== void 0 ? { settings: checkSettings(target, entry.settings, "settings") } : {},
3288
3387
  ...entry.fixtures !== void 0 ? { fixtures: entry.fixtures } : {},
3289
3388
  ...(advertisedHttpBase(entry) ?? entry.baseUrl) !== void 0 ? { baseUrl: advertisedHttpBase(entry) ?? entry.baseUrl } : {}
3290
3389
  });
@@ -3303,6 +3402,8 @@ var httpChild = async (target, entry, options, admission, generation, privateAcc
3303
3402
  ].some((method) => typeof created[method] !== "function"))
3304
3403
  throw new Error("HTTP target does not implement the fleet runtime protocol; build/install matching supported service versions");
3305
3404
  const runtime = created;
3405
+ if (entry.idBase !== void 0)
3406
+ runtime.setIdBase?.(entry.idBase);
3306
3407
  const unobserve = runtime.webhooks?.observeDeliveries(observer.delivery);
3307
3408
  if (options.outbound && runtime.webhooks)
3308
3409
  runtime.webhooks.setTransportPolicy(ownedTransport(options.outbound));
@@ -3901,6 +4002,7 @@ async function startFleet(config, options) {
3901
4002
  ...entry,
3902
4003
  adminPrefix: resolveAdminPrefix(entry.adminPrefix ?? adminPrefix),
3903
4004
  ...adminKey !== void 0 ? { adminKey } : {},
4005
+ ...(entry.idBase ?? config.idBase) !== void 0 ? { idBase: entry.idBase ?? config.idBase } : {},
3904
4006
  // Fleet-wide controls, with the service's own keys replacing them.
3905
4007
  ...config.adminControls !== void 0 || entry.adminControls !== void 0 ? { adminControls: { ...config.adminControls, ...entry.adminControls } } : {}
3906
4008
  }, options, (namespace, request) => management?.admit(namespace, request), (namespace) => management?.generation(namespace), (namespace, request) => management?.privateRequest(namespace, request) ?? false, {
@@ -4006,10 +4108,44 @@ async function startFleet(config, options) {
4006
4108
  }
4007
4109
  }
4008
4110
 
4009
- // ../../adapters/node/dist/fleet-tools.js
4010
- import { readFile as readFile4 } from "node:fs/promises";
4111
+ // ../../adapters/node/dist/fleet-loader.js
4011
4112
  import { createRequire as createRequire2 } from "node:module";
4012
4113
  import { resolve as resolve2 } from "node:path";
4114
+ import { pathToFileURL } from "node:url";
4115
+ var suffix = /^[a-z0-9]+(?:-[a-z0-9]+)*$/;
4116
+ function createInstalledServiceLoader(options) {
4117
+ if (!options.projectRoot)
4118
+ throw new Error("consumer projectRoot required");
4119
+ const allowed = new Set(options.services);
4120
+ for (const name of allowed)
4121
+ if (!suffix.test(name))
4122
+ throw new Error("invalid service suffix");
4123
+ const require2 = createRequire2(resolve2(options.projectRoot, "package.json"));
4124
+ const targets = new Map((options.targets ?? []).map((target) => [target.name, target]));
4125
+ return async (name) => {
4126
+ if (!suffix.test(name) || !allowed.has(name))
4127
+ throw new Error("service is not declared in loader allowlist");
4128
+ const own = targets.get(name);
4129
+ if (own)
4130
+ return own;
4131
+ const specifier = `@crvouga/mockingbird-service-${name}/server`;
4132
+ let location;
4133
+ try {
4134
+ location = require2.resolve(specifier);
4135
+ } catch {
4136
+ throw new Error(`cannot load service "${name}": install @crvouga/mockingbird-service-${name} in the consumer project; its /server export is required`);
4137
+ }
4138
+ const mod = await import(pathToFileURL(location).href);
4139
+ if (!mod.serveTarget || mod.serveTarget.name !== name || ("protocol" in mod.serveTarget ? typeof mod.serveTarget.start !== "function" : typeof mod.serveTarget.create !== "function"))
4140
+ throw new Error(`${specifier} exports no matching serveTarget`);
4141
+ return mod.serveTarget;
4142
+ };
4143
+ }
4144
+
4145
+ // ../../adapters/node/dist/fleet-tools.js
4146
+ import { readFile as readFile4 } from "node:fs/promises";
4147
+ import { createRequire as createRequire3 } from "node:module";
4148
+ import { resolve as resolve3 } from "node:path";
4013
4149
 
4014
4150
  // ../../adapters/node/dist/fleet-client.js
4015
4151
  import { randomUUID as randomUUID5 } from "node:crypto";
@@ -4023,6 +4159,14 @@ var FleetClientError = class extends Error {
4023
4159
  this.details = details;
4024
4160
  }
4025
4161
  };
4162
+ var FleetClientResponseError = class extends FleetClientError {
4163
+ code;
4164
+ constructor(code, status, origin) {
4165
+ super(status, { code, body: "omitted", ...origin ? { origin } : {} });
4166
+ this.code = code;
4167
+ this.name = "FleetClientResponseError";
4168
+ }
4169
+ };
4026
4170
  var FleetClient = class {
4027
4171
  base;
4028
4172
  options;
@@ -4035,7 +4179,14 @@ var FleetClient = class {
4035
4179
  if (url.username || url.password)
4036
4180
  throw new Error("fleet client URL must not contain credentials");
4037
4181
  url.searchParams.set("namespace", options.namespace ?? this.options.namespace ?? "default");
4182
+ const limit = options.maxResponseBytes ?? this.options.maxResponseBytes ?? 64 * 1024 * 1024;
4183
+ if (!Number.isSafeInteger(limit) || limit < 1)
4184
+ throw new Error("invalid response byte limit");
4185
+ const deadline = AbortSignal.timeout(this.options.timeoutMs ?? 3e4);
4186
+ const signal = options.signal ? AbortSignal.any([options.signal, deadline]) : deadline;
4187
+ signal.throwIfAborted();
4038
4188
  const response = await (this.options.fetch ?? fetch)(url, {
4189
+ redirect: "manual",
4039
4190
  method: options.method ?? (options.body === void 0 ? "GET" : "POST"),
4040
4191
  headers: {
4041
4192
  "content-type": "application/json",
@@ -4043,11 +4194,71 @@ var FleetClient = class {
4043
4194
  ...options.idempotencyKey ? { "idempotency-key": options.idempotencyKey } : {}
4044
4195
  },
4045
4196
  ...options.body !== void 0 ? { body: JSON.stringify(options.body) } : {},
4046
- signal: options.signal ?? AbortSignal.timeout(this.options.timeoutMs ?? 3e4)
4197
+ signal
4047
4198
  });
4048
- const data = await response.json();
4049
- if (!response.ok)
4050
- throw new FleetClientError(response.status, data);
4199
+ if (response.status >= 300 && response.status < 400) {
4200
+ await response.body?.cancel();
4201
+ throw new FleetClientResponseError("redirect", response.status, url.origin);
4202
+ }
4203
+ if (Number(response.headers.get("content-length")) > limit) {
4204
+ await response.body?.cancel();
4205
+ throw new FleetClientResponseError("response_too_large", response.status);
4206
+ }
4207
+ const reader = response.body?.getReader();
4208
+ const chunks = [];
4209
+ let size = 0;
4210
+ const abort = () => {
4211
+ void reader?.cancel(signal.reason).catch(() => {
4212
+ });
4213
+ };
4214
+ signal.addEventListener("abort", abort, { once: true });
4215
+ try {
4216
+ if (reader)
4217
+ while (true) {
4218
+ signal.throwIfAborted();
4219
+ const { done, value } = await reader.read();
4220
+ signal.throwIfAborted();
4221
+ if (done)
4222
+ break;
4223
+ size += value.byteLength;
4224
+ if (size > limit) {
4225
+ await reader.cancel();
4226
+ throw new FleetClientResponseError("response_too_large", response.status);
4227
+ }
4228
+ chunks.push(value);
4229
+ }
4230
+ } finally {
4231
+ signal.removeEventListener("abort", abort);
4232
+ if (signal.aborted)
4233
+ await reader?.cancel(signal.reason).catch(() => {
4234
+ });
4235
+ reader?.releaseLock();
4236
+ }
4237
+ const bytes = new Uint8Array(size);
4238
+ let offset = 0;
4239
+ for (const chunk of chunks) {
4240
+ bytes.set(chunk, offset);
4241
+ offset += chunk.byteLength;
4242
+ }
4243
+ const text2 = new TextDecoder().decode(bytes);
4244
+ let data;
4245
+ try {
4246
+ data = text2.length ? JSON.parse(text2) : void 0;
4247
+ } catch {
4248
+ if (response.ok)
4249
+ throw new FleetClientResponseError("invalid_json", response.status);
4250
+ }
4251
+ if (!response.ok) {
4252
+ const error = data && typeof data === "object" ? data.error : void 0;
4253
+ const detail = { body: "omitted" };
4254
+ if (error && typeof error === "object")
4255
+ for (const key of ["type", "code"]) {
4256
+ const value = error[key];
4257
+ if (typeof value === "string" && /^[A-Za-z0-9_.-]{1,128}$/.test(value))
4258
+ detail[key] = value;
4259
+ }
4260
+ throw new FleetClientError(response.status, detail);
4261
+ }
4051
4262
  return data;
4052
4263
  }
4053
4264
  discover() {
@@ -4113,17 +4324,52 @@ function renderConnections(manifest, privateManifest, namespace, mapping) {
4113
4324
  const child = manifest.services[entry.service], secret = privateManifest.services[entry.service];
4114
4325
  if (!child || !secret)
4115
4326
  throw new Error(`missing service mapping ${entry.service}`);
4327
+ let endpoint;
4116
4328
  if (child.protocol === "http") {
4117
4329
  const template = child.namespaces.path;
4118
4330
  if (typeof template !== "string")
4119
4331
  throw new Error(`missing HTTP namespace mapping ${entry.service}`);
4120
- result[variable] = new URL(template.replace("{name}", encodeURIComponent(namespace)), secret.url).href;
4332
+ endpoint = new URL(template.replace("{name}", encodeURIComponent(namespace)), secret.url).href;
4121
4333
  } else {
4122
- const endpoint = secret.namespaces?.[namespace];
4123
- if (!endpoint)
4334
+ const selected = secret.namespaces?.[namespace];
4335
+ if (!selected)
4124
4336
  throw new Error(`missing namespace mapping ${namespace}/${entry.service}`);
4125
- result[variable] = endpoint;
4337
+ endpoint = selected;
4126
4338
  }
4339
+ const url = new URL(endpoint);
4340
+ const field = entry.field ?? "url";
4341
+ let value;
4342
+ switch (field) {
4343
+ case "url":
4344
+ value = endpoint;
4345
+ break;
4346
+ case "hostname":
4347
+ value = url.hostname.replace(/^\[|\]$/g, "");
4348
+ break;
4349
+ case "port":
4350
+ value = url.port;
4351
+ break;
4352
+ case "username":
4353
+ value = decodeURIComponent(url.username);
4354
+ break;
4355
+ case "password":
4356
+ value = decodeURIComponent(url.password);
4357
+ break;
4358
+ case "pathname":
4359
+ value = decodeURIComponent(url.pathname);
4360
+ break;
4361
+ case "database":
4362
+ value = decodeURIComponent(url.pathname.replace(/^\//, ""));
4363
+ break;
4364
+ default:
4365
+ throw new Error("unsupported connection field");
4366
+ }
4367
+ if (!value) {
4368
+ if (typeof entry.fallback !== "string")
4369
+ throw new Error(`missing connection component ${field}`);
4370
+ value = entry.fallback;
4371
+ }
4372
+ result[variable] = value;
4127
4373
  }
4128
4374
  return result;
4129
4375
  }
@@ -4147,7 +4393,7 @@ async function doctorFleet(config, options, probes = []) {
4147
4393
  const plan = [];
4148
4394
  try {
4149
4395
  const targets = await preflightFleet(config, options);
4150
- const require2 = createRequire2(resolve2(process.cwd(), "package.json"));
4396
+ const require2 = createRequire3(resolve3(process.cwd(), "package.json"));
4151
4397
  for (const [service, target] of targets) {
4152
4398
  let version = "development";
4153
4399
  try {
@@ -4202,7 +4448,7 @@ async function doctorFleet(config, options, probes = []) {
4202
4448
  };
4203
4449
  }
4204
4450
  async function rehearseFleet(config, options, input, probes = [], timeoutMs = 3e4) {
4205
- const archive = validateArchive(input);
4451
+ const archive = assertArchiveCompatibility(input, options.archiveCompatibility);
4206
4452
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
4207
4453
  const isolated = {
4208
4454
  ...config,
@@ -4214,7 +4460,7 @@ async function rehearseFleet(config, options, input, probes = [], timeoutMs = 3e
4214
4460
  };
4215
4461
  let fleet;
4216
4462
  try {
4217
- fleet = await startFleet(isolated, { load: options.load });
4463
+ fleet = await startFleet(isolated, options);
4218
4464
  const client = new FleetClient(fleet.manifest.adminBase, {
4219
4465
  ...config.adminKey ? { adminKey: config.adminKey } : {}
4220
4466
  });
@@ -4441,6 +4687,16 @@ var COMMON_SERVE_OPTIONS = {
4441
4687
  value: "<seed>",
4442
4688
  description: "Seed for every random choice (env MOCKINGBIRD_SEED)"
4443
4689
  },
4690
+ "id-base": {
4691
+ type: "string",
4692
+ value: "<n|boot>",
4693
+ description: "Start generated ids at this base so a restart does not reissue the last boot's ids; boot derives one from the clock (env MOCKINGBIRD_ID_BASE; default 0, the same ids every boot)"
4694
+ },
4695
+ settings: {
4696
+ type: "string",
4697
+ value: "<json|file>",
4698
+ description: "Service settings to boot with, as JSON or a JSON file; every namespace starts from them (env MOCKINGBIRD_SETTINGS; only for services that declare settings)"
4699
+ },
4444
4700
  "admin-controls": {
4445
4701
  type: "string",
4446
4702
  value: "<json|file>",
@@ -4535,19 +4791,40 @@ var readJsonFile = async (path, label) => {
4535
4791
  }
4536
4792
  };
4537
4793
  var isObject2 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
4794
+ var readJsonOption = async (source, label) => {
4795
+ const trimmed = source.trim();
4796
+ if (trimmed.startsWith("{") || trimmed.startsWith("[")) {
4797
+ try {
4798
+ return JSON.parse(trimmed);
4799
+ } catch {
4800
+ throw new Error(`${label}: not valid JSON`);
4801
+ }
4802
+ }
4803
+ return readJsonFile(source, label);
4804
+ };
4805
+ var resolveServeIdBase = (values, env = process.env) => {
4806
+ const source = asString(values["id-base"]) ?? env.MOCKINGBIRD_ID_BASE;
4807
+ if (source === void 0 || source.trim() === "")
4808
+ return void 0;
4809
+ normalizeIdBase(source.trim(), "--id-base");
4810
+ return source.trim();
4811
+ };
4812
+ var resolveServeSettings = async (target, values, env = process.env) => {
4813
+ const flag = asString(values.settings);
4814
+ const source = flag ?? env.MOCKINGBIRD_SETTINGS;
4815
+ if (source === void 0 || source.trim() === "")
4816
+ return void 0;
4817
+ const label = flag !== void 0 ? "--settings" : "MOCKINGBIRD_SETTINGS";
4818
+ const parsed = await readJsonOption(source, label);
4819
+ if (!isObject2(parsed))
4820
+ throw new Error(`${label}: expected a JSON object`);
4821
+ return checkSettings(target, parsed, label);
4822
+ };
4538
4823
  var resolveServeControls = async (values, env = process.env, base) => {
4539
4824
  const source = asString(values["admin-controls"]) ?? env.MOCKINGBIRD_ADMIN_CONTROLS;
4540
4825
  let document = isObject2(base) ? { ...base } : {};
4541
4826
  if (source !== void 0 && source.trim() !== "") {
4542
- let parsed;
4543
- if (source.trim().startsWith("{")) {
4544
- try {
4545
- parsed = JSON.parse(source);
4546
- } catch {
4547
- throw new Error("--admin-controls: not valid JSON");
4548
- }
4549
- } else
4550
- parsed = await readJsonFile(source, "--admin-controls");
4827
+ const parsed = source.trim().startsWith("{") ? await readJsonOption(source, "--admin-controls") : await readJsonFile(source, "--admin-controls");
4551
4828
  if (!isObject2(parsed))
4552
4829
  throw new Error("--admin-controls: expected a JSON object");
4553
4830
  document = { ...document, ...parsed };
@@ -4589,26 +4866,7 @@ var resolveServeControls = async (values, env = process.env, base) => {
4589
4866
  normalizeBootControls(document, "adminControls");
4590
4867
  return document;
4591
4868
  };
4592
- var loadTarget = async (name, own) => {
4593
- if (name === own.name)
4594
- return own;
4595
- const specifier = `@crvouga/mockingbird-service-${name}/server`;
4596
- try {
4597
- let mod;
4598
- try {
4599
- mod = await import(specifier);
4600
- } catch {
4601
- const fromProject = createRequire3(resolve3(process.cwd(), "package.json"));
4602
- mod = await import(pathToFileURL(fromProject.resolve(specifier)).href);
4603
- }
4604
- if (!mod.serveTarget)
4605
- throw new Error(`${specifier} exports no serveTarget`);
4606
- return mod.serveTarget;
4607
- } catch (error) {
4608
- const reason = error instanceof Error ? error.message : String(error);
4609
- throw new Error(`cannot load service "${name}": ${reason}. Install @crvouga/mockingbird-service-${name}.`);
4610
- }
4611
- };
4869
+ var loadTarget = (name, own) => createInstalledServiceLoader({ projectRoot: process.cwd(), services: [name], targets: [own] })(name);
4612
4870
  var start = async (target, values, config) => {
4613
4871
  const adminPrefix = resolveAdminPrefix(config.adminPrefix);
4614
4872
  const runtime = await target.create(values, {
@@ -4616,8 +4874,11 @@ var start = async (target, values, config) => {
4616
4874
  adminKey: config.adminKey,
4617
4875
  seed: config.seed,
4618
4876
  onLog: formatLog(config.log),
4877
+ ...config.settings !== void 0 ? { settings: config.settings } : {},
4619
4878
  ...config.adminControls !== void 0 ? { adminControls: config.adminControls } : {}
4620
4879
  });
4880
+ if (config.idBase !== void 0)
4881
+ runtime.setIdBase?.(config.idBase);
4621
4882
  const listening = await listen(runtime, { port: config.port, host: config.host });
4622
4883
  target.listening?.(listening);
4623
4884
  console.log(`${target.name} emulator listening on ${listening.url}`);
@@ -4663,6 +4924,11 @@ var serveCommand = (target) => ({
4663
4924
  const adminControls = await resolveServeControls(values, process.env, config.adminControls);
4664
4925
  if (adminControls !== void 0)
4665
4926
  config.adminControls = adminControls;
4927
+ if (values.settings !== void 0)
4928
+ throw new Error("--settings serves a single service; give each service its own `settings` in the config");
4929
+ const idBase = config.idBase ?? resolveServeIdBase(values);
4930
+ if (idBase !== void 0)
4931
+ config.idBase = idBase;
4666
4932
  const fleet = await startFleet(config, {
4667
4933
  load: (name) => loadTarget(name, target),
4668
4934
  onLog: formatLog(config.log ?? log),
@@ -4692,8 +4958,12 @@ var serveCommand = (target) => ({
4692
4958
  let listening;
4693
4959
  try {
4694
4960
  const adminControls = await resolveServeControls(values);
4961
+ const idBase = resolveServeIdBase(values);
4962
+ const settings = await resolveServeSettings(target, values);
4695
4963
  listening = await start(target, values, {
4696
4964
  ...adminControls !== void 0 ? { adminControls } : {},
4965
+ ...idBase !== void 0 ? { idBase } : {},
4966
+ ...settings !== void 0 ? { settings } : {},
4697
4967
  adminPrefix: resolveAdminPrefix(asString(values["admin-prefix"]) ?? process.env.MOCKINGBIRD_ADMIN_PREFIX),
4698
4968
  port: port === void 0 ? target.defaultPort : Number.parseInt(port, 10),
4699
4969
  host: asString(values.host) ?? "127.0.0.1",
@@ -4728,6 +4998,20 @@ var createServer2 = async (options = {}) => {
4728
4998
  };
4729
4999
  };
4730
5000
  var text = (value) => typeof value === "string" ? value : void 0;
5001
+ var loadCatalogFile = (path, mode = "merge") => {
5002
+ let raw;
5003
+ try {
5004
+ raw = readFileSync(path, "utf8");
5005
+ } catch {
5006
+ throw new Error(`wholescripts catalog not found: ${path}`);
5007
+ }
5008
+ try {
5009
+ const parsed = parseCatalogDocument(JSON.parse(raw));
5010
+ return mode === "replace" ? { products: [], medPaxPills: [], privateLabelCartons: [], ...parsed } : mergeCatalog(DEFAULT_CATALOG, parsed);
5011
+ } catch (error) {
5012
+ throw new Error(`wholescripts catalog ${path}: ${error.message}`);
5013
+ }
5014
+ };
4731
5015
  var serveTarget = {
4732
5016
  name: "wholescripts",
4733
5017
  defaultPort: DEFAULT_PORT,
@@ -4746,6 +5030,16 @@ var serveTarget = {
4746
5030
  type: "string",
4747
5031
  value: "<ms:Status,Status,\u2026>",
4748
5032
  description: 'Walk every new order along a path, e.g. "2000:Processing,Complete"'
5033
+ },
5034
+ catalog: {
5035
+ type: "string",
5036
+ value: "<file.json>",
5037
+ description: "Catalog rows every namespace starts with and resets to: {products?, medPaxPills?, privateLabelCartons?} or a bare array of products, merged onto the default catalog by SKU"
5038
+ },
5039
+ "catalog-mode": {
5040
+ type: "string",
5041
+ value: "<merge|replace>",
5042
+ description: "With --catalog: merge onto the default catalog (default) or use the file as the whole catalog"
4749
5043
  }
4750
5044
  },
4751
5045
  create: (values, common) => {
@@ -4754,8 +5048,15 @@ var serveTarget = {
4754
5048
  const auto = text(values["auto-advance"]);
4755
5049
  const plan = auto ? /^(\d+):(.+)$/.exec(auto) : null;
4756
5050
  if (auto && !plan) throw new Error('--auto-advance must look like "2000:Processing,Complete"');
5051
+ const catalogPath = text(values.catalog);
5052
+ const mode = text(values["catalog-mode"]);
5053
+ if (mode !== void 0 && mode !== "merge" && mode !== "replace")
5054
+ throw new Error('--catalog-mode must be "merge" or "replace"');
5055
+ if (mode !== void 0 && catalogPath === void 0)
5056
+ throw new Error("--catalog-mode needs --catalog");
4757
5057
  return createRuntime({
4758
5058
  tickMs: 100,
5059
+ ...catalogPath ? { catalog: loadCatalogFile(catalogPath, mode) } : {},
4759
5060
  settings: {
4760
5061
  ...username && password ? { accounts: [{ username, password }] } : {},
4761
5062
  ...plan ? {
@@ -4783,6 +5084,7 @@ export {
4783
5084
  serveCommand,
4784
5085
  DEFAULT_PORT,
4785
5086
  createServer2 as createServer,
5087
+ loadCatalogFile,
4786
5088
  serveTarget
4787
5089
  };
4788
- //# sourceMappingURL=chunk-7DALIULQ.js.map
5090
+ //# sourceMappingURL=chunk-R57VJDWN.js.map