@ipab/cli 0.1.0-rc.13 → 0.1.0-rc.15

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 (44) hide show
  1. package/dist/authoring.d.ts +3 -1
  2. package/dist/authoring.d.ts.map +1 -1
  3. package/dist/authoring.js +14 -2
  4. package/dist/authoring.js.map +1 -1
  5. package/dist/builtins/skill.ipab.car +0 -0
  6. package/dist/cli.d.ts.map +1 -1
  7. package/dist/cli.js +62 -45
  8. package/dist/cli.js.map +1 -1
  9. package/dist/daemon-api.d.ts.map +1 -1
  10. package/dist/daemon-api.js +59 -19
  11. package/dist/daemon-api.js.map +1 -1
  12. package/dist/daemon-client.d.ts +67 -20
  13. package/dist/daemon-client.d.ts.map +1 -1
  14. package/dist/daemon-client.js.map +1 -1
  15. package/dist/publish-source.d.ts +8 -1
  16. package/dist/publish-source.d.ts.map +1 -1
  17. package/dist/publish-source.js +71 -13
  18. package/dist/publish-source.js.map +1 -1
  19. package/dist/swarm-fs-core.d.ts +7 -2
  20. package/dist/swarm-fs-core.d.ts.map +1 -1
  21. package/dist/swarm-fs-core.js +30 -4
  22. package/dist/swarm-fs-core.js.map +1 -1
  23. package/dist/swarm.d.ts +21 -1
  24. package/dist/swarm.d.ts.map +1 -1
  25. package/dist/swarm.js +203 -69
  26. package/dist/swarm.js.map +1 -1
  27. package/dist/templates.d.ts +2 -1
  28. package/dist/templates.d.ts.map +1 -1
  29. package/dist/templates.js +11 -2
  30. package/dist/templates.js.map +1 -1
  31. package/dist/unixfs-tree.d.ts +1 -1
  32. package/dist/unixfs-tree.d.ts.map +1 -1
  33. package/dist/unixfs-tree.js +5 -2
  34. package/dist/unixfs-tree.js.map +1 -1
  35. package/package.json +1 -1
  36. package/src/authoring.ts +21 -9
  37. package/src/cli.ts +67 -49
  38. package/src/daemon-api.ts +74 -20
  39. package/src/daemon-client.ts +62 -22
  40. package/src/publish-source.ts +98 -12
  41. package/src/swarm-fs-core.ts +47 -3
  42. package/src/swarm.ts +310 -87
  43. package/src/templates.ts +16 -1
  44. package/src/unixfs-tree.ts +3 -1
package/src/swarm.ts CHANGED
@@ -3,7 +3,7 @@ import { lstat, mkdir, open } from "node:fs/promises";
3
3
  import { homedir } from "node:os";
4
4
  import { join, resolve } from "node:path";
5
5
  import { setTimeout as delay } from "node:timers/promises";
6
- import { createHash, randomBytes } from "node:crypto";
6
+ import { createHash, randomBytes, randomUUID } from "node:crypto";
7
7
  import { stringify } from "yaml";
8
8
  import { CarBlockIterator } from "@ipld/car/iterator";
9
9
  import * as dagCbor from "@ipld/dag-cbor";
@@ -21,7 +21,14 @@ import {
21
21
  memoryTree,
22
22
  streamChunks,
23
23
  } from "@ipab/bundle-builder";
24
- import { ContentError, GatewayReadError, IpfsStore } from "@ipab/ipfs-store";
24
+ import {
25
+ ContentError,
26
+ GatewayReadError,
27
+ IpfsStore,
28
+ type StagedBlock,
29
+ } from "@ipab/ipfs-store";
30
+ import { Ownership } from "./history.js";
31
+ import { publicationSource } from "./publish-source.js";
25
32
  import {
26
33
  ScopeClient,
27
34
  ScopeApiError,
@@ -3410,7 +3417,7 @@ export async function writeNamesHead(
3410
3417
  return head.write(root, cid, uniqueId());
3411
3418
  }
3412
3419
  const idempotencyKey = uniqueId();
3413
- let receipt: ScopeWriteReceipt | null;
3420
+ let receipt: ScopeWriteReceipt;
3414
3421
  try {
3415
3422
  receipt = await requestPivotWriteReceipt(
3416
3423
  context,
@@ -3427,9 +3434,6 @@ export async function writeNamesHead(
3427
3434
  "publication",
3428
3435
  );
3429
3436
  }
3430
- if (receipt === null) {
3431
- return head.write(root, cid, idempotencyKey);
3432
- }
3433
3437
  return head.writeWithReceipt(receipt);
3434
3438
  });
