@ipab/cli 0.1.0-rc.1 → 0.1.0-rc.2

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 (62) hide show
  1. package/README.md +21 -5
  2. package/dist/app-authoring.d.ts +10 -0
  3. package/dist/app-authoring.d.ts.map +1 -1
  4. package/dist/app-authoring.js +127 -11
  5. package/dist/app-authoring.js.map +1 -1
  6. package/dist/assembly.d.ts +7 -0
  7. package/dist/assembly.d.ts.map +1 -0
  8. package/dist/assembly.js +131 -0
  9. package/dist/assembly.js.map +1 -0
  10. package/dist/authoring.d.ts +1 -1
  11. package/dist/authoring.d.ts.map +1 -1
  12. package/dist/authoring.js +3 -3
  13. package/dist/authoring.js.map +1 -1
  14. package/dist/builtins/template.node.car +0 -0
  15. package/dist/builtins/template.web-app.car +0 -0
  16. package/dist/cli.d.ts +1 -0
  17. package/dist/cli.d.ts.map +1 -1
  18. package/dist/cli.js +520 -66
  19. package/dist/cli.js.map +1 -1
  20. package/dist/config-secret.d.ts +3 -0
  21. package/dist/config-secret.d.ts.map +1 -0
  22. package/dist/config-secret.js +83 -0
  23. package/dist/config-secret.js.map +1 -0
  24. package/dist/config.d.ts +5 -2
  25. package/dist/config.d.ts.map +1 -1
  26. package/dist/config.js +105 -7
  27. package/dist/config.js.map +1 -1
  28. package/dist/content-provider.d.ts +9 -0
  29. package/dist/content-provider.d.ts.map +1 -0
  30. package/dist/content-provider.js +90 -0
  31. package/dist/content-provider.js.map +1 -0
  32. package/dist/get.d.ts +3 -0
  33. package/dist/get.d.ts.map +1 -0
  34. package/dist/get.js +61 -0
  35. package/dist/get.js.map +1 -0
  36. package/dist/identity.d.ts +9 -0
  37. package/dist/identity.d.ts.map +1 -0
  38. package/dist/identity.js +89 -0
  39. package/dist/identity.js.map +1 -0
  40. package/dist/source-bundle.js +1 -1
  41. package/dist/source-bundle.js.map +1 -1
  42. package/dist/state.d.ts +15 -0
  43. package/dist/state.d.ts.map +1 -1
  44. package/dist/state.js +100 -1
  45. package/dist/state.js.map +1 -1
  46. package/dist/swarm.d.ts +113 -0
  47. package/dist/swarm.d.ts.map +1 -0
  48. package/dist/swarm.js +760 -0
  49. package/dist/swarm.js.map +1 -0
  50. package/package.json +10 -5
  51. package/src/app-authoring.ts +188 -16
  52. package/src/assembly.ts +182 -0
  53. package/src/authoring.ts +10 -3
  54. package/src/cli.ts +641 -68
  55. package/src/config-secret.ts +96 -0
  56. package/src/config.ts +142 -7
  57. package/src/content-provider.ts +123 -0
  58. package/src/get.ts +68 -0
  59. package/src/identity.ts +133 -0
  60. package/src/source-bundle.ts +1 -1
  61. package/src/state.ts +112 -1
  62. package/src/swarm.ts +1186 -0
package/src/cli.ts CHANGED
@@ -11,6 +11,7 @@ import {
11
11
  publicUrl,
12
12
  stateLocation,
13
13
  storeConfiguration,
14
+ visibleConfig,
14
15
  type GlobalOptions,
15
16
  } from "./config.js";
16
17
  import { HostError, message, object, syntax } from "./errors.js";
@@ -26,11 +27,28 @@ import { execute } from "./runtime.js";
26
27
  import { validatedBundle } from "./space.js";
27
28
  import { exactCid, pinName, State, type RunRecord } from "./state.js";
28
29
  import { buildBundle, inspectBundle, importBundle } from "./authoring.js";
29
- import { buildApp, initApp } from "./app-authoring.js";
30
+ import { initApp } from "./app-authoring.js";
31
+ import { assembleBundle } from "./assembly.js";
32
+ import { getBundle } from "./get.js";
33
+ import {
34
+ createSwarm,
35
+ requestMembership,
36
+ approveMembership,
37
+ joinSwarm,
38
+ descriptor,
39
+ swarmHeader,
40
+ addSwarm,
41
+ updateSwarm,
42
+ searchNames,
43
+ resolveReference,
44
+ publish,
45
+ type SwarmContext,
46
+ } from "./swarm.js";
30
47
  import { schemaAlias } from "./app-definition.js";
31
48
  import { addPin, deletePin, pinDetails, renamePin } from "./pins.js";
32
49
  import { logFiles } from "./logs.js";
33
50
  import { builtinContent } from "./builtins.js";
51
+ import { readSecretStream } from "./config-secret.js";
34
52
 
