@drfed/models 0.2.0-dev.717 → 0.2.0-dev.719

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.
@@ -1,6 +1,92 @@
1
- import { J as RevisionAddressing, P as NewActivityPubObject, Y as RevisionEmbedding, Z as RevisionRelation, q as ResourceRevision, r as Transaction, t as Database } from "./db-CcbUSnp2.mjs";
1
+ import { $ as RevisionRelation, J as ResourceRevision, P as NewActivityPubObject, X as RevisionEmbedding, Y as RevisionAddressing, Z as RevisionExpansion, r as Transaction, t as Database } from "./db-Al_MT-L_.mjs";
2
2
  import { t as Uuid } from "./uuid-CKMzlIND.mjs";
3
+ import { t as DocumentExpansion } from "./expansion-p4BoMDVd.mjs";
3
4
  import { AddressingInput, AddressingOccurrence } from "./resource.mjs";
5
+ import "drizzle-orm/pg-core";
6
+ //#region src/revision-expansion.d.ts
7
+ /**
8
+ * The expansion of a new snapshot revision's document, computed by the caller
9
+ * before the transaction that stores it.
10
+ */
11
+ type RevisionExpansionInput = Exclude<DocumentExpansion, {
12
+ readonly outcome: "no_document";
13
+ }> & {
14
+ /**
15
+ * The revision whose expanded document this one was taken from, for an
16
+ * object embedded in a received activity.
17
+ */
18
+ readonly sourceRevisionId?: Uuid;
19
+ };
20
+ /** A revision the backfill has not reached, as {@link listUnexpandedRevisions} lists it. */
21
+ interface UnexpandedRevision {
22
+ readonly id: Uuid;
23
+ readonly resourceId: Uuid;
24
+ /** The IRI of the revision's resource. */
25
+ readonly resourceIri: string;
26
+ readonly kind: ResourceRevision["kind"];
27
+ readonly capture: ResourceRevision["capture"];
28
+ readonly document: unknown;
29
+ }
30
+ /**
31
+ * Lists revisions without an expansion, in ID order.
32
+ * @param db The database.
33
+ * @param options Where to continue from, and how many to list.
34
+ * @returns Up to `limit` revisions after `after`.
35
+ */
36
+ declare function listUnexpandedRevisions(db: Database | Transaction, options: {
37
+ readonly after?: Uuid;
38
+ readonly limit: number;
39
+ }): Promise<UnexpandedRevision[]>;
40
+ /**
41
+ * Lists snapshot revisions whose expansion failed, in ID order, so that a
42
+ * failure such as a context that could not be loaded can be retried.
43
+ * @param db The database.
44
+ * @param options Where to continue from, and how many to list.
45
+ * @returns Up to `limit` revisions after `after`.
46
+ */
47
+ declare function listFailedRevisions(db: Database | Transaction, options: {
48
+ readonly after?: Uuid;
49
+ readonly limit: number;
50
+ }): Promise<UnexpandedRevision[]>;
51
+ /**
52
+ * Finds the revision of the activity that first carried an embedded object,
53
+ * the one its typed row names, which an embedded revision's expansion is
54
+ * taken from.
55
+ * @param db The database.
56
+ * @param objectId The embedded object's resource.
57
+ * @returns The activity's first revision, or null if there is none.
58
+ */
59
+ declare function findCarryingActivityRevision(db: Database | Transaction, objectId: Uuid): Promise<{
60
+ readonly id: Uuid;
61
+ readonly document: unknown;
62
+ } | null>;
63
+ /**
64
+ * Records the expansion of a revision that has none. An existing row is kept,
65
+ * so that the backfill can run again or alongside new writes.
66
+ * @param db The database.
67
+ * @param revisionId The revision.
68
+ * @param expansion Its expansion, or null for a revision without a document,
69
+ * which must be `unavailable` or a `whiteout`.
70
+ * @returns The outcome of the row inserted, which is `failed` for an
71
+ * expansion JSON cannot hold, or null if the revision already had
72
+ * one.
73
+ * @throws {TypeError} If the revision does not exist, or the expansion does
74
+ * not suit its kind.
75
+ */
76
+ declare function recordRevisionExpansion(db: Database | Transaction, revisionId: Uuid, expansion: RevisionExpansionInput | null): Promise<RevisionExpansion["outcome"] | null>;
77
+ /**
78
+ * Replaces a failed expansion of a revision, as when a context that could not
79
+ * be loaded before now loads. A row that is no longer failed, because
80
+ * another writer replaced it first, is kept.
81
+ * @param db The database.
82
+ * @param revisionId The revision.
83
+ * @param expansion Its new expansion.
84
+ * @returns The outcome of the row replaced, or null if it was not failed.
85
+ * @throws {TypeError} If the revision does not exist, or the expansion does
86
+ * not suit its kind.
87
+ */
88
+ declare function retryRevisionExpansion(db: Database | Transaction, revisionId: Uuid, expansion: RevisionExpansionInput | null): Promise<RevisionExpansion["outcome"] | null>;
89
+ //#endregion
4
90
  //#region src/revision-conflict-error.d.ts
5
91
  /** The caller's expected current revision no longer matches the database. */
