@ternent/ledger 0.1.8 → 0.2.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,988 +1,385 @@
1
- import { canonicalStringify, getCommitSigningPayload, deriveEntryId, deriveCommitId, getCommitChain, validateLedger, getEntrySigningPayload } from "@ternent/concord-protocol";
2
- const LEDGER_FORMAT = "concord-ledger";
3
- const LEDGER_VERSION = "1";
4
- const LEDGER_SPEC = "@ternent/ledger@2";
5
- const textEncoder = new TextEncoder();
6
- const textDecoder = new TextDecoder();
7
- let armourRuntimePromise = null;
8
- let sealRuntimePromise = null;
9
- async function loadArmourRuntime() {
10
- if (!armourRuntimePromise) {
11
- armourRuntimePromise = import("@ternent/armour").then((module) => ({
12
- decryptWithIdentity: module.decryptWithIdentity,
13
- encryptForRecipients: module.encryptForRecipients,
14
- initArmour: module.initArmour
15
- }));
16
- }
17
- return await armourRuntimePromise;
18
- }
19
- async function loadSealRuntime() {
20
- if (!sealRuntimePromise) {
21
- sealRuntimePromise = import("@ternent/seal-cli").then((module) => ({
22
- createSealHash: module.createSealHash,
23
- createSealProof: module.createSealProof,
24
- verifySealProofAgainstBytes: module.verifySealProofAgainstBytes
25
- }));
26
- }
27
- return await sealRuntimePromise;
28
- }
29
- function cloneValue(value) {
30
- if (typeof structuredClone === "function") {
31
- return structuredClone(value);
32
- }
33
- return JSON.parse(JSON.stringify(value));
34
- }
35
- function normalizeMeta(value) {
36
- return value ?? null;
37
- }
38
- function normalizePayloadInput(value) {
39
- return value === void 0 ? null : value;
40
- }
41
- function isRecord(value) {
42
- return Boolean(value) && typeof value === "object" && !Array.isArray(value);
43
- }
44
- function assertRecordOrNull(value, label) {
45
- if (value === null)
46
- return null;
47
- if (!isRecord(value)) {
48
- throw new Error(`${label} must be an object or null.`);
49
- }
50
- return value;
51
- }
52
- function base64UrlEncode(bytes) {
53
- return Buffer.from(bytes).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
54
- }
55
- function base64UrlDecode(value) {
56
- const normalized = value.replace(/-/g, "+").replace(/_/g, "/");
57
- const pad = normalized.length % 4 === 0 ? "" : "=".repeat(4 - normalized.length % 4);
58
- return new Uint8Array(Buffer.from(`${normalized}${pad}`, "base64"));
59
- }
60
- function toCiphertextBytes(payload) {
61
- return payload.encoding === "armor" ? textEncoder.encode(payload.data) : base64UrlDecode(payload.data);
62
- }
63
- function createShadowEntryCore(entry) {
64
- return {
65
- kind: entry.kind,
66
- timestamp: entry.authoredAt,
67
- author: entry.author,
68
- payload: {
69
- meta: entry.meta,
70
- payload: entry.payload
71
- },
72
- signature: null
73
- };
74
- }
75
- function createShadowEntry(entry) {
76
- return {
77
- ...createShadowEntryCore(entry),
78
- signature: JSON.stringify(entry.seal)
79
- };
80
- }
81
- function buildUnsignedEntrySubject(entry) {
82
- return textEncoder.encode(getEntrySigningPayload(createShadowEntryCore(entry)));
83
- }
84
- function createShadowCommit(commit) {
85
- return {
86
- ...createShadowCommitCore(commit),
87
- signature: JSON.stringify(commit.seal)
88
- };
89
- }
90
- function createShadowCommitCore(commit) {
91
- return {
92
- parent: commit.parentCommitId,
93
- timestamp: commit.committedAt,
94
- metadata: commit.metadata,
95
- entries: commit.entryIds,
96
- signature: null
97
- };
98
- }
99
- function createShadowContainer(container) {
100
- const commits = {};
101
- const entries = {};
102
- for (const [commitId, commit] of Object.entries(container.commits)) {
103
- commits[commitId] = createShadowCommit(commit);
104
- }
105
- for (const [entryId, entry] of Object.entries(container.entries)) {
106
- entries[entryId] = createShadowEntry(entry);
107
- }
108
- return {
109
- format: "concord-ledger",
110
- version: "1.0",
111
- commits,
112
- entries,
113
- head: container.head
114
- };
115
- }
116
- function validatePayloadShape(payload) {
117
- if (payload.type === "plain") {
118
- return [];
119
- }
120
- const errors = [];
121
- if (payload.scheme !== "age") {
122
- errors.push("Encrypted payload scheme must be age.");
123
- }
124
- if (payload.mode !== "recipients") {
125
- errors.push("Encrypted payload mode must be recipients.");
126
- }
127
- if (payload.encoding !== "armor" && payload.encoding !== "binary") {
128
- errors.push("Encrypted payload encoding must be armor or binary.");
129
- }
130
- if (typeof payload.data !== "string" || payload.data.length === 0) {
131
- errors.push("Encrypted payload data must be a non-empty string.");
132
- }
133
- if (typeof payload.payloadHash !== "string" || payload.payloadHash.length === 0) {
134
- errors.push("Encrypted payload payloadHash must be a non-empty string.");
135
- }
136
- return errors;
137
- }
138
- function validateEntryShape(entry) {
139
- const errors = [];
140
- if (typeof entry.entryId !== "string" || entry.entryId.length === 0) {
141
- errors.push("Entry.entryId must be a non-empty string.");
142
- }
143
- if (typeof entry.kind !== "string" || entry.kind.length === 0) {
144
- errors.push("Entry.kind must be a non-empty string.");
145
- }
146
- if (typeof entry.authoredAt !== "string" || entry.authoredAt.length === 0) {
147
- errors.push("Entry.authoredAt must be a non-empty string.");
148
- }
149
- if (typeof entry.author !== "string" || entry.author.length === 0) {
150
- errors.push("Entry.author must be a non-empty string.");
151
- }
152
- if (entry.meta !== null && !isRecord(entry.meta)) {
153
- errors.push("Entry.meta must be an object or null.");
154
- }
155
- errors.push(...validatePayloadShape(entry.payload));
156
- if (!isRecord(entry.seal)) {
157
- errors.push("Entry.seal must be an object.");
158
- }
159
- return errors;
160
- }
161
- function validateCommitShape(commit) {
162
- const errors = [];
163
- if (typeof commit.commitId !== "string" || commit.commitId.length === 0) {
164
- errors.push("Commit.commitId must be a non-empty string.");
165
- }
166
- if (commit.parentCommitId !== null && (typeof commit.parentCommitId !== "string" || commit.parentCommitId.length === 0)) {
167
- errors.push("Commit.parentCommitId must be a non-empty string or null.");
168
- }
169
- if (typeof commit.committedAt !== "string" || commit.committedAt.length === 0) {
170
- errors.push("Commit.committedAt must be a non-empty string.");
171
- }
172
- if (commit.metadata !== null && !isRecord(commit.metadata)) {
173
- errors.push("Commit.metadata must be an object or null.");
174
- }
175
- if (!Array.isArray(commit.entryIds)) {
176
- errors.push("Commit.entryIds must be an array.");
177
- } else if (commit.entryIds.some((entryId) => typeof entryId !== "string")) {
178
- errors.push("Commit.entryIds must contain only strings.");
179
- }
180
- if (!isRecord(commit.seal)) {
181
- errors.push("Commit.seal must be an object.");
182
- }
183
- return errors;
184
- }
185
- function validatePublicContainerShape(container) {
186
- const errors = [];
187
- if (container.format !== LEDGER_FORMAT) {
188
- errors.push(`Ledger.format must be "${LEDGER_FORMAT}".`);
189
- }
190
- if (container.version !== LEDGER_VERSION) {
191
- errors.push(`Ledger.version must be "${LEDGER_VERSION}".`);
192
- }
193
- if (!isRecord(container.commits)) {
194
- errors.push("Ledger.commits must be an object.");
195
- }
196
- if (!isRecord(container.entries)) {
197
- errors.push("Ledger.entries must be an object.");
198
- }
199
- if (typeof container.head !== "string" || container.head.length === 0) {
200
- errors.push("Ledger.head must be a non-empty string.");
201
- }
202
- if (errors.length > 0) {
203
- return errors;
204
- }
205
- for (const [commitId, commit] of Object.entries(container.commits)) {
206
- if (commit.commitId !== commitId) {
207
- errors.push(`Commit key mismatch for ${commitId}.`);
208
- }
209
- errors.push(...validateCommitShape(commit));
210
- }
211
- for (const [entryId, entry] of Object.entries(container.entries)) {
212
- if (entry.entryId !== entryId) {
213
- errors.push(`Entry key mismatch for ${entryId}.`);
214
- }
215
- errors.push(...validateEntryShape(entry));
216
- }
217
- if (!container.commits[container.head]) {
218
- errors.push(`Ledger head ${container.head} does not exist in commits.`);
219
- }
220
- return errors;
221
- }
222
- function createDefaultProtocolContract() {
223
- return {
224
- canonicalizePayload(value) {
225
- return canonicalStringify(normalizePayloadInput(value));
226
- },
227
- getEntrySubjectBytes(entry) {
228
- return buildUnsignedEntrySubject(entry);
229
- },
230
- getCommitSubjectBytes(commit) {
231
- return textEncoder.encode(getCommitSigningPayload(createShadowCommitCore(commit)));
232
- },
233
- async deriveEntryId(entry) {
234
- return deriveEntryId(createShadowEntry(entry));
235
- },
236
- async deriveCommitId(commit) {
237
- return deriveCommitId(createShadowCommitCore(commit));
238
- },
239
- getCommitChain(container) {
240
- return getCommitChain(createShadowContainer(container));
241
- },
242
- validateContainer(container) {
243
- const errors = validatePublicContainerShape(container);
244
- if (errors.length > 0) {
245
- return { ok: false, errors };
246
- }
247
- try {
248
- const shadowValidation = validateLedger(createShadowContainer(container), {
249
- strictSpec: false
250
- });
251
- return shadowValidation.ok ? { ok: true, errors: [] } : { ok: false, errors: shadowValidation.errors };
252
- } catch (error) {
253
- return {
254
- ok: false,
255
- errors: [error instanceof Error ? error.message : "Invalid container."]
256
- };
257
- }
258
- }
259
- };
260
- }
261
- function createDefaultSealContract() {
262
- return {
263
- async createEntryProof(input) {
264
- const { createSealHash, createSealProof } = await loadSealRuntime();
265
- return await createSealProof({
266
- createdAt: input.entry.authoredAt,
267
- signer: input.signer,
268
- subject: {
269
- kind: "artifact",
270
- path: `ledger-entry:${input.entry.kind}:${input.entry.authoredAt}`,
271
- hash: await createSealHash(input.subjectBytes)
272
- }
273
- });
274
- },
275
- async verifyEntryProof(input) {
276
- const { verifySealProofAgainstBytes } = await loadSealRuntime();
277
- const result = await verifySealProofAgainstBytes(
278
- input.proof,
279
- input.subjectBytes
280
- );
281
- return result.valid;
282
- },
283
- async createCommitProof(input) {
284
- const { createSealHash, createSealProof } = await loadSealRuntime();
285
- return await createSealProof({
286
- createdAt: input.commit.committedAt,
287
- signer: input.signer,
288
- subject: {
289
- kind: "artifact",
290
- path: `ledger-commit:${input.commitId}`,
291
- hash: await createSealHash(input.subjectBytes)
292
- }
293
- });
294
- },
295
- async verifyCommitProof(input) {
296
- const { verifySealProofAgainstBytes } = await loadSealRuntime();
297
- const result = await verifySealProofAgainstBytes(
298
- input.proof,
299
- input.subjectBytes
300
- );
301
- return result.valid;
302
- }
303
- };
304
- }
305
- function createDefaultArmourContract() {
306
- return {
307
- async encrypt(input) {
308
- const { createSealHash } = await loadSealRuntime();
309
- const { encryptForRecipients, initArmour } = await loadArmourRuntime();
310
- await initArmour();
311
- const ciphertext = await encryptForRecipients({
312
- recipients: input.recipients,
313
- data: input.data,
314
- output: input.encoding
315
- });
316
- return {
317
- data: input.encoding === "armor" ? textDecoder.decode(ciphertext) : base64UrlEncode(ciphertext),
318
- payloadHash: await createSealHash(ciphertext)
319
- };
320
- },
321
- async decrypt(input) {
322
- const { decryptWithIdentity, initArmour } = await loadArmourRuntime();
323
- await initArmour();
324
- const plaintext = await decryptWithIdentity({
325
- identity: input.decryptor.identity,
326
- data: toCiphertextBytes(input.payload)
327
- });
328
- return JSON.parse(textDecoder.decode(plaintext));
329
- }
330
- };
331
- }
332
- function createEmptyProjection(value) {
333
- return cloneValue(value);
334
- }
335
- function createInitialState(initialProjection) {
336
- return {
337
- container: null,
338
- staged: [],
339
- projection: createEmptyProjection(initialProjection),
340
- verification: null
341
- };
342
- }
343
- function sortStrings(values) {
344
- return Array.from(values).sort((left, right) => left.localeCompare(right));
345
- }
346
- function mergeReplayOptions(defaults, options, hasDecryptor) {
347
- const verify = options?.verify ?? defaults?.verify ?? true;
348
- const decrypt = options?.decrypt ?? defaults?.decrypt ?? true;
349
- return {
350
- fromEntryId: options?.fromEntryId ?? "",
351
- toEntryId: options?.toEntryId ?? "",
352
- verify,
353
- decrypt: decrypt && hasDecryptor
354
- };
355
- }
356
- function assertAppendInput(input) {
357
- if (typeof input.kind !== "string" || input.kind.length === 0) {
358
- throw new Error("append input kind is required.");
359
- }
360
- if (input.meta !== void 0) {
361
- assertRecordOrNull(input.meta, "append input meta");
362
- }
363
- if (input.protection?.type === "recipients") {
364
- if (!Array.isArray(input.protection.recipients)) {
365
- throw new Error("append protection recipients must be an array.");
366
- }
367
- if (input.protection.recipients.length === 0) {
368
- throw new Error("append protection recipients must not be empty.");
369
- }
370
- }
371
- }
372
- function assertContainerInput(container) {
373
- const errors = validatePublicContainerShape(container);
374
- if (errors.length > 0) {
375
- throw new Error(errors.join("; "));
376
- }
377
- }
378
- function getCommittedEntriesInOrder(container, protocol) {
379
- const ordered = [];
380
- for (const commitId of protocol.getCommitChain(container)) {
381
- const commit = container.commits[commitId];
382
- if (!commit)
383
- continue;
384
- for (const entryId of commit.entryIds) {
385
- const entry = container.entries[entryId];
386
- if (entry) {
387
- ordered.push(entry);
388
- }
389
- }
390
- }
391
- return ordered;
392
- }
393
- function getProjectionSlice(entries, fromEntryId, toEntryId) {
394
- const startIndex = fromEntryId ? entries.findIndex((entry) => entry.entryId === fromEntryId) : 0;
395
- const endIndex = toEntryId ? entries.findIndex((entry) => entry.entryId === toEntryId) : entries.length - 1;
396
- if (startIndex < 0) {
397
- throw new Error(`from entry not found: ${fromEntryId}`);
398
- }
399
- if (toEntryId && endIndex < 0) {
400
- throw new Error(`to entry not found: ${toEntryId}`);
401
- }
402
- if (entries.length === 0) {
403
- return [];
404
- }
405
- return entries.slice(startIndex, endIndex + 1);
406
- }
407
- async function toReplayEntry(entry, decrypt, identity, armour) {
408
- if (entry.payload.type === "plain") {
409
- return {
410
- entryId: entry.entryId,
411
- kind: entry.kind,
412
- author: entry.author,
413
- authoredAt: entry.authoredAt,
414
- meta: entry.meta,
415
- payload: {
416
- type: "plain",
417
- data: cloneValue(entry.payload.data)
418
- },
419
- verified: true
420
- };
421
- }
422
- if (decrypt && identity.decryptor) {
423
- return {
424
- entryId: entry.entryId,
425
- kind: entry.kind,
426
- author: entry.author,
427
- authoredAt: entry.authoredAt,
428
- meta: entry.meta,
429
- payload: {
430
- type: "decrypted",
431
- original: "encrypted",
432
- data: await armour.decrypt({
433
- payload: entry.payload,
434
- decryptor: identity.decryptor
435
- })
436
- },
437
- verified: true,
438
- decrypted: true
439
- };
440
- }
441
- return {
442
- entryId: entry.entryId,
443
- kind: entry.kind,
444
- author: entry.author,
445
- authoredAt: entry.authoredAt,
446
- meta: entry.meta,
447
- payload: {
448
- type: "encrypted",
449
- scheme: entry.payload.scheme,
450
- mode: entry.payload.mode,
451
- encoding: entry.payload.encoding,
452
- data: entry.payload.data
453
- },
454
- verified: true,
455
- decrypted: false
456
- };
457
- }
458
- function createGenesisCommitDraft(timestamp, metadata) {
459
- return {
460
- parentCommitId: null,
461
- committedAt: timestamp,
462
- metadata: {
463
- genesis: true,
464
- spec: LEDGER_SPEC,
465
- ...metadata ?? {}
466
- },
467
- entryIds: []
468
- };
469
- }
470
- async function createLedger(config) {
471
- const now = config.now ?? (() => (/* @__PURE__ */ new Date()).toISOString());
472
- const protocol = config.protocol ?? createDefaultProtocolContract();
473
- const seal = config.seal ?? createDefaultSealContract();
474
- const armour = config.armour ?? createDefaultArmourContract();
475
- const replayPolicy = config.replayPolicy;
476
- const state = createInitialState(config.initialProjection);
477
- const listeners = /* @__PURE__ */ new Set();
478
- function notify() {
479
- for (const listener of listeners) {
480
- listener(state);
481
- }
482
- }
483
- async function persist() {
484
- if (!config.storage)
485
- return;
486
- const snapshot = {
487
- container: state.container ? cloneValue(state.container) : null,
488
- staged: cloneValue(state.staged)
489
- };
490
- await config.storage.save(snapshot);
491
- }
492
- async function buildCommitRecord(unsignedCommit) {
493
- const subjectBytes = protocol.getCommitSubjectBytes(unsignedCommit);
494
- const commitId = await protocol.deriveCommitId(unsignedCommit);
495
- const sealProof = await seal.createCommitProof({
496
- commit: unsignedCommit,
497
- commitId,
498
- subjectBytes,
499
- signer: config.identity.signer
500
- });
501
- return {
502
- ...unsignedCommit,
503
- commitId,
504
- seal: sealProof
505
- };
506
- }
507
- async function verifySnapshot(container, staged, options) {
508
- if (!container) {
509
- return {
510
- valid: true,
511
- committedHistoryValid: true,
512
- commitChainValid: true,
513
- commitProofsValid: true,
514
- entriesValid: true,
515
- entryProofsValid: true,
516
- payloadHashesValid: true,
517
- proofsValid: true,
518
- invalidCommitIds: [],
519
- invalidEntryIds: []
520
- };
521
- }
522
- const invalidCommitIds = /* @__PURE__ */ new Set();
523
- const invalidEntryIds = /* @__PURE__ */ new Set();
524
- let commitChainValid = true;
525
- let commitProofsValid = true;
526
- let entriesValid = true;
527
- let entryProofsValid = true;
528
- let payloadHashesValid = true;
529
- let proofsValid = true;
530
- let committedEntriesValid = true;
531
- let committedEntryProofsValid = true;
532
- let committedPayloadHashesValid = true;
533
- const containerValidation = protocol.validateContainer(container);
534
- if (!containerValidation.ok) {
535
- commitChainValid = false;
536
- }
537
- const reachableCommitIds = /* @__PURE__ */ new Set();
538
- const reachableEntryIds = /* @__PURE__ */ new Set();
539
- for (const [commitId, commit2] of Object.entries(container.commits)) {
540
- try {
541
- const derivedCommitId = await protocol.deriveCommitId({
542
- parentCommitId: commit2.parentCommitId,
543
- committedAt: commit2.committedAt,
544
- metadata: commit2.metadata,
545
- entryIds: commit2.entryIds
546
- });
547
- if (derivedCommitId !== commitId) {
548
- invalidCommitIds.add(commitId);
549
- commitChainValid = false;
550
- }
551
- } catch {
552
- invalidCommitIds.add(commitId);
553
- commitChainValid = false;
554
- }
555
- if (commit2.parentCommitId !== null && !container.commits[commit2.parentCommitId]) {
556
- invalidCommitIds.add(commitId);
557
- commitChainValid = false;
558
- }
559
- if (options?.includeProofs !== false) {
560
- try {
561
- const proofValid = await seal.verifyCommitProof({
562
- commit: commit2,
563
- subjectBytes: protocol.getCommitSubjectBytes({
564
- parentCommitId: commit2.parentCommitId,
565
- committedAt: commit2.committedAt,
566
- metadata: commit2.metadata,
567
- entryIds: commit2.entryIds
568
- }),
569
- proof: commit2.seal
570
- });
571
- if (!proofValid) {
572
- invalidCommitIds.add(commitId);
573
- commitProofsValid = false;
574
- proofsValid = false;
575
- }
576
- } catch {
577
- invalidCommitIds.add(commitId);
578
- commitProofsValid = false;
579
- proofsValid = false;
580
- }
581
- }
582
- for (const entryId of commit2.entryIds) {
583
- if (!container.entries[entryId]) {
584
- invalidEntryIds.add(entryId);
585
- entriesValid = false;
586
- }
587
- }
588
- }
589
- try {
590
- const chain = protocol.getCommitChain(container);
591
- for (const commitId of chain) {
592
- reachableCommitIds.add(commitId);
593
- for (const entryId of container.commits[commitId]?.entryIds ?? []) {
594
- reachableEntryIds.add(entryId);
595
- }
596
- }
597
- } catch {
598
- invalidCommitIds.add(container.head);
599
- commitChainValid = false;
600
- committedEntriesValid = false;
601
- committedEntryProofsValid = false;
602
- committedPayloadHashesValid = false;
603
- }
604
- const entriesToVerify = [
605
- ...Object.entries(container.entries).map(([recordKey, entry]) => ({
606
- recordKey,
607
- entry
608
- })),
609
- ...staged.map((entry) => ({ recordKey: null, entry }))
610
- ];
611
- for (const { recordKey, entry } of entriesToVerify) {
612
- const isReachableCommittedEntry = recordKey !== null && reachableEntryIds.has(recordKey) || reachableEntryIds.has(entry.entryId);
613
- try {
614
- const derivedEntryId = await protocol.deriveEntryId(entry);
615
- if (derivedEntryId !== entry.entryId) {
616
- invalidEntryIds.add(entry.entryId);
617
- entriesValid = false;
618
- if (isReachableCommittedEntry) {
619
- committedEntriesValid = false;
620
- }
621
- }
622
- } catch {
623
- invalidEntryIds.add(entry.entryId);
624
- entriesValid = false;
625
- if (isReachableCommittedEntry) {
626
- committedEntriesValid = false;
627
- }
628
- }
629
- const subjectBytes = buildUnsignedEntrySubject({
630
- kind: entry.kind,
631
- authoredAt: entry.authoredAt,
632
- author: entry.author,
633
- meta: entry.meta,
634
- payload: entry.payload
635
- });
636
- if (options?.includeProofs !== false) {
637
- try {
638
- const proofValid = await seal.verifyEntryProof({
639
- entry,
640
- subjectBytes,
641
- proof: entry.seal
642
- });
643
- if (!proofValid) {
644
- invalidEntryIds.add(entry.entryId);
645
- entriesValid = false;
646
- entryProofsValid = false;
647
- proofsValid = false;
648
- if (isReachableCommittedEntry) {
649
- committedEntriesValid = false;
650
- committedEntryProofsValid = false;
651
- }
652
- }
653
- } catch {
654
- invalidEntryIds.add(entry.entryId);
655
- entriesValid = false;
656
- entryProofsValid = false;
657
- proofsValid = false;
658
- if (isReachableCommittedEntry) {
659
- committedEntriesValid = false;
660
- committedEntryProofsValid = false;
661
- }
662
- }
663
- }
664
- if (entry.payload.type === "encrypted" && options?.includePayloadHashes !== false) {
665
- try {
666
- const { createSealHash } = await loadSealRuntime();
667
- const payloadHash = await createSealHash(toCiphertextBytes(entry.payload));
668
- if (payloadHash !== entry.payload.payloadHash) {
669
- invalidEntryIds.add(entry.entryId);
670
- entriesValid = false;
671
- payloadHashesValid = false;
672
- if (isReachableCommittedEntry) {
673
- committedEntriesValid = false;
674
- committedPayloadHashesValid = false;
675
- }
676
- }
677
- } catch {
678
- invalidEntryIds.add(entry.entryId);
679
- entriesValid = false;
680
- payloadHashesValid = false;
681
- if (isReachableCommittedEntry) {
682
- committedEntriesValid = false;
683
- committedPayloadHashesValid = false;
684
- }
685
- }
686
- }
687
- }
688
- for (const entryId of reachableEntryIds) {
689
- if (!container.entries[entryId]) {
690
- committedEntriesValid = false;
691
- committedEntryProofsValid = false;
692
- committedPayloadHashesValid = false;
693
- }
694
- }
695
- const committedHistoryValid = commitChainValid && commitProofsValid && committedEntriesValid && committedEntryProofsValid && committedPayloadHashesValid && containerValidation.ok;
696
- return {
697
- valid: committedHistoryValid,
698
- committedHistoryValid,
699
- commitChainValid,
700
- commitProofsValid,
701
- entriesValid,
702
- entryProofsValid,
703
- payloadHashesValid,
704
- proofsValid,
705
- invalidCommitIds: sortStrings(invalidCommitIds),
706
- invalidEntryIds: sortStrings(invalidEntryIds)
707
- };
708
- }
709
- async function verifyCurrent(options) {
710
- return verifySnapshot(state.container, state.staged, options);
711
- }
712
- async function rebuildProjection(options) {
713
- const merged = mergeReplayOptions(
714
- replayPolicy,
715
- options,
716
- !!config.identity.decryptor
717
- );
718
- if (merged.verify) {
719
- const verification = await verifyCurrent();
720
- state.verification = {
721
- valid: verification.valid,
722
- checkedAt: now()
723
- };
724
- notify();
725
- if (!verification.valid) {
726
- throw new Error("Ledger verification failed.");
727
- }
728
- }
729
- let orderedCommitted = [];
730
- if (state.container) {
731
- try {
732
- orderedCommitted = getCommittedEntriesInOrder(state.container, protocol);
733
- } catch (error) {
734
- if (merged.verify) {
735
- throw error;
736
- }
737
- }
738
- }
739
- const orderedEntries = [...orderedCommitted, ...state.staged];
740
- const slice = getProjectionSlice(
741
- orderedEntries,
742
- merged.fromEntryId,
743
- merged.toEntryId
744
- );
745
- let projection = createEmptyProjection(config.initialProjection);
746
- for (const entry of slice) {
747
- projection = config.projector(
748
- projection,
749
- await toReplayEntry(entry, merged.decrypt, config.identity, armour)
750
- );
751
- }
752
- state.projection = projection;
753
- notify();
754
- return projection;
755
- }
756
- async function buildEntryRecord(input) {
757
- assertAppendInput(input);
758
- protocol.canonicalizePayload(input.payload);
759
- const payloadValue = normalizePayloadInput(input.payload);
760
- const meta = normalizeMeta(input.meta);
761
- const authoredAt = now();
762
- const author = await config.identity.authorResolver();
763
- const payload = input.protection?.type === "recipients" ? {
764
- type: "encrypted",
765
- scheme: "age",
766
- mode: "recipients",
767
- encoding: input.protection.encoding ?? "armor",
768
- ...await armour.encrypt({
769
- recipients: config.identity.recipientResolver ? await config.identity.recipientResolver(input.protection.recipients) : input.protection.recipients,
770
- data: textEncoder.encode(protocol.canonicalizePayload(payloadValue)),
771
- encoding: input.protection.encoding ?? "armor"
772
- })
773
- } : {
774
- type: "plain",
775
- data: cloneValue(payloadValue)
776
- };
777
- const unsignedEntry = {
778
- kind: input.kind,
779
- authoredAt,
780
- author,
781
- meta,
782
- payload
783
- };
784
- const subjectBytes = buildUnsignedEntrySubject(unsignedEntry);
785
- const sealProof = await seal.createEntryProof({
786
- entry: unsignedEntry,
787
- subjectBytes,
788
- signer: config.identity.signer
789
- });
790
- const draft = {
791
- entryId: "",
792
- ...unsignedEntry,
793
- seal: sealProof
794
- };
795
- return {
796
- ...draft,
797
- entryId: await protocol.deriveEntryId(draft)
798
- };
799
- }
800
- function assertContainerExists() {
801
- if (!state.container) {
802
- throw new Error("Ledger has not been created or loaded.");
803
- }
804
- return state.container;
805
- }
806
- async function stageEntries(inputs) {
807
- const container = assertContainerExists();
808
- const existingIds = /* @__PURE__ */ new Set([
809
- ...Object.keys(container.entries),
810
- ...state.staged.map((entry) => entry.entryId)
811
- ]);
812
- const entries = [];
813
- for (const input of inputs) {
814
- const entry = await buildEntryRecord(input);
815
- if (existingIds.has(entry.entryId)) {
816
- throw new Error(`Entry ${entry.entryId} already exists.`);
817
- }
818
- existingIds.add(entry.entryId);
819
- entries.push(entry);
820
- }
821
- const baseCount = state.staged.length;
822
- state.staged = [...state.staged, ...entries];
823
- const results = entries.map((entry, index) => ({
824
- entry,
825
- stagedCount: baseCount + index + 1
826
- }));
827
- if (config.autoCommit && entries.length > 0) {
828
- await commit();
829
- return results;
830
- }
831
- await rebuildProjection();
832
- await persist();
833
- return results;
834
- }
835
- async function create(params) {
836
- const genesis = await buildCommitRecord(
837
- createGenesisCommitDraft(now(), normalizeMeta(params?.metadata))
838
- );
839
- state.container = {
840
- format: LEDGER_FORMAT,
841
- version: LEDGER_VERSION,
842
- commits: {
843
- [genesis.commitId]: genesis
844
- },
845
- entries: {},
846
- head: genesis.commitId
847
- };
848
- state.staged = [];
849
- state.verification = null;
850
- await rebuildProjection();
851
- await persist();
852
- }
853
- async function load(container) {
854
- assertContainerInput(container);
855
- state.container = cloneValue(container);
856
- state.staged = [];
857
- state.verification = null;
858
- await rebuildProjection();
859
- await persist();
860
- }
861
- async function loadFromStorage() {
862
- if (!config.storage) {
863
- return false;
864
- }
865
- const snapshot = await config.storage.load();
866
- if (!snapshot) {
867
- return false;
868
- }
869
- if (snapshot.container) {
870
- assertContainerInput(snapshot.container);
871
- }
872
- for (const stagedEntry of snapshot.staged) {
873
- const errors = validateEntryShape(stagedEntry);
874
- if (errors.length > 0) {
875
- throw new Error(errors.join("; "));
876
- }
877
- }
878
- state.container = snapshot.container ? cloneValue(snapshot.container) : null;
879
- state.staged = cloneValue(snapshot.staged);
880
- state.verification = null;
881
- await rebuildProjection();
882
- return true;
883
- }
884
- async function append(input) {
885
- const [result] = await stageEntries([input]);
886
- return result;
887
- }
888
- async function appendMany(inputs) {
889
- if (inputs.length === 0) {
890
- return [];
891
- }
892
- return stageEntries(inputs);
893
- }
894
- async function commit(input) {
895
- const container = assertContainerExists();
896
- if (state.staged.length === 0) {
897
- throw new Error("No staged entries to commit.");
898
- }
899
- const staged = cloneValue(state.staged);
900
- const entries = { ...container.entries };
901
- for (const entry of staged) {
902
- entries[entry.entryId] = entry;
903
- }
904
- const unsignedCommit = {
905
- parentCommitId: container.head,
906
- committedAt: now(),
907
- metadata: normalizeMeta(input?.metadata),
908
- entryIds: staged.map((entry) => entry.entryId)
909
- };
910
- const commitRecord = await buildCommitRecord(unsignedCommit);
911
- state.container = {
912
- format: container.format,
913
- version: container.version,
914
- commits: {
915
- ...container.commits,
916
- [commitRecord.commitId]: commitRecord
917
- },
918
- entries,
919
- head: commitRecord.commitId
920
- };
921
- state.staged = [];
922
- await rebuildProjection();
923
- await persist();
924
- return {
925
- commit: cloneValue(commitRecord),
926
- committedEntries: staged,
927
- committedEntryIds: staged.map((entry) => entry.entryId)
928
- };
929
- }
930
- async function replay(options) {
931
- return rebuildProjection(options);
932
- }
933
- async function recompute() {
934
- return rebuildProjection();
935
- }
936
- async function verify(options) {
937
- return verifyCurrent(options);
938
- }
939
- async function exportContainer() {
940
- const container = assertContainerExists();
941
- return cloneValue(container);
942
- }
943
- async function importContainer(container) {
944
- await load(container);
945
- }
946
- function getState() {
947
- return state;
948
- }
949
- function subscribe(listener) {
950
- listeners.add(listener);
951
- return () => {
952
- listeners.delete(listener);
953
- };
954
- }
955
- async function clearStaged() {
956
- state.staged = [];
957
- await rebuildProjection();
958
- await persist();
959
- }
960
- async function destroy() {
961
- state.container = null;
962
- state.staged = [];
963
- state.projection = createEmptyProjection(config.initialProjection);
964
- state.verification = null;
965
- notify();
966
- }
967
- return {
968
- create,
969
- load,
970
- loadFromStorage,
971
- append,
972
- appendMany,
973
- commit,
974
- replay,
975
- recompute,
976
- verify,
977
- export: exportContainer,
978
- import: importContainer,
979
- getState,
980
- subscribe,
981
- clearStaged,
982
- destroy
983
- };
984
- }
985
- export {
986
- createLedger
987
- };
988
- //# sourceMappingURL=index.js.map
1
+ import { C as parseJson, D as Fault, S as encodeJson, _ as appendInput, b as timestamp, c as hashLedgerEntry, d as inspectProtocol, f as ledgerSignatureMessage, g as verifyLedger, h as verifyDocument, i as compareLedgers, j as fail, l as identifier, m as signatureMessage, n as detached, p as orderedEntries, s as hashLedgerCommit, t as nonce, u as inspectLedger, v as limits, x as canonicalize, y as snapshot } from "./protocol-Cx0QN0oK.js";
2
+ import { decodeBase64Url, encodeBase64Url, validatePublicIdentity } from "@ternent/identity";
3
+
4
+ // src/ledger.ts
5
+ function optionsObject(value) {
6
+ return value !== null && typeof value === "object" && !Array.isArray(value);
7
+ }
8
+ async function createLedger(config = {}) {
9
+ if (!optionsObject(config) || Object.keys(config).some((key) => ![
10
+ "signer",
11
+ "limits",
12
+ "now",
13
+ "initialProjection",
14
+ "projector"
15
+ ].includes(key)) || "initialProjection" in config !== "projector" in config) fail("HOST_CONFIGURATION", "requirements");
16
+ const lim = limits(config.limits);
17
+ const copy = (value) => parseJson(encodeJson(value, lim.maxDepth), lim.maxDepth, lim.maxBytes);
18
+ const initial = detached(copy("initialProjection" in config ? config.initialProjection : []));
19
+ const projector = "projector" in config ? config.projector : (projection, entry) => [...projection, entry];
20
+ if (typeof projector !== "function" || config.now !== void 0 && typeof config.now !== "function") fail("HOST_CONFIGURATION", "requirements");
21
+ const now = config.now ?? (() => (/* @__PURE__ */ new Date()).toISOString());
22
+ const signer = config.signer && {
23
+ publicIdentity: detached(config.signer.publicIdentity),
24
+ sign: config.signer.sign
25
+ };
26
+ if (signer && (!validatePublicIdentity(signer.publicIdentity).ok || typeof signer.sign !== "function")) fail("HOST_CONFIGURATION", "requirements");
27
+ let state = detached({
28
+ container: null,
29
+ staged: [],
30
+ projection: initial,
31
+ verification: null
32
+ });
33
+ let queue = Promise.resolve();
34
+ let callbacks = 0;
35
+ let destroyed = false;
36
+ const listeners = /* @__PURE__ */ new Set();
37
+ const call = (fn) => {
38
+ callbacks++;
39
+ try {
40
+ return fn();
41
+ } finally {
42
+ callbacks--;
43
+ }
44
+ };
45
+ const clock = () => {
46
+ const value = call(now);
47
+ timestamp(value);
48
+ return value;
49
+ };
50
+ function submit(prepare) {
51
+ try {
52
+ if (callbacks) fail("HOST_CONFIGURATION", "requirements");
53
+ if (destroyed) fail("LEDGER_DESTROYED", "author");
54
+ const body = prepare();
55
+ const pending = queue.then(() => {
56
+ if (destroyed) fail("LEDGER_DESTROYED", "author");
57
+ return body();
58
+ });
59
+ queue = pending.then(() => void 0, () => void 0);
60
+ return pending;
61
+ } catch (cause) {
62
+ return Promise.reject(cause);
63
+ }
64
+ }
65
+ function publish(next) {
66
+ state = detached(next);
67
+ for (const listener of listeners) try {
68
+ call(() => listener(state));
69
+ } catch {}
70
+ }
71
+ function created() {
72
+ if (!state.container) fail("LEDGER_NOT_CREATED", "author");
73
+ return state.container;
74
+ }
75
+ function writer() {
76
+ if (!signer) fail("READ_ONLY_RUNTIME", "author");
77
+ return signer;
78
+ }
79
+ function project(container, staged) {
80
+ let projection = detached(initial);
81
+ const reduce = (entry, commitId) => {
82
+ const event = detached({
83
+ ...entry.subject,
84
+ entryId: entry.id,
85
+ commitId,
86
+ committed: commitId !== null
87
+ });
88
+ projection = detached(copy(call(() => projector(projection, event))));
89
+ };
90
+ for (const { commit, entry } of orderedEntries(container)) reduce(entry, commit.id);
91
+ for (const entry of staged) reduce(entry, null);
92
+ return projection;
93
+ }
94
+ async function verified(bytes) {
95
+ const result = await inspectProtocol(bytes, { limits: lim });
96
+ if (!result.snapshot) throw new Fault(result.report.findings[0]);
97
+ return {
98
+ container: detached(result.snapshot),
99
+ report: detached(result.report)
100
+ };
101
+ }
102
+ function metadata(input) {
103
+ if (!optionsObject(input) || Object.keys(input).some((key) => key !== "metadata")) fail("SCHEMA_INVALID", "input");
104
+ const value = input.metadata ?? null;
105
+ if (value !== null && (typeof value !== "object" || Array.isArray(value))) fail("SCHEMA_INVALID", "input");
106
+ if (encodeJson(value, lim.maxDepth).length > lim.maxMetadataBytes) fail("RESOURCE_LIMIT", "input");
107
+ return value;
108
+ }
109
+ async function candidate(base, entries, meta) {
110
+ const identity = writer();
111
+ const subject = {
112
+ version: 1,
113
+ suite: "ledger-ed25519-v1",
114
+ parent: base?.head ?? null,
115
+ nonce: nonce(),
116
+ signer: identity.publicIdentity,
117
+ committedAt: clock(),
118
+ entryIds: entries.map((entry) => entry.id),
119
+ metadata: meta
120
+ };
121
+ const id = identifier(subject, "commit", lim.maxDepth);
122
+ const commit = {
123
+ id,
124
+ subject,
125
+ signature: encodeBase64Url(/* @__PURE__ */ new Uint8Array(64))
126
+ };
127
+ const container = {
128
+ format: "ledger",
129
+ version: 1,
130
+ documentId: base?.documentId ?? id,
131
+ head: id,
132
+ commits: [...base?.commits ?? [], commit],
133
+ entries: [...base?.entries ?? [], ...entries]
134
+ };
135
+ if (encodeJson(container, lim.maxDepth).length > lim.maxBytes) fail("RESOURCE_LIMIT", "author");
136
+ snapshot(container, lim);
137
+ const message = signatureMessage(subject, lim.maxDepth);
138
+ let signature;
139
+ try {
140
+ signature = await call(() => identity.sign(message));
141
+ } catch {
142
+ fail("SIGNING_FAILED", "author");
143
+ }
144
+ if (!signature.ok || !(signature.value instanceof Uint8Array) || signature.value.length !== 64) fail("SIGNING_FAILED", "author");
145
+ commit.signature = encodeBase64Url(signature.value);
146
+ return {
147
+ ...await verified(encodeJson(container, lim.maxDepth)),
148
+ commit
149
+ };
150
+ }
151
+ function load(input) {
152
+ return submit(() => {
153
+ if (input instanceof Uint8Array && input.byteLength > lim.maxBytes) fail("RESOURCE_LIMIT", "input");
154
+ const bytes = input instanceof Uint8Array ? new Uint8Array(input) : encodeJson(input, lim.maxDepth);
155
+ return async () => {
156
+ if (state.staged.length) fail("DRAFT_PENDING", "author");
157
+ const next = await verified(bytes);
158
+ publish({
159
+ container: next.container,
160
+ verification: next.report,
161
+ staged: [],
162
+ projection: project(next.container, [])
163
+ });
164
+ };
165
+ });
166
+ }
167
+ function makeEntries(parent, inputs) {
168
+ const identity = writer();
169
+ return inputs.map((input) => {
170
+ const subject = {
171
+ version: 1,
172
+ parent,
173
+ nonce: input.nonce ?? nonce(),
174
+ kind: input.kind,
175
+ author: identity.publicIdentity.id,
176
+ authoredAt: clock(),
177
+ meta: input.meta ?? null,
178
+ payload: {
179
+ type: "plain",
180
+ data: input.payload ?? null
181
+ }
182
+ };
183
+ return {
184
+ id: identifier(subject, "entry", lim.maxDepth),
185
+ subject
186
+ };
187
+ });
188
+ }
189
+ function uniqueNonces(entries) {
190
+ if (new Set(entries.map((entry) => entry.subject.nonce)).size !== entries.length) fail("SCHEMA_INVALID", "author", "/nonce");
191
+ }
192
+ function appendBatch(inputs) {
193
+ return submit(() => {
194
+ const captured = copy(inputs);
195
+ if (!Array.isArray(captured) || !captured.length) fail("NO_ENTRIES", "author");
196
+ for (const input of captured) appendInput(input, lim);
197
+ return () => {
198
+ const base = created();
199
+ if (base.entries.length + state.staged.length + captured.length > lim.maxEntries) fail("RESOURCE_LIMIT", "author");
200
+ const entries = makeEntries(base.head, captured);
201
+ const staged = [...state.staged, ...entries];
202
+ uniqueNonces(staged);
203
+ if (encodeJson({
204
+ ...base,
205
+ entries: [...base.entries, ...staged]
206
+ }, lim.maxDepth).length > lim.maxBytes) fail("RESOURCE_LIMIT", "author");
207
+ publish({
208
+ ...state,
209
+ staged,
210
+ projection: project(base, staged)
211
+ });
212
+ return {
213
+ entries: detached(entries),
214
+ stagedCount: staged.length
215
+ };
216
+ };
217
+ });
218
+ }
219
+ return Object.freeze({
220
+ create(input = {}) {
221
+ return submit(() => {
222
+ const captured = copy(input);
223
+ if (!optionsObject(captured) || Object.keys(captured).some((key) => !["metadata", "entries"].includes(key))) fail("SCHEMA_INVALID", "input");
224
+ const meta = metadata(captured.metadata === void 0 ? {} : { metadata: captured.metadata });
225
+ const inputs = captured.entries ?? [];
226
+ if (!Array.isArray(inputs) || inputs.length > lim.maxEntries) fail("RESOURCE_LIMIT", "input");
227
+ for (const entry of inputs) appendInput(entry, lim);
228
+ return async () => {
229
+ if (state.container) fail("LEDGER_ALREADY_CREATED", "author");
230
+ const entries = makeEntries(null, inputs);
231
+ uniqueNonces(entries);
232
+ const next = await candidate(null, entries, meta);
233
+ publish({
234
+ container: next.container,
235
+ staged: [],
236
+ projection: project(next.container, []),
237
+ verification: next.report
238
+ });
239
+ };
240
+ });
241
+ },
242
+ load,
243
+ import: load,
244
+ async append(input) {
245
+ const result = await appendBatch([input]);
246
+ return {
247
+ entry: result.entries[0],
248
+ stagedCount: result.stagedCount
249
+ };
250
+ },
251
+ async appendMany(inputs) {
252
+ return (await appendBatch(inputs)).entries;
253
+ },
254
+ commit(input = {}) {
255
+ return submit(() => {
256
+ const meta = metadata(copy(input));
257
+ return async () => {
258
+ const base = created();
259
+ if (!state.staged.length) fail("NO_ENTRIES", "author");
260
+ const entries = state.staged;
261
+ const next = await candidate(base, entries, meta);
262
+ const projection = project(next.container, []);
263
+ publish({
264
+ container: next.container,
265
+ staged: [],
266
+ projection,
267
+ verification: next.report
268
+ });
269
+ return detached({
270
+ commit: next.commit,
271
+ committedEntries: entries,
272
+ committedEntryIds: next.commit.subject.entryIds
273
+ });
274
+ };
275
+ });
276
+ },
277
+ replay(options = {}) {
278
+ return submit(() => {
279
+ const captured = copy(options);
280
+ if (!optionsObject(captured) || Object.keys(captured).some((key) => key !== "includeStaged") || captured.includeStaged !== void 0 && typeof captured.includeStaged !== "boolean") fail("HOST_CONFIGURATION", "requirements");
281
+ return () => project(created(), captured.includeStaged === false ? [] : state.staged);
282
+ });
283
+ },
284
+ recompute() {
285
+ return submit(() => () => {
286
+ const projection = project(created(), state.staged);
287
+ publish({
288
+ ...state,
289
+ projection
290
+ });
291
+ return projection;
292
+ });
293
+ },
294
+ verify() {
295
+ return submit(() => () => verifyDocument(encodeJson(created(), lim.maxDepth), { limits: lim }));
296
+ },
297
+ export() {
298
+ return submit(() => () => detached(created()));
299
+ },
300
+ getState: () => state,
301
+ subscribe(listener) {
302
+ if (destroyed || typeof listener !== "function") fail("HOST_CONFIGURATION", "requirements");
303
+ listeners.add(listener);
304
+ try {
305
+ call(() => listener(state));
306
+ } catch {}
307
+ return () => {
308
+ listeners.delete(listener);
309
+ };
310
+ },
311
+ clearStaged() {
312
+ return submit(() => () => publish({
313
+ ...state,
314
+ staged: [],
315
+ projection: project(created(), [])
316
+ }));
317
+ },
318
+ destroy() {
319
+ return submit(() => () => {
320
+ destroyed = true;
321
+ publish({
322
+ container: null,
323
+ staged: [],
324
+ projection: initial,
325
+ verification: null
326
+ });
327
+ listeners.clear();
328
+ });
329
+ }
330
+ });
331
+ }
332
+
333
+ // src/payload.ts
334
+ const validId = (id) => typeof id === "string" && /^[a-z][a-z0-9.-]{0,127}$/.test(id);
335
+ function codecId(codec) {
336
+ if (!codec || !validId(codec.id)) fail("HOST_CONFIGURATION", "requirements");
337
+ return codec.id;
338
+ }
339
+ /** Encode portable JSON before appending it through the ordinary Ledger API. */
340
+ async function encodePayload(data, codec, options) {
341
+ const lim = limits(options), id = codecId(codec), encode = codec.encode;
342
+ if (typeof encode !== "function") fail("HOST_CONFIGURATION", "requirements");
343
+ const plaintext = encodeJson(data, lim.maxDepth);
344
+ if (plaintext.byteLength > lim.maxBytes) fail("RESOURCE_LIMIT", "input");
345
+ const encoded = await encode(plaintext);
346
+ if (!(encoded instanceof Uint8Array)) fail("PAYLOAD_CODEC_INVALID", "input");
347
+ if (encoded.byteLength > lim.maxBytes) fail("RESOURCE_LIMIT", "input");
348
+ const payload = {
349
+ format: "ledger-payload",
350
+ version: 1,
351
+ codec: id,
352
+ data: encodeBase64Url(encoded)
353
+ };
354
+ if (encodeJson(payload, lim.maxDepth).byteLength > lim.maxBytes) fail("RESOURCE_LIMIT", "input");
355
+ return detached(payload);
356
+ }
357
+ /** Decode a replayed payload without changing the signed entry or asserting trust. */
358
+ async function decodePayload(payload, codec, options) {
359
+ const lim = limits(options);
360
+ const data = parseJson(encodeJson(payload, lim.maxDepth), lim.maxDepth, lim.maxBytes);
361
+ if (!data || typeof data !== "object" || Array.isArray(data) || data.format !== "ledger-payload") return detached({
362
+ status: "plain",
363
+ data
364
+ });
365
+ if (Object.keys(data).length !== 4 || data.version !== 1 || !validId(data.codec) || typeof data.data !== "string") fail("PAYLOAD_INVALID", "input");
366
+ const encoded = decodeBase64Url(data.data);
367
+ if (!encoded.ok) fail("PAYLOAD_INVALID", "input");
368
+ const locked = () => detached({
369
+ status: "locked",
370
+ codec: data.codec
371
+ });
372
+ if (!codec || codecId(codec) !== data.codec || codec.decode === void 0) return locked();
373
+ const decode = codec.decode;
374
+ if (typeof decode !== "function") fail("HOST_CONFIGURATION", "requirements");
375
+ const plaintext = await decode(encoded.value);
376
+ if (plaintext === null) return locked();
377
+ if (!(plaintext instanceof Uint8Array)) fail("PAYLOAD_CODEC_INVALID", "input");
378
+ return detached({
379
+ status: "decoded",
380
+ data: parseJson(plaintext, lim.maxDepth, lim.maxBytes)
381
+ });
382
+ }
383
+
384
+ export { Fault, canonicalize, compareLedgers, createLedger, decodePayload, encodeJson, encodePayload, hashLedgerCommit, hashLedgerEntry, inspectLedger, ledgerSignatureMessage, parseJson, verifyLedger };
385
+ //# sourceMappingURL=index.js.map