spfn 0.3.0-beta.14 → 0.3.0-beta.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -949,7 +949,7 @@ import { dirname as dirname2, join as join10 } from "path";
949
949
  import { fileURLToPath as fileURLToPath2 } from "url";
950
950
  function getCliVersion() {
951
951
  if (true) {
952
- return "0.3.0-beta.14";
952
+ return "0.3.0-beta.16";
953
953
  }
954
954
  return fromPackageJson ?? (fromPackageJson = readPackageVersion());
955
955
  }
@@ -6339,80 +6339,23 @@ envCommand.command("audit").description("Find direct process.env reads and app e
6339
6339
  import { Command as Command15 } from "commander";
6340
6340
  import chalk36 from "chalk";
6341
6341
 
6342
- // src/utils/ops/plain.ts
6343
- function plain(value) {
6344
- return value.replace(/[\u0000-\u001f\u007f-\u009f]/g, "?");
6345
- }
6346
-
6347
- // src/utils/ops/client.ts
6348
- function joinUrl(appUrl, path5) {
6349
- return appUrl.replace(/\/+$/, "") + path5;
6350
- }
6351
- async function request(appUrl, token, method, path5, body) {
6352
- const response = await fetch(joinUrl(appUrl, path5), {
6353
- method,
6354
- headers: {
6355
- Authorization: `Bearer ${token}`,
6356
- ...body !== void 0 ? { "Content-Type": "application/json" } : {}
6357
- },
6358
- ...body !== void 0 ? { body: JSON.stringify(body) } : {}
6359
- });
6360
- const text = await response.text();
6361
- let parsed = text;
6362
- try {
6363
- parsed = text.length > 0 ? JSON.parse(text) : null;
6364
- } catch {
6365
- }
6366
- return { status: response.status, body: parsed };
6367
- }
6368
- async function fetchOpsManifest(appUrl, token) {
6369
- const { status, body } = await request(appUrl, token, "GET", "/_ops/_manifest");
6370
- if (status === 401 || status === 403) {
6371
- throw new Error("The app refused the ops token (check --token / SPFN_OPS_TOKEN / keychain).");
6372
- }
6373
- if (status === 404) {
6374
- throw new Error("No ops surface at this app (GET /_ops/_manifest answered 404). Mount one with createOpsRouter() and .packages([opsRouter]).");
6375
- }
6376
- if (status !== 200) {
6377
- throw new Error(`Manifest request failed with status ${status}.`);
6378
- }
6379
- const manifest = body;
6380
- if (manifest?.manifestVersion !== 1 || !Array.isArray(manifest.commands)) {
6381
- throw new Error("The manifest answer has an unknown shape.");
6382
- }
6383
- const modules = usableModules(manifest.modules);
6384
- return {
6385
- manifestVersion: 1,
6386
- ...manifest.modules !== void 0 ? { modules } : {},
6387
- commands: usableCommands(manifest.commands, new Set(modules.map((module) => module.id)))
6388
- };
6389
- }
6390
- var OPS_METHODS = /* @__PURE__ */ new Set(["GET", "POST", "PUT", "PATCH", "DELETE"]);
6391
- var OPS_EFFECTS = /* @__PURE__ */ new Set(["read", "write", "destructive"]);
6392
- var MODULE_ID = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
6393
- var CONTRACT_VERSION = /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)*$/;
6394
- var MAX_ID_LENGTH = 64;
6395
- var MAX_SOURCE_LENGTH = 128;
6396
- var MAX_SUMMARY_LENGTH = 500;
6397
- var MAX_SCOPES = 64;
6398
- var MAX_SCOPE_LENGTH = 128;
6399
- var OPS_PATH_PREFIX = "/_ops/";
6400
- var OPS_PATH_BASE = "https://spfn.invalid";
6401
- function unstableOpsPathBecause(path5) {
6342
+ // src/surface/command-path.ts
6343
+ var PATH_BASE = "https://spfn.invalid";
6344
+ function unstablePathBecause(path5, prefix) {
6402
6345
  let url;
6403
6346
  try {
6404
- url = new URL(path5, OPS_PATH_BASE);
6347
+ url = new URL(path5, PATH_BASE);
6405
6348
  } catch {
6406
6349
  return "is not a valid URL path";
6407
6350
  }
6408
- if (url.origin !== OPS_PATH_BASE || url.search !== "" || url.hash !== "") {
6351
+ if (url.origin !== PATH_BASE || url.search !== "" || url.hash !== "") {
6409
6352
  return "is not a plain absolute path";
6410
6353
  }
6411
6354
  if (url.pathname !== path5) {
6412
6355
  return "changes when URL-normalized";
6413
6356
  }
6414
- if (!url.pathname.startsWith(OPS_PATH_PREFIX)) {
6415
- return `is outside ${OPS_PATH_PREFIX}`;
6357
+ if (!url.pathname.startsWith(prefix)) {
6358
+ return `is outside ${prefix}`;
6416
6359
  }
6417
6360
  const slashCount = (path5.match(/\//g) ?? []).length;
6418
6361
  let decoded = path5;
@@ -6433,129 +6376,6 @@ function unstableOpsPathBecause(path5) {
6433
6376
  }
6434
6377
  return "uses too many percent-encoding layers";
6435
6378
  }
6436
- function unusableBecause(command) {
6437
- if (typeof command?.name !== "string" || command.name.length === 0) {
6438
- return "it has no name";
6439
- }
6440
- if (typeof command.method !== "string" || !OPS_METHODS.has(command.method)) {
6441
- return `its method is ${JSON.stringify(command.method)}`;
6442
- }
6443
- if (typeof command.path !== "string") {
6444
- return `its path ${JSON.stringify(command.path)} is not a string`;
6445
- }
6446
- const pathReason = unstableOpsPathBecause(command.path);
6447
- if (pathReason !== null) {
6448
- return `its path ${JSON.stringify(command.path)} ${pathReason}`;
6449
- }
6450
- return null;
6451
- }
6452
- function usableCommands(commands, moduleIds) {
6453
- const usable = [];
6454
- for (const command of commands) {
6455
- const reason = unusableBecause(command);
6456
- if (reason !== null) {
6457
- console.error(`\u26A0\uFE0F Ignoring an ops command the manifest announced: ${reason}.`);
6458
- continue;
6459
- }
6460
- const normalized = {
6461
- name: command.name,
6462
- method: command.method,
6463
- path: command.path,
6464
- input: isPlainObject(command.input) ? command.input : {}
6465
- };
6466
- const metadataReason = unusableModuleMetadataBecause(command, moduleIds);
6467
- if (metadataReason === null && command.module !== void 0) {
6468
- normalized.module = command.module;
6469
- normalized.summary = command.summary;
6470
- normalized.effect = command.effect;
6471
- normalized.scopes = [...command.scopes];
6472
- } else if (metadataReason !== null) {
6473
- normalized.metadataRejected = true;
6474
- console.error(
6475
- `\u26A0\uFE0F Ignoring module metadata for ops command "${plain(command.name)}": ${metadataReason}. Calling it will require --yes.`
6476
- );
6477
- }
6478
- usable.push(normalized);
6479
- }
6480
- return usable;
6481
- }
6482
- function unusableModuleMetadataBecause(command, moduleIds) {
6483
- const carriesMetadata = command.module !== void 0 || command.summary !== void 0 || command.effect !== void 0 || command.scopes !== void 0;
6484
- if (!carriesMetadata) {
6485
- return null;
6486
- }
6487
- if (typeof command.module !== "string" || !moduleIds.has(command.module)) {
6488
- return "it names no usable module";
6489
- }
6490
- if (!command.name.startsWith(`${command.module}.`)) {
6491
- return "its qualified name does not start with the module id";
6492
- }
6493
- if (!command.path.startsWith(`${OPS_PATH_PREFIX}${command.module}/`)) {
6494
- return "its path is outside the module namespace";
6495
- }
6496
- if (typeof command.summary !== "string" || command.summary.length === 0 || command.summary.length > MAX_SUMMARY_LENGTH) {
6497
- return "its summary is missing or too long";
6498
- }
6499
- if (typeof command.effect !== "string" || !OPS_EFFECTS.has(command.effect)) {
6500
- return "its effect is unknown";
6501
- }
6502
- if (!Array.isArray(command.scopes) || command.scopes.length === 0 || command.scopes.length > MAX_SCOPES || command.scopes.some((scope) => typeof scope !== "string" || scope.length === 0 || scope.length > MAX_SCOPE_LENGTH)) {
6503
- return "its scopes are missing or invalid";
6504
- }
6505
- return null;
6506
- }
6507
- function usableModules(value) {
6508
- if (value === void 0) {
6509
- return [];
6510
- }
6511
- if (!Array.isArray(value)) {
6512
- console.error("\u26A0\uFE0F Ignoring ops module metadata: modules is not an array.");
6513
- return [];
6514
- }
6515
- const modules = [];
6516
- const claimed = /* @__PURE__ */ new Set();
6517
- for (const raw of value) {
6518
- const reason = unusableModuleBecause(raw, claimed);
6519
- if (reason !== null) {
6520
- console.error(`\u26A0\uFE0F Ignoring an ops module the manifest announced: ${reason}.`);
6521
- continue;
6522
- }
6523
- const module = raw;
6524
- claimed.add(module.id);
6525
- modules.push({
6526
- id: module.id,
6527
- source: module.source,
6528
- contractVersion: module.contractVersion,
6529
- summary: module.summary
6530
- });
6531
- }
6532
- return modules;
6533
- }
6534
- function unusableModuleBecause(value, claimed) {
6535
- if (!isPlainObject(value)) {
6536
- return "it is not an object";
6537
- }
6538
- const id = value.id;
6539
- if (typeof id !== "string" || id.length > MAX_ID_LENGTH || !MODULE_ID.test(id)) {
6540
- return "its id is invalid";
6541
- }
6542
- if (claimed.has(id)) {
6543
- return `id "${id}" is duplicated`;
6544
- }
6545
- if (typeof value.source !== "string" || value.source.length === 0 || value.source.length > MAX_SOURCE_LENGTH) {
6546
- return `module "${id}" has an invalid source`;
6547
- }
6548
- if (typeof value.contractVersion !== "string" || !CONTRACT_VERSION.test(value.contractVersion)) {
6549
- return `module "${id}" has an invalid contract version`;
6550
- }
6551
- if (typeof value.summary !== "string" || value.summary.length === 0 || value.summary.length > MAX_SUMMARY_LENGTH) {
6552
- return `module "${id}" has an invalid summary`;
6553
- }
6554
- return null;
6555
- }
6556
- function isPlainObject(value) {
6557
- return value !== null && typeof value === "object" && !Array.isArray(value);
6558
- }
6559
6379
  function climbsOutOfItsSegment(value) {
6560
6380
  let decoded = value;
6561
6381
  for (let depth = 0; depth < 8; depth++) {
@@ -6575,10 +6395,10 @@ function climbsOutOfItsSegment(value) {
6575
6395
  }
6576
6396
  return true;
6577
6397
  }
6578
- function buildCommandPath(command, params, query) {
6579
- const templateReason = unstableOpsPathBecause(command.path);
6398
+ function buildCommandPath(command, params, query, namespace) {
6399
+ const templateReason = unstablePathBecause(command.path, `${namespace}/`);
6580
6400
  if (templateReason !== null) {
6581
- throw new Error(`Refusing ops command path ${JSON.stringify(command.path)} because it ${templateReason}.`);
6401
+ throw new Error(`Refusing command path ${JSON.stringify(command.path)} because it ${templateReason}.`);
6582
6402
  }
6583
6403
  const path5 = command.path.replace(/:([A-Za-z0-9_]+)/g, (_match, name) => {
6584
6404
  const value = params[name];
@@ -6598,12 +6418,13 @@ function buildCommandPath(command, params, query) {
6598
6418
  const search = new URLSearchParams(query).toString();
6599
6419
  return search.length > 0 ? `${path5}?${search}` : path5;
6600
6420
  }
6601
- async function invokeOpsCommand(appUrl, token, command, input) {
6602
- const path5 = buildCommandPath(command, input.params, input.query);
6603
- return await request(appUrl, token, command.method, path5, input.body);
6421
+
6422
+ // src/surface/plain.ts
6423
+ function plain(value) {
6424
+ return value.replace(/[\u0000-\u001f\u007f-\u009f]/g, "?");
6604
6425
  }
6605
6426
 
6606
- // src/utils/ops/describe.ts
6427
+ // src/surface/describe.ts
6607
6428
  var SECTIONS = [
6608
6429
  { key: "params", label: "path parameters", flag: "--param" },
6609
6430
  { key: "query", label: "query parameters", flag: "--query" },
@@ -6695,16 +6516,13 @@ function renderSection(label, flag, rows) {
6695
6516
  }
6696
6517
  return lines;
6697
6518
  }
6698
- function renderCommandUsage(command) {
6519
+ function renderCommandUsage(command, invoke) {
6699
6520
  const lines = [`${plain(command.name)} ${command.method} ${plain(command.path)}`, ""];
6700
6521
  let described = false;
6701
6522
  if (command.summary) {
6702
6523
  lines.push(` ${plain(command.summary)}`, "");
6703
6524
  }
6704
- if (command.effect || command.scopes) {
6705
- lines.push(` Effect: ${command.effect ?? "unknown"}`);
6706
- lines.push(` Scopes: ${command.scopes?.map(plain).join(", ") || "(not declared)"}`, "");
6707
- }
6525
+ lines.push(...metadataLines(command));
6708
6526
  for (const section of SECTIONS) {
6709
6527
  const schema = command.input[section.key];
6710
6528
  if (!isSchema(schema)) {
@@ -6720,8 +6538,20 @@ function renderCommandUsage(command) {
6720
6538
  if (!described) {
6721
6539
  lines.push(" Takes no input.", "");
6722
6540
  }
6723
- lines.push(` Invoke: spfn ops call ${plain(command.name)}${exampleFlags(command)}`);
6724
- return lines.join("\n");
6541
+ if (invoke !== void 0) {
6542
+ lines.push(` Invoke: ${invoke} ${plain(command.name)}${exampleFlags(command)}`);
6543
+ }
6544
+ return lines.join("\n").replace(/\n+$/, "");
6545
+ }
6546
+ function metadataLines(command) {
6547
+ if (!command.effect && !command.scopes) {
6548
+ return [];
6549
+ }
6550
+ const lines = [` Effect: ${command.effect ?? "unknown"}`];
6551
+ if (command.module !== void 0 || command.scopes !== void 0) {
6552
+ lines.push(` Scopes: ${command.scopes?.map(plain).join(", ") || "(not declared)"}`);
6553
+ }
6554
+ return [...lines, ""];
6725
6555
  }
6726
6556
  function exampleFlags(command) {
6727
6557
  const parts = [];
@@ -6739,6 +6569,356 @@ function exampleFlags(command) {
6739
6569
  return parts.join("");
6740
6570
  }
6741
6571
 
6572
+ // src/surface/manifest-trust.ts
6573
+ function trustedManifest(body, reader) {
6574
+ const manifest = body;
6575
+ if (manifest?.manifestVersion !== 1 || !Array.isArray(manifest.commands)) {
6576
+ throw new Error("The manifest answer has an unknown shape.");
6577
+ }
6578
+ const modules = usableModules(manifest.modules, reader);
6579
+ return {
6580
+ manifestVersion: 1,
6581
+ ...manifest.modules !== void 0 ? { modules } : {},
6582
+ commands: usableCommands(manifest.commands, new Set(modules.map((module) => module.id)), reader)
6583
+ };
6584
+ }
6585
+ var METHODS = /* @__PURE__ */ new Set(["GET", "POST", "PUT", "PATCH", "DELETE"]);
6586
+ var EFFECTS = /* @__PURE__ */ new Set(["read", "write", "destructive"]);
6587
+ var MODULE_ID = /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;
6588
+ var CONTRACT_VERSION = /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)*$/;
6589
+ var MAX_ID_LENGTH = 64;
6590
+ var MAX_SOURCE_LENGTH = 128;
6591
+ var MAX_SUMMARY_LENGTH = 500;
6592
+ var MAX_SCOPES = 64;
6593
+ var MAX_SCOPE_LENGTH = 128;
6594
+ function unusableBecause(command, reader) {
6595
+ if (typeof command?.name !== "string" || command.name.length === 0) {
6596
+ return "it has no name";
6597
+ }
6598
+ if (typeof command.method !== "string" || !METHODS.has(command.method)) {
6599
+ return `its method is ${JSON.stringify(command.method)}`;
6600
+ }
6601
+ if (typeof command.path !== "string") {
6602
+ return `its path ${JSON.stringify(command.path)} is not a string`;
6603
+ }
6604
+ const pathReason = unstablePathBecause(command.path, reader.prefix);
6605
+ if (pathReason !== null) {
6606
+ return `its path ${JSON.stringify(command.path)} ${pathReason}`;
6607
+ }
6608
+ return null;
6609
+ }
6610
+ function usableCommands(commands, moduleIds, reader) {
6611
+ const usable = [];
6612
+ for (const command of commands) {
6613
+ const reason = unusableBecause(command, reader);
6614
+ if (reason !== null) {
6615
+ reader.warn(
6616
+ `Ignoring a command the ${reader.namespace} manifest announced: ${reason}.`,
6617
+ { kind: "command", reason }
6618
+ );
6619
+ continue;
6620
+ }
6621
+ usable.push(withMetadata(command, moduleIds, reader));
6622
+ }
6623
+ return usable;
6624
+ }
6625
+ function withMetadata(command, moduleIds, reader) {
6626
+ const normalized = {
6627
+ name: command.name,
6628
+ method: command.method,
6629
+ path: command.path,
6630
+ input: isPlainObject(command.input) ? command.input : {}
6631
+ };
6632
+ if (command.module !== void 0 || command.scopes !== void 0) {
6633
+ return withModuleMetadata(normalized, command, moduleIds, reader);
6634
+ }
6635
+ return withAppMetadata(normalized, command, reader);
6636
+ }
6637
+ function withModuleMetadata(normalized, command, moduleIds, reader) {
6638
+ const reason = unusableModuleMetadataBecause(command, moduleIds, reader);
6639
+ if (reason !== null) {
6640
+ return rejectedMetadata(normalized, "module", reason, reader);
6641
+ }
6642
+ return {
6643
+ ...normalized,
6644
+ module: command.module,
6645
+ summary: command.summary,
6646
+ effect: command.effect,
6647
+ scopes: [...command.scopes]
6648
+ };
6649
+ }
6650
+ function withAppMetadata(normalized, command, reader) {
6651
+ const reason = unusableAppMetadataBecause(command);
6652
+ if (reason !== null) {
6653
+ return rejectedMetadata(normalized, "command", reason, reader);
6654
+ }
6655
+ return {
6656
+ ...normalized,
6657
+ ...command.summary !== void 0 ? { summary: command.summary } : {},
6658
+ ...command.effect !== void 0 ? { effect: command.effect } : {}
6659
+ };
6660
+ }
6661
+ function rejectedMetadata(normalized, metadata, reason, reader) {
6662
+ reader.warn(
6663
+ `Ignoring ${metadata} metadata for command "${plain(normalized.name)}": ${reason}. Its effect is unknown, so treat it as destructive.`,
6664
+ { kind: "metadata", command: normalized.name, metadata, reason }
6665
+ );
6666
+ return { ...normalized, metadataRejected: true };
6667
+ }
6668
+ function unusableAppMetadataBecause(command) {
6669
+ if (command.summary !== void 0 && !isUsableSummary(command.summary)) {
6670
+ return "its summary is empty or too long";
6671
+ }
6672
+ if (command.effect !== void 0 && !EFFECTS.has(command.effect)) {
6673
+ return "its effect is unknown";
6674
+ }
6675
+ return null;
6676
+ }
6677
+ function isUsableSummary(summary) {
6678
+ return typeof summary === "string" && summary.length > 0 && summary.length <= MAX_SUMMARY_LENGTH;
6679
+ }
6680
+ function unusableModuleMetadataBecause(command, moduleIds, reader) {
6681
+ if (typeof command.module !== "string" || !moduleIds.has(command.module)) {
6682
+ return "it names no usable module";
6683
+ }
6684
+ if (!command.name.startsWith(`${command.module}.`)) {
6685
+ return "its qualified name does not start with the module id";
6686
+ }
6687
+ if (!command.path.startsWith(`${reader.prefix}${command.module}/`)) {
6688
+ return "its path is outside the module namespace";
6689
+ }
6690
+ if (!isUsableSummary(command.summary)) {
6691
+ return "its summary is missing or too long";
6692
+ }
6693
+ if (typeof command.effect !== "string" || !EFFECTS.has(command.effect)) {
6694
+ return "its effect is unknown";
6695
+ }
6696
+ if (!Array.isArray(command.scopes) || command.scopes.length === 0 || command.scopes.length > MAX_SCOPES || command.scopes.some((scope) => typeof scope !== "string" || scope.length === 0 || scope.length > MAX_SCOPE_LENGTH)) {
6697
+ return "its scopes are missing or invalid";
6698
+ }
6699
+ return null;
6700
+ }
6701
+ function usableModules(value, reader) {
6702
+ if (value === void 0) {
6703
+ return [];
6704
+ }
6705
+ if (!Array.isArray(value)) {
6706
+ reader.warn("Ignoring module metadata: modules is not an array.", {
6707
+ kind: "modules",
6708
+ reason: "modules is not an array"
6709
+ });
6710
+ return [];
6711
+ }
6712
+ const modules = [];
6713
+ const claimed = /* @__PURE__ */ new Set();
6714
+ for (const raw of value) {
6715
+ const reason = unusableModuleBecause(raw, claimed);
6716
+ if (reason !== null) {
6717
+ reader.warn(
6718
+ `Ignoring a module the ${reader.namespace} manifest announced: ${reason}.`,
6719
+ { kind: "module", reason }
6720
+ );
6721
+ continue;
6722
+ }
6723
+ const module = raw;
6724
+ claimed.add(module.id);
6725
+ modules.push({
6726
+ id: module.id,
6727
+ source: module.source,
6728
+ contractVersion: module.contractVersion,
6729
+ summary: module.summary
6730
+ });
6731
+ }
6732
+ return modules;
6733
+ }
6734
+ function unusableModuleBecause(value, claimed) {
6735
+ if (!isPlainObject(value)) {
6736
+ return "it is not an object";
6737
+ }
6738
+ const id = value.id;
6739
+ if (typeof id !== "string" || id.length > MAX_ID_LENGTH || !MODULE_ID.test(id)) {
6740
+ return "its id is invalid";
6741
+ }
6742
+ if (claimed.has(id)) {
6743
+ return `id "${id}" is duplicated`;
6744
+ }
6745
+ if (typeof value.source !== "string" || value.source.length === 0 || value.source.length > MAX_SOURCE_LENGTH) {
6746
+ return `module "${id}" has an invalid source`;
6747
+ }
6748
+ if (typeof value.contractVersion !== "string" || !CONTRACT_VERSION.test(value.contractVersion)) {
6749
+ return `module "${id}" has an invalid contract version`;
6750
+ }
6751
+ if (typeof value.summary !== "string" || value.summary.length === 0 || value.summary.length > MAX_SUMMARY_LENGTH) {
6752
+ return `module "${id}" has an invalid summary`;
6753
+ }
6754
+ return null;
6755
+ }
6756
+ function isPlainObject(value) {
6757
+ return value !== null && typeof value === "object" && !Array.isArray(value);
6758
+ }
6759
+
6760
+ // src/surface/transport.ts
6761
+ function isLoopback(hostname3) {
6762
+ return hostname3 === "localhost" || hostname3 === "127.0.0.1" || hostname3 === "[::1]" || hostname3.endsWith(".localhost");
6763
+ }
6764
+ function transportRefusalOf(url) {
6765
+ if (url.protocol === "https:" || url.protocol === "http:" && isLoopback(url.hostname)) {
6766
+ return null;
6767
+ }
6768
+ return url.protocol === "http:" ? "cleartext-http" : "not-http";
6769
+ }
6770
+ function parseAppUrl(appUrl) {
6771
+ try {
6772
+ return new URL(appUrl);
6773
+ } catch {
6774
+ return null;
6775
+ }
6776
+ }
6777
+ function assertTransportSafe(appUrl) {
6778
+ const url = parseAppUrl(appUrl);
6779
+ if (url === null) {
6780
+ throw new Error(`Invalid app URL: ${appUrl}`);
6781
+ }
6782
+ const refusal = transportRefusalOf(url);
6783
+ if (refusal === "cleartext-http") {
6784
+ throw new Error(`Refusing to talk to ${appUrl} over http: a credential would cross it in the clear. Use https. http is allowed only against localhost.`);
6785
+ }
6786
+ if (refusal === "not-http") {
6787
+ throw new Error(`App URL must be https, got "${url.protocol}//". http is allowed only against localhost.`);
6788
+ }
6789
+ }
6790
+
6791
+ // src/surface/client.ts
6792
+ var NAMESPACE = /^(?:\/[A-Za-z0-9_-]+)+$/;
6793
+ var SurfaceManifestError = class extends Error {
6794
+ constructor(message, status) {
6795
+ super(message);
6796
+ this.status = status;
6797
+ this.name = "SurfaceManifestError";
6798
+ }
6799
+ };
6800
+ function joinUrl(appUrl, path5) {
6801
+ return appUrl.replace(/\/+$/, "") + path5;
6802
+ }
6803
+ async function request(appUrl, token, method, path5, body) {
6804
+ const response = await fetch(joinUrl(appUrl, path5), {
6805
+ method,
6806
+ headers: {
6807
+ Authorization: `Bearer ${token}`,
6808
+ ...body !== void 0 ? { "Content-Type": "application/json" } : {}
6809
+ },
6810
+ ...body !== void 0 ? { body: JSON.stringify(body) } : {}
6811
+ });
6812
+ const text = await response.text();
6813
+ let parsed = text;
6814
+ try {
6815
+ parsed = text.length > 0 ? JSON.parse(text) : null;
6816
+ } catch {
6817
+ }
6818
+ return { status: response.status, body: parsed };
6819
+ }
6820
+ function manifestRefusal(namespace, status) {
6821
+ if (status === 401 || status === 403) {
6822
+ return new SurfaceManifestError(`The app refused the token (GET ${namespace}/_manifest answered ${status}).`, status);
6823
+ }
6824
+ if (status === 404) {
6825
+ return new SurfaceManifestError(`No surface at ${namespace} on this app (GET ${namespace}/_manifest answered 404).`, status);
6826
+ }
6827
+ return new SurfaceManifestError(`Manifest request failed with status ${status}.`, status);
6828
+ }
6829
+ function assertNamespace(namespace) {
6830
+ if (typeof namespace !== "string" || !NAMESPACE.test(namespace)) {
6831
+ throw new Error(
6832
+ `Surface namespace ${JSON.stringify(namespace)} is invalid. Use an absolute path of [A-Za-z0-9_-] segments without a trailing slash, such as "/_app".`
6833
+ );
6834
+ }
6835
+ }
6836
+ function findCommand(manifest, name) {
6837
+ const command = manifest.commands.find((candidate) => candidate.name === name);
6838
+ if (!command) {
6839
+ throw new Error(`Unknown command "${plain(name)}".`);
6840
+ }
6841
+ return command;
6842
+ }
6843
+ function createSurfaceClient(options) {
6844
+ assertTransportSafe(options.appUrl);
6845
+ assertNamespace(options.namespace);
6846
+ const { appUrl, namespace } = options;
6847
+ const token = async () => typeof options.token === "function" ? await options.token() : options.token;
6848
+ const reader = { namespace, prefix: `${namespace}/`, warn: options.onWarning ?? (() => void 0) };
6849
+ const manifest = async () => {
6850
+ const { status, body } = await request(appUrl, await token(), "GET", `${namespace}/_manifest`);
6851
+ if (status !== 200) {
6852
+ throw manifestRefusal(namespace, status);
6853
+ }
6854
+ return trustedManifest(body, reader);
6855
+ };
6856
+ const invoke = async (command, input) => {
6857
+ const path5 = buildCommandPath(command, input.params, input.query, namespace);
6858
+ return await request(appUrl, await token(), command.method, path5, input.body);
6859
+ };
6860
+ return {
6861
+ manifest,
6862
+ invoke,
6863
+ describe: (fetched, name) => renderCommandUsage(findCommand(fetched, name)),
6864
+ call: async (name, input) => await invoke(findCommand(await manifest(), name), input)
6865
+ };
6866
+ }
6867
+
6868
+ // src/utils/ops/client.ts
6869
+ var OPS_NAMESPACE = "/_ops";
6870
+ function printOpsWarning(_message, warning) {
6871
+ switch (warning.kind) {
6872
+ case "command":
6873
+ console.error(`\u26A0\uFE0F Ignoring an ops command the manifest announced: ${warning.reason}.`);
6874
+ break;
6875
+ case "metadata":
6876
+ console.error(
6877
+ `\u26A0\uFE0F Ignoring ${warning.metadata ?? "module"} metadata for ops command "${plain(warning.command)}": ${warning.reason}. Calling it will require --yes.`
6878
+ );
6879
+ break;
6880
+ case "modules":
6881
+ console.error(`\u26A0\uFE0F Ignoring ops module metadata: ${warning.reason}.`);
6882
+ break;
6883
+ case "module":
6884
+ console.error(`\u26A0\uFE0F Ignoring an ops module the manifest announced: ${warning.reason}.`);
6885
+ break;
6886
+ }
6887
+ }
6888
+ function opsClient(appUrl, token) {
6889
+ return createSurfaceClient({ appUrl, namespace: OPS_NAMESPACE, token, onWarning: printOpsWarning });
6890
+ }
6891
+ function inOpsTerms(error) {
6892
+ if (!(error instanceof SurfaceManifestError)) {
6893
+ return error;
6894
+ }
6895
+ if (error.status === 401 || error.status === 403) {
6896
+ return new Error("The app refused the ops token (check --token / SPFN_OPS_TOKEN / keychain).");
6897
+ }
6898
+ if (error.status === 404) {
6899
+ return new Error("No ops surface at this app (GET /_ops/_manifest answered 404). Mount one with createOpsRouter() and .packages([opsRouter]).");
6900
+ }
6901
+ return error;
6902
+ }
6903
+ async function fetchOpsManifest(appUrl, token) {
6904
+ return await opsClient(appUrl, token).manifest().catch((error) => Promise.reject(inOpsTerms(error)));
6905
+ }
6906
+ function assertOpsCommandPath(command) {
6907
+ const templateReason = unstablePathBecause(command.path, `${OPS_NAMESPACE}/`);
6908
+ if (templateReason !== null) {
6909
+ throw new Error(`Refusing ops command path ${JSON.stringify(command.path)} because it ${templateReason}.`);
6910
+ }
6911
+ }
6912
+ async function invokeOpsCommand(appUrl, token, command, input) {
6913
+ assertOpsCommandPath(command);
6914
+ return await opsClient(appUrl, token).invoke(command, input);
6915
+ }
6916
+
6917
+ // src/utils/ops/describe.ts
6918
+ function renderCommandUsage2(command) {
6919
+ return renderCommandUsage(command, "spfn ops call");
6920
+ }
6921
+
6742
6922
  // src/commands/ops/resolve.ts
6743
6923
  import chalk33 from "chalk";
6744
6924
 
@@ -6811,14 +6991,12 @@ function deleteOpsToken(account) {
6811
6991
  }
6812
6992
 
6813
6993
  // src/commands/ops/resolve.ts
6814
- function isLoopback(hostname3) {
6815
- return hostname3 === "localhost" || hostname3 === "127.0.0.1" || hostname3 === "[::1]" || hostname3.endsWith(".localhost");
6816
- }
6817
- function assertTransportSafe(parsed, appUrl) {
6818
- if (parsed.protocol === "https:" || parsed.protocol === "http:" && isLoopback(parsed.hostname)) {
6994
+ function assertTransportSafe2(parsed, appUrl) {
6995
+ const refusal = transportRefusalOf(parsed);
6996
+ if (refusal === null) {
6819
6997
  return;
6820
6998
  }
6821
- if (parsed.protocol === "http:") {
6999
+ if (refusal === "cleartext-http") {
6822
7000
  console.error(chalk33.red(`\u274C Refusing to talk to ${appUrl} over http.`));
6823
7001
  console.error(chalk33.gray(" An administrator password and an ops token cross this connection, and http sends both in the clear."));
6824
7002
  console.error(chalk33.gray(" Use https. http is allowed only against localhost."));
@@ -6841,7 +7019,7 @@ function resolveAppUrl(options) {
6841
7019
  console.error(chalk33.red(`\u274C Invalid app URL: ${appUrl}`));
6842
7020
  process.exit(1);
6843
7021
  }
6844
- assertTransportSafe(parsed, appUrl);
7022
+ assertTransportSafe2(parsed, appUrl);
6845
7023
  return appUrl;
6846
7024
  }
6847
7025
  function appAccount(appUrl) {
@@ -7245,7 +7423,7 @@ async function callCommand(name, options) {
7245
7423
  process.exit(1);
7246
7424
  }
7247
7425
  if (options.describe) {
7248
- console.log(options.json ? JSON.stringify(command, null, 2) : renderCommandUsage(command));
7426
+ console.log(options.json ? JSON.stringify(command, null, 2) : renderCommandUsage2(command));
7249
7427
  return;
7250
7428
  }
7251
7429
  if (destructiveConfirmationRequired(command, options.yes)) {