@ai-matrx/summon 0.0.0 → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +21 -0
- package/LICENSE +21 -0
- package/README.md +379 -1
- package/dist/closeBinding-C6raC3qJ.d.cts +20 -0
- package/dist/closeBinding-C6raC3qJ.d.ts +20 -0
- package/dist/dialog.cjs +60 -0
- package/dist/dialog.cjs.map +1 -0
- package/dist/dialog.d.cts +16 -0
- package/dist/dialog.d.ts +16 -0
- package/dist/dialog.js +38 -0
- package/dist/dialog.js.map +1 -0
- package/dist/errors-eJrKXq33.d.cts +30 -0
- package/dist/errors-eJrKXq33.d.ts +30 -0
- package/dist/handles.cjs +411 -0
- package/dist/handles.cjs.map +1 -0
- package/dist/handles.d.cts +166 -0
- package/dist/handles.d.ts +166 -0
- package/dist/handles.js +388 -0
- package/dist/handles.js.map +1 -0
- package/dist/index.cjs +2383 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +1259 -0
- package/dist/index.d.ts +1259 -0
- package/dist/index.js +2363 -0
- package/dist/index.js.map +1 -0
- package/dist/lite.cjs +460 -0
- package/dist/lite.cjs.map +1 -0
- package/dist/lite.d.cts +56 -0
- package/dist/lite.d.ts +56 -0
- package/dist/lite.js +444 -0
- package/dist/lite.js.map +1 -0
- package/dist/next.cjs +61 -0
- package/dist/next.cjs.map +1 -0
- package/dist/next.d.cts +5 -0
- package/dist/next.d.ts +5 -0
- package/dist/next.js +39 -0
- package/dist/next.js.map +1 -0
- package/dist/persistence-data.cjs +143 -0
- package/dist/persistence-data.cjs.map +1 -0
- package/dist/persistence-data.d.cts +72 -0
- package/dist/persistence-data.d.ts +72 -0
- package/dist/persistence-data.js +120 -0
- package/dist/persistence-data.js.map +1 -0
- package/dist/persistence.cjs +1073 -0
- package/dist/persistence.cjs.map +1 -0
- package/dist/persistence.d.cts +236 -0
- package/dist/persistence.d.ts +236 -0
- package/dist/persistence.js +1077 -0
- package/dist/persistence.js.map +1 -0
- package/dist/react.cjs +738 -0
- package/dist/react.cjs.map +1 -0
- package/dist/react.d.cts +266 -0
- package/dist/react.d.ts +266 -0
- package/dist/react.js +723 -0
- package/dist/react.js.map +1 -0
- package/dist/sheet.cjs +71 -0
- package/dist/sheet.cjs.map +1 -0
- package/dist/sheet.d.cts +17 -0
- package/dist/sheet.d.ts +17 -0
- package/dist/sheet.js +49 -0
- package/dist/sheet.js.map +1 -0
- package/dist/styles.css +78 -0
- package/dist/testing.cjs +132 -0
- package/dist/testing.cjs.map +1 -0
- package/dist/testing.d.cts +44 -0
- package/dist/testing.d.ts +44 -0
- package/dist/testing.js +115 -0
- package/dist/testing.js.map +1 -0
- package/dist/url.cjs +362 -0
- package/dist/url.cjs.map +1 -0
- package/dist/url.d.cts +153 -0
- package/dist/url.d.ts +153 -0
- package/dist/url.js +352 -0
- package/dist/url.js.map +1 -0
- package/dist/window-host.cjs +123 -0
- package/dist/window-host.cjs.map +1 -0
- package/dist/window-host.d.cts +72 -0
- package/dist/window-host.d.ts +72 -0
- package/dist/window-host.js +104 -0
- package/dist/window-host.js.map +1 -0
- package/dist/window.cjs +3977 -0
- package/dist/window.cjs.map +1 -0
- package/dist/window.d.cts +796 -0
- package/dist/window.d.ts +796 -0
- package/dist/window.js +4002 -0
- package/dist/window.js.map +1 -0
- package/package.json +239 -1
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/persistence-data.ts
|
|
21
|
+
var persistence_data_exports = {};
|
|
22
|
+
__export(persistence_data_exports, {
|
|
23
|
+
PersistenceVersionConflictError: () => PersistenceVersionConflictError,
|
|
24
|
+
SUMMON_SURFACE_FEATURE: () => SUMMON_SURFACE_FEATURE,
|
|
25
|
+
createDataPersistence: () => createDataPersistence,
|
|
26
|
+
isVersionConflict: () => isVersionConflict,
|
|
27
|
+
userSurfaceStateTable: () => userSurfaceStateTable
|
|
28
|
+
});
|
|
29
|
+
module.exports = __toCommonJS(persistence_data_exports);
|
|
30
|
+
|
|
31
|
+
// src/persistence/data/createDataPersistence.ts
|
|
32
|
+
var import_db = require("@ai-matrx/data/db");
|
|
33
|
+
|
|
34
|
+
// src/persistence/errors.ts
|
|
35
|
+
var VERSION_CONFLICT_ERROR = "OverlayPersistenceVersionConflict";
|
|
36
|
+
var PersistenceVersionConflictError = class extends Error {
|
|
37
|
+
key;
|
|
38
|
+
expectedVersion;
|
|
39
|
+
currentVersion;
|
|
40
|
+
constructor(key, expectedVersion, currentVersion) {
|
|
41
|
+
super(`[overlays/persistence] "${key}" is at version ${currentVersion}, not the expected ${expectedVersion}`);
|
|
42
|
+
this.name = VERSION_CONFLICT_ERROR;
|
|
43
|
+
this.key = key;
|
|
44
|
+
this.expectedVersion = expectedVersion;
|
|
45
|
+
this.currentVersion = currentVersion;
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
function isVersionConflict(error) {
|
|
49
|
+
return error instanceof Error && error.name === VERSION_CONFLICT_ERROR;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// src/persistence/data/createDataPersistence.ts
|
|
53
|
+
var SUMMON_SURFACE_FEATURE = "summon";
|
|
54
|
+
var userSurfaceStateTable = {
|
|
55
|
+
schema: "users",
|
|
56
|
+
name: "user_surface_state",
|
|
57
|
+
kind: "table",
|
|
58
|
+
type: "entity",
|
|
59
|
+
pk: ["id"],
|
|
60
|
+
org: { rule: "binding" },
|
|
61
|
+
versioned: true,
|
|
62
|
+
softDelete: true,
|
|
63
|
+
archive: null,
|
|
64
|
+
readOnly: false,
|
|
65
|
+
deletesRefused: false,
|
|
66
|
+
readOnlyColumns: [],
|
|
67
|
+
listScope: "mine",
|
|
68
|
+
realtime: false,
|
|
69
|
+
createdBy: true
|
|
70
|
+
};
|
|
71
|
+
var COLUMNS = ["id", "surface_key", "state", "version", "deleted_at"];
|
|
72
|
+
var likeEscape = (value) => value.replace(/[\\%_]/g, (ch) => `\\${ch}`);
|
|
73
|
+
var isUniqueViolation = (error) => error instanceof import_db.DatabaseError && error.cause.code === "23505";
|
|
74
|
+
function createDataPersistence(options) {
|
|
75
|
+
const { db } = options;
|
|
76
|
+
const table = options.table ?? userSurfaceStateTable;
|
|
77
|
+
const feature = options.feature ?? SUMMON_SURFACE_FEATURE;
|
|
78
|
+
const personId = async () => {
|
|
79
|
+
const explicit = options.userId?.();
|
|
80
|
+
if (explicit) return explicit;
|
|
81
|
+
const session = db.client.auth ? await db.client.auth.getSession() : null;
|
|
82
|
+
const id = session?.data.session?.user?.id;
|
|
83
|
+
if (!id) throw new Error("[overlays/persistence/data] no signed-in person: overlay state is saved per person");
|
|
84
|
+
return id;
|
|
85
|
+
};
|
|
86
|
+
const find = async (key, includeDeleted) => {
|
|
87
|
+
const userId = await personId();
|
|
88
|
+
const rows = await (0, import_db.listAll)(db, table, (q) => q.eq("user_id", userId).eq("feature", feature).eq("surface_key", key), {
|
|
89
|
+
columns: COLUMNS,
|
|
90
|
+
includeDeleted
|
|
91
|
+
});
|
|
92
|
+
return rows.find((row) => row.deleted_at === null) ?? rows[0] ?? null;
|
|
93
|
+
};
|
|
94
|
+
const conflict = (key, expected, current) => new PersistenceVersionConflictError(key, expected, current);
|
|
95
|
+
return {
|
|
96
|
+
perPerson: true,
|
|
97
|
+
async load(key) {
|
|
98
|
+
const row = await find(key, false);
|
|
99
|
+
return row ? { value: row.state, version: row.version } : null;
|
|
100
|
+
},
|
|
101
|
+
async save(key, value, saveOptions) {
|
|
102
|
+
const expected = saveOptions?.expectedVersion;
|
|
103
|
+
const state = value;
|
|
104
|
+
const row = await find(key, true);
|
|
105
|
+
if (row && row.deleted_at === null) {
|
|
106
|
+
if (expected === 0) throw conflict(key, 0, row.version);
|
|
107
|
+
const result = await (0, import_db.update)(db, table, row.id, { state }, expected === void 0 ? { overwrite: true } : { expectedVersion: expected });
|
|
108
|
+
if (result.status === "saved") return { version: result.row.version };
|
|
109
|
+
if (result.status === "conflict") throw conflict(key, expected ?? row.version, result.currentVersion);
|
|
110
|
+
throw conflict(key, expected ?? row.version, 0);
|
|
111
|
+
}
|
|
112
|
+
if (expected !== void 0 && expected !== 0) throw conflict(key, expected, 0);
|
|
113
|
+
if (row) {
|
|
114
|
+
const result = await (0, import_db.update)(db, table, row.id, { state, deleted_at: null }, { expectedVersion: row.version });
|
|
115
|
+
if (result.status === "saved") return { version: result.row.version };
|
|
116
|
+
throw conflict(key, 0, result.status === "conflict" ? result.currentVersion : 0);
|
|
117
|
+
}
|
|
118
|
+
try {
|
|
119
|
+
const created = await (0, import_db.insert)(db, table, { user_id: await personId(), feature, surface_key: key, state });
|
|
120
|
+
return { version: created.version };
|
|
121
|
+
} catch (error) {
|
|
122
|
+
if (isUniqueViolation(error)) throw conflict(key, 0, (await find(key, true))?.version ?? 1);
|
|
123
|
+
throw error;
|
|
124
|
+
}
|
|
125
|
+
},
|
|
126
|
+
async remove(key) {
|
|
127
|
+
const row = await find(key, false);
|
|
128
|
+
if (!row) return;
|
|
129
|
+
await (0, import_db.remove)(db, table, row.id, { overwrite: true });
|
|
130
|
+
},
|
|
131
|
+
async list(prefix) {
|
|
132
|
+
const userId = await personId();
|
|
133
|
+
const rows = await (0, import_db.listAll)(
|
|
134
|
+
db,
|
|
135
|
+
table,
|
|
136
|
+
(q) => q.eq("user_id", userId).eq("feature", feature).like("surface_key", `${likeEscape(prefix)}%`),
|
|
137
|
+
{ columns: ["surface_key"] }
|
|
138
|
+
);
|
|
139
|
+
return rows.map((row) => row.surface_key).filter((key) => key.startsWith(prefix)).sort();
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
}
|
|
143
|
+
//# sourceMappingURL=persistence-data.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/persistence-data.ts","../src/persistence/data/createDataPersistence.ts","../src/persistence/errors.ts"],"sourcesContent":["// @ai-matrx/summon/persistence/data — the @ai-matrx/data adapter over users.user_surface_state\n// (feature 'summon'; surface_key 'workspace' and 'state:<instanceKey>'; optimistic versions).\nexport {\n createDataPersistence,\n userSurfaceStateTable,\n SUMMON_SURFACE_FEATURE,\n type DataPersistenceOptions,\n type DataOverlayPersistence,\n type UserSurfaceStateRow,\n type UserSurfaceStateInsert,\n type UserSurfaceStateUpdate,\n} from \"./persistence/data/createDataPersistence\";\nexport { PersistenceVersionConflictError, isVersionConflict } from \"./persistence/errors\";\n","/**\n * createDataPersistence — the OverlayPersistencePort over `@ai-matrx/data`, backed by the\n * canonical per-person working-data table `users.user_surface_state` (design R4):\n *\n * feature = 'overlays', surface_key = <key>, state = <value>, version = optimistic version.\n * Keys: `workspace` (the person's open windows/layout), `state:<overlayId>:<instanceId>`.\n *\n * Every call goes through the data package's doors (listAll / insert / update / remove) — the\n * descriptor's rules apply: the table is an `entity` with `org.rule = \"binding\"`, so an insert\n * takes the organization from `createDb({ organization })` (the host's active organization) and\n * the door REFUSES when there is none; this adapter adds no fallback of its own. Reads are scoped\n * to the signed-in person (`user_id`), never to an organization.\n *\n * The row is unique per (user_id, feature, surface_key) including soft-deleted rows, so `remove`\n * soft-deletes and a later `save` revives the same row instead of inserting a duplicate.\n */\nimport { DatabaseError, insert, listAll, remove as removeRow, update, type Db, type TableDescriptor } from \"@ai-matrx/data/db\";\nimport type { OverlayPersistencePort, StoredValue } from \"@ai-matrx/summon\";\nimport { PersistenceVersionConflictError } from \"../errors\";\n\nexport const SUMMON_SURFACE_FEATURE = \"summon\";\n\ntype Json = string | number | boolean | null | { [key: string]: Json | undefined } | Json[];\n\n/** The columns of users.user_surface_state this adapter reads and writes. */\nexport interface UserSurfaceStateRow {\n id: string;\n user_id: string;\n feature: string;\n surface_key: string;\n state: Json;\n organization_id: string;\n version: number;\n deleted_at: string | null;\n created_at: string;\n updated_at: string;\n created_by: string | null;\n updated_by: string | null;\n metadata: Json;\n custom_fields: Json;\n}\nexport interface UserSurfaceStateInsert {\n user_id: string;\n feature: string;\n surface_key?: string;\n state?: Json;\n organization_id?: string;\n deleted_at?: string | null;\n}\nexport type UserSurfaceStateUpdate = Partial<UserSurfaceStateInsert>;\n\n/**\n * The generated descriptor for users.user_surface_state (`matrx-data generate --schemas users`,\n * contract 1436b3e225ff). A host may pass its own freshly generated one instead.\n */\nexport const userSurfaceStateTable = {\n schema: \"users\",\n name: \"user_surface_state\",\n kind: \"table\",\n type: \"entity\",\n pk: [\"id\"],\n org: { rule: \"binding\" },\n versioned: true,\n softDelete: true,\n archive: null,\n readOnly: false,\n deletesRefused: false,\n readOnlyColumns: [],\n listScope: \"mine\",\n realtime: false,\n createdBy: true,\n} as const satisfies TableDescriptor<UserSurfaceStateRow, UserSurfaceStateInsert, UserSurfaceStateUpdate> as unknown as TableDescriptor<\n UserSurfaceStateRow,\n UserSurfaceStateInsert,\n UserSurfaceStateUpdate\n>;\n\nexport interface DataPersistenceOptions {\n readonly db: Db;\n /** The signed-in person's id. Default: the session on `db.client.auth`. */\n readonly userId?: () => string | null | undefined;\n /** Override the descriptor (a host's own generated `userSurfaceState`). */\n readonly table?: TableDescriptor<UserSurfaceStateRow, UserSurfaceStateInsert, UserSurfaceStateUpdate>;\n /** Default \"overlays\". */\n readonly feature?: string;\n}\n\nexport interface DataOverlayPersistence extends OverlayPersistencePort {\n readonly perPerson: true;\n list(prefix: string): Promise<readonly string[]>;\n}\n\nconst COLUMNS = [\"id\", \"surface_key\", \"state\", \"version\", \"deleted_at\"] as const;\ntype Found = Pick<UserSurfaceStateRow, (typeof COLUMNS)[number]>;\n\nconst likeEscape = (value: string) => value.replace(/[\\\\%_]/g, (ch) => `\\\\${ch}`);\nconst isUniqueViolation = (error: unknown) => error instanceof DatabaseError && error.cause.code === \"23505\";\n\nexport function createDataPersistence(options: DataPersistenceOptions): DataOverlayPersistence {\n const { db } = options;\n const table = options.table ?? userSurfaceStateTable;\n const feature = options.feature ?? SUMMON_SURFACE_FEATURE;\n\n const personId = async (): Promise<string> => {\n const explicit = options.userId?.();\n if (explicit) return explicit;\n const session = db.client.auth ? await db.client.auth.getSession() : null;\n const id = session?.data.session?.user?.id;\n if (!id) throw new Error(\"[overlays/persistence/data] no signed-in person: overlay state is saved per person\");\n return id;\n };\n\n const find = async (key: string, includeDeleted: boolean): Promise<Found | null> => {\n const userId = await personId();\n const rows = await listAll(db, table, (q) => q.eq(\"user_id\", userId).eq(\"feature\", feature).eq(\"surface_key\", key), {\n columns: COLUMNS,\n includeDeleted,\n });\n // Unique per (user_id, feature, surface_key); a live row beats a soft-deleted one.\n return rows.find((row) => row.deleted_at === null) ?? rows[0] ?? null;\n };\n\n const conflict = (key: string, expected: number, current: number) => new PersistenceVersionConflictError(key, expected, current);\n\n return {\n perPerson: true,\n\n async load<T = unknown>(key: string): Promise<StoredValue<T> | null> {\n const row = await find(key, false);\n return row ? { value: row.state as T, version: row.version } : null;\n },\n\n async save<T = unknown>(key: string, value: T, saveOptions?: { readonly expectedVersion?: number }) {\n const expected = saveOptions?.expectedVersion;\n const state = value as unknown as Json;\n const row = await find(key, true);\n if (row && row.deleted_at === null) {\n if (expected === 0) throw conflict(key, 0, row.version);\n const result = await update(db, table, row.id, { state }, expected === undefined ? { overwrite: true } : { expectedVersion: expected });\n if (result.status === \"saved\") return { version: result.row.version };\n if (result.status === \"conflict\") throw conflict(key, expected ?? row.version, result.currentVersion);\n throw conflict(key, expected ?? row.version, 0); // vanished between read and write\n }\n if (expected !== undefined && expected !== 0) throw conflict(key, expected, 0);\n if (row) {\n // Revive the soft-deleted row (the unique key includes deleted rows).\n const result = await update(db, table, row.id, { state, deleted_at: null }, { expectedVersion: row.version });\n if (result.status === \"saved\") return { version: result.row.version };\n throw conflict(key, 0, result.status === \"conflict\" ? result.currentVersion : 0);\n }\n try {\n const created = await insert(db, table, { user_id: await personId(), feature, surface_key: key, state });\n return { version: created.version };\n } catch (error) {\n // Another device created it first.\n if (isUniqueViolation(error)) throw conflict(key, 0, (await find(key, true))?.version ?? 1);\n throw error;\n }\n },\n\n async remove(key: string) {\n const row = await find(key, false);\n if (!row) return;\n await removeRow(db, table, row.id, { overwrite: true });\n },\n\n async list(prefix: string) {\n const userId = await personId();\n const rows = await listAll(\n db,\n table,\n (q) => q.eq(\"user_id\", userId).eq(\"feature\", feature).like(\"surface_key\", `${likeEscape(prefix)}%`),\n { columns: [\"surface_key\"] },\n );\n return rows.map((row) => row.surface_key).filter((key) => key.startsWith(prefix)).sort();\n },\n };\n}\n","/**\n * Errors every persistence store throws in the same shape. Matched by `name`, never `instanceof`:\n * each section entry may carry its own copy of this module in a built consumer.\n */\nimport type { StoredValue } from \"@ai-matrx/summon\";\n\nexport const VERSION_CONFLICT_ERROR = \"OverlayPersistenceVersionConflict\";\nexport const LOAD_TIMEOUT_ERROR = \"OverlayPersistenceLoadTimeout\";\n\n/** A save whose `expectedVersion` no longer matches the stored version. */\nexport class PersistenceVersionConflictError extends Error {\n readonly key: string;\n readonly expectedVersion: number;\n readonly currentVersion: number;\n constructor(key: string, expectedVersion: number, currentVersion: number) {\n super(`[overlays/persistence] \"${key}\" is at version ${currentVersion}, not the expected ${expectedVersion}`);\n this.name = VERSION_CONFLICT_ERROR;\n this.key = key;\n this.expectedVersion = expectedVersion;\n this.currentVersion = currentVersion;\n }\n}\n\nexport function isVersionConflict(error: unknown): error is PersistenceVersionConflictError {\n return error instanceof Error && error.name === VERSION_CONFLICT_ERROR;\n}\n\n/**\n * The fast tier missed and the slow tier did not answer within the read budget. `pending` still\n * resolves the authoritative answer: a caller keeps every automatic writer gated until it does,\n * so an unknown stored value is never overwritten.\n */\nexport class PersistenceLoadTimeoutError extends Error {\n readonly key: string;\n readonly pending: Promise<StoredValue | null>;\n constructor(key: string, budgetMs: number, pending: Promise<StoredValue | null>) {\n super(`[overlays/persistence] \"${key}\" did not load within ${budgetMs}ms`);\n this.name = LOAD_TIMEOUT_ERROR;\n this.key = key;\n this.pending = pending;\n }\n}\n\nexport function isLoadTimeout(error: unknown): error is PersistenceLoadTimeoutError {\n return error instanceof Error && error.name === LOAD_TIMEOUT_ERROR;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACgBA,gBAA2G;;;ACVpG,IAAM,yBAAyB;AAI/B,IAAM,kCAAN,cAA8C,MAAM;AAAA,EAChD;AAAA,EACA;AAAA,EACA;AAAA,EACT,YAAY,KAAa,iBAAyB,gBAAwB;AACxE,UAAM,2BAA2B,GAAG,mBAAmB,cAAc,sBAAsB,eAAe,EAAE;AAC5G,SAAK,OAAO;AACZ,SAAK,MAAM;AACX,SAAK,kBAAkB;AACvB,SAAK,iBAAiB;AAAA,EACxB;AACF;AAEO,SAAS,kBAAkB,OAA0D;AAC1F,SAAO,iBAAiB,SAAS,MAAM,SAAS;AAClD;;;ADLO,IAAM,yBAAyB;AAmC/B,IAAM,wBAAwB;AAAA,EACnC,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,MAAM;AAAA,EACN,MAAM;AAAA,EACN,IAAI,CAAC,IAAI;AAAA,EACT,KAAK,EAAE,MAA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pC,SAAS,OAAO;AAEd,YAAI,kBAAkB,KAAK,EAAG,OAAM,SAAS,KAAK,IAAI,MAAM,KAAK,KAAK,IAAI,IAAI,WAAW,CAAC;AAC1F,cAAM;AAAA,MACR;AAAA,IACF;AAAA,IAEA,MAAM,OAAO,KAAa;AACxB,YAAM,MAAM,MAAM,KAAK,KAAK,KAAK;AACjC,UAAI,CAAC,IAAK;AACV,gBAAM,UAAAA,QAAU,IAAI,OAAO,IAAI,IAAI,EAAE,WAAW,KAAK,CAAC;AAAA,IACxD;AAAA,IAEA,MAAM,KAAK,QAAgB;AACzB,YAAM,SAAS,MAAM,SAAS;AAC9B,YAAM,OAAO,UAAM;AAAA,QACjB;AAAA,QACA;AAAA,QACA,CAAC,MAAM,EAAE,GAAG,WAAW,MAAM,EAAE,GAAG,WAAW,OAAO,EAAE,KAAK,eAAe,GAAG,WAAW,MAAM,CAAC,GAAG;AAAA,QAClG,EAAE,SAAS,CAAC,aAAa,EAAE;AAAA,MAC7B;AACA,aAAO,KAAK,IAAI,CAAC,QAAQ,IAAI,WAAW,EAAE,OAAO,CAAC,QAAQ,IAAI,WAAW,MAAM,CAAC,EAAE,KAAK;AAAA,IACzF;AAAA,EACF;AACF;","names":["removeRow"]}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { Db, TableDescriptor } from '@ai-matrx/data/db';
|
|
2
|
+
import { OverlayPersistencePort } from '@ai-matrx/summon';
|
|
3
|
+
export { P as PersistenceVersionConflictError, i as isVersionConflict } from './errors-eJrKXq33.cjs';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* createDataPersistence — the OverlayPersistencePort over `@ai-matrx/data`, backed by the
|
|
7
|
+
* canonical per-person working-data table `users.user_surface_state` (design R4):
|
|
8
|
+
*
|
|
9
|
+
* feature = 'overlays', surface_key = <key>, state = <value>, version = optimistic version.
|
|
10
|
+
* Keys: `workspace` (the person's open windows/layout), `state:<overlayId>:<instanceId>`.
|
|
11
|
+
*
|
|
12
|
+
* Every call goes through the data package's doors (listAll / insert / update / remove) — the
|
|
13
|
+
* descriptor's rules apply: the table is an `entity` with `org.rule = "binding"`, so an insert
|
|
14
|
+
* takes the organization from `createDb({ organization })` (the host's active organization) and
|
|
15
|
+
* the door REFUSES when there is none; this adapter adds no fallback of its own. Reads are scoped
|
|
16
|
+
* to the signed-in person (`user_id`), never to an organization.
|
|
17
|
+
*
|
|
18
|
+
* The row is unique per (user_id, feature, surface_key) including soft-deleted rows, so `remove`
|
|
19
|
+
* soft-deletes and a later `save` revives the same row instead of inserting a duplicate.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
declare const SUMMON_SURFACE_FEATURE = "summon";
|
|
23
|
+
type Json = string | number | boolean | null | {
|
|
24
|
+
[key: string]: Json | undefined;
|
|
25
|
+
} | Json[];
|
|
26
|
+
/** The columns of users.user_surface_state this adapter reads and writes. */
|
|
27
|
+
interface UserSurfaceStateRow {
|
|
28
|
+
id: string;
|
|
29
|
+
user_id: string;
|
|
30
|
+
feature: string;
|
|
31
|
+
surface_key: string;
|
|
32
|
+
state: Json;
|
|
33
|
+
organization_id: string;
|
|
34
|
+
version: number;
|
|
35
|
+
deleted_at: string | null;
|
|
36
|
+
created_at: string;
|
|
37
|
+
updated_at: string;
|
|
38
|
+
created_by: string | null;
|
|
39
|
+
updated_by: string | null;
|
|
40
|
+
metadata: Json;
|
|
41
|
+
custom_fields: Json;
|
|
42
|
+
}
|
|
43
|
+
interface UserSurfaceStateInsert {
|
|
44
|
+
user_id: string;
|
|
45
|
+
feature: string;
|
|
46
|
+
surface_key?: string;
|
|
47
|
+
state?: Json;
|
|
48
|
+
organization_id?: string;
|
|
49
|
+
deleted_at?: string | null;
|
|
50
|
+
}
|
|
51
|
+
type UserSurfaceStateUpdate = Partial<UserSurfaceStateInsert>;
|
|
52
|
+
/**
|
|
53
|
+
* The generated descriptor for users.user_surface_state (`matrx-data generate --schemas users`,
|
|
54
|
+
* contract 1436b3e225ff). A host may pass its own freshly generated one instead.
|
|
55
|
+
*/
|
|
56
|
+
declare const userSurfaceStateTable: TableDescriptor<UserSurfaceStateRow, UserSurfaceStateInsert, UserSurfaceStateUpdate>;
|
|
57
|
+
interface DataPersistenceOptions {
|
|
58
|
+
readonly db: Db;
|
|
59
|
+
/** The signed-in person's id. Default: the session on `db.client.auth`. */
|
|
60
|
+
readonly userId?: () => string | null | undefined;
|
|
61
|
+
/** Override the descriptor (a host's own generated `userSurfaceState`). */
|
|
62
|
+
readonly table?: TableDescriptor<UserSurfaceStateRow, UserSurfaceStateInsert, UserSurfaceStateUpdate>;
|
|
63
|
+
/** Default "overlays". */
|
|
64
|
+
readonly feature?: string;
|
|
65
|
+
}
|
|
66
|
+
interface DataOverlayPersistence extends OverlayPersistencePort {
|
|
67
|
+
readonly perPerson: true;
|
|
68
|
+
list(prefix: string): Promise<readonly string[]>;
|
|
69
|
+
}
|
|
70
|
+
declare function createDataPersistence(options: DataPersistenceOptions): DataOverlayPersistence;
|
|
71
|
+
|
|
72
|
+
export { type DataOverlayPersistence, type DataPersistenceOptions, SUMMON_SURFACE_FEATURE, type UserSurfaceStateInsert, type UserSurfaceStateRow, type UserSurfaceStateUpdate, createDataPersistence, userSurfaceStateTable };
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { Db, TableDescriptor } from '@ai-matrx/data/db';
|
|
2
|
+
import { OverlayPersistencePort } from '@ai-matrx/summon';
|
|
3
|
+
export { P as PersistenceVersionConflictError, i as isVersionConflict } from './errors-eJrKXq33.js';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* createDataPersistence — the OverlayPersistencePort over `@ai-matrx/data`, backed by the
|
|
7
|
+
* canonical per-person working-data table `users.user_surface_state` (design R4):
|
|
8
|
+
*
|
|
9
|
+
* feature = 'overlays', surface_key = <key>, state = <value>, version = optimistic version.
|
|
10
|
+
* Keys: `workspace` (the person's open windows/layout), `state:<overlayId>:<instanceId>`.
|
|
11
|
+
*
|
|
12
|
+
* Every call goes through the data package's doors (listAll / insert / update / remove) — the
|
|
13
|
+
* descriptor's rules apply: the table is an `entity` with `org.rule = "binding"`, so an insert
|
|
14
|
+
* takes the organization from `createDb({ organization })` (the host's active organization) and
|
|
15
|
+
* the door REFUSES when there is none; this adapter adds no fallback of its own. Reads are scoped
|
|
16
|
+
* to the signed-in person (`user_id`), never to an organization.
|
|
17
|
+
*
|
|
18
|
+
* The row is unique per (user_id, feature, surface_key) including soft-deleted rows, so `remove`
|
|
19
|
+
* soft-deletes and a later `save` revives the same row instead of inserting a duplicate.
|
|
20
|
+
*/
|
|
21
|
+
|
|
22
|
+
declare const SUMMON_SURFACE_FEATURE = "summon";
|
|
23
|
+
type Json = string | number | boolean | null | {
|
|
24
|
+
[key: string]: Json | undefined;
|
|
25
|
+
} | Json[];
|
|
26
|
+
/** The columns of users.user_surface_state this adapter reads and writes. */
|
|
27
|
+
interface UserSurfaceStateRow {
|
|
28
|
+
id: string;
|
|
29
|
+
user_id: string;
|
|
30
|
+
feature: string;
|
|
31
|
+
surface_key: string;
|
|
32
|
+
state: Json;
|
|
33
|
+
organization_id: string;
|
|
34
|
+
version: number;
|
|
35
|
+
deleted_at: string | null;
|
|
36
|
+
created_at: string;
|
|
37
|
+
updated_at: string;
|
|
38
|
+
created_by: string | null;
|
|
39
|
+
updated_by: string | null;
|
|
40
|
+
metadata: Json;
|
|
41
|
+
custom_fields: Json;
|
|
42
|
+
}
|
|
43
|
+
interface UserSurfaceStateInsert {
|
|
44
|
+
user_id: string;
|
|
45
|
+
feature: string;
|
|
46
|
+
surface_key?: string;
|
|
47
|
+
state?: Json;
|
|
48
|
+
organization_id?: string;
|
|
49
|
+
deleted_at?: string | null;
|
|
50
|
+
}
|
|
51
|
+
type UserSurfaceStateUpdate = Partial<UserSurfaceStateInsert>;
|
|
52
|
+
/**
|
|
53
|
+
* The generated descriptor for users.user_surface_state (`matrx-data generate --schemas users`,
|
|
54
|
+
* contract 1436b3e225ff). A host may pass its own freshly generated one instead.
|
|
55
|
+
*/
|
|
56
|
+
declare const userSurfaceStateTable: TableDescriptor<UserSurfaceStateRow, UserSurfaceStateInsert, UserSurfaceStateUpdate>;
|
|
57
|
+
interface DataPersistenceOptions {
|
|
58
|
+
readonly db: Db;
|
|
59
|
+
/** The signed-in person's id. Default: the session on `db.client.auth`. */
|
|
60
|
+
readonly userId?: () => string | null | undefined;
|
|
61
|
+
/** Override the descriptor (a host's own generated `userSurfaceState`). */
|
|
62
|
+
readonly table?: TableDescriptor<UserSurfaceStateRow, UserSurfaceStateInsert, UserSurfaceStateUpdate>;
|
|
63
|
+
/** Default "overlays". */
|
|
64
|
+
readonly feature?: string;
|
|
65
|
+
}
|
|
66
|
+
interface DataOverlayPersistence extends OverlayPersistencePort {
|
|
67
|
+
readonly perPerson: true;
|
|
68
|
+
list(prefix: string): Promise<readonly string[]>;
|
|
69
|
+
}
|
|
70
|
+
declare function createDataPersistence(options: DataPersistenceOptions): DataOverlayPersistence;
|
|
71
|
+
|
|
72
|
+
export { type DataOverlayPersistence, type DataPersistenceOptions, SUMMON_SURFACE_FEATURE, type UserSurfaceStateInsert, type UserSurfaceStateRow, type UserSurfaceStateUpdate, createDataPersistence, userSurfaceStateTable };
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
// src/persistence/data/createDataPersistence.ts
|
|
2
|
+
import { DatabaseError, insert, listAll, remove as removeRow, update } from "@ai-matrx/data/db";
|
|
3
|
+
|
|
4
|
+
// src/persistence/errors.ts
|
|
5
|
+
var VERSION_CONFLICT_ERROR = "OverlayPersistenceVersionConflict";
|
|
6
|
+
var PersistenceVersionConflictError = class extends Error {
|
|
7
|
+
key;
|
|
8
|
+
expectedVersion;
|
|
9
|
+
currentVersion;
|
|
10
|
+
constructor(key, expectedVersion, currentVersion) {
|
|
11
|
+
super(`[overlays/persistence] "${key}" is at version ${currentVersion}, not the expected ${expectedVersion}`);
|
|
12
|
+
this.name = VERSION_CONFLICT_ERROR;
|
|
13
|
+
this.key = key;
|
|
14
|
+
this.expectedVersion = expectedVersion;
|
|
15
|
+
this.currentVersion = currentVersion;
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
function isVersionConflict(error) {
|
|
19
|
+
return error instanceof Error && error.name === VERSION_CONFLICT_ERROR;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// src/persistence/data/createDataPersistence.ts
|
|
23
|
+
var SUMMON_SURFACE_FEATURE = "summon";
|
|
24
|
+
var userSurfaceStateTable = {
|
|
25
|
+
schema: "users",
|
|
26
|
+
name: "user_surface_state",
|
|
27
|
+
kind: "table",
|
|
28
|
+
type: "entity",
|
|
29
|
+
pk: ["id"],
|
|
30
|
+
org: { rule: "binding" },
|
|
31
|
+
versioned: true,
|
|
32
|
+
softDelete: true,
|
|
33
|
+
archive: null,
|
|
34
|
+
readOnly: false,
|
|
35
|
+
deletesRefused: false,
|
|
36
|
+
readOnlyColumns: [],
|
|
37
|
+
listScope: "mine",
|
|
38
|
+
realtime: false,
|
|
39
|
+
createdBy: true
|
|
40
|
+
};
|
|
41
|
+
var COLUMNS = ["id", "surface_key", "state", "version", "deleted_at"];
|
|
42
|
+
var likeEscape = (value) => value.replace(/[\\%_]/g, (ch) => `\\${ch}`);
|
|
43
|
+
var isUniqueViolation = (error) => error instanceof DatabaseError && error.cause.code === "23505";
|
|
44
|
+
function createDataPersistence(options) {
|
|
45
|
+
const { db } = options;
|
|
46
|
+
const table = options.table ?? userSurfaceStateTable;
|
|
47
|
+
const feature = options.feature ?? SUMMON_SURFACE_FEATURE;
|
|
48
|
+
const personId = async () => {
|
|
49
|
+
const explicit = options.userId?.();
|
|
50
|
+
if (explicit) return explicit;
|
|
51
|
+
const session = db.client.auth ? await db.client.auth.getSession() : null;
|
|
52
|
+
const id = session?.data.session?.user?.id;
|
|
53
|
+
if (!id) throw new Error("[overlays/persistence/data] no signed-in person: overlay state is saved per person");
|
|
54
|
+
return id;
|
|
55
|
+
};
|
|
56
|
+
const find = async (key, includeDeleted) => {
|
|
57
|
+
const userId = await personId();
|
|
58
|
+
const rows = await listAll(db, table, (q) => q.eq("user_id", userId).eq("feature", feature).eq("surface_key", key), {
|
|
59
|
+
columns: COLUMNS,
|
|
60
|
+
includeDeleted
|
|
61
|
+
});
|
|
62
|
+
return rows.find((row) => row.deleted_at === null) ?? rows[0] ?? null;
|
|
63
|
+
};
|
|
64
|
+
const conflict = (key, expected, current) => new PersistenceVersionConflictError(key, expected, current);
|
|
65
|
+
return {
|
|
66
|
+
perPerson: true,
|
|
67
|
+
async load(key) {
|
|
68
|
+
const row = await find(key, false);
|
|
69
|
+
return row ? { value: row.state, version: row.version } : null;
|
|
70
|
+
},
|
|
71
|
+
async save(key, value, saveOptions) {
|
|
72
|
+
const expected = saveOptions?.expectedVersion;
|
|
73
|
+
const state = value;
|
|
74
|
+
const row = await find(key, true);
|
|
75
|
+
if (row && row.deleted_at === null) {
|
|
76
|
+
if (expected === 0) throw conflict(key, 0, row.version);
|
|
77
|
+
const result = await update(db, table, row.id, { state }, expected === void 0 ? { overwrite: true } : { expectedVersion: expected });
|
|
78
|
+
if (result.status === "saved") return { version: result.row.version };
|
|
79
|
+
if (result.status === "conflict") throw conflict(key, expected ?? row.version, result.currentVersion);
|
|
80
|
+
throw conflict(key, expected ?? row.version, 0);
|
|
81
|
+
}
|
|
82
|
+
if (expected !== void 0 && expected !== 0) throw conflict(key, expected, 0);
|
|
83
|
+
if (row) {
|
|
84
|
+
const result = await update(db, table, row.id, { state, deleted_at: null }, { expectedVersion: row.version });
|
|
85
|
+
if (result.status === "saved") return { version: result.row.version };
|
|
86
|
+
throw conflict(key, 0, result.status === "conflict" ? result.currentVersion : 0);
|
|
87
|
+
}
|
|
88
|
+
try {
|
|
89
|
+
const created = await insert(db, table, { user_id: await personId(), feature, surface_key: key, state });
|
|
90
|
+
return { version: created.version };
|
|
91
|
+
} catch (error) {
|
|
92
|
+
if (isUniqueViolation(error)) throw conflict(key, 0, (await find(key, true))?.version ?? 1);
|
|
93
|
+
throw error;
|
|
94
|
+
}
|
|
95
|
+
},
|
|
96
|
+
async remove(key) {
|
|
97
|
+
const row = await find(key, false);
|
|
98
|
+
if (!row) return;
|
|
99
|
+
await removeRow(db, table, row.id, { overwrite: true });
|
|
100
|
+
},
|
|
101
|
+
async list(prefix) {
|
|
102
|
+
const userId = await personId();
|
|
103
|
+
const rows = await listAll(
|
|
104
|
+
db,
|
|
105
|
+
table,
|
|
106
|
+
(q) => q.eq("user_id", userId).eq("feature", feature).like("surface_key", `${likeEscape(prefix)}%`),
|
|
107
|
+
{ columns: ["surface_key"] }
|
|
108
|
+
);
|
|
109
|
+
return rows.map((row) => row.surface_key).filter((key) => key.startsWith(prefix)).sort();
|
|
110
|
+
}
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
export {
|
|
114
|
+
PersistenceVersionConflictError,
|
|
115
|
+
SUMMON_SURFACE_FEATURE,
|
|
116
|
+
createDataPersistence,
|
|
117
|
+
isVersionConflict,
|
|
118
|
+
userSurfaceStateTable
|
|
119
|
+
};
|
|
120
|
+
//# sourceMappingURL=persistence-data.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/persistence/data/createDataPersistence.ts","../src/persistence/errors.ts"],"sourcesContent":["/**\n * createDataPersistence — the OverlayPersistencePort over `@ai-matrx/data`, backed by the\n * canonical per-person working-data table `users.user_surface_state` (design R4):\n *\n * feature = 'overlays', surface_key = <key>, state = <value>, version = optimistic version.\n * Keys: `workspace` (the person's open windows/layout), `state:<overlayId>:<instanceId>`.\n *\n * Every call goes through the data package's doors (listAll / insert / update / remove) — the\n * descriptor's rules apply: the table is an `entity` with `org.rule = \"binding\"`, so an insert\n * takes the organization from `createDb({ organization })` (the host's active organization) and\n * the door REFUSES when there is none; this adapter adds no fallback of its own. Reads are scoped\n * to the signed-in person (`user_id`), never to an organization.\n *\n * The row is unique per (user_id, feature, surface_key) including soft-deleted rows, so `remove`\n * soft-deletes and a later `save` revives the same row instead of inserting a duplicate.\n */\nimport { DatabaseError, insert, listAll, remove as removeRow, update, type Db, type TableDescriptor } from \"@ai-matrx/data/db\";\nimport type { OverlayPersistencePort, StoredValue } from \"@ai-matrx/summon\";\nimport { PersistenceVersionConflictError } from \"../errors\";\n\nexport const SUMMON_SURFACE_FEATURE = \"summon\";\n\ntype Json = string | number | boolean | null | { [key: string]: Json | undefined } | Json[];\n\n/** The columns of users.user_surface_state this adapter reads and writes. */\nexport interface UserSurfaceStateRow {\n id: string;\n user_id: string;\n feature: string;\n surface_key: string;\n state: Json;\n organization_id: string;\n version: number;\n deleted_at: string | null;\n created_at: string;\n updated_at: string;\n created_by: string | null;\n updated_by: string | null;\n metadata: Json;\n custom_fields: Json;\n}\nexport interface UserSurfaceStateInsert {\n user_id: string;\n feature: string;\n surface_key?: string;\n state?: Json;\n organization_id?: string;\n deleted_at?: string | null;\n}\nexport type UserSurfaceStateUpdate = Partial<UserSurfaceStateInsert>;\n\n/**\n * The generated descriptor for users.user_surface_state (`matrx-data generate --schemas users`,\n * contract 1436b3e225ff). A host may pass its own freshly generated one instead.\n */\nexport const userSurfaceStateTable = {\n schema: \"users\",\n name: \"user_surface_state\",\n kind: \"table\",\n type: \"entity\",\n pk: [\"id\"],\n org: { rule: \"binding\" },\n versioned: true,\n softDelete: true,\n archive: null,\n readOnly: false,\n deletesRefused: false,\n readOnlyColumns: [],\n listScope: \"mine\",\n realtime: false,\n createdBy: true,\n} as const satisfies TableDescriptor<UserSurfaceStateRow, UserSurfaceStateInsert, UserSurfaceStateUpdate> as unknown as TableDescriptor<\n UserSurfaceStateRow,\n UserSurfaceStateInsert,\n UserSurfaceStateUpdate\n>;\n\nexport interface DataPersistenceOptions {\n readonly db: Db;\n /** The signed-in person's id. Default: the session on `db.client.auth`. */\n readonly userId?: () => string | null | undefined;\n /** Override the descriptor (a host's own generated `userSurfaceState`). */\n readonly table?: TableDescriptor<UserSurfaceStateRow, UserSurfaceStateInsert, UserSurfaceStateUpdate>;\n /** Default \"overlays\". */\n readonly feature?: string;\n}\n\nexport interface DataOverlayPersistence extends OverlayPersistencePort {\n readonly perPerson: true;\n list(prefix: string): Promise<readonly string[]>;\n}\n\nconst COLUMNS = [\"id\", \"surface_key\", \"state\", \"version\", \"deleted_at\"] as const;\ntype Found = Pick<UserSurfaceStateRow, (typeof COLUMNS)[number]>;\n\nconst likeEscape = (value: string) => value.replace(/[\\\\%_]/g, (ch) => `\\\\${ch}`);\nconst isUniqueViolation = (error: unknown) => error instanceof DatabaseError && error.cause.code === \"23505\";\n\nexport function createDataPersistence(options: DataPersistenceOptions): DataOverlayPersistence {\n const { db } = options;\n const table = options.table ?? userSurfaceStateTable;\n const feature = options.feature ?? SUMMON_SURFACE_FEATURE;\n\n const personId = async (): Promise<string> => {\n const explicit = options.userId?.();\n if (explicit) return explicit;\n const session = db.client.auth ? await db.client.auth.getSession() : null;\n const id = session?.data.session?.user?.id;\n if (!id) throw new Error(\"[overlays/persistence/data] no signed-in person: overlay state is saved per person\");\n return id;\n };\n\n const find = async (key: string, includeDeleted: boolean): Promise<Found | null> => {\n const userId = await personId();\n const rows = await listAll(db, table, (q) => q.eq(\"user_id\", userId).eq(\"feature\", feature).eq(\"surface_key\", key), {\n columns: COLUMNS,\n includeDeleted,\n });\n // Unique per (user_id, feature, surface_key); a live row beats a soft-deleted one.\n return rows.find((row) => row.deleted_at === null) ?? rows[0] ?? null;\n };\n\n const conflict = (key: string, expected: number, current: number) => new PersistenceVersionConflictError(key, expected, current);\n\n return {\n perPerson: true,\n\n async load<T = unknown>(key: string): Promise<StoredValue<T> | null> {\n const row = await find(key, false);\n return row ? { value: row.state as T, version: row.version } : null;\n },\n\n async save<T = unknown>(key: string, value: T, saveOptions?: { readonly expectedVersion?: number }) {\n const expected = saveOptions?.expectedVersion;\n const state = value as unknown as Json;\n const row = await find(key, true);\n if (row && row.deleted_at === null) {\n if (expected === 0) throw conflict(key, 0, row.version);\n const result = await update(db, table, row.id, { state }, expected === undefined ? { overwrite: true } : { expectedVersion: expected });\n if (result.status === \"saved\") return { version: result.row.version };\n if (result.status === \"conflict\") throw conflict(key, expected ?? row.version, result.currentVersion);\n throw conflict(key, expected ?? row.version, 0); // vanished between read and write\n }\n if (expected !== undefined && expected !== 0) throw conflict(key, expected, 0);\n if (row) {\n // Revive the soft-deleted row (the unique key includes deleted rows).\n const result = await update(db, table, row.id, { state, deleted_at: null }, { expectedVersion: row.version });\n if (result.status === \"saved\") return { version: result.row.version };\n throw conflict(key, 0, result.status === \"conflict\" ? result.currentVersion : 0);\n }\n try {\n const created = await insert(db, table, { user_id: await personId(), feature, surface_key: key, state });\n return { version: created.version };\n } catch (error) {\n // Another device created it first.\n if (isUniqueViolation(error)) throw conflict(key, 0, (await find(key, true))?.version ?? 1);\n throw error;\n }\n },\n\n async remove(key: string) {\n const row = await find(key, false);\n if (!row) return;\n await removeRow(db, table, row.id, { overwrite: true });\n },\n\n async list(prefix: string) {\n const userId = await personId();\n const rows = await listAll(\n db,\n table,\n (q) => q.eq(\"user_id\", userId).eq(\"feature\", feature).like(\"surface_key\", `${likeEscape(prefix)}%`),\n { columns: [\"surface_key\"] },\n );\n return rows.map((row) => row.surface_key).filter((key) => key.startsWith(prefix)).sort();\n },\n };\n}\n","/**\n * Errors every persistence store throws in the same shape. Matched by `name`, never `instanceof`:\n * each section entry may carry its own copy of this module in a built consumer.\n */\nimport type { StoredValue } from \"@ai-matrx/summon\";\n\nexport const VERSION_CONFLICT_ERROR = \"OverlayPersistenceVersionConflict\";\nexport const LOAD_TIMEOUT_ERROR = \"OverlayPersistenceLoadTimeout\";\n\n/** A save whose `expectedVersion` no longer matches the stored version. */\nexport class PersistenceVersionConflictError extends Error {\n readonly key: string;\n readonly expectedVersion: number;\n readonly currentVersion: number;\n constructor(key: string, expectedVersion: number, currentVersion: number) {\n super(`[overlays/persistence] \"${key}\" is at version ${currentVersion}, not the expected ${expectedVersion}`);\n this.name = VERSION_CONFLICT_ERROR;\n this.key = key;\n this.expectedVersion = expectedVersion;\n this.currentVersion = currentVersion;\n }\n}\n\nexport function isVersionConflict(error: unknown): error is PersistenceVersionConflictError {\n return error instanceof Error && error.name === VERSION_CONFLICT_ERROR;\n}\n\n/**\n * The fast tier missed and the slow tier did not answer within the read budget. `pending` still\n * resolves the authoritative answer: a caller keeps every automatic writer gated until it does,\n * so an unknown stored value is never overwritten.\n */\nexport class PersistenceLoadTimeoutError extends Error {\n readonly key: string;\n readonly pending: Promise<StoredValue | null>;\n constructor(key: string, budgetMs: number, pending: Promise<StoredValue | null>) {\n super(`[overlays/persistence] \"${key}\" did not load within ${budgetMs}ms`);\n this.name = LOAD_TIMEOUT_ERROR;\n this.key = key;\n this.pending = pending;\n }\n}\n\nexport function isLoadTimeout(error: unknown): error is PersistenceLoadTimeoutError {\n return error instanceof Error && error.name === LOAD_TIMEOUT_ERROR;\n}\n"],"mappings":";AAgBA,SAAS,eAAe,QAAQ,SAAS,UAAU,WAAW,cAA6C;;;ACVpG,IAAM,yBAAyB;AAI/B,IAAM,kCAAN,cAA8C,MAAM;AAAA,EAChD;AAAA,EACA;AAAA,EACA;AAAA,EACT,YAAY,KAAa,iBAAyB,gBAAwB;AACxE,UAAM,2BAA2B,GAAG,mBAAmB,cAAc,sBAAsB,eAAe,EAAE;AAC5G,SAAK,OAAO;AACZ,SAAK,MAAM;AACX,SAAK,kBAAkB;AACvB,SAAK,iBAAiB;AAAA,EACxB;AACF;AAEO,SAAS,kBAAkB,OAA0D;AAC1F,SAAO,iBAAiB,SAAS,MAAM,SAAS;AAClD;;;ADLO,IAAM,yBAAyB;AAmC/B,IAAM,wBAAwB;AAAA,EACnC,QAAQ;AAAA,EACR,MAAM;AAAA,EACN,MAAM;AAAA,EACN,MAAM;AAAA,EACN,IAAI,CAAC,IAAI;AAAA,EACT,KAAK,EAAE,MAAM,UAAU;AAAA,EACvB,WAAW;AAAA,EACX,YAAY;AAAA,EACZ,SAAS;AAAA,EACT,UAAU;AAAA,EACV,gBAAgB;AAAA,EAChB,iBAAiB,CAAC;AAAA,EAClB,WAAW;A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