6
92
  declare class RevisionConflictError extends Error {
@@ -25,14 +111,25 @@ declare class ResourceRevisionStateError extends Error {
25
111
  }
26
112
  //#endregion
27
113
  //#region src/legacy-resource-revision.d.ts
114
+ /** Options for {@link captureLegacyResourceRevision}. */
115
+ interface CaptureLegacyResourceRevisionOptions {
116
+ /**
117
+ * The expansion of the typed row's document, computed before the
118
+ * transaction. When omitted, a captured snapshot is expanded offline within
119
+ * the transaction.
120
+ */
121
+ readonly expansion?: RevisionExpansionInput;
122
+ }
28
123
  /**
29
124
  * Captures fully written legacy typed state within its creating transaction.
30
125
  * This trusted compatibility operation performs no authorization or fetching.
31
126
  * Repeated calls return the original revision only when the typed state agrees.
127
+ * Revisions of the resource without an expansion get one, so that a capture
128
+ * reusing a revision made before expansions were stored records it too.
32
129
  * @returns The first retained revision ID, including an unavailable snapshot.
33
130
  * @throws {LegacyResourceRevisionError} When typed state cannot be captured.
34
131
  */
35
- declare function captureLegacyResourceRevision(tx: Transaction, resourceId: Uuid): Promise<Uuid>;
132
+ declare function captureLegacyResourceRevision(tx: Transaction, resourceId: Uuid, options?: CaptureLegacyResourceRevisionOptions): Promise<Uuid>;
36
133
  //#endregion
37
134
  //#region src/resource-revision.d.ts
38
135
  /** A value representable by JSON, without implicit coercion. */
@@ -81,6 +178,14 @@ type AppendResourceRevisionInput = AppendBase & ({
81
178
  /** Embedded documents whose source is known, each path once. */
82
179
  readonly embeddings?: readonly RevisionEmbeddingInput[];
83
180
  readonly projection?: ResourceRevision["projection"];
181
+ /**
182
+ * The document's expansion. When omitted, the document is expanded
183
+ * offline, from preloaded contexts only, before this function opens
184
+ * its transaction, or within the caller's. A document that needs
185
+ * remote contexts must be expanded before the caller's transaction
186
+ * and passed here, since none is fetched within it.
187
+ */
188
+ readonly expansion?: RevisionExpansionInput;
84
189
  } | {
85
190
  readonly kind: "whiteout";
86
191
  readonly deleted: Temporal.Instant;
@@ -96,9 +201,15 @@ interface StoredResourceRevision extends ResourceRevision {
96
201
  * The caller must validate the document and authorize the write. Lock multiple
97
202
  * canonical IRIs in sorted order before composing several appends in one transaction.
98
203
  * This does not publish, change collection membership, or reserve delivery.
204
+ * The revision's expansion is stored with it; see the `expansion` input.
99
205
  * @returns The stored revision, including protected blind addressing.
100
206
  */
101
207
  declare function appendResourceRevision(db: Database | Transaction, input: AppendResourceRevisionInput): Promise<StoredResourceRevision>;
208
+ /**
209
+ * Loads the recorded expansion of a revision's document.
210
+ * @returns The expansion, or null if the revision has not been expanded.
211
+ */
212
+ declare function loadRevisionExpansion(db: Database | Transaction, revisionId: Uuid): Promise<RevisionExpansion | null>;
102
213
  /**
103
214
  * Loads protected local JSON without applying authorization or stripping bto/bcc.
104
215
  * @returns The immutable revision and projections, or null if not found.
@@ -134,6 +245,8 @@ type TypedResourceRevisionInput = TypedRevisionBase & ({
134
245
  /** Embedded documents whose source is known, each path once. */
135
246
  readonly embeddings?: readonly RevisionEmbeddingInput[];
136
247
  readonly projection?: ResourceRevision["projection"];
248
+ /** As for {@link appendResourceRevision}. */
249
+ readonly expansion?: RevisionExpansionInput;
137
250
  } | {
138
251
  readonly kind: "whiteout";
139
252
  readonly deleted: Temporal.Instant;
@@ -158,5 +271,5 @@ type TypedResourceRevisionInput = TypedRevisionBase & ({
158
271
  */
159
272
  declare function writeTypedResourceRevision(db: Database | Transaction, input: TypedResourceRevisionInput): Promise<StoredResourceRevision>;
160
273
  //#endregion
161
- export { RevisionConflictError as _, RevisionRelationInput as a, TypedResourceRevisionInput as c, loadCurrentResourceRevision as d, loadResourceRevision as f, LegacyResourceRevisionError as g, ResourceRevisionStateError as h, RevisionEmbeddingInput as i, appendResourceRevision as l, captureLegacyResourceRevision as m, JsonObject as n, StoredResourceRevision as o, writeTypedResourceRevision as p, JsonValue as r, TypedObjectColumns as s, AppendResourceRevisionInput as t, listResourceRevisions as u };
162
- //# sourceMappingURL=resource-revision-rDmHhNCj.d.mts.map
274
+ export { listFailedRevisions as C, retryRevisionExpansion as E, findCarryingActivityRevision as S, recordRevisionExpansion as T, ResourceRevisionStateError as _, RevisionRelationInput as a, RevisionExpansionInput as b, TypedResourceRevisionInput as c, loadCurrentResourceRevision as d, loadResourceRevision as f, captureLegacyResourceRevision as g, CaptureLegacyResourceRevisionOptions as h, RevisionEmbeddingInput as i, appendResourceRevision as l, writeTypedResourceRevision as m, JsonObject as n, StoredResourceRevision as o, loadRevisionExpansion as p, JsonValue as r, TypedObjectColumns as s, AppendResourceRevisionInput as t, listResourceRevisions as u, LegacyResourceRevisionError as v, listUnexpandedRevisions as w, UnexpandedRevision as x, RevisionConflictError as y };
275
+ //# sourceMappingURL=resource-revision-BbXciRsu.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"resource-revision-BbXciRsu.d.mts","names":[],"sources":["../src/revision-expansion.ts","../src/revision-conflict-error.ts","../src/legacy-resource-revision-error.ts","../src/resource-revision-state-error.ts","../src/legacy-resource-revision.ts","../src/resource-revision.ts"],"mappings":";;;;;;;;;;KAsCY,yBAAyB,QACnC;WACW;;;;;;WAMF,mBAAmB;;;UA4Qb;WACN,IAAI;WACJ,YAAY;;WAEZ;WACA,MAAM;WACN,SAAS;WACT;;;;;;;;iBASW,wBACpB,IAAI,WAAW,aACf;WAAoB,QAAQ;WAAe;IAC1C,QAAQ;;;;;;;;iBAeW,oBACpB,IAAI,WAAW,aACf;WAAoB,QAAQ;WAAe;IAC1C,QAAQ;;;;;;;;;iBAmDW,6BACpB,IAAI,WAAW,aACf,UAAU,OACT;WAAmB,IAAI;WAAe;;;;;;;;;;;;;;;iBAiCnB,wBACpB,IAAI,WAAW,aACf,YAAY,MACZ,WAAW,gCACV,QAAQ;;;;;;;;;;;;iBAqBW,uBACpB,IAAI,WAAW,aACf,YAAY,MACZ,WAAW,gCACV,QAAQ;;;;cChcE,8BAA8B;WAE9B,YAAY;WACZ,oBAAoB;WACpB,kBAAkB;EAH7B,YACW,YAAY,MACZ,oBAAoB,aACpB,kBAAkB;;;;;cCJlB,oCAAoC;WAC1B,YAAY;EAAjC,YAAqB,YAAY;;;;;cCHtB,mCAAmC;WAEnC;EADX,YACW;;;;;UCSI;;;;;;WAMN,YAAY;;;;;;;;;;;iBAYD,8BACpB,IAAI,aACJ,YAAY,MACZ,UAAS,uCACR,QAAQ;;;;KCeC,wDAKC;YAEG,mBAAmB;;KAEvB;YAAyB,mBAAmB;;;UAGvC;WACN;WACA;WACA,gBAAgB;WAChB;;;;;;;UAQM;;WAEN;;WAEA,kBAAkB;WAClB,UAAU;;UAGX;WACC,YAAY;WACZ;;WAEA,oBAAoB;;KAEnB,8BAA8B;WAGzB;WACA,UAAU;WACV,SAAS;WACT,aAAa;;;;;WAKb,iCAAiC;WACjC,qBAAqB;;WAErB,sBAAsB;WACtB,aAAa;;;;;;;;WAQb,YAAY;;WAGZ;WACA,SAAS,SAAS;WAClB;;;UAeA,+BAA+B;WACrC,qBAAqB;WACrB,oBAAoB;;;;;;;;;;iBAwcT,uBACpB,IAAI,WAAW,aACf,OAAO,8BACN,QAAQ;;;;;iBASW,sBACpB,IAAI,WAAW,aACf,YAAY,OACX,QAAQ;;;;;iBAaW,qBACpB,IAAI,WAAW,aACf,YAAY,OACX,QAAQ;;;;;iBAaW,4BACpB,IAAI,WAAW,aACf,YAAY,OACX,QAAQ;;;;;iBAWW,sBACpB,IAAI,WAAW,aACf,YAAY,MACZ;WAAoB;WAAkC;IACrD,QAAQ;;KA0DC,qBAAqB,KAC/B;UAYQ;WACC,YAAY;;WAEZ,oBAAoB;;KAEnB,6BAA6B;WAGxB;WACA,UAAU;;WAEV,SAAS,SAAS,KAAK,+BAC9B,QAAQ,KAAK;WACN,gCAAgC;WAChC,qBAAqB;;WAErB,sBAAsB;WACtB,aAAa;;WAEb,YAAY;;WAGZ;WACA,SAAS,SAAS;WAClB;;;;;;;;;;;;;;;;;;;iBAyDK,2BACpB,IAAI,WAAW,aACf,OAAO,6BACN,QAAQ"}
@@ -1,8 +1,49 @@
1
- import { activities, addressing, addressingPropertyEnum, objects, resourceHeads, resourceRevisionCaptureEnum, resourceRevisionProjectionEnum, resourceRevisions, resources, revisionAddressing, revisionEmbeddingRelationEnum, revisionEmbeddings, revisionRelations } from "./schema.mjs";
1
+ import { activities, addressing, addressingPropertyEnum, objects, resourceHeads, resourceRevisionCaptureEnum, resourceRevisionProjectionEnum, resourceRevisions, resources, revisionAddressing, revisionEmbeddingRelationEnum, revisionEmbeddings, revisionExpansions, revisionRelations } from "./schema.mjs";
2
2
  import { areUuidsEqual, uuidV7, validateUuid } from "./uuid.mjs";
3
3
  import { ResourceKindConflictError, checkAddressingOccurrences, replaceAddressing } from "./resource.mjs";
4
4
  import { storableText } from "./text.mjs";
5
- import { and, desc, eq, inArray, isNull, lt, sql } from "drizzle-orm";
5
+ import { expandDocument } from "./expansion.mjs";
6
+ import { and, asc, desc, eq, gt, inArray, isNull, lt, sql } from "drizzle-orm";
7
+ //#region src/json-text.ts
8
+ function jsonKeys(value) {
9
+ const prototype = Object.getPrototypeOf(value);
10
+ if (Array.isArray(value) ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null) throw new TypeError("JSON objects must be plain records.");
11
+ const result = [];
12
+ for (const key of Reflect.ownKeys(value)) {
13
+ const descriptor = Object.getOwnPropertyDescriptor(value, key);
14
+ if (typeof key !== "string" || descriptor === void 0 || !("value" in descriptor)) throw new TypeError("JSON values cannot contain symbol keys or accessors.");
15
+ if (Array.isArray(value) && key === "length") continue;
16
+ if (!descriptor.enumerable) throw new TypeError("JSON members must be enumerable.");
17
+ if (Array.isArray(value) && (!/^(?:0|[1-9][0-9]*)$/u.test(key) || Number(key) >= value.length)) throw new TypeError("JSON arrays cannot contain named properties.");
18
+ result.push(key);
19
+ }
20
+ return result;
21
+ }
22
+ /**
23
+ * Serializes a JSON value without coercion, keeping negative zero and
24
+ * escaped Unicode, for storage in `json` columns.
25
+ * @param value The value to serialize.
26
+ * @param ancestors Objects being serialized, to reject cycles.
27
+ * @returns The JSON text.
28
+ */
29
+ function json(value, ancestors = /* @__PURE__ */ new Set()) {
30
+ if (value === null) return "null";
31
+ if (typeof value === "string" || typeof value === "boolean") return JSON.stringify(value);
32
+ if (typeof value === "number") {
33
+ if (!Number.isFinite(value)) throw new TypeError("JSON numbers must be finite.");
34
+ return Object.is(value, -0) ? "-0" : JSON.stringify(value);
35
+ }
36
+ if (typeof value !== "object" || ancestors.has(value)) throw new TypeError("Expected an acyclic JSON value without coercion.");
37
+ const keys = jsonKeys(value);
38
+ ancestors.add(value);
39
+ try {
40
+ if (Array.isArray(value)) return `[${Array.from(value, (entry) => json(entry, ancestors)).join(",")}]`;
41
+ return `{${keys.map((key) => `${JSON.stringify(key)}:${json(Object.getOwnPropertyDescriptor(value, key).value, ancestors)}`).join(",")}}`;
42
+ } finally {
43
+ ancestors.delete(value);
44
+ }
45
+ }
46
+ //#endregion
6
47
  //#region src/legacy-resource-revision-error.ts
7
48
  /** Legacy typed rows require the coordinated application adapter in #152. */
8
49
  var LegacyResourceRevisionError = class extends Error {
@@ -40,15 +81,271 @@ var RevisionConflictError = class extends Error {
40
81
  }
41
82
  };
42
83
  //#endregion
84
+ //#region src/revision-expansion.ts
85
+ function terms(value) {
86
+ return Array.isArray(value) && value.every((term) => typeof term === "string");
87
+ }
88
+ /**
89
+ * Checks the shape of a caller's expansion.
90
+ * @param input The expansion.
91
+ * @throws {TypeError} If it is not an expanded or failed outcome.
92
+ */
93
+ function checkRevisionExpansion(input) {
94
+ if (input === null || typeof input !== "object") throw new TypeError("Expected a document expansion.");
95
+ const expansion = input;
96
+ if (expansion.sourceRevisionId !== void 0 && (typeof expansion.sourceRevisionId !== "string" || !validateUuid(expansion.sourceRevisionId))) throw new TypeError("Expected a canonical source revision UUID.");
97
+ if (expansion.outcome === "expanded") {
98
+ if (!Array.isArray(expansion.document) || !terms(expansion.droppedTerms) || !terms(expansion.undefinedTerms)) throw new TypeError("Expected an expanded document and its terms.");
99
+ return;
100
+ }
101
+ if (expansion.outcome === "failed") {
102
+ if (typeof expansion.failure !== "string") throw new TypeError("Expected the reason of a failed expansion.");
103
+ return;
104
+ }
105
+ throw new TypeError("Expected an expanded or failed outcome.");
106
+ }
107
+ function storableString(value) {
108
+ if (storableText(value)) return value;
109
+ return value.replaceAll("\0", "�").toWellFormed();
110
+ }
111
+ /**
112
+ * Normalizes an expanded document for `jsonb`, replacing in every string and
113
+ * key what it refuses with U+FFFD. The stored document keeps the exact
114
+ * values, so the expansion need not.
115
+ * @param value Part of an expanded document.
116
+ * @returns The value with storable strings and keys.
117
+ */
118
+ function storableJson(value) {
119
+ if (typeof value === "string") return storableString(value);
120
+ if (Array.isArray(value)) return value.map(storableJson);
121
+ if (value === null || typeof value !== "object") return value;
122
+ return Object.fromEntries(Object.entries(value).map(([key, entry]) => [storableString(key), storableJson(entry)]));
123
+ }
124
+ /**
125
+ * Checks that an embedded snapshot's expansion names the revision it was
126
+ * taken from, since an embedded document cannot be expanded on its own.
127
+ * @param capture How the snapshot was captured.
128
+ * @param expansion Its expansion.
129
+ * @throws {TypeError} If an embedded expansion has no source.
130
+ */
131
+ function checkExpansionSource(capture, expansion) {
132
+ if (capture === "embedded" && expansion?.outcome === "expanded" && expansion.sourceRevisionId === void 0) throw new TypeError("An embedded snapshot's expansion names the revision it was taken from.");
133
+ }
134
+ /**
135
+ * Serializes an expansion for storage. An expanded document that JSON cannot
136
+ * represent, such as one keeping a number beyond the double range, is
137
+ * recorded as a failure instead of failing the write. Strings are normalized
138
+ * for `jsonb` and `text`, and `jsonb` stores negative zero as zero.
139
+ * @param expansion The expansion, or null for a revision without a document.
140
+ * @returns The serialized expansion.
141
+ */
142
+ function serializeExpansion(expansion) {
143
+ const none = {
144
+ document: null,
145
+ droppedTerms: null,
146
+ undefinedTerms: null,
147
+ failure: null
148
+ };
149
+ if (expansion === null) return {
150
+ ...none,
151
+ outcome: "no_document",
152
+ sourceRevisionId: null
153
+ };
154
+ const sourceRevisionId = expansion.sourceRevisionId ?? null;
155
+ if (expansion.outcome === "expanded") try {
156
+ return {
157
+ outcome: "expanded",
158
+ document: json(storableJson(expansion.document)),
159
+ droppedTerms: expansion.droppedTerms.map(storableString),
160
+ undefinedTerms: expansion.undefinedTerms.map(storableString),
161
+ failure: null,
162
+ sourceRevisionId
163
+ };
164
+ } catch (error) {
165
+ if (!(error instanceof TypeError)) throw error;
166
+ return {
167
+ ...none,
168
+ outcome: "failed",
169
+ failure: `The expanded document cannot be stored as JSON: ${error.message}`,
170
+ sourceRevisionId
171
+ };
172
+ }
173
+ return {
174
+ ...none,
175
+ outcome: "failed",
176
+ failure: storableString(expansion.failure),
177
+ sourceRevisionId
178
+ };
179
+ }
180
+ /**
181
+ * Builds the row recording a revision's expansion.
182
+ * @param revisionId The revision.
183
+ * @param serialized The serialized expansion.
184
+ * @returns The row to insert.
185
+ */
186
+ function expansionRow(revisionId, serialized) {
187
+ return {
188
+ revisionId,
189
+ outcome: serialized.outcome,
190
+ document: serialized.document === null ? null : sql`${serialized.document}::jsonb`,
191
+ droppedTerms: serialized.droppedTerms === null ? null : [...serialized.droppedTerms],
192
+ undefinedTerms: serialized.undefinedTerms === null ? null : [...serialized.undefinedTerms],
193
+ failure: serialized.failure,
194
+ sourceRevisionId: serialized.sourceRevisionId
195
+ };
196
+ }
197
+ /**
198
+ * Records the expansions of a resource's revisions that have none, after a
199
+ * legacy capture. Revisions the capture created have none; a revision it
200
+ * reused has none only if it predates expansions, and the capture has then
201
+ * verified that its document equals the typed one. `expansion` is of that
202
+ * document, so it is recorded only for the snapshot the capture returned;
203
+ * other snapshots without one are handled as if none were given.
204
+ * @param tx The capturing transaction.
205
+ * @param resourceId The captured resource.
206
+ * @param capturedId The revision the capture returned.
207
+ * @param expansion The expansion of the typed document, if the caller computed
208
+ * it; otherwise the document is expanded offline here, from
209
+ * preloaded contexts only, when it was written locally. A
210
+ * received, embedded, or fetched snapshot may need remote
211
+ * contexts or the context it inherits, so without one it is
212
+ * left without a row for the backfill, which loads them;
213
+ * a failure recorded offline would keep the backfill away.
214
+ */
215
+ async function recordMissingExpansions(tx, resourceId, capturedId, expansion) {
216
+ const missing = await tx.select({
217
+ id: resourceRevisions.id,
218
+ kind: resourceRevisions.kind,
219
+ capture: resourceRevisions.capture,
220
+ document: resourceRevisions.document
221
+ }).from(resourceRevisions).leftJoin(revisionExpansions, eq(revisionExpansions.revisionId, resourceRevisions.id)).where(and(eq(resourceRevisions.resourceId, resourceId), isNull(revisionExpansions.revisionId))).orderBy(asc(resourceRevisions.sequence));
222
+ const rows = [];
223
+ const given = expansion === void 0 ? void 0 : serializeExpansion(expansion);
224
+ for (const revision of missing) {
225
+ if (revision.kind !== "snapshot") {
226
+ const failed = revision.id === capturedId && revision.kind === "unavailable" && given?.outcome === "failed";
227
+ if (revision.id === capturedId && given !== void 0 && !failed) throw new TypeError(`A revision of kind ${revision.kind} has no document to expand.`);
228
+ rows.push(expansionRow(revision.id, failed ? given : serializeExpansion(null)));
229
+ continue;
230
+ }
231
+ if (given === void 0 || revision.id !== capturedId) {
232
+ if (revision.capture !== "local") continue;
233
+ const own = await expandDocument(revision.document);
234
+ if (own.outcome === "no_document") throw new TypeError("A snapshot revision has a document.");
235
+ rows.push(expansionRow(revision.id, serializeExpansion(own)));
236
+ continue;
237
+ }
238
+ checkExpansionSource(revision.capture, expansion);
239
+ rows.push(expansionRow(revision.id, given));
240
+ }
241
+ if (rows.length > 0) await tx.insert(revisionExpansions).values(rows).onConflictDoNothing();
242
+ }
243
+ /**
244
+ * Lists revisions without an expansion, in ID order.
245
+ * @param db The database.
246
+ * @param options Where to continue from, and how many to list.
247
+ * @returns Up to `limit` revisions after `after`.
248
+ */
249
+ async function listUnexpandedRevisions(db, options) {
250
+ return await listRevisions(db, isNull(revisionExpansions.revisionId), options);
251
+ }
252
+ /**
253
+ * Lists snapshot revisions whose expansion failed, in ID order, so that a
254
+ * failure such as a context that could not be loaded can be retried.
255
+ * @param db The database.
256
+ * @param options Where to continue from, and how many to list.
257
+ * @returns Up to `limit` revisions after `after`.
258
+ */
259
+ async function listFailedRevisions(db, options) {
260
+ return await listRevisions(db, and(eq(revisionExpansions.outcome, "failed"), eq(resourceRevisions.kind, "snapshot")), options);
261
+ }
262
+ async function listRevisions(db, condition, options) {
263
+ return await db.select({
264
+ id: resourceRevisions.id,
265
+ resourceId: resourceRevisions.resourceId,
266
+ resourceIri: resources.iri,
267
+ kind: resourceRevisions.kind,
268
+ capture: resourceRevisions.capture,
269
+ document: resourceRevisions.document
270
+ }).from(resourceRevisions).innerJoin(resources, eq(resources.id, resourceRevisions.resourceId)).leftJoin(revisionExpansions, eq(revisionExpansions.revisionId, resourceRevisions.id)).where(and(condition, options.after === void 0 ? void 0 : gt(resourceRevisions.id, options.after))).orderBy(asc(resourceRevisions.id)).limit(options.limit);
271
+ }
272
+ /**
273
+ * Finds the revision of the activity that first carried an embedded object,
274
+ * the one its typed row names, which an embedded revision's expansion is
275
+ * taken from.
276
+ * @param db The database.
277
+ * @param objectId The embedded object's resource.
278
+ * @returns The activity's first revision, or null if there is none.
279
+ */
280
+ async function findCarryingActivityRevision(db, objectId) {
281
+ const [row] = await db.select({
282
+ id: resourceRevisions.id,
283
+ document: resourceRevisions.document
284
+ }).from(objects).innerJoin(resourceRevisions, and(eq(resourceRevisions.resourceId, objects.activityId), eq(resourceRevisions.sequence, 1), eq(resourceRevisions.kind, "snapshot"))).where(eq(objects.id, objectId)).limit(1);
285
+ return row ?? null;
286
+ }
287
+ /**
288
+ * Records the expansion of a revision that has none. An existing row is kept,
289
+ * so that the backfill can run again or alongside new writes.
290
+ * @param db The database.
291
+ * @param revisionId The revision.
292
+ * @param expansion Its expansion, or null for a revision without a document,
293
+ * which must be `unavailable` or a `whiteout`.
294
+ * @returns The outcome of the row inserted, which is `failed` for an
295
+ * expansion JSON cannot hold, or null if the revision already had
296
+ * one.
297
+ * @throws {TypeError} If the revision does not exist, or the expansion does
298
+ * not suit its kind.
299
+ */
300
+ async function recordRevisionExpansion(db, revisionId, expansion) {
301
+ const serialized = await checkedExpansion(db, revisionId, expansion);
302
+ return (await db.insert(revisionExpansions).values(expansionRow(revisionId, serialized)).onConflictDoNothing().returning({ outcome: revisionExpansions.outcome }))[0]?.outcome ?? null;
303
+ }
304
+ /**
305
+ * Replaces a failed expansion of a revision, as when a context that could not
306
+ * be loaded before now loads. A row that is no longer failed, because
307
+ * another writer replaced it first, is kept.
308
+ * @param db The database.
309
+ * @param revisionId The revision.
310
+ * @param expansion Its new expansion.
311
+ * @returns The outcome of the row replaced, or null if it was not failed.
312
+ * @throws {TypeError} If the revision does not exist, or the expansion does
313
+ * not suit its kind.
314
+ */
315
+ async function retryRevisionExpansion(db, revisionId, expansion) {
316
+ const { revisionId: _revisionId, ...columns } = expansionRow(revisionId, await checkedExpansion(db, revisionId, expansion));
317
+ return (await db.update(revisionExpansions).set(columns).where(and(eq(revisionExpansions.revisionId, revisionId), eq(revisionExpansions.outcome, "failed"))).returning({ outcome: revisionExpansions.outcome }))[0]?.outcome ?? null;
318
+ }
319
+ async function checkedExpansion(db, revisionId, expansion) {
320
+ if (expansion !== null) checkRevisionExpansion(expansion);
321
+ const serialized = serializeExpansion(expansion);
322
+ const [revision] = await db.select({
323
+ kind: resourceRevisions.kind,
324
+ capture: resourceRevisions.capture
325
+ }).from(resourceRevisions).where(eq(resourceRevisions.id, revisionId)).limit(1);
326
+ if (revision === void 0) throw new TypeError("The revision does not exist.");
327
+ if (!(revision.kind === "snapshot" ? expansion !== null : expansion === null || revision.kind === "unavailable" && expansion.outcome === "failed")) throw new TypeError(revision.kind === "snapshot" ? "A snapshot has a document to expand." : `A revision of kind ${revision.kind} has no document to expand.`);
328
+ checkExpansionSource(revision.capture, expansion);
329
+ return serialized;
330
+ }
331
+ //#endregion
43
332
  //#region src/legacy-resource-revision.ts
44
333
  /**
45
334
  * Captures fully written legacy typed state within its creating transaction.
46
335
  * This trusted compatibility operation performs no authorization or fetching.
47
336
  * Repeated calls return the original revision only when the typed state agrees.
337
+ * Revisions of the resource without an expansion get one, so that a capture
338
+ * reusing a revision made before expansions were stored records it too.
48
339
  * @returns The first retained revision ID, including an unavailable snapshot.
49
340
  * @throws {LegacyResourceRevisionError} When typed state cannot be captured.
50
341
  */
51
- async function captureLegacyResourceRevision(tx, resourceId) {
342
+ async function captureLegacyResourceRevision(tx, resourceId, options = {}) {
343
+ if (options.expansion !== void 0) checkRevisionExpansion(options.expansion);
344
+ const id = await capture(tx, resourceId);
345
+ await recordMissingExpansions(tx, resourceId, id, options.expansion);
346
+ return id;
347
+ }
348
+ async function capture(tx, resourceId) {
52
349
  try {
53
350
  const [row] = await tx.select({ id: sql`drfed_capture_legacy_resource(${resourceId}::uuid, false)` }).from(sql`(VALUES (1)) AS capture_input(value)`);
54
351
  if (row === void 0) throw new Error("Legacy capture returned no revision.");
@@ -67,37 +364,6 @@ async function captureLegacyResourceRevision(tx, resourceId) {
67
364
  function text(value) {
68
365
  if (typeof value !== "string" || !storableText(value)) throw new TypeError("A projection must contain losslessly storable text.");
69
366
  }
70
- function jsonKeys(value) {
71
- const prototype = Object.getPrototypeOf(value);
72
- if (Array.isArray(value) ? prototype !== Array.prototype : prototype !== Object.prototype && prototype !== null) throw new TypeError("JSON objects must be plain records.");
73
- const result = [];
74
- for (const key of Reflect.ownKeys(value)) {
75
- const descriptor = Object.getOwnPropertyDescriptor(value, key);
76
- if (typeof key !== "string" || descriptor === void 0 || !("value" in descriptor)) throw new TypeError("JSON values cannot contain symbol keys or accessors.");
77
- if (Array.isArray(value) && key === "length") continue;
78
- if (!descriptor.enumerable) throw new TypeError("JSON members must be enumerable.");
79
- if (Array.isArray(value) && (!/^(?:0|[1-9][0-9]*)$/u.test(key) || Number(key) >= value.length)) throw new TypeError("JSON arrays cannot contain named properties.");
80
- result.push(key);
81
- }
82
- return result;
83
- }
84
- function json(value, ancestors = /* @__PURE__ */ new Set()) {
85
- if (value === null) return "null";
86
- if (typeof value === "string" || typeof value === "boolean") return JSON.stringify(value);
87
- if (typeof value === "number") {
88
- if (!Number.isFinite(value)) throw new TypeError("JSON numbers must be finite.");
89
- return Object.is(value, -0) ? "-0" : JSON.stringify(value);
90
- }
91
- if (typeof value !== "object" || ancestors.has(value)) throw new TypeError("Expected an acyclic JSON value without coercion.");
92
- const keys = jsonKeys(value);
93
- ancestors.add(value);
94
- try {
95
- if (Array.isArray(value)) return `[${Array.from(value, (entry) => json(entry, ancestors)).join(",")}]`;
96
- return `{${keys.map((key) => `${JSON.stringify(key)}:${json(Object.getOwnPropertyDescriptor(value, key).value, ancestors)}`).join(",")}}`;
97
- } finally {
98
- ancestors.delete(value);
99
- }
100
- }
101
367
  function projectionRows(input = {}) {
102
368
  const rows = [];
103
369
  for (const property of Object.keys(input)) if (!addressingPropertyEnum.enumValues.includes(property)) throw new TypeError("Unknown addressing projection property.");
@@ -186,6 +452,10 @@ function prepareSnapshot(input) {
186
452
  };
187
453
  });
188
454
  }
455
+ if (input.expansion !== void 0) {
456
+ checkRevisionExpansion(input.expansion);
457
+ checkExpansionSource(input.capture, input.expansion);
458
+ }
189
459
  return {
190
460
  kind: "snapshot",
191
461
  serialized: json(input.document),
@@ -195,7 +465,9 @@ function prepareSnapshot(input) {
195
465
  relations: relationRows(input.relations),
196
466
  embeddings: embeddingRows(input.embeddings),
197
467
  deleted: null,
198
- formerTypes: null
468
+ formerTypes: null,
469
+ expansion: input.expansion === void 0 ? void 0 : serializeExpansion(input.expansion),
470
+ source: input.document
199
471
  };
200
472
  }
201
473
  function prepareWhiteout(input) {
@@ -211,7 +483,9 @@ function prepareWhiteout(input) {
211
483
  relations: [],
212
484
  embeddings: [],
213
485
  deleted: input.deleted,
214
- formerTypes
486
+ formerTypes,
487
+ expansion: serializeExpansion(null),
488
+ source: null
215
489
  };
216
490
  }
217
491
  function prepareRevision(input) {
@@ -280,6 +554,8 @@ async function appendPrepared(tx, input, typed = false) {
280
554
  ...row,
281
555
  revisionId: id
282
556
  })));
557
+ if (input.expansion === void 0) throw new TypeError("A snapshot must be expanded before its transaction.");
558
+ await tx.insert(revisionExpansions).values(expansionRow(id, input.expansion));
283
559
  if (previous === null) await tx.insert(resourceHeads).values({
284
560
  resourceId,
285
561
  revisionId: id
@@ -287,18 +563,37 @@ async function appendPrepared(tx, input, typed = false) {
287
563
  else await tx.update(resourceHeads).set({ revisionId: id }).where(eq(resourceHeads.resourceId, resourceId));
288
564
  return await hydrate(tx, revision);
289
565
  }
566
+ async function expanded(prepared) {
567
+ if (prepared.expansion !== void 0 || prepared.source === null) return prepared;
568
+ if (prepared.capture === "embedded") throw new TypeError("An embedded snapshot needs its given expansion.");
569
+ const expansion = await expandDocument(prepared.source);
570
+ if (expansion.outcome === "no_document") throw new TypeError("A snapshot revision has a document.");
571
+ return {
572
+ ...prepared,
573
+ expansion: serializeExpansion(expansion)
574
+ };
575
+ }
290
576
  /**
291
577
  * Appends one current object version or saved activity, atomically with projections.
292
578
  * The caller must validate the document and authorize the write. Lock multiple
293
579
  * canonical IRIs in sorted order before composing several appends in one transaction.
294
580
  * This does not publish, change collection membership, or reserve delivery.
581
+ * The revision's expansion is stored with it; see the `expansion` input.
295
582
  * @returns The stored revision, including protected blind addressing.
296
583
  */
297
584
  async function appendResourceRevision(db, input) {
298
- const prepared = prepareRevision(input);
585
+ const prepared = await expanded(prepareRevision(input));
299
586
  return await db.transaction((tx) => appendPrepared(tx, prepared));
300
587
  }
301
588
  /**
589
+ * Loads the recorded expansion of a revision's document.
590
+ * @returns The expansion, or null if the revision has not been expanded.
591
+ */
592
+ async function loadRevisionExpansion(db, revisionId) {
593
+ const [row] = await db.select().from(revisionExpansions).where(eq(revisionExpansions.revisionId, revisionId)).limit(1);
594
+ return row ?? null;
595
+ }
596
+ /**
302
597
  * Loads protected local JSON without applying authorization or stripping bto/bcc.
303
598
  * @returns The immutable revision and projections, or null if not found.
304
599
  */
@@ -387,7 +682,7 @@ async function sameTypedState(tx, resourceId, head) {
387
682
  * @throws {ResourceRevisionStateError} If the object is already deleted.
388
683
  */
389
684
  async function writeTypedResourceRevision(db, input) {
390
- const prepared = prepareRevision(input.kind === "snapshot" ? {
685
+ const prepared = await expanded(prepareRevision(input.kind === "snapshot" ? {
391
686
  resourceId: input.resourceId,
392
687
  resourceKind: "object",
393
688
  expectedRevisionId: input.expectedRevisionId,
@@ -397,7 +692,8 @@ async function writeTypedResourceRevision(db, input) {
397
692
  addressingOccurrences: input.addressingOccurrences,
398
693
  ...input.relations === void 0 ? {} : { relations: input.relations },
399
694
  ...input.embeddings === void 0 ? {} : { embeddings: input.embeddings },
400
- ...input.projection === void 0 ? {} : { projection: input.projection }
695
+ ...input.projection === void 0 ? {} : { projection: input.projection },
696
+ ...input.expansion === void 0 ? {} : { expansion: input.expansion }
401
697
  } : {
402
698
  resourceId: input.resourceId,
403
699
  resourceKind: "object",
@@ -405,7 +701,7 @@ async function writeTypedResourceRevision(db, input) {
405
701
  kind: "whiteout",
406
702
  deleted: input.deleted,
407
703
  formerTypes: input.formerTypes
408
- });
704
+ }));
409
705
  if (prepared.expectedRevisionId === null) throw new TypeError("A typed object always has a current revision.");
410
706
  return await db.transaction(async (tx) => {
411
707
  const [resource] = await tx.select({ kind: resources.kind }).from(resources).where(eq(resources.id, prepared.resourceId)).for("no key update");
@@ -433,6 +729,6 @@ async function writeTypedResourceRevision(db, input) {
433
729
  });
434
730
  }
435
731
  //#endregion
436
- export { writeTypedResourceRevision as a, ResourceRevisionStateError as c, loadResourceRevision as i, LegacyResourceRevisionError as l, listResourceRevisions as n, captureLegacyResourceRevision as o, loadCurrentResourceRevision as r, RevisionConflictError as s, appendResourceRevision as t };
732
+ export { loadRevisionExpansion as a, findCarryingActivityRevision as c, recordRevisionExpansion as d, retryRevisionExpansion as f, LegacyResourceRevisionError as h, loadResourceRevision as i, listFailedRevisions as l, ResourceRevisionStateError as m, listResourceRevisions as n, writeTypedResourceRevision as o, RevisionConflictError as p, loadCurrentResourceRevision as r, captureLegacyResourceRevision as s, appendResourceRevision as t, listUnexpandedRevisions as u };
437
733
 
438
- //# sourceMappingURL=resource-revision-bTQyJ7aw.mjs.map
734
+ //# sourceMappingURL=resource-revision-DGsz8fnS.mjs.map