@drfed/models 0.2.0-dev.639 → 0.2.0-dev.682
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 +340 -188
- package/dist/activity-delivery.d.mts +1 -1
- package/dist/activity-delivery.d.mts.map +1 -1
- package/dist/activity-delivery.mjs +34 -9
- package/dist/activity-delivery.mjs.map +1 -1
- package/dist/{db-DtcLuISw.d.mts → db-BBw4F4HU.d.mts} +478 -6
- package/dist/{db-DtcLuISw.d.mts.map → db-BBw4F4HU.d.mts.map} +1 -1
- package/dist/db.d.mts +1 -1
- package/dist/document.d.mts +200 -0
- package/dist/document.d.mts.map +1 -0
- package/dist/document.mjs +1264 -0
- package/dist/document.mjs.map +1 -0
- package/dist/index.d.mts +3 -2
- package/dist/index.mjs +2 -1
- package/dist/instance.d.mts +1 -1
- package/dist/key.d.mts +1 -1
- package/dist/login.d.mts +1 -1
- package/dist/migrations-manifest.json +12 -0
- package/dist/relations.d.mts +1 -1
- package/dist/relations.mjs +65 -0
- package/dist/relations.mjs.map +1 -1
- package/dist/resource-revision-BuG5kUlA.d.mts +103 -0
- package/dist/resource-revision-BuG5kUlA.d.mts.map +1 -0
- package/dist/resource-revision-DWg6et77.mjs +313 -0
- package/dist/resource-revision-DWg6et77.mjs.map +1 -0
- package/dist/resource-revision.d.mts +2 -0
- package/dist/resource-revision.mjs +3 -0
- package/dist/resource.d.mts +1 -1
- package/dist/schema.d.mts +2 -2
- package/dist/schema.mjs +104 -5
- package/dist/schema.mjs.map +1 -1
- package/drizzle/20261026181201_resource_revision_storage/migration.sql +72 -0
- package/drizzle/20261026181201_resource_revision_storage/snapshot.json +4501 -0
- package/drizzle/20261026181206_guard_resource_revisions/migration.sql +175 -0
- package/drizzle/20261026181206_guard_resource_revisions/snapshot.json +4501 -0
- package/drizzle/20261026192411_capture_legacy_resource_revisions/migration.sql +249 -0
- package/drizzle/20261026192411_capture_legacy_resource_revisions/snapshot.json +4501 -0
- package/package.json +19 -7
|
@@ -0,0 +1 @@
|
|
|
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"}
|
|
@@ -0,0 +1,313 @@
|
|
|
1
|
+
import { activities, addressingPropertyEnum, objects, resourceHeads, resourceRevisionCaptureEnum, resourceRevisionProjectionEnum, resourceRevisions, resources, revisionAddressing, revisionRelations } from "./schema.mjs";
|
|
2
|
+
import { areUuidsEqual, uuidV7, validateUuid } from "./uuid.mjs";
|
|
3
|
+
import { ResourceKindConflictError } from "./resource.mjs";
|
|
4
|
+
import { storableText } from "./text.mjs";
|
|
5
|
+
import { and, desc, eq, inArray, lt, sql } from "drizzle-orm";
|
|
6
|
+
//#region src/legacy-resource-revision-error.ts
|
|
7
|
+
/** Legacy typed rows require the coordinated application adapter in #152. */
|
|
8
|
+
var LegacyResourceRevisionError = class extends Error {
|
|
9
|
+
resourceId;
|
|
10
|
+
constructor(resourceId) {
|
|
11
|
+
super("Legacy typed state requires coordinated capture and must agree with retained history.");
|
|
12
|
+
this.resourceId = resourceId;
|
|
13
|
+
this.name = "LegacyResourceRevisionError";
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
//#endregion
|
|
17
|
+
//#region src/resource-revision-state-error.ts
|
|
18
|
+
/** A requested state transition would change a saved activity or revive a deletion. */
|
|
19
|
+
var ResourceRevisionStateError = class extends Error {
|
|
20
|
+
code;
|
|
21
|
+
constructor(code) {
|
|
22
|
+
super(`Unsupported resource revision transition: ${code}.`);
|
|
23
|
+
this.code = code;
|
|
24
|
+
this.name = "ResourceRevisionStateError";
|
|
25
|
+
}
|
|
26
|
+
};
|
|
27
|
+
//#endregion
|
|
28
|
+
//#region src/revision-conflict-error.ts
|
|
29
|
+
/** The caller's expected current revision no longer matches the database. */
|
|
30
|
+
var RevisionConflictError = class extends Error {
|
|
31
|
+
resourceId;
|
|
32
|
+
expectedRevisionId;
|
|
33
|
+
actualRevisionId;
|
|
34
|
+
constructor(resourceId, expectedRevisionId, actualRevisionId) {
|
|
35
|
+
super("The resource's current revision has changed.");
|
|
36
|
+
this.resourceId = resourceId;
|
|
37
|
+
this.expectedRevisionId = expectedRevisionId;
|
|
38
|
+
this.actualRevisionId = actualRevisionId;
|
|
39
|
+
this.name = "RevisionConflictError";
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
//#endregion
|
|
43
|
+
//#region src/legacy-resource-revision.ts
|
|
44
|
+
/**
|
|
45
|
+
* Captures fully written legacy typed state within its creating transaction.
|
|
46
|
+
* This trusted compatibility operation performs no authorization or fetching.
|
|
47
|
+
* Repeated calls return the original revision only when the typed state agrees.
|
|
48
|
+
* @returns The first retained revision ID, including an unavailable snapshot.
|
|
49
|
+
* @throws {LegacyResourceRevisionError} When typed state cannot be captured.
|
|
50
|
+
*/
|
|
51
|
+
async function captureLegacyResourceRevision(tx, resourceId) {
|
|
52
|
+
try {
|
|
53
|
+
const [row] = await tx.select({ id: sql`drfed_capture_legacy_resource(${resourceId}::uuid, false)` }).from(sql`(VALUES (1)) AS capture_input(value)`);
|
|
54
|
+
if (row === void 0) throw new Error("Legacy capture returned no revision.");
|
|
55
|
+
return row.id;
|
|
56
|
+
} catch (error) {
|
|
57
|
+
let detail = error;
|
|
58
|
+
while (detail instanceof Error) {
|
|
59
|
+
if ("constraint" in detail && detail.constraint === "resource_revisions_legacy_guard" || "constraint_name" in detail && detail.constraint_name === "resource_revisions_legacy_guard") throw new LegacyResourceRevisionError(resourceId);
|
|
60
|
+
detail = detail.cause;
|
|
61
|
+
}
|
|
62
|
+
throw error;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
//#endregion
|
|
66
|
+
//#region src/resource-revision.ts
|
|
67
|
+
function text(value) {
|
|
68
|
+
if (typeof value !== "string" || !storableText(value)) throw new TypeError("A projection must contain losslessly storable text.");
|
|
69
|
+
}
|
|
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
|
+
function projectionRows(input = {}) {
|
|
102
|
+
const rows = [];
|
|
103
|
+
for (const property of Object.keys(input)) if (!addressingPropertyEnum.enumValues.includes(property)) throw new TypeError("Unknown addressing projection property.");
|
|
104
|
+
for (const property of addressingPropertyEnum.enumValues) {
|
|
105
|
+
const values = input[property];
|
|
106
|
+
if (values === void 0) continue;
|
|
107
|
+
if (!Array.isArray(values)) throw new TypeError("Addressing projections must be arrays.");
|
|
108
|
+
for (const [position, iri] of values.entries()) {
|
|
109
|
+
text(iri);
|
|
110
|
+
rows.push({
|
|
111
|
+
property,
|
|
112
|
+
position,
|
|
113
|
+
iri
|
|
114
|
+
});
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return rows;
|
|
118
|
+
}
|
|
119
|
+
function relationRows(input = []) {
|
|
120
|
+
if (!Array.isArray(input)) throw new TypeError("Relation projections must be arrays.");
|
|
121
|
+
return input.map((relation, occurrence) => {
|
|
122
|
+
text(relation.property);
|
|
123
|
+
const targetIri = relation.targetIri ?? null;
|
|
124
|
+
if (targetIri !== null) text(targetIri);
|
|
125
|
+
if (![
|
|
126
|
+
"reference",
|
|
127
|
+
"embedded",
|
|
128
|
+
"link"
|
|
129
|
+
].includes(relation.representation) || relation.representation === "reference" && targetIri === null) throw new TypeError("Invalid relation representation.");
|
|
130
|
+
const path = relation.path ?? null;
|
|
131
|
+
if (path !== null && (!Array.isArray(path) || Array.from(path).some((part) => typeof part !== "string" && !(Number.isSafeInteger(part) && part >= 0)))) throw new TypeError("A relation path must contain field names and nonnegative indexes.");
|
|
132
|
+
return {
|
|
133
|
+
occurrence,
|
|
134
|
+
property: relation.property,
|
|
135
|
+
representation: relation.representation,
|
|
136
|
+
targetIri,
|
|
137
|
+
path: path === null ? null : [...path]
|
|
138
|
+
};
|
|
139
|
+
});
|
|
140
|
+
}
|
|
141
|
+
async function current(db, resourceId) {
|
|
142
|
+
const [row] = await db.select({ revision: resourceRevisions }).from(resourceHeads).innerJoin(resourceRevisions, and(eq(resourceHeads.resourceId, resourceRevisions.resourceId), eq(resourceHeads.revisionId, resourceRevisions.id))).where(eq(resourceHeads.resourceId, resourceId)).limit(1);
|
|
143
|
+
return row?.revision ?? null;
|
|
144
|
+
}
|
|
145
|
+
async function hydrate(db, revision) {
|
|
146
|
+
const [addressing, relations] = await Promise.all([db.select().from(revisionAddressing).where(eq(revisionAddressing.revisionId, revision.id)).orderBy(revisionAddressing.property, revisionAddressing.position), db.select().from(revisionRelations).where(eq(revisionRelations.revisionId, revision.id)).orderBy(revisionRelations.occurrence)]);
|
|
147
|
+
return {
|
|
148
|
+
...revision,
|
|
149
|
+
addressing,
|
|
150
|
+
relations
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
function prepareSnapshot(input) {
|
|
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
|
+
const projection = input.projection ?? "partial";
|
|
156
|
+
if (!resourceRevisionCaptureEnum.enumValues.includes(input.capture) || !resourceRevisionProjectionEnum.enumValues.includes(projection)) throw new TypeError("Invalid capture or projection category.");
|
|
157
|
+
return {
|
|
158
|
+
kind: "snapshot",
|
|
159
|
+
serialized: json(input.document),
|
|
160
|
+
capture: input.capture,
|
|
161
|
+
projection,
|
|
162
|
+
addressing: projectionRows(input.addressing),
|
|
163
|
+
relations: relationRows(input.relations),
|
|
164
|
+
deleted: null,
|
|
165
|
+
formerTypes: null
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
function prepareWhiteout(input) {
|
|
169
|
+
if (!(input.deleted instanceof Temporal.Instant) || !Array.isArray(input.formerTypes)) throw new TypeError("Expected a deletion instant and former type array.");
|
|
170
|
+
const formerTypes = [...input.formerTypes];
|
|
171
|
+
for (const type of formerTypes) text(type);
|
|
172
|
+
return {
|
|
173
|
+
kind: "whiteout",
|
|
174
|
+
serialized: null,
|
|
175
|
+
capture: void 0,
|
|
176
|
+
projection: void 0,
|
|
177
|
+
addressing: [],
|
|
178
|
+
relations: [],
|
|
179
|
+
deleted: input.deleted,
|
|
180
|
+
formerTypes
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
function prepareRevision(input) {
|
|
184
|
+
const { resourceId, resourceKind, expectedRevisionId } = input;
|
|
185
|
+
if (!validateUuid(resourceId) || expectedRevisionId !== null && !validateUuid(expectedRevisionId)) throw new TypeError("Expected canonical resource and revision UUIDs.");
|
|
186
|
+
if (resourceKind !== "object" && resourceKind !== "activity") throw new TypeError("Unsupported resource kind.");
|
|
187
|
+
if (input.kind === "snapshot") return {
|
|
188
|
+
resourceId,
|
|
189
|
+
resourceKind,
|
|
190
|
+
expectedRevisionId,
|
|
191
|
+
...prepareSnapshot(input)
|
|
192
|
+
};
|
|
193
|
+
if (input.kind === "whiteout") return {
|
|
194
|
+
resourceId,
|
|
195
|
+
resourceKind,
|
|
196
|
+
expectedRevisionId,
|
|
197
|
+
...prepareWhiteout(input)
|
|
198
|
+
};
|
|
199
|
+
throw new TypeError("Unsupported revision kind.");
|
|
200
|
+
}
|
|
201
|
+
async function lockRevisionTarget(tx, input) {
|
|
202
|
+
const { resourceId, resourceKind, expectedRevisionId, kind } = input;
|
|
203
|
+
const [resource] = await tx.select().from(resources).where(eq(resources.id, resourceId)).for("no key update");
|
|
204
|
+
if (resource === void 0) throw new Error("The canonical resource is not registered.");
|
|
205
|
+
const previous = await current(tx, resourceId);
|
|
206
|
+
if (!(previous === null ? expectedRevisionId === null : expectedRevisionId !== null && areUuidsEqual(previous.id, expectedRevisionId))) throw new RevisionConflictError(resourceId, expectedRevisionId, previous?.id ?? null);
|
|
207
|
+
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);
|
|
209
|
+
if (resource.kind !== "unknown" && resource.kind !== resourceKind) throw new ResourceKindConflictError(resource.iri, resource.kind, resourceKind);
|
|
210
|
+
if (previous !== null && resourceKind === "activity") throw new ResourceRevisionStateError("activity-immutable");
|
|
211
|
+
if (previous?.kind === "whiteout") throw new ResourceRevisionStateError("deleted");
|
|
212
|
+
if (kind === "whiteout" && previous === null) throw new ResourceRevisionStateError("initial-whiteout");
|
|
213
|
+
if (resource.kind === "unknown") await tx.update(resources).set({ kind: resourceKind }).where(eq(resources.id, resourceId));
|
|
214
|
+
return previous;
|
|
215
|
+
}
|
|
216
|
+
async function appendPrepared(tx, input) {
|
|
217
|
+
const previous = await lockRevisionTarget(tx, input);
|
|
218
|
+
const { resourceId, kind, serialized, capture, projection, deleted, formerTypes, addressing, relations } = input;
|
|
219
|
+
const id = uuidV7();
|
|
220
|
+
const [revision] = await tx.insert(resourceRevisions).values({
|
|
221
|
+
id,
|
|
222
|
+
resourceId,
|
|
223
|
+
sequence: (previous?.sequence ?? 0) + 1,
|
|
224
|
+
kind,
|
|
225
|
+
capture: capture ?? previous.capture,
|
|
226
|
+
projection: projection ?? previous.projection,
|
|
227
|
+
document: serialized === null ? null : sql`${serialized}::json`,
|
|
228
|
+
deleted,
|
|
229
|
+
formerTypes
|
|
230
|
+
}).returning();
|
|
231
|
+
if (revision === void 0) throw new Error("Revision insertion returned no row.");
|
|
232
|
+
if (kind === "whiteout") {
|
|
233
|
+
const inherited = await hydrate(tx, previous);
|
|
234
|
+
addressing.push(...inherited.addressing.map(({ revisionId: _revisionId, ...row }) => row));
|
|
235
|
+
relations.push(...inherited.relations.map(({ revisionId: _revisionId, ...row }) => row));
|
|
236
|
+
}
|
|
237
|
+
if (addressing.length > 0) await tx.insert(revisionAddressing).values(addressing.map((row) => ({
|
|
238
|
+
...row,
|
|
239
|
+
revisionId: id
|
|
240
|
+
})));
|
|
241
|
+
if (relations.length > 0) await tx.insert(revisionRelations).values(relations.map((row) => ({
|
|
242
|
+
...row,
|
|
243
|
+
revisionId: id
|
|
244
|
+
})));
|
|
245
|
+
if (previous === null) await tx.insert(resourceHeads).values({
|
|
246
|
+
resourceId,
|
|
247
|
+
revisionId: id
|
|
248
|
+
});
|
|
249
|
+
else await tx.update(resourceHeads).set({ revisionId: id }).where(eq(resourceHeads.resourceId, resourceId));
|
|
250
|
+
return await hydrate(tx, revision);
|
|
251
|
+
}
|
|
252
|
+
/**
|
|
253
|
+
* Appends one current object version or saved activity, atomically with projections.
|
|
254
|
+
* The caller must validate the document and authorize the write. Lock multiple
|
|
255
|
+
* canonical IRIs in sorted order before composing several appends in one transaction.
|
|
256
|
+
* This does not publish, change collection membership, or reserve delivery.
|
|
257
|
+
* @returns The stored revision, including protected blind addressing.
|
|
258
|
+
*/
|
|
259
|
+
async function appendResourceRevision(db, input) {
|
|
260
|
+
const prepared = prepareRevision(input);
|
|
261
|
+
return await db.transaction((tx) => appendPrepared(tx, prepared));
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Loads protected local JSON without applying authorization or stripping bto/bcc.
|
|
265
|
+
* @returns The immutable revision and projections, or null if not found.
|
|
266
|
+
*/
|
|
267
|
+
async function loadResourceRevision(db, revisionId) {
|
|
268
|
+
const [revision] = await db.select().from(resourceRevisions).where(eq(resourceRevisions.id, revisionId)).limit(1);
|
|
269
|
+
return revision === void 0 ? null : await hydrate(db, revision);
|
|
270
|
+
}
|
|
271
|
+
/**
|
|
272
|
+
* Loads current protected local state without dereferencing any document target.
|
|
273
|
+
* @returns A snapshot, unavailable record or whiteout, or null when unversioned.
|
|
274
|
+
*/
|
|
275
|
+
async function loadCurrentResourceRevision(db, resourceId) {
|
|
276
|
+
const revision = await current(db, resourceId);
|
|
277
|
+
return revision === null ? null : await hydrate(db, revision);
|
|
278
|
+
}
|
|
279
|
+
const MAX_HISTORY_LIMIT = 100;
|
|
280
|
+
const DEFAULT_HISTORY_LIMIT = 20;
|
|
281
|
+
/**
|
|
282
|
+
* Lists protected history in descending sequence order; authorization belongs to callers.
|
|
283
|
+
* @returns Up to limit revisions strictly before beforeSequence, when supplied.
|
|
284
|
+
*/
|
|
285
|
+
async function listResourceRevisions(db, resourceId, options = {}) {
|
|
286
|
+
const { beforeSequence, limit = DEFAULT_HISTORY_LIMIT } = options;
|
|
287
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > MAX_HISTORY_LIMIT || beforeSequence !== void 0 && (!Number.isSafeInteger(beforeSequence) || beforeSequence < 1)) throw new RangeError("Invalid history bounds.");
|
|
288
|
+
const revisions = await db.select().from(resourceRevisions).where(and(eq(resourceRevisions.resourceId, resourceId), beforeSequence === void 0 ? void 0 : lt(resourceRevisions.sequence, beforeSequence))).orderBy(desc(resourceRevisions.sequence)).limit(limit);
|
|
289
|
+
if (revisions.length === 0) return [];
|
|
290
|
+
const revisionIds = revisions.map(({ id }) => id);
|
|
291
|
+
const [addressing, relations] = await Promise.all([db.select().from(revisionAddressing).where(inArray(revisionAddressing.revisionId, revisionIds)).orderBy(revisionAddressing.property, revisionAddressing.position), db.select().from(revisionRelations).where(inArray(revisionRelations.revisionId, revisionIds)).orderBy(revisionRelations.occurrence)]);
|
|
292
|
+
const addressingByRevision = /* @__PURE__ */ new Map();
|
|
293
|
+
for (const row of addressing) {
|
|
294
|
+
const rows = addressingByRevision.get(row.revisionId) ?? [];
|
|
295
|
+
rows.push(row);
|
|
296
|
+
addressingByRevision.set(row.revisionId, rows);
|
|
297
|
+
}
|
|
298
|
+
const relationsByRevision = /* @__PURE__ */ new Map();
|
|
299
|
+
for (const row of relations) {
|
|
300
|
+
const rows = relationsByRevision.get(row.revisionId) ?? [];
|
|
301
|
+
rows.push(row);
|
|
302
|
+
relationsByRevision.set(row.revisionId, rows);
|
|
303
|
+
}
|
|
304
|
+
return revisions.map((revision) => ({
|
|
305
|
+
...revision,
|
|
306
|
+
addressing: addressingByRevision.get(revision.id) ?? [],
|
|
307
|
+
relations: relationsByRevision.get(revision.id) ?? []
|
|
308
|
+
}));
|
|
309
|
+
}
|
|
310
|
+
//#endregion
|
|
311
|
+
export { captureLegacyResourceRevision as a, LegacyResourceRevisionError as c, loadResourceRevision as i, listResourceRevisions as n, RevisionConflictError as o, loadCurrentResourceRevision as r, ResourceRevisionStateError as s, appendResourceRevision as t };
|
|
312
|
+
|
|
313
|
+
//# sourceMappingURL=resource-revision-DWg6et77.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"resource-revision-DWg6et77.mjs","names":[],"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, 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 { type AddressingInput, ResourceKindConflictError } from \"./resource.ts\";\nimport { RevisionConflictError } from \"./revision-conflict-error.ts\";\nimport {\n type ResourceRevision,\n type RevisionAddressing,\n type RevisionRelation,\n activities,\n addressingPropertyEnum,\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 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 return {\n kind: \"snapshot\",\n serialized: json(input.document),\n capture: input.capture,\n projection,\n addressing: projectionRows(input.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): 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 if (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): Promise<StoredResourceRevision> {\n const previous = await lockRevisionTarget(tx, input);\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\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,GAAS,iCAAiC,WAAW,gBAC3D,CAAC,CAAC,CACD,KAAK,GAAG,sCAAsC;EACjD,IAAI,QAAQ,KAAA,GACV,MAAM,IAAI,MAAM,sCAAsC;EAExD,OAAO,IAAI;CACb,SAAS,OAAO;EACd,IAAI,SAAkB;EACtB,OAAO,kBAAkB,OAAO;GAC9B,IACG,gBAAgB,UACf,OAAO,eAAe,qCACvB,qBAAqB,UACpB,OAAO,oBAAoB,mCAE7B,MAAM,IAAI,4BAA4B,UAAU;GAElD,SAAS,OAAO;EAClB;EACA,MAAM;CACR;AACF;;;ACoCA,SAAS,KAAK,OAAyC;CACrD,IAAI,OAAO,UAAU,YAAY,CA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AC,CAAC,CAC1D,QAAQ,mBAAmB,UAAU,mBAAmB,QAAQ,GACnE,GACG,OAAO,CAAC,CACR,KAAK,iBAAiB,CAAC,CACvB,MAAM,QAAQ,kBAAkB,YAAY,WAAW,CAAC,CAAC,CACzD,QAAQ,kBAAkB,UAAU,CACzC,CAAC;CACD,MAAM,uCAAuB,IAAI,IAAgC;CACjE,KAAK,MAAM,OAAO,YAAY;EAC5B,MAAM,OAAO,qBAAqB,IAAI,IAAI,UAAU,KAAK,CAAC;EAC1D,KAAK,KAAK,GAAG;EACb,qBAAqB,IAAI,IAAI,YAAY,IAAI;CAC/C;CACA,MAAM,sCAAsB,IAAI,IAA8B;CAC9D,KAAK,MAAM,OAAO,WAAW;EAC3B,MAAM,OAAO,oBAAoB,IAAI,IAAI,UAAU,KAAK,CAAC;EACzD,KAAK,KAAK,GAAG;EACb,oBAAoB,IAAI,IAAI,YAAY,IAAI;CAC9C;CACA,OAAO,UAAU,KAAK,cAAc;EAClC,GAAG;EACH,YAAY,qBAAqB,IAAI,SAAS,EAAE,KAAK,CAAC;EACtD,WAAW,oBAAoB,IAAI,SAAS,EAAE,KAAK,CAAC;CACtD,EAAE;AACJ"}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import { a as StoredResourceRevision, c as loadCurrentResourceRevision, d as ResourceRevisionStateError, f as LegacyResourceRevisionError, i as RevisionRelationInput, l as loadResourceRevision, n as JsonObject, o as appendResourceRevision, p as RevisionConflictError, r as JsonValue, s as listResourceRevisions, t as AppendResourceRevisionInput, u as captureLegacyResourceRevision } from "./resource-revision-BuG5kUlA.mjs";
|
|
2
|
+
export { AppendResourceRevisionInput, JsonObject, JsonValue, LegacyResourceRevisionError, ResourceRevisionStateError, RevisionConflictError, RevisionRelationInput, StoredResourceRevision, appendResourceRevision, captureLegacyResourceRevision, listResourceRevisions, loadCurrentResourceRevision, loadResourceRevision };
|
|
@@ -0,0 +1,3 @@
|
|
|
1
|
+
import "./resource.mjs";
|
|
2
|
+
import "./text.mjs";
|
|
3
|
+
export { c as LegacyResourceRevisionError, s as ResourceRevisionStateError, o as RevisionConflictError, t as appendResourceRevision, a as captureLegacyResourceRevision, n as listResourceRevisions, r as loadCurrentResourceRevision, i as loadResourceRevision } from "./resource-revision-DWg6et77.mjs";
|
package/dist/resource.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { G as Resource, b as CollectionRole, r as Transaction, t as Database, v as AddressingProperty } from "./db-BBw4F4HU.mjs";
|
|
2
2
|
import { t as Uuid } from "./uuid-CKMzlIND.mjs";
|
|
3
3
|
//#region src/resource.d.ts
|
|
4
4
|
declare const PUBLIC_IRI = "https://www.w3.org/ns/activitystreams#Public";
|
package/dist/schema.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { $ as
|
|
2
|
-
export { Account, ActivityDelivery, ActivityDeliveryActor, ActivityDeliveryActorCollection, ActivityDeliveryAttempt, ActivityDeliveryDirection, ActivityDeliveryStatus, ActivityDeliveryVerificationMechanism, ActivityDeliveryVerificationResult, ActivityPubObject, Actor, ActorType, Addressing, AddressingProperty, Collection, CollectionRole, Instance, InstanceMember, Key, KeyVersion, LOGIN_CHALLENGE_CODE_LENGTH, LocalActor, LocalActorKey, LocalActorKeyType, LocalInstance, LoginChallenge, NewAccount, NewActivityDelivery, NewActivityDeliveryActor, NewActivityPubObject, NewActor, NewInstance, NewInstanceMember, NewLocalActor, NewLocalActorKey, NewLocalInstance, NewLoginChallenge, NewSession, ObjectType, Resource, Session, StoredActivity, accounts, activities, activityDeliveries, activityDeliveryActorCollections, activityDeliveryActors, activityDeliveryAttempts, activityDeliveryDirectionEnum, activityDeliveryStatusEnum, activityDeliveryVerificationMechanismEnum, activityDeliveryVerificationResultEnum, activityTypeEnum, actorCollectionReferences, actorTypeEnum, actors, addressing, addressingPropertyEnum, collectionItems, collectionRoleEnum, collectionTypeEnum, collections, instanceMembers, instances, keyVersions, keys, localActorKeyTypeEnum, localActorKeys, localActors, localInstances, loginChallenges, objectTypeEnum, objects, resourceKindEnum, resources, sessions };
|
|
1
|
+
import { $ as accounts, A as LoginChallenge, At as resourceHeads, B as NewLocalInstance, Bt as revisionRelationRepresentationEnum, C as Key, Ct as localActorKeyTypeEnum, D as LocalActorKey, Dt as loginChallenges, E as LocalActor, Et as localInstances, F as NewActor, Ft as resourceRevisions, G as Resource, H as NewResourceRevision, I as NewInstance, It as resources, J as RevisionAddressing, K as ResourceHead, L as NewInstanceMember, Lt as revisionAddressing, M as NewActivityDelivery, Mt as resourceRevisionCaptureEnum, N as NewActivityDeliveryActor, Nt as resourceRevisionKindEnum, O as LocalActorKeyType, Ot as objectTypeEnum, P as NewActivityPubObject, Pt as resourceRevisionProjectionEnum, Q as StoredActivity, R as NewLocalActor, Rt as revisionReceiptRoleEnum, S as InstanceMember, St as keys, T as LOGIN_CHALLENGE_CODE_LENGTH, Tt as localActors, U as NewSession, Ut as sessions, V as NewLoginChallenge, Vt as revisionRelations, W as ObjectType, X as RevisionRelation, Y as RevisionReceipt, Z as Session, _ as Addressing, _t as collectionTypeEnum, a as Account, at as activityDeliveryDirectionEnum, b as CollectionRole, bt as instances, c as ActivityDeliveryActorCollection, ct as activityDeliveryVerificationResultEnum, d as ActivityDeliveryStatus, dt as actorTypeEnum, et as activities, f as ActivityDeliveryVerificationMechanism, ft as actors, g as ActorType, gt as collectionRoleEnum, h as Actor, ht as collectionItems, it as activityDeliveryAttempts, j as NewAccount, jt as resourceKindEnum, k as LocalInstance, kt as objects, l as ActivityDeliveryAttempt, lt as activityTypeEnum, m as ActivityPubObject, mt as addressingPropertyEnum, nt as activityDeliveryActorCollections, o as ActivityDelivery, ot as activityDeliveryStatusEnum, p as ActivityDeliveryVerificationResult, pt as addressing, q as ResourceRevision, rt as activityDeliveryActors, s as ActivityDeliveryActor, st as activityDeliveryVerificationMechanismEnum, tt as activityDeliveries, u as ActivityDeliveryDirection, ut as actorCollectionReferences, v as AddressingProperty, vt as collections, w as KeyVersion, wt as localActorKeys, x as Instance, xt as keyVersions, y as Collection, yt as instanceMembers, z as NewLocalActorKey, zt as revisionReceipts } from "./db-BBw4F4HU.mjs";
|
|
2
|
+
export { Account, ActivityDelivery, ActivityDeliveryActor, ActivityDeliveryActorCollection, ActivityDeliveryAttempt, ActivityDeliveryDirection, ActivityDeliveryStatus, ActivityDeliveryVerificationMechanism, ActivityDeliveryVerificationResult, ActivityPubObject, Actor, ActorType, Addressing, AddressingProperty, Collection, CollectionRole, Instance, InstanceMember, Key, KeyVersion, LOGIN_CHALLENGE_CODE_LENGTH, LocalActor, LocalActorKey, LocalActorKeyType, LocalInstance, LoginChallenge, NewAccount, NewActivityDelivery, NewActivityDeliveryActor, NewActivityPubObject, NewActor, NewInstance, NewInstanceMember, NewLocalActor, NewLocalActorKey, NewLocalInstance, NewLoginChallenge, NewResourceRevision, NewSession, ObjectType, Resource, ResourceHead, ResourceRevision, RevisionAddressing, RevisionReceipt, RevisionRelation, Session, StoredActivity, accounts, activities, activityDeliveries, activityDeliveryActorCollections, activityDeliveryActors, activityDeliveryAttempts, activityDeliveryDirectionEnum, activityDeliveryStatusEnum, activityDeliveryVerificationMechanismEnum, activityDeliveryVerificationResultEnum, activityTypeEnum, actorCollectionReferences, actorTypeEnum, actors, addressing, addressingPropertyEnum, collectionItems, collectionRoleEnum, collectionTypeEnum, collections, instanceMembers, instances, keyVersions, keys, localActorKeyTypeEnum, localActorKeys, localActors, localInstances, loginChallenges, objectTypeEnum, objects, resourceHeads, resourceKindEnum, resourceRevisionCaptureEnum, resourceRevisionKindEnum, resourceRevisionProjectionEnum, resourceRevisions, resources, revisionAddressing, revisionReceiptRoleEnum, revisionReceipts, revisionRelationRepresentationEnum, revisionRelations, sessions };
|
package/dist/schema.mjs
CHANGED
|
@@ -35,8 +35,18 @@ var schema_exports = /* @__PURE__ */ __exportAll({
|
|
|
35
35
|
loginChallenges: () => loginChallenges,
|
|
36
36
|
objectTypeEnum: () => objectTypeEnum,
|
|
37
37
|
objects: () => objects,
|
|
38
|
+
resourceHeads: () => resourceHeads,
|
|
38
39
|
resourceKindEnum: () => resourceKindEnum,
|
|
40
|
+
resourceRevisionCaptureEnum: () => resourceRevisionCaptureEnum,
|
|
41
|
+
resourceRevisionKindEnum: () => resourceRevisionKindEnum,
|
|
42
|
+
resourceRevisionProjectionEnum: () => resourceRevisionProjectionEnum,
|
|
43
|
+
resourceRevisions: () => resourceRevisions,
|
|
39
44
|
resources: () => resources,
|
|
45
|
+
revisionAddressing: () => revisionAddressing,
|
|
46
|
+
revisionReceiptRoleEnum: () => revisionReceiptRoleEnum,
|
|
47
|
+
revisionReceipts: () => revisionReceipts,
|
|
48
|
+
revisionRelationRepresentationEnum: () => revisionRelationRepresentationEnum,
|
|
49
|
+
revisionRelations: () => revisionRelations,
|
|
40
50
|
sessions: () => sessions
|
|
41
51
|
});
|
|
42
52
|
/** A timestamptz column preserving PostgreSQL's microsecond precision. */
|
|
@@ -140,9 +150,9 @@ const resourceKindEnum = pgEnum("resource_kind", [
|
|
|
140
150
|
"unknown"
|
|
141
151
|
]);
|
|
142
152
|
/**
|
|
143
|
-
* Canonical IRI registry.
|
|
144
|
-
*
|
|
145
|
-
*
|
|
153
|
+
* Canonical IRI registry. Retained revisions keep their resource identity
|
|
154
|
+
* even after a current typed row is deleted. Other references may also
|
|
155
|
+
* intentionally restrict physical removal of the resource.
|
|
146
156
|
*/
|
|
147
157
|
const resources = pgTable("resources", {
|
|
148
158
|
id: uuid().$type().primaryKey(),
|
|
@@ -284,7 +294,7 @@ const activities = pgTable("activities", {
|
|
|
284
294
|
id: uuid().$type().primaryKey().references(() => resources.id, { onDelete: "cascade" }),
|
|
285
295
|
type: activityTypeEnum().notNull(),
|
|
286
296
|
actorId: uuid("actor_id").$type().notNull().references(() => actors.id, { onDelete: "cascade" }),
|
|
287
|
-
objectId: uuid("object_id").$type().references(() => resources.id, { onDelete: "
|
|
297
|
+
objectId: uuid("object_id").$type().references(() => resources.id, { onDelete: "set null" }),
|
|
288
298
|
published: instant().notNull(),
|
|
289
299
|
document: json(),
|
|
290
300
|
created: instant().notNull().default(currentTimestamp)
|
|
@@ -489,7 +499,96 @@ const activityDeliveryActorCollections = pgTable("activity_delivery_actor_collec
|
|
|
489
499
|
columns: [table.deliveryId, table.actorId],
|
|
490
500
|
foreignColumns: [activityDeliveryActors.deliveryId, activityDeliveryActors.actorId]
|
|
491
501
|
}).onDelete("cascade")]);
|
|
502
|
+
const resourceRevisionKindEnum = pgEnum("resource_revision_kind", [
|
|
503
|
+
"snapshot",
|
|
504
|
+
"unavailable",
|
|
505
|
+
"whiteout"
|
|
506
|
+
]);
|
|
507
|
+
const resourceRevisionCaptureEnum = pgEnum("resource_revision_capture", [
|
|
508
|
+
"local",
|
|
509
|
+
"received",
|
|
510
|
+
"embedded",
|
|
511
|
+
"fetched"
|
|
512
|
+
]);
|
|
513
|
+
const resourceRevisionProjectionEnum = pgEnum("resource_revision_projection", ["partial", "complete"]);
|
|
514
|
+
/** Immutable parsed documents, independently of current typed rows. */
|
|
515
|
+
const resourceRevisions = pgTable("resource_revisions", {
|
|
516
|
+
id: uuid().$type().primaryKey().defaultRandom(),
|
|
517
|
+
resourceId: uuid("resource_id").$type().notNull().references(() => resources.id, { onDelete: "restrict" }),
|
|
518
|
+
sequence: integer().notNull(),
|
|
519
|
+
kind: resourceRevisionKindEnum().notNull(),
|
|
520
|
+
capture: resourceRevisionCaptureEnum().notNull(),
|
|
521
|
+
backfilled: boolean().notNull().default(false),
|
|
522
|
+
document: json(),
|
|
523
|
+
formerTypes: text("former_types").array(),
|
|
524
|
+
deleted: instant(),
|
|
525
|
+
projection: resourceRevisionProjectionEnum().notNull().default("partial"),
|
|
526
|
+
created: instant().notNull().default(currentTimestamp)
|
|
527
|
+
}, (t) => [
|
|
528
|
+
unique("resource_revisions_resource_sequence_key").on(t.resourceId, t.sequence),
|
|
529
|
+
unique("resource_revisions_resource_id_key").on(t.resourceId, t.id),
|
|
530
|
+
check("resource_revisions_sequence_check", sql`${t.sequence} > 0`),
|
|
531
|
+
check("resource_revisions_document_check", sql`(${t.kind} = 'snapshot' AND ${t.document} IS NOT NULL)
|
|
532
|
+
OR (${t.kind} IN ('unavailable', 'whiteout') AND ${t.document} IS NULL)`),
|
|
533
|
+
check("resource_revisions_deletion_check", sql`(${t.kind} = 'whiteout' AND ${t.deleted} IS NOT NULL AND ${t.formerTypes} IS NOT NULL)
|
|
534
|
+
OR (${t.kind} <> 'whiteout' AND ${t.deleted} IS NULL AND ${t.formerTypes} IS NULL)`)
|
|
535
|
+
]);
|
|
536
|
+
/** The current revision of one canonical resource. */
|
|
537
|
+
const resourceHeads = pgTable("resource_heads", {
|
|
538
|
+
resourceId: uuid("resource_id").$type().primaryKey().references(() => resources.id, { onDelete: "restrict" }),
|
|
539
|
+
revisionId: uuid("revision_id").$type().notNull()
|
|
540
|
+
}, (t) => [foreignKey({
|
|
541
|
+
name: "resource_heads_resource_revision_fkey",
|
|
542
|
+
columns: [t.resourceId, t.revisionId],
|
|
543
|
+
foreignColumns: [resourceRevisions.resourceId, resourceRevisions.id]
|
|
544
|
+
}).onDelete("restrict")]);
|
|
545
|
+
/** Root addressing occurrences, including blind recipients and duplicates. */
|
|
546
|
+
const revisionAddressing = pgTable("revision_addressing", {
|
|
547
|
+
revisionId: uuid("revision_id").$type().notNull().references(() => resourceRevisions.id, { onDelete: "restrict" }),
|
|
548
|
+
property: addressingPropertyEnum().notNull(),
|
|
549
|
+
position: integer().notNull(),
|
|
550
|
+
iri: text().notNull()
|
|
551
|
+
}, (t) => [
|
|
552
|
+
primaryKey({ columns: [
|
|
553
|
+
t.revisionId,
|
|
554
|
+
t.property,
|
|
555
|
+
t.position
|
|
556
|
+
] }),
|
|
557
|
+
check("revision_addressing_position_check", sql`${t.position} >= 0`),
|
|
558
|
+
index("revision_addressing_iri_property_index").on(t.iri, t.property)
|
|
559
|
+
]);
|
|
560
|
+
const revisionRelationRepresentationEnum = pgEnum("revision_relation_representation", [
|
|
561
|
+
"reference",
|
|
562
|
+
"embedded",
|
|
563
|
+
"link"
|
|
564
|
+
]);
|
|
565
|
+
/** Caller-supplied relation occurrences; the saved JSON remains authoritative. */
|
|
566
|
+
const revisionRelations = pgTable("revision_relations", {
|
|
567
|
+
revisionId: uuid("revision_id").$type().notNull().references(() => resourceRevisions.id, { onDelete: "restrict" }),
|
|
568
|
+
occurrence: integer().notNull(),
|
|
569
|
+
property: text().notNull(),
|
|
570
|
+
path: json().$type(),
|
|
571
|
+
representation: revisionRelationRepresentationEnum().notNull(),
|
|
572
|
+
targetIri: text("target_iri")
|
|
573
|
+
}, (t) => [
|
|
574
|
+
primaryKey({ columns: [t.revisionId, t.occurrence] }),
|
|
575
|
+
check("revision_relations_occurrence_check", sql`${t.occurrence} >= 0`),
|
|
576
|
+
check("revision_relations_path_check", sql`${t.path} IS NULL OR json_typeof(${t.path}) = 'array'`),
|
|
577
|
+
check("revision_relations_reference_check", sql`${t.representation} <> 'reference' OR ${t.targetIri} IS NOT NULL`),
|
|
578
|
+
index("revision_relations_property_target_index").on(t.property, t.targetIri, t.revisionId)
|
|
579
|
+
]);
|
|
580
|
+
const revisionReceiptRoleEnum = pgEnum("revision_receipt_role", ["activity", "object"]);
|
|
581
|
+
/** Mutable index of delivery evidence, not part of immutable document history. */
|
|
582
|
+
const revisionReceipts = pgTable("revision_receipts", {
|
|
583
|
+
deliveryId: uuid("delivery_id").$type().notNull().references(() => activityDeliveries.id, { onDelete: "cascade" }),
|
|
584
|
+
revisionId: uuid("revision_id").$type().notNull().references(() => resourceRevisions.id, { onDelete: "restrict" }),
|
|
585
|
+
role: revisionReceiptRoleEnum().notNull()
|
|
586
|
+
}, (t) => [primaryKey({ columns: [
|
|
587
|
+
t.deliveryId,
|
|
588
|
+
t.revisionId,
|
|
589
|
+
t.role
|
|
590
|
+
] }), index("revision_receipts_revision_index").on(t.revisionId)]);
|
|
492
591
|
//#endregion
|
|
493
|
-
export { LOGIN_CHALLENGE_CODE_LENGTH, accounts, activities, activityDeliveries, activityDeliveryActorCollections, activityDeliveryActors, activityDeliveryAttempts, activityDeliveryDirectionEnum, activityDeliveryStatusEnum, activityDeliveryVerificationMechanismEnum, activityDeliveryVerificationResultEnum, activityTypeEnum, actorCollectionReferences, actorTypeEnum, actors, addressing, addressingPropertyEnum, collectionItems, collectionRoleEnum, collectionTypeEnum, collections, instanceMembers, instances, keyVersions, keys, localActorKeyTypeEnum, localActorKeys, localActors, localInstances, loginChallenges, objectTypeEnum, objects, resourceKindEnum, resources, sessions, schema_exports as t };
|
|
592
|
+
export { LOGIN_CHALLENGE_CODE_LENGTH, accounts, activities, activityDeliveries, activityDeliveryActorCollections, activityDeliveryActors, activityDeliveryAttempts, activityDeliveryDirectionEnum, activityDeliveryStatusEnum, activityDeliveryVerificationMechanismEnum, activityDeliveryVerificationResultEnum, activityTypeEnum, actorCollectionReferences, actorTypeEnum, actors, addressing, addressingPropertyEnum, collectionItems, collectionRoleEnum, collectionTypeEnum, collections, instanceMembers, instances, keyVersions, keys, localActorKeyTypeEnum, localActorKeys, localActors, localInstances, loginChallenges, objectTypeEnum, objects, resourceHeads, resourceKindEnum, resourceRevisionCaptureEnum, resourceRevisionKindEnum, resourceRevisionProjectionEnum, resourceRevisions, resources, revisionAddressing, revisionReceiptRoleEnum, revisionReceipts, revisionRelationRepresentationEnum, revisionRelations, sessions, schema_exports as t };
|
|
494
593
|
|
|
495
594
|
//# sourceMappingURL=schema.mjs.map
|