3435
3439
  }
@@ -3440,7 +3444,7 @@ async function requestPivotWriteReceipt(
3440
3444
  root: string,
3441
3445
  ifCid: string,
3442
3446
  idempotencyKey: string,
3443
- ): Promise<ScopeWriteReceipt | null> {
3447
+ ): Promise<ScopeWriteReceipt> {
3444
3448
  const record = await approvedMembership(context, url);
3445
3449
  const config = record.config!;
3446
3450
  const identity = await contextIdentity(context);
@@ -3450,26 +3454,21 @@ async function requestPivotWriteReceipt(
3450
3454
  );
3451
3455
  if (!pivots.length)
3452
3456
  throw new HostError(
3453
- "No Pivot nodes are declared. Declare an independent member with swarm profile --pivot true before publishing; HEAD was not changed.",
3457
+ "No Pivot nodes are declared. Declare an authorized Pivot with swarm profile --pivot true before publishing; HEAD was not changed.",
3454
3458
  );
3459
+ const self = pivots.find(
3460
+ ({ member }) =>
3461
+ member.publicKey === record.account &&
3462
+ (record.account === config.owner ||
3463
+ record.secret?.certificate.body.write.includes(config.headId)),
3464
+ );
3455
3465
  const remote = pivots.filter(
3456
3466
  ({ member }) => member.publicKey !== record.account,
3457
3467
  );
3458
- if (!remote.length) {
3459
- if (
3460
- members.length === 1 &&
3461
- members[0]!.member.publicKey === record.account &&
3462
- record.account === config.owner
3463
- ) {
3464
- context.diagnostic?.(
3465
- `[${url}] Solo self-Pivot Swarm detected; publishing ${root} directly without remote Pivot receipt.`,
3466
- );
3467
- return null;
3468
- }
3468
+ if (!self && !remote.length)
3469
3469
  throw new HostError(
3470
- "Publication requires an independent Pivot node. Declare another member with swarm profile --pivot true; HEAD was not changed.",
3470
+ "Publication requires an authorized Pivot. Ask the Owner to grant Pivot HEAD authority; HEAD was not changed.",
3471
3471
  );
3472
- }
3473
3472
  const authorized = remote.filter(
3474
3473
  ({ member }) =>
3475
3474
  member.publicKey === config.owner ||
@@ -3477,7 +3476,7 @@ async function requestPivotWriteReceipt(
3477
3476
  ? member.role === "pivot"
3478
3477
  : member.pivotAuthority === true),
3479
3478
  );
3480
- const candidates = authorized.length
3479
+ const remoteCandidates = authorized.length
3481
3480
  ? [
3482
3481
  ...authorized,
3483
3482
  ...remote.filter(
@@ -3488,6 +3487,7 @@ async function requestPivotWriteReceipt(
3488
3487
  ),
3489
3488
  ]
3490
3489
  : remote;
3490
+ const candidates = self ? [self, ...remoteCandidates] : remoteCandidates;
3491
3491
  if (!context.requestPivotReceipt && !context.node)
3492
3492
  throw new HostError("State pin requires an active publishing node.");
3493
3493
  const c = coordinates(url);
@@ -3513,16 +3513,19 @@ async function requestPivotWriteReceipt(
3513
3513
  const errors: string[] = [];
3514
3514
  for (const pivot of candidates) {
3515
3515
  try {
3516
- const receipt = context.requestPivotReceipt
3517
- ? await context.requestPivotReceipt(pivot, request, signal)
3518
- : await requestPivotReceiptOverP2p(
3519
- context.node!,
3520
- pivot.member.peerId,
3521
- pivot.profile.addresses,
3522
- request,
3523
- signal,
3524
- context.fetch,
3525
- );
3516
+ const local = pivot === self;
3517
+ const receipt = local
3518
+ ? await handlePivotReceiptRequest(context, url, request, signal)
3519
+ : context.requestPivotReceipt
3520
+ ? await context.requestPivotReceipt(pivot, request, signal)
3521
+ : await requestPivotReceiptOverP2p(
3522
+ context.node!,
3523
+ pivot.member.peerId,
3524
+ pivot.profile.addresses,
3525
+ request,
3526
+ signal,
3527
+ context.fetch,
3528
+ );
3526
3529
  if (
3527
3530
  JSON.stringify(receipt.value) !== JSON.stringify({ root }) ||
3528
3531
  receipt.ifCid !== ifCid ||
@@ -3533,7 +3536,7 @@ async function requestPivotWriteReceipt(
3533
3536
  `Pivot ${pivot.member.publicKey} returned a receipt that does not match this publication.`,
3534
3537
  );
3535
3538
  context.diagnostic?.(
3536
- `[${url}] Received HEAD write receipt from Pivot ${pivot.profile.name} (${pivot.member.publicKey}).`,
3539
+ `[${url}] Received HEAD write receipt from ${local ? "local" : "remote"} Pivot ${pivot.profile.name} (${pivot.member.publicKey})${local ? "; no independent replica is confirmed" : ""}.`,
3537
3540
  );
3538
3541
  return receipt;
3539
3542
  } catch (cause) {
@@ -3545,7 +3548,7 @@ async function requestPivotWriteReceipt(
3545
3548
  }
3546
3549
  }
3547
3550
  throw new HostError(
3548
- `No authorized independent Pivot issued a HEAD write receipt for publication ${root} (${errors.join("; ")}); HEAD was not changed.`,
3551
+ `No authorized Pivot issued a HEAD write receipt for publication ${root} (${errors.join("; ")}); HEAD was not changed.`,
3549
3552
  );
3550
3553
  }
3551
3554
 
@@ -3608,7 +3611,7 @@ export async function handlePivotReceiptRequest(
3608
3611
  );
3609
3612
  try {
3610
3613
  if (CID.parse(request.root).code === dagPb.code) {
3611
- if (peers.length > 0)
3614
+ if (peers.length > 0 && member.peerId !== node.peerId)
3612
3615
  await probePeer(node, member.peerId, peers, signal).catch(() => false);
3613
3616
  await readSnapshot(source, request.root, url);
3614
3617
  await pinPublication(source, [request.root], node, signal, context.fetch);
@@ -4183,6 +4186,7 @@ export async function jsonBundle(
4183
4186
  store: IpfsStore,
4184
4187
  type: BundleType,
4185
4188
  value: unknown,
4189
+ operation?: PublicationOperation,
4186
4190
  ): Promise<string> {
4187
4191
  const encoded = await encodeBundleCar(
4188
4192
  memoryTree(
@@ -4206,7 +4210,25 @@ export async function jsonBundle(
4206
4210
  const iterator = await CarBlockIterator.fromIterable(
4207
4211
  streamChunks(encoded.stream),
4208
4212
  );
4209
- for await (const block of iterator) await store.put(block.cid, block.bytes);
4213
+ const blocks: StagedBlock[] = [];
4214
+ for await (const block of iterator) {
4215
+ operation?.signal?.throwIfAborted();
4216
+ if (operation) blocks.push({ cid: block.cid, bytes: block.bytes });
4217
+ else await store.put(block.cid, block.bytes);
4218
+ }
4219
+ if (operation) {
4220
+ try {
4221
+ return await operation.owner.importBlocks(
4222
+ operation.session,
4223
+ blocks,
4224
+ encoded.cid,
4225
+ operation.signal ? { signal: operation.signal } : {},
4226
+ );
4227
+ } catch (cause) {
4228
+ operation.recoveryRequired = true;
4229
+ throw cause;
4230
+ }
4231
+ }
4210
4232
  return encoded.cid.toString();
4211
4233
  } finally {
4212
4234
  await encoded.close();
@@ -7034,7 +7056,7 @@ export async function swarmMeta(
7034
7056
  const cid = header.snapshot.names.ipab;
7035
7057
  if (!cid)
7036
7058
  throw new HostError(
7037
- 'Swarm Meta Name "ipab" is missing. Create a new seeded Swarm or explicitly publish a typed Swarm Meta Bundle; existing Swarms are never automatically upgraded.',
7059
+ 'Swarm Meta Name "ipab" is missing. Create a new seeded v7 Swarm and explicitly transfer reviewed paths; legacy Swarms are never automatically upgraded.',
7038
7060
  );
7039
7061
  try {
7040
7062
  const bundle = await openBundle(cid, {
@@ -7047,7 +7069,7 @@ export async function swarmMeta(
7047
7069
  return parseSwarmMeta(await typedJson(context.store, cid.toString(), type));
7048
7070
  } catch (cause) {
7049
7071
  throw new HostError(
7050
- `Invalid Swarm Meta at Name "ipab": ${message(cause)}. Publish a valid typed Meta Bundle explicitly; no builtin or legacy fallback is used.`,
7072
+ `Invalid Swarm Meta at Name "ipab": ${message(cause)}. Legacy consumers require a direct typed Meta, not a versioned Artifact. Create a new seeded v7 Swarm and explicitly transfer reviewed paths; no builtin or legacy fallback is used.`,
7051
7073
  );
7052
7074
  }
7053
7075
  }
@@ -7150,7 +7172,7 @@ function missingSkillPathError(snapshot: Snapshot): HostError {
7150
7172
  return new HostError(
7151
7173
  snapshot.stateBundle
7152
7174
  ? "This Swarm uses the earlier exact State Bundle type without skillPath. There is no in-place root-configuration migration command. Create a new seeded Swarm and explicitly republish reviewed Names. Publishing a user Name ipab never overrides root configuration; upgrades never rewrite it."
7153
- : `This Swarm uses the legacy exact Meta type without skillPath. Explicitly build and publish a new typed Meta Bundle with templatePath and registryPath preserved and skillPath chosen, then run ipab publish ipab META_SOURCE --expect ${metaCid(snapshot)}. Upgrades never overwrite Meta.`,
7175
+ : "This Swarm uses the legacy exact Meta type without skillPath. Publish now creates an Artifact and cannot migrate direct Meta; create a new seeded v7 Swarm and explicitly transfer reviewed paths. Existing Meta is never overwritten automatically.",
7154
7176
  );
7155
7177
  }
7156
7178
 
@@ -7955,37 +7977,44 @@ export async function setSwarmTemplate(
7955
7977
  ) {
7956
7978
  templateName(selector);
7957
7979
  await swarmFsTransport.pointer(context, configUrl);
7958
- const content = await templatePublicationSource(source, context.store);
7959
- const details = await inspectTemplate(context.store, content);
7960
- let location:
7961
- { name: string; templatePath: string; metaCid: string } | undefined;
7962
- const targetCid = await publishContent(
7963
- context,
7964
- content,
7965
- {
7980
+ return withPublicationOperation(context, async (operation) => {
7981
+ const content = await templatePublicationSource(
7982
+ source,
7983
+ context.store,
7984
+ operation,
7985
+ );
7986
+ const details = await inspectTemplate(context.store, content);
7987
+ let location:
7988
+ { name: string; templatePath: string; metaCid: string } | undefined;
7989
+ const targetCid = await publishContent(
7990
+ context,
7991
+ content,
7992
+ {
7993
+ swarm: configUrl,
7994
+ name: selector,
7995
+ operation,
7996
+ ...(expect === undefined ? {} : { expect }),
7997
+ },
7998
+ async (current) => {
7999
+ const meta = await swarmMeta(context, { snapshot: current });
8000
+ const name = formalName(`${meta.templatePath}/${selector}`);
8001
+ location = {
8002
+ name,
8003
+ templatePath: meta.templatePath,
8004
+ metaCid: metaCid(current),
8005
+ };
8006
+ return name;
8007
+ },
8008
+ );
8009
+ return {
7966
8010
  swarm: configUrl,
7967
- name: selector,
7968
- ...(expect === undefined ? {} : { expect }),
7969
- },
7970
- async (current) => {
7971
- const meta = await swarmMeta(context, { snapshot: current });
7972
- const name = formalName(`${meta.templatePath}/${selector}`);
7973
- location = {
7974
- name,
7975
- templatePath: meta.templatePath,
7976
- metaCid: metaCid(current),
7977
- };
7978
- return name;
7979
- },
7980
- );
7981
- return {
7982
- swarm: configUrl,
7983
- ...location!,
7984
- selector,
7985
- reference: formatNameReference(configUrl, location!.name),
7986
- targetCid,
7987
- ...details,
7988
- };
8011
+ ...location!,
8012
+ selector,
8013
+ reference: formatNameReference(configUrl, location!.name),
8014
+ targetCid,
8015
+ ...details,
8016
+ };
8017
+ });
7989
8018
  }
7990
8019
  export async function removeSwarmTemplate(
7991
8020
  context: SwarmContext,
@@ -8409,10 +8438,173 @@ export async function publish(
8409
8438
  name: string;
8410
8439
  expect?: string;
8411
8440
  snapshot?: boolean;
8441
+ operation?: PublicationOperation;
8412
8442
  },
8413
8443
  ): Promise<string> {
8414
- return publishContent(context, content, options);
8444
+ if (options.snapshot !== undefined)
8445
+ syntax(
8446
+ "--snapshot was removed. For a direct binding use ipab fs set NAME --source SOURCE [--expect OLD_CID].",
8447
+ );
8448
+ if (options.operation)
8449
+ return publishContent(context, content, {
8450
+ ...options,
8451
+ operation: options.operation,
8452
+ });
8453
+ if (!options.swarm)
8454
+ throw new HostError(
8455
+ "Publication requires a selected Swarm configuration URL or alias.",
8456
+ );
8457
+ await swarmFsTransport.pointer(context, options.swarm);
8458
+ return withPublicationOperation(context, (operation) =>
8459
+ publishContent(context, content, { ...options, operation }),
8460
+ );
8461
+ }
8462
+
8463
+ export interface PublicationOperation {
8464
+ owner: Ownership;
8465
+ session: string;
8466
+ signal?: AbortSignal;
8467
+ recoveryRequired?: boolean;
8468
+ completedCid?: string;
8415
8469
  }
8470
+
8471
+ async function withPublicationOperation<T>(
8472
+ context: SwarmContext,
8473
+ action: (operation: PublicationOperation) => Promise<T>,
8474
+ signal?: AbortSignal,
8475
+ ): Promise<T> {
8476
+ const session = `publication:${randomUUID()}`;
8477
+ const state = context.state ?? new State(context.stateDir);
8478
+ let operation: PublicationOperation | undefined;
8479
+ let result: T;
8480
+ let cleanupError: HostError | undefined;
8481
+ let failed = false;
8482
+ try {
8483
+ const owner = await Ownership.create(
8484
+ state,
8485
+ context.store,
8486
+ session,
8487
+ session,
8488
+ );
8489
+ operation = { owner, session, ...(signal ? { signal } : {}) };
8490
+ result = await action(operation);
8491
+ } catch (cause) {
8492
+ failed = true;
8493
+ throw cause;
8494
+ } finally {
8495
+ try {
8496
+ if (operation?.recoveryRequired) {
8497
+ const hold = state.hold(operation.owner.owner);
8498
+ if (hold) state.saveHold({ ...hold, pid: null });
8499
+ context.diagnostic?.(
8500
+ `Publication preparation failed; unfinished retention intent remains for recovery (${session}). HEAD was not submitted.`,
8501
+ );
8502
+ } else {
8503
+ try {
8504
+ await operation?.owner.release();
8505
+ } catch (cause) {
8506
+ if (!failed)
8507
+ cleanupError = new HostError(
8508
+ `Binding completed as ${operation?.completedCid ?? "(unknown target)"}, but temporary ownership cleanup failed: ${message(cause)}. Durable ownership was not released; inspect the target before retry.`,
8509
+ 1,
8510
+ "OPERATION_FAILED",
8511
+ "publication",
8512
+ );
8513
+ else
8514
+ context.diagnostic?.(
8515
+ `Temporary ownership cleanup also failed: ${message(cause)}.`,
8516
+ );
8517
+ }
8518
+ }
8519
+ } finally {
8520
+ if (!context.state) state.close();
8521
+ }
8522
+ }
8523
+ if (cleanupError) throw cleanupError;
8524
+ return result;
8525
+ }
8526
+
8527
+ async function retainPublicationRoots(
8528
+ operation: PublicationOperation,
8529
+ roots: string[],
8530
+ ) {
8531
+ try {
8532
+ await operation.owner.retain(roots, operation.signal);
8533
+ } catch (cause) {
8534
+ operation.recoveryRequired = true;
8535
+ throw cause;
8536
+ }
8537
+ }
8538
+
8539
+ export async function bindPublicationSource(
8540
+ context: SwarmContext,
8541
+ input: string,
8542
+ options: {
8543
+ swarm: string;
8544
+ name: string;
8545
+ kind: "fs" | "publish";
8546
+ expect?: string;
8547
+ replace?: boolean;
8548
+ signal?: AbortSignal;
8549
+ },
8550
+ ) {
8551
+ options.signal?.throwIfAborted();
8552
+ await swarmFsTransport.pointer(context, options.swarm);
8553
+ return withPublicationOperation(
8554
+ context,
8555
+ async (operation) => {
8556
+ const contentCid = await publicationSource(input, context.store, {
8557
+ owner: operation.owner,
8558
+ session: operation.session,
8559
+ options: options.signal ? { signal: options.signal } : {},
8560
+ onImportFailure: () => {
8561
+ operation.recoveryRequired = true;
8562
+ },
8563
+ });
8564
+ options.signal?.throwIfAborted();
8565
+ if (options.kind === "publish") {
8566
+ const cid = await publishContent(context, contentCid, {
8567
+ ...options,
8568
+ operation,
8569
+ });
8570
+ return { cid, contentCid };
8571
+ }
8572
+ const roots = await dependencies(context.store, contentCid);
8573
+ await retainPublicationRoots(operation, [...roots]);
8574
+ options.signal?.throwIfAborted();
8575
+ const currentRoots = await currentDependencies(context.store, contentCid);
8576
+ await withStateAsync(context, (state) =>
8577
+ pinCid(state, contentCid, context.store, [...currentRoots]),
8578
+ );
8579
+ options.signal?.throwIfAborted();
8580
+ const result = await swarmFs.setSwarmFsPath(
8581
+ context,
8582
+ options.swarm,
8583
+ options.name,
8584
+ contentCid,
8585
+ {
8586
+ ...(options.expect !== undefined ? { expect: options.expect } : {}),
8587
+ ...(options.replace !== undefined
8588
+ ? { replace: options.replace }
8589
+ : {}),
8590
+ ...(options.signal ? { signal: options.signal } : {}),
8591
+ recursiveRoots: [...currentRoots],
8592
+ writeBlock: (cid, bytes) =>
8593
+ context.store.stageBlock(
8594
+ operation.session,
8595
+ cid,
8596
+ bytes,
8597
+ options.signal ? { signal: options.signal } : {},
8598
+ ),
8599
+ },
8600
+ );
8601
+ operation.completedCid = result.cid;
8602
+ return result;
8603
+ },
8604
+ options.signal,
8605
+ );
8606
+ }
8607
+
8416
8608
  async function publishContent(
8417
8609
  context: SwarmContext,
8418
8610
  content: string,
@@ -8420,7 +8612,7 @@ async function publishContent(
8420
8612
  swarm?: string;
8421
8613
  name: string;
8422
8614
  expect?: string;
8423
- snapshot?: boolean;
8615
+ operation: PublicationOperation;
8424
8616
  },
8425
8617
  nameForSnapshot?: (current: Snapshot) => Promise<string>,
8426
8618
  ): Promise<string> {
@@ -8429,42 +8621,55 @@ async function publishContent(
8429
8621
  "Publication requires a selected Swarm configuration URL or alias.",
8430
8622
  );
8431
8623
  await swarmFsTransport.pointer(context, options.swarm);
8624
+ const operation = options.operation;
8625
+ operation.signal?.throwIfAborted();
8432
8626
  const roots = await dependencies(context.store, content);
8627
+ await retainPublicationRoots(operation, [...roots]);
8433
8628
  const currentRoots = [...(await currentDependencies(context.store, content))];
8629
+ operation.signal?.throwIfAborted();
8434
8630
  await withStateAsync(context, (state) =>
8435
8631
  pinCid(state, content, context.store, currentRoots),
8436
8632
  );
8437
8633
  let name = formalName(options.name);
8438
8634
  let resolvedName: string | undefined;
8439
- if (options.snapshot && options.expect)
8440
- throw new HostError("Snapshots cannot replace an occupied Name.");
8441
8635
  const expected = options.expect
8442
8636
  ? CID.parse(options.expect).toV1().toString()
8443
8637
  : undefined;
8444
8638
  const contentBundle = await openBundle(CID.parse(content), {
8445
8639
  resolveCid: (cid) => context.store.block.get(cid.toString()),
8446
8640
  });
8447
- const direct =
8641
+ const migration =
8448
8642
  contentBundle.schemaKey === appSchemaCid.toString() ||
8449
8643
  contentBundle.schemaKey === swarmMetaSchema.cid.toString() ||
8450
8644
  contentBundle.schemaKey === legacySwarmMetaSchema.cid.toString();
8451
- const candidate =
8452
- options.snapshot || direct
8453
- ? content
8454
- : await jsonBundle(context.store, artifactType, {
8455
- value: content,
8456
- ...(expected ? { previous: expected } : {}),
8457
- timestamp: new Date().toISOString(),
8458
- });
8645
+ if (migration)
8646
+ context.diagnostic?.(
8647
+ "Publish now creates an Artifact version; target CID will differ from content CID. For a direct binding use ipab fs set NAME --source SOURCE [--expect OLD_CID].",
8648
+ );
8649
+ const candidate = await jsonBundle(
8650
+ context.store,
8651
+ artifactType,
8652
+ {
8653
+ value: content,
8654
+ ...(expected ? { previous: expected } : {}),
8655
+ timestamp: new Date().toISOString(),
8656
+ },
8657
+ operation,
8658
+ );
8459
8659
  roots.add(candidate);
8460
- const expectedDeps = expected
8461
- ? await dependencies(context.store, expected)
8462
- : undefined;
8463
- if (expectedDeps) for (const root of expectedDeps) roots.add(root);
8464
- const retained = [candidate, ...(expectedDeps ?? [])];
8660
+ let previousPrepared = false;
8661
+ const retained = [candidate];
8465
8662
  const committed = await swarmFs.commitSwarmPaths(context, options.swarm, {
8466
8663
  allowLegacyNames: true,
8467
8664
  refreshAfterCommit: true,
8665
+ ...(operation.signal ? { signal: operation.signal } : {}),
8666
+ writeBlock: (cid, bytes) =>
8667
+ context.store.stageBlock(
8668
+ operation.session,
8669
+ cid,
8670
+ bytes,
8671
+ operation.signal ? { signal: operation.signal } : {},
8672
+ ),
8468
8673
  plan: async (planCtx) => {
8469
8674
  if (nameForSnapshot) {
8470
8675
  name = await nameForSnapshot(planCtx.snapshot);
@@ -8486,6 +8691,23 @@ async function publishContent(
8486
8691
  "EDIT_CONFLICT",
8487
8692
  "publication",
8488
8693
  );
8694
+ if (expected && !previousPrepared) {
8695
+ let expectedDeps: Set<string>;
8696
+ try {
8697
+ expectedDeps = await dependencies(context.store, expected);
8698
+ } catch (cause) {
8699
+ throw new HostError(
8700
+ `Cannot retain the exact previous Bundle ${expected}: ${message(cause)}. Manage non-Bundle targets with ipab fs set.`,
8701
+ 1,
8702
+ "INVALID_PREVIOUS",
8703
+ "publication",
8704
+ );
8705
+ }
8706
+ await retainPublicationRoots(operation, [...expectedDeps]);
8707
+ for (const root of expectedDeps) roots.add(root);
8708
+ retained.push(...expectedDeps);
8709
+ previousPrepared = true;
8710
+ }
8489
8711
  return {
8490
8712
  kind: "commit",
8491
8713
  operations: [
@@ -8504,5 +8726,6 @@ async function publishContent(
8504
8726
  headBusy: () => `HEAD is busy; candidate ${candidate} remains retained.`,
8505
8727
  },
8506
8728
  });
8729
+ operation.completedCid = committed.result;
8507
8730
  return committed.result;
8508
8731
  }
package/src/templates.ts CHANGED
@@ -5,6 +5,7 @@ import { bundleLimits, openBundle } from "@ipab/bundle";
5
5
  import type { IpfsStore } from "@ipab/ipfs-store";
6
6
  import { HostError } from "./errors.js";
7
7
  import { publicationSource } from "./publish-source.js";
8
+ import type { PublicationOperation } from "./swarm.js";
8
9
  import { bytes } from "./space.js";
9
10
  import {
10
11
  templateDefinition,
@@ -38,6 +39,7 @@ export async function inspectTemplate(store: IpfsStore, cid: string) {
38
39
  export async function templatePublicationSource(
39
40
  input: string,
40
41
  store: IpfsStore,
42
+ operation?: PublicationOperation,
41
43
  ) {
42
44
  let cid: CID | undefined;
43
45
  try {
@@ -71,7 +73,20 @@ export async function templatePublicationSource(
71
73
  );
72
74
  }
73
75
  }
74
- const content = await publicationSource(input, store);
76
+ const content = await publicationSource(
77
+ input,
78
+ store,
79
+ operation
80
+ ? {
81
+ owner: operation.owner,
82
+ session: operation.session,
83
+ options: operation.signal ? { signal: operation.signal } : {},
84
+ onImportFailure: () => {
85
+ operation.recoveryRequired = true;
86
+ },
87
+ }
88
+ : undefined,
89
+ );
75
90
  await inspectTemplate(store, content);
76
91
  return content;
77
92
  }
@@ -183,6 +183,7 @@ export async function applyUnixfsMutations(
183
183
  store: IpfsStore,
184
184
  rootCid: CID,
185
185
  mutations: readonly UnixfsMutation[],
186
+ writeBlock?: (cid: CID, bytes: Uint8Array) => Promise<void>,
186
187
  ): Promise<ApplyUnixfsMutationsResult> {
187
188
  const canonicalRoot = rootCid.toV1();
188
189
  if (mutations.length === 0) {
@@ -385,7 +386,8 @@ export async function applyUnixfsMutations(
385
386
 
386
387
  const encoded = await encodeUnixfsDirectory(node.links.values());
387
388
  if (!node.originalCid || !encoded.cid.equals(node.originalCid)) {
388
- await store.put(encoded.cid, encoded.bytes);
389
+ if (writeBlock) await writeBlock(encoded.cid, encoded.bytes);
390
+ else await store.put(encoded.cid, encoded.bytes);
389
391
  node.newlyWritten = true;
390
392
  node.encodedCid = encoded.cid;
391
393
  } else {