@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.
@@ -0,0 +1,670 @@
1
+ import {
2
+ SeedClientError
3
+ } from "./chunk-CBELM7KX.mjs";
4
+ import {
5
+ createChange,
6
+ createChangeOps,
7
+ signDocumentChange,
8
+ visibilityToCbor
9
+ } from "./chunk-O5MHN2EO.mjs";
10
+ import {
11
+ createVersionRef
12
+ } from "./chunk-PJ2RFT5A.mjs";
13
+ import {
14
+ sameDocumentVersion
15
+ } from "./chunk-QLR4OWHG.mjs";
16
+
17
+ // src/prepare-change.ts
18
+ import { decode as cborDecode } from "@ipld/dag-cbor";
19
+ import { CID } from "multiformats/cid";
20
+ var BLOCK_FIELDS = /* @__PURE__ */ new Set(["id", "iD", "type", "text", "link", "annotations", "attributes", "revision"]);
21
+ var ANNOTATION_FIELDS = /* @__PURE__ */ new Set(["type", "link", "starts", "ends", "attributes"]);
22
+ function documentOperationsToChanges(ops) {
23
+ const changes = [];
24
+ for (const op of ops) {
25
+ switch (op.type) {
26
+ case "ReplaceBlock":
27
+ changes.push({ op: { case: "replaceBlock", value: nativeBlockToProtoBlock(op.block) } });
28
+ break;
29
+ case "MoveBlocks": {
30
+ const parent = op.parent ?? "";
31
+ let left = "";
32
+ for (const blockId of op.blocks) {
33
+ if (typeof blockId !== "string" || !blockId) throw new Error("MoveBlocks: every block needs an id");
34
+ if (blockId === left) continue;
35
+ changes.push({ op: { case: "moveBlock", value: { blockId, parent, leftSibling: left } } });
36
+ left = blockId;
37
+ }
38
+ break;
39
+ }
40
+ case "DeleteBlocks":
41
+ for (const blockId of op.blocks) {
42
+ if (typeof blockId !== "string" || !blockId) throw new Error("DeleteBlocks: every block needs an id");
43
+ changes.push({ op: { case: "deleteBlock", value: blockId } });
44
+ }
45
+ break;
46
+ case "SetAttributes":
47
+ for (const attr of op.attrs) changes.push(attributeChange(attr.key, attr.value));
48
+ break;
49
+ default:
50
+ throw new Error(`Unsupported document operation: ${String(op.type)}`);
51
+ }
52
+ }
53
+ return changes;
54
+ }
55
+ function attributeChange(key, value) {
56
+ const name = Array.isArray(key) ? key.join(".") : String(key);
57
+ if (!Array.isArray(key) || key.length === 0) throw new Error("SetAttributes: an attribute needs a key");
58
+ for (const segment of key) {
59
+ if (typeof segment !== "string" || !segment || segment.includes(".")) {
60
+ throw new Error(`SetAttributes: key segments must be non-empty strings without dots (in "${name}")`);
61
+ }
62
+ }
63
+ if (typeof value === "string") {
64
+ if (key.length === 1) return { op: { case: "setMetadata", value: { key: key[0], value } } };
65
+ return { op: { case: "setAttribute", value: { blockId: "", key, value: { case: "stringValue", value } } } };
66
+ }
67
+ if (typeof value === "boolean") {
68
+ return { op: { case: "setAttribute", value: { blockId: "", key, value: { case: "boolValue", value } } } };
69
+ }
70
+ if (value === null) {
71
+ return { op: { case: "setAttribute", value: { blockId: "", key, value: { case: "nullValue", value: {} } } } };
72
+ }
73
+ if (typeof value === "number" || typeof value === "bigint") {
74
+ if (typeof value === "number" && !Number.isSafeInteger(value)) {
75
+ throw new Error(
76
+ `SetAttributes: "${name}" is ${value}; a document attribute number must be a whole number (store anything else as a string)`
77
+ );
78
+ }
79
+ return { op: { case: "setAttribute", value: { blockId: "", key, value: { case: "intValue", value: BigInt(value) } } } };
80
+ }
81
+ throw new Error(
82
+ `SetAttributes: "${name}" has a ${Array.isArray(value) ? "list" : typeof value} value; a document attribute is a string, a whole number, a boolean or null`
83
+ );
84
+ }
85
+ var UnpreparableDocumentUpdateError = class extends Error {
86
+ constructor(reason) {
87
+ super(`This update cannot be prepared by the server: ${reason}`);
88
+ this.reason = reason;
89
+ this.name = "UnpreparableDocumentUpdateError";
90
+ }
91
+ };
92
+ function preparableDocumentChanges(ops, content) {
93
+ const parentOf = /* @__PURE__ */ new Map();
94
+ const leftOf = /* @__PURE__ */ new Map();
95
+ const childrenOf = /* @__PURE__ */ new Map();
96
+ const walk = (nodes, parent) => {
97
+ var _a;
98
+ if (!Array.isArray(nodes)) return;
99
+ const ids = [];
100
+ for (const node of nodes) {
101
+ const id = (_a = node == null ? void 0 : node.block) == null ? void 0 : _a.id;
102
+ if (typeof id !== "string" || !id) continue;
103
+ parentOf.set(id, parent);
104
+ leftOf.set(id, ids[ids.length - 1] ?? "");
105
+ ids.push(id);
106
+ walk(node.children, id);
107
+ }
108
+ childrenOf.set(parent, ids);
109
+ };
110
+ walk(content, "");
111
+ const deleted = /* @__PURE__ */ new Set();
112
+ const destination = /* @__PURE__ */ new Map();
113
+ const orderedParents = /* @__PURE__ */ new Set();
114
+ for (const op of ops) {
115
+ if (op.type === "DeleteBlocks") for (const id of op.blocks) deleted.add(id);
116
+ if (op.type === "MoveBlocks") {
117
+ const parent = op.parent ?? "";
118
+ if (orderedParents.has(parent)) {
119
+ return { unpreparable: `the update orders the blocks under ${parent ? `block ${parent}` : "the root"} twice` };
120
+ }
121
+ orderedParents.add(parent);
122
+ for (const id of op.blocks) {
123
+ if (destination.has(id)) return { unpreparable: `the update places block ${id} twice` };
124
+ destination.set(id, parent);
125
+ }
126
+ }
127
+ }
128
+ for (const id of Array.from(destination.keys())) {
129
+ if (deleted.has(id)) return { unpreparable: `the update deletes block ${id} and places it` };
130
+ }
131
+ const loop = blockInLoop([...edgesOf(parentOf), ...edgesOf(destination)]);
132
+ if (loop !== null) {
133
+ return { unpreparable: `the update puts block ${loop} under a block that is, or was, inside it` };
134
+ }
135
+ const replaces = [];
136
+ const changes = [];
137
+ for (const op of ops) {
138
+ if (op.type === "ReplaceBlock") {
139
+ replaces.push(...documentOperationsToChanges([op]));
140
+ continue;
141
+ }
142
+ if (op.type !== "MoveBlocks") {
143
+ changes.push(...documentOperationsToChanges([op]));
144
+ continue;
145
+ }
146
+ const parent = op.parent ?? "";
147
+ for (const blockId of op.blocks) {
148
+ if (typeof blockId !== "string" || !blockId) throw new Error("MoveBlocks: every block needs an id");
149
+ }
150
+ const before = childrenOf.get(parent) ?? [];
151
+ const level = [...op.blocks, ...before.filter((id) => !deleted.has(id) && !destination.has(id))];
152
+ const settled = longestRisingRun(level.map((id) => parentOf.get(id) === parent ? before.indexOf(id) : -1));
153
+ for (let index = 0; index < level.length; index++) {
154
+ if (settled.has(index)) continue;
155
+ const blockId = level[index];
156
+ const leftSibling = index > 0 ? level[index - 1] : "";
157
+ if (parentOf.get(blockId) === parent) {
158
+ let was = leftOf.get(blockId) ?? "";
159
+ const followed = /* @__PURE__ */ new Set([was]);
160
+ while (was && deleted.has(was)) {
161
+ was = leftOf.get(was) ?? "";
162
+ followed.add(was);
163
+ }
164
+ if (followed.has(leftSibling)) {
165
+ return { unpreparable: `block ${blockId} moves together with the block before it` };
166
+ }
167
+ }
168
+ changes.push({ op: { case: "moveBlock", value: { blockId, parent, leftSibling } } });
169
+ }
170
+ }
171
+ return { changes: [...replaces, ...changes] };
172
+ }
173
+ function edgesOf(parentOf) {
174
+ return Array.from(parentOf, ([child, parent]) => [parent, child]);
175
+ }
176
+ function blockInLoop(edges) {
177
+ var _a;
178
+ const children = /* @__PURE__ */ new Map();
179
+ for (const [parent, child] of edges) {
180
+ if (parent === child) return child;
181
+ if (!parent) continue;
182
+ const list = children.get(parent);
183
+ if (list) list.push(child);
184
+ else children.set(parent, [child]);
185
+ }
186
+ const open = /* @__PURE__ */ new Set();
187
+ const done = /* @__PURE__ */ new Set();
188
+ for (const start of Array.from(children.keys())) {
189
+ if (done.has(start)) continue;
190
+ const stack = [{ id: start, next: 0 }];
191
+ open.add(start);
192
+ while (stack.length) {
193
+ const top = stack[stack.length - 1];
194
+ const child = (_a = children.get(top.id)) == null ? void 0 : _a[top.next++];
195
+ if (child === void 0) {
196
+ open.delete(top.id);
197
+ done.add(top.id);
198
+ stack.pop();
199
+ } else if (open.has(child)) {
200
+ return child;
201
+ } else if (!done.has(child)) {
202
+ open.add(child);
203
+ stack.push({ id: child, next: 0 });
204
+ }
205
+ }
206
+ }
207
+ return null;
208
+ }
209
+ function longestRisingRun(values) {
210
+ const best = new Array(values.length).fill(0);
211
+ const previous = new Array(values.length).fill(-1);
212
+ let end = -1;
213
+ for (let i = 0; i < values.length; i++) {
214
+ if (values[i] < 0) continue;
215
+ best[i] = 1;
216
+ for (let j = 0; j < i; j++) {
217
+ if (values[j] >= 0 && values[j] < values[i] && best[j] + 1 > best[i]) {
218
+ best[i] = best[j] + 1;
219
+ previous[i] = j;
220
+ }
221
+ }
222
+ if (end < 0 || best[i] > best[end]) end = i;
223
+ }
224
+ const run = /* @__PURE__ */ new Set();
225
+ for (let i = end; i >= 0; i = previous[i]) run.add(i);
226
+ return run;
227
+ }
228
+ function nativeBlockToProtoBlock(block) {
229
+ if (!isPlainObject(block)) throw new Error("ReplaceBlock: the block must be an object");
230
+ const id = block.id ?? block.iD;
231
+ if (typeof id !== "string" || !id) throw new Error("ReplaceBlock: the block needs an id");
232
+ const where = `block ${id}`;
233
+ const out = { id };
234
+ const type = optionalString(block.type, `${where}: type`);
235
+ if (type) out.type = type;
236
+ const text = optionalString(block.text, `${where}: text`);
237
+ if (text) out.text = text;
238
+ const link = optionalString(block.link, `${where}: link`);
239
+ if (link) out.link = link;
240
+ const attributes = collectAttributes(block, BLOCK_FIELDS, where);
241
+ if (attributes) out.attributes = attributes;
242
+ if (block.annotations !== void 0 && block.annotations !== null) {
243
+ if (!Array.isArray(block.annotations)) throw new Error(`${where}: annotations must be a list`);
244
+ if (block.annotations.length) {
245
+ out.annotations = block.annotations.map(
246
+ (annotation, index) => nativeAnnotationToProto(annotation, `${where}: annotation ${index}`)
247
+ );
248
+ }
249
+ }
250
+ return out;
251
+ }
252
+ function nativeAnnotationToProto(annotation, where) {
253
+ if (!isPlainObject(annotation)) throw new Error(`${where} must be an object`);
254
+ if (typeof annotation.type !== "string" || !annotation.type) throw new Error(`${where} needs a type`);
255
+ const out = { type: annotation.type };
256
+ const link = optionalString(annotation.link, `${where}: link`);
257
+ if (link) out.link = link;
258
+ const attributes = collectAttributes(annotation, ANNOTATION_FIELDS, where);
259
+ if (attributes) out.attributes = attributes;
260
+ const starts = offsets(annotation.starts, `${where}: starts`);
261
+ const ends = offsets(annotation.ends, `${where}: ends`);
262
+ if (starts.length !== ends.length) throw new Error(`${where}: starts and ends must have the same length`);
263
+ if (starts.length) {
264
+ out.starts = starts;
265
+ out.ends = ends;
266
+ }
267
+ return out;
268
+ }
269
+ function collectAttributes(source, known, where) {
270
+ const inline = {};
271
+ for (const [key, value] of Object.entries(source)) {
272
+ if (known.has(key) || value === void 0) continue;
273
+ inline[key] = plainJson(value, `${where}: ${key}`);
274
+ }
275
+ let nested;
276
+ if (source.attributes !== void 0 && source.attributes !== null) {
277
+ const value = plainJson(source.attributes, `${where}: attributes`);
278
+ if (!isPlainObject(value)) throw new Error(`${where}: attributes must be an object`);
279
+ if (Object.keys(value).length) nested = value;
280
+ }
281
+ const inlineKeys = Object.keys(inline);
282
+ if (nested && inlineKeys.length) {
283
+ throw new Error(
284
+ `${where} has both an "attributes" map and attributes beside it (${inlineKeys.join(", ")}); use one form`
285
+ );
286
+ }
287
+ if (nested) return nested;
288
+ return inlineKeys.length ? inline : void 0;
289
+ }
290
+ function optionalString(value, where) {
291
+ if (value === void 0 || value === null) return void 0;
292
+ if (typeof value !== "string") throw new Error(`${where} must be a string`);
293
+ return value;
294
+ }
295
+ function offsets(value, where) {
296
+ if (value === void 0 || value === null) return [];
297
+ if (!Array.isArray(value)) throw new Error(`${where} must be a list`);
298
+ return value.map((offset) => {
299
+ const number = typeof offset === "bigint" ? Number(offset) : offset;
300
+ if (typeof number !== "number" || !Number.isInteger(number) || number < 0 || number > 2147483647) {
301
+ throw new Error(`${where} must hold whole, non-negative numbers`);
302
+ }
303
+ return number;
304
+ });
305
+ }
306
+ function isPlainObject(value) {
307
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return false;
308
+ const proto = Object.getPrototypeOf(value);
309
+ return proto === Object.prototype || proto === null;
310
+ }
311
+ function plainJson(value, where) {
312
+ if (value === null || typeof value === "string" || typeof value === "boolean") return value;
313
+ if (typeof value === "number") {
314
+ if (!Number.isFinite(value)) throw new Error(`${where} is ${value}, which an attribute cannot hold`);
315
+ return value;
316
+ }
317
+ if (typeof value === "bigint") {
318
+ const number = Number(value);
319
+ if (!Number.isSafeInteger(number)) throw new Error(`${where} is too large a number for an attribute`);
320
+ return number;
321
+ }
322
+ if (Array.isArray(value)) {
323
+ return value.map((item, index) => plainJson(item === void 0 ? null : item, `${where}[${index}]`));
324
+ }
325
+ if (isPlainObject(value)) {
326
+ const out = {};
327
+ for (const [key, item] of Object.entries(value)) {
328
+ if (item === void 0) continue;
329
+ out[key] = plainJson(item, `${where}.${key}`);
330
+ }
331
+ return out;
332
+ }
333
+ throw new Error(
334
+ `${where} is not plain JSON (${describeValue(
335
+ value
336
+ )}); attributes hold strings, numbers, booleans, null, lists and plain objects`
337
+ );
338
+ }
339
+ function describeValue(value) {
340
+ var _a, _b;
341
+ if (value === void 0) return "undefined";
342
+ if (typeof value !== "object" || value === null) return typeof value;
343
+ return ((_b = (_a = Object.getPrototypeOf(value)) == null ? void 0 : _a.constructor) == null ? void 0 : _b.name) || "object";
344
+ }
345
+ function isEmptyPreparedChange(unsignedChange) {
346
+ var _a;
347
+ const change = cborDecode(unsignedChange);
348
+ const ops = (_a = change.body) == null ? void 0 : _a.ops;
349
+ return !Array.isArray(ops) || ops.length === 0;
350
+ }
351
+ async function prepareDocumentUpdateBlobs(input) {
352
+ if (input.ops && input.changes) throw new Error("Give either ops or changes, not both");
353
+ if (!input.baseVersion) {
354
+ throw new Error("baseVersion is required: prepareDocumentUpdateBlobs updates an existing document");
355
+ }
356
+ const changes = input.changes ?? changesForOps(input.ops ?? [], input.content);
357
+ const unchanged = { changed: false, blobs: [], version: input.baseVersion };
358
+ if (!changes.length) return unchanged;
359
+ const { unsignedChange } = await input.client.request(
360
+ "PrepareDocumentChange",
361
+ {
362
+ account: input.account,
363
+ path: input.path ?? "",
364
+ baseVersion: input.baseVersion,
365
+ changes,
366
+ capability: input.capability,
367
+ visibility: input.visibility
368
+ },
369
+ { signal: input.signal }
370
+ );
371
+ if (isEmptyPreparedChange(unsignedChange)) return unchanged;
372
+ return signPreparedChange(input, unsignedChange);
373
+ }
374
+ async function signPreparedChange(input, unsignedChange) {
375
+ const decoded = cborDecode(unsignedChange);
376
+ const changeTs = Number(decoded.ts ?? 0);
377
+ let generation = input.generation;
378
+ if (generation == null) generation = keptGeneration(input.currentGeneration, changeTs);
379
+ const signed = await signDocumentChange(
380
+ {
381
+ account: input.account,
382
+ path: input.path ?? "",
383
+ unsignedChange,
384
+ genesis: input.genesis,
385
+ generation,
386
+ capability: input.capability,
387
+ visibility: input.visibility
388
+ },
389
+ input.signer
390
+ );
391
+ return {
392
+ changed: true,
393
+ blobs: signed.publishInput.blobs.map((blob) => ({ cid: blob.cid, data: blob.data })),
394
+ version: signed.changeCid.toString(),
395
+ genesis: signed.genesis,
396
+ generation: signed.generation,
397
+ ts: changeTs,
398
+ depth: Number(decoded.depth ?? 0)
399
+ };
400
+ }
401
+ function changesForOps(ops, content) {
402
+ if (content === void 0 && ops.some((op) => op.type === "MoveBlocks")) {
403
+ throw new Error(
404
+ "content is required with ops that move blocks: pass the content of the document the ops were computed against"
405
+ );
406
+ }
407
+ const prepared = preparableDocumentChanges(ops, content);
408
+ if ("unpreparable" in prepared) throw new UnpreparableDocumentUpdateError(prepared.unpreparable);
409
+ return prepared.changes;
410
+ }
411
+ async function clientBuiltDocumentUpdateBlobs(input) {
412
+ const now = Math.floor((input.now ?? Date.now)());
413
+ const headTs = input.state.headTs;
414
+ const depth = input.state.headDepth + 1;
415
+ const { unsignedBytes, ts } = createChangeOps({
416
+ ops: input.ops,
417
+ genesisCid: CID.parse(input.state.genesis),
418
+ deps: input.state.heads.map((head) => CID.parse(head)),
419
+ depth,
420
+ ts: BigInt(headTs !== void 0 && Number.isFinite(headTs) && headTs >= now ? headTs + 1 : now)
421
+ });
422
+ const change = await createChange(unsignedBytes, input.signer);
423
+ const generation = keptGeneration(input.currentGeneration, Number(ts));
424
+ const version = change.cid.toString();
425
+ const ref = await createVersionRef(
426
+ {
427
+ space: input.account,
428
+ path: input.path ?? "",
429
+ genesis: input.state.genesis,
430
+ version,
431
+ generation,
432
+ capability: input.capability,
433
+ visibility: visibilityToCbor(input.visibility)
434
+ },
435
+ input.signer
436
+ );
437
+ return {
438
+ changed: true,
439
+ blobs: [
440
+ { data: new Uint8Array(change.bytes), cid: version },
441
+ ...ref.blobs.map((blob) => ({ data: blob.data, cid: blob.cid }))
442
+ ],
443
+ version,
444
+ genesis: input.state.genesis,
445
+ generation,
446
+ ts: Number(ts),
447
+ depth
448
+ };
449
+ }
450
+ var DEFAULT_PREPARE_TIMEOUT_MS = 15e3;
451
+ var DEFAULT_MAX_PREPARED_CHANGE_BYTES = 1024 * 1024;
452
+ async function documentUpdateBlobs(input) {
453
+ const { state } = input;
454
+ const unchanged = { changed: false, blobs: [], version: state.version };
455
+ if (!input.ops.length) return unchanged;
456
+ const local = async (localReason) => {
457
+ const built = await clientBuiltDocumentUpdateBlobs({
458
+ signer: input.signer,
459
+ account: input.account,
460
+ path: input.path,
461
+ state: { ...state, headTs: state.headTs ?? await headTimestamp(input.client, state.heads) },
462
+ ops: parentsFirst(input.localOps ?? input.ops),
463
+ capability: input.capability,
464
+ currentGeneration: input.currentGeneration,
465
+ visibility: input.visibility,
466
+ now: input.now
467
+ });
468
+ return { ...built, builtBy: "local", localReason };
469
+ };
470
+ if (input.documentVersion !== void 0 && !sameDocumentVersion(input.documentVersion, state.version)) {
471
+ return local("the document changed while it was being read");
472
+ }
473
+ let changes;
474
+ try {
475
+ const preparable = preparableDocumentChanges(input.ops, input.content);
476
+ if ("unpreparable" in preparable) return local(`the server cannot place the blocks (${preparable.unpreparable})`);
477
+ changes = preparable.changes;
478
+ } catch (error) {
479
+ return local(`the server cannot be sent this update (${errorText(error)})`);
480
+ }
481
+ if (!changes.length) return unchanged;
482
+ const documentKey = `${input.account}${input.path ?? ""}`;
483
+ const silentUntil = unansweredDocuments.get(documentKey);
484
+ if (silentUntil !== void 0) {
485
+ if (silentUntil > Date.now()) return local("the server did not answer an earlier request for this document");
486
+ unansweredDocuments.delete(documentKey);
487
+ }
488
+ const timeoutMs = input.prepareTimeoutMs ?? DEFAULT_PREPARE_TIMEOUT_MS;
489
+ const abort = new AbortController();
490
+ let timer;
491
+ const timedOut = /* @__PURE__ */ Symbol("timed out");
492
+ let unsignedChange;
493
+ try {
494
+ const request = input.client.request(
495
+ "PrepareDocumentChange",
496
+ {
497
+ account: input.account,
498
+ path: input.path ?? "",
499
+ baseVersion: state.version,
500
+ changes,
501
+ capability: input.capability,
502
+ visibility: input.visibility
503
+ },
504
+ { signal: abort.signal }
505
+ );
506
+ request.catch(() => {
507
+ });
508
+ const answer = await Promise.race([
509
+ request,
510
+ new Promise((resolve) => {
511
+ timer = setTimeout(() => {
512
+ abort.abort();
513
+ resolve(timedOut);
514
+ }, timeoutMs);
515
+ })
516
+ ]);
517
+ if (answer === timedOut) {
518
+ unansweredDocuments.set(documentKey, Date.now() + UNANSWERED_DOCUMENT_MS);
519
+ return local(`the server did not answer within ${Math.round(timeoutMs / 100) / 10} s`);
520
+ }
521
+ unsignedChange = answer.unsignedChange;
522
+ } catch (error) {
523
+ const refusal = prepareRefusal(error);
524
+ if (refusal === null) throw error;
525
+ return local(refusal);
526
+ } finally {
527
+ clearTimeout(timer);
528
+ }
529
+ if (isEmptyPreparedChange(unsignedChange)) return unchanged;
530
+ const implausible = implausiblePreparedChange(
531
+ unsignedChange,
532
+ changes,
533
+ input.maxPreparedChangeBytes ?? DEFAULT_MAX_PREPARED_CHANGE_BYTES
534
+ );
535
+ if (implausible) return local(`the server's change is not what was asked for (${implausible})`);
536
+ const signed = await signPreparedChange({ ...input, genesis: state.genesis }, unsignedChange);
537
+ return { ...signed, builtBy: "server" };
538
+ }
539
+ function parentsFirst(ops) {
540
+ const slots = [];
541
+ const placedBy = /* @__PURE__ */ new Map();
542
+ ops.forEach((op, index) => {
543
+ if (op.type !== "MoveBlocks") return;
544
+ slots.push(index);
545
+ for (const block of op.blocks) if (!placedBy.has(block)) placedBy.set(block, index);
546
+ });
547
+ const ordered = [];
548
+ const visiting = /* @__PURE__ */ new Set();
549
+ const visit = (index) => {
550
+ if (ordered.includes(index) || visiting.has(index)) return;
551
+ visiting.add(index);
552
+ const parent = ops[index].parent ?? "";
553
+ const before = parent ? placedBy.get(parent) : void 0;
554
+ if (before !== void 0) visit(before);
555
+ visiting.delete(index);
556
+ ordered.push(index);
557
+ };
558
+ slots.forEach(visit);
559
+ if (ordered.every((index, position) => index === slots[position])) return ops;
560
+ const out = [...ops];
561
+ slots.forEach((slot, position) => {
562
+ out[slot] = ops[ordered[position]];
563
+ });
564
+ return out;
565
+ }
566
+ var unansweredDocuments = /* @__PURE__ */ new Map();
567
+ var UNANSWERED_DOCUMENT_MS = 10 * 6e4;
568
+ function prepareRefusal(error) {
569
+ var _a;
570
+ if (!(error instanceof SeedClientError)) return null;
571
+ const text = `${error.message} ${error.body ?? ""}`;
572
+ if (error.status === 413) return "the server refused the request as too large (HTTP 413)";
573
+ if (error.status === 404 && /Unknown action key/i.test(text)) return "the server has no PrepareDocumentChange";
574
+ if (error.status < 500) return null;
575
+ if (/must be greater than ts of its dependency/.test(text)) {
576
+ return "the server's clock is not past the time of the document's latest change";
577
+ }
578
+ if (/\[(permission_denied|unauthenticated|invalid_argument|not_found|failed_precondition|already_exists|unimplemented|out_of_range)\]/.test(
579
+ text
580
+ ) || /permission|not allowed|unauthori[sz]ed|forbidden/i.test(text)) {
581
+ return null;
582
+ }
583
+ const said = ((_a = /"error"\s*:\s*"((?:[^"\\]|\\.)*)"/.exec(error.body ?? "")) == null ? void 0 : _a[1]) ?? error.message;
584
+ return `the server could not prepare it (HTTP ${error.status}: ${said.slice(0, 200)})`;
585
+ }
586
+ function keptGeneration(current, fresh) {
587
+ if (current === void 0 || current === null) return fresh;
588
+ const generation = Number(current);
589
+ return Number.isFinite(generation) ? generation : fresh;
590
+ }
591
+ function errorText(error) {
592
+ return error instanceof Error ? error.message : String(error);
593
+ }
594
+ function implausiblePreparedChange(unsignedChange, changes, maxBytes = DEFAULT_MAX_PREPARED_CHANGE_BYTES) {
595
+ var _a, _b;
596
+ if (unsignedChange.byteLength > maxBytes) {
597
+ return `it is ${unsignedChange.byteLength} bytes, over the ${maxBytes} this client signs`;
598
+ }
599
+ const moved = /* @__PURE__ */ new Map();
600
+ const replaced = /* @__PURE__ */ new Set();
601
+ const deleted = /* @__PURE__ */ new Set();
602
+ let moves = 0;
603
+ for (const { op } of changes) {
604
+ if (op.case === "moveBlock") {
605
+ moved.set(op.value.blockId, (moved.get(op.value.blockId) ?? 0) + 1);
606
+ moves++;
607
+ } else if (op.case === "replaceBlock") {
608
+ replaced.add(String(op.value.id));
609
+ } else if (op.case === "deleteBlock") {
610
+ deleted.add(op.value);
611
+ }
612
+ }
613
+ const ops = (_a = cborDecode(unsignedChange).body) == null ? void 0 : _a.ops;
614
+ const placedTimes = /* @__PURE__ */ new Map();
615
+ let placed = 0;
616
+ let replaces = 0;
617
+ for (const op of Array.isArray(ops) ? ops : []) {
618
+ const blocks = Array.isArray(op.blocks) ? op.blocks : [];
619
+ if (op.type === "MoveBlocks") {
620
+ for (const block of blocks) {
621
+ const id = String(block);
622
+ const wanted = moved.get(id) ?? 1;
623
+ const times = (placedTimes.get(id) ?? 0) + 1;
624
+ if (times > wanted)
625
+ return `it places block ${id} ${times} times, the request ${wanted === 1 ? "once" : `${wanted} times`}`;
626
+ placedTimes.set(id, times);
627
+ }
628
+ placed += blocks.length;
629
+ } else if (op.type === "DeleteBlocks") {
630
+ for (const block of blocks) {
631
+ if (!deleted.has(String(block))) return `it deletes block ${String(block)}, which the request does not`;
632
+ }
633
+ } else if (op.type === "ReplaceBlock") {
634
+ const id = String((_b = op.block) == null ? void 0 : _b.id);
635
+ if (!replaced.has(id)) return `it replaces block ${id}, which the request does not`;
636
+ replaces++;
637
+ }
638
+ }
639
+ if (placed > moves) return `it places blocks ${placed} times for ${moves} requested`;
640
+ if (replaces > replaced.size) return `it replaces blocks ${replaces} times for ${replaced.size} requested`;
641
+ return null;
642
+ }
643
+ async function headTimestamp(client, heads) {
644
+ try {
645
+ let latest = 0;
646
+ for (const cid of heads) {
647
+ const { value } = await client.request("GetCID", { cid });
648
+ const ts = Number(value == null ? void 0 : value.ts);
649
+ if (!Number.isFinite(ts)) return void 0;
650
+ latest = Math.max(latest, ts);
651
+ }
652
+ return latest;
653
+ } catch {
654
+ return void 0;
655
+ }
656
+ }
657
+
658
+ export {
659
+ documentOperationsToChanges,
660
+ UnpreparableDocumentUpdateError,
661
+ preparableDocumentChanges,
662
+ nativeBlockToProtoBlock,
663
+ isEmptyPreparedChange,
664
+ prepareDocumentUpdateBlobs,
665
+ clientBuiltDocumentUpdateBlobs,
666
+ DEFAULT_PREPARE_TIMEOUT_MS,
667
+ DEFAULT_MAX_PREPARED_CHANGE_BYTES,
668
+ documentUpdateBlobs,
669
+ implausiblePreparedChange
670
+ };