35
53
  export interface IO {
36
54
  out(text: string): void;
@@ -38,6 +56,7 @@ export interface IO {
38
56
  tty: boolean;
39
57
  columns?(): number | undefined;
40
58
  confirm(text: string): Promise<boolean>;
59
+ readSecret?(): Promise<string>;
41
60
  }
42
61
  export const processIO: IO = {
43
62
  out(text) {
@@ -50,6 +69,14 @@ export const processIO: IO = {
50
69
  columns() {
51
70
  return process.stdout.columns;
52
71
  },
72
+ async readSecret() {
73
+ if (process.stdin.isTTY)
74
+ syntax(
75
+ "Pipe the API key through stdin; interactive echo is not permitted.",
76
+ );
77
+ process.stdin.setEncoding("utf8");
78
+ return readSecretStream(process.stdin as AsyncIterable<string>);
79
+ },
53
80
  async confirm(text) {
54
81
  const reader = createInterface({
55
82
  input: process.stdin,
@@ -65,13 +92,28 @@ export const processIO: IO = {
65
92
  },
66
93
  };
67
94
  const commands: Record<string, string> = {
95
+ "swarm create": "swarm create [--service URL] [--resume OPERATION]",
96
+ "swarm request": "swarm request SWARM_CID",
97
+ "swarm approve": "swarm approve REQUEST_CID [--expires-in SECONDS] --yes",
98
+ "swarm join": "swarm join RESPONSE_CID",
99
+ "swarm status": "swarm status [SWARM_CID]",
100
+ "swarm list": "swarm list",
101
+ "swarm add": "swarm add SWARM_CID [--alias ALIAS]",
102
+ "swarm use": "swarm use CID_OR_ALIAS",
103
+ "swarm remove": "swarm remove CID_OR_ALIAS",
104
+ "swarm update":
105
+ "swarm update [CID_OR_ALIAS] [--name TEXT] [--description TEXT]",
106
+ publish:
107
+ "publish CID_OR_CAR [--name NAME [--expect OLD_NODE_CID | --snapshot]]",
108
+ get: "get REF [--raw] [--force | --no-force] [-o DIRECTORY]",
109
+ search: "search QUERY [--current] [--force | --no-force]",
68
110
  init: "init NAME [DIR] [OPTIONS]",
69
- build: "build [DIR] [OPTIONS]",
111
+ build: "build [SOURCE] [OPTIONS]",
70
112
  "bundle build": "bundle build SOURCE [OPTIONS]",
71
113
  "bundle inspect": "bundle inspect SOURCE",
72
114
  "bundle import": "bundle import FILE.car",
73
- exec: "exec [--log] APP [APP_ARGS...]",
74
- open: "open [--log] CONTENT",
115
+ exec: "exec [--log] [--force | --no-force] APP [APP_ARGS...]",
116
+ open: "open [--log] [--raw] [--force | --no-force] CONTENT",
75
117
  "pin add": "pin add NAME CID",
76
118
  "pin delete": "pin delete NAME",
77
119
  "pin list": "pin list [--type TYPE]",
@@ -81,7 +123,8 @@ const commands: Record<string, string> = {
81
123
  "register set": "register set SCHEMA APP [--replace] [-- TEMPLATE...]",
82
124
  "register remove": "register remove SCHEMA",
83
125
  "config get": "config get [KEY]",
84
- "config set": "config set KEY VALUE",
126
+ "config set":
127
+ "config set KEY VALUE\n ipab config set pointers.apiKey - < protected-key-file",
85
128
  "config reset": "config reset KEY",
86
129
  "store usage": "store usage",
87
130
  "store gc": "store gc",
@@ -91,6 +134,7 @@ const commands: Record<string, string> = {
91
134
  "history remove RUN_ID... [--yes]\n ipab history remove FILTERS [--yes]",
92
135
  };
93
136
  const groups: Record<string, string> = {
137
+ swarm: "Create, authorize, select and manage personal swarms",
94
138
  bundle: "Create, inspect and import content bundles",
95
139
  pin: "Retain content and manage short names",
96
140
  register: "Associate content types with Apps",
@@ -108,6 +152,156 @@ const commandHelp: Record<
108
152
  notes?: string[];
109
153
  }
110
154
  > = {
155
+ "swarm create": {
156
+ summary: "Create a swarm using the account HOME identity",
157
+ options: [
158
+ "--service URL Must match the protected pointers.service origin.",
159
+ "--resume OPERATION Recover the same saved create/idempotency result.",
160
+ "--name TEXT Initial mutable swarm name.",
161
+ "--description TEXT Initial mutable description.",
162
+ "--alias ALIAS Optional local registry alias (not the shared name).",
163
+ ],
164
+ examples: [
165
+ "ipab config set pointers.service https://service.example",
166
+ "ipab config set pointers.apiKey -",
167
+ "ipab swarm create",
168
+ ],
169
+ notes: [
170
+ "Creation uses the protected, origin-bound API key and owner possession proof.",
171
+ "Uses the prepared private Kubo provider; never deploys infrastructure.",
172
+ "Returns one descriptor CID; owner needs no member certificate.",
173
+ ],
174
+ },
175
+ "swarm request": {
176
+ summary: "Publish a signed account membership request",
177
+ examples: ["ipab swarm request SWARM_CID"],
178
+ notes: [
179
+ "Returns one request CID. Private IPFS access is a prerequisite, not membership.",
180
+ ],
181
+ },
182
+ "swarm approve": {
183
+ summary: "Owner signs a certificate for an exact request",
184
+ options: [
185
+ "--yes Explicit approval; required outside a TTY.",
186
+ "--expires-in SECONDS 60..2592000; default 604800.",
187
+ ],
188
+ examples: ["ipab swarm approve REQUEST_CID --yes"],
189
+ notes: ["Returns one response CID. Never exports the owner private key."],
190
+ },
191
+ "swarm join": {
192
+ summary: "Verify a response and authenticate HEAD",
193
+ examples: ["ipab swarm join RESPONSE_CID"],
194
+ options: ["--alias ALIAS Register this swarm with a local alias."],
195
+ notes: [
196
+ "Requires this account's exact pending request and bound member certificate.",
197
+ ],
198
+ },
199
+ "swarm status": {
200
+ summary: "Authenticate the current swarm HEAD",
201
+ examples: ["ipab swarm status", "ipab swarm status work"],
202
+ notes: [
203
+ "Always authenticate and refresh HEAD; update the local header cache.",
204
+ ],
205
+ },
206
+ "swarm list": {
207
+ summary: "List local swarm registrations and the effective selection",
208
+ examples: ["ipab swarm list", "ipab --json swarm list"],
209
+ notes: ["Local only; does not verify remote membership or refresh HEAD."],
210
+ },
211
+ "swarm add": {
212
+ summary: "Authenticate and register a swarm you already have access to",
213
+ options: [
214
+ "--alias ALIAS Unique local alias; does not rename the shared swarm.",
215
+ ],
216
+ examples: ["ipab swarm add SWARM_CID --alias work"],
217
+ notes: [
218
+ "Not a membership grant. The first registration becomes the saved default only if none exists.",
219
+ ],
220
+ },
221
+ "swarm use": {
222
+ summary: "Save a registered swarm as the current default",
223
+ examples: ["ipab swarm use work"],
224
+ notes: ["Local only. --swarm still overrides the saved default."],
225
+ },
226
+ "swarm remove": {
227
+ summary: "Forget a local registration without revoking membership",
228
+ examples: ["ipab swarm remove work"],
229
+ notes: [
230
+ "Preserves credentials, content and remote membership. Clears a matching saved default without selecting a replacement.",
231
+ ],
232
+ },
233
+ "swarm update": {
234
+ summary: "Update shared swarm information as an owner or member",
235
+ arguments: ["CID_OR_ALIAS Defaults to the effective current swarm."],
236
+ options: [
237
+ "--name TEXT Replace the shared display name; empty text clears it.",
238
+ "--description TEXT Replace the shared description; empty text clears it.",
239
+ ],
240
+ examples: [
241
+ 'ipab swarm update work --name "Team" --description "Shared workspace"',
242
+ 'ipab swarm update --description ""',
243
+ ],
244
+ notes: [
245
+ "Requires at least one field. Any authorized member can update both fields.",
246
+ "Last successful write wins for the specified fields; no expected-value/version input.",
247
+ "Automatically retries HEAD contention while preserving current Names and unspecified properties.",
248
+ "Shared name changes do not rename local registry aliases.",
249
+ ],
250
+ },
251
+ search: {
252
+ summary: "Search formal Names across registered swarms",
253
+ arguments: [
254
+ "QUERY Case-insensitive literal name substring, 1..256 characters.",
255
+ ],
256
+ options: [
257
+ "--current Search only the effective current swarm; conflicts with --swarm.",
258
+ "--force Refresh HEAD for every swarm in the search scope.",
259
+ "--no-force Override swarm.forceRefresh and use valid cached headers.",
260
+ ],
261
+ examples: ["ipab search hello", "ipab --swarm work search hello --force"],
262
+ notes: [
263
+ "Searches all registered swarms unless --current or --swarm selects one.",
264
+ "Valid caches use local Names only; absent/expired caches refresh. No payload downloads.",
265
+ "No matches is success, not a reason to refresh valid caches. Any failed swarm fails the whole search.",
266
+ ],
267
+ },
268
+ publish: {
269
+ summary: "Provide built content and explicitly publish a Name",
270
+ options: [
271
+ "--name NAME New formal Name; occupied Names fail.",
272
+ "--expect CID Exact old Artifact node, required for iteration.",
273
+ "--snapshot Name ordinary content without an Artifact; initial only.",
274
+ ],
275
+ examples: [
276
+ "ipab publish app.car --name apps/hello",
277
+ "ipab publish APP_CID --name apps/hello --expect OLD_NODE_CID",
278
+ "ipab publish CONTENT_CID",
279
+ ],
280
+ notes: [
281
+ "No build, edit, install or execution. CID-only stdout.",
282
+ "Different-name CAS contention is rebased; same-name edits conflict (exit 3).",
283
+ "Kubo pin confirmation precedes HEAD; it does not prove a remote device is online.",
284
+ ],
285
+ },
286
+ get: {
287
+ summary: "Verify and unpack Bundle content without executing it",
288
+ options: [
289
+ "--raw Select the Artifact node instead of its value.",
290
+ "--force Refresh the shared Name's swarm HEAD.",
291
+ "--no-force Override swarm.forceRefresh and use valid cached headers.",
292
+ "-o, --output DIRECTORY New or empty directory; defaults to resolved CID.",
293
+ ],
294
+ examples: [
295
+ "ipab --json get ipab:///apps/hello -o hello-app",
296
+ "ipab get ipab://work/apps/hello -o hello-app",
297
+ "ipab get --raw RELEASE_CID",
298
+ ],
299
+ notes: [
300
+ "Returns the selected content CID and original target CID (editing baseline).",
301
+ "ipab://SWARM_CID_OR_ALIAS/PATH selects its own swarm; ipab:///PATH uses --swarm or swarm.default.",
302
+ "Does not install, build, edit, or automatically retrieve associated source.",
303
+ ],
304
+ },
111
305
  "store usage": {
112
306
  summary: "Query cached and recursively pinned block bytes",
113
307
  examples: ["ipab store usage", "ipab --json store usage"],
@@ -140,21 +334,24 @@ const commandHelp: Record<
140
334
  notes: ["Does not install dependencies or execute template code."],
141
335
  },
142
336
  build: {
143
- summary: "Build an App CAR from a project",
144
- arguments: ["DIR Project directory (default: current directory)."],
337
+ summary: "Assemble any Bundle using ipab.build.yaml (no compilation)",
338
+ arguments: [
339
+ "SOURCE Recipe file or Bundle directory (default: current directory).",
340
+ ],
145
341
  options: [
146
- "-o, --output FILE Destination (default: dist/app.car).",
342
+ "-o, --output FILE Destination (default: dist/bundle.car).",
147
343
  "--replace Allow replacing existing regular artifacts.",
148
- "--no-import Write CAR files without importing the App into Store.",
149
- "--with-source Include a separate source CAR (default: enabled).",
150
- "--without-source Omit source CAR; conflicts with --with-source.",
344
+ "--no-import Write the CAR without importing the Bundle into Store.",
345
+ ],
346
+ examples: [
347
+ "ipab build prepared-app",
348
+ "ipab build ipab.build.yaml --replace",
151
349
  ],
152
- examples: ["ipab build", "ipab build hello --replace --without-source"],
153
350
  notes: [
154
- "Uses local tsc and bundles Node CommonJS; ipab.yaml configures the build.",
155
- "Explicit ipab-prebuild strategy executes trusted project code.",
156
- "Source follows project .gitignore rules; review private files before sharing.",
157
- "Imports only the App, without pinning; source needs separate import/retention.",
351
+ "Recipe explicitly maps source files and exact CID imports to target paths.",
352
+ "Type and entry come from .bundle.yaml; imported DAG identities are preserved.",
353
+ "Legacy App ipab.yaml is rejected; use project preparation tools separately.",
354
+ "Select explicit files; review private files before providing Bundles.",
158
355
  "Store failures preserve the CAR; retry with ipab bundle import FILE.car.",
159
356
  ],
160
357
  },
@@ -192,20 +389,23 @@ const commandHelp: Record<
192
389
  ],
193
390
  },
194
391
  exec: {
195
- summary: "Run an App by CID or named pin",
392
+ summary: "Run an App by CID, named pin or IPAB URI",
196
393
  arguments: [
197
394
  "APP_ARGS Everything after APP is passed verbatim, including --help.",
198
395
  ],
199
396
  options: [
200
397
  "--log Record stdout/stderr; must precede APP. Requires history enabled.",
398
+ "--force Refresh the shared Name's swarm HEAD; must precede APP.",
399
+ "--no-force Override swarm.forceRefresh; must precede APP.",
201
400
  ],
202
401
  examples: [
203
402
  "ipab exec reader",
204
- "ipab exec reader --help",
205
403
  "ipab exec --log reader",
404
+ "ipab exec ipab://work/apps/hello --help",
206
405
  ],
207
406
  notes: [
208
407
  "Apps are NOT sandboxed; run only Apps you trust.",
408
+ "ipab://SWARM_CID_OR_ALIAS/PATH selects its own swarm; ipab:///PATH uses --swarm or swarm.default.",
209
409
  "History stores argv by default; do not put secrets in arguments.",
210
410
  "Logs may contain secrets; stdin is never logged. Logging makes output non-TTY.",
211
411
  "--json is not supported; App stdio is passed through.",
@@ -213,11 +413,21 @@ const commandHelp: Record<
213
413
  },
214
414
  open: {
215
415
  summary: "Open content with its registered App",
216
- arguments: ["CONTENT Bundle CID or named pin."],
217
- options: ["--log Record stdout/stderr; requires history enabled."],
218
- examples: ["ipab open CONTENT_CID", "ipab open --log my-note"],
416
+ arguments: ["CONTENT Bundle CID, named pin or IPAB URI."],
417
+ options: [
418
+ "--log Record stdout/stderr; requires history enabled.",
419
+ "--raw Open the Artifact node rather than its value.",
420
+ "--force Refresh the shared Name's swarm HEAD.",
421
+ "--no-force Override swarm.forceRefresh and use valid cached headers.",
422
+ ],
423
+ examples: [
424
+ "ipab open CONTENT_CID",
425
+ "ipab open --log my-note",
426
+ "ipab open ipab:///documents/readme",
427
+ ],
219
428
  notes: [
220
429
  "Requires a saved registration and App support for the exact content type.",
430
+ "ipab://SWARM_CID_OR_ALIAS/PATH selects its own swarm; ipab:///PATH uses --swarm or swarm.default.",
221
431
  "Apps are NOT sandboxed; run only Apps you trust.",
222
432
  "Logs may contain secrets; stdin is never logged. Logging makes output non-TTY.",
223
433
  "--json is not supported; App stdio is passed through.",
@@ -306,11 +516,15 @@ const commandHelp: Record<
306
516
  "config set": {
307
517
  summary: "Save a local configuration value",
308
518
  examples: [
519
+ "ipab config set pointers.apiKey -",
309
520
  "ipab config set store.gateway http://127.0.0.1:8080",
310
521
  "ipab config set history.enabled false",
311
522
  ],
312
523
  notes: [
313
524
  "store.gateway is a read-only HTTP gateway; blocks, pins and GC remain local.",
525
+ "pointers.service is a canonical HTTPS origin (HTTP loopback allowed).",
526
+ "pointers.apiKey is accepted only through stdin using VALUE '-'; queries and confirmations redact it.",
527
+ "Saving pointers.apiKey protects state SQLite files with account-only Unix modes or Windows ACLs.",
314
528
  ],
315
529
  },
316
530
  "config reset": {
@@ -363,6 +577,7 @@ const commandHelp: Record<
363
577
 
364
578
  export function help(path = ""): string {
365
579
  const globalOptions = `Global options (before COMMAND):
580
+ --swarm CID|ALIAS Select shared swarm (otherwise swarm.default; URI swarm takes precedence)
366
581
  --state-dir PATH Set the local state directory
367
582
  --store-gateway URL Use a read-only upstream HTTP gateway
368
583
  --json Output management/development metadata, not App stdio`;
@@ -383,6 +598,10 @@ Create:
383
598
  bundle ${groups.bundle}
384
599
 
385
600
  Manage:
601
+ swarm ${groups.swarm}
602
+ search Search formal Names across registered swarms
603
+ publish ${commandHelp.publish!.summary}
604
+ get ${commandHelp.get!.summary}
386
605
  pin ${groups.pin}
387
606
  register ${groups.register}
388
607
  config ${groups.config}
@@ -586,10 +805,15 @@ export function parse(argv: readonly string[]): Parsed {
586
805
  syntax(
587
806
  "Store RPC is no longer supported. Use --store-gateway with an HTTP gateway URL; existing Kubo pins are not migrated.",
588
807
  );
589
- else if (flag === "--state-dir" || flag === "--store-gateway") {
808
+ else if (
809
+ flag === "--state-dir" ||
810
+ flag === "--store-gateway" ||
811
+ flag === "--swarm"
812
+ ) {
590
813
  const value = tokens.shift();
591
814
  if (!value || value.startsWith("-")) syntax(`${flag} needs a value.`);
592
815
  if (flag === "--state-dir") flags.stateDir = value;
816
+ else if (flag === "--swarm") flags.swarm = value;
593
817
  else {
594
818
  flags.storeGateway = publicUrl(value);
595
819
  }
@@ -607,10 +831,14 @@ export function parse(argv: readonly string[]): Parsed {
607
831
  if (!group) return result;
608
832
  if (group === "exec") {
609
833
  if (flags.json) syntax("--json is not supported for exec/open.");
610
- if (tokens[0] === "--log") {
611
- result.options.log = true;
612
- tokens.shift();
834
+ while (["--log", "--force", "--no-force"].includes(tokens[0] ?? "")) {
835
+ const option = tokens.shift()!.slice(2);
836
+ if (Object.hasOwn(result.options, option))
837
+ syntax(`Duplicate option --${option}.`);
838
+ result.options[option] = true;
613
839
  }
840
+ if (result.options.force && result.options["no-force"])
841
+ syntax("--force and --no-force are mutually exclusive.");
614
842
  if (tokens[0] === "-h" || tokens[0] === "--help") {
615
843
  result.help = true;
616
844
  return result;
@@ -620,11 +848,17 @@ export function parse(argv: readonly string[]): Parsed {
620
848
  result.positional = tokens;
621
849
  return result;
622
850
  }
623
- if (!["open", "init", "build"].includes(group)) {
851
+ if (!["open", "init", "build", "publish", "get", "search"].includes(group)) {
624
852
  if (
625
- !["bundle", "pin", "register", "config", "history", "store"].includes(
626
- group,
627
- )
853
+ ![
854
+ "bundle",
855
+ "pin",
856
+ "register",
857
+ "config",
858
+ "history",
859
+ "store",
860
+ "swarm",
861
+ ].includes(group)
628
862
  )
629
863
  syntax(`Unknown command "${group}".`);
630
864
  if (!tokens.length || tokens[0] === "-h" || tokens[0] === "--help") {
@@ -642,30 +876,58 @@ export function parse(argv: readonly string[]): Parsed {
642
876
  result.help = true;
643
877
  return result;
644
878
  }
879
+ if (
880
+ result.path === "config set" &&
881
+ tokens.includes("pointers.apiKey") &&
882
+ !(tokens.length === 2 && tokens[1] === "-")
883
+ )
884
+ syntax(
885
+ "API key must be provided through '-' and piped stdin; never pass it in command arguments.",
886
+ );
645
887
  const booleans =
646
888
  result.path === "bundle build"
647
889
  ? ["replace", "schema-only", "no-import"]
648
890
  : result.path === "build"
649
- ? ["replace", "no-import", "with-source", "without-source"]
650
- : result.path === "register set"
651
- ? ["replace"]
652
- : result.path === "history remove"
653
- ? ["yes"]
654
- : result.path === "open"
655
- ? ["log"]
656
- : [];
891
+ ? ["replace", "no-import"]
892
+ : result.path === "publish"
893
+ ? ["snapshot"]
894
+ : result.path === "get"
895
+ ? ["raw", "force", "no-force"]
896
+ : result.path === "search"
897
+ ? ["current", "force", "no-force"]
898
+ : result.path === "swarm approve"
899
+ ? ["yes"]
900
+ : result.path === "register set"
901
+ ? ["replace"]
902
+ : result.path === "history remove"
903
+ ? ["yes"]
904
+ : result.path === "open"
905
+ ? ["log", "raw", "force", "no-force"]
906
+ : [];
657
907
  const values =
658
- result.path === "init"
659
- ? ["template"]
660
- : result.path === "bundle build" || result.path === "build"
661
- ? ["output"]
662
- : result.path === "history list"
663
- ? ["app", "status", "since", "until", "limit", "before"]
664
- : result.path === "history remove"
665
- ? ["app", "status", "since", "until"]
666
- : result.path === "pin list"
667
- ? ["type"]
668
- : [];
908
+ result.path === "swarm create"
909
+ ? ["service", "resume", "name", "description", "alias"]
910
+ : result.path === "swarm add" || result.path === "swarm join"
911
+ ? ["alias"]
912
+ : result.path === "swarm update"
913
+ ? ["name", "description"]
914
+ : result.path === "swarm approve"
915
+ ? ["expires-in"]
916
+ : result.path === "publish"
917
+ ? ["name", "expect"]
918
+ : result.path === "get"
919
+ ? ["output"]
920
+ : result.path === "init"
921
+ ? ["template"]
922
+ : result.path === "bundle build" || result.path === "build"
923
+ ? ["output"]
924
+ : result.path === "history list"
925
+ ? ["app", "status", "since", "until", "limit", "before"]
926
+ : result.path === "history remove"
927
+ ? ["app", "status", "since", "until"]
928
+ : result.path === "pin list"
929
+ ? ["type"]
930
+ : [];
669
931
  while (tokens.length) {
670
932
  const value = tokens.shift()!;
671
933
  if (value.startsWith("--") || value === "-o") {
@@ -682,12 +944,38 @@ export function parse(argv: readonly string[]): Parsed {
682
944
  if (booleans.includes(option)) result.options[option] = true;
683
945
  else if (values.includes(option)) {
684
946
  const input = tokens.shift();
685
- if (!input || input.startsWith("--")) syntax(`${value} needs a value.`);
947
+ if (
948
+ input === undefined ||
949
+ input.startsWith("--") ||
950
+ (input === "" && result.path !== "swarm update")
951
+ )
952
+ syntax(`${value} needs a value.`);
686
953
  result.options[option] = input;
687
954
  } else syntax(`Unknown option "${value}".`);
688
955
  } else result.positional.push(value);
689
956
  }
957
+ if (result.options.force && result.options["no-force"])
958
+ syntax("--force and --no-force are mutually exclusive.");
959
+ if (
960
+ result.path === "search" &&
961
+ result.options.current &&
962
+ flags.swarm !== undefined
963
+ )
964
+ syntax("--current and --swarm are mutually exclusive.");
690
965
  const counts: Record<string, [number, number]> = {
966
+ "swarm create": [0, 0],
967
+ "swarm request": [1, 1],
968
+ "swarm approve": [1, 1],
969
+ "swarm join": [1, 1],
970
+ "swarm status": [0, 1],
971
+ "swarm list": [0, 0],
972
+ "swarm add": [1, 1],
973
+ "swarm use": [1, 1],
974
+ "swarm remove": [1, 1],
975
+ "swarm update": [0, 1],
976
+ publish: [1, 1],
977
+ get: [1, 1],
978
+ search: [1, 1],
691
979
  init: [1, 2],
692
980
  build: [0, 1],
693
981
  "bundle build": [1, 1],
@@ -743,8 +1031,15 @@ export function parse(argv: readonly string[]): Parsed {
743
1031
  !(result.path === "config reset" && result.positional[0] === "store.rpc")
744
1032
  )
745
1033
  configKey(result.positional[0]);
746
- if (result.path === "config set")
747
- parseValue(configKey(result.positional[0]), result.positional[1], true);
1034
+ if (result.path === "config set") {
1035
+ if (result.positional[0] === "pointers.apiKey") {
1036
+ if (result.positional[1] !== "-")
1037
+ syntax(
1038
+ "Set pointers.apiKey using '-' and piped stdin; never put the key in command-line arguments.",
1039
+ );
1040
+ } else
1041
+ parseValue(configKey(result.positional[0]), result.positional[1], true);
1042
+ }
748
1043
  }
749
1044
  if (typeof result.options.limit === "string")
750
1045
  parseValue("history.limit", result.options.limit, true);
@@ -795,17 +1090,285 @@ async function performCli(
795
1090
  );
796
1091
  return 0;
797
1092
  }
798
- const items = effectiveConfig(state.config(), parsed.flags, env);
1093
+ const items = effectiveConfig(
1094
+ state.config(),
1095
+ parsed.flags,
1096
+ env,
1097
+ (reference) => state!.resolveSwarm(reference),
1098
+ );
799
1099
  const value = (key: string) =>
800
1100
  items.find((item) => item.key === key)!.value;
801
1101
  const emit = (result: unknown, human: string) => {
802
1102
  io.out(parsed.flags.json ? JSON.stringify(result) : human);
803
1103
  };
804
1104
  const [first, second] = parsed.positional;
1105
+ const selectedSwarm =
1106
+ value("swarm.default") === null
1107
+ ? undefined
1108
+ : String(value("swarm.default"));
1109
+ const swarmContext = (): SwarmContext => ({
1110
+ store: store!,
1111
+ state: state!,
1112
+ env,
1113
+ stateDir: stateLocation(parsed.flags, env).path,
1114
+ provider: String(value("swarm.provider") ?? "http://127.0.0.1:5001"),
1115
+ cacheTtl: Number(value("swarm.cacheTtl")),
1116
+ forceRefresh: parsed.options.force
1117
+ ? true
1118
+ : parsed.options["no-force"]
1119
+ ? false
1120
+ : Boolean(value("swarm.forceRefresh")),
1121
+ diagnostic: (text) => {
1122
+ io.err(text);
1123
+ },
1124
+ ...(typeof value("pointers.service") === "string"
1125
+ ? { pointerService: String(value("pointers.service")) }
1126
+ : {}),
1127
+ ...(typeof value("pointers.apiKey") === "string"
1128
+ ? { pointerApiKey: String(value("pointers.apiKey")) }
1129
+ : {}),
1130
+ });
805
1131
  const filter = parsed.path.startsWith("history ")
806
1132
  ? filters(state, parsed.options)
807
1133
  : {};
1134
+ const selection = () => {
1135
+ const current = effectiveConfig(
1136
+ state!.config(),
1137
+ parsed.flags,
1138
+ env,
1139
+ (reference) => state!.resolveSwarm(reference),
1140
+ ).find((item) => item.key === "swarm.default")!;
1141
+ return {
1142
+ savedCurrent: state!.config()["swarm.default"] ?? null,
1143
+ effectiveCurrent: current.value,
1144
+ source: current.source,
1145
+ };
1146
+ };
808
1147
  switch (parsed.path) {
1148
+ case "swarm list": {
1149
+ const result = { swarms: state.swarms(), ...selection() };
1150
+ emit(
1151
+ result,
1152
+ [
1153
+ ...result.swarms.map(
1154
+ (entry) =>
1155
+ `${entry.cid === result.savedCurrent ? "*" : " "} ${printable(entry.alias ?? entry.cid)} ${entry.cid}`,
1156
+ ),
1157
+ `Saved current: ${result.savedCurrent ?? "(none)"}`,
1158
+ `Effective current: ${result.effectiveCurrent ?? "(none)"} (${result.source})`,
1159
+ ].join("\n"),
1160
+ );
1161
+ break;
1162
+ }
1163
+ case "swarm use": {
1164
+ state.useSwarm(first!);
1165
+ const result = selection();
1166
+ emit(result, `Saved current swarm: ${result.savedCurrent}`);
1167
+ if (result.source === "flag" || result.source === "env")
1168
+ io.err(
1169
+ `The saved default is overridden by ${result.source}: ${result.effectiveCurrent}.`,
1170
+ );
1171
+ break;
1172
+ }
1173
+ case "swarm remove": {
1174
+ const removed = state.removeSwarm(first!);
1175
+ emit(
1176
+ { removed, savedCurrent: state.config()["swarm.default"] ?? null },
1177
+ `Removed registration ${removed}. Credentials, content and remote membership are unchanged.`,
1178
+ );
1179
+ break;
1180
+ }
1181
+ case "swarm add":
1182
+ case "swarm update":
1183
+ case "search":
1184
+ case "swarm create":
1185
+ case "swarm request":
1186
+ case "swarm approve":
1187
+ case "swarm join":
1188
+ case "swarm status":
1189
+ case "publish":
1190
+ case "get": {
1191
+ store = new IpfsStore(await storeConfiguration(value("store.gateway")));
1192
+ const context = swarmContext();
1193
+ if (parsed.path === "swarm update") {
1194
+ const cid = first ? state.resolveSwarm(first) : selectedSwarm;
1195
+ if (!cid)
1196
+ syntax(
1197
+ "swarm update requires a registered alias, Swarm CID or current swarm.",
1198
+ );
1199
+ const result = await updateSwarm(context, cid, {
1200
+ ...(typeof parsed.options.name === "string"
1201
+ ? { name: parsed.options.name }
1202
+ : {}),
1203
+ ...(typeof parsed.options.description === "string"
1204
+ ? { description: parsed.options.description }
1205
+ : {}),
1206
+ });
1207
+ emit(
1208
+ result,
1209
+ `Swarm: ${result.cid}\nName: ${printable(result.properties.name)}\nDescription: ${printable(result.properties.description)}\nHEAD: ${result.root}\nRevision: ${result.revision}`,
1210
+ );
1211
+ break;
1212
+ }
1213
+ if (parsed.path === "swarm add") {
1214
+ const cid = exactCid(first!);
1215
+ await addSwarm(
1216
+ context,
1217
+ cid,
1218
+ typeof parsed.options.alias === "string"
1219
+ ? parsed.options.alias
1220
+ : undefined,
1221
+ );
1222
+ const entry = state.registeredSwarm(cid);
1223
+ emit(
1224
+ { ...entry, savedCurrent: state.config()["swarm.default"] ?? null },
1225
+ `Registered swarm ${entry.alias ?? cid} (${cid}).`,
1226
+ );
1227
+ break;
1228
+ }
1229
+ if (parsed.path === "search") {
1230
+ const source = items.find(
1231
+ (item) => item.key === "swarm.default",
1232
+ )!.source;
1233
+ const limited = parsed.options.current || source === "flag";
1234
+ if (limited && !selectedSwarm)
1235
+ syntax(
1236
+ "Search of the current swarm requires --swarm or swarm.default.",
1237
+ );
1238
+ const registrations = state.swarms();
1239
+ const scope = limited
1240
+ ? [
1241
+ {
1242
+ cid: selectedSwarm!,
1243
+ alias:
1244
+ registrations.find((entry) => entry.cid === selectedSwarm)
1245
+ ?.alias ?? null,
1246
+ },
1247
+ ]
1248
+ : registrations;
1249
+ const result = await searchNames(context, first!, scope);
1250
+ emit(
1251
+ result,
1252
+ result.matches.length
1253
+ ? result.matches
1254
+ .map(
1255
+ (match) =>
1256
+ `${printable(match.alias ?? match.swarm)} ${printable(match.name)} ${match.targetCid}\n ipab get ${printable(match.reference)}`,
1257
+ )
1258
+ .join("\n")
1259
+ : "No matching Names.",
1260
+ );
1261
+ break;
1262
+ }
1263
+ if (parsed.path === "swarm status") {
1264
+ const cid = first ? state.resolveSwarm(first) : selectedSwarm;
1265
+ if (!cid)
1266
+ syntax("swarm status requires a Swarm CID or swarm.default.");
1267
+ const data = await descriptor(store, cid);
1268
+ const { head, snapshot } = await swarmHeader(context, cid, true);
1269
+ emit(
1270
+ {
1271
+ cid,
1272
+ ...data,
1273
+ root: head.root,
1274
+ revision: head.revision,
1275
+ properties: snapshot.properties,
1276
+ },
1277
+ `Swarm: ${cid}\nName: ${printable(snapshot.properties.name)}\nDescription: ${printable(snapshot.properties.description)}\nHEAD: ${head.root}\nRevision: ${head.revision}`,
1278
+ );
1279
+ break;
1280
+ }
1281
+ if (parsed.path === "get") {
1282
+ const selected = await resolveReference(
1283
+ context,
1284
+ first!,
1285
+ selectedSwarm,
1286
+ (reference) => state!.resolve(reference),
1287
+ Boolean(parsed.options.raw),
1288
+ );
1289
+ const directory = await getBundle(
1290
+ store,
1291
+ selected.cid,
1292
+ typeof parsed.options.output === "string"
1293
+ ? parsed.options.output
1294
+ : undefined,
1295
+ );
1296
+ emit(
1297
+ { ...selected, directory },
1298
+ `CID: ${selected.cid}\nTarget CID: ${selected.targetCid}\nDirectory: ${directory}`,
1299
+ );
1300
+ break;
1301
+ }
1302
+ let cid: string;
1303
+ if (parsed.path === "swarm create") {
1304
+ cid = await createSwarm(context, {
1305
+ ...(typeof parsed.options.service === "string"
1306
+ ? { service: parsed.options.service }
1307
+ : {}),
1308
+ ...(typeof parsed.options.resume === "string"
1309
+ ? { resume: parsed.options.resume }
1310
+ : {}),
1311
+ properties: {
1312
+ name: String(parsed.options.name ?? ""),
1313
+ description: String(parsed.options.description ?? ""),
1314
+ },
1315
+ ...(typeof parsed.options.alias === "string"
1316
+ ? { alias: parsed.options.alias }
1317
+ : {}),
1318
+ });
1319
+ } else if (parsed.path === "swarm request")
1320
+ cid = await requestMembership(context, exactCid(first!));
1321
+ else if (parsed.path === "swarm approve") {
1322
+ if (
1323
+ !parsed.options.yes &&
1324
+ (!io.tty ||
1325
+ !(await io.confirm(
1326
+ `Approve membership request ${first!}? This grants swarm HEAD read/write access.`,
1327
+ )))
1328
+ )
1329
+ throw new HostError(
1330
+ "Approval requires explicit --yes or interactive confirmation.",
1331
+ );
1332
+ cid = await approveMembership(
1333
+ context,
1334
+ exactCid(first!),
1335
+ parsed.options["expires-in"] === undefined
1336
+ ? undefined
1337
+ : Number(parsed.options["expires-in"]),
1338
+ );
1339
+ } else if (parsed.path === "swarm join")
1340
+ cid = await joinSwarm(
1341
+ context,
1342
+ exactCid(first!),
1343
+ typeof parsed.options.alias === "string"
1344
+ ? parsed.options.alias
1345
+ : undefined,
1346
+ );
1347
+ else {
1348
+ let content: string;
1349
+ if (first!.toLowerCase().endsWith(".car"))
1350
+ content = (
1351
+ await importBundle(first!, () => Promise.resolve(store!))
1352
+ ).cid;
1353
+ else content = exactCid(first!);
1354
+ cid = await publish(context, content, {
1355
+ ...(selectedSwarm ? { swarm: selectedSwarm } : {}),
1356
+ ...(typeof parsed.options.name === "string"
1357
+ ? { name: parsed.options.name }
1358
+ : {}),
1359
+ ...(typeof parsed.options.expect === "string"
1360
+ ? { expect: parsed.options.expect }
1361
+ : {}),
1362
+ snapshot: Boolean(parsed.options.snapshot),
1363
+ });
1364
+ }
1365
+ if (parsed.path === "swarm create" || parsed.path === "swarm join")
1366
+ io.err(
1367
+ `Registered swarm ${state.registeredSwarm(cid).alias ?? cid}. Saved current: ${state.config()["swarm.default"] ?? "(none)"}.`,
1368
+ );
1369
+ emit({ cid }, cid);
1370
+ break;
1371
+ }
809
1372
  case "store usage":
810
1373
  case "store gc": {
811
1374
  store = new IpfsStore(await storeConfiguration(value("store.gateway")));
@@ -872,7 +1435,7 @@ async function performCli(
872
1435
  if (parsed.path === "bundle build" || parsed.path === "build")
873
1436
  io.err(
874
1437
  parsed.path === "build"
875
- ? "Typechecking, bundling and building App..."
1438
+ ? "Assembling and validating Bundle (no compilation)..."
876
1439
  : "Validating and building bundle...",
877
1440
  );
878
1441
  if (parsed.path === "bundle import")
@@ -895,14 +1458,9 @@ async function performCli(
895
1458
  : {}),
896
1459
  })
897
1460
  : parsed.path === "build"
898
- ? await buildApp(first, {
1461
+ ? await assembleBundle(first, {
899
1462
  ...request,
900
1463
  replace: Boolean(parsed.options.replace),
901
- ...(parsed.options["with-source"]
902
- ? { includeSource: true }
903
- : parsed.options["without-source"]
904
- ? { includeSource: false }
905
- : {}),
906
1464
  ...(typeof parsed.options.output === "string"
907
1465
  ? { output: parsed.options.output }
908
1466
  : {}),
@@ -944,7 +1502,7 @@ async function performCli(
944
1502
  if ("output" in result)
945
1503
  emit(
946
1504
  { ...result, imported: importing },
947
- `CID: ${result.cid}\nSchema CID: ${result.schemaCid}\nCAR: ${result.output}${result.validation !== undefined ? `\nEntry validation: ${result.validation?.status ?? "not-applicable"}` : ""}${"source" in result ? `\nSource CID: ${result.source.cid}\nSource CAR: ${result.source.output} (not imported or pinned)` : ""}\nStore: ${importing ? "imported (not pinned)" : "not imported (--no-import)"}`,
1505
+ `CID: ${result.cid}\nSchema CID: ${result.schemaCid}\nCAR: ${result.output}${result.validation !== undefined ? `\nEntry validation: ${result.validation?.status ?? "not-applicable"}` : ""}\nStore: ${importing ? "imported (not pinned)" : "not imported (--no-import)"}`,
948
1506
  );
949
1507
  else if (result.kind === "bundle-import")
950
1508
  emit(
@@ -962,7 +1520,7 @@ async function performCli(
962
1520
  result.files.includes("ipab.json"))
963
1521
  )
964
1522
  io.err(
965
- `Next: install declared dependencies in ${JSON.stringify(result.directory)}; then ipab build ${JSON.stringify(result.directory)} (requires locally linked ipab).`,
1523
+ `Next: install declared dependencies and explicitly link the candidate @ipab/cli as a project dependency in ${JSON.stringify(result.directory)}; run pnpm build to prepare and package the App. Root ipab build does not compile.`,
966
1524
  );
967
1525
  else if (result.files.includes(".bundle.yaml"))
968
1526
  io.err(
@@ -1113,9 +1671,9 @@ async function performCli(
1113
1671
  break;
1114
1672
  }
1115
1673
  case "config get": {
1116
- const selected = first
1117
- ? items.filter((item) => item.key === first)
1118
- : items;
1674
+ const selected = (
1675
+ first ? items.filter((item) => item.key === first) : items
1676
+ ).map(visibleConfig);
1119
1677
  emit(
1120
1678
  { items: selected },
1121
1679
  table(
@@ -1128,14 +1686,21 @@ async function performCli(
1128
1686
  }
1129
1687
  case "config set": {
1130
1688
  const key = configKey(first!);
1131
- const saved = parseValue(key, second, true);
1689
+ const saved = parseValue(
1690
+ key,
1691
+ key === "pointers.apiKey"
1692
+ ? await (io.readSecret ?? processIO.readSecret!)()
1693
+ : second,
1694
+ true,
1695
+ );
1132
1696
  state.setConfig(key, saved);
1133
1697
  const source = items.find((item) => item.key === key)!.source;
1134
1698
  if (source === "env" || source === "flag")
1135
1699
  io.err(`Warning: saved user value is masked by ${source}.`);
1700
+ const display = visibleConfig({ key, value: saved, source: "user" });
1136
1701
  emit(
1137
- { key, value: saved, source: "user" },
1138
- `Saved ${key} = ${printable(String(saved))} (user).`,
1702
+ display,
1703
+ `Saved ${key} = ${printable(String(display.value))} (user).`,
1139
1704
  );
1140
1705
  break;
1141
1706
  }
@@ -1234,9 +1799,17 @@ async function performCli(
1234
1799
  throw new HostError(
1235
1800
  "Execution logging requires history.enabled=true.",
1236
1801
  );
1237
- const target = state.resolve(first!);
1238
1802
  await recoverInactive(state);
1239
1803
  store = new IpfsStore(await storeConfiguration(value("store.gateway")));
1804
+ const target = (
1805
+ await resolveReference(
1806
+ swarmContext(),
1807
+ first!,
1808
+ selectedSwarm,
1809
+ (reference) => state!.resolve(reference),
1810
+ Boolean(parsed.options.raw),
1811
+ )
1812
+ ).cid;
1240
1813
  let appCid: string;
1241
1814
  let appArgv: string[];
1242
1815
  if (parsed.path === "open") {