@drfed/models 0.2.0-dev.639 → 0.2.0-dev.651
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 +32 -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/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 +12 -7
|
@@ -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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MAAM,CAAC,YAAY,aAAa,MAAM,QAAQ,IAAI,CAChD,GACG,OAAO,CAAC,CACR,KAAK,kBAAkB,CAAC,CACxB,MAAM,QAAQ,mBAAmB,YAAY,WAAW,CAAC,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
|
package/dist/schema.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schema.mjs","names":[],"sources":["../src/schema.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 { webcrypto } from \"node:crypto\";\n\nimport { desc, sql } from \"drizzle-orm\";\nimport {\n type AnyPgColumn,\n boolean,\n bytea,\n char,\n check,\n customType,\n foreignKey,\n index,\n integer,\n json,\n jsonb,\n pgEnum,\n pgTable,\n primaryKey,\n text,\n unique,\n uniqueIndex,\n uuid,\n varchar,\n} from \"drizzle-orm/pg-core\";\n\nimport type { PublicJwk } from \"./key.ts\";\nimport type { Uuid } from \"./uuid.ts\";\n\n/** A timestamptz column preserving PostgreSQL's microsecond precision. */\nconst instant = customType<{ data: Temporal.Instant; driverData: string }>({\n dataType: () => \"timestamp with time zone\",\n fromDriver: (value) => Temporal.Instant.from(value),\n toDriver(value: Temporal.Instant | string) {\n // Pothos composite cursors decode timestamps as strings.\n if (typeof value === \"string\") return value;\n if (value instanceof Temporal.Instant) return value.toString();\n throw new TypeError(\n \"Expected a Temporal.Instant or a cursor timestamp string.\",\n );\n },\n});\n\nconst currentTimestamp = sql`CURRENT_TIMESTAMP`;\n\n/**\n * The database table to represent accounts.\n */\nexport const accounts = pgTable(\n \"accounts\",\n {\n id: uuid().$type<Uuid>().primaryKey(),\n email: varchar({ length: 255 }).notNull().unique(),\n name: varchar({ length: 100 }).notNull(),\n maxInstances: integer(\"max_instances\").notNull().default(10),\n admin: boolean().notNull().default(false),\n created: instant().notNull().default(currentTimestamp),\n },\n (table) => [\n check(\n \"accounts_email_check\",\n sql`${table.email} ~ '^[^@]+@[^@]+\\\\.[^@]+$'`,\n ),\n check(\"accounts_max_instances_check\", sql`${table.maxInstances} >= 0`),\n check(\"accounts_name_check\", sql`trim(both from ${table.name}) <> ''`),\n ],\n);\n\nexport type Account = typeof accounts.$inferSelect;\nexport type NewAccount = typeof accounts.$inferInsert;\n\n/**\n * The database table to represent instances.\n */\nexport const instances = pgTable(\"instances\", {\n id: uuid().$type<Uuid>().primaryKey(),\n localId: uuid(\"local_id\")\n .$type<Uuid>()\n .references(() => localInstances.id, {\n onDelete: \"cascade\",\n }),\n created: instant().notNull().default(currentTimestamp),\n // The authority an instance is federated under, which is what Fedify's\n // `Context.host` reports and therefore what dispatchers look instances up\n // by. That is a DNS name, at most 253 octets, plus a `:port` suffix of up\n // to 6 more characters when the deployment is not on the scheme's default\n // port. Both locally composed `<slug>.<root domain>` names and remote\n // hosts discovered from the fediverse live here.\n host: varchar({ length: 259 }).notNull().unique(),\n nodeInfoUrl: text(\"node_info_url\"),\n software: text(),\n softwareVersion: text(\"software_version\"),\n});\n\nexport type Instance = typeof instances.$inferSelect;\nexport type NewInstance = typeof instances.$inferInsert;\n\nexport const localInstances = pgTable(\n \"local_instances\",\n {\n id: uuid().$type<Uuid>().primaryKey(),\n slug: varchar({ length: 63 }).notNull().unique(),\n expires: instant().notNull(),\n maxActors: integer(\"max_actors\").notNull().default(10),\n },\n (table) => [\n // Keep this in agreement with `isValidSlug()` in ./slug.ts. A slug\n // becomes the leftmost label of the instance's host name, so it has to be\n // a valid DNS label: no leading or trailing hyphen, and none of RFC 5891's\n // reserved LDH labels except the `xn--` prefix of an A-label, which stays\n // allowed so that instances can carry internationalized domain names.\n check(\n \"local_instances_slug_check\",\n sql`${table.slug} ~ '^[a-z0-9][a-z0-9-]{2,61}[a-z0-9]$'\n AND (${table.slug} !~ '^..--' OR ${table.slug} ~ '^xn--')`,\n ),\n check(\"instances_max_actors_check\", sql`${table.maxActors} > 0`),\n ],\n);\n\nexport type LocalInstance = typeof localInstances.$inferSelect;\nexport type NewLocalInstance = typeof localInstances.$inferInsert;\n\n/**\n * The association table between instances and its member accounts.\n * Note that it also contains the just invited members, which are not yet\n * accepted. The `accepted` field is `NULL` for those members.\n */\nexport const instanceMembers = pgTable(\n \"instance_members\",\n {\n accountId: uuid(\"account_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => accounts.id),\n instanceId: uuid(\"instance_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => instances.id),\n admin: boolean().notNull().default(false),\n accepted: instant(),\n created: instant().notNull().default(currentTimestamp),\n },\n (table) => [\n primaryKey({ columns: [table.instanceId, table.accountId] }),\n index()\n .on(table.accountId)\n .where(sql`${table.accepted} IS NOT NULL`),\n index()\n .on(table.instanceId)\n .where(sql`${table.accepted} IS NOT NULL`),\n ],\n);\n\nexport type InstanceMember = typeof instanceMembers.$inferSelect;\nexport type NewInstanceMember = typeof instanceMembers.$inferInsert;\n\n/** The length of an email login verification code. */\nexport const LOGIN_CHALLENGE_CODE_LENGTH = 6;\n\n/**\n * Email login challenges identified by a public UUID and verified by a\n * plaintext code. Each challenge expires after 15 minutes and is single-use.\n */\nexport const loginChallenges = pgTable(\"login_challenges\", {\n id: uuid().$type<Uuid>().primaryKey(),\n accountId: uuid(\"account_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => accounts.id, { onDelete: \"cascade\" }),\n code: char({ length: LOGIN_CHALLENGE_CODE_LENGTH }).notNull(),\n created: instant().notNull().default(currentTimestamp),\n expires: instant()\n .notNull()\n .default(sql`CURRENT_TIMESTAMP + INTERVAL '15 minutes'`),\n consumed: instant(),\n});\n\nexport type LoginChallenge = typeof loginChallenges.$inferSelect;\nexport type NewLoginChallenge = typeof loginChallenges.$inferInsert;\n\n/**\n * Authenticated sessions. The `id` field is used to revoke a session, and\n * the `tokenHash` is the hash of the bearer access token.\n */\nexport const sessions = pgTable(\"sessions\", {\n id: uuid().$type<Uuid>().primaryKey(),\n accountId: uuid(\"account_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => accounts.id, { onDelete: \"cascade\" }),\n tokenHash: varchar(\"token_hash\", { length: 64 }).notNull().unique(),\n created: instant().notNull().default(currentTimestamp),\n expires: instant()\n .notNull()\n .default(sql`CURRENT_TIMESTAMP + INTERVAL '1 month'`),\n});\n\nexport type Session = typeof sessions.$inferSelect;\nexport type NewSession = typeof sessions.$inferInsert;\n\nexport const actorTypeEnum = pgEnum(\"actor_type\", [\n \"Application\",\n \"Group\",\n \"Organization\",\n \"Person\",\n \"Service\",\n]);\n\nexport type ActorType = (typeof actorTypeEnum.enumValues)[number];\n\nexport const resourceKindEnum = pgEnum(\"resource_kind\", [\n \"actor\",\n \"object\",\n \"activity\",\n \"collection\",\n \"unknown\",\n]);\n\n/**\n * Canonical IRI registry. Physical deletion of an actor, object, activity or\n * collection must also delete its source addressing and resource in the same\n * transaction. References from other resources intentionally restrict deletion.\n */\nexport const resources = pgTable(\"resources\", {\n id: uuid().$type<Uuid>().primaryKey(),\n iri: text().notNull().unique(),\n kind: resourceKindEnum().notNull(),\n created: instant().notNull().default(currentTimestamp),\n});\nexport type Resource = typeof resources.$inferSelect;\n\nexport const actors = pgTable(\n \"actors\",\n {\n id: uuid()\n .$type<Uuid>()\n .primaryKey()\n .references(() => resources.id, { onDelete: \"cascade\" }),\n localId: uuid(\"local_id\")\n .$type<Uuid>()\n .unique()\n .references(() => localActors.id, { onDelete: \"cascade\" }),\n type: actorTypeEnum().notNull(),\n /**\n * A local actor's handle username; a remote actor's `preferredUsername`\n * as received, which ActivityPub neither requires nor makes unique.\n */\n username: text(),\n instanceId: uuid(\"instance_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => instances.id, { onDelete: \"cascade\" }),\n document: json(),\n inboxUrl: text(\"inbox_url\").notNull(),\n /**\n * The IRI of the followers collection a remote actor declares, as\n * received. It is never fetched, so it is no `collections` row: what the\n * collection is and holds is unknown.\n */\n followersUrl: text(\"followers_url\"),\n profileUrl: text(\"profile_url\"),\n avatarUrl: text(\"avatar_url\"),\n headerUrl: text(\"header_url\"),\n name: text(),\n bioHtml: text(\"bio_html\"),\n automaticallyApprovesFollowers: boolean(\"automatically_approves_followers\")\n .notNull()\n .default(false),\n fieldHtmls: jsonb(\"field_htmls\")\n .$type<Record<string, string>>()\n .notNull()\n .default({}),\n emojis: jsonb().$type<Record<string, string>>().notNull().default({}),\n tags: jsonb().$type<Record<string, string>>().notNull().default({}),\n sensitive: boolean().notNull().default(false),\n // Moderation sanction state, denormalized from flag_action records\n // (which remain the audit source of truth):\n // - Not sanctioned: suspended IS NULL\n // - Temporary suspension: suspended = start, suspendedUntil = end\n // - Permanent suspension (ban) for local actors, or permanent federation\n // block for remote actors: suspended set, suspendedUntil IS NULL\n // Whether a sanction is *currently* active is always determined by\n // comparing against the current time (lazy expiry; no cron):\n // Temporal.Instant.compare(suspended, now) <= 0 AND (suspendedUntil IS NULL OR Temporal.Instant.compare(suspendedUntil, now) > 0).\n suspended: instant(),\n suspendedUntil: instant(\"suspended_until\"),\n successorId: uuid(\"successor_id\")\n .$type<Uuid>()\n .references((): AnyPgColumn => actors.id, {\n onDelete: \"set null\",\n }),\n aliases: text()\n .array()\n .notNull()\n .default(sql`(ARRAY[]::text[])`),\n followingCount: integer(\"following_count\").notNull().default(0),\n followersCount: integer(\"followers_count\").notNull().default(0),\n updated: instant()\n .notNull()\n .default(currentTimestamp)\n .$onUpdate(() => currentTimestamp),\n published: instant(),\n created: instant().notNull().default(currentTimestamp),\n // When implementing actor deletion, add activities.deleted and set it\n // together with objects.deleted in the same transaction.\n // FIXME: https://github.com/fedify-dev/drfed/issues/89\n deleted: instant(),\n },\n (t) => [\n uniqueIndex(\"username_key\")\n .on(t.username, t.instanceId)\n .where(sql`${t.localId} IS NOT NULL`),\n check(\n \"actors_username_check\",\n sql`${t.localId} IS NULL OR ${t.username} NOT LIKE '%@%'`,\n ),\n check(\n \"actors_local_username_check\",\n sql`${t.localId} IS NULL OR ${t.username} IS NOT NULL`,\n ),\n check(\n \"actors_suspended_check\",\n sql`\n ${t.suspendedUntil} IS NULL OR (\n ${t.suspended} IS NOT NULL AND\n ${t.suspendedUntil} > ${t.suspended}\n )\n `,\n ),\n index(\"actor_instance_index\").on(t.instanceId),\n ],\n);\n\nexport type Actor = typeof actors.$inferSelect;\nexport type NewActor = typeof actors.$inferInsert;\n\nexport const localActors = pgTable(\"local_actors\", {\n id: uuid().$type<Uuid>().primaryKey(),\n avatar: text(),\n header: text(),\n});\n\nexport type LocalActor = typeof localActors.$inferSelect;\nexport type NewLocalActor = typeof localActors.$inferInsert;\n\n/** Signing algorithms available to local actors. */\nexport const localActorKeyTypeEnum = pgEnum(\"local_actor_key_type\", [\n \"RSASSA-PKCS1-v1_5\",\n \"Ed25519\",\n]);\nexport type LocalActorKeyType =\n (typeof localActorKeyTypeEnum.enumValues)[number];\n/** Private signing material; never expose this table through GraphQL. */\nexport const localActorKeys = pgTable(\n \"local_actor_keys\",\n {\n localActorId: uuid(\"local_actor_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => localActors.id, { onDelete: \"cascade\" }),\n type: localActorKeyTypeEnum().notNull(),\n publicKey: jsonb(\"public_key\").$type<PublicJwk>().notNull(),\n privateKey: jsonb(\"private_key\").$type<webcrypto.JsonWebKey>().notNull(),\n },\n (table) => [\n primaryKey({ columns: [table.localActorId, table.type] }),\n check(\n \"local_actor_keys_public_key_check\",\n sql`jsonb_typeof(${table.publicKey}) = 'object' AND NOT (${table.publicKey} ?| array['d','p','q','dp','dq','qi','oth','k'])`,\n ),\n ],\n);\nexport type LocalActorKey = typeof localActorKeys.$inferSelect;\nexport type NewLocalActorKey = typeof localActorKeys.$inferInsert;\n\nexport const objectTypeEnum = pgEnum(\"object_type\", [\"Article\", \"Note\"]);\nexport type ObjectType = (typeof objectTypeEnum.enumValues)[number];\n/** ActivityPub objects authored by actors. */\nexport const objects = pgTable(\n \"objects\",\n {\n id: uuid()\n .$type<Uuid>()\n .primaryKey()\n .references(() => resources.id, { onDelete: \"cascade\" }),\n actorId: uuid(\"actor_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => actors.id, { onDelete: \"cascade\" }),\n /**\n * The activity that carried the stored snapshot. Who may read a remote\n * object follows it, not the activities that refer to the object later\n * with another version of it.\n */\n activityId: uuid(\"activity_id\")\n .$type<Uuid>()\n .references(() => resources.id, { onDelete: \"set null\" }),\n /**\n * Whether `document` was fetched from the object's IRI rather than taken\n * from the activity that carried it, which then proves nothing of it.\n */\n fetched: boolean().notNull().default(false),\n type: objectTypeEnum().notNull(),\n document: json(),\n url: text(),\n name: text(),\n summary: text(),\n contentHtml: text(\"content_html\").notNull(),\n language: varchar({ length: 35 }),\n sensitive: boolean().notNull().default(false),\n published: instant().notNull().default(currentTimestamp),\n updated: instant()\n .notNull()\n .default(currentTimestamp)\n .$onUpdate(() => currentTimestamp),\n created: instant().notNull().default(currentTimestamp),\n deleted: instant(),\n },\n (t) => [\n check(\n \"objects_content_html_check\",\n sql`trim(both from ${t.contentHtml}) <> ''`,\n ),\n unique(\"objects_activity_id_key\").on(t.activityId),\n index(\"object_actor_published_index\").on(\n t.actorId,\n desc(t.published),\n desc(t.id),\n ),\n ],\n);\nexport type ActivityPubObject = typeof objects.$inferSelect;\nexport type NewActivityPubObject = typeof objects.$inferInsert;\n\nexport const collectionTypeEnum = pgEnum(\"collection_type\", [\n \"Collection\",\n \"OrderedCollection\",\n]);\nexport const collectionRoleEnum = pgEnum(\"collection_role\", [\n \"followers\",\n \"following\",\n \"featured\",\n \"outbox\",\n]);\nexport type CollectionRole = (typeof collectionRoleEnum.enumValues)[number];\nexport const collections = pgTable(\"collections\", {\n id: uuid()\n .$type<Uuid>()\n .primaryKey()\n .references(() => resources.id, { onDelete: \"cascade\" }),\n type: collectionTypeEnum().notNull(),\n /**\n * Lifecycle owner of a locally managed collection. Physical deletion of\n * the owner cascades to the collection and all references. Soft deletion\n * hides the collection and every actor's reference to it from GraphQL.\n */\n ownerActorId: uuid(\"owner_actor_id\")\n .$type<Uuid>()\n .references(() => actors.id, { onDelete: \"cascade\" }),\n totalItems: integer(\"total_items\"),\n document: json(),\n updated: instant()\n .notNull()\n .default(currentTimestamp)\n .$onUpdate(() => currentTimestamp),\n});\nexport type Collection = typeof collections.$inferSelect;\n\n/** Actor-declared collection roles; a collection may be shared across roles or actors. */\nexport const actorCollectionReferences = pgTable(\n \"actor_collection_references\",\n {\n actorId: uuid(\"actor_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => actors.id, { onDelete: \"cascade\" }),\n role: collectionRoleEnum().notNull(),\n collectionId: uuid(\"collection_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => collections.id, { onDelete: \"cascade\" }),\n },\n (t) => [\n primaryKey({ columns: [t.actorId, t.role] }),\n index(\"actor_collection_reference_collection_index\").on(t.collectionId),\n ],\n);\n\nexport const collectionItems = pgTable(\n \"collection_items\",\n {\n collectionId: uuid(\"collection_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => collections.id, { onDelete: \"cascade\" }),\n itemId: uuid(\"item_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => resources.id, { onDelete: \"cascade\" }),\n position: integer(),\n observed: instant().notNull().default(currentTimestamp),\n },\n (t) => [\n primaryKey({ columns: [t.collectionId, t.itemId] }),\n index(\"collection_item_position_index\").on(t.collectionId, t.position),\n ],\n);\n\nexport const activityTypeEnum = pgEnum(\"activity_type\", [\"Create\"]);\nexport const activities = pgTable(\n \"activities\",\n {\n id: uuid()\n .$type<Uuid>()\n .primaryKey()\n .references(() => resources.id, { onDelete: \"cascade\" }),\n type: activityTypeEnum().notNull(),\n actorId: uuid(\"actor_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => actors.id, { onDelete: \"cascade\" }),\n objectId: uuid(\"object_id\")\n .$type<Uuid>()\n .references(() => resources.id, { onDelete: \"cascade\" }),\n published: instant().notNull(),\n document: json(),\n created: instant().notNull().default(currentTimestamp),\n },\n (t) => [\n index(\"activity_actor_published_index\").on(\n t.actorId,\n desc(t.published),\n desc(t.id),\n ),\n index(\"activity_object_published_index\").on(t.objectId, t.published, t.id),\n ],\n);\nexport type StoredActivity = typeof activities.$inferSelect;\n\nexport const addressingPropertyEnum = pgEnum(\"addressing_property\", [\n \"to\",\n \"cc\",\n \"bto\",\n \"bcc\",\n \"audience\",\n]);\nexport type AddressingProperty =\n (typeof addressingPropertyEnum.enumValues)[number];\nexport const addressing = pgTable(\n \"addressing\",\n {\n id: uuid().$type<Uuid>().primaryKey(),\n sourceId: uuid(\"source_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => resources.id, { onDelete: \"cascade\" }),\n property: addressingPropertyEnum().notNull(),\n position: integer().notNull(),\n targetId: uuid(\"target_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => resources.id, { onDelete: \"restrict\" }),\n },\n (t) => [\n unique(\"addressing_source_property_position_key\").on(\n t.sourceId,\n t.property,\n t.position,\n ),\n index(\"addressing_target_property_index\").on(t.targetId, t.property),\n ],\n);\nexport type Addressing = typeof addressing.$inferSelect;\n\n/** Direction of an observed delivery. */\nexport const activityDeliveryDirectionEnum = pgEnum(\n \"activity_delivery_direction\",\n [\"inbound\", \"outbound\"],\n);\n\n/**\n * Inbound: `received` (2xx, listener ran), `acknowledged` (2xx, listener did\n * not run), `unverified`, `rejected` (refused although verified); a request\n * whose handling threw is one of the last two, without a status code. Outbound:\n * `queued` (no attempt ended yet), `sent`, `failed` (the latest attempt\n * failed; a queued delivery may be retried), `permanently_failed`,\n * `abandoned` (the retry policy ran out).\n */\nexport const activityDeliveryStatusEnum = pgEnum(\"activity_delivery_status\", [\n \"received\",\n \"acknowledged\",\n \"unverified\",\n \"rejected\",\n \"queued\",\n \"sent\",\n \"failed\",\n \"permanently_failed\",\n \"abandoned\",\n]);\n\n/** The mechanism that authenticated an inbound activity. */\nexport const activityDeliveryVerificationMechanismEnum = pgEnum(\n \"activity_delivery_verification_mechanism\",\n [\"http_signature\", \"ld_signature\", \"object_integrity_proof\"],\n);\n\n/**\n * What Fedify reported of an inbound verification; `unattempted` when it\n * answered before verifying, and `unobserved` when recording failed.\n */\nexport const activityDeliveryVerificationResultEnum = pgEnum(\n \"activity_delivery_verification_result\",\n [\n \"verified\",\n \"invalid_signature\",\n \"key_fetch_error\",\n \"no_signature\",\n \"unattempted\",\n \"unobserved\",\n ],\n);\n\n/** Logical public keys, identified by their exact IRI. */\nexport const keys = pgTable(\"keys\", {\n id: uuid().$type<Uuid>().primaryKey(),\n iri: text().notNull().unique(),\n created: instant().notNull().default(currentTimestamp),\n});\n\n/** Immutable key material, independently retained from Fedify's KV cache. */\nexport const keyVersions = pgTable(\n \"key_versions\",\n {\n id: uuid().$type<Uuid>().primaryKey(),\n keyId: uuid(\"key_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => keys.id, { onDelete: \"restrict\" }),\n publicKey: jsonb(\"public_key\").$type<PublicJwk>().notNull(),\n fingerprint: text().notNull(),\n /** DrFed observation time, not remote rotation time or evidence of continuous use. */\n firstSeen: instant(\"first_seen\").notNull(),\n /** DrFed observation time, not remote rotation time or evidence of continuous use. */\n lastSeen: instant(\"last_seen\").notNull(),\n },\n (table) => [\n unique(\"key_versions_key_id_fingerprint_unique\").on(\n table.keyId,\n table.fingerprint,\n ),\n check(\n \"key_versions_seen_check\",\n sql`${table.lastSeen} >= ${table.firstSeen}`,\n ),\n check(\n \"key_versions_public_key_check\",\n sql`NOT (${table.publicKey} ?| array['d','p','q','dp','dq','qi','oth','k'])`,\n ),\n index(\"key_version_key_first_seen_index\").on(\n table.keyId,\n table.firstSeen,\n table.id,\n ),\n ],\n);\n\n/** Delivery observations; payloads may contain unverified, private remote input. */\nexport const activityDeliveries = pgTable(\n \"activity_deliveries\",\n {\n id: uuid().$type<Uuid>().primaryKey(),\n instanceId: uuid(\"instance_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => instances.id, { onDelete: \"cascade\" }),\n /** The owner of the inbox the request arrived at, or the sending actor. */\n actorId: uuid(\"actor_id\")\n .$type<Uuid>()\n .references(() => actors.id, { onDelete: \"set null\" }),\n direction: activityDeliveryDirectionEnum().notNull(),\n status: activityDeliveryStatusEnum().notNull(),\n verificationMechanism: activityDeliveryVerificationMechanismEnum(\n \"verification_mechanism\",\n ),\n verificationResult: activityDeliveryVerificationResultEnum(\n \"verification_result\",\n ),\n type: text(),\n types: text()\n .array()\n .notNull()\n .default(sql`'{}'`),\n activityIri: text(\"activity_iri\"),\n /**\n * The stored activity `activityIri` names: for an inbound delivery, only\n * one Fedify verified and accepted. The database enforces the latter;\n * `linkInboundActivity()` matches the IRI.\n */\n activityId: uuid(\"activity_id\")\n .$type<Uuid>()\n .references(() => activities.id, { onDelete: \"set null\" }),\n /**\n * Whether an inbound delivery carried the stored activity as it is, not\n * only its IRI. `linkInboundActivity()` decides it, and only such a\n * delivery opens the activity to its instance.\n */\n carriedSnapshot: boolean(\"carried_snapshot\").notNull().default(false),\n /**\n * The object an inbound delivery's inbox listener fetched from its IRI,\n * when it had to.\n */\n fetchedObject: jsonb(\"fetched_object\").$type<unknown>(),\n /**\n * Whether an inbound delivery carried the object stored with its activity\n * as it is: the activity carried it, or the delivery fetched it as stored.\n * `linkInboundActivity()` decides it, and only such a delivery opens the\n * object to its instance.\n */\n carriedObjectSnapshot: boolean(\"carried_object_snapshot\")\n .notNull()\n .default(false),\n objectType: text(\"object_type\"),\n objectIri: text(\"object_iri\"),\n signedKeyIri: text(\"signed_key_iri\"),\n /** A referenced version does not imply successful verification. */\n verificationKeyId: uuid(\"verification_key_id\")\n .$type<Uuid>()\n .references(() => keyVersions.id, { onDelete: \"restrict\" }),\n /** Inbound, only the first `actor`; the rest are in `payload`. */\n remoteActorIri: text(\"remote_actor_iri\"),\n remoteHost: text(\"remote_host\"),\n inboxUrl: text(\"inbox_url\").notNull(),\n requestUrl: text(\"request_url\"),\n /** Names are lowercase; original order and case are not kept. */\n headers: jsonb().$type<readonly (readonly [string, string])[]>(),\n body: bytea(),\n statusCode: integer(\"status_code\"),\n responseBody: text(\"response_body\"),\n error: text(),\n payload: jsonb().$type<unknown>(),\n recipientIris: text(\"recipient_iris\")\n .array()\n .notNull()\n .default(sql`'{}'`),\n /** Inbound, when the request arrived; outbound, when delivery started. */\n created: instant().notNull().default(currentTimestamp),\n /** Inbound, when DrFed answered; outbound, the latest status change. */\n completed: instant(),\n },\n (table) => [\n check(\n \"activity_deliveries_direction_status_check\",\n sql`(${table.direction} = 'inbound' AND ${table.status} IN ('received', 'acknowledged', 'unverified', 'rejected')) OR (${table.direction} = 'outbound' AND ${table.status} IN ('queued', 'sent', 'failed', 'permanently_failed', 'abandoned'))`,\n ),\n check(\n \"activity_deliveries_completed_check\",\n sql`(${table.completed} IS NULL) = (${table.status} = 'queued')`,\n ),\n check(\n \"activity_deliveries_status_code_check\",\n sql`${table.statusCode} IS NULL OR ${table.statusCode} BETWEEN 100 AND 599`,\n ),\n check(\n \"activity_deliveries_outbound_key_check\",\n sql`${table.direction} <> 'outbound' OR ${table.verificationKeyId} IS NULL`,\n ),\n check(\n \"activity_deliveries_verification_result_check\",\n sql`(${table.direction} = 'inbound') = (${table.verificationResult} IS NOT NULL)`,\n ),\n check(\n \"activity_deliveries_verification_mechanism_check\",\n sql`${table.verificationMechanism} IS NULL OR (${table.direction} = 'inbound' AND ${table.verificationResult} NOT IN ('unattempted', 'unobserved'))`,\n ),\n check(\n \"activity_deliveries_body_check\",\n sql`(${table.direction} = 'inbound') = (${table.body} IS NOT NULL)`,\n ),\n check(\n \"activity_deliveries_activity_check\",\n sql`${table.activityId} IS NULL OR ${table.direction} = 'outbound' OR (${table.verificationResult} = 'verified' AND ${table.status} IN ('received', 'acknowledged'))`,\n ),\n index(\"activity_delivery_instance_created_index\").on(\n table.instanceId,\n desc(table.created),\n desc(table.id),\n ),\n index(\"activity_delivery_actor_index\").on(table.actorId),\n index(\"activity_delivery_activity_created_index\").on(\n table.activityId,\n desc(table.created),\n desc(table.id),\n ),\n index(\"activity_delivery_verification_key_index\").on(\n table.verificationKeyId,\n ),\n index(\"activity_delivery_outbound_index\")\n .on(table.activityIri, table.inboxUrl)\n .where(sql`${table.direction} = 'outbound'`),\n ],\n);\n\n/** Each ended attempt of an outbound delivery. */\nexport const activityDeliveryAttempts = pgTable(\n \"activity_delivery_attempts\",\n {\n id: uuid().$type<Uuid>().primaryKey(),\n deliveryId: uuid(\"delivery_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => activityDeliveries.id, { onDelete: \"cascade\" }),\n succeeded: boolean().notNull(),\n statusCode: integer(\"status_code\"),\n responseBody: text(\"response_body\"),\n error: text(),\n /** When the attempt ended. */\n created: instant().notNull().default(currentTimestamp),\n },\n (table) => [\n check(\n \"activity_delivery_attempts_status_code_check\",\n sql`${table.statusCode} IS NULL OR ${table.statusCode} BETWEEN 100 AND 599`,\n ),\n check(\n \"activity_delivery_attempts_error_check\",\n sql`${table.succeeded} = (${table.error} IS NULL)`,\n ),\n index(\"activity_delivery_attempt_delivery_index\").on(\n table.deliveryId,\n table.created,\n table.id,\n ),\n ],\n);\n\n/**\n * The local actors a delivery concerns, one row per delivery and actor; each\n * must be a local actor of the delivery's instance, which the record functions\n * check.\n */\nexport const activityDeliveryActors = pgTable(\n \"activity_delivery_actors\",\n {\n deliveryId: uuid(\"delivery_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => activityDeliveries.id, { onDelete: \"cascade\" }),\n actorId: uuid(\"actor_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => actors.id, { onDelete: \"cascade\" }),\n inboxOwner: boolean(\"inbox_owner\").notNull().default(false),\n /** Addressed directly or through a collection. */\n addressed: boolean().notNull().default(false),\n /** Addressed by its own IRI; collections are in a row each. */\n addressedDirectly: boolean(\"addressed_directly\").notNull().default(false),\n sender: boolean().notNull().default(false),\n /** The delivery's `created`, which an actor's deliveries are ordered by. */\n created: instant().notNull(),\n },\n (table) => [\n primaryKey({ columns: [table.deliveryId, table.actorId] }),\n check(\n \"activity_delivery_actors_role_check\",\n sql`${table.inboxOwner} OR ${table.addressed} OR ${table.sender}`,\n ),\n check(\n \"activity_delivery_actors_addressed_directly_check\",\n sql`NOT ${table.addressedDirectly} OR ${table.addressed}`,\n ),\n index(\"activity_delivery_actor_created_index\").on(\n table.actorId,\n desc(table.created),\n desc(table.deliveryId),\n ),\n ],\n);\n\n/** Each addressed collection a delivery reached a local actor through. */\nexport const activityDeliveryActorCollections = pgTable(\n \"activity_delivery_actor_collections\",\n {\n deliveryId: uuid(\"delivery_id\").$type<Uuid>().notNull(),\n actorId: uuid(\"actor_id\").$type<Uuid>().notNull(),\n collectionIri: text(\"collection_iri\").notNull(),\n },\n (table) => [\n primaryKey({\n columns: [table.deliveryId, table.actorId, table.collectionIri],\n }),\n foreignKey({\n name: \"activity_delivery_actor_collections_link_fkey\",\n columns: [table.deliveryId, table.actorId],\n foreignColumns: [\n activityDeliveryActors.deliveryId,\n activityDeliveryActors.actorId,\n ],\n }).onDelete(\"cascade\"),\n ],\n);\nexport type Key = typeof keys.$inferSelect;\nexport type KeyVersion = typeof keyVersions.$inferSelect;\nexport type ActivityDelivery = typeof activityDeliveries.$inferSelect;\nexport type NewActivityDelivery = typeof activityDeliveries.$inferInsert;\nexport type ActivityDeliveryAttempt =\n typeof activityDeliveryAttempts.$inferSelect;\nexport type ActivityDeliveryActor = typeof activityDeliveryActors.$inferSelect;\nexport type NewActivityDeliveryActor =\n typeof activityDeliveryActors.$inferInsert;\nexport type ActivityDeliveryActorCollection =\n typeof activityDeliveryActorCollections.$inferSelect;\nexport type ActivityDeliveryDirection =\n (typeof activityDeliveryDirectionEnum.enumValues)[number];\nexport type ActivityDeliveryStatus =\n (typeof activityDeliveryStatusEnum.enumValues)[number];\nexport type ActivityDeliveryVerificationMechanism =\n (typeof activityDeliveryVerificationMechanismEnum.enumValues)[number];\nexport type ActivityDeliveryVerificationResult =\n (typeof activityDeliveryVerificationResultEnum.enumValues)[number];\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,MAAM,UAAU,WAA2D;CACzE,gBAAgB;CAChB,aAAa,UAAU,SAAS,QAAQ,KAAK,KAAK;CAClD,SAAS,OAAkC;EAEzC,IAAI,OAAO,UAAU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CAAC,GACD,WAAW;CACT,MAAM;CACN,SAAS,CAAC,MAAM,YAAY,MAAM,OAAO;CACzC,gBAAgB,CACd,uBAAuB,YACvB,uBAAuB,OACzB;AACF,CAAC,CAAC,CAAC,SAAS,SAAS,CACvB,CACF"}
|
|
1
|
+
{"version":3,"file":"schema.mjs","names":[],"sources":["../src/schema.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 { webcrypto } from \"node:crypto\";\n\nimport { desc, sql } from \"drizzle-orm\";\nimport {\n type AnyPgColumn,\n boolean,\n bytea,\n char,\n check,\n customType,\n foreignKey,\n index,\n integer,\n json,\n jsonb,\n pgEnum,\n pgTable,\n primaryKey,\n text,\n unique,\n uniqueIndex,\n uuid,\n varchar,\n} from \"drizzle-orm/pg-core\";\n\nimport type { PublicJwk } from \"./key.ts\";\nimport type { Uuid } from \"./uuid.ts\";\n\n/** A timestamptz column preserving PostgreSQL's microsecond precision. */\nconst instant = customType<{ data: Temporal.Instant; driverData: string }>({\n dataType: () => \"timestamp with time zone\",\n fromDriver: (value) => Temporal.Instant.from(value),\n toDriver(value: Temporal.Instant | string) {\n // Pothos composite cursors decode timestamps as strings.\n if (typeof value === \"string\") return value;\n if (value instanceof Temporal.Instant) return value.toString();\n throw new TypeError(\n \"Expected a Temporal.Instant or a cursor timestamp string.\",\n );\n },\n});\n\nconst currentTimestamp = sql`CURRENT_TIMESTAMP`;\n\n/**\n * The database table to represent accounts.\n */\nexport const accounts = pgTable(\n \"accounts\",\n {\n id: uuid().$type<Uuid>().primaryKey(),\n email: varchar({ length: 255 }).notNull().unique(),\n name: varchar({ length: 100 }).notNull(),\n maxInstances: integer(\"max_instances\").notNull().default(10),\n admin: boolean().notNull().default(false),\n created: instant().notNull().default(currentTimestamp),\n },\n (table) => [\n check(\n \"accounts_email_check\",\n sql`${table.email} ~ '^[^@]+@[^@]+\\\\.[^@]+$'`,\n ),\n check(\"accounts_max_instances_check\", sql`${table.maxInstances} >= 0`),\n check(\"accounts_name_check\", sql`trim(both from ${table.name}) <> ''`),\n ],\n);\n\nexport type Account = typeof accounts.$inferSelect;\nexport type NewAccount = typeof accounts.$inferInsert;\n\n/**\n * The database table to represent instances.\n */\nexport const instances = pgTable(\"instances\", {\n id: uuid().$type<Uuid>().primaryKey(),\n localId: uuid(\"local_id\")\n .$type<Uuid>()\n .references(() => localInstances.id, {\n onDelete: \"cascade\",\n }),\n created: instant().notNull().default(currentTimestamp),\n // The authority an instance is federated under, which is what Fedify's\n // `Context.host` reports and therefore what dispatchers look instances up\n // by. That is a DNS name, at most 253 octets, plus a `:port` suffix of up\n // to 6 more characters when the deployment is not on the scheme's default\n // port. Both locally composed `<slug>.<root domain>` names and remote\n // hosts discovered from the fediverse live here.\n host: varchar({ length: 259 }).notNull().unique(),\n nodeInfoUrl: text(\"node_info_url\"),\n software: text(),\n softwareVersion: text(\"software_version\"),\n});\n\nexport type Instance = typeof instances.$inferSelect;\nexport type NewInstance = typeof instances.$inferInsert;\n\nexport const localInstances = pgTable(\n \"local_instances\",\n {\n id: uuid().$type<Uuid>().primaryKey(),\n slug: varchar({ length: 63 }).notNull().unique(),\n expires: instant().notNull(),\n maxActors: integer(\"max_actors\").notNull().default(10),\n },\n (table) => [\n // Keep this in agreement with `isValidSlug()` in ./slug.ts. A slug\n // becomes the leftmost label of the instance's host name, so it has to be\n // a valid DNS label: no leading or trailing hyphen, and none of RFC 5891's\n // reserved LDH labels except the `xn--` prefix of an A-label, which stays\n // allowed so that instances can carry internationalized domain names.\n check(\n \"local_instances_slug_check\",\n sql`${table.slug} ~ '^[a-z0-9][a-z0-9-]{2,61}[a-z0-9]$'\n AND (${table.slug} !~ '^..--' OR ${table.slug} ~ '^xn--')`,\n ),\n check(\"instances_max_actors_check\", sql`${table.maxActors} > 0`),\n ],\n);\n\nexport type LocalInstance = typeof localInstances.$inferSelect;\nexport type NewLocalInstance = typeof localInstances.$inferInsert;\n\n/**\n * The association table between instances and its member accounts.\n * Note that it also contains the just invited members, which are not yet\n * accepted. The `accepted` field is `NULL` for those members.\n */\nexport const instanceMembers = pgTable(\n \"instance_members\",\n {\n accountId: uuid(\"account_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => accounts.id),\n instanceId: uuid(\"instance_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => instances.id),\n admin: boolean().notNull().default(false),\n accepted: instant(),\n created: instant().notNull().default(currentTimestamp),\n },\n (table) => [\n primaryKey({ columns: [table.instanceId, table.accountId] }),\n index()\n .on(table.accountId)\n .where(sql`${table.accepted} IS NOT NULL`),\n index()\n .on(table.instanceId)\n .where(sql`${table.accepted} IS NOT NULL`),\n ],\n);\n\nexport type InstanceMember = typeof instanceMembers.$inferSelect;\nexport type NewInstanceMember = typeof instanceMembers.$inferInsert;\n\n/** The length of an email login verification code. */\nexport const LOGIN_CHALLENGE_CODE_LENGTH = 6;\n\n/**\n * Email login challenges identified by a public UUID and verified by a\n * plaintext code. Each challenge expires after 15 minutes and is single-use.\n */\nexport const loginChallenges = pgTable(\"login_challenges\", {\n id: uuid().$type<Uuid>().primaryKey(),\n accountId: uuid(\"account_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => accounts.id, { onDelete: \"cascade\" }),\n code: char({ length: LOGIN_CHALLENGE_CODE_LENGTH }).notNull(),\n created: instant().notNull().default(currentTimestamp),\n expires: instant()\n .notNull()\n .default(sql`CURRENT_TIMESTAMP + INTERVAL '15 minutes'`),\n consumed: instant(),\n});\n\nexport type LoginChallenge = typeof loginChallenges.$inferSelect;\nexport type NewLoginChallenge = typeof loginChallenges.$inferInsert;\n\n/**\n * Authenticated sessions. The `id` field is used to revoke a session, and\n * the `tokenHash` is the hash of the bearer access token.\n */\nexport const sessions = pgTable(\"sessions\", {\n id: uuid().$type<Uuid>().primaryKey(),\n accountId: uuid(\"account_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => accounts.id, { onDelete: \"cascade\" }),\n tokenHash: varchar(\"token_hash\", { length: 64 }).notNull().unique(),\n created: instant().notNull().default(currentTimestamp),\n expires: instant()\n .notNull()\n .default(sql`CURRENT_TIMESTAMP + INTERVAL '1 month'`),\n});\n\nexport type Session = typeof sessions.$inferSelect;\nexport type NewSession = typeof sessions.$inferInsert;\n\nexport const actorTypeEnum = pgEnum(\"actor_type\", [\n \"Application\",\n \"Group\",\n \"Organization\",\n \"Person\",\n \"Service\",\n]);\n\nexport type ActorType = (typeof actorTypeEnum.enumValues)[number];\n\nexport const resourceKindEnum = pgEnum(\"resource_kind\", [\n \"actor\",\n \"object\",\n \"activity\",\n \"collection\",\n \"unknown\",\n]);\n\n/**\n * Canonical IRI registry. Retained revisions keep their resource identity\n * even after a current typed row is deleted. Other references may also\n * intentionally restrict physical removal of the resource.\n */\nexport const resources = pgTable(\"resources\", {\n id: uuid().$type<Uuid>().primaryKey(),\n iri: text().notNull().unique(),\n kind: resourceKindEnum().notNull(),\n created: instant().notNull().default(currentTimestamp),\n});\nexport type Resource = typeof resources.$inferSelect;\n\nexport const actors = pgTable(\n \"actors\",\n {\n id: uuid()\n .$type<Uuid>()\n .primaryKey()\n .references(() => resources.id, { onDelete: \"cascade\" }),\n localId: uuid(\"local_id\")\n .$type<Uuid>()\n .unique()\n .references(() => localActors.id, { onDelete: \"cascade\" }),\n type: actorTypeEnum().notNull(),\n /**\n * A local actor's handle username; a remote actor's `preferredUsername`\n * as received, which ActivityPub neither requires nor makes unique.\n */\n username: text(),\n instanceId: uuid(\"instance_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => instances.id, { onDelete: \"cascade\" }),\n document: json(),\n inboxUrl: text(\"inbox_url\").notNull(),\n /**\n * The IRI of the followers collection a remote actor declares, as\n * received. It is never fetched, so it is no `collections` row: what the\n * collection is and holds is unknown.\n */\n followersUrl: text(\"followers_url\"),\n profileUrl: text(\"profile_url\"),\n avatarUrl: text(\"avatar_url\"),\n headerUrl: text(\"header_url\"),\n name: text(),\n bioHtml: text(\"bio_html\"),\n automaticallyApprovesFollowers: boolean(\"automatically_approves_followers\")\n .notNull()\n .default(false),\n fieldHtmls: jsonb(\"field_htmls\")\n .$type<Record<string, string>>()\n .notNull()\n .default({}),\n emojis: jsonb().$type<Record<string, string>>().notNull().default({}),\n tags: jsonb().$type<Record<string, string>>().notNull().default({}),\n sensitive: boolean().notNull().default(false),\n // Moderation sanction state, denormalized from flag_action records\n // (which remain the audit source of truth):\n // - Not sanctioned: suspended IS NULL\n // - Temporary suspension: suspended = start, suspendedUntil = end\n // - Permanent suspension (ban) for local actors, or permanent federation\n // block for remote actors: suspended set, suspendedUntil IS NULL\n // Whether a sanction is *currently* active is always determined by\n // comparing against the current time (lazy expiry; no cron):\n // Temporal.Instant.compare(suspended, now) <= 0 AND (suspendedUntil IS NULL OR Temporal.Instant.compare(suspendedUntil, now) > 0).\n suspended: instant(),\n suspendedUntil: instant(\"suspended_until\"),\n successorId: uuid(\"successor_id\")\n .$type<Uuid>()\n .references((): AnyPgColumn => actors.id, {\n onDelete: \"set null\",\n }),\n aliases: text()\n .array()\n .notNull()\n .default(sql`(ARRAY[]::text[])`),\n followingCount: integer(\"following_count\").notNull().default(0),\n followersCount: integer(\"followers_count\").notNull().default(0),\n updated: instant()\n .notNull()\n .default(currentTimestamp)\n .$onUpdate(() => currentTimestamp),\n published: instant(),\n created: instant().notNull().default(currentTimestamp),\n // When implementing actor deletion, add activities.deleted and set it\n // together with objects.deleted in the same transaction.\n // FIXME: https://github.com/fedify-dev/drfed/issues/89\n deleted: instant(),\n },\n (t) => [\n uniqueIndex(\"username_key\")\n .on(t.username, t.instanceId)\n .where(sql`${t.localId} IS NOT NULL`),\n check(\n \"actors_username_check\",\n sql`${t.localId} IS NULL OR ${t.username} NOT LIKE '%@%'`,\n ),\n check(\n \"actors_local_username_check\",\n sql`${t.localId} IS NULL OR ${t.username} IS NOT NULL`,\n ),\n check(\n \"actors_suspended_check\",\n sql`\n ${t.suspendedUntil} IS NULL OR (\n ${t.suspended} IS NOT NULL AND\n ${t.suspendedUntil} > ${t.suspended}\n )\n `,\n ),\n index(\"actor_instance_index\").on(t.instanceId),\n ],\n);\n\nexport type Actor = typeof actors.$inferSelect;\nexport type NewActor = typeof actors.$inferInsert;\n\nexport const localActors = pgTable(\"local_actors\", {\n id: uuid().$type<Uuid>().primaryKey(),\n avatar: text(),\n header: text(),\n});\n\nexport type LocalActor = typeof localActors.$inferSelect;\nexport type NewLocalActor = typeof localActors.$inferInsert;\n\n/** Signing algorithms available to local actors. */\nexport const localActorKeyTypeEnum = pgEnum(\"local_actor_key_type\", [\n \"RSASSA-PKCS1-v1_5\",\n \"Ed25519\",\n]);\nexport type LocalActorKeyType =\n (typeof localActorKeyTypeEnum.enumValues)[number];\n/** Private signing material; never expose this table through GraphQL. */\nexport const localActorKeys = pgTable(\n \"local_actor_keys\",\n {\n localActorId: uuid(\"local_actor_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => localActors.id, { onDelete: \"cascade\" }),\n type: localActorKeyTypeEnum().notNull(),\n publicKey: jsonb(\"public_key\").$type<PublicJwk>().notNull(),\n privateKey: jsonb(\"private_key\").$type<webcrypto.JsonWebKey>().notNull(),\n },\n (table) => [\n primaryKey({ columns: [table.localActorId, table.type] }),\n check(\n \"local_actor_keys_public_key_check\",\n sql`jsonb_typeof(${table.publicKey}) = 'object' AND NOT (${table.publicKey} ?| array['d','p','q','dp','dq','qi','oth','k'])`,\n ),\n ],\n);\nexport type LocalActorKey = typeof localActorKeys.$inferSelect;\nexport type NewLocalActorKey = typeof localActorKeys.$inferInsert;\n\nexport const objectTypeEnum = pgEnum(\"object_type\", [\"Article\", \"Note\"]);\nexport type ObjectType = (typeof objectTypeEnum.enumValues)[number];\n/** ActivityPub objects authored by actors. */\nexport const objects = pgTable(\n \"objects\",\n {\n id: uuid()\n .$type<Uuid>()\n .primaryKey()\n .references(() => resources.id, { onDelete: \"cascade\" }),\n actorId: uuid(\"actor_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => actors.id, { onDelete: \"cascade\" }),\n /**\n * The activity that carried the stored snapshot. Who may read a remote\n * object follows it, not the activities that refer to the object later\n * with another version of it.\n */\n activityId: uuid(\"activity_id\")\n .$type<Uuid>()\n .references(() => resources.id, { onDelete: \"set null\" }),\n /**\n * Whether `document` was fetched from the object's IRI rather than taken\n * from the activity that carried it, which then proves nothing of it.\n */\n fetched: boolean().notNull().default(false),\n type: objectTypeEnum().notNull(),\n document: json(),\n url: text(),\n name: text(),\n summary: text(),\n contentHtml: text(\"content_html\").notNull(),\n language: varchar({ length: 35 }),\n sensitive: boolean().notNull().default(false),\n published: instant().notNull().default(currentTimestamp),\n updated: instant()\n .notNull()\n .default(currentTimestamp)\n .$onUpdate(() => currentTimestamp),\n created: instant().notNull().default(currentTimestamp),\n deleted: instant(),\n },\n (t) => [\n check(\n \"objects_content_html_check\",\n sql`trim(both from ${t.contentHtml}) <> ''`,\n ),\n unique(\"objects_activity_id_key\").on(t.activityId),\n index(\"object_actor_published_index\").on(\n t.actorId,\n desc(t.published),\n desc(t.id),\n ),\n ],\n);\nexport type ActivityPubObject = typeof objects.$inferSelect;\nexport type NewActivityPubObject = typeof objects.$inferInsert;\n\nexport const collectionTypeEnum = pgEnum(\"collection_type\", [\n \"Collection\",\n \"OrderedCollection\",\n]);\nexport const collectionRoleEnum = pgEnum(\"collection_role\", [\n \"followers\",\n \"following\",\n \"featured\",\n \"outbox\",\n]);\nexport type CollectionRole = (typeof collectionRoleEnum.enumValues)[number];\nexport const collections = pgTable(\"collections\", {\n id: uuid()\n .$type<Uuid>()\n .primaryKey()\n .references(() => resources.id, { onDelete: \"cascade\" }),\n type: collectionTypeEnum().notNull(),\n /**\n * Lifecycle owner of a locally managed collection. Physical deletion of\n * the owner cascades to the collection and all references. Soft deletion\n * hides the collection and every actor's reference to it from GraphQL.\n */\n ownerActorId: uuid(\"owner_actor_id\")\n .$type<Uuid>()\n .references(() => actors.id, { onDelete: \"cascade\" }),\n totalItems: integer(\"total_items\"),\n document: json(),\n updated: instant()\n .notNull()\n .default(currentTimestamp)\n .$onUpdate(() => currentTimestamp),\n});\nexport type Collection = typeof collections.$inferSelect;\n\n/** Actor-declared collection roles; a collection may be shared across roles or actors. */\nexport const actorCollectionReferences = pgTable(\n \"actor_collection_references\",\n {\n actorId: uuid(\"actor_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => actors.id, { onDelete: \"cascade\" }),\n role: collectionRoleEnum().notNull(),\n collectionId: uuid(\"collection_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => collections.id, { onDelete: \"cascade\" }),\n },\n (t) => [\n primaryKey({ columns: [t.actorId, t.role] }),\n index(\"actor_collection_reference_collection_index\").on(t.collectionId),\n ],\n);\n\nexport const collectionItems = pgTable(\n \"collection_items\",\n {\n collectionId: uuid(\"collection_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => collections.id, { onDelete: \"cascade\" }),\n itemId: uuid(\"item_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => resources.id, { onDelete: \"cascade\" }),\n position: integer(),\n observed: instant().notNull().default(currentTimestamp),\n },\n (t) => [\n primaryKey({ columns: [t.collectionId, t.itemId] }),\n index(\"collection_item_position_index\").on(t.collectionId, t.position),\n ],\n);\n\nexport const activityTypeEnum = pgEnum(\"activity_type\", [\"Create\"]);\nexport const activities = pgTable(\n \"activities\",\n {\n id: uuid()\n .$type<Uuid>()\n .primaryKey()\n .references(() => resources.id, { onDelete: \"cascade\" }),\n type: activityTypeEnum().notNull(),\n actorId: uuid(\"actor_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => actors.id, { onDelete: \"cascade\" }),\n objectId: uuid(\"object_id\")\n .$type<Uuid>()\n .references(() => resources.id, { onDelete: \"set null\" }),\n published: instant().notNull(),\n document: json(),\n created: instant().notNull().default(currentTimestamp),\n },\n (t) => [\n index(\"activity_actor_published_index\").on(\n t.actorId,\n desc(t.published),\n desc(t.id),\n ),\n index(\"activity_object_published_index\").on(t.objectId, t.published, t.id),\n ],\n);\nexport type StoredActivity = typeof activities.$inferSelect;\n\nexport const addressingPropertyEnum = pgEnum(\"addressing_property\", [\n \"to\",\n \"cc\",\n \"bto\",\n \"bcc\",\n \"audience\",\n]);\nexport type AddressingProperty =\n (typeof addressingPropertyEnum.enumValues)[number];\nexport const addressing = pgTable(\n \"addressing\",\n {\n id: uuid().$type<Uuid>().primaryKey(),\n sourceId: uuid(\"source_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => resources.id, { onDelete: \"cascade\" }),\n property: addressingPropertyEnum().notNull(),\n position: integer().notNull(),\n targetId: uuid(\"target_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => resources.id, { onDelete: \"restrict\" }),\n },\n (t) => [\n unique(\"addressing_source_property_position_key\").on(\n t.sourceId,\n t.property,\n t.position,\n ),\n index(\"addressing_target_property_index\").on(t.targetId, t.property),\n ],\n);\nexport type Addressing = typeof addressing.$inferSelect;\n\n/** Direction of an observed delivery. */\nexport const activityDeliveryDirectionEnum = pgEnum(\n \"activity_delivery_direction\",\n [\"inbound\", \"outbound\"],\n);\n\n/**\n * Inbound: `received` (2xx, listener ran), `acknowledged` (2xx, listener did\n * not run), `unverified`, `rejected` (refused although verified); a request\n * whose handling threw is one of the last two, without a status code. Outbound:\n * `queued` (no attempt ended yet), `sent`, `failed` (the latest attempt\n * failed; a queued delivery may be retried), `permanently_failed`,\n * `abandoned` (the retry policy ran out).\n */\nexport const activityDeliveryStatusEnum = pgEnum(\"activity_delivery_status\", [\n \"received\",\n \"acknowledged\",\n \"unverified\",\n \"rejected\",\n \"queued\",\n \"sent\",\n \"failed\",\n \"permanently_failed\",\n \"abandoned\",\n]);\n\n/** The mechanism that authenticated an inbound activity. */\nexport const activityDeliveryVerificationMechanismEnum = pgEnum(\n \"activity_delivery_verification_mechanism\",\n [\"http_signature\", \"ld_signature\", \"object_integrity_proof\"],\n);\n\n/**\n * What Fedify reported of an inbound verification; `unattempted` when it\n * answered before verifying, and `unobserved` when recording failed.\n */\nexport const activityDeliveryVerificationResultEnum = pgEnum(\n \"activity_delivery_verification_result\",\n [\n \"verified\",\n \"invalid_signature\",\n \"key_fetch_error\",\n \"no_signature\",\n \"unattempted\",\n \"unobserved\",\n ],\n);\n\n/** Logical public keys, identified by their exact IRI. */\nexport const keys = pgTable(\"keys\", {\n id: uuid().$type<Uuid>().primaryKey(),\n iri: text().notNull().unique(),\n created: instant().notNull().default(currentTimestamp),\n});\n\n/** Immutable key material, independently retained from Fedify's KV cache. */\nexport const keyVersions = pgTable(\n \"key_versions\",\n {\n id: uuid().$type<Uuid>().primaryKey(),\n keyId: uuid(\"key_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => keys.id, { onDelete: \"restrict\" }),\n publicKey: jsonb(\"public_key\").$type<PublicJwk>().notNull(),\n fingerprint: text().notNull(),\n /** DrFed observation time, not remote rotation time or evidence of continuous use. */\n firstSeen: instant(\"first_seen\").notNull(),\n /** DrFed observation time, not remote rotation time or evidence of continuous use. */\n lastSeen: instant(\"last_seen\").notNull(),\n },\n (table) => [\n unique(\"key_versions_key_id_fingerprint_unique\").on(\n table.keyId,\n table.fingerprint,\n ),\n check(\n \"key_versions_seen_check\",\n sql`${table.lastSeen} >= ${table.firstSeen}`,\n ),\n check(\n \"key_versions_public_key_check\",\n sql`NOT (${table.publicKey} ?| array['d','p','q','dp','dq','qi','oth','k'])`,\n ),\n index(\"key_version_key_first_seen_index\").on(\n table.keyId,\n table.firstSeen,\n table.id,\n ),\n ],\n);\n\n/** Delivery observations; payloads may contain unverified, private remote input. */\nexport const activityDeliveries = pgTable(\n \"activity_deliveries\",\n {\n id: uuid().$type<Uuid>().primaryKey(),\n instanceId: uuid(\"instance_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => instances.id, { onDelete: \"cascade\" }),\n /** The owner of the inbox the request arrived at, or the sending actor. */\n actorId: uuid(\"actor_id\")\n .$type<Uuid>()\n .references(() => actors.id, { onDelete: \"set null\" }),\n direction: activityDeliveryDirectionEnum().notNull(),\n status: activityDeliveryStatusEnum().notNull(),\n verificationMechanism: activityDeliveryVerificationMechanismEnum(\n \"verification_mechanism\",\n ),\n verificationResult: activityDeliveryVerificationResultEnum(\n \"verification_result\",\n ),\n type: text(),\n types: text()\n .array()\n .notNull()\n .default(sql`'{}'`),\n activityIri: text(\"activity_iri\"),\n /**\n * The stored activity `activityIri` names: for an inbound delivery, only\n * one Fedify verified and accepted. The database enforces the latter;\n * `linkInboundActivity()` matches the IRI.\n */\n activityId: uuid(\"activity_id\")\n .$type<Uuid>()\n .references(() => activities.id, { onDelete: \"set null\" }),\n /**\n * Whether an inbound delivery carried the stored activity as it is, not\n * only its IRI. `linkInboundActivity()` decides it, and only such a\n * delivery opens the activity to its instance.\n */\n carriedSnapshot: boolean(\"carried_snapshot\").notNull().default(false),\n /**\n * The object an inbound delivery's inbox listener fetched from its IRI,\n * when it had to.\n */\n fetchedObject: jsonb(\"fetched_object\").$type<unknown>(),\n /**\n * Whether an inbound delivery carried the object stored with its activity\n * as it is: the activity carried it, or the delivery fetched it as stored.\n * `linkInboundActivity()` decides it, and only such a delivery opens the\n * object to its instance.\n */\n carriedObjectSnapshot: boolean(\"carried_object_snapshot\")\n .notNull()\n .default(false),\n objectType: text(\"object_type\"),\n objectIri: text(\"object_iri\"),\n signedKeyIri: text(\"signed_key_iri\"),\n /** A referenced version does not imply successful verification. */\n verificationKeyId: uuid(\"verification_key_id\")\n .$type<Uuid>()\n .references(() => keyVersions.id, { onDelete: \"restrict\" }),\n /** Inbound, only the first `actor`; the rest are in `payload`. */\n remoteActorIri: text(\"remote_actor_iri\"),\n remoteHost: text(\"remote_host\"),\n inboxUrl: text(\"inbox_url\").notNull(),\n requestUrl: text(\"request_url\"),\n /** Names are lowercase; original order and case are not kept. */\n headers: jsonb().$type<readonly (readonly [string, string])[]>(),\n body: bytea(),\n statusCode: integer(\"status_code\"),\n responseBody: text(\"response_body\"),\n error: text(),\n payload: jsonb().$type<unknown>(),\n recipientIris: text(\"recipient_iris\")\n .array()\n .notNull()\n .default(sql`'{}'`),\n /** Inbound, when the request arrived; outbound, when delivery started. */\n created: instant().notNull().default(currentTimestamp),\n /** Inbound, when DrFed answered; outbound, the latest status change. */\n completed: instant(),\n },\n (table) => [\n check(\n \"activity_deliveries_direction_status_check\",\n sql`(${table.direction} = 'inbound' AND ${table.status} IN ('received', 'acknowledged', 'unverified', 'rejected')) OR (${table.direction} = 'outbound' AND ${table.status} IN ('queued', 'sent', 'failed', 'permanently_failed', 'abandoned'))`,\n ),\n check(\n \"activity_deliveries_completed_check\",\n sql`(${table.completed} IS NULL) = (${table.status} = 'queued')`,\n ),\n check(\n \"activity_deliveries_status_code_check\",\n sql`${table.statusCode} IS NULL OR ${table.statusCode} BETWEEN 100 AND 599`,\n ),\n check(\n \"activity_deliveries_outbound_key_check\",\n sql`${table.direction} <> 'outbound' OR ${table.verificationKeyId} IS NULL`,\n ),\n check(\n \"activity_deliveries_verification_result_check\",\n sql`(${table.direction} = 'inbound') = (${table.verificationResult} IS NOT NULL)`,\n ),\n check(\n \"activity_deliveries_verification_mechanism_check\",\n sql`${table.verificationMechanism} IS NULL OR (${table.direction} = 'inbound' AND ${table.verificationResult} NOT IN ('unattempted', 'unobserved'))`,\n ),\n check(\n \"activity_deliveries_body_check\",\n sql`(${table.direction} = 'inbound') = (${table.body} IS NOT NULL)`,\n ),\n check(\n \"activity_deliveries_activity_check\",\n sql`${table.activityId} IS NULL OR ${table.direction} = 'outbound' OR (${table.verificationResult} = 'verified' AND ${table.status} IN ('received', 'acknowledged'))`,\n ),\n index(\"activity_delivery_instance_created_index\").on(\n table.instanceId,\n desc(table.created),\n desc(table.id),\n ),\n index(\"activity_delivery_actor_index\").on(table.actorId),\n index(\"activity_delivery_activity_created_index\").on(\n table.activityId,\n desc(table.created),\n desc(table.id),\n ),\n index(\"activity_delivery_verification_key_index\").on(\n table.verificationKeyId,\n ),\n index(\"activity_delivery_outbound_index\")\n .on(table.activityIri, table.inboxUrl)\n .where(sql`${table.direction} = 'outbound'`),\n ],\n);\n\n/** Each ended attempt of an outbound delivery. */\nexport const activityDeliveryAttempts = pgTable(\n \"activity_delivery_attempts\",\n {\n id: uuid().$type<Uuid>().primaryKey(),\n deliveryId: uuid(\"delivery_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => activityDeliveries.id, { onDelete: \"cascade\" }),\n succeeded: boolean().notNull(),\n statusCode: integer(\"status_code\"),\n responseBody: text(\"response_body\"),\n error: text(),\n /** When the attempt ended. */\n created: instant().notNull().default(currentTimestamp),\n },\n (table) => [\n check(\n \"activity_delivery_attempts_status_code_check\",\n sql`${table.statusCode} IS NULL OR ${table.statusCode} BETWEEN 100 AND 599`,\n ),\n check(\n \"activity_delivery_attempts_error_check\",\n sql`${table.succeeded} = (${table.error} IS NULL)`,\n ),\n index(\"activity_delivery_attempt_delivery_index\").on(\n table.deliveryId,\n table.created,\n table.id,\n ),\n ],\n);\n\n/**\n * The local actors a delivery concerns, one row per delivery and actor; each\n * must be a local actor of the delivery's instance, which the record functions\n * check.\n */\nexport const activityDeliveryActors = pgTable(\n \"activity_delivery_actors\",\n {\n deliveryId: uuid(\"delivery_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => activityDeliveries.id, { onDelete: \"cascade\" }),\n actorId: uuid(\"actor_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => actors.id, { onDelete: \"cascade\" }),\n inboxOwner: boolean(\"inbox_owner\").notNull().default(false),\n /** Addressed directly or through a collection. */\n addressed: boolean().notNull().default(false),\n /** Addressed by its own IRI; collections are in a row each. */\n addressedDirectly: boolean(\"addressed_directly\").notNull().default(false),\n sender: boolean().notNull().default(false),\n /** The delivery's `created`, which an actor's deliveries are ordered by. */\n created: instant().notNull(),\n },\n (table) => [\n primaryKey({ columns: [table.deliveryId, table.actorId] }),\n check(\n \"activity_delivery_actors_role_check\",\n sql`${table.inboxOwner} OR ${table.addressed} OR ${table.sender}`,\n ),\n check(\n \"activity_delivery_actors_addressed_directly_check\",\n sql`NOT ${table.addressedDirectly} OR ${table.addressed}`,\n ),\n index(\"activity_delivery_actor_created_index\").on(\n table.actorId,\n desc(table.created),\n desc(table.deliveryId),\n ),\n ],\n);\n\n/** Each addressed collection a delivery reached a local actor through. */\nexport const activityDeliveryActorCollections = pgTable(\n \"activity_delivery_actor_collections\",\n {\n deliveryId: uuid(\"delivery_id\").$type<Uuid>().notNull(),\n actorId: uuid(\"actor_id\").$type<Uuid>().notNull(),\n collectionIri: text(\"collection_iri\").notNull(),\n },\n (table) => [\n primaryKey({\n columns: [table.deliveryId, table.actorId, table.collectionIri],\n }),\n foreignKey({\n name: \"activity_delivery_actor_collections_link_fkey\",\n columns: [table.deliveryId, table.actorId],\n foreignColumns: [\n activityDeliveryActors.deliveryId,\n activityDeliveryActors.actorId,\n ],\n }).onDelete(\"cascade\"),\n ],\n);\nexport type Key = typeof keys.$inferSelect;\nexport type KeyVersion = typeof keyVersions.$inferSelect;\nexport type ActivityDelivery = typeof activityDeliveries.$inferSelect;\nexport type NewActivityDelivery = typeof activityDeliveries.$inferInsert;\nexport type ActivityDeliveryAttempt =\n typeof activityDeliveryAttempts.$inferSelect;\nexport type ActivityDeliveryActor = typeof activityDeliveryActors.$inferSelect;\nexport type NewActivityDeliveryActor =\n typeof activityDeliveryActors.$inferInsert;\nexport type ActivityDeliveryActorCollection =\n typeof activityDeliveryActorCollections.$inferSelect;\nexport type ActivityDeliveryDirection =\n (typeof activityDeliveryDirectionEnum.enumValues)[number];\nexport type ActivityDeliveryStatus =\n (typeof activityDeliveryStatusEnum.enumValues)[number];\nexport type ActivityDeliveryVerificationMechanism =\n (typeof activityDeliveryVerificationMechanismEnum.enumValues)[number];\nexport type ActivityDeliveryVerificationResult =\n (typeof activityDeliveryVerificationResultEnum.enumValues)[number];\n\nexport const resourceRevisionKindEnum = pgEnum(\"resource_revision_kind\", [\n \"snapshot\",\n \"unavailable\",\n \"whiteout\",\n]);\nexport const resourceRevisionCaptureEnum = pgEnum(\"resource_revision_capture\", [\n \"local\",\n \"received\",\n \"embedded\",\n \"fetched\",\n]);\nexport const resourceRevisionProjectionEnum = pgEnum(\n \"resource_revision_projection\",\n [\"partial\", \"complete\"],\n);\n\n/** Immutable parsed documents, independently of current typed rows. */\nexport const resourceRevisions = pgTable(\n \"resource_revisions\",\n {\n id: uuid().$type<Uuid>().primaryKey().defaultRandom(),\n resourceId: uuid(\"resource_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => resources.id, { onDelete: \"restrict\" }),\n sequence: integer().notNull(),\n kind: resourceRevisionKindEnum().notNull(),\n capture: resourceRevisionCaptureEnum().notNull(),\n backfilled: boolean().notNull().default(false),\n document: json(),\n formerTypes: text(\"former_types\").array(),\n deleted: instant(),\n projection: resourceRevisionProjectionEnum().notNull().default(\"partial\"),\n created: instant().notNull().default(currentTimestamp),\n },\n (t) => [\n unique(\"resource_revisions_resource_sequence_key\").on(\n t.resourceId,\n t.sequence,\n ),\n unique(\"resource_revisions_resource_id_key\").on(t.resourceId, t.id),\n check(\"resource_revisions_sequence_check\", sql`${t.sequence} > 0`),\n check(\n \"resource_revisions_document_check\",\n sql`(${t.kind} = 'snapshot' AND ${t.document} IS NOT NULL)\n OR (${t.kind} IN ('unavailable', 'whiteout') AND ${t.document} IS NULL)`,\n ),\n check(\n \"resource_revisions_deletion_check\",\n sql`(${t.kind} = 'whiteout' AND ${t.deleted} IS NOT NULL AND ${t.formerTypes} IS NOT NULL)\n OR (${t.kind} <> 'whiteout' AND ${t.deleted} IS NULL AND ${t.formerTypes} IS NULL)`,\n ),\n ],\n);\n\n/** The current revision of one canonical resource. */\nexport const resourceHeads = pgTable(\n \"resource_heads\",\n {\n resourceId: uuid(\"resource_id\")\n .$type<Uuid>()\n .primaryKey()\n .references(() => resources.id, { onDelete: \"restrict\" }),\n revisionId: uuid(\"revision_id\").$type<Uuid>().notNull(),\n },\n (t) => [\n foreignKey({\n name: \"resource_heads_resource_revision_fkey\",\n columns: [t.resourceId, t.revisionId],\n foreignColumns: [resourceRevisions.resourceId, resourceRevisions.id],\n }).onDelete(\"restrict\"),\n ],\n);\n\n/** Root addressing occurrences, including blind recipients and duplicates. */\nexport const revisionAddressing = pgTable(\n \"revision_addressing\",\n {\n revisionId: uuid(\"revision_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => resourceRevisions.id, { onDelete: \"restrict\" }),\n property: addressingPropertyEnum().notNull(),\n position: integer().notNull(),\n iri: text().notNull(),\n },\n (t) => [\n primaryKey({ columns: [t.revisionId, t.property, t.position] }),\n check(\"revision_addressing_position_check\", sql`${t.position} >= 0`),\n index(\"revision_addressing_iri_property_index\").on(t.iri, t.property),\n ],\n);\n\nexport const revisionRelationRepresentationEnum = pgEnum(\n \"revision_relation_representation\",\n [\"reference\", \"embedded\", \"link\"],\n);\n/** Caller-supplied relation occurrences; the saved JSON remains authoritative. */\nexport const revisionRelations = pgTable(\n \"revision_relations\",\n {\n revisionId: uuid(\"revision_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => resourceRevisions.id, { onDelete: \"restrict\" }),\n occurrence: integer().notNull(),\n property: text().notNull(),\n path: json().$type<readonly (string | number)[]>(),\n representation: revisionRelationRepresentationEnum().notNull(),\n targetIri: text(\"target_iri\"),\n },\n (t) => [\n primaryKey({ columns: [t.revisionId, t.occurrence] }),\n check(\"revision_relations_occurrence_check\", sql`${t.occurrence} >= 0`),\n check(\n \"revision_relations_path_check\",\n sql`${t.path} IS NULL OR json_typeof(${t.path}) = 'array'`,\n ),\n check(\n \"revision_relations_reference_check\",\n sql`${t.representation} <> 'reference' OR ${t.targetIri} IS NOT NULL`,\n ),\n index(\"revision_relations_property_target_index\").on(\n t.property,\n t.targetIri,\n t.revisionId,\n ),\n ],\n);\n\nexport const revisionReceiptRoleEnum = pgEnum(\"revision_receipt_role\", [\n \"activity\",\n \"object\",\n]);\n/** Mutable index of delivery evidence, not part of immutable document history. */\nexport const revisionReceipts = pgTable(\n \"revision_receipts\",\n {\n deliveryId: uuid(\"delivery_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => activityDeliveries.id, { onDelete: \"cascade\" }),\n revisionId: uuid(\"revision_id\")\n .$type<Uuid>()\n .notNull()\n .references(() => resourceRevisions.id, { onDelete: \"restrict\" }),\n role: revisionReceiptRoleEnum().notNull(),\n },\n (t) => [\n primaryKey({ columns: [t.deliveryId, t.revisionId, t.role] }),\n index(\"revision_receipts_revision_index\").on(t.revisionId),\n ],\n);\n\nexport type ResourceRevision = typeof resourceRevisions.$inferSelect;\nexport type NewResourceRevision = typeof resourceRevisions.$inferInsert;\nexport type ResourceHead = typeof resourceHeads.$inferSelect;\nexport type RevisionAddressing = typeof revisionAddressing.$inferSelect;\nexport type RevisionRelation = typeof revisionRelations.$inferSelect;\nexport type RevisionReceipt = typeof revisionReceipts.$inferSelect;\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,MAAM,UAAU,WAA2D;CACzE,gBAAgB;CAChB,aAAa,UAAU,SAAS,QAAQ,KAAK,KAAK;CAClD,SAAS,OAAkC;EAEzC,IAAI,OAAO,UAAU,UAAU,OAAO;EACtC,IAAI,iBAAiB,SAAS,SAAS,OAAO,MAAM,SAAS;EAC7D,MAAM,IAAI,UACR,2DACF;CACF;AACF,CAAC;AAED,MAAM,mBAAmB,GAAG;;;;AAK5B,MAAa,WAAW,QACtB,YACA;CACE,IAAI,KAAK,CAAC,CAAC,MAAY,CAAC,CAAC,WAAW;CACpC,OAAO,QAAQ,EAAE,QAAQ,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC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