@seed-hypermedia/client 0.0.129 → 0.0.130

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.
@@ -45,13 +45,28 @@ async function resolveDocumentState(client, targetId) {
45
45
  if (d > maxHeadDepth) maxHeadDepth = d;
46
46
  }
47
47
  const version = heads.join(".");
48
+ let headTs = 0;
49
+ for (const change of changesResp.changes) {
50
+ if (!change.id || !heads.includes(change.id)) continue;
51
+ const ts = change.createTime ? Date.parse(change.createTime) : NaN;
52
+ if (!Number.isFinite(ts)) {
53
+ headTs = void 0;
54
+ break;
55
+ }
56
+ if (ts > headTs) headTs = ts;
57
+ }
48
58
  return {
49
59
  genesis,
50
60
  heads,
51
61
  headDepth: maxHeadDepth,
52
- version
62
+ version,
63
+ headTs
53
64
  };
54
65
  }
66
+ function sameDocumentVersion(a, b) {
67
+ const heads = (version) => (version ?? "").split(".").filter(Boolean).sort().join(".");
68
+ return heads(a) === heads(b);
69
+ }
55
70
  var MAX_REDIRECT_HOPS = 5;
56
71
  async function followRedirects(client, id) {
57
72
  const seen = /* @__PURE__ */ new Set([packHmId(id)]);
@@ -98,8 +113,12 @@ async function followToDocument(client, id) {
98
113
  };
99
114
  }
100
115
  async function resolveEditableDocument(client, id) {
101
- const followed = await followToDocument(client, id);
102
- const state = await resolveDocumentState(client, packHmId(followed.targetId));
116
+ let followed = await followToDocument(client, id);
117
+ let state = await resolveDocumentState(client, packHmId(followed.targetId));
118
+ if (!sameDocumentVersion(followed.document.version, state.version)) {
119
+ followed = await followToDocument(client, id);
120
+ state = await resolveDocumentState(client, packHmId(followed.targetId));
121
+ }
103
122
  return { ...followed, state };
104
123
  }
