@drfed/models 0.2.0-dev.698 → 0.2.0-dev.703
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/README.md +113 -69
- package/dist/document.d.mts +51 -1
- package/dist/document.d.mts.map +1 -1
- package/dist/document.mjs +114 -2
- package/dist/document.mjs.map +1 -1
- package/dist/index.d.mts +3 -3
- package/dist/index.mjs +3 -3
- package/dist/{resource-revision-BuG5kUlA.d.mts → resource-revision-BauDwFIn.d.mts} +47 -4
- package/dist/resource-revision-BauDwFIn.d.mts.map +1 -0
- package/dist/{resource-revision-DWg6et77.mjs → resource-revision-iQ8HZ699.mjs} +110 -10
- package/dist/resource-revision-iQ8HZ699.mjs.map +1 -0
- package/dist/resource-revision.d.mts +2 -2
- package/dist/resource-revision.mjs +1 -1
- package/dist/resource.d.mts +27 -1
- package/dist/resource.d.mts.map +1 -1
- package/dist/resource.mjs +41 -1
- package/dist/resource.mjs.map +1 -1
- package/package.json +6 -6
- package/dist/resource-revision-BuG5kUlA.d.mts.map +0 -1
- package/dist/resource-revision-DWg6et77.mjs.map +0 -1
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { J as RevisionAddressing, X as RevisionRelation, q as ResourceRevision, r as Transaction, t as Database } from "./db-BBw4F4HU.mjs";
|
|
1
|
+
import { J as RevisionAddressing, P as NewActivityPubObject, X as RevisionRelation, q as ResourceRevision, r as Transaction, t as Database } from "./db-BBw4F4HU.mjs";
|
|
2
2
|
import { t as Uuid } from "./uuid-CKMzlIND.mjs";
|
|
3
|
-
import { AddressingInput } from "./resource.mjs";
|
|
3
|
+
import { AddressingInput, AddressingOccurrence } from "./resource.mjs";
|
|
4
4
|
//#region src/revision-conflict-error.d.ts
|
|
5
5
|
/** The caller's expected current revision no longer matches the database. */
|
|
6
6
|
declare class RevisionConflictError extends Error {
|
|
@@ -60,6 +60,11 @@ type AppendResourceRevisionInput = AppendBase & ({
|
|
|
60
60
|
readonly document: JsonObject;
|
|
61
61
|
readonly capture: ResourceRevision["capture"];
|
|
62
62
|
readonly addressing?: AddressingInput;
|
|
63
|
+
/**
|
|
64
|
+
* Explicit occurrences at their source positions, instead of
|
|
65
|
+
* `addressing`; positions of unindexed values stay unused.
|
|
66
|
+
*/
|
|
67
|
+
readonly addressingOccurrences?: readonly AddressingOccurrence[];
|
|
63
68
|
readonly relations?: readonly RevisionRelationInput[];
|
|
64
69
|
readonly projection?: ResourceRevision["projection"];
|
|
65
70
|
} | {
|
|
@@ -98,6 +103,44 @@ declare function listResourceRevisions(db: Database | Transaction, resourceId: U
|
|
|
98
103
|
readonly beforeSequence?: number;
|
|
99
104
|
readonly limit?: number;
|
|
100
105
|
}): Promise<StoredResourceRevision[]>;
|
|
106
|
+
/** Typed object columns a coordinated edit may set, besides its document. */
|
|
107
|
+
type TypedObjectColumns = Pick<NewActivityPubObject, "type" | "url" | "name" | "summary" | "contentHtml" | "language" | "sensitive" | "published" | "updated">;
|
|
108
|
+
interface TypedRevisionBase {
|
|
109
|
+
readonly resourceId: Uuid;
|
|
110
|
+
/** The current revision; a typed object always has one. */
|
|
111
|
+
readonly expectedRevisionId: Uuid;
|
|
112
|
+
}
|
|
113
|
+
type TypedResourceRevisionInput = TypedRevisionBase & ({
|
|
114
|
+
readonly kind: "snapshot";
|
|
115
|
+
readonly document: JsonObject;
|
|
116
|
+
/** Every column the typed row serves; `updated` is not implied. */
|
|
117
|
+
readonly columns: Required<Omit<TypedObjectColumns, "type">> & Partial<Pick<TypedObjectColumns, "type">>;
|
|
118
|
+
readonly addressingOccurrences: readonly AddressingOccurrence[];
|
|
119
|
+
readonly relations?: readonly RevisionRelationInput[];
|
|
120
|
+
readonly projection?: ResourceRevision["projection"];
|
|
121
|
+
} | {
|
|
122
|
+
readonly kind: "whiteout";
|
|
123
|
+
readonly deleted: Temporal.Instant;
|
|
124
|
+
readonly formerTypes: readonly string[];
|
|
125
|
+
});
|
|
126
|
+
/**
|
|
127
|
+
* Edits or deletes an object that has a legacy typed row, keeping the typed
|
|
128
|
+
* row, its current addressing, and the revision history in step. Under the
|
|
129
|
+
* canonical lock, the current revision must be the expected snapshot, and the
|
|
130
|
+
* typed row's document and addressing must still equal it; otherwise nothing
|
|
131
|
+
* changes. A snapshot sets the typed columns, the typed document to the same
|
|
132
|
+
* JSON as the new revision, and the current addressing to the occurrences. A
|
|
133
|
+
* whiteout soft-deletes the typed row and keeps its addressing, which
|
|
134
|
+
* continues to describe the last content. The caller must validate and
|
|
135
|
+
* authorize the change and check any served column against the old head.
|
|
136
|
+
* The whole write runs in a savepoint, so a caught error leaves no part of it.
|
|
137
|
+
* @returns The appended revision, including protected blind addressing.
|
|
138
|
+
* @throws {RevisionConflictError} If the current revision is not the expected.
|
|
139
|
+
* @throws {LegacyResourceRevisionError} If the resource has no live typed
|
|
140
|
+
* object or the typed state differs from its current revision.
|
|
141
|
+
* @throws {ResourceRevisionStateError} If the object is already deleted.
|
|
142
|
+
*/
|
|
143
|
+
declare function writeTypedResourceRevision(db: Database | Transaction, input: TypedResourceRevisionInput): Promise<StoredResourceRevision>;
|
|
101
144
|
//#endregion
|
|
102
|
-
export { StoredResourceRevision as a,
|
|
103
|
-
//# sourceMappingURL=resource-revision-
|
|
145
|
+
export { StoredResourceRevision as a, appendResourceRevision as c, loadResourceRevision as d, writeTypedResourceRevision as f, RevisionConflictError as g, LegacyResourceRevisionError as h, RevisionRelationInput as i, listResourceRevisions as l, ResourceRevisionStateError as m, JsonObject as n, TypedObjectColumns as o, captureLegacyResourceRevision as p, JsonValue as r, TypedResourceRevisionInput as s, AppendResourceRevisionInput as t, loadCurrentResourceRevision as u };
|
|
146
|
+
//# sourceMappingURL=resource-revision-BauDwFIn.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resource-revision-BauDwFIn.d.mts","names":[],"sources":["../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":";;;;;cAmBa,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;;;;;;;;;;;iBCUS,8BACpB,IAAI,aACJ,YAAY,OACX,QAAQ;;;;KCkBC,wDAKC;YAEG,mBAAmB;;KAEvB;YAAyB,mBAAmB;;;UAGvC;WACN;WACA;WACA,gBAAgB;WAChB;;UAGD;WACC,YAAY;WACZ;;WAEA,oBAAoB;;KAEnB,8BAA8B;WAGzB;WACA,UAAU;WACV,SAAS;WACT,aAAa;;;;;WAKb,iCAAiC;WACjC,qBAAqB;WACrB,aAAa;;WAGb;WACA,SAAS,SAAS;WAClB;;;UAKA,+BAA+B;WACrC,qBAAqB;WACrB,oBAAoB;;;;;;;;;iBA+aT,uBACpB,IAAI,WAAW,aACf,OAAO,8BACN,QAAQ;;;;;iBASW,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;WACrB,aAAa;;WAGb;WACA,SAAS,SAAS;WAClB;;;;;;;;;;;;;;;;;;;iBAyDK,2BACpB,IAAI,WAAW,aACf,OAAO,6BACN,QAAQ"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { activities, addressingPropertyEnum, objects, resourceHeads, resourceRevisionCaptureEnum, resourceRevisionProjectionEnum, resourceRevisions, resources, revisionAddressing, revisionRelations } from "./schema.mjs";
|
|
1
|
+
import { activities, addressing, addressingPropertyEnum, objects, resourceHeads, resourceRevisionCaptureEnum, resourceRevisionProjectionEnum, resourceRevisions, resources, revisionAddressing, revisionRelations } from "./schema.mjs";
|
|
2
2
|
import { areUuidsEqual, uuidV7, validateUuid } from "./uuid.mjs";
|
|
3
|
-
import { ResourceKindConflictError } from "./resource.mjs";
|
|
3
|
+
import { ResourceKindConflictError, checkAddressingOccurrences, replaceAddressing } from "./resource.mjs";
|
|
4
4
|
import { storableText } from "./text.mjs";
|
|
5
|
-
import { and, desc, eq, inArray, lt, sql } from "drizzle-orm";
|
|
5
|
+
import { and, desc, eq, inArray, isNull, lt, sql } from "drizzle-orm";
|
|
6
6
|
//#region src/legacy-resource-revision-error.ts
|
|
7
7
|
/** Legacy typed rows require the coordinated application adapter in #152. */
|
|
8
8
|
var LegacyResourceRevisionError = class extends Error {
|
|
@@ -154,12 +154,26 @@ function prepareSnapshot(input) {
|
|
|
154
154
|
if (input.document === null || typeof input.document !== "object" || Array.isArray(input.document)) throw new TypeError("A new resource document must be a JSON object.");
|
|
155
155
|
const projection = input.projection ?? "partial";
|
|
156
156
|
if (!resourceRevisionCaptureEnum.enumValues.includes(input.capture) || !resourceRevisionProjectionEnum.enumValues.includes(projection)) throw new TypeError("Invalid capture or projection category.");
|
|
157
|
+
let addressing;
|
|
158
|
+
if (input.addressingOccurrences === void 0) addressing = projectionRows(input.addressing);
|
|
159
|
+
else {
|
|
160
|
+
if (input.addressing !== void 0) throw new TypeError("Pass addressing or its occurrences, not both.");
|
|
161
|
+
checkAddressingOccurrences(input.addressingOccurrences);
|
|
162
|
+
addressing = input.addressingOccurrences.map(({ property, position, iri }) => {
|
|
163
|
+
text(iri);
|
|
164
|
+
return {
|
|
165
|
+
property,
|
|
166
|
+
position,
|
|
167
|
+
iri
|
|
168
|
+
};
|
|
169
|
+
});
|
|
170
|
+
}
|
|
157
171
|
return {
|
|
158
172
|
kind: "snapshot",
|
|
159
173
|
serialized: json(input.document),
|
|
160
174
|
capture: input.capture,
|
|
161
175
|
projection,
|
|
162
|
-
addressing
|
|
176
|
+
addressing,
|
|
163
177
|
relations: relationRows(input.relations),
|
|
164
178
|
deleted: null,
|
|
165
179
|
formerTypes: null
|
|
@@ -198,14 +212,14 @@ function prepareRevision(input) {
|
|
|
198
212
|
};
|
|
199
213
|
throw new TypeError("Unsupported revision kind.");
|
|
200
214
|
}
|
|
201
|
-
async function lockRevisionTarget(tx, input) {
|
|
215
|
+
async function lockRevisionTarget(tx, input, typed = false) {
|
|
202
216
|
const { resourceId, resourceKind, expectedRevisionId, kind } = input;
|
|
203
217
|
const [resource] = await tx.select().from(resources).where(eq(resources.id, resourceId)).for("no key update");
|
|
204
218
|
if (resource === void 0) throw new Error("The canonical resource is not registered.");
|
|
205
219
|
const previous = await current(tx, resourceId);
|
|
206
220
|
if (!(previous === null ? expectedRevisionId === null : expectedRevisionId !== null && areUuidsEqual(previous.id, expectedRevisionId))) throw new RevisionConflictError(resourceId, expectedRevisionId, previous?.id ?? null);
|
|
207
221
|
const [legacyObject, legacyActivity] = await Promise.all([tx.select({ id: objects.id }).from(objects).where(eq(objects.id, resourceId)).limit(1), tx.select({ id: activities.id }).from(activities).where(eq(activities.id, resourceId)).limit(1)]);
|
|
208
|
-
if (legacyObject.length > 0 || legacyActivity.length > 0) throw new LegacyResourceRevisionError(resourceId);
|
|
222
|
+
if (!typed && (legacyObject.length > 0 || legacyActivity.length > 0)) throw new LegacyResourceRevisionError(resourceId);
|
|
209
223
|
if (resource.kind !== "unknown" && resource.kind !== resourceKind) throw new ResourceKindConflictError(resource.iri, resource.kind, resourceKind);
|
|
210
224
|
if (previous !== null && resourceKind === "activity") throw new ResourceRevisionStateError("activity-immutable");
|
|
211
225
|
if (previous?.kind === "whiteout") throw new ResourceRevisionStateError("deleted");
|
|
@@ -213,8 +227,8 @@ async function lockRevisionTarget(tx, input) {
|
|
|
213
227
|
if (resource.kind === "unknown") await tx.update(resources).set({ kind: resourceKind }).where(eq(resources.id, resourceId));
|
|
214
228
|
return previous;
|
|
215
229
|
}
|
|
216
|
-
async function appendPrepared(tx, input) {
|
|
217
|
-
const previous = await lockRevisionTarget(tx, input);
|
|
230
|
+
async function appendPrepared(tx, input, typed = false) {
|
|
231
|
+
const previous = await lockRevisionTarget(tx, input, typed);
|
|
218
232
|
const { resourceId, kind, serialized, capture, projection, deleted, formerTypes, addressing, relations } = input;
|
|
219
233
|
const id = uuidV7();
|
|
220
234
|
const [revision] = await tx.insert(resourceRevisions).values({
|
|
@@ -307,7 +321,93 @@ async function listResourceRevisions(db, resourceId, options = {}) {
|
|
|
307
321
|
relations: relationsByRevision.get(revision.id) ?? []
|
|
308
322
|
}));
|
|
309
323
|
}
|
|
324
|
+
async function sameTypedState(tx, resourceId, head) {
|
|
325
|
+
const [row] = await tx.select({ same: sql`${objects.document}::text IS NOT DISTINCT FROM ${resourceRevisions.document}::text
|
|
326
|
+
AND NOT EXISTS (
|
|
327
|
+
(SELECT saved.property, saved.position, saved.iri
|
|
328
|
+
FROM ${revisionAddressing} AS saved
|
|
329
|
+
WHERE saved.revision_id = ${head.id})
|
|
330
|
+
EXCEPT ALL
|
|
331
|
+
(SELECT declared.property, declared.position, target.iri
|
|
332
|
+
FROM ${addressing} AS declared
|
|
333
|
+
JOIN ${resources} AS target ON target.id = declared.target_id
|
|
334
|
+
WHERE declared.source_id = ${resourceId})
|
|
335
|
+
)
|
|
336
|
+
AND NOT EXISTS (
|
|
337
|
+
(SELECT declared.property, declared.position, target.iri
|
|
338
|
+
FROM ${addressing} AS declared
|
|
339
|
+
JOIN ${resources} AS target ON target.id = declared.target_id
|
|
340
|
+
WHERE declared.source_id = ${resourceId})
|
|
341
|
+
EXCEPT ALL
|
|
342
|
+
(SELECT saved.property, saved.position, saved.iri
|
|
343
|
+
FROM ${revisionAddressing} AS saved
|
|
344
|
+
WHERE saved.revision_id = ${head.id})
|
|
345
|
+
)` }).from(objects).innerJoin(resourceRevisions, eq(resourceRevisions.id, head.id)).where(and(eq(objects.id, resourceId), isNull(objects.deleted)));
|
|
346
|
+
return row?.same === true;
|
|
347
|
+
}
|
|
348
|
+
/**
|
|
349
|
+
* Edits or deletes an object that has a legacy typed row, keeping the typed
|
|
350
|
+
* row, its current addressing, and the revision history in step. Under the
|
|
351
|
+
* canonical lock, the current revision must be the expected snapshot, and the
|
|
352
|
+
* typed row's document and addressing must still equal it; otherwise nothing
|
|
353
|
+
* changes. A snapshot sets the typed columns, the typed document to the same
|
|
354
|
+
* JSON as the new revision, and the current addressing to the occurrences. A
|
|
355
|
+
* whiteout soft-deletes the typed row and keeps its addressing, which
|
|
356
|
+
* continues to describe the last content. The caller must validate and
|
|
357
|
+
* authorize the change and check any served column against the old head.
|
|
358
|
+
* The whole write runs in a savepoint, so a caught error leaves no part of it.
|
|
359
|
+
* @returns The appended revision, including protected blind addressing.
|
|
360
|
+
* @throws {RevisionConflictError} If the current revision is not the expected.
|
|
361
|
+
* @throws {LegacyResourceRevisionError} If the resource has no live typed
|
|
362
|
+
* object or the typed state differs from its current revision.
|
|
363
|
+
* @throws {ResourceRevisionStateError} If the object is already deleted.
|
|
364
|
+
*/
|
|
365
|
+
async function writeTypedResourceRevision(db, input) {
|
|
366
|
+
const prepared = prepareRevision(input.kind === "snapshot" ? {
|
|
367
|
+
resourceId: input.resourceId,
|
|
368
|
+
resourceKind: "object",
|
|
369
|
+
expectedRevisionId: input.expectedRevisionId,
|
|
370
|
+
kind: "snapshot",
|
|
371
|
+
document: input.document,
|
|
372
|
+
capture: "local",
|
|
373
|
+
addressingOccurrences: input.addressingOccurrences,
|
|
374
|
+
...input.relations === void 0 ? {} : { relations: input.relations },
|
|
375
|
+
...input.projection === void 0 ? {} : { projection: input.projection }
|
|
376
|
+
} : {
|
|
377
|
+
resourceId: input.resourceId,
|
|
378
|
+
resourceKind: "object",
|
|
379
|
+
expectedRevisionId: input.expectedRevisionId,
|
|
380
|
+
kind: "whiteout",
|
|
381
|
+
deleted: input.deleted,
|
|
382
|
+
formerTypes: input.formerTypes
|
|
383
|
+
});
|
|
384
|
+
if (prepared.expectedRevisionId === null) throw new TypeError("A typed object always has a current revision.");
|
|
385
|
+
return await db.transaction(async (tx) => {
|
|
386
|
+
const [resource] = await tx.select({ kind: resources.kind }).from(resources).where(eq(resources.id, prepared.resourceId)).for("no key update");
|
|
387
|
+
const [typed] = await tx.select({ id: objects.id }).from(objects).where(eq(objects.id, prepared.resourceId)).for("update");
|
|
388
|
+
if (resource?.kind !== "object" || typed === void 0) throw new LegacyResourceRevisionError(prepared.resourceId);
|
|
389
|
+
const head = await current(tx, prepared.resourceId);
|
|
390
|
+
if (head === null || !areUuidsEqual(head.id, prepared.expectedRevisionId)) throw new RevisionConflictError(prepared.resourceId, prepared.expectedRevisionId, head?.id ?? null);
|
|
391
|
+
if (head.kind === "whiteout") throw new ResourceRevisionStateError("deleted");
|
|
392
|
+
if (head.kind !== "snapshot" || !await sameTypedState(tx, prepared.resourceId, head)) throw new LegacyResourceRevisionError(prepared.resourceId);
|
|
393
|
+
if (input.kind === "snapshot") {
|
|
394
|
+
await tx.update(objects).set({
|
|
395
|
+
...input.columns,
|
|
396
|
+
fetched: false,
|
|
397
|
+
document: sql`${prepared.serialized}::json`
|
|
398
|
+
}).where(eq(objects.id, prepared.resourceId));
|
|
399
|
+
await replaceAddressing(tx, prepared.resourceId, input.addressingOccurrences);
|
|
400
|
+
} else {
|
|
401
|
+
const [row] = await tx.select({ updated: objects.updated }).from(objects).where(eq(objects.id, prepared.resourceId));
|
|
402
|
+
await tx.update(objects).set({
|
|
403
|
+
deleted: input.deleted,
|
|
404
|
+
updated: row.updated
|
|
405
|
+
}).where(eq(objects.id, prepared.resourceId));
|
|
406
|
+
}
|
|
407
|
+
return await appendPrepared(tx, prepared, true);
|
|
408
|
+
});
|
|
409
|
+
}
|
|
310
410
|
//#endregion
|
|
311
|
-
export {
|
|
411
|
+
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 };
|
|
312
412
|
|
|
313
|
-
//# sourceMappingURL=resource-revision-
|
|
413
|
+
//# sourceMappingURL=resource-revision-iQ8HZ699.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resource-revision-iQ8HZ699.mjs","names":["addressingTable"],"sources":["../src/legacy-resource-revision-error.ts","../src/resource-revision-state-error.ts","../src/revision-conflict-error.ts","../src/legacy-resource-revision.ts","../src/resource-revision.ts"],"sourcesContent":["// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n\nimport type { Uuid } from \"./uuid.ts\";\n\n/** Legacy typed rows require the coordinated application adapter in #152. */\nexport class LegacyResourceRevisionError extends Error {\n constructor(readonly resourceId: Uuid) {\n super(\n \"Legacy typed state requires coordinated capture and must agree with retained history.\",\n );\n this.name = \"LegacyResourceRevisionError\";\n }\n}\n","// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n\n/** A requested state transition would change a saved activity or revive a deletion. */\nexport class ResourceRevisionStateError extends Error {\n constructor(\n readonly code: \"activity-immutable\" | \"deleted\" | \"initial-whiteout\",\n ) {\n super(`Unsupported resource revision transition: ${code}.`);\n this.name = \"ResourceRevisionStateError\";\n }\n}\n","// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n\nimport type { Uuid } from \"./uuid.ts\";\n\n/** The caller's expected current revision no longer matches the database. */\nexport class RevisionConflictError extends Error {\n constructor(\n readonly resourceId: Uuid,\n readonly expectedRevisionId: Uuid | null,\n readonly actualRevisionId: Uuid | null,\n ) {\n super(\"The resource's current revision has changed.\");\n this.name = \"RevisionConflictError\";\n }\n}\n","// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n\nimport { sql } from \"drizzle-orm\";\n\nimport type { Transaction } from \"./db.ts\";\nimport { LegacyResourceRevisionError } from \"./legacy-resource-revision-error.ts\";\nimport type { Uuid } from \"./uuid.ts\";\n\n/**\n * Captures fully written legacy typed state within its creating transaction.\n * This trusted compatibility operation performs no authorization or fetching.\n * Repeated calls return the original revision only when the typed state agrees.\n * @returns The first retained revision ID, including an unavailable snapshot.\n * @throws {LegacyResourceRevisionError} When typed state cannot be captured.\n */\nexport async function captureLegacyResourceRevision(\n tx: Transaction,\n resourceId: Uuid,\n): Promise<Uuid> {\n try {\n const [row] = await tx\n .select({\n id: sql<Uuid>`drfed_capture_legacy_resource(${resourceId}::uuid, false)`,\n })\n .from(sql`(VALUES (1)) AS capture_input(value)`);\n if (row === undefined) {\n throw new Error(\"Legacy capture returned no revision.\");\n }\n return row.id;\n } catch (error) {\n let detail: unknown = error;\n while (detail instanceof Error) {\n if (\n (\"constraint\" in detail &&\n detail.constraint === \"resource_revisions_legacy_guard\") ||\n (\"constraint_name\" in detail &&\n detail.constraint_name === \"resource_revisions_legacy_guard\")\n ) {\n throw new LegacyResourceRevisionError(resourceId);\n }\n detail = detail.cause;\n }\n throw error;\n }\n}\n","// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n\nimport { and, desc, eq, inArray, isNull, lt, sql } from \"drizzle-orm\";\n\nimport type { Database, Transaction } from \"./db.ts\";\nimport { LegacyResourceRevisionError } from \"./legacy-resource-revision-error.ts\";\nimport { ResourceRevisionStateError } from \"./resource-revision-state-error.ts\";\nimport {\n type AddressingInput,\n type AddressingOccurrence,\n ResourceKindConflictError,\n checkAddressingOccurrences,\n replaceAddressing,\n} from \"./resource.ts\";\nimport { RevisionConflictError } from \"./revision-conflict-error.ts\";\nimport {\n type NewActivityPubObject,\n type ResourceRevision,\n type RevisionAddressing,\n type RevisionRelation,\n activities,\n addressingPropertyEnum,\n addressing as addressingTable,\n objects,\n resourceHeads,\n resourceRevisionCaptureEnum,\n resourceRevisionProjectionEnum,\n resourceRevisions,\n resources,\n revisionAddressing,\n revisionRelations,\n} from \"./schema.ts\";\nimport { storableText } from \"./text.ts\";\nimport { type Uuid, areUuidsEqual, uuidV7, validateUuid } from \"./uuid.ts\";\n\n/** A value representable by JSON, without implicit coercion. */\nexport type JsonValue =\n | string\n | number\n | boolean\n | null\n | readonly JsonValue[]\n | {\n readonly [property: string]: JsonValue;\n };\nexport type JsonObject = { readonly [property: string]: JsonValue };\n\n/** A semantic adapter's relation projection; no JSON-LD interpretation occurs here. */\nexport interface RevisionRelationInput {\n readonly property: string;\n readonly path?: readonly (string | number)[] | null;\n readonly representation: RevisionRelation[\"representation\"];\n readonly targetIri?: string | null;\n}\n\ninterface AppendBase {\n readonly resourceId: Uuid;\n readonly resourceKind: \"object\" | \"activity\";\n /** Null requires that the resource has no current revision. */\n readonly expectedRevisionId: Uuid | null;\n}\nexport type AppendResourceRevisionInput = AppendBase &\n (\n | {\n readonly kind: \"snapshot\";\n readonly document: JsonObject;\n readonly capture: ResourceRevision[\"capture\"];\n readonly addressing?: AddressingInput;\n /**\n * Explicit occurrences at their source positions, instead of\n * `addressing`; positions of unindexed values stay unused.\n */\n readonly addressingOccurrences?: readonly AddressingOccurrence[];\n readonly relations?: readonly RevisionRelationInput[];\n readonly projection?: ResourceRevision[\"projection\"];\n }\n | {\n readonly kind: \"whiteout\";\n readonly deleted: Temporal.Instant;\n readonly formerTypes: readonly string[];\n }\n );\n\n/** Protected local JSON and projections, not an authorized or wire representation. */\nexport interface StoredResourceRevision extends ResourceRevision {\n readonly addressing: readonly RevisionAddressing[];\n readonly relations: readonly RevisionRelation[];\n}\n\nexport { RevisionConflictError } from \"./revision-conflict-error.ts\";\nexport { LegacyResourceRevisionError } from \"./legacy-resource-revision-error.ts\";\nexport { ResourceRevisionStateError } from \"./resource-revision-state-error.ts\";\n\nfunction text(value: unknown): asserts value is string {\n if (typeof value !== \"string\" || !storableText(value)) {\n throw new TypeError(\"A projection must contain losslessly storable text.\");\n }\n}\n\nfunction jsonKeys(value: object): string[] {\n const prototype: unknown = Object.getPrototypeOf(value);\n if (\n Array.isArray(value)\n ? prototype !== Array.prototype\n : prototype !== Object.prototype && prototype !== null\n ) {\n throw new TypeError(\"JSON objects must be plain records.\");\n }\n const result: string[] = [];\n for (const key of Reflect.ownKeys(value)) {\n const descriptor = Object.getOwnPropertyDescriptor(value, key);\n if (\n typeof key !== \"string\" ||\n descriptor === undefined ||\n !(\"value\" in descriptor)\n ) {\n throw new TypeError(\n \"JSON values cannot contain symbol keys or accessors.\",\n );\n }\n if (Array.isArray(value) && key === \"length\") continue;\n if (!descriptor.enumerable) {\n throw new TypeError(\"JSON members must be enumerable.\");\n }\n if (\n Array.isArray(value) &&\n (!/^(?:0|[1-9][0-9]*)$/u.test(key) || Number(key) >= value.length)\n ) {\n throw new TypeError(\"JSON arrays cannot contain named properties.\");\n }\n result.push(key);\n }\n return result;\n}\n\n// Produce JSON directly so negative zero and escaped Unicode are retained.\nfunction json(value: unknown, ancestors = new Set<object>()): string {\n if (value === null) return \"null\";\n if (typeof value === \"string\" || typeof value === \"boolean\") {\n return JSON.stringify(value);\n }\n if (typeof value === \"number\") {\n if (!Number.isFinite(value)) {\n throw new TypeError(\"JSON numbers must be finite.\");\n }\n return Object.is(value, -0) ? \"-0\" : JSON.stringify(value);\n }\n if (typeof value !== \"object\" || ancestors.has(value)) {\n throw new TypeError(\"Expected an acyclic JSON value without coercion.\");\n }\n const keys = jsonKeys(value);\n ancestors.add(value);\n try {\n if (Array.isArray(value)) {\n return `[${Array.from(value, (entry: unknown) => json(entry, ancestors)).join(\",\")}]`;\n }\n return `{${keys.map((key) => `${JSON.stringify(key)}:${json(Object.getOwnPropertyDescriptor(value, key)!.value, ancestors)}`).join(\",\")}}`;\n } finally {\n ancestors.delete(value);\n }\n}\n\nfunction projectionRows(\n input: AddressingInput = {},\n): Omit<RevisionAddressing, \"revisionId\">[] {\n const rows: Omit<RevisionAddressing, \"revisionId\">[] = [];\n for (const property of Object.keys(input)) {\n if (\n !addressingPropertyEnum.enumValues.includes(\n property as RevisionAddressing[\"property\"],\n )\n ) {\n throw new TypeError(\"Unknown addressing projection property.\");\n }\n }\n for (const property of addressingPropertyEnum.enumValues) {\n const values = input[property];\n if (values === undefined) continue;\n if (!Array.isArray(values)) {\n throw new TypeError(\"Addressing projections must be arrays.\");\n }\n for (const [position, iri] of values.entries()) {\n text(iri);\n rows.push({ property, position, iri });\n }\n }\n return rows;\n}\n\nfunction relationRows(\n input: readonly RevisionRelationInput[] = [],\n): Omit<RevisionRelation, \"revisionId\">[] {\n if (!Array.isArray(input)) {\n throw new TypeError(\"Relation projections must be arrays.\");\n }\n return input.map((relation, occurrence) => {\n text(relation.property);\n const targetIri = relation.targetIri ?? null;\n if (targetIri !== null) text(targetIri);\n if (\n ![\"reference\", \"embedded\", \"link\"].includes(relation.representation) ||\n (relation.representation === \"reference\" && targetIri === null)\n ) {\n throw new TypeError(\"Invalid relation representation.\");\n }\n const path = relation.path ?? null;\n if (\n path !== null &&\n (!Array.isArray(path) ||\n Array.from(path).some(\n (part) =>\n typeof part !== \"string\" &&\n !(Number.isSafeInteger(part) && part >= 0),\n ))\n ) {\n throw new TypeError(\n \"A relation path must contain field names and nonnegative indexes.\",\n );\n }\n return {\n occurrence,\n property: relation.property,\n representation: relation.representation,\n targetIri,\n path: path === null ? null : [...path],\n };\n });\n}\n\nasync function current(\n db: Database | Transaction,\n resourceId: Uuid,\n): Promise<ResourceRevision | null> {\n const [row] = await db\n .select({ revision: resourceRevisions })\n .from(resourceHeads)\n .innerJoin(\n resourceRevisions,\n and(\n eq(resourceHeads.resourceId, resourceRevisions.resourceId),\n eq(resourceHeads.revisionId, resourceRevisions.id),\n ),\n )\n .where(eq(resourceHeads.resourceId, resourceId))\n .limit(1);\n return row?.revision ?? null;\n}\n\nasync function hydrate(\n db: Database | Transaction,\n revision: ResourceRevision,\n): Promise<StoredResourceRevision> {\n const [addressing, relations] = await Promise.all([\n db\n .select()\n .from(revisionAddressing)\n .where(eq(revisionAddressing.revisionId, revision.id))\n .orderBy(revisionAddressing.property, revisionAddressing.position),\n db\n .select()\n .from(revisionRelations)\n .where(eq(revisionRelations.revisionId, revision.id))\n .orderBy(revisionRelations.occurrence),\n ]);\n return { ...revision, addressing, relations };\n}\n\ninterface PreparedRevision extends AppendBase {\n readonly kind: \"snapshot\" | \"whiteout\";\n readonly serialized: string | null;\n readonly capture: ResourceRevision[\"capture\"] | undefined;\n readonly projection: ResourceRevision[\"projection\"] | undefined;\n readonly addressing: Omit<RevisionAddressing, \"revisionId\">[];\n readonly relations: Omit<RevisionRelation, \"revisionId\">[];\n readonly deleted: Temporal.Instant | null;\n readonly formerTypes: string[] | null;\n}\n\ntype PreparedValue = Omit<PreparedRevision, keyof AppendBase>;\nfunction prepareSnapshot(\n input: Extract<AppendResourceRevisionInput, { kind: \"snapshot\" }>,\n): PreparedValue {\n if (\n input.document === null ||\n typeof input.document !== \"object\" ||\n Array.isArray(input.document)\n ) {\n throw new TypeError(\"A new resource document must be a JSON object.\");\n }\n const projection = input.projection ?? \"partial\";\n if (\n !resourceRevisionCaptureEnum.enumValues.includes(input.capture) ||\n !resourceRevisionProjectionEnum.enumValues.includes(projection)\n ) {\n throw new TypeError(\"Invalid capture or projection category.\");\n }\n let addressing: Omit<RevisionAddressing, \"revisionId\">[];\n if (input.addressingOccurrences === undefined) {\n addressing = projectionRows(input.addressing);\n } else {\n if (input.addressing !== undefined) {\n throw new TypeError(\"Pass addressing or its occurrences, not both.\");\n }\n checkAddressingOccurrences(input.addressingOccurrences);\n addressing = input.addressingOccurrences.map(\n ({ property, position, iri }) => {\n text(iri);\n return { property, position, iri };\n },\n );\n }\n return {\n kind: \"snapshot\",\n serialized: json(input.document),\n capture: input.capture,\n projection,\n addressing,\n relations: relationRows(input.relations),\n deleted: null,\n formerTypes: null,\n };\n}\n\nfunction prepareWhiteout(\n input: Extract<AppendResourceRevisionInput, { kind: \"whiteout\" }>,\n): PreparedValue {\n if (\n !(input.deleted instanceof Temporal.Instant) ||\n !Array.isArray(input.formerTypes)\n ) {\n throw new TypeError(\"Expected a deletion instant and former type array.\");\n }\n const formerTypes = [...input.formerTypes];\n for (const type of formerTypes) text(type);\n return {\n kind: \"whiteout\",\n serialized: null,\n capture: undefined,\n projection: undefined,\n addressing: [],\n relations: [],\n deleted: input.deleted,\n formerTypes,\n };\n}\n\nfunction prepareRevision(input: AppendResourceRevisionInput): PreparedRevision {\n const { resourceId, resourceKind, expectedRevisionId } = input;\n if (\n !validateUuid(resourceId) ||\n (expectedRevisionId !== null && !validateUuid(expectedRevisionId))\n ) {\n throw new TypeError(\"Expected canonical resource and revision UUIDs.\");\n }\n if (resourceKind !== \"object\" && resourceKind !== \"activity\") {\n throw new TypeError(\"Unsupported resource kind.\");\n }\n if (input.kind === \"snapshot\") {\n return {\n resourceId,\n resourceKind,\n expectedRevisionId,\n ...prepareSnapshot(input),\n };\n }\n if (input.kind === \"whiteout\") {\n return {\n resourceId,\n resourceKind,\n expectedRevisionId,\n ...prepareWhiteout(input),\n };\n }\n throw new TypeError(\"Unsupported revision kind.\");\n}\n\nasync function lockRevisionTarget(\n tx: Transaction,\n input: PreparedRevision,\n typed = false,\n): Promise<ResourceRevision | null> {\n const { resourceId, resourceKind, expectedRevisionId, kind } = input;\n const [resource] = await tx\n .select()\n .from(resources)\n .where(eq(resources.id, resourceId))\n .for(\"no key update\");\n if (resource === undefined) {\n throw new Error(\"The canonical resource is not registered.\");\n }\n // Read the head separately after the resource lock, including after a wait.\n const previous = await current(tx, resourceId);\n const matches =\n previous === null\n ? expectedRevisionId === null\n : expectedRevisionId !== null &&\n areUuidsEqual(previous.id, expectedRevisionId);\n if (!matches) {\n throw new RevisionConflictError(\n resourceId,\n expectedRevisionId,\n previous?.id ?? null,\n );\n }\n const [legacyObject, legacyActivity] = await Promise.all([\n tx\n .select({ id: objects.id })\n .from(objects)\n .where(eq(objects.id, resourceId))\n .limit(1),\n tx\n .select({ id: activities.id })\n .from(activities)\n .where(eq(activities.id, resourceId))\n .limit(1),\n ]);\n // A typed append has verified and changes the typed row itself.\n if (!typed && (legacyObject.length > 0 || legacyActivity.length > 0)) {\n throw new LegacyResourceRevisionError(resourceId);\n }\n if (resource.kind !== \"unknown\" && resource.kind !== resourceKind) {\n throw new ResourceKindConflictError(\n resource.iri,\n resource.kind,\n resourceKind,\n );\n }\n if (previous !== null && resourceKind === \"activity\") {\n throw new ResourceRevisionStateError(\"activity-immutable\");\n }\n if (previous?.kind === \"whiteout\") {\n throw new ResourceRevisionStateError(\"deleted\");\n }\n if (kind === \"whiteout\" && previous === null) {\n throw new ResourceRevisionStateError(\"initial-whiteout\");\n }\n if (resource.kind === \"unknown\") {\n await tx\n .update(resources)\n .set({ kind: resourceKind })\n .where(eq(resources.id, resourceId));\n }\n return previous;\n}\n\nasync function appendPrepared(\n tx: Transaction,\n input: PreparedRevision,\n typed = false,\n): Promise<StoredResourceRevision> {\n const previous = await lockRevisionTarget(tx, input, typed);\n const {\n resourceId,\n kind,\n serialized,\n capture,\n projection,\n deleted,\n formerTypes,\n addressing,\n relations,\n } = input;\n const id = uuidV7();\n const [revision] = await tx\n .insert(resourceRevisions)\n .values({\n id,\n resourceId,\n sequence: (previous?.sequence ?? 0) + 1,\n kind,\n capture: capture ?? previous!.capture,\n projection: projection ?? previous!.projection,\n document: serialized === null ? null : sql`${serialized}::json`,\n deleted,\n formerTypes,\n })\n .returning();\n if (revision === undefined) {\n throw new Error(\"Revision insertion returned no row.\");\n }\n if (kind === \"whiteout\") {\n const inherited = await hydrate(tx, previous!);\n addressing.push(\n ...inherited.addressing.map(({ revisionId: _revisionId, ...row }) => row),\n );\n relations.push(\n ...inherited.relations.map(({ revisionId: _revisionId, ...row }) => row),\n );\n }\n if (addressing.length > 0) {\n await tx\n .insert(revisionAddressing)\n .values(addressing.map((row) => ({ ...row, revisionId: id })));\n }\n if (relations.length > 0) {\n await tx\n .insert(revisionRelations)\n .values(relations.map((row) => ({ ...row, revisionId: id })));\n }\n if (previous === null) {\n await tx.insert(resourceHeads).values({ resourceId, revisionId: id });\n } else {\n await tx\n .update(resourceHeads)\n .set({ revisionId: id })\n .where(eq(resourceHeads.resourceId, resourceId));\n }\n return await hydrate(tx, revision);\n}\n\n/**\n * Appends one current object version or saved activity, atomically with projections.\n * The caller must validate the document and authorize the write. Lock multiple\n * canonical IRIs in sorted order before composing several appends in one transaction.\n * This does not publish, change collection membership, or reserve delivery.\n * @returns The stored revision, including protected blind addressing.\n */\nexport async function appendResourceRevision(\n db: Database | Transaction,\n input: AppendResourceRevisionInput,\n): Promise<StoredResourceRevision> {\n const prepared = prepareRevision(input);\n return await db.transaction((tx) => appendPrepared(tx, prepared));\n}\n\n/**\n * Loads protected local JSON without applying authorization or stripping bto/bcc.\n * @returns The immutable revision and projections, or null if not found.\n */\nexport async function loadResourceRevision(\n db: Database | Transaction,\n revisionId: Uuid,\n): Promise<StoredResourceRevision | null> {\n const [revision] = await db\n .select()\n .from(resourceRevisions)\n .where(eq(resourceRevisions.id, revisionId))\n .limit(1);\n return revision === undefined ? null : await hydrate(db, revision);\n}\n\n/**\n * Loads current protected local state without dereferencing any document target.\n * @returns A snapshot, unavailable record or whiteout, or null when unversioned.\n */\nexport async function loadCurrentResourceRevision(\n db: Database | Transaction,\n resourceId: Uuid,\n): Promise<StoredResourceRevision | null> {\n const revision = await current(db, resourceId);\n return revision === null ? null : await hydrate(db, revision);\n}\n\nconst MAX_HISTORY_LIMIT = 100;\nconst DEFAULT_HISTORY_LIMIT = 20;\n/**\n * Lists protected history in descending sequence order; authorization belongs to callers.\n * @returns Up to limit revisions strictly before beforeSequence, when supplied.\n */\nexport async function listResourceRevisions(\n db: Database | Transaction,\n resourceId: Uuid,\n options: { readonly beforeSequence?: number; readonly limit?: number } = {},\n): Promise<StoredResourceRevision[]> {\n const { beforeSequence, limit = DEFAULT_HISTORY_LIMIT } = options;\n if (\n !Number.isInteger(limit) ||\n limit < 1 ||\n limit > MAX_HISTORY_LIMIT ||\n (beforeSequence !== undefined &&\n (!Number.isSafeInteger(beforeSequence) || beforeSequence < 1))\n ) {\n throw new RangeError(\"Invalid history bounds.\");\n }\n const revisions = await db\n .select()\n .from(resourceRevisions)\n .where(\n and(\n eq(resourceRevisions.resourceId, resourceId),\n beforeSequence === undefined\n ? undefined\n : lt(resourceRevisions.sequence, beforeSequence),\n ),\n )\n .orderBy(desc(resourceRevisions.sequence))\n .limit(limit);\n if (revisions.length === 0) return [];\n const revisionIds = revisions.map(({ id }) => id);\n const [addressing, relations] = await Promise.all([\n db\n .select()\n .from(revisionAddressing)\n .where(inArray(revisionAddressing.revisionId, revisionIds))\n .orderBy(revisionAddressing.property, revisionAddressing.position),\n db\n .select()\n .from(revisionRelations)\n .where(inArray(revisionRelations.revisionId, revisionIds))\n .orderBy(revisionRelations.occurrence),\n ]);\n const addressingByRevision = new Map<Uuid, RevisionAddressing[]>();\n for (const row of addressing) {\n const rows = addressingByRevision.get(row.revisionId) ?? [];\n rows.push(row);\n addressingByRevision.set(row.revisionId, rows);\n }\n const relationsByRevision = new Map<Uuid, RevisionRelation[]>();\n for (const row of relations) {\n const rows = relationsByRevision.get(row.revisionId) ?? [];\n rows.push(row);\n relationsByRevision.set(row.revisionId, rows);\n }\n return revisions.map((revision) => ({\n ...revision,\n addressing: addressingByRevision.get(revision.id) ?? [],\n relations: relationsByRevision.get(revision.id) ?? [],\n }));\n}\n\n/** Typed object columns a coordinated edit may set, besides its document. */\nexport type TypedObjectColumns = Pick<\n NewActivityPubObject,\n | \"type\"\n | \"url\"\n | \"name\"\n | \"summary\"\n | \"contentHtml\"\n | \"language\"\n | \"sensitive\"\n | \"published\"\n | \"updated\"\n>;\n\ninterface TypedRevisionBase {\n readonly resourceId: Uuid;\n /** The current revision; a typed object always has one. */\n readonly expectedRevisionId: Uuid;\n}\nexport type TypedResourceRevisionInput = TypedRevisionBase &\n (\n | {\n readonly kind: \"snapshot\";\n readonly document: JsonObject;\n /** Every column the typed row serves; `updated` is not implied. */\n readonly columns: Required<Omit<TypedObjectColumns, \"type\">> &\n Partial<Pick<TypedObjectColumns, \"type\">>;\n readonly addressingOccurrences: readonly AddressingOccurrence[];\n readonly relations?: readonly RevisionRelationInput[];\n readonly projection?: ResourceRevision[\"projection\"];\n }\n | {\n readonly kind: \"whiteout\";\n readonly deleted: Temporal.Instant;\n readonly formerTypes: readonly string[];\n }\n );\n\nasync function sameTypedState(\n tx: Transaction,\n resourceId: Uuid,\n head: ResourceRevision,\n): Promise<boolean> {\n // Compare JSON text, as legacy capture does, rather than parsed values.\n const [row] = await tx\n .select({\n same: sql<boolean>`${objects.document}::text IS NOT DISTINCT FROM ${resourceRevisions.document}::text\n AND NOT EXISTS (\n (SELECT saved.property, saved.position, saved.iri\n FROM ${revisionAddressing} AS saved\n WHERE saved.revision_id = ${head.id})\n EXCEPT ALL\n (SELECT declared.property, declared.position, target.iri\n FROM ${addressingTable} AS declared\n JOIN ${resources} AS target ON target.id = declared.target_id\n WHERE declared.source_id = ${resourceId})\n )\n AND NOT EXISTS (\n (SELECT declared.property, declared.position, target.iri\n FROM ${addressingTable} AS declared\n JOIN ${resources} AS target ON target.id = declared.target_id\n WHERE declared.source_id = ${resourceId})\n EXCEPT ALL\n (SELECT saved.property, saved.position, saved.iri\n FROM ${revisionAddressing} AS saved\n WHERE saved.revision_id = ${head.id})\n )`,\n })\n .from(objects)\n .innerJoin(resourceRevisions, eq(resourceRevisions.id, head.id))\n .where(and(eq(objects.id, resourceId), isNull(objects.deleted)));\n return row?.same === true;\n}\n\n/**\n * Edits or deletes an object that has a legacy typed row, keeping the typed\n * row, its current addressing, and the revision history in step. Under the\n * canonical lock, the current revision must be the expected snapshot, and the\n * typed row's document and addressing must still equal it; otherwise nothing\n * changes. A snapshot sets the typed columns, the typed document to the same\n * JSON as the new revision, and the current addressing to the occurrences. A\n * whiteout soft-deletes the typed row and keeps its addressing, which\n * continues to describe the last content. The caller must validate and\n * authorize the change and check any served column against the old head.\n * The whole write runs in a savepoint, so a caught error leaves no part of it.\n * @returns The appended revision, including protected blind addressing.\n * @throws {RevisionConflictError} If the current revision is not the expected.\n * @throws {LegacyResourceRevisionError} If the resource has no live typed\n * object or the typed state differs from its current revision.\n * @throws {ResourceRevisionStateError} If the object is already deleted.\n */\nexport async function writeTypedResourceRevision(\n db: Database | Transaction,\n input: TypedResourceRevisionInput,\n): Promise<StoredResourceRevision> {\n const prepared = prepareRevision(\n input.kind === \"snapshot\"\n ? {\n resourceId: input.resourceId,\n resourceKind: \"object\",\n expectedRevisionId: input.expectedRevisionId,\n kind: \"snapshot\",\n document: input.document,\n capture: \"local\",\n addressingOccurrences: input.addressingOccurrences,\n ...(input.relations === undefined\n ? {}\n : { relations: input.relations }),\n ...(input.projection === undefined\n ? {}\n : { projection: input.projection }),\n }\n : {\n resourceId: input.resourceId,\n resourceKind: \"object\",\n expectedRevisionId: input.expectedRevisionId,\n kind: \"whiteout\",\n deleted: input.deleted,\n formerTypes: input.formerTypes,\n },\n );\n if (prepared.expectedRevisionId === null) {\n throw new TypeError(\"A typed object always has a current revision.\");\n }\n return await db.transaction(async (tx) => {\n const [resource] = await tx\n .select({ kind: resources.kind })\n .from(resources)\n .where(eq(resources.id, prepared.resourceId))\n .for(\"no key update\");\n const [typed] = await tx\n .select({ id: objects.id })\n .from(objects)\n .where(eq(objects.id, prepared.resourceId))\n .for(\"update\");\n if (resource?.kind !== \"object\" || typed === undefined) {\n throw new LegacyResourceRevisionError(prepared.resourceId);\n }\n const head = await current(tx, prepared.resourceId);\n if (\n head === null ||\n !areUuidsEqual(head.id, prepared.expectedRevisionId!)\n ) {\n throw new RevisionConflictError(\n prepared.resourceId,\n prepared.expectedRevisionId,\n head?.id ?? null,\n );\n }\n if (head.kind === \"whiteout\") {\n throw new ResourceRevisionStateError(\"deleted\");\n }\n if (\n head.kind !== \"snapshot\" ||\n !(await sameTypedState(tx, prepared.resourceId, head))\n ) {\n throw new LegacyResourceRevisionError(prepared.resourceId);\n }\n if (input.kind === \"snapshot\") {\n await tx\n .update(objects)\n .set({\n ...input.columns,\n // The edited document is local, not a copy fetched from its IRI.\n fetched: false,\n document: sql`${prepared.serialized}::json`,\n })\n .where(eq(objects.id, prepared.resourceId));\n await replaceAddressing(\n tx,\n prepared.resourceId,\n input.addressingOccurrences,\n );\n } else {\n // Keep the update hook from moving `updated` past the deletion.\n const [row] = await tx\n .select({ updated: objects.updated })\n .from(objects)\n .where(eq(objects.id, prepared.resourceId));\n await tx\n .update(objects)\n .set({ deleted: input.deleted, updated: row!.updated })\n .where(eq(objects.id, prepared.resourceId));\n }\n return await appendPrepared(tx, prepared, true);\n });\n}\n\nexport { captureLegacyResourceRevision } from \"./legacy-resource-revision.ts\";\n"],"mappings":";;;;;;;AAmBA,IAAa,8BAAb,cAAiD,MAAM;CAChC;CAArB,YAAY,YAA2B;EACrC,MACE,uFACF;EAHmB,KAAA,aAAA;EAInB,KAAK,OAAO;CACd;AACF;;;;ACTA,IAAa,6BAAb,cAAgD,MAAM;CAEzC;CADX,YACE,MACA;EACA,MAAM,6CAA6C,KAAK,EAAE;EAFjD,KAAA,OAAA;EAGT,KAAK,OAAO;CACd;AACF;;;;ACLA,IAAa,wBAAb,cAA2C,MAAM;CAEpC;CACA;CACA;CAHX,YACE,YACA,oBACA,kBACA;EACA,MAAM,8CAA8C;EAJ3C,KAAA,aAAA;EACA,KAAA,qBAAA;EACA,KAAA,mBAAA;EAGT,KAAK,OAAO;CACd;AACF;;;;;;;;;;ACCA,eAAsB,8BACpB,IACA,YACe;CACf,IAAI;EACF,MAAM,CAAC,OAAO,MAAM,GACjB,OAAO,EACN,IAAI,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MAAM,GAAG,QAAQ,IAAI,SAAS,UAAU,CAAC;GAC5C,MAAM,GACH,OAAO,OAAO,CAAC,CACf,IAAI;IAAE,SAAS,MAAM;IAAS,SAAS,IAAK;GAAQ,CAAC,CAAC,CACtD,MAAM,GAAG,QAAQ,IAAI,SAAS,UAAU,CAAC;EAC9C;EACA,OAAO,MAAM,eAAe,IAAI,UAAU,IAAI;CAChD,CAAC;AACH"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as StoredResourceRevision, c as
|
|
2
|
-
export { AppendResourceRevisionInput, JsonObject, JsonValue, LegacyResourceRevisionError, ResourceRevisionStateError, RevisionConflictError, RevisionRelationInput, StoredResourceRevision, appendResourceRevision, captureLegacyResourceRevision, listResourceRevisions, loadCurrentResourceRevision, loadResourceRevision };
|
|
1
|
+
import { a as StoredResourceRevision, c as appendResourceRevision, d as loadResourceRevision, f as writeTypedResourceRevision, g as RevisionConflictError, h as LegacyResourceRevisionError, i as RevisionRelationInput, l as listResourceRevisions, m as ResourceRevisionStateError, n as JsonObject, o as TypedObjectColumns, p as captureLegacyResourceRevision, r as JsonValue, s as TypedResourceRevisionInput, t as AppendResourceRevisionInput, u as loadCurrentResourceRevision } from "./resource-revision-BauDwFIn.mjs";
|
|
2
|
+
export { AppendResourceRevisionInput, JsonObject, JsonValue, LegacyResourceRevisionError, ResourceRevisionStateError, RevisionConflictError, RevisionRelationInput, StoredResourceRevision, TypedObjectColumns, TypedResourceRevisionInput, appendResourceRevision, captureLegacyResourceRevision, listResourceRevisions, loadCurrentResourceRevision, loadResourceRevision, writeTypedResourceRevision };
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
import "./resource.mjs";
|
|
2
2
|
import "./text.mjs";
|
|
3
|
-
export {
|
|
3
|
+
export { l as LegacyResourceRevisionError, c as ResourceRevisionStateError, s as RevisionConflictError, t as appendResourceRevision, o as captureLegacyResourceRevision, n as listResourceRevisions, r as loadCurrentResourceRevision, i as loadResourceRevision, a as writeTypedResourceRevision } from "./resource-revision-iQ8HZ699.mjs";
|
package/dist/resource.d.mts
CHANGED
|
@@ -33,6 +33,32 @@ declare function promoteResource<T>(db: Database | Transaction, iri: string, kin
|
|
|
33
33
|
type AddressingInput = Readonly<Partial<Record<AddressingProperty, readonly string[]>>>;
|
|
34
34
|
/** Stores every occurrence, including duplicates, in its original position. */
|
|
35
35
|
declare function storeAddressing(tx: Transaction, sourceId: Uuid, input: AddressingInput): Promise<void>;
|
|
36
|
+
/**
|
|
37
|
+
* One addressing occurrence at its source position. Positions need not be
|
|
38
|
+
* contiguous: a value that names no IRI, such as an anonymous embedded object,
|
|
39
|
+
* leaves its position unused instead of shifting the later ones.
|
|
40
|
+
*/
|
|
41
|
+
interface AddressingOccurrence {
|
|
42
|
+
readonly property: AddressingProperty;
|
|
43
|
+
readonly position: number;
|
|
44
|
+
readonly iri: string;
|
|
45
|
+
}
|
|
46
|
+
/**
|
|
47
|
+
* Stores explicit occurrences, keeping each at its own position.
|
|
48
|
+
* @throws {TypeError} If a property is unknown, a position is not a
|
|
49
|
+
* non-negative safe integer, or two occurrences share a position.
|
|
50
|
+
*/
|
|
51
|
+
declare function storeAddressingOccurrences(tx: Transaction, sourceId: Uuid, occurrences: readonly AddressingOccurrence[]): Promise<void>;
|
|
52
|
+
/**
|
|
53
|
+
* Replaces the current addressing of a resource with explicit occurrences.
|
|
54
|
+
* @throws {TypeError} As {@link storeAddressingOccurrences} does.
|
|
55
|
+
*/
|
|
56
|
+
declare function replaceAddressing(tx: Transaction, sourceId: Uuid, occurrences: readonly AddressingOccurrence[]): Promise<void>;
|
|
57
|
+
/**
|
|
58
|
+
* Checks occurrences before any write, so a malformed list writes nothing.
|
|
59
|
+
* @throws {TypeError} If an occurrence is malformed or duplicated.
|
|
60
|
+
*/
|
|
61
|
+
declare function checkAddressingOccurrences(occurrences: readonly AddressingOccurrence[]): void;
|
|
36
62
|
/**
|
|
37
63
|
* Locks an actor's declared collection until the transaction ends.
|
|
38
64
|
* @returns The locked collection ID.
|
|
@@ -46,5 +72,5 @@ declare function lockActorCollection(tx: Transaction, actorId: Uuid, role: Colle
|
|
|
46
72
|
*/
|
|
47
73
|
declare function addActorCollectionItem(db: Database | Transaction, actorId: Uuid, role: CollectionRole, itemId: Uuid): Promise<void>;
|
|
48
74
|
//#endregion
|
|
49
|
-
export { AddressingInput, PUBLIC_IRI, PUBLIC_RESOURCE_ID, ResourceKindConflictError, addActorCollectionItem, ensureResource, lockActorCollection, lockResources, promoteResource, storeAddressing };
|
|
75
|
+
export { AddressingInput, AddressingOccurrence, PUBLIC_IRI, PUBLIC_RESOURCE_ID, ResourceKindConflictError, addActorCollectionItem, checkAddressingOccurrences, ensureResource, lockActorCollection, lockResources, promoteResource, replaceAddressing, storeAddressing, storeAddressingOccurrences };
|
|
50
76
|
//# sourceMappingURL=resource.d.mts.map
|
package/dist/resource.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resource.d.mts","names":[],"sources":["../src/resource.ts"],"mappings":";;;cAmCa;cACA,oBAAoB;;;;;iBAMX,eACpB,IAAI,WAAW,aACf,aACA,2DACC,QAAQ;;;;;;iBAqCW,cACpB,IAAI,aACJ,0BACC;;cAYU,kCAAkC;WAElC;WACA,MAAM;WACN,WAAW,QAAQ;EAH9B,YACW,aACA,MAAM,kBACN,WAAW,QAAQ;;;;;;;;;;iBAeV,gBAAgB,GACpC,IAAI,WAAW,aACf,aACA,MAAM,QAAQ,8BACd,SAAS,IAAI,aAAa,UAAU,aAAa,QAAQ,IACzD,KAAK,MACL,SAAS,IAAI,aAAa,UAAU,aAAa,QAAQ,KACxD,QAAQ;KA8BC,kBAAkB,SAC5B,QAAQ,OAAO;;iBAIK,gBACpB,IAAI,aACJ,UAAU,MACV,OAAO,kBACN;;;;;
|
|
1
|
+
{"version":3,"file":"resource.d.mts","names":[],"sources":["../src/resource.ts"],"mappings":";;;cAmCa;cACA,oBAAoB;;;;;iBAMX,eACpB,IAAI,WAAW,aACf,aACA,2DACC,QAAQ;;;;;;iBAqCW,cACpB,IAAI,aACJ,0BACC;;cAYU,kCAAkC;WAElC;WACA,MAAM;WACN,WAAW,QAAQ;EAH9B,YACW,aACA,MAAM,kBACN,WAAW,QAAQ;;;;;;;;;;iBAeV,gBAAgB,GACpC,IAAI,WAAW,aACf,aACA,MAAM,QAAQ,8BACd,SAAS,IAAI,aAAa,UAAU,aAAa,QAAQ,IACzD,KAAK,MACL,SAAS,IAAI,aAAa,UAAU,aAAa,QAAQ,KACxD,QAAQ;KA8BC,kBAAkB,SAC5B,QAAQ,OAAO;;iBAIK,gBACpB,IAAI,aACJ,UAAU,MACV,OAAO,kBACN;;;;;;UA+Bc;WACN,UAAU;WACV;WACA;;;;;;;iBAQW,2BACpB,IAAI,aACJ,UAAU,MACV,sBAAsB,yBACrB;;;;;iBAuBmB,kBACpB,IAAI,aACJ,UAAU,MACV,sBAAsB,yBACrB;;;;;iBAUa,2BACd,sBAAsB;;;;;iBA6BF,oBACpB,IAAI,aACJ,SAAS,MACT,MAAM,iBACL,QAAQ;;;;;;;iBA4BW,uBACpB,IAAI,WAAW,aACf,SAAS,MACT,MAAM,gBACN,QAAQ,OACP"}
|
package/dist/resource.mjs
CHANGED
|
@@ -92,6 +92,46 @@ async function storeAddressing(tx, sourceId, input) {
|
|
|
92
92
|
}
|
|
93
93
|
}
|
|
94
94
|
/**
|
|
95
|
+
* Stores explicit occurrences, keeping each at its own position.
|
|
96
|
+
* @throws {TypeError} If a property is unknown, a position is not a
|
|
97
|
+
* non-negative safe integer, or two occurrences share a position.
|
|
98
|
+
*/
|
|
99
|
+
async function storeAddressingOccurrences(tx, sourceId, occurrences) {
|
|
100
|
+
checkAddressingOccurrences(occurrences);
|
|
101
|
+
const targets = /* @__PURE__ */ new Map();
|
|
102
|
+
for (const iri of [...new Set(occurrences.map((entry) => entry.iri))].sort()) targets.set(iri, await ensureResource(tx, iri));
|
|
103
|
+
for (const { property, position, iri } of occurrences) await tx.insert(addressing).values({
|
|
104
|
+
id: uuidV7(),
|
|
105
|
+
sourceId,
|
|
106
|
+
property,
|
|
107
|
+
position,
|
|
108
|
+
targetId: targets.get(iri).id
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Replaces the current addressing of a resource with explicit occurrences.
|
|
113
|
+
* @throws {TypeError} As {@link storeAddressingOccurrences} does.
|
|
114
|
+
*/
|
|
115
|
+
async function replaceAddressing(tx, sourceId, occurrences) {
|
|
116
|
+
checkAddressingOccurrences(occurrences);
|
|
117
|
+
await tx.delete(addressing).where(eq(addressing.sourceId, sourceId));
|
|
118
|
+
await storeAddressingOccurrences(tx, sourceId, occurrences);
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Checks occurrences before any write, so a malformed list writes nothing.
|
|
122
|
+
* @throws {TypeError} If an occurrence is malformed or duplicated.
|
|
123
|
+
*/
|
|
124
|
+
function checkAddressingOccurrences(occurrences) {
|
|
125
|
+
if (!Array.isArray(occurrences)) throw new TypeError("Addressing occurrences must be an array.");
|
|
126
|
+
const seen = /* @__PURE__ */ new Set();
|
|
127
|
+
for (const { property, position, iri } of occurrences) {
|
|
128
|
+
if (!addressingPropertyEnum.enumValues.includes(property) || !Number.isSafeInteger(position) || position < 0 || position > 2147483647 || typeof iri !== "string") throw new TypeError("Invalid addressing occurrence.");
|
|
129
|
+
const key = `${property}:${position}`;
|
|
130
|
+
if (seen.has(key)) throw new TypeError("Addressing occurrences must not share a position.");
|
|
131
|
+
seen.add(key);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
/**
|
|
95
135
|
* Locks an actor's declared collection until the transaction ends.
|
|
96
136
|
* @returns The locked collection ID.
|
|
97
137
|
*/
|
|
@@ -118,6 +158,6 @@ async function addActorCollectionItem(db, actorId, role, itemId) {
|
|
|
118
158
|
});
|
|
119
159
|
}
|
|
120
160
|
//#endregion
|
|
121
|
-
export { PUBLIC_IRI, PUBLIC_RESOURCE_ID, ResourceKindConflictError, addActorCollectionItem, ensureResource, lockActorCollection, lockResources, promoteResource, storeAddressing };
|
|
161
|
+
export { PUBLIC_IRI, PUBLIC_RESOURCE_ID, ResourceKindConflictError, addActorCollectionItem, checkAddressingOccurrences, ensureResource, lockActorCollection, lockResources, promoteResource, replaceAddressing, storeAddressing, storeAddressingOccurrences };
|
|
122
162
|
|
|
123
163
|
//# sourceMappingURL=resource.mjs.map
|
package/dist/resource.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resource.mjs","names":[],"sources":["../src/resource.ts"],"sourcesContent":["// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n\n// Keep dependent database writes and observations sequential.\n// oxlint-disable no-await-in-loop\n\nimport { and, asc, eq, inArray, min } from \"drizzle-orm\";\n\nimport type { Database, Transaction } from \"./db.ts\";\nimport {\n type AddressingProperty,\n type CollectionRole,\n type Resource,\n actorCollectionReferences,\n addressing,\n addressingPropertyEnum,\n collectionItems,\n collections,\n resources,\n} from \"./schema.ts\";\nimport { type Uuid, uuidV7 } from \"./uuid.ts\";\n\nexport const PUBLIC_IRI = \"https://www.w3.org/ns/activitystreams#Public\";\nexport const PUBLIC_RESOURCE_ID: Uuid = \"00000000-0000-4000-8000-000000000000\";\n\n/**\n * Returns the canonical resource without interpreting or normalizing its IRI.\n * @returns The existing or newly registered resource.\n */\nexport async function ensureResource(\n tx: Database | Transaction,\n iri: string,\n id = uuidV7(),\n): Promise<Resource> {\n const [existing] = await tx\n .select()\n .from(resources)\n .where(eq(resources.iri, iri))\n .limit(1);\n if (existing != null) return existing;\n const [inserted] = await tx\n .insert(resources)\n .values({ id, iri, kind: \"unknown\" })\n .onConflictDoNothing({ target: resources.iri })\n .returning();\n if (inserted != null) return inserted;\n // A concurrent insertion can win after the first SELECT. A separate\n // statement sees that committed row under PostgreSQL's READ COMMITTED.\n const [resource] = await tx\n .select()\n .from(resources)\n .where(eq(resources.iri, iri))\n .limit(1);\n if (resource == null) throw new Error(\"Resource insertion returned no row.\");\n return resource;\n}\n\n/**\n * Promotions of one resource exclude each other, but not the foreign key\n * checks of rows referring to it, such as addressing it: `kind` is no key.\n * An exclusive lock would make two writers that each promote one resource and\n * address the other deadlock.\n */\nconst PROMOTION_LOCK = \"no key update\";\n\n/**\n * Locks resources for promotion in IRI order, so that transactions promoting\n * several of them never wait for each other in a cycle. Only registered IRIs\n * are locked; see {@link ensureResource}.\n */\nexport async function lockResources(\n tx: Transaction,\n iris: readonly string[],\n): Promise<void> {\n if (iris.length === 0) return;\n // PostgreSQL locks the rows after sorting them.\n await tx\n .select({ id: resources.id })\n .from(resources)\n .where(inArray(resources.iri, [...iris]))\n .orderBy(asc(resources.iri))\n .for(PROMOTION_LOCK);\n}\n\n/** Thrown when an IRI is already registered as another kind of resource. */\nexport class ResourceKindConflictError extends Error {\n constructor(\n readonly iri: string,\n readonly kind: Resource[\"kind\"],\n readonly requested: Exclude<Resource[\"kind\"], \"unknown\">,\n ) {\n super(`Resource ${iri} is already a ${kind}.`);\n this.name = \"ResourceKindConflictError\";\n }\n}\n\n/**\n * Atomically promotes an unknown IRI and inserts its typed row. An IRI that\n * already is of the kind is passed to `reuse` instead, under the same lock, so\n * that concurrent writers of one IRI insert its typed row once.\n * @returns The typed-row insertion or reuse callback result.\n * @throws {ResourceKindConflictError} If the IRI is another kind of resource.\n * @throws {Error} If the IRI already is of the kind and `reuse` is not given.\n */\nexport async function promoteResource<T>(\n db: Database | Transaction,\n iri: string,\n kind: Exclude<Resource[\"kind\"], \"unknown\">,\n insert: (tx: Transaction, resource: Resource) => Promise<T>,\n id?: Uuid,\n reuse?: (tx: Transaction, resource: Resource) => Promise<T>,\n): Promise<T> {\n return await db.transaction(async (tx) => {\n const ensured = await ensureResource(tx, iri, id);\n // Re-read the kind after locking so a concurrent promotion cannot change\n // it between validation and update.\n const [resource] = await tx\n .select()\n .from(resources)\n .where(eq(resources.id, ensured.id))\n .for(PROMOTION_LOCK);\n if (resource == null) {\n throw new Error(\"Resource disappeared during promotion.\");\n }\n if (resource.kind === kind) {\n if (reuse == null) {\n throw new Error(`Resource ${iri} has already been promoted.`);\n }\n return await reuse(tx, resource);\n }\n if (resource.kind !== \"unknown\") {\n throw new ResourceKindConflictError(iri, resource.kind, kind);\n }\n await tx\n .update(resources)\n .set({ kind })\n .where(eq(resources.id, resource.id));\n return await insert(tx, { ...resource, kind });\n });\n}\n\nexport type AddressingInput = Readonly<\n Partial<Record<AddressingProperty, readonly string[]>>\n>;\n\n/** Stores every occurrence, including duplicates, in its original position. */\nexport async function storeAddressing(\n tx: Transaction,\n sourceId: Uuid,\n input: AddressingInput,\n): Promise<void> {\n // Acquire unique-index locks for new IRIs in a consistent order across\n // writers. This does not change occurrence order in the addressing rows.\n const targets = new Map<string, Resource>();\n const iris = [\n ...new Set(\n addressingPropertyEnum.enumValues.flatMap(\n (property) => input[property] ?? [],\n ),\n ),\n ].sort();\n for (const iri of iris) targets.set(iri, await ensureResource(tx, iri));\n for (const property of addressingPropertyEnum.enumValues) {\n for (const [position, iri] of (input[property] ?? []).entries()) {\n const target = targets.get(iri)!;\n await tx.insert(addressing).values({\n id: uuidV7(),\n sourceId,\n property,\n position,\n targetId: target.id,\n });\n }\n }\n}\n\n/**\n * Locks an actor's declared collection until the transaction ends.\n * @returns The locked collection ID.\n */\nexport async function lockActorCollection(\n tx: Transaction,\n actorId: Uuid,\n role: CollectionRole,\n): Promise<Uuid> {\n const [reference] = await tx\n .select({ collectionId: collections.id })\n .from(collections)\n .innerJoin(\n actorCollectionReferences,\n eq(collections.id, actorCollectionReferences.collectionId),\n )\n .where(\n and(\n eq(actorCollectionReferences.actorId, actorId),\n eq(actorCollectionReferences.role, role),\n ),\n )\n .for(\"update\", { of: collections })\n .limit(1);\n if (reference == null) {\n throw new Error(`Actor ${actorId} declares no ${role} collection.`);\n }\n return reference.collectionId;\n}\n\n/**\n * Records a resource in an actor's declared collection, idempotently.\n * Position ASC is presentation order. Outboxes are reverse chronological,\n * so the newest item receives the smallest position.\n * @throws {Error} If the actor declares no collection for the role.\n */\nexport async function addActorCollectionItem(\n db: Database | Transaction,\n actorId: Uuid,\n role: CollectionRole,\n itemId: Uuid,\n): Promise<void> {\n await db.transaction(async (tx) => {\n const collectionId = await lockActorCollection(tx, actorId, role);\n const [row] = await tx\n .select({ position: min(collectionItems.position) })\n .from(collectionItems)\n .where(eq(collectionItems.collectionId, collectionId));\n await tx\n .insert(collectionItems)\n .values({ collectionId, itemId, position: (row?.position ?? 0) - 1 })\n .onConflictDoNothing();\n });\n}\n"],"mappings":";;;;AAmCA,MAAa,aAAa;AAC1B,MAAa,qBAA2B;;;;;AAMxC,eAAsB,eACpB,IACA,KACA,KAAK,OAAO,GACO;CACnB,MAAM,CAAC,YAAY,MAAM,GACtB,OAAO,CAAC,CACR,KAAK,SAAS,CAAC,CACf,MAAM,GAAG,UAAU,KAAK,GAAG,CAAC,CAAC,CAC7B,MAAM,CAAC;CACV,IAAI,YAAY,MAAM,OAAO;CAC7B,MAAM,CAAC,YAAY,MAAM,GACtB,OAAO,SAAS,CAAC,CACjB,OAAO;EAAE;EAAI;EAAK,MAAM;CAAU,CAAC,CAAC,CACpC,oBAAoB,EAAE,QAAQ,UAAU,IAAI,CAAC,CAAC,CAC9C,UAAU;CACb,IAAI,YAAY,MAAM,OAAO;CAG7B,MAAM,CAAC,YAAY,MAAM,GACtB,OAAO,CAAC,CACR,KAAK,SAAS,CAAC,CACf,MAAM,GAAG,UAAU,KAAK,GAAG,CAAC,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oB,IAAI,SAAS,IAAI;EAChE,MAAM,CAAC,OAAO,MAAM,GACjB,OAAO,EAAE,UAAU,IAAI,gBAAgB,QAAQ,EAAE,CAAC,CAAC,CACnD,KAAK,eAAe,CAAC,CACrB,MAAM,GAAG,gBAAgB,cAAc,YAAY,CAAC;EACvD,MAAM,GACH,OAAO,eAAe,CAAC,CACvB,OAAO;GAAE;GAAc;GAAQ,WAAW,KAAK,YAAY,KAAK;EAAE,CAAC,CAAC,CACpE,oBAAoB;CACzB,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"resource.mjs","names":[],"sources":["../src/resource.ts"],"sourcesContent":["// DrFed: A web-based platform for developing and debugging ActivityPub apps\n// Copyright (C) 2026 DrFed team\n//\n// This program is free software: you can redistribute it and/or modify\n// it under the terms of the GNU Affero General Public License as published by\n// the Free Software Foundation, either version 3 of the License, or\n// (at your option) any later version.\n//\n// This program is distributed in the hope that it will be useful,\n// but WITHOUT ANY WARRANTY; without even the implied warranty of\n// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n// GNU Affero General Public License for more details.\n//\n// You should have received a copy of the GNU Affero General Public License\n// along with this program. If not, see <https://www.gnu.org/licenses/>.\n\n// Keep dependent database writes and observations sequential.\n// oxlint-disable no-await-in-loop\n\nimport { and, asc, eq, inArray, min } from \"drizzle-orm\";\n\nimport type { Database, Transaction } from \"./db.ts\";\nimport {\n type AddressingProperty,\n type CollectionRole,\n type Resource,\n actorCollectionReferences,\n addressing,\n addressingPropertyEnum,\n collectionItems,\n collections,\n resources,\n} from \"./schema.ts\";\nimport { type Uuid, uuidV7 } from \"./uuid.ts\";\n\nexport const PUBLIC_IRI = \"https://www.w3.org/ns/activitystreams#Public\";\nexport const PUBLIC_RESOURCE_ID: Uuid = \"00000000-0000-4000-8000-000000000000\";\n\n/**\n * Returns the canonical resource without interpreting or normalizing its IRI.\n * @returns The existing or newly registered resource.\n */\nexport async function ensureResource(\n tx: Database | Transaction,\n iri: string,\n id = uuidV7(),\n): Promise<Resource> {\n const [existing] = await tx\n .select()\n .from(resources)\n .where(eq(resources.iri, iri))\n .limit(1);\n if (existing != null) return existing;\n const [inserted] = await tx\n .insert(resources)\n .values({ id, iri, kind: \"unknown\" })\n .onConflictDoNothing({ target: resources.iri })\n .returning();\n if (inserted != null) return inserted;\n // A concurrent insertion can win after the first SELECT. A separate\n // statement sees that committed row under PostgreSQL's READ COMMITTED.\n const [resource] = await tx\n .select()\n .from(resources)\n .where(eq(resources.iri, iri))\n .limit(1);\n if (resource == null) throw new Error(\"Resource insertion returned no row.\");\n return resource;\n}\n\n/**\n * Promotions of one resource exclude each other, but not the foreign key\n * checks of rows referring to it, such as addressing it: `kind` is no key.\n * An exclusive lock would make two writers that each promote one resource and\n * address the other deadlock.\n */\nconst PROMOTION_LOCK = \"no key update\";\n\n/**\n * Locks resources for promotion in IRI order, so that transactions promoting\n * several of them never wait for each other in a cycle. Only registered IRIs\n * are locked; see {@link ensureResource}.\n */\nexport async function lockResources(\n tx: Transaction,\n iris: readonly string[],\n): Promise<void> {\n if (iris.length === 0) return;\n // PostgreSQL locks the rows after sorting them.\n await tx\n .select({ id: resources.id })\n .from(resources)\n .where(inArray(resources.iri, [...iris]))\n .orderBy(asc(resources.iri))\n .for(PROMOTION_LOCK);\n}\n\n/** Thrown when an IRI is already registered as another kind of resource. */\nexport class ResourceKindConflictError extends Error {\n constructor(\n readonly iri: string,\n readonly kind: Resource[\"kind\"],\n readonly requested: Exclude<Resource[\"kind\"], \"unknown\">,\n ) {\n super(`Resource ${iri} is already a ${kind}.`);\n this.name = \"ResourceKindConflictError\";\n }\n}\n\n/**\n * Atomically promotes an unknown IRI and inserts its typed row. An IRI that\n * already is of the kind is passed to `reuse` instead, under the same lock, so\n * that concurrent writers of one IRI insert its typed row once.\n * @returns The typed-row insertion or reuse callback result.\n * @throws {ResourceKindConflictError} If the IRI is another kind of resource.\n * @throws {Error} If the IRI already is of the kind and `reuse` is not given.\n */\nexport async function promoteResource<T>(\n db: Database | Transaction,\n iri: string,\n kind: Exclude<Resource[\"kind\"], \"unknown\">,\n insert: (tx: Transaction, resource: Resource) => Promise<T>,\n id?: Uuid,\n reuse?: (tx: Transaction, resource: Resource) => Promise<T>,\n): Promise<T> {\n return await db.transaction(async (tx) => {\n const ensured = await ensureResource(tx, iri, id);\n // Re-read the kind after locking so a concurrent promotion cannot change\n // it between validation and update.\n const [resource] = await tx\n .select()\n .from(resources)\n .where(eq(resources.id, ensured.id))\n .for(PROMOTION_LOCK);\n if (resource == null) {\n throw new Error(\"Resource disappeared during promotion.\");\n }\n if (resource.kind === kind) {\n if (reuse == null) {\n throw new Error(`Resource ${iri} has already been promoted.`);\n }\n return await reuse(tx, resource);\n }\n if (resource.kind !== \"unknown\") {\n throw new ResourceKindConflictError(iri, resource.kind, kind);\n }\n await tx\n .update(resources)\n .set({ kind })\n .where(eq(resources.id, resource.id));\n return await insert(tx, { ...resource, kind });\n });\n}\n\nexport type AddressingInput = Readonly<\n Partial<Record<AddressingProperty, readonly string[]>>\n>;\n\n/** Stores every occurrence, including duplicates, in its original position. */\nexport async function storeAddressing(\n tx: Transaction,\n sourceId: Uuid,\n input: AddressingInput,\n): Promise<void> {\n // Acquire unique-index locks for new IRIs in a consistent order across\n // writers. This does not change occurrence order in the addressing rows.\n const targets = new Map<string, Resource>();\n const iris = [\n ...new Set(\n addressingPropertyEnum.enumValues.flatMap(\n (property) => input[property] ?? [],\n ),\n ),\n ].sort();\n for (const iri of iris) targets.set(iri, await ensureResource(tx, iri));\n for (const property of addressingPropertyEnum.enumValues) {\n for (const [position, iri] of (input[property] ?? []).entries()) {\n const target = targets.get(iri)!;\n await tx.insert(addressing).values({\n id: uuidV7(),\n sourceId,\n property,\n position,\n targetId: target.id,\n });\n }\n }\n}\n\n/**\n * One addressing occurrence at its source position. Positions need not be\n * contiguous: a value that names no IRI, such as an anonymous embedded object,\n * leaves its position unused instead of shifting the later ones.\n */\nexport interface AddressingOccurrence {\n readonly property: AddressingProperty;\n readonly position: number;\n readonly iri: string;\n}\n\n/**\n * Stores explicit occurrences, keeping each at its own position.\n * @throws {TypeError} If a property is unknown, a position is not a\n * non-negative safe integer, or two occurrences share a position.\n */\nexport async function storeAddressingOccurrences(\n tx: Transaction,\n sourceId: Uuid,\n occurrences: readonly AddressingOccurrence[],\n): Promise<void> {\n checkAddressingOccurrences(occurrences);\n const targets = new Map<string, Resource>();\n for (const iri of [\n ...new Set(occurrences.map((entry) => entry.iri)),\n ].sort()) {\n targets.set(iri, await ensureResource(tx, iri));\n }\n for (const { property, position, iri } of occurrences) {\n await tx.insert(addressing).values({\n id: uuidV7(),\n sourceId,\n property,\n position,\n targetId: targets.get(iri)!.id,\n });\n }\n}\n\n/**\n * Replaces the current addressing of a resource with explicit occurrences.\n * @throws {TypeError} As {@link storeAddressingOccurrences} does.\n */\nexport async function replaceAddressing(\n tx: Transaction,\n sourceId: Uuid,\n occurrences: readonly AddressingOccurrence[],\n): Promise<void> {\n checkAddressingOccurrences(occurrences);\n await tx.delete(addressing).where(eq(addressing.sourceId, sourceId));\n await storeAddressingOccurrences(tx, sourceId, occurrences);\n}\n\n/**\n * Checks occurrences before any write, so a malformed list writes nothing.\n * @throws {TypeError} If an occurrence is malformed or duplicated.\n */\nexport function checkAddressingOccurrences(\n occurrences: readonly AddressingOccurrence[],\n): void {\n if (!Array.isArray(occurrences)) {\n throw new TypeError(\"Addressing occurrences must be an array.\");\n }\n const seen = new Set<string>();\n for (const { property, position, iri } of occurrences) {\n if (\n !addressingPropertyEnum.enumValues.includes(property) ||\n !Number.isSafeInteger(position) ||\n position < 0 ||\n // Both addressing tables store positions as 32-bit integers.\n position > 2_147_483_647 ||\n typeof iri !== \"string\"\n ) {\n throw new TypeError(\"Invalid addressing occurrence.\");\n }\n const key = `${property}:${position}`;\n if (seen.has(key)) {\n throw new TypeError(\"Addressing occurrences must not share a position.\");\n }\n seen.add(key);\n }\n}\n\n/**\n * Locks an actor's declared collection until the transaction ends.\n * @returns The locked collection ID.\n */\nexport async function lockActorCollection(\n tx: Transaction,\n actorId: Uuid,\n role: CollectionRole,\n): Promise<Uuid> {\n const [reference] = await tx\n .select({ collectionId: collections.id })\n .from(collections)\n .innerJoin(\n actorCollectionReferences,\n eq(collections.id, actorCollectionReferences.collectionId),\n )\n .where(\n and(\n eq(actorCollectionReferences.actorId, actorId),\n eq(actorCollectionReferences.role, role),\n ),\n )\n .for(\"update\", { of: collections })\n .limit(1);\n if (reference == null) {\n throw new Error(`Actor ${actorId} declares no ${role} collection.`);\n }\n return reference.collectionId;\n}\n\n/**\n * Records a resource in an actor's declared collection, idempotently.\n * Position ASC is presentation order. Outboxes are reverse chronological,\n * so the newest item receives the smallest position.\n * @throws {Error} If the actor declares no collection for the role.\n */\nexport async function addActorCollectionItem(\n db: Database | Transaction,\n actorId: Uuid,\n role: CollectionRole,\n itemId: Uuid,\n): Promise<void> {\n await db.transaction(async (tx) => {\n const collectionId = await lockActorCollection(tx, actorId, role);\n const [row] = await tx\n .select({ position: min(collectionItems.position) })\n .from(collectionItems)\n .where(eq(collectionItems.collectionId, collectionId));\n await tx\n .insert(collectionItems)\n .values({ collectionId, itemId, position: (row?.position ?? 0) - 1 })\n .onConflictDoNothing();\n });\n}\n"],"mappings":";;;;AAmCA,MAAa,aAAa;AAC1B,MAAa,qBAA2B;;;;;AAMxC,eAAsB,eACpB,IACA,KACA,KAAK,OAAO,GACO;CACnB,MAAM,CAAC,YAAY,MAAM,GACtB,OAAO,CAAC,CACR,KAAK,SAAS,CAAC,CACf,MAAM,GAAG,UAAU,KAAK,GAAG,CAAC,CAAC,CAC7B,MAAM,CAAC;CACV,IAAI,YAAY,MAAM,OAAO;CAC7B,MAAM,CAAC,YAAY,MAAM,GACtB,OAAO,SAAS,CAAC,CACjB,OAAO;EAAE;EAAI;EAAK,MAAM;CAAU,CAAC,CAAC,CACpC,oBAAoB,EAAE,QAAQ,UAAU,IAAI,CAAC,CAAC,CAC9C,UAAU;CACb,IAAI,YAAY,MAAM,OAAO;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E,MAAM,CAAC,OAAO,MAAM,GACjB,OAAO,EAAE,UAAU,IAAI,gBAAgB,QAAQ,EAAE,CAAC,CAAC,CACnD,KAAK,eAAe,CAAC,CACrB,MAAM,GAAG,gBAAgB,cAAc,YAAY,CAAC;EACvD,MAAM,GACH,OAAO,eAAe,CAAC,CACvB,OAAO;GAAE;GAAc;GAAQ,WAAW,KAAK,YAAY,KAAK;EAAE,CAAC,CAAC,CACpE,oBAAoB;CACzB,CAAC;AACH"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@drfed/models",
|
|
3
|
-
"version": "0.2.0-dev.
|
|
3
|
+
"version": "0.2.0-dev.703",
|
|
4
4
|
"description": "Database models for DrFed.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ActivityPub",
|
|
@@ -191,13 +191,13 @@
|
|
|
191
191
|
},
|
|
192
192
|
"drfedBuild": {
|
|
193
193
|
"enabled": true,
|
|
194
|
-
"version": "0.2.0-dev.
|
|
195
|
-
"fullVersion": "0.2.0-dev.
|
|
194
|
+
"version": "0.2.0-dev.703",
|
|
195
|
+
"fullVersion": "0.2.0-dev.703+a34fc230",
|
|
196
196
|
"baseVersion": "0.2.0",
|
|
197
197
|
"channel": "dev",
|
|
198
|
-
"sha": "
|
|
199
|
-
"runNumber": "
|
|
200
|
-
"runId": "
|
|
198
|
+
"sha": "a34fc2304b78997824db72f9edee44be2adb2f65",
|
|
199
|
+
"runNumber": "703",
|
|
200
|
+
"runId": "41786716066",
|
|
201
201
|
"ref": "refs/heads/main",
|
|
202
202
|
"workflow": ".github/workflows/main.yaml"
|
|
203
203
|
},
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"resource-revision-BuG5kUlA.d.mts","names":[],"sources":["../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":";;;;;cAmBa,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;;;;;;;;;;;iBCUS,8BACpB,IAAI,aACJ,YAAY,OACX,QAAQ;;;;KCUC,wDAKC;YAEG,mBAAmB;;KAEvB;YAAyB,mBAAmB;;;UAGvC;WACN;WACA;WACA,gBAAgB;WAChB;;UAGD;WACC,YAAY;WACZ;;WAEA,oBAAoB;;KAEnB,8BAA8B;WAGzB;WACA,UAAU;WACV,SAAS;WACT,aAAa;WACb,qBAAqB;WACrB,aAAa;;WAGb;WACA,SAAS,SAAS;WAClB;;;UAKA,+BAA+B;WACrC,qBAAqB;WACrB,oBAAoB;;;;;;;;;iBA6ZT,uBACpB,IAAI,WAAW,aACf,OAAO,8BACN,QAAQ;;;;;iBASW,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"}
|