105
124
  function editRefGeneration(document, fresh, supersedesRedirect = false) {
@@ -158,6 +177,7 @@ function computeDepths(changesResp) {
158
177
 
159
178
  export {
160
179
  resolveDocumentState,
180
+ sameDocumentVersion,
161
181
  followRedirects,
162
182
  describeRedirect,
163
183
  followToDocument,
@@ -17,11 +17,20 @@ export type DocumentState = {
17
17
  headDepth: number;
18
18
  /** Dot-separated head CIDs (version string). */
19
19
  version: string;
20
+ /**
21
+ * The latest timestamp among the head changes, in milliseconds (a Change's `ts`). A Change built
22
+ * on these heads must be stamped later than this, whatever the local clock says: the daemon
23
+ * treats a Change that is not later than its dependencies as broken. Absent when the server
24
+ * did not report the heads' times.
25
+ */
26
+ headTs?: number;
20
27
  };
21
28
  /**
22
29
  * Resolves the current document state including head depth.
23
30
  */
24
31
  export declare function resolveDocumentState(client: Pick<SeedClient, 'request'>, targetId: string): Promise<DocumentState>;
32
+ /** Whether two version strings name the same heads, in any order. */
33
+ export declare function sameDocumentVersion(a: string | undefined, b: string | undefined): boolean;
25
34
  /** A document address resolved through redirects to the document it currently presents. */
26
35
  export type FollowedDocument = {
27
36
  /** The address that was resolved — where a new Ref should be published to affect this path. */
@@ -102,6 +111,10 @@ export declare function followToDocument(client: Pick<SeedClient, 'request'>, id
102
111
  * path has no changes of its own — `ListChanges` returns nothing for it) and publish a Version
103
112
  * Ref at the source path with a fresh generation, which supersedes the redirect Ref. Every other
104
113
  * edit keeps the document's generation: see {@link editRefGeneration}.
114
+ *
115
+ * `document` and `state` are read one after the other; when they name different versions both are
116
+ * read once more. Compare `document.version` with `state.version` ({@link sameDocumentVersion})
117
+ * to know whether the content is the content at the heads.
105
118
  */
106
119
  export declare function resolveEditableDocument(client: Pick<SeedClient, 'request'>, id: UnpackedHypermediaId): Promise<EditableDocumentBase>;
107
120
  /**
@@ -4,8 +4,9 @@ import {
4
4
  followRedirects,
5
5
  followToDocument,
6
6
  resolveDocumentState,
7
- resolveEditableDocument
8
- } from "./chunk-ZRJYHORB.mjs";
7
+ resolveEditableDocument,
8
+ sameDocumentVersion
9
+ } from "./chunk-QLR4OWHG.mjs";
9
10
  import "./chunk-QU6XHE3U.mjs";
10
11
  import "./chunk-AHQWDCHV.mjs";
11
12
  import "./chunk-7P6ASYW6.mjs";
@@ -15,5 +16,6 @@ export {
15
16
  followRedirects,
16
17
  followToDocument,
17
18
  resolveDocumentState,
18
- resolveEditableDocument
19
+ resolveEditableDocument,
20
+ sameDocumentVersion
19
21
  };
package/dist/index.d.ts CHANGED
@@ -42,7 +42,9 @@ export { createBlocksMap, matchBlockIds, computeReplaceOps, hmBlockNodeToBlockNo
42
42
  export type { APIBlockNode, APIBlock } from './block-diff';
43
43
  export { autoLinkChildToParent, createAutoLinkOps, documentContainsLinkToChild, documentHasSelfQuery, shouldAutoLinkParent, } from './auto-link';
44
44
  export type { AutoLinkChildToParentOptions } from './auto-link';
45
- export { describeRedirect, followRedirects, followToDocument, editRefGeneration, resolveDocumentState, resolveEditableDocument, } from './document-state';
45
+ export { clientBuiltDocumentUpdateBlobs, DEFAULT_MAX_PREPARED_CHANGE_BYTES, DEFAULT_PREPARE_TIMEOUT_MS, documentOperationsToChanges, documentUpdateBlobs, implausiblePreparedChange, isEmptyPreparedChange, nativeBlockToProtoBlock, preparableDocumentChanges, prepareDocumentUpdateBlobs, UnpreparableDocumentUpdateError, } from './prepare-change';
46
+ export type { ClientBuiltDocumentUpdateInput, DocumentContent, DocumentChangeInput, DocumentChanges, DocumentUpdateBlobsInput, DocumentUpdateBlobsResult, PrepareDocumentUpdateInput, PrepareDocumentUpdateResult, ProtoAnnotationJson, ProtoBlockJson, } from './prepare-change';
47
+ export { describeRedirect, followRedirects, followToDocument, editRefGeneration, resolveDocumentState, resolveEditableDocument, sameDocumentVersion, } from './document-state';
46
48
  export type { DocumentState, EditableDocumentBase, FollowedDocument, FollowedResource, RedirectHop, } from './document-state';
47
49
  export { editorBlockToHMBlock, editorBlocksToHMBlockNodes } from './editorblock-to-hmblock';
48
50
  export { hmBlocksToEditorContent, hmBlockToEditorBlock, annotationContains } from './hmblock-to-editorblock';
package/dist/index.mjs CHANGED
@@ -56,11 +56,6 @@ import {
56
56
  import {
57
57
  createSeedClient
58
58
  } from "./chunk-HY4NWSHF.mjs";
59
- import {
60
- SeedClientError,
61
- SeedNetworkError,
62
- SeedValidationError
63
- } from "./chunk-CBELM7KX.mjs";
64
59
  import {
65
60
  commentRecordIdFromBlob,
66
61
  createComment,
@@ -88,7 +83,25 @@ import {
88
83
  documentContainsLinkToChild,
89
84
  documentHasSelfQuery,
90
85
  shouldAutoLinkParent
91
- } from "./chunk-LGJJ4V2O.mjs";
86
+ } from "./chunk-D3PRDISB.mjs";
87
+ import {
88
+ DEFAULT_MAX_PREPARED_CHANGE_BYTES,
89
+ DEFAULT_PREPARE_TIMEOUT_MS,
90
+ UnpreparableDocumentUpdateError,
91
+ clientBuiltDocumentUpdateBlobs,
92
+ documentOperationsToChanges,
93
+ documentUpdateBlobs,
94
+ implausiblePreparedChange,
95
+ isEmptyPreparedChange,
96
+ nativeBlockToProtoBlock,
97
+ preparableDocumentChanges,
98
+ prepareDocumentUpdateBlobs
99
+ } from "./chunk-IRP2ZGH3.mjs";
100
+ import {
101
+ SeedClientError,
102
+ SeedNetworkError,
103
+ SeedValidationError
104
+ } from "./chunk-CBELM7KX.mjs";
92
105
  import {
93
106
  createChange,
94
107
  createChangeOps,
@@ -110,8 +123,9 @@ import {
110
123
  followRedirects,
111
124
  followToDocument,
112
125
  resolveDocumentState,
113
- resolveEditableDocument
114
- } from "./chunk-ZRJYHORB.mjs";
126
+ resolveEditableDocument,
127
+ sameDocumentVersion
128
+ } from "./chunk-QLR4OWHG.mjs";
115
129
  import "./chunk-2MD3FXKB.mjs";
116
130
  import {
117
131
  computeReplaceOps,
@@ -167,17 +181,21 @@ import "./chunk-7P6ASYW6.mjs";
167
181
  export {
168
182
  AnnotationSet,
169
183
  DEFAULT_GROBID_URL,
184
+ DEFAULT_MAX_PREPARED_CHANGE_BYTES,
185
+ DEFAULT_PREPARE_TIMEOUT_MS,
170
186
  HYPERMEDIA_SCHEME,
171
187
  InvalidMermaidError,
172
188
  MarkdownFrontmatterError,
173
189
  SeedClientError,
174
190
  SeedNetworkError,
175
191
  SeedValidationError,
192
+ UnpreparableDocumentUpdateError,
176
193
  addSpanToAnnotation,
177
194
  annotationContains,
178
195
  assertValidMermaid,
179
196
  autoLinkChildToParent,
180
197
  blocksToMarkdown,
198
+ clientBuiltDocumentUpdateBlobs,
181
199
  codePointLength,
182
200
  collectMermaidBlocks,
183
201
  commentRecordIdFromBlob,
@@ -207,7 +225,9 @@ export {
207
225
  directoryToIpfsBlobs,
208
226
  documentContainsLinkToChild,
209
227
  documentHasSelfQuery,
228
+ documentOperationsToChanges,
210
229
  documentToResolvedMarkdown,
230
+ documentUpdateBlobs,
211
231
  draftFilename,
212
232
  editRefGeneration,
213
233
  editorBlockToHMBlock,
@@ -229,12 +249,15 @@ export {
229
249
  hmBlocksToEditorContent,
230
250
  hmDomainUrlToWebUrl,
231
251
  hmIdPathToEntityQueryPath,
252
+ implausiblePreparedChange,
253
+ isEmptyPreparedChange,
232
254
  isGrobidAvailable,
233
255
  isSurrogate,
234
256
  encryption_exports as keyEncryption,
235
257
  keyfile_exports as keyfile,
236
258
  markdownBlockNodesToHMBlockNodes,
237
259
  matchBlockIds,
260
+ nativeBlockToProtoBlock,
238
261
  normalizeDirectoryFilePath,
239
262
  packBaseId,
240
263
  packHmId,
@@ -245,6 +268,8 @@ export {
245
268
  parseInlineFormatting,
246
269
  parseMarkdown,
247
270
  pdfToBlocks,
271
+ preparableDocumentChanges,
272
+ prepareDocumentUpdateBlobs,
248
273
  processFulltextDocument,
249
274
  pushSpanToAnnotation,
250
275
  rebindTableIdentities,
@@ -255,6 +280,7 @@ export {
255
280
  resolveHypermediaUrl,
256
281
  resolveId,
257
282
  resolveIdWithClient,
283
+ sameDocumentVersion,
258
284
  serializeBlockRange,
259
285
  shouldAutoLinkParent,
260
286
  signDocumentChange,
@@ -0,0 +1,407 @@
1
+ /**
2
+ * Document updates through the daemon's `PrepareDocumentChange`.
3
+ *
4
+ * A Change built on the client ({@link createChangeOps}) is stored exactly as it was written, so
5
+ * every op the caller listed lands in the document's history, whether or not it changed anything:
6
+ * a `MoveBlocks` that re-lists a whole level re-moves every block of it, and a `ReplaceBlock` of an
7
+ * untouched block is stored again. The daemon applies the same ops to the document's real state
8
+ * and writes only what differs: a block already in place is not moved, a block already holding the
9
+ * same content is not replaced, an attribute already holding the same value is not set. (Its
10
+ * comparison of values is strict about whole numbers: a block with a whole-number attribute, or a
11
+ * whole-number document attribute, is written again even when equal. Moves, text, links,
12
+ * annotations and other attribute values are compared as you would expect.)
13
+ *
14
+ * This module is the seam for updating an EXISTING document that way. {@link documentUpdateBlobs}
15
+ * is the one function to call: it asks the daemon, checks what comes back, and builds the Change
16
+ * here instead whenever the daemon cannot be asked, refuses, does not answer in time or answers
17
+ * with something implausible. Its parts are exported for callers that need one of them alone:
18
+ *
19
+ * 1. {@link preparableDocumentChanges} turns native ops into the request's `changes`, in the form
20
+ * the daemon applies correctly, or says that it cannot ({@link documentOperationsToChanges} is
21
+ * the plain conversion underneath, which is NOT safe to send for a document that has content).
22
+ * 2. {@link prepareDocumentUpdateBlobs} asks the daemon for the unsigned Change, signs it and
23
+ * returns the Change and Ref blobs without publishing them, so a caller can publish them
24
+ * together with file blobs, tombstones or another document's blobs. It has none of the guards.
25
+ * 3. {@link clientBuiltDocumentUpdateBlobs} is the way out for an update the daemon cannot be
26
+ * asked for: the Change built here, stored as written.
27
+ *
28
+ * Creating a document (and the home document's genesis) stays with `createDocumentBlobs` and
29
+ * `createChangeOps`: a first Change has no earlier state to be redundant against.
30
+ */
31
+ import { type DocumentOperation } from './change';
32
+ import type { SeedClient } from './client';
33
+ import { type DocumentState } from './document-state';
34
+ import type { CollectedBlob } from './file-to-ipfs';
35
+ import type { HMPrepareDocumentChangeInput } from './hm-types';
36
+ import type { AnySigner } from './signer';
37
+ /** The `changes` of a `PrepareDocumentChange` request. */
38
+ export type DocumentChanges = HMPrepareDocumentChangeInput['changes'];
39
+ /** One entry of {@link DocumentChanges}. */
40
+ export type DocumentChangeInput = DocumentChanges[number];
41
+ /** A block in the JSON form of the daemon's `Block` message, as `replaceBlock` takes it. */
42
+ export type ProtoBlockJson = {
43
+ id: string;
44
+ type?: string;
45
+ text?: string;
46
+ link?: string;
47
+ attributes?: Record<string, unknown>;
48
+ annotations?: ProtoAnnotationJson[];
49
+ };
50
+ /** An annotation in the JSON form of the daemon's `Annotation` message. */
51
+ export type ProtoAnnotationJson = {
52
+ type: string;
53
+ link?: string;
54
+ attributes?: Record<string, unknown>;
55
+ starts?: number[];
56
+ ends?: number[];
57
+ };
58
+ /**
59
+ * Converts native ops to the `changes` of a `PrepareDocumentChange` request, keeping their order
60
+ * and their meaning:
61
+ *
62
+ * - `ReplaceBlock` becomes `replaceBlock` with the block in proto JSON (see
63
+ * {@link nativeBlockToProtoBlock}).
64
+ * - `MoveBlocks {blocks, parent}` becomes one `moveBlock` per block. A native `MoveBlocks` carries
65
+ * no anchor, which places its blocks at the START of the parent's children, in the order listed;
66
+ * so the first block gets `leftSibling: ''` and each following block gets the block before it.
67
+ * A block listed twice in a row is placed once.
68
+ * - `DeleteBlocks` becomes one `deleteBlock` per block.
69
+ * - `SetAttributes` becomes `setMetadata` for a one-segment key with a string value and
70
+ * `setAttribute` (document level) for everything else. The daemon takes strings, whole numbers,
71
+ * booleans and null; anything else throws here instead of being stored as something else.
72
+ *
73
+ * To place a block anywhere but the start of a level, write the `moveBlock` change yourself: it
74
+ * names the left sibling, which a native `MoveBlocks` cannot.
75
+ *
76
+ * This is the plain conversion. Its moves are NOT safe to send for a document that already has
77
+ * blocks: the daemon misplaces blocks when a level is re-listed. Use
78
+ * {@link preparableDocumentChanges} for an update.
79
+ */
80
+ export declare function documentOperationsToChanges(ops: DocumentOperation[]): DocumentChanges;
81
+ /** A document's block tree (`document.content`), as far as placing blocks needs it. */
82
+ export type DocumentContent = Array<{
83
+ block: {
84
+ id: string;
85
+ };
86
+ children?: unknown;
87
+ }> | undefined | null;
88
+ /**
89
+ * Thrown by {@link prepareDocumentUpdateBlobs} for ops that {@link preparableDocumentChanges}
90
+ * cannot turn into a request the daemon applies correctly. Build that update with
91
+ * {@link clientBuiltDocumentUpdateBlobs} instead.
92
+ */
93
+ export declare class UnpreparableDocumentUpdateError extends Error {
94
+ readonly reason: string;
95
+ constructor(reason: string);
96
+ }
97
+ /**
98
+ * The `changes` to send to `PrepareDocumentChange` for `ops`, or why they cannot be sent.
99
+ *
100
+ * This is the one conversion to use for an update of a document that has content. `content` is the
101
+ * content of the document the ops were computed against (the one `baseVersion` names).
102
+ *
103
+ * Replaces, deletes and attributes go as {@link documentOperationsToChanges} writes them. Moves do
104
+ * not. A `MoveBlocks` from a diff lists a whole level, which as a request is "first block at the
105
+ * start, each next block after the one before". The daemon (as seen on a real one, 2026-11-16)
106
+ * gets that wrong in two ways:
107
+ *
108
+ * - a first block "moved" to where it already is makes the block after it land before it:
109
+ * `[a, b]` plus a new block after `a` reads back as `[new, a, b]`;
110
+ * - a block whose move leaves it behind the same block as before is not written, even when that
111
+ * block itself moved: `[a, b, c, d]` to `[a, c, d, b]` sent as a chain stores only the move of
112
+ * `c` and reads back `[a, c, b, d]`.
113
+ *
114
+ * So each level is sent as the fewest moves that produce it: the longest run of blocks already in
115
+ * the right order relative to each other stays put and is not mentioned, and every other block is
116
+ * placed after the block that precedes it in the result. No block in place is ever sent, which
117
+ * covers the first case. The second cannot be said to the daemon at all when a block that has to
118
+ * move keeps its left neighbour (`[a, b, c, d]` to `[c, d, a, b]`: whichever pair moves, its
119
+ * second block follows its first as before). Such an update is `unpreparable`: build it with
120
+ * {@link clientBuiltDocumentUpdateBlobs}, where the level is stored as listed.
121
+ *
122
+ * A native `MoveBlocks` puts its blocks at the start of the level, in order, ahead of the blocks it
123
+ * does not list; that is the result computed here when a list is not the whole level. Ops that
124
+ * order the same level twice, place a block twice, or delete a block and place it are
125
+ * unpreparable too.
126
+ *
127
+ * Every `replaceBlock` comes before the first `moveBlock` or `deleteBlock`. The daemon learns that
128
+ * a new block can be a parent when it sees its `replaceBlock`, but only until the first move or
129
+ * delete of the request; a new block's content sent after that point makes a move under it fail
130
+ * ("desired parent block is not in the tree"). The moves themselves keep the order of the ops.
131
+ *
132
+ * An update that turns a block's descendant into its ancestor (a parent and child swapping places,
133
+ * or any longer loop of that kind) is unpreparable: the daemon either refuses it ("cycle
134
+ * detected") or, without Seed PR #1375, never answers and keeps a CPU busy. Only the document's
135
+ * current tree is looked at here. A daemon without that fix also never answers a request that
136
+ * moves or deletes blocks in a document whose HISTORY holds such a turn; nothing reads the history
137
+ * to avoid that, and {@link documentUpdateBlobs} stops waiting after its timeout.
138
+ */
139
+ export declare function preparableDocumentChanges(ops: DocumentOperation[], content: DocumentContent): {
140
+ changes: DocumentChanges;
141
+ } | {
142
+ unpreparable: string;
143
+ };
144
+ /**
145
+ * Converts a native block (the `block` of a `ReplaceBlock` op) to the proto JSON the daemon takes,
146
+ * so that the daemon stores the block the native op would have stored.
147
+ *
148
+ * A native block keeps `id`, `type`, `text`, `link` and `annotations` as fields and its attributes
149
+ * beside them (`{id, type, text, childrenType: 'Ordered'}`); the older form with a nested
150
+ * `attributes` map is read the same way. Both become the proto block's `attributes`. A block that
151
+ * has a non-empty `attributes` map AND attributes beside it is refused: a reader of the stored
152
+ * native block would see only the nested map, so one of the two would be lost. `revision`, which
153
+ * blocks read from the API carry, is not content and is dropped. Annotations follow the same rule.
154
+ *
155
+ * Attribute values must be plain JSON (strings, finite numbers, booleans, null, arrays and plain
156
+ * objects). Anything else, a protobuf message in particular, throws: stored as it is, it would
157
+ * be kept in its in-memory shape (`{fields: {x: {kind: …}}}`).
158
+ */
159
+ export declare function nativeBlockToProtoBlock(block: unknown): ProtoBlockJson;
160
+ /**
161
+ * Whether an unsigned Change from `PrepareDocumentChange` carries no operations.
162
+ *
163
+ * The daemon does not refuse a request whose changes are all already true of the document: it
164
+ * answers with a well-formed Change that has an empty body. Signing and publishing that would add
165
+ * an empty version to the document's history, so callers check this first.
166
+ */
167
+ export declare function isEmptyPreparedChange(unsignedChange: Uint8Array): boolean;
168
+ /** What to update, for {@link prepareDocumentUpdateBlobs}. */
169
+ export type PrepareDocumentUpdateInput = {
170
+ /** Any client that reaches a Seed API (`PrepareDocumentChange`). */
171
+ client: Pick<SeedClient, 'request'>;
172
+ /** Signs the Change and the Ref. The daemon never sees the key. */
173
+ signer: AnySigner;
174
+ /** Account (space) the document lives in. */
175
+ account: string;
176
+ /** Document path in API form (`/notes/first`); `''` or omitted for the home document. */
177
+ path?: string;
178
+ /** The version to build on: the document's current heads joined with `.`. */
179
+ baseVersion: string;
180
+ /**
181
+ * Native ops to apply; converted with {@link preparableDocumentChanges}, which needs `content`.
182
+ * Give this or `changes`. Ops the daemon cannot be asked for throw
183
+ * {@link UnpreparableDocumentUpdateError}.
184
+ */
185
+ ops?: DocumentOperation[];
186
+ /**
187
+ * With `ops`: the content of the document at `baseVersion` (`document.content`), which the ops
188
+ * were computed against. Required when the ops move blocks; `[]` for a document with no blocks.
189
+ */
190
+ content?: DocumentContent;
191
+ /** Changes already in the request's form, for what native ops cannot say (a `moveBlock` with a left sibling). */
192
+ changes?: DocumentChanges;
193
+ /** Writer capability CID, when the signer writes into another account's space. */
194
+ capability?: string;
195
+ /** Genesis for the Ref. Defaults to the genesis the prepared Change names. */
196
+ genesis?: string;
197
+ /**
198
+ * Generation for the Ref, used as given. Left out, the Ref keeps `currentGeneration`, or takes
199
+ * the prepared Change's timestamp (the daemon's clock) when that is left out too.
200
+ */
201
+ generation?: number | bigint;
202
+ /**
203
+ * The generation the document has now (`document.generationInfo.generation`). An edit continues
204
+ * that generation, so the Ref carries it as it is (see `editRefGeneration`). Leave it out only
205
+ * when the Ref must open a new generation: to take a path over from a redirect, or for a
206
+ * document that reports none. Ignored when `generation` is given.
207
+ */
208
+ currentGeneration?: number | bigint | string;
209
+ /** Proto `ResourceVisibility` (2 is private); only needed for a private document. */
210
+ visibility?: number;
211
+ /** Aborts the request. */
212
+ signal?: AbortSignal;
213
+ };
214
+ /** The outcome of {@link prepareDocumentUpdateBlobs}. */
215
+ export type PrepareDocumentUpdateResult = {
216
+ /** The document changes: publish `blobs`. */
217
+ changed: true;
218
+ /** The signed Change, then the Version Ref that makes it the latest version. */
219
+ blobs: CollectedBlob[];
220
+ /** CID of the new Change, which is the document's new version. */
221
+ version: string;
222
+ genesis: string;
223
+ generation: number;
224
+ /** The new Change's timestamp (milliseconds) and depth: what a Change built on top of it needs. */
225
+ ts: number;
226
+ depth: number;
227
+ } | {
228
+ /** Every requested change is already true of the document: there is nothing to publish. */
229
+ changed: false;
230
+ blobs: [];
231
+ /** The version the request was built on, which is still the latest one it knows. */
232
+ version: string;
233
+ };
234
+ /**
235
+ * Builds the blobs for the next version of an existing document, letting the daemon compute the
236
+ * Change.
237
+ *
238
+ * It sends the changes to `PrepareDocumentChange`, signs the unsigned Change it returns and signs
239
+ * the Version Ref for it. Nothing is published: the caller publishes `blobs`, usually together with
240
+ * other blobs, in one `client.publish`.
241
+ *
242
+ * When the daemon finds nothing to change (every block already in place and unchanged, every
243
+ * attribute already set) the result is `{changed: false, blobs: []}`. No Change is signed and
244
+ * there is nothing to publish. An empty list of ops gives the same result without a request.
245
+ *
246
+ * The site is trusted for the Change's content: the bytes it returns are signed as they are, the
247
+ * way `client.publishDocument` does. There is no timeout, no check of the answer and no way out
248
+ * when the daemon refuses; {@link documentUpdateBlobs} adds those and is what an update should
249
+ * normally go through.
250
+ */
251
+ export declare function prepareDocumentUpdateBlobs(input: PrepareDocumentUpdateInput): Promise<PrepareDocumentUpdateResult>;
252
+ /** What to update, for {@link clientBuiltDocumentUpdateBlobs}. */
253
+ export type ClientBuiltDocumentUpdateInput = {
254
+ signer: AnySigner;
255
+ /** Account (space) the document lives in. */
256
+ account: string;
257
+ /** Document path in API form (`/notes/first`); `''` or omitted for the home document. */
258
+ path?: string;
259
+ /**
260
+ * The change history to build on (`resolveDocumentState`, or `resolveEditableDocument().state`).
261
+ * `headTs` matters: see the timestamp rule below.
262
+ */
263
+ state: Pick<DocumentState, 'genesis' | 'heads' | 'headDepth' | 'headTs'>;
264
+ ops: DocumentOperation[];
265
+ /** Writer capability CID, when the signer writes into another account's space. */
266
+ capability?: string;
267
+ /** The generation the document has now, which the Ref keeps. Left out, the Ref takes the Change's timestamp. */
268
+ currentGeneration?: number | bigint | string;
269
+ /** Proto `ResourceVisibility` (2 is private); only needed for a private document. */
270
+ visibility?: number;
271
+ /** This machine's clock in milliseconds. Defaults to `Date.now`. */
272
+ now?: () => number;
273
+ };
274
+ /**
275
+ * Builds the blobs for the next version of an existing document without the daemon: the Change
276
+ * holds `ops` exactly as given, on top of `state.heads`.
277
+ *
278
+ * Its timestamp is this machine's clock, or one millisecond after the latest head
279
+ * (`state.headTs`) when the clock is not past it. A Change must be later than the Changes it
280
+ * builds on: the daemon stores one that is not and then reads the document as broken ("missing
281
+ * dependency"). The heads often carry another machine's clock (a prepared Change carries the
282
+ * site's), so a clock a second behind is enough to hit that.
283
+ *
284
+ * Nothing is compared with the document, so an op that changes nothing is stored too. Use it for
285
+ * the updates {@link prepareDocumentUpdateBlobs} cannot make: ops that are unpreparable
286
+ * ({@link UnpreparableDocumentUpdateError}), attribute values the request cannot carry, or a
287
+ * request the site refuses. Returns the same shape as a prepared update that changed the
288
+ * document; nothing is published.
289
+ */
290
+ export declare function clientBuiltDocumentUpdateBlobs(input: ClientBuiltDocumentUpdateInput): Promise<Extract<PrepareDocumentUpdateResult, {
291
+ changed: true;
292
+ }>>;
293
+ /** How long {@link documentUpdateBlobs} waits for `PrepareDocumentChange` before building the Change itself. */
294
+ export declare const DEFAULT_PREPARE_TIMEOUT_MS = 15000;
295
+ /**
296
+ * The largest prepared Change {@link documentUpdateBlobs} signs. A stored block may be 2 MB and a
297
+ * publish request 4 MB; a daemon that repeats moves has been seen to answer a one-block insert
298
+ * with 2 to 23 MB.
299
+ */
300
+ export declare const DEFAULT_MAX_PREPARED_CHANGE_BYTES: number;
301
+ /** What to update, for {@link documentUpdateBlobs}. */
302
+ export type DocumentUpdateBlobsInput = {
303
+ /** Any client that reaches a Seed API (`PrepareDocumentChange`, `GetCID`). */
304
+ client: Pick<SeedClient, 'request'>;
305
+ /** Signs the Change and the Ref. The daemon never sees the key. */
306
+ signer: AnySigner;
307
+ /** Account (space) of the address being written. */
308
+ account: string;
309
+ /** Path of the address being written, in API form (`/notes/first`); `''` or omitted for the home document. */
310
+ path?: string;
311
+ /**
312
+ * The change history to build on (`resolveEditableDocument().state`). For an address that holds
313
+ * a redirect this is the redirect target's state: the Change continues the target's history
314
+ * and the Ref lands at `path`.
315
+ */
316
+ state: DocumentState;
317
+ /** Native ops to apply, computed against `content`. */
318
+ ops: DocumentOperation[];
319
+ /** The content of the document the ops were computed against (`document.content`). */
320
+ content: DocumentContent;
321
+ /**
322
+ * The version `content` was read at (`document.version`). When it does not name the heads of
323
+ * `state`, the content is stale, so nothing is asked of the daemon and the Change is built here.
324
+ */
325
+ documentVersion?: string;
326
+ /**
327
+ * The ops to store when the Change is built here, if they should differ from `ops`. A caller
328
+ * that keeps part of an update out of `ops` because the daemon cannot carry it puts the whole
329
+ * update here, so a Change built here needs no second Change on top. Used only when `ops` is
330
+ * not empty and the daemon's Change is not used.
331
+ */
332
+ localOps?: DocumentOperation[];
333
+ /** Writer capability CID, when the signer writes into another account's space. */
334
+ capability?: string;
335
+ /**
336
+ * The generation the document has now (`document.generationInfo.generation`), which the new Ref
337
+ * keeps: an edit does not open a new generation. Leave it out for a redirect takeover, so the
338
+ * Ref takes a fresh generation (the Change's timestamp) and outranks the redirect Ref.
339
+ */
340
+ currentGeneration?: number | bigint | string;
341
+ /** Proto `ResourceVisibility` (2 is private); only needed for a private document. */
342
+ visibility?: number;
343
+ /** This machine's clock in milliseconds, for a Change built here. Defaults to `Date.now`. */
344
+ now?: () => number;
345
+ /** How long to wait for the daemon's answer. Defaults to {@link DEFAULT_PREPARE_TIMEOUT_MS}. */
346
+ prepareTimeoutMs?: number;
347
+ /** The largest prepared Change to sign. Defaults to {@link DEFAULT_MAX_PREPARED_CHANGE_BYTES}. */
348
+ maxPreparedChangeBytes?: number;
349
+ };
350
+ /** The outcome of {@link documentUpdateBlobs}. */
351
+ export type DocumentUpdateBlobsResult = (Extract<PrepareDocumentUpdateResult, {
352
+ changed: true;
353
+ }> & {
354
+ /** Who computed the Change: the server (only what differs is stored), or this process (the ops as written). */
355
+ builtBy: 'server' | 'local';
356
+ /** Why the Change was built here, in words fit to show after "built locally because". */
357
+ localReason?: string;
358
+ }) | Extract<PrepareDocumentUpdateResult, {
359
+ changed: false;
360
+ }>;
361
+ /**
362
+ * Builds the blobs for the next version of an existing document: the one way an update should be
363
+ * made. Nothing is published; the caller publishes `blobs`.
364
+ *
365
+ * The daemon is asked for the Change (`PrepareDocumentChange`), so that only what differs from
366
+ * the document is stored, and `{changed: false}` comes back when nothing differs. The Change is
367
+ * built here instead (`builtBy: 'local'`, with `localReason`), holding the ops as written, when:
368
+ *
369
+ * - `content` is not the content at the heads (`documentVersion` differs from `state.version`);
370
+ * - the ops cannot be put in a request the daemon applies correctly
371
+ * ({@link preparableDocumentChanges}), or hold an attribute value the request cannot carry;
372
+ * - the daemon does not answer within `prepareTimeoutMs` (the document is then built here for
373
+ * the next ten minutes without asking again);
374
+ * - the site refuses the request as too large (413) or does not know `PrepareDocumentChange`;
375
+ * - the daemon fails to apply the changes (a 5xx such as "is not in the tree" or "cycle
376
+ * detected"), or its clock is not past the document's latest Change ("must be greater than ts
377
+ * of its dependency");
378
+ * - the Change it answers with is not plausible for the request: it moves, replaces or deletes
379
+ * blocks the request did not name, places more blocks than the request did, or is larger than
380
+ * `maxPreparedChangeBytes`.
381
+ *
382
+ * Falling back is safe because `PrepareDocumentChange` only reads: the daemon loads the document,
383
+ * applies the changes in memory and returns unsigned bytes (`PrepareChange` in
384
+ * `backend/api/documents/v3alpha/documents.go` stores nothing). Whatever happened to that request,
385
+ * nothing was published, so building the Change here cannot publish the update twice.
386
+ *
387
+ * Errors that are the caller's to see are thrown as they are: a refusal for lack of permission, a
388
+ * 4xx about the request itself, and a network failure (the site that could not be reached for
389
+ * this would not take the publish either).
390
+ */
391
+ export declare function documentUpdateBlobs(input: DocumentUpdateBlobsInput): Promise<DocumentUpdateBlobsResult>;
392
+ /**
393
+ * Why an unsigned Change from the daemon is not a plausible answer to `changes`, or null when it is.
394
+ *
395
+ * The daemon writes no more than what was asked: a block already in place is not moved, a block
396
+ * already holding the content is not replaced. So a prepared Change never places more blocks than
397
+ * the request has `moveBlock` changes, never places one block more often than the request does,
398
+ * and never replaces or deletes a block the request did not name. (It stores one `MoveBlocks` per
399
+ * run of neighbours, so the count is of blocks placed, not of ops.) A daemon that repeats moves
400
+ * (seen in 2026: every move once per stale entry of each ancestor, compounding with depth) breaks
401
+ * the first two rules and is caught here, before anything is signed.
402
+ *
403
+ * The blocks it moves need not be the ones the request moved. The daemon derives its moves from
404
+ * the resulting order, and where two sets of moves give the same order it may pick the other one:
405
+ * asked to put `c` after `d` in `[a, b, c, d]`, it may store `d` after `b`.
406
+ */
407
+ export declare function implausiblePreparedChange(unsignedChange: Uint8Array, changes: DocumentChanges, maxBytes?: number): string | null;
@@ -0,0 +1,35 @@
1
+ import {
2
+ DEFAULT_MAX_PREPARED_CHANGE_BYTES,
3
+ DEFAULT_PREPARE_TIMEOUT_MS,
4
+ UnpreparableDocumentUpdateError,
5
+ clientBuiltDocumentUpdateBlobs,
6
+ documentOperationsToChanges,
7
+ documentUpdateBlobs,
8
+ implausiblePreparedChange,
9
+ isEmptyPreparedChange,
10
+ nativeBlockToProtoBlock,
11
+ preparableDocumentChanges,
12
+ prepareDocumentUpdateBlobs
13
+ } from "./chunk-IRP2ZGH3.mjs";
14
+ import "./chunk-CBELM7KX.mjs";
15
+ import "./chunk-O5MHN2EO.mjs";
16
+ import "./chunk-PJ2RFT5A.mjs";
17
+ import "./chunk-QLR4OWHG.mjs";
18
+ import "./chunk-LVAHHQIK.mjs";
19
+ import "./chunk-DR3HJ6BV.mjs";
20
+ import "./chunk-QU6XHE3U.mjs";
21
+ import "./chunk-AHQWDCHV.mjs";
22
+ import "./chunk-7P6ASYW6.mjs";
23
+ export {
24
+ DEFAULT_MAX_PREPARED_CHANGE_BYTES,
25
+ DEFAULT_PREPARE_TIMEOUT_MS,
26
+ UnpreparableDocumentUpdateError,
27
+ clientBuiltDocumentUpdateBlobs,
28
+ documentOperationsToChanges,
29
+ documentUpdateBlobs,
30
+ implausiblePreparedChange,
31
+ isEmptyPreparedChange,
32
+ nativeBlockToProtoBlock,
33
+ preparableDocumentChanges,
34
+ prepareDocumentUpdateBlobs
35
+ };