@marktiderman/genesis-core 1.9.0 → 1.11.0
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 +57 -0
- package/dist/{chunk-EF5BKT4B.js → chunk-ALOP5MZM.js} +10 -5
- package/dist/chunk-ALOP5MZM.js.map +1 -0
- package/dist/index.d.ts +3 -2
- package/dist/index.js +2 -2
- package/dist/provider/index.d.ts +21 -8
- package/dist/provider/index.js +1 -1
- package/dist/read-outcome-BnboMYOV.d.ts +30 -0
- package/dist/schema/index.d.ts +2 -1
- package/dist/testing/index.d.ts +102 -0
- package/dist/testing/index.js +210 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/{read-outcome-B6nACXZ7.d.ts → write-outcome-B2fE29yZ.d.ts} +1 -30
- package/package.json +5 -1
- package/dist/chunk-EF5BKT4B.js.map +0 -1
package/README.md
CHANGED
|
@@ -389,6 +389,61 @@ leave; asks with `window.confirm` otherwise). For other state,
|
|
|
389
389
|
`confirmLeave` and `beforeunload` handling. Neither depends on a router; see
|
|
390
390
|
genesis-ui's SKILL.md "Unsaved changes" for React Router and TanStack Router.
|
|
391
391
|
|
|
392
|
+
## Test your data contract
|
|
393
|
+
|
|
394
|
+
`@marktiderman/genesis-core/testing` checks your own provider keeps the data rules, against your
|
|
395
|
+
real schema (a local Supabase in CI). Its pgTAP twin is genesis-supabase's `genesis_testing`; both
|
|
396
|
+
use the same fixture people (`FIXTURE_USERS`: owner, staff, client, stranger), so seed them once
|
|
397
|
+
with `select genesis_testing.create_users();`.
|
|
398
|
+
|
|
399
|
+
Each check passes only on evidence and throws a `ContractError` otherwise, so it works in vitest,
|
|
400
|
+
jest or node:test. A wrong resource, a missing row or a typo fails instead of passing. The control and system
|
|
401
|
+
writes are real (and `expectServerOwned` puts its value back): run the checks on test data.
|
|
402
|
+
|
|
403
|
+
A refusal must read as plain words, so a provider that passes the database's raw text through (an
|
|
404
|
+
RLS insert refusal says `new row violates row-level security policy …`) fails `expectRefused`. Map
|
|
405
|
+
it to a plain message in the provider; that failure is the kit doing its job.
|
|
406
|
+
|
|
407
|
+
```ts
|
|
408
|
+
import { createClient } from "@supabase/supabase-js";
|
|
409
|
+
import { createSupabaseProvider } from "@marktiderman/genesis-core/provider";
|
|
410
|
+
import {
|
|
411
|
+
expectBinned, expectNeverShows, expectRefused, expectServerOwned, fixtureAccessToken,
|
|
412
|
+
} from "@marktiderman/genesis-core/testing";
|
|
413
|
+
|
|
414
|
+
// The local stack's legacy JWT secret (`supabase status`); never a production one.
|
|
415
|
+
const providerFor = async (who: "owner" | "client" | "stranger") => {
|
|
416
|
+
const token = await fixtureAccessToken(who, { secret: process.env.SUPABASE_JWT_SECRET! });
|
|
417
|
+
const client = createClient(url, anonKey, { global: { headers: { Authorization: `Bearer ${token}` } } });
|
|
418
|
+
return createSupabaseProvider(client, { binTables: ["notes"] });
|
|
419
|
+
};
|
|
420
|
+
|
|
421
|
+
const client = await providerFor("client");
|
|
422
|
+
const owner = await providerFor("owner");
|
|
423
|
+
const stranger = await providerFor("stranger");
|
|
424
|
+
const system = createSupabaseProvider(createClient(url, serviceRoleKey)); // the server's own writes
|
|
425
|
+
|
|
426
|
+
// A write the client may not make is refused, in plain words. When RLS hides the row (it reaches
|
|
427
|
+
// no row), the control runs the same write as someone who may make it and must change a row.
|
|
428
|
+
await expectRefused((p) => p.update("tasks", { id, data: { title: "x" } }), { as: stranger, control: owner });
|
|
429
|
+
// A column only the server sets stays as it was (the system proves it can change it first).
|
|
430
|
+
await expectServerOwned({ as: client, system, resource: "tasks", id, field: "status", value: "done" });
|
|
431
|
+
// A private value never shows, reports included: read the list around it, not the row by id.
|
|
432
|
+
await expectNeverShows(client.getList("group_progress", {}), "private-marker-7");
|
|
433
|
+
// A delete on a bin table keeps the row.
|
|
434
|
+
await expectBinned({ as: client, resource: "notes", id, inBin: () => adminSeesDeleted("notes", id) });
|
|
435
|
+
```
|
|
436
|
+
|
|
437
|
+
| Check | Passes when |
|
|
438
|
+
| --- | --- |
|
|
439
|
+
| `expectRefused(write, { as?, control? })` | it's refused (42501, a guard's P0001, or `forbidden` / `unauthenticated`) in plain words; reaching no row counts only when `control` makes the same write and changes a row |
|
|
440
|
+
| `expectAllowed(write)` | it resolves |
|
|
441
|
+
| `expectServerOwned({ as, system, … })` | `system` can change the value (then puts it back), and it's unchanged after `as` tries; refused or put back both count |
|
|
442
|
+
| `expectNeverShows(read, marker)` | the marker appears nowhere in the result (raw or JSON-escaped), or the read is refused; a read that found nothing fails |
|
|
443
|
+
| `expectSees(read, n)` | the read returns exactly `n` rows |
|
|
444
|
+
| `expectBinned({ as, resource, id, inBin })` | `as` sees the row, deletes it, can't read it back, and `inBin()` confirms it's still stored |
|
|
445
|
+
| `expectPlainMessage(error)` | the message has no raw database text or error codes |
|
|
446
|
+
|
|
392
447
|
## Autosave a draft
|
|
393
448
|
|
|
394
449
|
`useDraft` saves one row as someone edits it: an answer to a questionnaire, a
|
|
@@ -498,7 +553,9 @@ await callRpc(supabase, "release_step", { item_id }, { messages: { "55000": "Thi
|
|
|
498
553
|
const { row, adopted } = await createOrAdopt(provider, "lesson_notes", { person_id, lesson_id, body }, {
|
|
499
554
|
key: ["person_id", "lesson_id"],
|
|
500
555
|
merge: (existing) => (existing.body ? null : { body }),
|
|
556
|
+
final: (existing) => existing.status === "submitted", // finished: handed back with final: true, never written over
|
|
501
557
|
});
|
|
558
|
+
// Key fields that are null match rows where they're null.
|
|
502
559
|
|
|
503
560
|
// In a component: pending, plain error words, and invalidation after a success.
|
|
504
561
|
const release = useWrite((itemId: string) => callRpc(supabase, "release_step", { item_id: itemId }), {
|
|
@@ -721,7 +721,7 @@ async function callRpc(client, fn, args = {}, options = {}) {
|
|
|
721
721
|
async function createOrAdopt(provider, resource, data, options) {
|
|
722
722
|
if (options.key.length === 0) throw new Error(`[genesis-core] createOrAdopt("${resource}") needs a key`);
|
|
723
723
|
try {
|
|
724
|
-
return { row: (await provider.create(resource, { data })).data, adopted: false };
|
|
724
|
+
return { row: (await provider.create(resource, { data })).data, adopted: false, final: false };
|
|
725
725
|
} catch (error) {
|
|
726
726
|
if (!isDataWriteError(error) || error.outcome !== "duplicate") throw error;
|
|
727
727
|
if (error.fields && Object.keys(error.fields).some((field) => !options.key.includes(field))) throw error;
|
|
@@ -736,12 +736,17 @@ async function createOrAdopt(provider, resource, data, options) {
|
|
|
736
736
|
const { data: rows } = await provider.getList(resource, { filters, pagination: { page: 1, perPage: 2 } });
|
|
737
737
|
if (rows.length !== 1) throw error;
|
|
738
738
|
const existing = rows[0];
|
|
739
|
+
if (options.final?.(existing)) return { row: existing, adopted: true, final: true };
|
|
739
740
|
const changes = options.merge?.(existing);
|
|
740
|
-
if (!changes || Object.keys(changes).length === 0) return { row: existing, adopted: true };
|
|
741
|
-
return {
|
|
741
|
+
if (!changes || Object.keys(changes).length === 0) return { row: existing, adopted: true, final: false };
|
|
742
|
+
return {
|
|
743
|
+
row: (await provider.update(resource, { id: existing.id, data: changes })).data,
|
|
744
|
+
adopted: true,
|
|
745
|
+
final: false
|
|
746
|
+
};
|
|
742
747
|
}
|
|
743
748
|
}
|
|
744
749
|
|
|
745
750
|
export { DEFAULT_RPC_MESSAGES, RPC_FAILED, callRpc, createOrAdopt, createSupabaseProvider, fieldErrorsFromPostgrest, readOutcomeFromCode, toDataWriteError, writeOutcomeFromCode };
|
|
746
|
-
//# sourceMappingURL=chunk-
|
|
747
|
-
//# sourceMappingURL=chunk-
|
|
751
|
+
//# sourceMappingURL=chunk-ALOP5MZM.js.map
|
|
752
|
+
//# sourceMappingURL=chunk-ALOP5MZM.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/provider/postgrest-errors.ts","../src/provider/supabase-provider.ts","../src/provider/write-helpers.ts"],"names":["ties","run","from"],"mappings":";;;;;AAiBO,SAAS,oBAAoB,IAAA,EAA8C;AAChF,EAAA,IAAI,CAAC,MAAM,OAAO,OAAA;AAClB,EAAA,IAAI,IAAA,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,CAAA;AACvB,IAAA,IAAI,OAAA,CAAQ,KAAA,GAAQ,QAAQ,CAAA,EAAG,OAAO,EAAE,GAAA,EAAK,QAAA,EAAU,OAAA,EAAS,IAAA,EAAM,KAAA,EAAO,IAAA,EAAK;AAClF,IAAA,MAAM,OAAA,GAAU,OAAA,CAAQ,KAAA,GAAQ,QAAQ,CAAA;AACxC,IAAA,IAAI,CAAC,OAAA,IAAW,MAAA,CAAO,IAAA,CAAK,OAAO,CAAA,CAAE,MAAA,KAAW,CAAA,EAAG,OAAO,EAAE,GAAA,EAAK,QAAA,EAAU,OAAA,EAAS,IAAA,EAAM,OAAO,KAAA,EAAM;AACvG,IAAA,OAAO;AAAA,MACL,GAAA,EAAA,CAAM,MAAM,QAAA,CAAS,MAAA,CAAU,QAAA,EAAU,EAAE,EAAA,EAAI,QAAA,CAAS,EAAA,EAAI,IAAA,EAAM,OAAA,EAAS,CAAA,EAAG,IAAA;AAAA,MAC9E,OAAA,EAAS,IAAA;AAAA,MACT,KAAA,EAAO;AAAA,KACT;AAAA,EACF;AACF","file":"chunk-ALOP5MZM.js","sourcesContent":["// ---------------------------------------------------------------------------\n// Postgres / PostgREST error codes → Genesis write outcomes\n// ---------------------------------------------------------------------------\n\nimport {\n DataWriteError,\n isDataWriteError,\n type WriteOutcome,\n} from \"../schema/write-outcome\";\nimport type { ReadOutcome } from \"../schema/read-outcome\";\nimport { titleCase } from \"../utils\";\n\n/**\n * Maps a store error code to the read outcome it means: the write mapping,\n * with `22***` and PostgREST request errors (`PGRST1**` other than PGRST116,\n * `42703` unknown column, `42P01` unknown table) read as `invalid`.\n */\nexport function readOutcomeFromCode(code: string | null | undefined): ReadOutcome {\n if (!code) return \"error\";\n if (code === \"42703\" || code === \"42P01\" || (/^PGRST1\\d\\d$/.test(code) && code !== \"PGRST116\")) {\n return \"invalid\";\n }\n const write = writeOutcomeFromCode(code);\n return write === \"forbidden\" || write === \"gone\" || write === \"unauthenticated\" || write === \"invalid\"\n ? write\n : \"error\";\n}\n\n/**\n * Maps a Postgres SQLSTATE or PostgREST error code to the write outcome it\n * means. Anything not listed is `error`: a code is only read as a refusal or\n * a bad value when it says so.\n *\n * - `42501` (insufficient privilege, including \"new row violates row-level\n * security policy\") → `forbidden`\n * - `23505` (unique violation) → `duplicate`\n * - `22***` (data exception: bad type, out of range) and the other `23***`\n * (integrity constraint: `23503` foreign key, `23502` not null, `23514`\n * check) → `invalid`\n * - `PGRST301`–`PGRST303` (JWT missing, expired or rejected), `28000`,\n * `28P01` → `unauthenticated`\n * - `PGRST116` (one row was asked for and none came back) → `gone`\n */\nexport function writeOutcomeFromCode(code: string | null | undefined): WriteOutcome {\n if (!code) return \"error\";\n if (code === \"42501\") return \"forbidden\";\n if (code === \"PGRST116\") return \"gone\";\n if (code === \"PGRST301\" || code === \"PGRST302\" || code === \"PGRST303\") return \"unauthenticated\";\n if (code === \"28000\" || code === \"28P01\") return \"unauthenticated\";\n if (code === \"23505\") return \"duplicate\";\n if (/^2[23][0-9A-Z]{3}$/.test(code)) return \"invalid\";\n return \"error\";\n}\n\n/** A column name as Postgres reports it unquoted; anything else is not mapped. */\nconst COLUMN = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/**\n * One index expression as Postgres prints it: a plain column, or one column\n * wrapped in a function, optionally cast (`lower(email::text)`,\n * `lower((email)::text)`). Anything else is not mapped.\n */\nconst WRAPPED_COLUMN = /^[A-Za-z_][A-Za-z0-9_]*\\(\\(?([A-Za-z_][A-Za-z0-9_]*)\\)?(?:::[A-Za-z_][A-Za-z0-9_ ]*)?\\)$/;\n\nfunction columnOf(expression: string): string | undefined {\n if (COLUMN.test(expression)) return expression;\n return WRAPPED_COLUMN.exec(expression)?.[1];\n}\n\n/**\n * The columns of a `Key (a, b)=(...)` detail line, or none when any is not a\n * plain column (or one column in a simple expression index). The key list is\n * read with its parentheses balanced, so an expression index such as\n * `Key (lower(email::text))=(…)` is recognised.\n */\nfunction keyColumns(details: string, tail: RegExp): string[] {\n if (!details.startsWith(\"Key (\") || !tail.test(details)) return [];\n let depth = 1;\n let end = -1;\n for (let i = \"Key (\".length; i < details.length; i++) {\n const ch = details[i];\n if (ch === \"(\") depth++;\n else if (ch === \")\" && --depth === 0) {\n end = i;\n break;\n }\n }\n if (end < 0 || details.slice(end + 1, end + 3) !== \"=(\") return [];\n const parts: string[] = [];\n let level = 0;\n let current = \"\";\n for (const ch of details.slice(\"Key (\".length, end)) {\n if (ch === \"(\") level++;\n else if (ch === \")\") level--;\n if (ch === \",\" && level === 0) {\n parts.push(current.trim());\n current = \"\";\n } else {\n current += ch;\n }\n }\n parts.push(current.trim());\n const columns = parts.map(columnOf);\n return columns.length > 0 && columns.every((c): c is string => !!c) ? columns : [];\n}\n\nfunction listLabels(columns: string[]): string {\n const labels = columns.map((c) => titleCase(c));\n if (labels.length === 1) return labels[0]!;\n return `${labels.slice(0, -1).join(\", \")} and ${labels[labels.length - 1]}`;\n}\n\n/** Field errors read from a store error, with the safe sentence that sums them up. */\nexport interface PostgrestFieldErrors {\n /** Column name → safe message for that input. */\n fields: Record<string, string>;\n /** One safe sentence for the whole error, to replace the store's raw text. */\n message: string;\n}\n\n/**\n * Reads which columns a Postgres constraint error is about, from PostgREST's\n * `message` / `details`, and gives safe messages for them. Only plain column\n * names are taken from the store's text; the values it echoes are never\n * used. A unique violation whose columns cannot be read (a complex\n * expression index, no details), or an insert/update foreign-key violation\n * whose key is an expression, gets the safe sentence with no `fields`, so the\n * store's raw text (constraint name, echoed value) never reaches the user.\n * Returns `undefined` for anything else.\n *\n * - `23505` unique violation, `Key (email)=(…) already exists.` → each\n * column: \"This value is already in use.\" (several columns: \"This\n * combination is already in use.\")\n * - `23502` not-null, `null value in column \"title\" …` → \"This field is\n * required.\"\n * - `23503` foreign key on insert/update, `Key (owner_id)=(…) is not present\n * in table …` → \"The selected item doesn't exist.\"\n */\nexport function fieldErrorsFromPostgrest(error: {\n code?: unknown;\n message?: unknown;\n details?: unknown;\n}): PostgrestFieldErrors | undefined {\n const code = typeof error.code === \"string\" ? error.code : undefined;\n const details = typeof error.details === \"string\" ? error.details.trim() : \"\";\n const message = typeof error.message === \"string\" ? error.message : \"\";\n if (code === \"23505\") {\n const columns = keyColumns(details, /\\) already exists\\.?$/);\n // Not mappable to a column: still never show the store's raw text (it\n // names the constraint and echoes the value).\n if (columns.length === 0) return { fields: {}, message: \"This value is already in use.\" };\n const each = columns.length === 1 ? \"This value is already in use.\" : \"This combination is already in use.\";\n return {\n fields: Object.fromEntries(columns.map((c) => [c, each])),\n message:\n columns.length === 1\n ? `${listLabels(columns)} is already in use.`\n : `This combination of ${listLabels(columns)} is already in use.`,\n };\n }\n if (code === \"23502\") {\n const column = /^null value in column \"([A-Za-z_][A-Za-z0-9_]*)\"(?: |$)/.exec(message)?.[1];\n if (!column || !COLUMN.test(column)) return undefined;\n return {\n fields: { [column]: \"This field is required.\" },\n message: `${titleCase(column)} is required.`,\n };\n }\n if (code === \"23503\") {\n const tail = /\\) is not present in table \"[^\"]*\"\\.?$/;\n if (!tail.test(details)) return undefined;\n const columns = keyColumns(details, tail);\n if (columns.length === 0) return { fields: {}, message: \"The selected item doesn't exist.\" };\n return {\n fields: Object.fromEntries(columns.map((c) => [c, \"The selected item doesn't exist.\"])),\n message: `${listLabels(columns)}: the selected item doesn't exist.`,\n };\n }\n return undefined;\n}\n\n/**\n * Turns anything a write threw, or the `{ message, code }` error a Supabase\n * client returned, into a `DataWriteError`. A `DataWriteError` passes through\n * unchanged; anything else keeps its message and `code`, and is kept as the\n * `cause`.\n *\n * When the error names the columns it is about (`fieldErrorsFromPostgrest`:\n * unique, not-null and foreign-key violations), the result carries `fields`\n * and its message is replaced with a safe sentence; the raw text stays on\n * the `cause`.\n */\nexport function toDataWriteError(error: unknown): DataWriteError {\n if (isDataWriteError(error)) return error;\n const shape = (typeof error === \"object\" && error !== null ? error : {}) as {\n message?: unknown;\n code?: unknown;\n details?: unknown;\n };\n const code = typeof shape.code === \"string\" ? shape.code : undefined;\n const mapped = fieldErrorsFromPostgrest(shape);\n if (mapped) {\n return new DataWriteError(writeOutcomeFromCode(code), mapped.message, {\n code,\n fields: Object.keys(mapped.fields).length > 0 ? mapped.fields : undefined,\n cause: error,\n });\n }\n const message =\n typeof shape.message === \"string\" && shape.message\n ? shape.message\n : error instanceof Error\n ? error.message\n : String(error);\n return new DataWriteError(writeOutcomeFromCode(code), message, { code, cause: error });\n}\n","import type {\n BaseRecord,\n DataProvider,\n FilterParam,\n Identifier,\n InvalidationKey,\n ListParams,\n ResourceChangeEvent,\n WriteEvent,\n} from \"./types\";\nimport { DataWriteError } from \"../schema/write-outcome\";\nimport { DataReadError, readFailureMessage } from \"../schema/read-outcome\";\nimport type { FilterOperator, ProviderCapabilities } from \"../schema/types\";\nimport { readOutcomeFromCode, toDataWriteError } from \"./postgrest-errors\";\n\n// ---------------------------------------------------------------------------\n// Minimal Supabase client shape — no hard dependency on @supabase/supabase-js\n// ---------------------------------------------------------------------------\n\n/** A chainable query builder returned by `client.from(table)`. */\ninterface SupabaseQueryBuilder {\n select(\n columns?: string,\n options?: { count?: \"exact\" | \"planned\" | \"estimated\" },\n ): SupabaseQueryBuilder;\n insert(data: Record<string, unknown> | Record<string, unknown>[]): SupabaseQueryBuilder;\n update(data: Record<string, unknown>): SupabaseQueryBuilder;\n delete(): SupabaseQueryBuilder;\n eq(column: string, value: unknown): SupabaseQueryBuilder;\n neq(column: string, value: unknown): SupabaseQueryBuilder;\n gt(column: string, value: unknown): SupabaseQueryBuilder;\n lt(column: string, value: unknown): SupabaseQueryBuilder;\n gte(column: string, value: unknown): SupabaseQueryBuilder;\n lte(column: string, value: unknown): SupabaseQueryBuilder;\n ilike(column: string, value: string): SupabaseQueryBuilder;\n in(column: string, values: unknown[]): SupabaseQueryBuilder;\n is(column: string, value: null): SupabaseQueryBuilder;\n not(column: string, operator: string, value: unknown): SupabaseQueryBuilder;\n or(filters: string): SupabaseQueryBuilder;\n order(column: string, options?: { ascending?: boolean; nullsFirst?: boolean }): SupabaseQueryBuilder;\n range(from: number, to: number): SupabaseQueryBuilder;\n single(): SupabaseQueryBuilder;\n then: Promise<{ data: unknown; error: unknown; count?: number | null }>[\"then\"];\n}\n\n/**\n * Minimal Supabase client interface — the public shape this package has\n * always exposed for a caller that wants to type its own client or a\n * wrapper around one. Unchanged: `from()` still returns `SupabaseQueryBuilder`\n * so existing consumers that annotate a variable with this type and chain\n * off it keep type-checking exactly as before.\n */\nexport interface SupabaseClient {\n from(table: string): SupabaseQueryBuilder;\n /** Supabase Realtime; needed only for `subscribe` (see `SupabaseProviderOptions.realtime`). */\n channel?(name: string): SupabaseRealtimeChannel;\n /** Releases a channel made by `channel()`. */\n removeChannel?(channel: SupabaseRealtimeChannel): unknown;\n}\n\n/**\n * One `postgres_changes` message, as Supabase Realtime sends it. Only the\n * fields the provider reads; a real payload has more.\n */\nexport interface SupabaseRealtimePayload {\n eventType: \"INSERT\" | \"UPDATE\" | \"DELETE\";\n /** The row after an insert or update (empty for a delete). */\n new?: Record<string, unknown>;\n /** For a delete or update: the old row's key (all of it with `REPLICA IDENTITY FULL`). */\n old?: Record<string, unknown>;\n}\n\n/**\n * The part of a Supabase `RealtimeChannel` the provider uses. A real\n * `@supabase/supabase-js` channel satisfies it.\n */\nexport interface SupabaseRealtimeChannel {\n on(\n type: \"postgres_changes\",\n filter: {\n event: \"*\" | \"INSERT\" | \"UPDATE\" | \"DELETE\";\n schema: string;\n table: string;\n filter?: string;\n },\n callback: (payload: SupabaseRealtimePayload) => void,\n ): SupabaseRealtimeChannel;\n subscribe(callback?: (status: string, error?: unknown) => void): SupabaseRealtimeChannel;\n unsubscribe?(): unknown;\n}\n\n/**\n * What `createSupabaseProvider` actually requires from its `client` argument\n * — deliberately looser than the public `SupabaseClient` above, and used\n * ONLY for that one parameter. A real `@supabase/supabase-js` client's\n * `from()` returns a generic, table-typed `PostgrestQueryBuilder` whose chain\n * methods don't structurally match `SupabaseQueryBuilder`, which used to\n * force callers to pass their client through `as never`. Since `unknown` is\n * a supertype of everything, any real client's `from(table: string)`\n * satisfies THIS shape without a cast; `createSupabaseProvider` narrows to\n * `SupabaseQueryBuilder` internally, once, right after each `from()` call.\n * Loosening only the input here — rather than `SupabaseClient` itself —\n * means a caller relying on `SupabaseClient`'s stricter return type for\n * their own chaining is unaffected.\n */\nexport interface SupabaseClientInput {\n from(table: string): unknown;\n /** Database functions, for a resource whose `source` is an `rpc`. Any real client's `rpc` fits. */\n rpc?(fn: string, args?: Record<string, unknown>, options?: { count?: \"exact\" | \"planned\" | \"estimated\" }): unknown;\n /** Supabase Realtime, for `subscribe`. Any real client's `channel` fits. */\n channel?(name: string): unknown;\n removeChannel?(channel: unknown): unknown;\n}\n\n// ---------------------------------------------------------------------------\n// Provider factory\n// ---------------------------------------------------------------------------\n\n/** What a write hook is told about the write it is part of. */\nexport interface SupabaseWriteContext {\n resource: string;\n action: \"create\" | \"update\";\n /** The row's id, for an update. */\n id?: Identifier;\n}\n\n/** Per-resource rules for `createSupabaseProvider`. Every field is optional. */\nexport interface SupabaseResourceConfig {\n /** Singular noun for failure messages, e.g. \"project\". Defaults to \"record\". */\n noun?: string;\n /** Plural for list messages, when it isn't `noun` + \"s\" (\"categories\"). */\n nounPlural?: string;\n /**\n * The columns a search covers. `[]` means the resource can't be searched,\n * and `capabilities(resource).search` reports false so a UI hides the box.\n * Set, they replace the caller's `search.fields`; omitted, those are used\n * as given.\n */\n searchFields?: readonly string[];\n /**\n * The column a sorted list orders by last, so rows with equal sort values\n * keep one order from page to page (none repeats, none is skipped).\n * Default `\"id\"`; `false` for a table or view without one. With the\n * default, a view that turns out to have no `id` column is read as before\n * (without the key order) and a development warning suggests setting this.\n */\n orderKey?: string | false;\n /**\n * `\"bin\"` for a table whose delete trigger moves the row to a recycle bin\n * instead of removing it (see `SupabaseProviderOptions.binTables`).\n * `\"hard\"` forces a plain delete even when `binTables` lists the table.\n */\n deleteMode?: \"hard\" | \"bin\";\n /**\n * Turns submitted values into the row to write: trim, drop read-only keys,\n * validate. Runs before every create and update, including the `create`\n * and `update` overrides. Throw (ideally `DataWriteError(\"invalid\", ...)`)\n * to refuse the write; nothing is sent.\n */\n prepare?: (\n values: Record<string, unknown>,\n context: SupabaseWriteContext,\n ) => Record<string, unknown> | Promise<Record<string, unknown>>;\n /**\n * Creates the row some other way than an insert, e.g. a security-definer\n * RPC. Return the new row, or its id and the provider reads the row back\n * (if the read-back fails, the create is still reported as saved, with\n * just the id, so the user does not retry and make a second one). Throw to\n * fail; a Supabase `{ message, code }` error is mapped like any other.\n */\n create?: (row: Record<string, unknown>) => Promise<BaseRecord | Identifier>;\n /**\n * Updates the row some other way than an update, e.g. an RPC. Return the\n * updated row, or its id (or `true`) and the provider reads it back.\n * Returning nothing (`undefined`/`null`/`false`) means no row changed: the provider then reads the\n * row to say why (`forbidden` or `gone`), exactly as for a plain update,\n * so a function that silently skips a row never reports a save.\n */\n update?: (\n id: Identifier,\n row: Record<string, unknown>,\n ) => Promise<BaseRecord | Identifier | boolean | null | undefined | void>;\n /** Maps a stored row to edit-form values; see `DataProvider.toFormValues`. */\n toFormValues?: (record: Record<string, unknown>) => Record<string, unknown>;\n /**\n * Other cache keys a committed write to this resource makes stale, e.g.\n * `[[\"staff\"], [\"me\"]]`. Served through `DataProvider.invalidates`, which\n * `useResource` and `useResourceForm` invalidate after their writes.\n */\n invalidates?: InvalidationKey[] | ((event: WriteEvent) => InvalidationKey[]);\n /**\n * Serve `subscribe` for this resource through Supabase Realtime\n * (`postgres_changes`), so `live` lists and records refresh when the table\n * changes. The table must be in the `supabase_realtime` publication, with\n * RLS on. `false` turns it off even when `SupabaseProviderOptions.realtime`\n * covers the resource.\n */\n realtime?: boolean;\n /**\n * Read this resource from somewhere else than its table: a view (joins,\n * counts, aggregations) or a database function that returns rows. Writes\n * still go to the table. Lists keep paging, filters, search, sort, totals\n * and cursors, because PostgREST filters a view or a set-returning function\n * like a table. Realtime still watches the table.\n *\n * Row-level security: a plain view runs as its owner and a SECURITY DEFINER\n * function as its definer, so either one reads past RLS. Create the view\n * `with (security_invoker = true)` and the function `security invoker` (or\n * have it filter by `auth.uid()` itself), or this exposes every row.\n *\n * ```ts\n * resources: {\n * tasks: { source: \"tasks_with_people\" },\n * course_progress: { source: { rpc: \"group_progress\", args: () => ({ group_id: currentGroup() }) } },\n * }\n * ```\n */\n source?: string | { rpc: string; args?: () => Record<string, unknown> };\n /** The columns read when the caller names none, e.g. embedded joins: `\"*, person:people(full_name)\"`. Default `\"*\"`. */\n select?: string;\n /**\n * With a `source` (or a `select` that embeds other tables), the table's own\n * columns: creates and updates write only these, so a form built from the\n * richer read row never sends its joined or computed columns to the table.\n * Without it, an update writes only the columns the table's row has.\n */\n writeColumns?: readonly string[];\n}\n\n/** Options for `createSupabaseProvider`. All optional; none changes reads. */\nexport interface SupabaseProviderOptions {\n /**\n * Recycle-bin tables: their delete trigger turns a delete into a \"binned\"\n * mark and the binned row drops out of the caller's view (RLS or a view\n * filter). The database reports such a delete as zero rows, so for these\n * the provider checks the row is visible, deletes it, and reads it back:\n * gone from view is success, still visible is `forbidden`. A row that was\n * not visible beforehand is `gone`.\n */\n binTables?: readonly string[] | ((resource: string) => boolean);\n /** Per-resource rules, keyed by resource (table) name. */\n resources?: Record<string, SupabaseResourceConfig>;\n /**\n * Called after every committed create, update and delete, e.g. to\n * invalidate caches the Genesis hooks don't know about. Awaited, but a\n * failure is logged and never turns a committed write into a failed one.\n */\n onWrite?: (event: WriteEvent) => void | Promise<void>;\n /**\n * The most rows one list page may ask for (PostgREST's `max-rows` caps\n * reads anyway; default 1000). A larger request is refused with an\n * `invalid` `DataReadError` (its `cause` says why) rather than cut short,\n * so page boundaries never disagree with the caller's `perPage`.\n * `capabilities().maxPerPage` reports it.\n */\n maxPerPage?: number;\n /**\n * Called with every failed read, before it is thrown. The thrown\n * `DataReadError` carries a plain message for users; the store's own\n * error (its raw text and code) is its `cause`, for logging here.\n */\n onReadError?: (\n error: DataReadError,\n context: { resource: string; operation: \"getList\" | \"getOne\" | \"getMany\" },\n ) => void | Promise<void>;\n /**\n * Which resources `subscribe` serves through Supabase Realtime: `true` for\n * all, a list of names, or a test. Off by default; a resource's own\n * `resources[name].realtime` wins. Needs a client with `channel()` (any\n * `@supabase/supabase-js` client).\n */\n realtime?: boolean | readonly string[] | ((resource: string) => boolean);\n}\n\n/** A PostgREST \"undefined column\" error (42703) naming `column`. */\n/**\n * A PostgreSQL \"undefined column\" error (42703) for `table`'s own `column`:\n * `column \"id\" does not exist` or `column <table>.id does not exist`. Not a\n * related table's column (`author.id`) or any other message mentioning it.\n */\nfunction isMissingColumn(error: unknown, table: string, column: string): boolean {\n if (!error || typeof error !== \"object\") return false;\n const { code, message } = error as { code?: unknown; message?: unknown };\n if (code !== \"42703\" || typeof message !== \"string\") return false;\n const match = /^column (?:\"?([^.\"\\s]+)\"?\\.)?\"?([^.\"\\s]+)\"? does not exist$/.exec(message.trim());\n if (!match || match[2] !== column) return false;\n const ownTable = table.split(\".\").pop()?.replace(/\"/g, \"\");\n return match[1] === undefined || match[1] === ownTable;\n}\n\nconst SERVED_OPERATORS: readonly FilterOperator[] = [\n \"eq\", \"neq\", \"gt\", \"lt\", \"gte\", \"lte\", \"contains\", \"in\", \"between\", \"is_null\", \"is_not_null\",\n];\n\nfunction escapeIlike(value: string): string {\n return value.replace(/[%_\\\\]/g, (char) => `\\\\${char}`);\n}\n\nfunction isIdentifier(value: unknown): value is Identifier {\n return typeof value === \"string\" || typeof value === \"number\";\n}\n\n// ---------------------------------------------------------------------------\n// Cursor (keyset) paging\n// ---------------------------------------------------------------------------\n\n/** What a cursor holds: the sort it was made for, and the last row's values. */\ninterface CursorState {\n /** Sort field, or null when ordered by the key alone. */\n s: string | null;\n o: \"asc\" | \"desc\";\n /** The key column. */\n k: string;\n /** The last row's sort value (absent when `s` is null). */\n v?: string | number | boolean | null;\n /** The last row's key value. */\n id: string | number;\n}\n\nconst PLAIN_COLUMN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;\n\nfunction encodeCursor(state: CursorState): string {\n const bytes = new TextEncoder().encode(JSON.stringify(state));\n let binary = \"\";\n for (const b of bytes) binary += String.fromCharCode(b);\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nfunction decodeCursor(cursor: string): CursorState | undefined {\n try {\n const binary = atob(cursor.replace(/-/g, \"+\").replace(/_/g, \"/\"));\n const bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0));\n const state = JSON.parse(new TextDecoder().decode(bytes)) as CursorState;\n if (!state || typeof state !== \"object\" || typeof state.k !== \"string\" || !isIdentifier(state.id)) return undefined;\n if (state.o !== \"asc\" && state.o !== \"desc\") return undefined;\n return state;\n } catch {\n return undefined;\n }\n}\n\n/** A value quoted for a PostgREST filter, so commas, dots and parens are literal. */\nfunction quoteFilterValue(value: string | number | boolean): string {\n return `\"${String(value).replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"')}\"`;\n}\n\n/**\n * The PostgREST `or` clauses selecting the rows after `state`, for a list\n * ordered by `s` (`o`, nulls last when ascending and first when descending,\n * as Postgres orders them by default) and then by the key ascending.\n * @internal Exported for tests.\n */\nexport function keysetClauses(state: CursorState): string {\n const k = state.k;\n const K = quoteFilterValue(state.id);\n if (state.s === null) return `${k}.${state.o === \"asc\" ? \"gt\" : \"lt\"}.${K}`;\n const s = state.s;\n const v = state.v;\n const afterInTies = (eq: string) => `and(${eq},${k}.gt.${K})`;\n if (v === null || v === undefined) {\n // Asc: nulls are last, so only later nulls remain. Desc: nulls are\n // first, so later nulls and then every non-null row remain.\n const ties = afterInTies(`${s}.is.null`);\n return state.o === \"asc\" ? ties : `${s}.not.is.null,${ties}`;\n }\n const V = quoteFilterValue(v);\n const ties = afterInTies(`${s}.eq.${V}`);\n return state.o === \"asc\" ? `${s}.gt.${V},${ties},${s}.is.null` : `${s}.lt.${V},${ties}`;\n}\n/** `\"schema.table\"` or `\"table\"` (schema `public`), as Realtime names them. */\nfunction realtimeTable(resource: string): { schema: string; table: string } {\n const dot = resource.indexOf(\".\");\n const strip = (name: string) => name.replace(/\"/g, \"\");\n return dot < 0\n ? { schema: \"public\", table: strip(resource) }\n : { schema: strip(resource.slice(0, dot)), table: strip(resource.slice(dot + 1)) };\n}\n\nlet realtimeChannelSeq = 0;\nconst warnedRealtime = new Set<string>();\n\n/**\n * The Supabase data provider. Reads and writes go through the client you\n * pass, under that client's session and RLS.\n *\n * Writes never report a save that did not happen:\n * - `update` and `deleteOne` ask for the affected rows. Zero rows is a\n * `DataWriteError`: the row is read back, and still visible means\n * `forbidden` (RLS or a trigger refused the change), no longer visible\n * means `gone`.\n * - Database errors on writes are thrown as `DataWriteError` with the\n * outcome their code means (`writeOutcomeFromCode`) and the code kept on\n * `error.code`.\n * - Recycle-bin tables (`binTables`) succeed when the row leaves the\n * caller's view.\n *\n * Reads are unchanged: errors are thrown as an `Error` carrying `code`.\n */\nexport function createSupabaseProvider(\n client: SupabaseClientInput,\n options: SupabaseProviderOptions = {},\n): DataProvider {\n // ---------------------------------------------------------------------------\n // Helpers\n // ---------------------------------------------------------------------------\n\n function applyFilters(\n query: SupabaseQueryBuilder,\n filters: FilterParam[] | undefined,\n ): SupabaseQueryBuilder {\n if (!filters) return query;\n for (const f of filters) {\n switch (f.operator) {\n case \"eq\":\n query = query.eq(f.field, f.value);\n break;\n case \"neq\":\n query = query.neq(f.field, f.value);\n break;\n case \"gt\":\n query = query.gt(f.field, f.value);\n break;\n case \"lt\":\n query = query.lt(f.field, f.value);\n break;\n case \"gte\":\n query = query.gte(f.field, f.value);\n break;\n case \"lte\":\n query = query.lte(f.field, f.value);\n break;\n case \"contains\":\n query = query.ilike(f.field, `%${escapeIlike(String(f.value))}%`);\n break;\n case \"in\":\n query = query.in(f.field, f.value);\n break;\n case \"is_null\":\n query = query.is(f.field, null);\n break;\n case \"is_not_null\":\n query = query.not(f.field, \"is\", null);\n break;\n case \"between\": {\n const [lo, hi] = f.value;\n query = query.gte(f.field, lo).lte(f.field, hi);\n break;\n }\n default:\n throw new Error(`[SupabaseProvider] Unknown filter operator \"${(f as FilterParam).operator}\"`);\n break;\n }\n }\n return query;\n }\n\n const maxPerPage = options.maxPerPage ?? 1000;\n // Resources found to have no \"id\" column for the default orderKey.\n const keylessResources = new Set<string>();\n\n /** Tell `onReadError` (sync or async; its failure is swallowed), then throw. */\n async function reportReadError(\n error: DataReadError,\n resource: string,\n operation: \"getList\" | \"getOne\" | \"getMany\",\n ): Promise<never> {\n try {\n await Promise.resolve(options.onReadError?.(error, { resource, operation }));\n } catch {\n // A logging hook never changes what the caller is told.\n }\n throw error;\n }\n\n /** A failed read, as a `DataReadError` with a message users can be shown. */\n async function throwIfReadError(\n result: { error: unknown },\n resource: string,\n operation: \"getList\" | \"getOne\" | \"getMany\",\n ): Promise<void> {\n if (!result.error) return;\n const raw = result.error as { message?: string; code?: string };\n const code = typeof raw.code === \"string\" ? raw.code : undefined;\n const outcome = readOutcomeFromCode(code);\n const error = new DataReadError(\n outcome,\n readFailureMessage(outcome, nounFor(resource), operation === \"getOne\", configFor(resource).nounPlural),\n { code, cause: result.error },\n );\n await reportReadError(error, resource, operation);\n }\n\n // ---------------------------------------------------------------------------\n // Write helpers\n // ---------------------------------------------------------------------------\n\n const from = (resource: string) => client.from(resource) as SupabaseQueryBuilder;\n\n /** The relation PostgREST names in errors about a read of `resource`: its view, function or table. */\n function readName(resource: string): string {\n const source = configFor(resource).source;\n return typeof source === \"string\" ? source : source ? source.rpc : resource;\n }\n\n /**\n * The values a create or update sends to the table: with `writeColumns`,\n * only those; for an update of a sourced resource without them, only the\n * columns the table's row has, so read-only columns from a view never go out.\n */\n async function tableValues(\n resource: string,\n values: Record<string, unknown>,\n id?: Identifier,\n ): Promise<Record<string, unknown>> {\n const config = configFor(resource);\n if (config.writeColumns) {\n const allowed = new Set(config.writeColumns);\n return Object.fromEntries(Object.entries(values).filter(([key]) => allowed.has(key)));\n }\n if (!config.source || id === undefined) return values;\n const row = await readBack(resource, id);\n if (!row) return values;\n return Object.fromEntries(Object.entries(values).filter(([key]) => key in row));\n }\n\n /** A read of `resource` from its configured source (table, view or function), with its default columns. */\n function read(resource: string, columns: string | undefined, count?: \"exact\"): SupabaseQueryBuilder {\n const config = configFor(resource);\n const cols = columns ?? config.select ?? \"*\";\n const source = config.source;\n if (source && typeof source === \"object\") {\n if (!client.rpc) {\n throw new DataReadError(\"error\", `[SupabaseProvider] \"${resource}\" reads from ${source.rpc}(), but the client has no rpc.`);\n }\n const builder = client.rpc(source.rpc, source.args?.() ?? {}, count ? { count } : undefined) as SupabaseQueryBuilder;\n return builder.select(cols);\n }\n const table = client.from(source ?? resource) as SupabaseQueryBuilder;\n return count ? table.select(cols, { count }) : table.select(cols);\n }\n const configFor = (resource: string): SupabaseResourceConfig =>\n options.resources?.[resource] ?? {};\n const nounFor = (resource: string) => configFor(resource).noun ?? \"record\";\n\n function realtimeEnabled(resource: string): boolean {\n if (typeof client.channel !== \"function\") return false;\n const own = configFor(resource).realtime;\n if (own !== undefined) return own;\n const all = options.realtime;\n if (!all) return false;\n if (all === true) return true;\n return typeof all === \"function\" ? all(resource) : all.includes(resource);\n }\n\n function isBinTable(resource: string): boolean {\n const mode = configFor(resource).deleteMode;\n if (mode) return mode === \"bin\";\n const bin = options.binTables;\n if (!bin) return false;\n return typeof bin === \"function\" ? bin(resource) : bin.includes(resource);\n }\n\n /** Awaits a write-path query: its rows, or a `DataWriteError`. */\n async function run(query: SupabaseQueryBuilder): Promise<unknown[]> {\n let result: { data: unknown; error: unknown };\n try {\n result = (await query) as { data: unknown; error: unknown };\n } catch (error) {\n throw toDataWriteError(error);\n }\n if (result.error) throw toDataWriteError(result.error);\n if (Array.isArray(result.data)) return result.data;\n return result.data == null ? [] : [result.data];\n }\n\n async function isVisible(resource: string, id: Identifier): Promise<boolean> {\n return (await run(from(resource).select(\"id\").eq(\"id\", id))).length > 0;\n }\n\n async function readBack(resource: string, id: Identifier): Promise<BaseRecord | undefined> {\n return (await run(from(resource).select(\"*\").eq(\"id\", id)))[0] as BaseRecord | undefined;\n }\n\n function goneError(resource: string): DataWriteError {\n return new DataWriteError(\n \"gone\",\n `This ${nounFor(resource)} no longer exists, or you can no longer see it.`,\n );\n }\n\n /**\n * A write matched no rows: read the row back to say why. Still visible\n * means the change was refused; not visible means it is gone (deleted, or\n * hidden from this user — the two can't be told apart under RLS).\n */\n async function noRowsError(\n resource: string,\n id: Identifier,\n verb: \"change\" | \"delete\",\n ): Promise<DataWriteError> {\n let visible: boolean;\n try {\n visible = await isVisible(resource, id);\n } catch (error) {\n const cause = toDataWriteError(error);\n return new DataWriteError(\n cause.outcome === \"unauthenticated\" ? \"unauthenticated\" : \"error\",\n `This ${nounFor(resource)} was not ${verb === \"change\" ? \"changed\" : \"deleted\"}, and reading it back failed (${cause.message}).`,\n { code: cause.code, cause: error },\n );\n }\n if (visible) {\n return new DataWriteError(\"forbidden\", `You can't ${verb} this ${nounFor(resource)}.`);\n }\n return goneError(resource);\n }\n\n async function prepare(\n resource: string,\n values: Record<string, unknown>,\n context: SupabaseWriteContext,\n ): Promise<Record<string, unknown>> {\n const rule = configFor(resource).prepare;\n if (!rule) return values;\n try {\n return await rule({ ...values }, context);\n } catch (error) {\n throw toDataWriteError(error);\n }\n }\n\n /** After a committed write. Never turns it into a failure. */\n async function committed(event: WriteEvent): Promise<void> {\n if (!options.onWrite) return;\n try {\n await options.onWrite(event);\n } catch (error) {\n console.error(`[SupabaseProvider] onWrite failed for \"${event.resource}\":`, error);\n }\n }\n\n // ---------------------------------------------------------------------------\n // DataProvider implementation\n // ---------------------------------------------------------------------------\n\n /** The search as PostgREST `or` clauses, or \"\" for none. */\n function searchClauses(resource: string, params: ListParams): string {\n const searchFields = configFor(resource).searchFields ?? params.search?.fields ?? [];\n if (!params.search || !params.search.query || searchFields.length === 0) return \"\";\n const escaped = escapeIlike(params.search.query);\n const safeFieldPattern = /^[a-zA-Z_][a-zA-Z0-9_.]*$/;\n return searchFields\n .filter((f) => safeFieldPattern.test(f))\n // Quoted, so commas, dots and parens in the query stay literal (also\n // when nested inside the keyset's `and(or(…))`).\n .map((f) => `${f}.ilike.${quoteFilterValue(`%${escaped}%`)}`)\n .join(\",\");\n }\n\n /** A cursor request this provider can't serve: `invalid`, with why as the cause. */\n function refuseCursor(resource: string, why: string): Promise<never> {\n return reportReadError(\n new DataReadError(\n \"invalid\",\n readFailureMessage(\"invalid\", nounFor(resource), false, configFor(resource).nounPlural),\n { cause: new Error(`[SupabaseProvider] \"${resource}\": ${why}`) },\n ),\n resource,\n \"getList\",\n );\n }\n\n /**\n * One page by keyset: ordered by the sort column and then the key, the\n * rows after the cursor's row, plus one more to tell whether a next page\n * exists. Counted only on the first page.\n */\n async function getCursorPage(\n resource: string,\n params: ListParams,\n key: string | false,\n ): Promise<{ data: unknown[]; total: number; nextCursor: string | null }> {\n const { cursor } = params.pagination!;\n // The look-ahead row must fit under PostgREST's max-rows (maxPerPage), or\n // it is dropped and the list would end after one page. A keyset page can\n // be shorter than asked without skipping or repeating rows.\n const perPage = Math.max(1, Math.min(params.pagination!.perPage, maxPerPage - 1));\n if (!key) {\n return refuseCursor(resource, \"cursor paging needs a unique key column to order by; its orderKey is false. Set orderKey to a unique, non-null column, or page by offset.\");\n }\n if (!PLAIN_COLUMN.test(key)) return refuseCursor(resource, `the key column \"${key}\" can't be used in a cursor.`);\n const sort = params.sort && params.sort.field !== key ? params.sort : undefined;\n if (sort && !PLAIN_COLUMN.test(sort.field)) {\n return refuseCursor(resource, `cursor paging can sort only by a plain column, not \"${sort.field}\".`);\n }\n const order: \"asc\" | \"desc\" = params.sort?.order ?? \"asc\";\n const sortField = sort ? sort.field : null;\n\n let after: CursorState | undefined;\n if (cursor) {\n after = decodeCursor(cursor);\n if (!after) return refuseCursor(resource, \"the cursor is not one this provider made.\");\n if (after.s !== sortField || after.o !== order || after.k !== key) {\n return refuseCursor(resource, \"the cursor was made for a different sort; start again from the first page (cursor: null).\");\n }\n }\n\n let query = read(resource, params.select, cursor ? undefined : \"exact\");\n query = applyFilters(query, params.filters);\n const search = searchClauses(resource, params);\n const keyset = after ? keysetClauses(after) : \"\";\n // Both are OR groups that must hold together: nest them in one `or`.\n if (search && keyset) query = query.or(`and(or(${search}),or(${keyset}))`);\n else if (search || keyset) query = query.or(search || keyset);\n\n if (sortField) {\n // Pinned to Postgres's default null placement, which the keyset assumes.\n query = query.order(sortField, { ascending: order === \"asc\", nullsFirst: order === \"desc\" });\n query = query.order(key, { ascending: true });\n } else {\n query = query.order(key, { ascending: order === \"asc\" });\n }\n query = query.range(0, perPage);\n\n const result = (await query) as unknown as { data: unknown[] | null; error: unknown; count?: number | null };\n await throwIfReadError(result, resource, \"getList\");\n const rows = (result.data ?? []) as Record<string, unknown>[];\n const page = rows.slice(0, perPage);\n let nextCursor: string | null = null;\n if (rows.length > perPage) {\n const last = page[page.length - 1]!;\n const id = last[key];\n const v = sortField ? last[sortField] : undefined;\n if (!isIdentifier(id) || (sortField && !(sortField in last))) {\n return refuseCursor(resource, `the selected columns must include \"${key}\"${sortField ? ` and \"${sortField}\"` : \"\"} to page by cursor.`);\n }\n if (v !== undefined && v !== null && typeof v === \"object\") {\n return refuseCursor(resource, `cursor paging can't sort by \"${sortField}\": its values aren't plain (text, number, date, boolean).`);\n }\n nextCursor = encodeCursor({\n s: sortField,\n o: order,\n k: key,\n ...(sortField ? { v: (v ?? null) as CursorState[\"v\"] } : {}),\n id,\n });\n }\n return { data: page, total: cursor ? -1 : (result.count ?? 0), nextCursor };\n }\n\n const provider: DataProvider = {\n async getList(resource, params) {\n // Refused, not cut short: a shorter page than the caller asked for\n // would shift every later page's boundary and skip or repeat rows.\n if (params.pagination && params.pagination.perPage > maxPerPage) {\n const { perPage } = params.pagination;\n await reportReadError(\n new DataReadError(\n \"invalid\",\n readFailureMessage(\"invalid\", nounFor(resource), false, configFor(resource).nounPlural),\n {\n cause: new Error(\n `[SupabaseProvider] \"${resource}\" asked for ${perPage} rows per page; the most is ${maxPerPage} (maxPerPage). Ask for at most ${maxPerPage} and page through the rest.`,\n ),\n },\n ),\n resource,\n \"getList\",\n );\n }\n\n const configuredKey = configFor(resource).orderKey;\n if (params.pagination && params.pagination.cursor !== undefined) {\n return getCursorPage(resource, params, configuredKey === undefined ? \"id\" : configuredKey) as never;\n }\n const run = (key: string | false) => {\n let query = read(resource, params.select, \"exact\");\n\n query = applyFilters(query, params.filters);\n\n // Search — convert to OR of ilike. A resource's configured\n // `searchFields` win over the caller's.\n const clauses = searchClauses(resource, params);\n if (clauses) {\n query = query.or(clauses);\n }\n\n // Sort, then the key column, so equal sort values keep one order\n // across pages (otherwise a row can repeat on page 2 or be skipped).\n // An unsorted page is ordered by the key alone: without an ORDER BY\n // the database may return pages in any order.\n if (params.sort) {\n query = query.order(params.sort.field, {\n ascending: params.sort.order === \"asc\",\n });\n if (key && key !== params.sort.field) query = query.order(key, { ascending: true });\n } else if (params.pagination && key) {\n query = query.order(key, { ascending: true });\n }\n\n if (params.pagination) {\n const { page, perPage } = params.pagination;\n const from = (page - 1) * perPage;\n const to = from + perPage - 1;\n query = query.range(from, to);\n }\n\n return query as unknown as Promise<{\n data: unknown[];\n error: unknown;\n count?: number | null;\n }>;\n };\n\n // The default key (\"id\") is a guess: a view without that column reads\n // as before, without the key order, and is not ordered by it again.\n const guessKey = configuredKey === undefined && !keylessResources.has(resource);\n let result = await run(configuredKey ?? (keylessResources.has(resource) ? false : \"id\"));\n if (guessKey && isMissingColumn(result.error, readName(resource), \"id\")) {\n keylessResources.add(resource);\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\n `[SupabaseProvider] \"${resource}\" has no \"id\" column, so its pages have no stable order. Set resources.${resource}.orderKey to a unique column (or false to silence this).`,\n );\n }\n result = await run(false);\n }\n await throwIfReadError(result, resource, \"getList\");\n\n return { data: result.data ?? [], total: result.count ?? 0 } as never;\n },\n\n async getOne(resource, params) {\n const result = (await read(resource, params.select)\n .eq(\"id\", params.id)\n .single()) as { data: unknown; error: unknown };\n await throwIfReadError(result, resource, \"getOne\");\n return { data: result.data } as never;\n },\n\n async getMany(resource, params) {\n if (params.ids.length === 0) return { data: [] } as never;\n const result = (await read(resource, undefined)\n .in(\"id\", params.ids)) as { data: unknown[]; error: unknown };\n await throwIfReadError(result, resource, \"getMany\");\n return { data: result.data ?? [] } as never;\n },\n\n async capabilities(resource?: string): Promise<ProviderCapabilities> {\n return {\n search: resource ? configFor(resource).searchFields?.length !== 0 : true,\n sort: true,\n filterOperators: SERVED_OPERATORS,\n bulkWrites: false,\n versionedWrites: false,\n compositeKeys: false,\n multiSort: false,\n create: true,\n delete: true,\n maxPerPage,\n softDelete: resource ? isBinTable(resource) : false,\n cursorPagination: resource ? configFor(resource).orderKey !== false : true,\n realtime: resource\n ? realtimeEnabled(resource)\n : typeof client.channel === \"function\" &&\n (!!options.realtime ||\n Object.values(options.resources ?? {}).some((r) => r.realtime === true)),\n };\n },\n\n subscribe(resource, params, callback) {\n if (!realtimeEnabled(resource)) {\n if (process.env.NODE_ENV !== \"production\" && !warnedRealtime.has(resource)) {\n warnedRealtime.add(resource);\n console.warn(\n typeof client.channel !== \"function\"\n ? `[SupabaseProvider] \"${resource}\" was subscribed to, but the client has no channel() (Supabase Realtime), so nothing will be reported.`\n : `[SupabaseProvider] \"${resource}\" was subscribed to, but realtime is off for it. Set resources.${resource}.realtime (or the realtime option) to true.`,\n );\n }\n return () => {};\n }\n const { schema, table } = realtimeTable(resource);\n // No server-side `id=eq.` filter for one record: Realtime never\n // delivers DELETE events through a filter, so the id is matched below.\n // A unique topic: supabase-js hands back an existing channel for a\n // topic already open, and removing it would end the other subscriber.\n const channel = client.channel!(\n `genesis:${resource}:${++realtimeChannelSeq}`,\n ) as SupabaseRealtimeChannel;\n let closed = false;\n let subscribedOnce = false;\n let interrupted = false;\n const emit = (event: ResourceChangeEvent) => {\n if (closed) return;\n try {\n callback(event);\n } catch (error) {\n console.error(`[SupabaseProvider] a realtime callback for \"${resource}\" threw:`, error);\n }\n };\n channel\n .on(\n \"postgres_changes\",\n { event: \"*\", schema, table },\n (payload) => {\n // Only the id: the payload is a hint, never data to show. Realtime\n // applies RLS to inserts and updates, but a delete's old key is\n // sent to every subscriber, so nothing else is passed on.\n const row = payload.eventType === \"DELETE\" ? payload.old : payload.new;\n const id = row?.[\"id\"];\n if (params.id != null && isIdentifier(id) && String(id) !== String(params.id)) return;\n const type =\n payload.eventType === \"INSERT\" ? \"created\" : payload.eventType === \"UPDATE\" ? \"updated\" : \"deleted\";\n emit(isIdentifier(id) ? { type, id } : { type });\n },\n )\n .subscribe((status) => {\n if (status === \"SUBSCRIBED\") {\n // Back after a drop: changes made meanwhile were not sent.\n if (subscribedOnce && interrupted) emit({ type: \"changed\" });\n subscribedOnce = true;\n interrupted = false;\n } else if (status === \"CHANNEL_ERROR\" || status === \"TIMED_OUT\" || status === \"CLOSED\") {\n interrupted = true;\n }\n });\n return () => {\n if (closed) return;\n closed = true;\n try {\n const done =\n typeof client.removeChannel === \"function\"\n ? client.removeChannel(channel)\n : channel.unsubscribe?.();\n // A failed removal (socket already gone) is nothing to report.\n if (done && typeof (done as Promise<unknown>).catch === \"function\") {\n (done as Promise<unknown>).catch(() => {});\n }\n } catch {\n // As above.\n }\n };\n },\n\n async create(resource, params) {\n const row = await tableValues(\n resource,\n await prepare(resource, params.data as Record<string, unknown>, { resource, action: \"create\" }),\n );\n const override = configFor(resource).create;\n let record: BaseRecord;\n if (override) {\n let returned: BaseRecord | Identifier;\n try {\n returned = await override(row);\n } catch (error) {\n throw toDataWriteError(error);\n }\n if (isIdentifier(returned)) {\n // The row exists from here on. A failed read-back must not report\n // the create as failed: the user would retry and make a second one.\n record = (await readBack(resource, returned).catch(() => undefined)) ?? { id: returned };\n } else if (returned && typeof returned === \"object\" && isIdentifier(returned.id)) {\n record = returned;\n } else {\n throw new DataWriteError(\n \"error\",\n `[SupabaseProvider] The create rule for \"${resource}\" returned neither the new row nor its id.`,\n );\n }\n } else {\n const rows = await run(from(resource).insert(row).select(\"*\").single());\n record = rows[0] as BaseRecord;\n }\n await committed({ resource, kind: \"create\", id: record.id, record });\n return { data: record } as never;\n },\n\n async update(resource, params) {\n const { id } = params;\n const row = await tableValues(\n resource,\n await prepare(resource, params.data as Record<string, unknown>, { resource, action: \"update\", id }),\n id,\n );\n const override = configFor(resource).update;\n let record: BaseRecord;\n if (override) {\n let returned: BaseRecord | Identifier | boolean | null | undefined | void;\n try {\n returned = await override(id, row);\n } catch (error) {\n throw toDataWriteError(error);\n }\n const result: unknown = returned;\n if (result == null || result === false) throw await noRowsError(resource, id, \"change\");\n if (isIdentifier(result) || result === true) {\n // The change committed; a failed read-back still reports it saved.\n const readId = result === true ? id : result;\n record = (await readBack(resource, readId).catch(() => undefined)) ?? { ...row, id: readId };\n } else if (typeof result === \"object\") {\n record = { id, ...(result as Record<string, unknown>) } as BaseRecord;\n } else {\n throw new DataWriteError(\n \"error\",\n `[SupabaseProvider] The update rule for \"${resource}\" returned neither the row, its id, nor nothing.`,\n );\n }\n } else {\n const rows = await run(from(resource).update(row).eq(\"id\", id).select(\"*\"));\n if (rows.length === 0) throw await noRowsError(resource, id, \"change\");\n record = rows[0] as BaseRecord;\n }\n await committed({ resource, kind: \"update\", id, record });\n return { data: record } as never;\n },\n\n async deleteOne(resource, params) {\n const { id } = params;\n let deletedId: Identifier = id;\n if (isBinTable(resource)) {\n // A binned delete reports zero rows whether or not it worked, so the\n // answer comes from visibility before and after.\n if (!(await isVisible(resource, id))) throw goneError(resource);\n await run(from(resource).delete().eq(\"id\", id));\n let stillVisible: boolean;\n try {\n stillVisible = await isVisible(resource, id);\n } catch (error) {\n const cause = toDataWriteError(error);\n throw new DataWriteError(\n \"error\",\n `The ${nounFor(resource)} may not have been deleted: checking it failed (${cause.message}).`,\n { code: cause.code, cause: error },\n );\n }\n if (stillVisible) {\n throw new DataWriteError(\"forbidden\", `You can't delete this ${nounFor(resource)}.`);\n }\n } else {\n const rows = await run(from(resource).delete().eq(\"id\", id).select(\"id\"));\n if (rows.length === 0) throw await noRowsError(resource, id, \"delete\");\n const returnedId = (rows[0] as { id?: unknown }).id;\n if (isIdentifier(returnedId)) deletedId = returnedId;\n }\n await committed({ resource, kind: \"delete\", id: deletedId });\n return { data: { id: deletedId } };\n },\n\n toFormValues(resource, record) {\n const map = configFor(resource).toFormValues;\n return map ? map(record) : record;\n },\n\n invalidates(event) {\n const keys = configFor(event.resource).invalidates;\n if (!keys) return [];\n return typeof keys === \"function\" ? keys(event) : keys;\n },\n };\n\n return provider;\n}\n","// ---------------------------------------------------------------------------\n// Write helpers (README \"One-off writes\")\n//\n// The writes a resource page doesn't cover: a database function (RPC) with\n// plain error words, and \"one live row per key\" (create, or adopt the row\n// that's already there). Both fail with a DataWriteError, like the provider.\n// ---------------------------------------------------------------------------\n\nimport { DataWriteError, isDataWriteError } from \"../schema/write-outcome\";\nimport { toDataWriteError } from \"./postgrest-errors\";\nimport type { BaseRecord, DataProvider, FilterParam } from \"./types\";\n\n/** Anything with Supabase's `rpc`. */\nexport interface RpcClient {\n rpc(fn: string, args?: Record<string, unknown>): PromiseLike<{ data: unknown; error: unknown }>;\n}\n\n/** The words shown for a code when the caller gives none. A guard's own `raise exception` (P0001) keeps its words. */\nexport const DEFAULT_RPC_MESSAGES: Readonly<Record<string, string>> = {\n \"42501\": \"You can't do that.\",\n \"22023\": \"That request isn't valid.\",\n \"23505\": \"That already exists.\",\n \"28000\": \"Sign in to continue.\",\n PGRST202: \"That action isn't available.\",\n PGRST301: \"Sign in to continue.\",\n};\n\nexport const RPC_FAILED = \"That didn't work. Try again.\";\n\nexport interface CallRpcOptions {\n /** Words per error code, e.g. `{ \"55000\": \"This course has already started.\" }`; these win over the defaults. */\n messages?: Record<string, string>;\n}\n\n/**\n * Calls a database function and returns its result. A failure throws a\n * DataWriteError with the usual outcome and code, and words a person can\n * read: yours for the code, a guard's own message (P0001), the defaults\n * above, or a generic sentence. The raw error stays on `cause`.\n */\nexport async function callRpc<T = unknown>(\n client: RpcClient,\n fn: string,\n args: Record<string, unknown> = {},\n options: CallRpcOptions = {},\n): Promise<T> {\n let result: { data: unknown; error: unknown };\n try {\n result = await client.rpc(fn, args);\n } catch (error) {\n // A client that already speaks DataWriteError (signed out, a refusal) keeps its outcome and code.\n if (isDataWriteError(error)) throw error;\n throw new DataWriteError(\"error\", RPC_FAILED, { cause: error });\n }\n if (!result || typeof result !== \"object\") {\n throw new DataWriteError(\"error\", RPC_FAILED, { cause: new Error(`rpc ${fn} returned ${String(result)}`) });\n }\n if (!result.error) return result.data as T;\n const mapped = toDataWriteError(result.error);\n const code = mapped.code;\n const custom = code !== undefined ? options.messages?.[code] : undefined;\n const raw = (result.error as { message?: unknown }).message;\n const guardWords = typeof raw === \"string\" && raw.trim() ? raw : undefined;\n const message =\n custom ??\n (code === \"P0001\" ? guardWords : undefined) ??\n (mapped.fields ? mapped.message : undefined) ??\n (code !== undefined ? DEFAULT_RPC_MESSAGES[code] : undefined) ??\n RPC_FAILED;\n throw new DataWriteError(mapped.outcome, message, { code, fields: mapped.fields, cause: result.error });\n}\n\nexport interface CreateOrAdoptOptions<T extends BaseRecord> {\n /** The fields that make a row unique (its unique index), read from `data`. */\n key: readonly (keyof T & string)[];\n /**\n * Changes to write over a row that was already there; return null to keep it\n * as it is. It runs on the row as read just now, and the update isn't\n * conditional: two callers merging into one row at once can each overwrite\n * the other. Where that matters, merge in a database function instead.\n */\n merge?: (existing: T) => Partial<T> | null;\n /**\n * Whether the row already there is finished and can't take changes (a sent answer): it's handed\n * back with `final: true` and `merge` isn't called, so the caller stops instead of writing over it.\n */\n final?: (existing: T) => boolean;\n}\n\nexport type CreateOrAdoptResult<T> = {\n row: T;\n /** The row was already there. */\n adopted: boolean;\n /** The row already there is finished (see `final`): nothing was written. */\n final: boolean;\n};\n\n/**\n * \"One live row per key\": creates the row, or, when one with the same key is\n * already there (a `duplicate`), adopts it, optionally merging changes in.\n * `adopted` says which, and `final` that the row already there is finished. Key\n * fields that are null or undefined match rows where they're null. A duplicate\n * you can't see is still an error.\n */\nexport async function createOrAdopt<T extends BaseRecord>(\n provider: DataProvider,\n resource: string,\n data: Partial<T>,\n options: CreateOrAdoptOptions<T>,\n): Promise<CreateOrAdoptResult<T>> {\n if (options.key.length === 0) throw new Error(`[genesis-core] createOrAdopt(\"${resource}\") needs a key`);\n try {\n return { row: (await provider.create<T>(resource, { data })).data, adopted: false, final: false };\n } catch (error) {\n if (!isDataWriteError(error) || error.outcome !== \"duplicate\") throw error;\n // A clash on some other unique index isn't this key's row.\n if (error.fields && Object.keys(error.fields).some((field) => !options.key.includes(field as keyof T & string))) throw error;\n const filters: FilterParam[] = options.key.map((field) => {\n const value = (data as Record<string, unknown>)[field];\n if (value === null || value === undefined) return { field, operator: \"is_null\" };\n if (typeof value !== \"string\" && typeof value !== \"number\" && typeof value !== \"boolean\") {\n throw new Error(`[genesis-core] createOrAdopt(\"${resource}\") key field ${field} must be a string, number or boolean`);\n }\n return { field, operator: \"eq\", value };\n });\n const { data: rows } = await provider.getList<T>(resource, { filters, pagination: { page: 1, perPage: 2 } });\n if (rows.length !== 1) throw error;\n const existing = rows[0]!;\n if (options.final?.(existing)) return { row: existing, adopted: true, final: true };\n const changes = options.merge?.(existing);\n if (!changes || Object.keys(changes).length === 0) return { row: existing, adopted: true, final: false };\n return {\n row: (await provider.update<T>(resource, { id: existing.id, data: changes })).data,\n adopted: true,\n final: false,\n };\n }\n}\n"]}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { L as ListParams, a as Identifier } from './types-B9DDfvWa.js';
|
|
2
2
|
export { A as ArrayFilter, B as BaseRecord, b as BulkChange, c as BulkResult, C as CreateParams, d as CreateResult, D as DataProvider, e as DeleteParams, f as DeleteResult, F as FilterParam, G as GetManyParams, g as GetManyResult, h as GetOneParams, i as GetOneResult, H as HistoryParams, j as ImportParams, I as InvalidationKey, k as ListResult, N as NullFilter, P as PaginationParam, R as RangeFilter, l as ResourceChangeEvent, m as RowFailure, S as ScalarFilter, n as SortParam, o as SubscribeParams, U as UpdateParams, p as UpdateResult, W as WriteEvent } from './types-B9DDfvWa.js';
|
|
3
|
-
export { D as
|
|
4
|
-
export { CallRpcOptions, CreateOrAdoptOptions, DEFAULT_RPC_MESSAGES, DataProviderRoot, DataProviderRootProps, GenesisProvider, GenesisProviderProps, MockProviderOptions, PostgrestFieldErrors, RPC_FAILED, RpcClient, SupabaseClient, SupabaseClientInput, SupabaseProviderOptions, SupabaseRealtimeChannel, SupabaseRealtimePayload, SupabaseResourceConfig, SupabaseWriteContext, callRpc, createMockProvider, createOrAdopt, createSupabaseProvider, fieldErrorsFromPostgrest, readOutcomeFromCode, toDataWriteError, useDataProvider, useStorage, writeOutcomeFromCode } from './provider/index.js';
|
|
3
|
+
export { D as DataWriteError, a as DataWriteErrorOptions, W as WriteOutcome, i as isDataWriteError } from './write-outcome-B2fE29yZ.js';
|
|
4
|
+
export { CallRpcOptions, CreateOrAdoptOptions, CreateOrAdoptResult, DEFAULT_RPC_MESSAGES, DataProviderRoot, DataProviderRootProps, GenesisProvider, GenesisProviderProps, MockProviderOptions, PostgrestFieldErrors, RPC_FAILED, RpcClient, SupabaseClient, SupabaseClientInput, SupabaseProviderOptions, SupabaseRealtimeChannel, SupabaseRealtimePayload, SupabaseResourceConfig, SupabaseWriteContext, callRpc, createMockProvider, createOrAdopt, createSupabaseProvider, fieldErrorsFromPostgrest, readOutcomeFromCode, toDataWriteError, useDataProvider, useStorage, writeOutcomeFromCode } from './provider/index.js';
|
|
5
|
+
export { D as DataReadError, a as DataReadErrorOptions, R as ReadOutcome, i as isDataReadError, r as readFailureMessage } from './read-outcome-BnboMYOV.js';
|
|
5
6
|
export { S as StorageAdapter } from './types-DKcxHXxq.js';
|
|
6
7
|
export { createLocalStorageAdapter, createMemoryStorageAdapter, createNoopStorageAdapter } from './storage/index.js';
|
|
7
8
|
export { UseResourceOptions, UseResourceReturn, useResource } from './hooks/use-resource.js';
|
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
export { DEFAULT_RPC_MESSAGES, RPC_FAILED, callRpc, createOrAdopt, createSupabaseProvider, fieldErrorsFromPostgrest, readOutcomeFromCode, toDataWriteError, writeOutcomeFromCode } from './chunk-
|
|
1
|
+
export { DEFAULT_RPC_MESSAGES, RPC_FAILED, callRpc, createOrAdopt, createSupabaseProvider, fieldErrorsFromPostgrest, readOutcomeFromCode, toDataWriteError, writeOutcomeFromCode } from './chunk-ALOP5MZM.js';
|
|
2
2
|
export { decodeRecordKey, encodeRecordKey, keyFields } from './chunk-KV2HW4G4.js';
|
|
3
|
-
export { DataReadError, isDataReadError, readFailureMessage } from './chunk-HUNGCTRA.js';
|
|
4
3
|
import './chunk-XCX2TRBL.js';
|
|
4
|
+
export { DataReadError, isDataReadError, readFailureMessage } from './chunk-HUNGCTRA.js';
|
|
5
5
|
import './chunk-65SXNHWE.js';
|
|
6
6
|
export { ViewerScope, clearViewerCache } from './chunk-5ORRAXIV.js';
|
|
7
7
|
export { useResource } from './chunk-NMFABW4Y.js';
|
package/dist/provider/index.d.ts
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
import { D as DataProvider, a as Identifier, B as BaseRecord, I as InvalidationKey, W as WriteEvent } from '../types-B9DDfvWa.js';
|
|
2
2
|
export { A as ArrayFilter, b as BulkChange, c as BulkResult, C as CreateParams, d as CreateResult, e as DeleteParams, f as DeleteResult, F as FilterParam, G as GetManyParams, g as GetManyResult, h as GetOneParams, i as GetOneResult, H as HistoryParams, j as ImportParams, L as ListParams, k as ListResult, N as NullFilter, P as PaginationParam, R as RangeFilter, l as ResourceChangeEvent, m as RowFailure, S as ScalarFilter, n as SortParam, o as SubscribeParams, U as UpdateParams, p as UpdateResult } from '../types-B9DDfvWa.js';
|
|
3
|
-
import { D as
|
|
4
|
-
export { a as
|
|
3
|
+
import { D as DataWriteError, W as WriteOutcome } from '../write-outcome-B2fE29yZ.js';
|
|
4
|
+
export { a as DataWriteErrorOptions, i as isDataWriteError } from '../write-outcome-B2fE29yZ.js';
|
|
5
|
+
import { D as DataReadError, R as ReadOutcome } from '../read-outcome-BnboMYOV.js';
|
|
6
|
+
export { a as DataReadErrorOptions, i as isDataReadError, r as readFailureMessage } from '../read-outcome-BnboMYOV.js';
|
|
5
7
|
import * as react from 'react';
|
|
6
8
|
import { ReactNode } from 'react';
|
|
7
9
|
import { QueryClient } from '@tanstack/react-query';
|
|
@@ -375,16 +377,27 @@ interface CreateOrAdoptOptions<T extends BaseRecord> {
|
|
|
375
377
|
* the other. Where that matters, merge in a database function instead.
|
|
376
378
|
*/
|
|
377
379
|
merge?: (existing: T) => Partial<T> | null;
|
|
380
|
+
/**
|
|
381
|
+
* Whether the row already there is finished and can't take changes (a sent answer): it's handed
|
|
382
|
+
* back with `final: true` and `merge` isn't called, so the caller stops instead of writing over it.
|
|
383
|
+
*/
|
|
384
|
+
final?: (existing: T) => boolean;
|
|
378
385
|
}
|
|
386
|
+
type CreateOrAdoptResult<T> = {
|
|
387
|
+
row: T;
|
|
388
|
+
/** The row was already there. */
|
|
389
|
+
adopted: boolean;
|
|
390
|
+
/** The row already there is finished (see `final`): nothing was written. */
|
|
391
|
+
final: boolean;
|
|
392
|
+
};
|
|
379
393
|
/**
|
|
380
394
|
* "One live row per key": creates the row, or, when one with the same key is
|
|
381
395
|
* already there (a `duplicate`), adopts it, optionally merging changes in.
|
|
382
|
-
* `adopted` says which
|
|
396
|
+
* `adopted` says which, and `final` that the row already there is finished. Key
|
|
397
|
+
* fields that are null or undefined match rows where they're null. A duplicate
|
|
398
|
+
* you can't see is still an error.
|
|
383
399
|
*/
|
|
384
|
-
declare function createOrAdopt<T extends BaseRecord>(provider: DataProvider, resource: string, data: Partial<T>, options: CreateOrAdoptOptions<T>): Promise<
|
|
385
|
-
row: T;
|
|
386
|
-
adopted: boolean;
|
|
387
|
-
}>;
|
|
400
|
+
declare function createOrAdopt<T extends BaseRecord>(provider: DataProvider, resource: string, data: Partial<T>, options: CreateOrAdoptOptions<T>): Promise<CreateOrAdoptResult<T>>;
|
|
388
401
|
|
|
389
402
|
/**
|
|
390
403
|
* Puts a `DataProvider` in context, and nothing else. Mount it inside your
|
|
@@ -437,4 +450,4 @@ type GenesisProviderProps = {
|
|
|
437
450
|
*/
|
|
438
451
|
declare function GenesisProvider({ children, provider, mock, storage, queryClient: queryClientProp, }: GenesisProviderProps): react.JSX.Element;
|
|
439
452
|
|
|
440
|
-
export { BaseRecord, type CallRpcOptions, type CreateOrAdoptOptions, DEFAULT_RPC_MESSAGES, DataProvider, DataProviderRoot, type DataProviderRootProps, DataReadError, DataWriteError, GenesisProvider, type GenesisProviderProps, Identifier, InvalidationKey, type MockProviderOptions, type PostgrestFieldErrors, RPC_FAILED, ReadOutcome, type RpcClient, type SupabaseClient, type SupabaseClientInput, type SupabaseProviderOptions, type SupabaseRealtimeChannel, type SupabaseRealtimePayload, type SupabaseResourceConfig, type SupabaseWriteContext, WriteEvent, WriteOutcome, callRpc, createMockProvider, createOrAdopt, createSupabaseProvider, fieldErrorsFromPostgrest, readOutcomeFromCode, toDataWriteError, useDataProvider, useStorage, writeOutcomeFromCode };
|
|
453
|
+
export { BaseRecord, type CallRpcOptions, type CreateOrAdoptOptions, type CreateOrAdoptResult, DEFAULT_RPC_MESSAGES, DataProvider, DataProviderRoot, type DataProviderRootProps, DataReadError, DataWriteError, GenesisProvider, type GenesisProviderProps, Identifier, InvalidationKey, type MockProviderOptions, type PostgrestFieldErrors, RPC_FAILED, ReadOutcome, type RpcClient, type SupabaseClient, type SupabaseClientInput, type SupabaseProviderOptions, type SupabaseRealtimeChannel, type SupabaseRealtimePayload, type SupabaseResourceConfig, type SupabaseWriteContext, WriteEvent, WriteOutcome, callRpc, createMockProvider, createOrAdopt, createSupabaseProvider, fieldErrorsFromPostgrest, readOutcomeFromCode, toDataWriteError, useDataProvider, useStorage, writeOutcomeFromCode };
|
package/dist/provider/index.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { DEFAULT_RPC_MESSAGES, RPC_FAILED, callRpc, createOrAdopt, createSupabaseProvider, fieldErrorsFromPostgrest, readOutcomeFromCode, toDataWriteError, writeOutcomeFromCode } from '../chunk-
|
|
1
|
+
export { DEFAULT_RPC_MESSAGES, RPC_FAILED, callRpc, createOrAdopt, createSupabaseProvider, fieldErrorsFromPostgrest, readOutcomeFromCode, toDataWriteError, writeOutcomeFromCode } from '../chunk-ALOP5MZM.js';
|
|
2
2
|
export { DataReadError, isDataReadError, readFailureMessage } from '../chunk-HUNGCTRA.js';
|
|
3
3
|
export { DataProviderRoot, GenesisProvider, createMockProvider, useDataProvider, useStorage } from '../chunk-GGSXSI6Z.js';
|
|
4
4
|
import '../chunk-ZYJUEJ4Z.js';
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* - `unauthenticated`: no signed-in user, or the session expired.
|
|
3
|
+
* - `forbidden`: this user may not read these records.
|
|
4
|
+
* - `gone`: the one record asked for doesn't exist, or isn't visible.
|
|
5
|
+
* - `invalid`: the request itself was wrong (an unknown column, a bad value).
|
|
6
|
+
* - `error`: anything else.
|
|
7
|
+
*/
|
|
8
|
+
type ReadOutcome = "unauthenticated" | "forbidden" | "gone" | "invalid" | "error";
|
|
9
|
+
interface DataReadErrorOptions {
|
|
10
|
+
/** The store's own error code (a Postgres SQLSTATE or PostgREST code). */
|
|
11
|
+
code?: string;
|
|
12
|
+
/** The underlying error, with its raw text, kept for logging. */
|
|
13
|
+
cause?: unknown;
|
|
14
|
+
}
|
|
15
|
+
/** Thrown by a provider when a read failed. Its `message` is safe to show. */
|
|
16
|
+
declare class DataReadError extends Error {
|
|
17
|
+
readonly outcome: ReadOutcome;
|
|
18
|
+
/** The store's own error code, when it gave one. */
|
|
19
|
+
readonly code?: string;
|
|
20
|
+
constructor(outcome: ReadOutcome, message: string, options?: DataReadErrorOptions);
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* `instanceof` fails when two copies of this package are installed, so check
|
|
24
|
+
* the shape instead.
|
|
25
|
+
*/
|
|
26
|
+
declare function isDataReadError(error: unknown): error is DataReadError;
|
|
27
|
+
/** The plain sentence for a failed read of `noun` records (one, or a list). */
|
|
28
|
+
declare function readFailureMessage(outcome: ReadOutcome, noun: string, one: boolean, plural?: string): string;
|
|
29
|
+
|
|
30
|
+
export { DataReadError as D, type ReadOutcome as R, type DataReadErrorOptions as a, isDataReadError as i, readFailureMessage as r };
|
package/dist/schema/index.d.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { e as ResourceContract, D as DataRow } from '../types-C7FJtFXV.js';
|
|
2
2
|
export { A as AuditEntry, F as FieldPermissions, a as FieldReference, b as FieldSchema, c as FilterOperator, P as ProviderCapabilities, R as RecordComment, d as ResourceAccess, f as ResourceRelation, g as ResourceSchema, h as ResourceSummary, i as RowAction, S as StorageType, V as VersionField } from '../types-C7FJtFXV.js';
|
|
3
3
|
import { a as Identifier } from '../types-B9DDfvWa.js';
|
|
4
|
-
export { D as
|
|
4
|
+
export { D as DataWriteError, a as DataWriteErrorOptions, W as WriteOutcome, i as isDataWriteError } from '../write-outcome-B2fE29yZ.js';
|
|
5
|
+
export { D as DataReadError, a as DataReadErrorOptions, R as ReadOutcome, i as isDataReadError, r as readFailureMessage } from '../read-outcome-BnboMYOV.js';
|
|
5
6
|
export { FieldType as WidgetHint } from '../form-types.js';
|
|
6
7
|
|
|
7
8
|
/** The key of a contract as a list, whichever form `key` was declared in. */
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { D as DataProvider, a as Identifier } from '../types-B9DDfvWa.js';
|
|
2
|
+
import { D as DataWriteError } from '../write-outcome-B2fE29yZ.js';
|
|
3
|
+
import '../types-C7FJtFXV.js';
|
|
4
|
+
import '../form-types.js';
|
|
5
|
+
|
|
6
|
+
/** The shared fixture logins, the same ids `genesis_testing.user_id()` uses. */
|
|
7
|
+
declare const FIXTURE_USERS: {
|
|
8
|
+
readonly owner: "00000000-0000-4000-8000-000000000001";
|
|
9
|
+
readonly staff: "00000000-0000-4000-8000-000000000002";
|
|
10
|
+
readonly client: "00000000-0000-4000-8000-000000000003";
|
|
11
|
+
readonly stranger: "00000000-0000-4000-8000-000000000004";
|
|
12
|
+
};
|
|
13
|
+
type FixtureUser = keyof typeof FIXTURE_USERS;
|
|
14
|
+
/** A broken contract: the message says what happened instead. */
|
|
15
|
+
declare class ContractError extends Error {
|
|
16
|
+
constructor(message: string);
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* A signed access token for a fixture person (or any user id), for a test
|
|
20
|
+
* database's legacy JWT secret. Hand it to the client as
|
|
21
|
+
* `Authorization: Bearer <token>`; `auth.uid()` then reads that user. Test
|
|
22
|
+
* databases only: never give it a production secret.
|
|
23
|
+
*/
|
|
24
|
+
declare function fixtureAccessToken(user: FixtureUser | string, options: {
|
|
25
|
+
secret: string;
|
|
26
|
+
expiresInSeconds?: number;
|
|
27
|
+
role?: string;
|
|
28
|
+
}): Promise<string>;
|
|
29
|
+
/** The error's message is plain words: no raw database text or error codes. */
|
|
30
|
+
declare function expectPlainMessage(error: unknown): void;
|
|
31
|
+
/**
|
|
32
|
+
* Whether a failed write is a refusal: a refusal code (42501, P0001), or the
|
|
33
|
+
* provider's own `forbidden` (the row is still visible but unchanged) or
|
|
34
|
+
* `unauthenticated`. `gone` is not: it also means the id matched nothing.
|
|
35
|
+
*/
|
|
36
|
+
declare function isRefusal(error: unknown): error is DataWriteError;
|
|
37
|
+
interface ExpectRefusedOptions {
|
|
38
|
+
/** With a write function: who tries it (and must be refused). */
|
|
39
|
+
as?: DataProvider;
|
|
40
|
+
/**
|
|
41
|
+
* Proof a write that reached no row (`gone`) was refused, not mistyped.
|
|
42
|
+
* With a write function: a provider for someone who may make it, which runs
|
|
43
|
+
* the same function. With a promise: a function making the same write as
|
|
44
|
+
* that someone. Either way it must resolve with the row it changed. Its
|
|
45
|
+
* write is real: run the check on test data.
|
|
46
|
+
*/
|
|
47
|
+
control?: DataProvider | (() => Promise<unknown>);
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* The write is refused, in plain words: a refusal code (42501, P0001) or the
|
|
51
|
+
* provider's `forbidden` / `unauthenticated`. A write that reaches no row
|
|
52
|
+
* (`gone`) counts only with a `control` that makes the same write and changes
|
|
53
|
+
* a row, so a typo'd id or resource can't pass. Pass the write as a function
|
|
54
|
+
* of a provider (with `as` and a control provider) to run exactly the same
|
|
55
|
+
* write both ways. Returns the refusal for more checks.
|
|
56
|
+
*
|
|
57
|
+
* ```ts
|
|
58
|
+
* await expectRefused((p) => p.update("tasks", { id, data: { title: "x" } }), { as: stranger, control: owner });
|
|
59
|
+
* ```
|
|
60
|
+
*/
|
|
61
|
+
declare function expectRefused(write: Promise<unknown> | ((provider: DataProvider) => Promise<unknown>), options?: ExpectRefusedOptions): Promise<DataWriteError>;
|
|
62
|
+
/** The write succeeds. Returns what it resolved to. */
|
|
63
|
+
declare function expectAllowed<T>(write: Promise<T>): Promise<T>;
|
|
64
|
+
/**
|
|
65
|
+
* A client can't change a column only the server sets. First `system` (the
|
|
66
|
+
* service role, or whoever the server writes as) sets `field` to `value` and
|
|
67
|
+
* must change the stored value, then puts it back: that proves the row exists
|
|
68
|
+
* and the value can change at all. Then `as` tries the same update, and the
|
|
69
|
+
* stored value must stay as it was, whether the update was refused, reached
|
|
70
|
+
* no row, or a trigger put the value back. Any other error fails.
|
|
71
|
+
*/
|
|
72
|
+
declare function expectServerOwned(args: {
|
|
73
|
+
as: DataProvider;
|
|
74
|
+
system: DataProvider;
|
|
75
|
+
resource: string;
|
|
76
|
+
id: Identifier;
|
|
77
|
+
field: string;
|
|
78
|
+
value: unknown;
|
|
79
|
+
}): Promise<void>;
|
|
80
|
+
/**
|
|
81
|
+
* `marker` (a value only a private row holds) appears nowhere in what the read
|
|
82
|
+
* returns: use a list or report read that returns the rows around the private
|
|
83
|
+
* one. A refused read (42501, or `forbidden` / `unauthenticated`) shows
|
|
84
|
+
* nothing and passes; any other failure fails, `gone` included, so a wrong id
|
|
85
|
+
* or a broken query can't pass.
|
|
86
|
+
*/
|
|
87
|
+
declare function expectNeverShows(read: Promise<unknown>, marker: string): Promise<void>;
|
|
88
|
+
/** The read returns exactly `expected` rows (a list result, a getMany result or an array). */
|
|
89
|
+
declare function expectSees(read: Promise<unknown>, expected: number): Promise<void>;
|
|
90
|
+
/**
|
|
91
|
+
* A delete on a recycle-bin table moves the row to the bin: `as` deletes it,
|
|
92
|
+
* can no longer read it (gone or forbidden), and `inBin` (a check with the
|
|
93
|
+
* service role or a bin query) confirms the row is still stored.
|
|
94
|
+
*/
|
|
95
|
+
declare function expectBinned(args: {
|
|
96
|
+
as: DataProvider;
|
|
97
|
+
resource: string;
|
|
98
|
+
id: Identifier;
|
|
99
|
+
inBin: () => Promise<boolean>;
|
|
100
|
+
}): Promise<void>;
|
|
101
|
+
|
|
102
|
+
export { ContractError, type ExpectRefusedOptions, FIXTURE_USERS, type FixtureUser, expectAllowed, expectBinned, expectNeverShows, expectPlainMessage, expectRefused, expectSees, expectServerOwned, fixtureAccessToken, isRefusal };
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
import { isDataReadError } from '../chunk-HUNGCTRA.js';
|
|
2
|
+
import { isDataWriteError } from '../chunk-LG6TUBVM.js';
|
|
3
|
+
|
|
4
|
+
// src/testing/index.ts
|
|
5
|
+
var FIXTURE_USERS = {
|
|
6
|
+
owner: "00000000-0000-4000-8000-000000000001",
|
|
7
|
+
staff: "00000000-0000-4000-8000-000000000002",
|
|
8
|
+
client: "00000000-0000-4000-8000-000000000003",
|
|
9
|
+
stranger: "00000000-0000-4000-8000-000000000004"
|
|
10
|
+
};
|
|
11
|
+
var ContractError = class extends Error {
|
|
12
|
+
constructor(message) {
|
|
13
|
+
super(message);
|
|
14
|
+
this.name = "ContractError";
|
|
15
|
+
}
|
|
16
|
+
};
|
|
17
|
+
async function fixtureAccessToken(user, options) {
|
|
18
|
+
const sub = Object.hasOwn(FIXTURE_USERS, user) ? FIXTURE_USERS[user] : user;
|
|
19
|
+
const now = Math.floor(Date.now() / 1e3);
|
|
20
|
+
const role = options.role ?? "authenticated";
|
|
21
|
+
const claims = { sub, role, aud: role, iat: now, exp: now + (options.expiresInSeconds ?? 3600) };
|
|
22
|
+
const encode = (bytes) => btoa(String.fromCharCode(...bytes)).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
23
|
+
const text = (value) => encode(new TextEncoder().encode(JSON.stringify(value)));
|
|
24
|
+
const body = `${text({ alg: "HS256", typ: "JWT" })}.${text(claims)}`;
|
|
25
|
+
const key = await crypto.subtle.importKey(
|
|
26
|
+
"raw",
|
|
27
|
+
new TextEncoder().encode(options.secret),
|
|
28
|
+
{ name: "HMAC", hash: "SHA-256" },
|
|
29
|
+
false,
|
|
30
|
+
["sign"]
|
|
31
|
+
);
|
|
32
|
+
const signature = await crypto.subtle.sign("HMAC", key, new TextEncoder().encode(body));
|
|
33
|
+
return `${body}.${encode(new Uint8Array(signature))}`;
|
|
34
|
+
}
|
|
35
|
+
var RAW_TEXT = /violates|constraint|duplicate key|row-level security|permission denied for|relation "|syntax error|null value in column|\b(?:42501|42P01|42703|23505|23503|23502|23514|22P02|P0001|PGRST[0-9]{3})\b/i;
|
|
36
|
+
function expectPlainMessage(error) {
|
|
37
|
+
const message = error instanceof Error ? error.message : error && typeof error === "object" && typeof error.message === "string" ? error.message : typeof error === "string" ? error : "";
|
|
38
|
+
if (!message.trim()) throw new ContractError("the error has no message to show");
|
|
39
|
+
if (RAW_TEXT.test(message)) throw new ContractError(`the message shows raw database text: ${message}`);
|
|
40
|
+
}
|
|
41
|
+
var REFUSAL_CODES = /* @__PURE__ */ new Set(["42501", "P0001"]);
|
|
42
|
+
function isRefusal(error) {
|
|
43
|
+
if (!isDataWriteError(error)) return false;
|
|
44
|
+
if (error.code !== void 0 && REFUSAL_CODES.has(error.code)) return true;
|
|
45
|
+
return error.outcome === "forbidden" || error.outcome === "unauthenticated";
|
|
46
|
+
}
|
|
47
|
+
var describeError = (error) => isDataWriteError(error) || isDataReadError(error) ? `${error.outcome}${error.code ? ` (${error.code})` : ""}: ${error.message}` : String(error);
|
|
48
|
+
function changedARow(result) {
|
|
49
|
+
if (!result || typeof result !== "object") return false;
|
|
50
|
+
const r = result;
|
|
51
|
+
if (r.error !== void 0 && r.error !== null) return false;
|
|
52
|
+
if (Array.isArray(r.data)) return r.data.length > 0;
|
|
53
|
+
return r.data !== null && typeof r.data === "object";
|
|
54
|
+
}
|
|
55
|
+
async function expectRefused(write, options = {}) {
|
|
56
|
+
if (typeof write !== "function") void write.catch(() => void 0);
|
|
57
|
+
let attempt;
|
|
58
|
+
let control;
|
|
59
|
+
if (typeof write === "function") {
|
|
60
|
+
if (!options.as) throw new ContractError("pass `as`: the provider that should be refused");
|
|
61
|
+
const by = options.control;
|
|
62
|
+
if (by !== void 0 && typeof by === "function") {
|
|
63
|
+
throw new ContractError("with a write function, `control` is a provider that runs the same write");
|
|
64
|
+
}
|
|
65
|
+
attempt = write(options.as);
|
|
66
|
+
control = by ? () => write(by) : void 0;
|
|
67
|
+
} else {
|
|
68
|
+
attempt = write;
|
|
69
|
+
if (options.control !== void 0 && typeof options.control !== "function") {
|
|
70
|
+
throw new ContractError("with a write promise, `control` is a function making the same write");
|
|
71
|
+
}
|
|
72
|
+
control = options.control;
|
|
73
|
+
}
|
|
74
|
+
let result;
|
|
75
|
+
try {
|
|
76
|
+
result = await attempt;
|
|
77
|
+
} catch (error) {
|
|
78
|
+
if (isRefusal(error)) {
|
|
79
|
+
expectPlainMessage(error);
|
|
80
|
+
return error;
|
|
81
|
+
}
|
|
82
|
+
if (isDataWriteError(error) && error.outcome === "gone") {
|
|
83
|
+
if (!control) {
|
|
84
|
+
throw new ContractError(
|
|
85
|
+
`it reached no row (${error.message}); pass a control that can make the same write, or it could be a wrong id`
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
let controlResult;
|
|
89
|
+
try {
|
|
90
|
+
controlResult = await control();
|
|
91
|
+
} catch (controlError) {
|
|
92
|
+
throw new ContractError(`the control failed too (${describeError(controlError)}): nothing was refused`);
|
|
93
|
+
}
|
|
94
|
+
if (!changedARow(controlResult)) {
|
|
95
|
+
throw new ContractError(
|
|
96
|
+
`the control changed no row (${JSON.stringify(controlResult)?.slice(0, 200)}): nothing was refused`
|
|
97
|
+
);
|
|
98
|
+
}
|
|
99
|
+
expectPlainMessage(error);
|
|
100
|
+
return error;
|
|
101
|
+
}
|
|
102
|
+
throw new ContractError(`it failed, but not as a refusal: ${describeError(error)}`);
|
|
103
|
+
}
|
|
104
|
+
throw new ContractError(`it was allowed: ${JSON.stringify(result)?.slice(0, 300)}`);
|
|
105
|
+
}
|
|
106
|
+
async function expectAllowed(write) {
|
|
107
|
+
try {
|
|
108
|
+
return await write;
|
|
109
|
+
} catch (error) {
|
|
110
|
+
throw new ContractError(`it was refused: ${describeError(error)}`);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
var stable = (value) => JSON.stringify(
|
|
114
|
+
value,
|
|
115
|
+
(_key, v) => v && typeof v === "object" && !Array.isArray(v) ? Object.fromEntries(Object.entries(v).sort(([a], [b]) => a < b ? -1 : 1)) : v
|
|
116
|
+
);
|
|
117
|
+
async function expectServerOwned(args) {
|
|
118
|
+
const { as, system, resource, id, field, value } = args;
|
|
119
|
+
const read = async () => {
|
|
120
|
+
const row = (await system.getOne(resource, { id })).data;
|
|
121
|
+
if (!row || !(field in row)) throw new ContractError(`${resource} ${String(id)} has no field ${field}`);
|
|
122
|
+
return row[field];
|
|
123
|
+
};
|
|
124
|
+
const before = await read();
|
|
125
|
+
if (stable(before) === stable(value)) {
|
|
126
|
+
throw new ContractError(`${field} is already ${stable(value)}: try a different value`);
|
|
127
|
+
}
|
|
128
|
+
const set = async (to, what) => {
|
|
129
|
+
try {
|
|
130
|
+
await system.update(resource, { id, data: { [field]: to } });
|
|
131
|
+
} catch (error) {
|
|
132
|
+
throw new ContractError(`the system couldn't ${what} ${field} (${describeError(error)}): nothing was tested`);
|
|
133
|
+
}
|
|
134
|
+
};
|
|
135
|
+
await set(value, "set");
|
|
136
|
+
const changed = await read();
|
|
137
|
+
await set(before, "put back");
|
|
138
|
+
if (stable(changed) === stable(before)) {
|
|
139
|
+
throw new ContractError(`the system couldn't change ${field} either: nothing was tested`);
|
|
140
|
+
}
|
|
141
|
+
if (stable(await read()) !== stable(before)) {
|
|
142
|
+
throw new ContractError(`the system couldn't put ${field} back to ${stable(before)}`);
|
|
143
|
+
}
|
|
144
|
+
try {
|
|
145
|
+
await as.update(resource, { id, data: { [field]: value } });
|
|
146
|
+
} catch (error) {
|
|
147
|
+
if (!isRefusal(error) && !(isDataWriteError(error) && error.outcome === "gone")) {
|
|
148
|
+
throw new ContractError(`setting ${field} failed, but not as a refusal: ${describeError(error)}`);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
const after = await read();
|
|
152
|
+
if (stable(after) !== stable(before)) {
|
|
153
|
+
await system.update(resource, { id, data: { [field]: before } }).catch(() => void 0);
|
|
154
|
+
throw new ContractError(`${resource}.${field} changed from ${stable(before)} to ${stable(after)}`);
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
async function expectNeverShows(read, marker) {
|
|
158
|
+
if (!marker) throw new ContractError("give a marker to look for");
|
|
159
|
+
let result;
|
|
160
|
+
try {
|
|
161
|
+
result = await read;
|
|
162
|
+
} catch (error) {
|
|
163
|
+
const refused = (isDataReadError(error) || isDataWriteError(error)) && (error.code !== void 0 && REFUSAL_CODES.has(error.code) || error.outcome === "forbidden" || error.outcome === "unauthenticated");
|
|
164
|
+
if (refused) return;
|
|
165
|
+
throw new ContractError(`the read failed: ${describeError(error)}`);
|
|
166
|
+
}
|
|
167
|
+
if (result === void 0) throw new ContractError("the read returned nothing to look through");
|
|
168
|
+
if (result && typeof result === "object" && "error" in result && result.error != null) {
|
|
169
|
+
throw new ContractError(`the read failed: ${JSON.stringify(result.error)?.slice(0, 200)}`);
|
|
170
|
+
}
|
|
171
|
+
const text = JSON.stringify(result) ?? "";
|
|
172
|
+
const escaped = JSON.stringify(marker).slice(1, -1);
|
|
173
|
+
if (text.includes(marker) || text.includes(escaped)) {
|
|
174
|
+
throw new ContractError(`"${marker}" appears in: ${text.slice(0, 300)}`);
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
async function expectSees(read, expected) {
|
|
178
|
+
let result;
|
|
179
|
+
try {
|
|
180
|
+
result = await read;
|
|
181
|
+
} catch (error) {
|
|
182
|
+
throw new ContractError(`the read failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
183
|
+
}
|
|
184
|
+
const rows = Array.isArray(result) ? result : result && typeof result === "object" && Array.isArray(result.data) ? result.data : void 0;
|
|
185
|
+
if (!rows) throw new ContractError(`the read returned no rows to count: ${JSON.stringify(result)?.slice(0, 300)}`);
|
|
186
|
+
if (rows.length !== expected) throw new ContractError(`saw ${rows.length} row(s), expected ${expected}`);
|
|
187
|
+
}
|
|
188
|
+
async function expectBinned(args) {
|
|
189
|
+
const { as, resource, id, inBin } = args;
|
|
190
|
+
try {
|
|
191
|
+
await as.getOne(resource, { id });
|
|
192
|
+
} catch (error) {
|
|
193
|
+
throw new ContractError(`${resource} ${String(id)} isn't visible before the delete: ${describeError(error)}`);
|
|
194
|
+
}
|
|
195
|
+
await expectAllowed(as.deleteOne(resource, { id }));
|
|
196
|
+
try {
|
|
197
|
+
await as.getOne(resource, { id });
|
|
198
|
+
} catch (error) {
|
|
199
|
+
if (!isDataReadError(error) || error.outcome !== "gone" && error.outcome !== "forbidden") {
|
|
200
|
+
throw new ContractError(`reading it back failed: ${describeError(error)}`);
|
|
201
|
+
}
|
|
202
|
+
if (!await inBin()) throw new ContractError(`${resource} ${String(id)} was deleted for good, not binned`);
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
throw new ContractError(`${resource} ${String(id)} is still visible after the delete`);
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
export { ContractError, FIXTURE_USERS, expectAllowed, expectBinned, expectNeverShows, expectPlainMessage, expectRefused, expectSees, expectServerOwned, fixtureAccessToken, isRefusal };
|
|
209
|
+
//# sourceMappingURL=index.js.map
|
|
210
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/testing/index.ts"],"names":[],"mappings":";;;;AAmBO,IAAM,aAAA,GAAgB;AAAA,EAC3B,KAAA,EAAO,sCAAA;AAAA,EACP,KAAA,EAAO,sCAAA;AAAA,EACP,MAAA,EAAQ,sCAAA;AAAA,EACR,QAAA,EAAU;AACZ;AAKO,IAAM,aAAA,GAAN,cAA4B,KAAA,CAAM;AAAA,EACvC,YAAY,OAAA,EAAiB;AAC3B,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,eAAA;AAAA,EACd;AACF;AAQA,eAAsB,kBAAA,CACpB,MACA,OAAA,EACiB;AACjB,EAAA,MAAM,GAAA,GAAM,OAAO,MAAA,CAAO,aAAA,EAAe,IAAI,CAAA,GAAI,aAAA,CAAc,IAAmB,CAAA,GAAI,IAAA;AACtF,EAAA,MAAM,MAAM,IAAA,CAAK,KAAA,CAAM,IAAA,CAAK,GAAA,KAAQ,GAAI,CAAA;AACxC,EAAA,MAAM,IAAA,GAAO,QAAQ,IAAA,IAAQ,eAAA;AAC7B,EAAA,MAAM,MAAA,GAAS,EAAE,GAAA,EAAK,IAAA,EAAM,GAAA,EAAK,IAAA,EAAM,GAAA,EAAK,GAAA,EAAK,GAAA,EAAK,GAAA,IAAO,OAAA,CAAQ,gBAAA,IAAoB,IAAA,CAAA,EAAM;AAC/F,EAAA,MAAM,MAAA,GAAS,CAAC,KAAA,KACd,IAAA,CAAK,OAAO,YAAA,CAAa,GAAG,KAAK,CAAC,CAAA,CAAE,QAAQ,KAAA,EAAO,GAAG,EAAE,OAAA,CAAQ,KAAA,EAAO,GAAG,CAAA,CAAE,OAAA,CAAQ,OAAO,EAAE,CAAA;AAC/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AAC,CAAA,kCAAA,CAAoC,CAAA;AACvF","file":"index.js","sourcesContent":["// ---------------------------------------------------------------------------\n// Contract test kit (README \"Test your data contract\")\n//\n// Checks an app's own provider keeps the Genesis data rules, run against the\n// app's real schema (a local Supabase in CI): a write the user may not make is\n// refused in plain words, a column only the server sets stays as it was, a\n// private value never shows, a binned delete keeps the row. The pgTAP half is\n// genesis-supabase's `genesis_testing`; both use the same fixture people.\n//\n// Every check passes only on evidence and throws a ContractError otherwise, so\n// it works in vitest, jest or node:test alike. A wrong resource, a missing row\n// or a typo fails the check instead of passing it.\n// ---------------------------------------------------------------------------\n\nimport type { BaseRecord, DataProvider, Identifier } from \"../provider/types\";\nimport { isDataReadError } from \"../schema/read-outcome\";\nimport { isDataWriteError, type DataWriteError } from \"../schema/write-outcome\";\n\n/** The shared fixture logins, the same ids `genesis_testing.user_id()` uses. */\nexport const FIXTURE_USERS = {\n owner: \"00000000-0000-4000-8000-000000000001\",\n staff: \"00000000-0000-4000-8000-000000000002\",\n client: \"00000000-0000-4000-8000-000000000003\",\n stranger: \"00000000-0000-4000-8000-000000000004\",\n} as const;\n\nexport type FixtureUser = keyof typeof FIXTURE_USERS;\n\n/** A broken contract: the message says what happened instead. */\nexport class ContractError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ContractError\";\n }\n}\n\n/**\n * A signed access token for a fixture person (or any user id), for a test\n * database's legacy JWT secret. Hand it to the client as\n * `Authorization: Bearer <token>`; `auth.uid()` then reads that user. Test\n * databases only: never give it a production secret.\n */\nexport async function fixtureAccessToken(\n user: FixtureUser | string,\n options: { secret: string; expiresInSeconds?: number; role?: string },\n): Promise<string> {\n const sub = Object.hasOwn(FIXTURE_USERS, user) ? FIXTURE_USERS[user as FixtureUser] : user;\n const now = Math.floor(Date.now() / 1000);\n const role = options.role ?? \"authenticated\";\n const claims = { sub, role, aud: role, iat: now, exp: now + (options.expiresInSeconds ?? 3600) };\n const encode = (bytes: Uint8Array) =>\n btoa(String.fromCharCode(...bytes)).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n const text = (value: unknown) => encode(new TextEncoder().encode(JSON.stringify(value)));\n const body = `${text({ alg: \"HS256\", typ: \"JWT\" })}.${text(claims)}`;\n const key = await crypto.subtle.importKey(\n \"raw\",\n new TextEncoder().encode(options.secret),\n { name: \"HMAC\", hash: \"SHA-256\" },\n false,\n [\"sign\"],\n );\n const signature = await crypto.subtle.sign(\"HMAC\", key, new TextEncoder().encode(body));\n return `${body}.${encode(new Uint8Array(signature))}`;\n}\n\n/** Raw database text that must never reach a person. */\nconst RAW_TEXT =\n /violates|constraint|duplicate key|row-level security|permission denied for|relation \"|syntax error|null value in column|\\b(?:42501|42P01|42703|23505|23503|23502|23514|22P02|P0001|PGRST[0-9]{3})\\b/i;\n\n/** The error's message is plain words: no raw database text or error codes. */\nexport function expectPlainMessage(error: unknown): void {\n const message =\n error instanceof Error\n ? error.message\n : error && typeof error === \"object\" && typeof (error as { message?: unknown }).message === \"string\"\n ? (error as { message: string }).message\n : typeof error === \"string\"\n ? error\n : \"\";\n if (!message.trim()) throw new ContractError(\"the error has no message to show\");\n if (RAW_TEXT.test(message)) throw new ContractError(`the message shows raw database text: ${message}`);\n}\n\n/** Codes that are refusals: insufficient privilege (RLS, grants) and a guard's `raise exception`. */\nconst REFUSAL_CODES = new Set([\"42501\", \"P0001\"]);\n\n/**\n * Whether a failed write is a refusal: a refusal code (42501, P0001), or the\n * provider's own `forbidden` (the row is still visible but unchanged) or\n * `unauthenticated`. `gone` is not: it also means the id matched nothing.\n */\nexport function isRefusal(error: unknown): error is DataWriteError {\n if (!isDataWriteError(error)) return false;\n if (error.code !== undefined && REFUSAL_CODES.has(error.code)) return true;\n return error.outcome === \"forbidden\" || error.outcome === \"unauthenticated\";\n}\n\nconst describeError = (error: unknown) =>\n isDataWriteError(error) || isDataReadError(error)\n ? `${error.outcome}${error.code ? ` (${error.code})` : \"\"}: ${error.message}`\n : String(error);\n\n/** Whether a write's result shows a row it changed: `{ data: row }` or a non-empty `data` list, with no `error`. */\nfunction changedARow(result: unknown): boolean {\n if (!result || typeof result !== \"object\") return false;\n const r = result as { data?: unknown; error?: unknown };\n if (r.error !== undefined && r.error !== null) return false;\n if (Array.isArray(r.data)) return r.data.length > 0;\n return r.data !== null && typeof r.data === \"object\";\n}\n\nexport interface ExpectRefusedOptions {\n /** With a write function: who tries it (and must be refused). */\n as?: DataProvider;\n /**\n * Proof a write that reached no row (`gone`) was refused, not mistyped.\n * With a write function: a provider for someone who may make it, which runs\n * the same function. With a promise: a function making the same write as\n * that someone. Either way it must resolve with the row it changed. Its\n * write is real: run the check on test data.\n */\n control?: DataProvider | (() => Promise<unknown>);\n}\n\n/**\n * The write is refused, in plain words: a refusal code (42501, P0001) or the\n * provider's `forbidden` / `unauthenticated`. A write that reaches no row\n * (`gone`) counts only with a `control` that makes the same write and changes\n * a row, so a typo'd id or resource can't pass. Pass the write as a function\n * of a provider (with `as` and a control provider) to run exactly the same\n * write both ways. Returns the refusal for more checks.\n *\n * ```ts\n * await expectRefused((p) => p.update(\"tasks\", { id, data: { title: \"x\" } }), { as: stranger, control: owner });\n * ```\n */\nexport async function expectRefused(\n write: Promise<unknown> | ((provider: DataProvider) => Promise<unknown>),\n options: ExpectRefusedOptions = {},\n): Promise<DataWriteError> {\n // A write promise may reject before an argument check below throws: mark it handled now\n // (awaiting it later still sees the rejection).\n if (typeof write !== \"function\") void write.catch(() => undefined);\n let attempt: Promise<unknown>;\n let control: (() => Promise<unknown>) | undefined;\n if (typeof write === \"function\") {\n if (!options.as) throw new ContractError(\"pass `as`: the provider that should be refused\");\n const by = options.control;\n if (by !== undefined && typeof by === \"function\") {\n throw new ContractError(\"with a write function, `control` is a provider that runs the same write\");\n }\n attempt = write(options.as);\n control = by ? () => write(by) : undefined;\n } else {\n attempt = write;\n if (options.control !== undefined && typeof options.control !== \"function\") {\n throw new ContractError(\"with a write promise, `control` is a function making the same write\");\n }\n control = options.control;\n }\n let result: unknown;\n try {\n result = await attempt;\n } catch (error) {\n if (isRefusal(error)) {\n expectPlainMessage(error);\n return error;\n }\n if (isDataWriteError(error) && error.outcome === \"gone\") {\n if (!control) {\n throw new ContractError(\n `it reached no row (${error.message}); pass a control that can make the same write, or it could be a wrong id`,\n );\n }\n let controlResult: unknown;\n try {\n controlResult = await control();\n } catch (controlError) {\n throw new ContractError(`the control failed too (${describeError(controlError)}): nothing was refused`);\n }\n if (!changedARow(controlResult)) {\n throw new ContractError(\n `the control changed no row (${JSON.stringify(controlResult)?.slice(0, 200)}): nothing was refused`,\n );\n }\n expectPlainMessage(error);\n return error;\n }\n throw new ContractError(`it failed, but not as a refusal: ${describeError(error)}`);\n }\n throw new ContractError(`it was allowed: ${JSON.stringify(result)?.slice(0, 300)}`);\n}\n\n/** The write succeeds. Returns what it resolved to. */\nexport async function expectAllowed<T>(write: Promise<T>): Promise<T> {\n try {\n return await write;\n } catch (error) {\n throw new ContractError(`it was refused: ${describeError(error)}`);\n }\n}\n\nconst stable = (value: unknown) =>\n JSON.stringify(value, (_key, v: unknown) =>\n v && typeof v === \"object\" && !Array.isArray(v)\n ? Object.fromEntries(Object.entries(v as Record<string, unknown>).sort(([a], [b]) => (a < b ? -1 : 1)))\n : v,\n );\n\n/**\n * A client can't change a column only the server sets. First `system` (the\n * service role, or whoever the server writes as) sets `field` to `value` and\n * must change the stored value, then puts it back: that proves the row exists\n * and the value can change at all. Then `as` tries the same update, and the\n * stored value must stay as it was, whether the update was refused, reached\n * no row, or a trigger put the value back. Any other error fails.\n */\nexport async function expectServerOwned(args: {\n as: DataProvider;\n system: DataProvider;\n resource: string;\n id: Identifier;\n field: string;\n value: unknown;\n}): Promise<void> {\n const { as, system, resource, id, field, value } = args;\n const read = async () => {\n const row = (await system.getOne<BaseRecord>(resource, { id })).data;\n if (!row || !(field in row)) throw new ContractError(`${resource} ${String(id)} has no field ${field}`);\n return row[field];\n };\n const before = await read();\n if (stable(before) === stable(value)) {\n throw new ContractError(`${field} is already ${stable(value)}: try a different value`);\n }\n const set = async (to: unknown, what: string) => {\n try {\n await system.update(resource, { id, data: { [field]: to } });\n } catch (error) {\n throw new ContractError(`the system couldn't ${what} ${field} (${describeError(error)}): nothing was tested`);\n }\n };\n await set(value, \"set\");\n const changed = await read();\n await set(before, \"put back\");\n if (stable(changed) === stable(before)) {\n throw new ContractError(`the system couldn't change ${field} either: nothing was tested`);\n }\n if (stable(await read()) !== stable(before)) {\n throw new ContractError(`the system couldn't put ${field} back to ${stable(before)}`);\n }\n try {\n await as.update(resource, { id, data: { [field]: value } });\n } catch (error) {\n if (!isRefusal(error) && !(isDataWriteError(error) && error.outcome === \"gone\")) {\n throw new ContractError(`setting ${field} failed, but not as a refusal: ${describeError(error)}`);\n }\n }\n const after = await read();\n if (stable(after) !== stable(before)) {\n // Put the value back, so a failed check doesn't change what the next one sees.\n await system.update(resource, { id, data: { [field]: before } }).catch(() => undefined);\n throw new ContractError(`${resource}.${field} changed from ${stable(before)} to ${stable(after)}`);\n }\n}\n\n/**\n * `marker` (a value only a private row holds) appears nowhere in what the read\n * returns: use a list or report read that returns the rows around the private\n * one. A refused read (42501, or `forbidden` / `unauthenticated`) shows\n * nothing and passes; any other failure fails, `gone` included, so a wrong id\n * or a broken query can't pass.\n */\nexport async function expectNeverShows(read: Promise<unknown>, marker: string): Promise<void> {\n if (!marker) throw new ContractError(\"give a marker to look for\");\n let result: unknown;\n try {\n result = await read;\n } catch (error) {\n const refused =\n (isDataReadError(error) || isDataWriteError(error)) &&\n ((error.code !== undefined && REFUSAL_CODES.has(error.code)) ||\n error.outcome === \"forbidden\" ||\n error.outcome === \"unauthenticated\");\n if (refused) return;\n throw new ContractError(`the read failed: ${describeError(error)}`);\n }\n if (result === undefined) throw new ContractError(\"the read returned nothing to look through\");\n if (result && typeof result === \"object\" && \"error\" in result && (result as { error: unknown }).error != null) {\n throw new ContractError(`the read failed: ${JSON.stringify((result as { error: unknown }).error)?.slice(0, 200)}`);\n }\n const text = JSON.stringify(result) ?? \"\";\n const escaped = JSON.stringify(marker).slice(1, -1);\n if (text.includes(marker) || text.includes(escaped)) {\n throw new ContractError(`\"${marker}\" appears in: ${text.slice(0, 300)}`);\n }\n}\n\n/** The read returns exactly `expected` rows (a list result, a getMany result or an array). */\nexport async function expectSees(read: Promise<unknown>, expected: number): Promise<void> {\n let result: unknown;\n try {\n result = await read;\n } catch (error) {\n throw new ContractError(`the read failed: ${error instanceof Error ? error.message : String(error)}`);\n }\n const rows = Array.isArray(result)\n ? result\n : result && typeof result === \"object\" && Array.isArray((result as { data?: unknown }).data)\n ? (result as { data: unknown[] }).data\n : undefined;\n if (!rows) throw new ContractError(`the read returned no rows to count: ${JSON.stringify(result)?.slice(0, 300)}`);\n if (rows.length !== expected) throw new ContractError(`saw ${rows.length} row(s), expected ${expected}`);\n}\n\n/**\n * A delete on a recycle-bin table moves the row to the bin: `as` deletes it,\n * can no longer read it (gone or forbidden), and `inBin` (a check with the\n * service role or a bin query) confirms the row is still stored.\n */\nexport async function expectBinned(args: {\n as: DataProvider;\n resource: string;\n id: Identifier;\n inBin: () => Promise<boolean>;\n}): Promise<void> {\n const { as, resource, id, inBin } = args;\n // Visible first, so \"can't read it back\" is evidence of the delete.\n try {\n await as.getOne(resource, { id });\n } catch (error) {\n throw new ContractError(`${resource} ${String(id)} isn't visible before the delete: ${describeError(error)}`);\n }\n await expectAllowed(as.deleteOne(resource, { id }));\n try {\n await as.getOne(resource, { id });\n } catch (error) {\n if (!isDataReadError(error) || (error.outcome !== \"gone\" && error.outcome !== \"forbidden\")) {\n throw new ContractError(`reading it back failed: ${describeError(error)}`);\n }\n if (!(await inBin())) throw new ContractError(`${resource} ${String(id)} was deleted for good, not binned`);\n return;\n }\n throw new ContractError(`${resource} ${String(id)} is still visible after the delete`);\n}\n"]}
|
|
@@ -59,33 +59,4 @@ declare class DataWriteError extends Error {
|
|
|
59
59
|
*/
|
|
60
60
|
declare function isDataWriteError(error: unknown): error is DataWriteError;
|
|
61
61
|
|
|
62
|
-
|
|
63
|
-
* - `unauthenticated`: no signed-in user, or the session expired.
|
|
64
|
-
* - `forbidden`: this user may not read these records.
|
|
65
|
-
* - `gone`: the one record asked for doesn't exist, or isn't visible.
|
|
66
|
-
* - `invalid`: the request itself was wrong (an unknown column, a bad value).
|
|
67
|
-
* - `error`: anything else.
|
|
68
|
-
*/
|
|
69
|
-
type ReadOutcome = "unauthenticated" | "forbidden" | "gone" | "invalid" | "error";
|
|
70
|
-
interface DataReadErrorOptions {
|
|
71
|
-
/** The store's own error code (a Postgres SQLSTATE or PostgREST code). */
|
|
72
|
-
code?: string;
|
|
73
|
-
/** The underlying error, with its raw text, kept for logging. */
|
|
74
|
-
cause?: unknown;
|
|
75
|
-
}
|
|
76
|
-
/** Thrown by a provider when a read failed. Its `message` is safe to show. */
|
|
77
|
-
declare class DataReadError extends Error {
|
|
78
|
-
readonly outcome: ReadOutcome;
|
|
79
|
-
/** The store's own error code, when it gave one. */
|
|
80
|
-
readonly code?: string;
|
|
81
|
-
constructor(outcome: ReadOutcome, message: string, options?: DataReadErrorOptions);
|
|
82
|
-
}
|
|
83
|
-
/**
|
|
84
|
-
* `instanceof` fails when two copies of this package are installed, so check
|
|
85
|
-
* the shape instead.
|
|
86
|
-
*/
|
|
87
|
-
declare function isDataReadError(error: unknown): error is DataReadError;
|
|
88
|
-
/** The plain sentence for a failed read of `noun` records (one, or a list). */
|
|
89
|
-
declare function readFailureMessage(outcome: ReadOutcome, noun: string, one: boolean, plural?: string): string;
|
|
90
|
-
|
|
91
|
-
export { DataReadError as D, type ReadOutcome as R, type WriteOutcome as W, type DataReadErrorOptions as a, DataWriteError as b, type DataWriteErrorOptions as c, isDataWriteError as d, isDataReadError as i, readFailureMessage as r };
|
|
62
|
+
export { DataWriteError as D, type WriteOutcome as W, type DataWriteErrorOptions as a, isDataWriteError as i };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@marktiderman/genesis-core",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.11.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -51,6 +51,10 @@
|
|
|
51
51
|
"types": "./dist/navigation.d.ts",
|
|
52
52
|
"import": "./dist/navigation.js"
|
|
53
53
|
},
|
|
54
|
+
"./testing": {
|
|
55
|
+
"types": "./dist/testing/index.d.ts",
|
|
56
|
+
"import": "./dist/testing/index.js"
|
|
57
|
+
},
|
|
54
58
|
"./dates": {
|
|
55
59
|
"types": "./dist/dates.d.ts",
|
|
56
60
|
"import": "./dist/dates.js"
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/provider/postgrest-errors.ts","../src/provider/supabase-provider.ts","../src/provider/write-helpers.ts"],"names":["ties","run","from"],"mappings":";;;;;AAiBO,SAAS,oBAAoB,IAAA,EAA8C;AAChF,EAAA,IAAI,CAAC,MAAM,OAAO,OAAA;AAClB,EAAA,IAAI,IAAA,KAAS,WAAW,IAAA,KAAS,OAAA,IAAY,eAAe,IAAA,CAAK,IAAI,CAAA,IAAK,IAAA,KAAS,UAAA,EAAa;AAC9F,IAAA,OAAO,SAAA;AAAA,EACT;AACA,EAAA,MAAM,KAAA,GAAQ,qBAAqB,IAAI,CAAA;AACvC,EAAA,OAAO,KAAA,KAAU,eAAe,KAAA,KAAU,MAAA,IAAU,UAAU,iBAAA,IAAqB,KAAA,KAAU,YACzF,KAAA,GACA,OAAA;AACN;AAiBO,SAAS,qBAAqB,IAAA,EAA+C;AAClF,EAAA,IAAI,CAAC,MAAM,OAAO,OAAA;AAClB,EAAA,IAAI,IAAA,KAAS,SAAS,OAAO,WAAA;AAC7B,EAAA,IAAI,IAAA,KAAS,YAAY,OAAO,MAAA;AAChC,EAAA,IAAI,SAAS,UAAA,IAAc,IAAA,KAAS,UAAA,IAAc,IAAA,KAAS,YAAY,OAAO,iBAAA;AAC9E,EAAA,IAAI,IAAA,KAAS,O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AA,EAAO,UAAU,SAAA,EAAU;AAC/E,MAAA,IAAI,OAAO,UAAU,QAAA,IAAY,OAAO,UAAU,QAAA,IAAY,OAAO,UAAU,SAAA,EAAW;AACxF,QAAA,MAAM,IAAI,KAAA,CAAM,CAAA,8BAAA,EAAiC,QAAQ,CAAA,aAAA,EAAgB,KAAK,CAAA,oCAAA,CAAsC,CAAA;AAAA,MACtH;AACA,MAAA,OAAO,EAAE,KAAA,EAAO,QAAA,EAAU,IAAA,EAAM,KAAA,EAAM;AAAA,IACxC,CAAC,CAAA;AACD,IAAA,MAAM,EAAE,IAAA,EAAM,IAAA,EAAK,GAAI,MAAM,SAAS,OAAA,CAAW,QAAA,EAAU,EAAE,OAAA,EAAS,YAAY,EAAE,IAAA,EAAM,GAAG,OAAA,EAAS,CAAA,IAAK,CAAA;AAC3G,IAAA,IAAI,IAAA,CAAK,MAAA,KAAW,CAAA,EAAG,MAAM,KAAA;AAC7B,IAAA,MAAM,QAAA,GAAW,KAAK,CAAC,CAAA;AACvB,IAAA,MAAM,OAAA,GAAU,OAAA,CAAQ,KAAA,GAAQ,QAAQ,CAAA;AACxC,IAAA,IAAI,CAAC,OAAA,IAAW,MAAA,CAAO,IAAA,CAAK,OAAO,CAAA,CAAE,MAAA,KAAW,CAAA,EAAG,OAAO,EAAE,GAAA,EAAK,QAAA,EAAU,SAAS,IAAA,EAAK;AACzF,IAAA,OAAO,EAAE,GAAA,EAAA,CAAM,MAAM,QAAA,CAAS,MAAA,CAAU,UAAU,EAAE,EAAA,EAAI,QAAA,CAAS,EAAA,EAAI,MAAM,OAAA,EAAS,CAAA,EAAG,IAAA,EAAM,SAAS,IAAA,EAAK;AAAA,EAC7G;AACF","file":"chunk-EF5BKT4B.js","sourcesContent":["// ---------------------------------------------------------------------------\n// Postgres / PostgREST error codes → Genesis write outcomes\n// ---------------------------------------------------------------------------\n\nimport {\n DataWriteError,\n isDataWriteError,\n type WriteOutcome,\n} from \"../schema/write-outcome\";\nimport type { ReadOutcome } from \"../schema/read-outcome\";\nimport { titleCase } from \"../utils\";\n\n/**\n * Maps a store error code to the read outcome it means: the write mapping,\n * with `22***` and PostgREST request errors (`PGRST1**` other than PGRST116,\n * `42703` unknown column, `42P01` unknown table) read as `invalid`.\n */\nexport function readOutcomeFromCode(code: string | null | undefined): ReadOutcome {\n if (!code) return \"error\";\n if (code === \"42703\" || code === \"42P01\" || (/^PGRST1\\d\\d$/.test(code) && code !== \"PGRST116\")) {\n return \"invalid\";\n }\n const write = writeOutcomeFromCode(code);\n return write === \"forbidden\" || write === \"gone\" || write === \"unauthenticated\" || write === \"invalid\"\n ? write\n : \"error\";\n}\n\n/**\n * Maps a Postgres SQLSTATE or PostgREST error code to the write outcome it\n * means. Anything not listed is `error`: a code is only read as a refusal or\n * a bad value when it says so.\n *\n * - `42501` (insufficient privilege, including \"new row violates row-level\n * security policy\") → `forbidden`\n * - `23505` (unique violation) → `duplicate`\n * - `22***` (data exception: bad type, out of range) and the other `23***`\n * (integrity constraint: `23503` foreign key, `23502` not null, `23514`\n * check) → `invalid`\n * - `PGRST301`–`PGRST303` (JWT missing, expired or rejected), `28000`,\n * `28P01` → `unauthenticated`\n * - `PGRST116` (one row was asked for and none came back) → `gone`\n */\nexport function writeOutcomeFromCode(code: string | null | undefined): WriteOutcome {\n if (!code) return \"error\";\n if (code === \"42501\") return \"forbidden\";\n if (code === \"PGRST116\") return \"gone\";\n if (code === \"PGRST301\" || code === \"PGRST302\" || code === \"PGRST303\") return \"unauthenticated\";\n if (code === \"28000\" || code === \"28P01\") return \"unauthenticated\";\n if (code === \"23505\") return \"duplicate\";\n if (/^2[23][0-9A-Z]{3}$/.test(code)) return \"invalid\";\n return \"error\";\n}\n\n/** A column name as Postgres reports it unquoted; anything else is not mapped. */\nconst COLUMN = /^[A-Za-z_][A-Za-z0-9_]*$/;\n\n/**\n * One index expression as Postgres prints it: a plain column, or one column\n * wrapped in a function, optionally cast (`lower(email::text)`,\n * `lower((email)::text)`). Anything else is not mapped.\n */\nconst WRAPPED_COLUMN = /^[A-Za-z_][A-Za-z0-9_]*\\(\\(?([A-Za-z_][A-Za-z0-9_]*)\\)?(?:::[A-Za-z_][A-Za-z0-9_ ]*)?\\)$/;\n\nfunction columnOf(expression: string): string | undefined {\n if (COLUMN.test(expression)) return expression;\n return WRAPPED_COLUMN.exec(expression)?.[1];\n}\n\n/**\n * The columns of a `Key (a, b)=(...)` detail line, or none when any is not a\n * plain column (or one column in a simple expression index). The key list is\n * read with its parentheses balanced, so an expression index such as\n * `Key (lower(email::text))=(…)` is recognised.\n */\nfunction keyColumns(details: string, tail: RegExp): string[] {\n if (!details.startsWith(\"Key (\") || !tail.test(details)) return [];\n let depth = 1;\n let end = -1;\n for (let i = \"Key (\".length; i < details.length; i++) {\n const ch = details[i];\n if (ch === \"(\") depth++;\n else if (ch === \")\" && --depth === 0) {\n end = i;\n break;\n }\n }\n if (end < 0 || details.slice(end + 1, end + 3) !== \"=(\") return [];\n const parts: string[] = [];\n let level = 0;\n let current = \"\";\n for (const ch of details.slice(\"Key (\".length, end)) {\n if (ch === \"(\") level++;\n else if (ch === \")\") level--;\n if (ch === \",\" && level === 0) {\n parts.push(current.trim());\n current = \"\";\n } else {\n current += ch;\n }\n }\n parts.push(current.trim());\n const columns = parts.map(columnOf);\n return columns.length > 0 && columns.every((c): c is string => !!c) ? columns : [];\n}\n\nfunction listLabels(columns: string[]): string {\n const labels = columns.map((c) => titleCase(c));\n if (labels.length === 1) return labels[0]!;\n return `${labels.slice(0, -1).join(\", \")} and ${labels[labels.length - 1]}`;\n}\n\n/** Field errors read from a store error, with the safe sentence that sums them up. */\nexport interface PostgrestFieldErrors {\n /** Column name → safe message for that input. */\n fields: Record<string, string>;\n /** One safe sentence for the whole error, to replace the store's raw text. */\n message: string;\n}\n\n/**\n * Reads which columns a Postgres constraint error is about, from PostgREST's\n * `message` / `details`, and gives safe messages for them. Only plain column\n * names are taken from the store's text; the values it echoes are never\n * used. A unique violation whose columns cannot be read (a complex\n * expression index, no details), or an insert/update foreign-key violation\n * whose key is an expression, gets the safe sentence with no `fields`, so the\n * store's raw text (constraint name, echoed value) never reaches the user.\n * Returns `undefined` for anything else.\n *\n * - `23505` unique violation, `Key (email)=(…) already exists.` → each\n * column: \"This value is already in use.\" (several columns: \"This\n * combination is already in use.\")\n * - `23502` not-null, `null value in column \"title\" …` → \"This field is\n * required.\"\n * - `23503` foreign key on insert/update, `Key (owner_id)=(…) is not present\n * in table …` → \"The selected item doesn't exist.\"\n */\nexport function fieldErrorsFromPostgrest(error: {\n code?: unknown;\n message?: unknown;\n details?: unknown;\n}): PostgrestFieldErrors | undefined {\n const code = typeof error.code === \"string\" ? error.code : undefined;\n const details = typeof error.details === \"string\" ? error.details.trim() : \"\";\n const message = typeof error.message === \"string\" ? error.message : \"\";\n if (code === \"23505\") {\n const columns = keyColumns(details, /\\) already exists\\.?$/);\n // Not mappable to a column: still never show the store's raw text (it\n // names the constraint and echoes the value).\n if (columns.length === 0) return { fields: {}, message: \"This value is already in use.\" };\n const each = columns.length === 1 ? \"This value is already in use.\" : \"This combination is already in use.\";\n return {\n fields: Object.fromEntries(columns.map((c) => [c, each])),\n message:\n columns.length === 1\n ? `${listLabels(columns)} is already in use.`\n : `This combination of ${listLabels(columns)} is already in use.`,\n };\n }\n if (code === \"23502\") {\n const column = /^null value in column \"([A-Za-z_][A-Za-z0-9_]*)\"(?: |$)/.exec(message)?.[1];\n if (!column || !COLUMN.test(column)) return undefined;\n return {\n fields: { [column]: \"This field is required.\" },\n message: `${titleCase(column)} is required.`,\n };\n }\n if (code === \"23503\") {\n const tail = /\\) is not present in table \"[^\"]*\"\\.?$/;\n if (!tail.test(details)) return undefined;\n const columns = keyColumns(details, tail);\n if (columns.length === 0) return { fields: {}, message: \"The selected item doesn't exist.\" };\n return {\n fields: Object.fromEntries(columns.map((c) => [c, \"The selected item doesn't exist.\"])),\n message: `${listLabels(columns)}: the selected item doesn't exist.`,\n };\n }\n return undefined;\n}\n\n/**\n * Turns anything a write threw, or the `{ message, code }` error a Supabase\n * client returned, into a `DataWriteError`. A `DataWriteError` passes through\n * unchanged; anything else keeps its message and `code`, and is kept as the\n * `cause`.\n *\n * When the error names the columns it is about (`fieldErrorsFromPostgrest`:\n * unique, not-null and foreign-key violations), the result carries `fields`\n * and its message is replaced with a safe sentence; the raw text stays on\n * the `cause`.\n */\nexport function toDataWriteError(error: unknown): DataWriteError {\n if (isDataWriteError(error)) return error;\n const shape = (typeof error === \"object\" && error !== null ? error : {}) as {\n message?: unknown;\n code?: unknown;\n details?: unknown;\n };\n const code = typeof shape.code === \"string\" ? shape.code : undefined;\n const mapped = fieldErrorsFromPostgrest(shape);\n if (mapped) {\n return new DataWriteError(writeOutcomeFromCode(code), mapped.message, {\n code,\n fields: Object.keys(mapped.fields).length > 0 ? mapped.fields : undefined,\n cause: error,\n });\n }\n const message =\n typeof shape.message === \"string\" && shape.message\n ? shape.message\n : error instanceof Error\n ? error.message\n : String(error);\n return new DataWriteError(writeOutcomeFromCode(code), message, { code, cause: error });\n}\n","import type {\n BaseRecord,\n DataProvider,\n FilterParam,\n Identifier,\n InvalidationKey,\n ListParams,\n ResourceChangeEvent,\n WriteEvent,\n} from \"./types\";\nimport { DataWriteError } from \"../schema/write-outcome\";\nimport { DataReadError, readFailureMessage } from \"../schema/read-outcome\";\nimport type { FilterOperator, ProviderCapabilities } from \"../schema/types\";\nimport { readOutcomeFromCode, toDataWriteError } from \"./postgrest-errors\";\n\n// ---------------------------------------------------------------------------\n// Minimal Supabase client shape — no hard dependency on @supabase/supabase-js\n// ---------------------------------------------------------------------------\n\n/** A chainable query builder returned by `client.from(table)`. */\ninterface SupabaseQueryBuilder {\n select(\n columns?: string,\n options?: { count?: \"exact\" | \"planned\" | \"estimated\" },\n ): SupabaseQueryBuilder;\n insert(data: Record<string, unknown> | Record<string, unknown>[]): SupabaseQueryBuilder;\n update(data: Record<string, unknown>): SupabaseQueryBuilder;\n delete(): SupabaseQueryBuilder;\n eq(column: string, value: unknown): SupabaseQueryBuilder;\n neq(column: string, value: unknown): SupabaseQueryBuilder;\n gt(column: string, value: unknown): SupabaseQueryBuilder;\n lt(column: string, value: unknown): SupabaseQueryBuilder;\n gte(column: string, value: unknown): SupabaseQueryBuilder;\n lte(column: string, value: unknown): SupabaseQueryBuilder;\n ilike(column: string, value: string): SupabaseQueryBuilder;\n in(column: string, values: unknown[]): SupabaseQueryBuilder;\n is(column: string, value: null): SupabaseQueryBuilder;\n not(column: string, operator: string, value: unknown): SupabaseQueryBuilder;\n or(filters: string): SupabaseQueryBuilder;\n order(column: string, options?: { ascending?: boolean; nullsFirst?: boolean }): SupabaseQueryBuilder;\n range(from: number, to: number): SupabaseQueryBuilder;\n single(): SupabaseQueryBuilder;\n then: Promise<{ data: unknown; error: unknown; count?: number | null }>[\"then\"];\n}\n\n/**\n * Minimal Supabase client interface — the public shape this package has\n * always exposed for a caller that wants to type its own client or a\n * wrapper around one. Unchanged: `from()` still returns `SupabaseQueryBuilder`\n * so existing consumers that annotate a variable with this type and chain\n * off it keep type-checking exactly as before.\n */\nexport interface SupabaseClient {\n from(table: string): SupabaseQueryBuilder;\n /** Supabase Realtime; needed only for `subscribe` (see `SupabaseProviderOptions.realtime`). */\n channel?(name: string): SupabaseRealtimeChannel;\n /** Releases a channel made by `channel()`. */\n removeChannel?(channel: SupabaseRealtimeChannel): unknown;\n}\n\n/**\n * One `postgres_changes` message, as Supabase Realtime sends it. Only the\n * fields the provider reads; a real payload has more.\n */\nexport interface SupabaseRealtimePayload {\n eventType: \"INSERT\" | \"UPDATE\" | \"DELETE\";\n /** The row after an insert or update (empty for a delete). */\n new?: Record<string, unknown>;\n /** For a delete or update: the old row's key (all of it with `REPLICA IDENTITY FULL`). */\n old?: Record<string, unknown>;\n}\n\n/**\n * The part of a Supabase `RealtimeChannel` the provider uses. A real\n * `@supabase/supabase-js` channel satisfies it.\n */\nexport interface SupabaseRealtimeChannel {\n on(\n type: \"postgres_changes\",\n filter: {\n event: \"*\" | \"INSERT\" | \"UPDATE\" | \"DELETE\";\n schema: string;\n table: string;\n filter?: string;\n },\n callback: (payload: SupabaseRealtimePayload) => void,\n ): SupabaseRealtimeChannel;\n subscribe(callback?: (status: string, error?: unknown) => void): SupabaseRealtimeChannel;\n unsubscribe?(): unknown;\n}\n\n/**\n * What `createSupabaseProvider` actually requires from its `client` argument\n * — deliberately looser than the public `SupabaseClient` above, and used\n * ONLY for that one parameter. A real `@supabase/supabase-js` client's\n * `from()` returns a generic, table-typed `PostgrestQueryBuilder` whose chain\n * methods don't structurally match `SupabaseQueryBuilder`, which used to\n * force callers to pass their client through `as never`. Since `unknown` is\n * a supertype of everything, any real client's `from(table: string)`\n * satisfies THIS shape without a cast; `createSupabaseProvider` narrows to\n * `SupabaseQueryBuilder` internally, once, right after each `from()` call.\n * Loosening only the input here — rather than `SupabaseClient` itself —\n * means a caller relying on `SupabaseClient`'s stricter return type for\n * their own chaining is unaffected.\n */\nexport interface SupabaseClientInput {\n from(table: string): unknown;\n /** Database functions, for a resource whose `source` is an `rpc`. Any real client's `rpc` fits. */\n rpc?(fn: string, args?: Record<string, unknown>, options?: { count?: \"exact\" | \"planned\" | \"estimated\" }): unknown;\n /** Supabase Realtime, for `subscribe`. Any real client's `channel` fits. */\n channel?(name: string): unknown;\n removeChannel?(channel: unknown): unknown;\n}\n\n// ---------------------------------------------------------------------------\n// Provider factory\n// ---------------------------------------------------------------------------\n\n/** What a write hook is told about the write it is part of. */\nexport interface SupabaseWriteContext {\n resource: string;\n action: \"create\" | \"update\";\n /** The row's id, for an update. */\n id?: Identifier;\n}\n\n/** Per-resource rules for `createSupabaseProvider`. Every field is optional. */\nexport interface SupabaseResourceConfig {\n /** Singular noun for failure messages, e.g. \"project\". Defaults to \"record\". */\n noun?: string;\n /** Plural for list messages, when it isn't `noun` + \"s\" (\"categories\"). */\n nounPlural?: string;\n /**\n * The columns a search covers. `[]` means the resource can't be searched,\n * and `capabilities(resource).search` reports false so a UI hides the box.\n * Set, they replace the caller's `search.fields`; omitted, those are used\n * as given.\n */\n searchFields?: readonly string[];\n /**\n * The column a sorted list orders by last, so rows with equal sort values\n * keep one order from page to page (none repeats, none is skipped).\n * Default `\"id\"`; `false` for a table or view without one. With the\n * default, a view that turns out to have no `id` column is read as before\n * (without the key order) and a development warning suggests setting this.\n */\n orderKey?: string | false;\n /**\n * `\"bin\"` for a table whose delete trigger moves the row to a recycle bin\n * instead of removing it (see `SupabaseProviderOptions.binTables`).\n * `\"hard\"` forces a plain delete even when `binTables` lists the table.\n */\n deleteMode?: \"hard\" | \"bin\";\n /**\n * Turns submitted values into the row to write: trim, drop read-only keys,\n * validate. Runs before every create and update, including the `create`\n * and `update` overrides. Throw (ideally `DataWriteError(\"invalid\", ...)`)\n * to refuse the write; nothing is sent.\n */\n prepare?: (\n values: Record<string, unknown>,\n context: SupabaseWriteContext,\n ) => Record<string, unknown> | Promise<Record<string, unknown>>;\n /**\n * Creates the row some other way than an insert, e.g. a security-definer\n * RPC. Return the new row, or its id and the provider reads the row back\n * (if the read-back fails, the create is still reported as saved, with\n * just the id, so the user does not retry and make a second one). Throw to\n * fail; a Supabase `{ message, code }` error is mapped like any other.\n */\n create?: (row: Record<string, unknown>) => Promise<BaseRecord | Identifier>;\n /**\n * Updates the row some other way than an update, e.g. an RPC. Return the\n * updated row, or its id (or `true`) and the provider reads it back.\n * Returning nothing (`undefined`/`null`/`false`) means no row changed: the provider then reads the\n * row to say why (`forbidden` or `gone`), exactly as for a plain update,\n * so a function that silently skips a row never reports a save.\n */\n update?: (\n id: Identifier,\n row: Record<string, unknown>,\n ) => Promise<BaseRecord | Identifier | boolean | null | undefined | void>;\n /** Maps a stored row to edit-form values; see `DataProvider.toFormValues`. */\n toFormValues?: (record: Record<string, unknown>) => Record<string, unknown>;\n /**\n * Other cache keys a committed write to this resource makes stale, e.g.\n * `[[\"staff\"], [\"me\"]]`. Served through `DataProvider.invalidates`, which\n * `useResource` and `useResourceForm` invalidate after their writes.\n */\n invalidates?: InvalidationKey[] | ((event: WriteEvent) => InvalidationKey[]);\n /**\n * Serve `subscribe` for this resource through Supabase Realtime\n * (`postgres_changes`), so `live` lists and records refresh when the table\n * changes. The table must be in the `supabase_realtime` publication, with\n * RLS on. `false` turns it off even when `SupabaseProviderOptions.realtime`\n * covers the resource.\n */\n realtime?: boolean;\n /**\n * Read this resource from somewhere else than its table: a view (joins,\n * counts, aggregations) or a database function that returns rows. Writes\n * still go to the table. Lists keep paging, filters, search, sort, totals\n * and cursors, because PostgREST filters a view or a set-returning function\n * like a table. Realtime still watches the table.\n *\n * Row-level security: a plain view runs as its owner and a SECURITY DEFINER\n * function as its definer, so either one reads past RLS. Create the view\n * `with (security_invoker = true)` and the function `security invoker` (or\n * have it filter by `auth.uid()` itself), or this exposes every row.\n *\n * ```ts\n * resources: {\n * tasks: { source: \"tasks_with_people\" },\n * course_progress: { source: { rpc: \"group_progress\", args: () => ({ group_id: currentGroup() }) } },\n * }\n * ```\n */\n source?: string | { rpc: string; args?: () => Record<string, unknown> };\n /** The columns read when the caller names none, e.g. embedded joins: `\"*, person:people(full_name)\"`. Default `\"*\"`. */\n select?: string;\n /**\n * With a `source` (or a `select` that embeds other tables), the table's own\n * columns: creates and updates write only these, so a form built from the\n * richer read row never sends its joined or computed columns to the table.\n * Without it, an update writes only the columns the table's row has.\n */\n writeColumns?: readonly string[];\n}\n\n/** Options for `createSupabaseProvider`. All optional; none changes reads. */\nexport interface SupabaseProviderOptions {\n /**\n * Recycle-bin tables: their delete trigger turns a delete into a \"binned\"\n * mark and the binned row drops out of the caller's view (RLS or a view\n * filter). The database reports such a delete as zero rows, so for these\n * the provider checks the row is visible, deletes it, and reads it back:\n * gone from view is success, still visible is `forbidden`. A row that was\n * not visible beforehand is `gone`.\n */\n binTables?: readonly string[] | ((resource: string) => boolean);\n /** Per-resource rules, keyed by resource (table) name. */\n resources?: Record<string, SupabaseResourceConfig>;\n /**\n * Called after every committed create, update and delete, e.g. to\n * invalidate caches the Genesis hooks don't know about. Awaited, but a\n * failure is logged and never turns a committed write into a failed one.\n */\n onWrite?: (event: WriteEvent) => void | Promise<void>;\n /**\n * The most rows one list page may ask for (PostgREST's `max-rows` caps\n * reads anyway; default 1000). A larger request is refused with an\n * `invalid` `DataReadError` (its `cause` says why) rather than cut short,\n * so page boundaries never disagree with the caller's `perPage`.\n * `capabilities().maxPerPage` reports it.\n */\n maxPerPage?: number;\n /**\n * Called with every failed read, before it is thrown. The thrown\n * `DataReadError` carries a plain message for users; the store's own\n * error (its raw text and code) is its `cause`, for logging here.\n */\n onReadError?: (\n error: DataReadError,\n context: { resource: string; operation: \"getList\" | \"getOne\" | \"getMany\" },\n ) => void | Promise<void>;\n /**\n * Which resources `subscribe` serves through Supabase Realtime: `true` for\n * all, a list of names, or a test. Off by default; a resource's own\n * `resources[name].realtime` wins. Needs a client with `channel()` (any\n * `@supabase/supabase-js` client).\n */\n realtime?: boolean | readonly string[] | ((resource: string) => boolean);\n}\n\n/** A PostgREST \"undefined column\" error (42703) naming `column`. */\n/**\n * A PostgreSQL \"undefined column\" error (42703) for `table`'s own `column`:\n * `column \"id\" does not exist` or `column <table>.id does not exist`. Not a\n * related table's column (`author.id`) or any other message mentioning it.\n */\nfunction isMissingColumn(error: unknown, table: string, column: string): boolean {\n if (!error || typeof error !== \"object\") return false;\n const { code, message } = error as { code?: unknown; message?: unknown };\n if (code !== \"42703\" || typeof message !== \"string\") return false;\n const match = /^column (?:\"?([^.\"\\s]+)\"?\\.)?\"?([^.\"\\s]+)\"? does not exist$/.exec(message.trim());\n if (!match || match[2] !== column) return false;\n const ownTable = table.split(\".\").pop()?.replace(/\"/g, \"\");\n return match[1] === undefined || match[1] === ownTable;\n}\n\nconst SERVED_OPERATORS: readonly FilterOperator[] = [\n \"eq\", \"neq\", \"gt\", \"lt\", \"gte\", \"lte\", \"contains\", \"in\", \"between\", \"is_null\", \"is_not_null\",\n];\n\nfunction escapeIlike(value: string): string {\n return value.replace(/[%_\\\\]/g, (char) => `\\\\${char}`);\n}\n\nfunction isIdentifier(value: unknown): value is Identifier {\n return typeof value === \"string\" || typeof value === \"number\";\n}\n\n// ---------------------------------------------------------------------------\n// Cursor (keyset) paging\n// ---------------------------------------------------------------------------\n\n/** What a cursor holds: the sort it was made for, and the last row's values. */\ninterface CursorState {\n /** Sort field, or null when ordered by the key alone. */\n s: string | null;\n o: \"asc\" | \"desc\";\n /** The key column. */\n k: string;\n /** The last row's sort value (absent when `s` is null). */\n v?: string | number | boolean | null;\n /** The last row's key value. */\n id: string | number;\n}\n\nconst PLAIN_COLUMN = /^[a-zA-Z_][a-zA-Z0-9_]*$/;\n\nfunction encodeCursor(state: CursorState): string {\n const bytes = new TextEncoder().encode(JSON.stringify(state));\n let binary = \"\";\n for (const b of bytes) binary += String.fromCharCode(b);\n return btoa(binary).replace(/\\+/g, \"-\").replace(/\\//g, \"_\").replace(/=+$/, \"\");\n}\n\nfunction decodeCursor(cursor: string): CursorState | undefined {\n try {\n const binary = atob(cursor.replace(/-/g, \"+\").replace(/_/g, \"/\"));\n const bytes = Uint8Array.from(binary, (c) => c.charCodeAt(0));\n const state = JSON.parse(new TextDecoder().decode(bytes)) as CursorState;\n if (!state || typeof state !== \"object\" || typeof state.k !== \"string\" || !isIdentifier(state.id)) return undefined;\n if (state.o !== \"asc\" && state.o !== \"desc\") return undefined;\n return state;\n } catch {\n return undefined;\n }\n}\n\n/** A value quoted for a PostgREST filter, so commas, dots and parens are literal. */\nfunction quoteFilterValue(value: string | number | boolean): string {\n return `\"${String(value).replace(/\\\\/g, \"\\\\\\\\\").replace(/\"/g, '\\\\\"')}\"`;\n}\n\n/**\n * The PostgREST `or` clauses selecting the rows after `state`, for a list\n * ordered by `s` (`o`, nulls last when ascending and first when descending,\n * as Postgres orders them by default) and then by the key ascending.\n * @internal Exported for tests.\n */\nexport function keysetClauses(state: CursorState): string {\n const k = state.k;\n const K = quoteFilterValue(state.id);\n if (state.s === null) return `${k}.${state.o === \"asc\" ? \"gt\" : \"lt\"}.${K}`;\n const s = state.s;\n const v = state.v;\n const afterInTies = (eq: string) => `and(${eq},${k}.gt.${K})`;\n if (v === null || v === undefined) {\n // Asc: nulls are last, so only later nulls remain. Desc: nulls are\n // first, so later nulls and then every non-null row remain.\n const ties = afterInTies(`${s}.is.null`);\n return state.o === \"asc\" ? ties : `${s}.not.is.null,${ties}`;\n }\n const V = quoteFilterValue(v);\n const ties = afterInTies(`${s}.eq.${V}`);\n return state.o === \"asc\" ? `${s}.gt.${V},${ties},${s}.is.null` : `${s}.lt.${V},${ties}`;\n}\n/** `\"schema.table\"` or `\"table\"` (schema `public`), as Realtime names them. */\nfunction realtimeTable(resource: string): { schema: string; table: string } {\n const dot = resource.indexOf(\".\");\n const strip = (name: string) => name.replace(/\"/g, \"\");\n return dot < 0\n ? { schema: \"public\", table: strip(resource) }\n : { schema: strip(resource.slice(0, dot)), table: strip(resource.slice(dot + 1)) };\n}\n\nlet realtimeChannelSeq = 0;\nconst warnedRealtime = new Set<string>();\n\n/**\n * The Supabase data provider. Reads and writes go through the client you\n * pass, under that client's session and RLS.\n *\n * Writes never report a save that did not happen:\n * - `update` and `deleteOne` ask for the affected rows. Zero rows is a\n * `DataWriteError`: the row is read back, and still visible means\n * `forbidden` (RLS or a trigger refused the change), no longer visible\n * means `gone`.\n * - Database errors on writes are thrown as `DataWriteError` with the\n * outcome their code means (`writeOutcomeFromCode`) and the code kept on\n * `error.code`.\n * - Recycle-bin tables (`binTables`) succeed when the row leaves the\n * caller's view.\n *\n * Reads are unchanged: errors are thrown as an `Error` carrying `code`.\n */\nexport function createSupabaseProvider(\n client: SupabaseClientInput,\n options: SupabaseProviderOptions = {},\n): DataProvider {\n // ---------------------------------------------------------------------------\n // Helpers\n // ---------------------------------------------------------------------------\n\n function applyFilters(\n query: SupabaseQueryBuilder,\n filters: FilterParam[] | undefined,\n ): SupabaseQueryBuilder {\n if (!filters) return query;\n for (const f of filters) {\n switch (f.operator) {\n case \"eq\":\n query = query.eq(f.field, f.value);\n break;\n case \"neq\":\n query = query.neq(f.field, f.value);\n break;\n case \"gt\":\n query = query.gt(f.field, f.value);\n break;\n case \"lt\":\n query = query.lt(f.field, f.value);\n break;\n case \"gte\":\n query = query.gte(f.field, f.value);\n break;\n case \"lte\":\n query = query.lte(f.field, f.value);\n break;\n case \"contains\":\n query = query.ilike(f.field, `%${escapeIlike(String(f.value))}%`);\n break;\n case \"in\":\n query = query.in(f.field, f.value);\n break;\n case \"is_null\":\n query = query.is(f.field, null);\n break;\n case \"is_not_null\":\n query = query.not(f.field, \"is\", null);\n break;\n case \"between\": {\n const [lo, hi] = f.value;\n query = query.gte(f.field, lo).lte(f.field, hi);\n break;\n }\n default:\n throw new Error(`[SupabaseProvider] Unknown filter operator \"${(f as FilterParam).operator}\"`);\n break;\n }\n }\n return query;\n }\n\n const maxPerPage = options.maxPerPage ?? 1000;\n // Resources found to have no \"id\" column for the default orderKey.\n const keylessResources = new Set<string>();\n\n /** Tell `onReadError` (sync or async; its failure is swallowed), then throw. */\n async function reportReadError(\n error: DataReadError,\n resource: string,\n operation: \"getList\" | \"getOne\" | \"getMany\",\n ): Promise<never> {\n try {\n await Promise.resolve(options.onReadError?.(error, { resource, operation }));\n } catch {\n // A logging hook never changes what the caller is told.\n }\n throw error;\n }\n\n /** A failed read, as a `DataReadError` with a message users can be shown. */\n async function throwIfReadError(\n result: { error: unknown },\n resource: string,\n operation: \"getList\" | \"getOne\" | \"getMany\",\n ): Promise<void> {\n if (!result.error) return;\n const raw = result.error as { message?: string; code?: string };\n const code = typeof raw.code === \"string\" ? raw.code : undefined;\n const outcome = readOutcomeFromCode(code);\n const error = new DataReadError(\n outcome,\n readFailureMessage(outcome, nounFor(resource), operation === \"getOne\", configFor(resource).nounPlural),\n { code, cause: result.error },\n );\n await reportReadError(error, resource, operation);\n }\n\n // ---------------------------------------------------------------------------\n // Write helpers\n // ---------------------------------------------------------------------------\n\n const from = (resource: string) => client.from(resource) as SupabaseQueryBuilder;\n\n /** The relation PostgREST names in errors about a read of `resource`: its view, function or table. */\n function readName(resource: string): string {\n const source = configFor(resource).source;\n return typeof source === \"string\" ? source : source ? source.rpc : resource;\n }\n\n /**\n * The values a create or update sends to the table: with `writeColumns`,\n * only those; for an update of a sourced resource without them, only the\n * columns the table's row has, so read-only columns from a view never go out.\n */\n async function tableValues(\n resource: string,\n values: Record<string, unknown>,\n id?: Identifier,\n ): Promise<Record<string, unknown>> {\n const config = configFor(resource);\n if (config.writeColumns) {\n const allowed = new Set(config.writeColumns);\n return Object.fromEntries(Object.entries(values).filter(([key]) => allowed.has(key)));\n }\n if (!config.source || id === undefined) return values;\n const row = await readBack(resource, id);\n if (!row) return values;\n return Object.fromEntries(Object.entries(values).filter(([key]) => key in row));\n }\n\n /** A read of `resource` from its configured source (table, view or function), with its default columns. */\n function read(resource: string, columns: string | undefined, count?: \"exact\"): SupabaseQueryBuilder {\n const config = configFor(resource);\n const cols = columns ?? config.select ?? \"*\";\n const source = config.source;\n if (source && typeof source === \"object\") {\n if (!client.rpc) {\n throw new DataReadError(\"error\", `[SupabaseProvider] \"${resource}\" reads from ${source.rpc}(), but the client has no rpc.`);\n }\n const builder = client.rpc(source.rpc, source.args?.() ?? {}, count ? { count } : undefined) as SupabaseQueryBuilder;\n return builder.select(cols);\n }\n const table = client.from(source ?? resource) as SupabaseQueryBuilder;\n return count ? table.select(cols, { count }) : table.select(cols);\n }\n const configFor = (resource: string): SupabaseResourceConfig =>\n options.resources?.[resource] ?? {};\n const nounFor = (resource: string) => configFor(resource).noun ?? \"record\";\n\n function realtimeEnabled(resource: string): boolean {\n if (typeof client.channel !== \"function\") return false;\n const own = configFor(resource).realtime;\n if (own !== undefined) return own;\n const all = options.realtime;\n if (!all) return false;\n if (all === true) return true;\n return typeof all === \"function\" ? all(resource) : all.includes(resource);\n }\n\n function isBinTable(resource: string): boolean {\n const mode = configFor(resource).deleteMode;\n if (mode) return mode === \"bin\";\n const bin = options.binTables;\n if (!bin) return false;\n return typeof bin === \"function\" ? bin(resource) : bin.includes(resource);\n }\n\n /** Awaits a write-path query: its rows, or a `DataWriteError`. */\n async function run(query: SupabaseQueryBuilder): Promise<unknown[]> {\n let result: { data: unknown; error: unknown };\n try {\n result = (await query) as { data: unknown; error: unknown };\n } catch (error) {\n throw toDataWriteError(error);\n }\n if (result.error) throw toDataWriteError(result.error);\n if (Array.isArray(result.data)) return result.data;\n return result.data == null ? [] : [result.data];\n }\n\n async function isVisible(resource: string, id: Identifier): Promise<boolean> {\n return (await run(from(resource).select(\"id\").eq(\"id\", id))).length > 0;\n }\n\n async function readBack(resource: string, id: Identifier): Promise<BaseRecord | undefined> {\n return (await run(from(resource).select(\"*\").eq(\"id\", id)))[0] as BaseRecord | undefined;\n }\n\n function goneError(resource: string): DataWriteError {\n return new DataWriteError(\n \"gone\",\n `This ${nounFor(resource)} no longer exists, or you can no longer see it.`,\n );\n }\n\n /**\n * A write matched no rows: read the row back to say why. Still visible\n * means the change was refused; not visible means it is gone (deleted, or\n * hidden from this user — the two can't be told apart under RLS).\n */\n async function noRowsError(\n resource: string,\n id: Identifier,\n verb: \"change\" | \"delete\",\n ): Promise<DataWriteError> {\n let visible: boolean;\n try {\n visible = await isVisible(resource, id);\n } catch (error) {\n const cause = toDataWriteError(error);\n return new DataWriteError(\n cause.outcome === \"unauthenticated\" ? \"unauthenticated\" : \"error\",\n `This ${nounFor(resource)} was not ${verb === \"change\" ? \"changed\" : \"deleted\"}, and reading it back failed (${cause.message}).`,\n { code: cause.code, cause: error },\n );\n }\n if (visible) {\n return new DataWriteError(\"forbidden\", `You can't ${verb} this ${nounFor(resource)}.`);\n }\n return goneError(resource);\n }\n\n async function prepare(\n resource: string,\n values: Record<string, unknown>,\n context: SupabaseWriteContext,\n ): Promise<Record<string, unknown>> {\n const rule = configFor(resource).prepare;\n if (!rule) return values;\n try {\n return await rule({ ...values }, context);\n } catch (error) {\n throw toDataWriteError(error);\n }\n }\n\n /** After a committed write. Never turns it into a failure. */\n async function committed(event: WriteEvent): Promise<void> {\n if (!options.onWrite) return;\n try {\n await options.onWrite(event);\n } catch (error) {\n console.error(`[SupabaseProvider] onWrite failed for \"${event.resource}\":`, error);\n }\n }\n\n // ---------------------------------------------------------------------------\n // DataProvider implementation\n // ---------------------------------------------------------------------------\n\n /** The search as PostgREST `or` clauses, or \"\" for none. */\n function searchClauses(resource: string, params: ListParams): string {\n const searchFields = configFor(resource).searchFields ?? params.search?.fields ?? [];\n if (!params.search || !params.search.query || searchFields.length === 0) return \"\";\n const escaped = escapeIlike(params.search.query);\n const safeFieldPattern = /^[a-zA-Z_][a-zA-Z0-9_.]*$/;\n return searchFields\n .filter((f) => safeFieldPattern.test(f))\n // Quoted, so commas, dots and parens in the query stay literal (also\n // when nested inside the keyset's `and(or(…))`).\n .map((f) => `${f}.ilike.${quoteFilterValue(`%${escaped}%`)}`)\n .join(\",\");\n }\n\n /** A cursor request this provider can't serve: `invalid`, with why as the cause. */\n function refuseCursor(resource: string, why: string): Promise<never> {\n return reportReadError(\n new DataReadError(\n \"invalid\",\n readFailureMessage(\"invalid\", nounFor(resource), false, configFor(resource).nounPlural),\n { cause: new Error(`[SupabaseProvider] \"${resource}\": ${why}`) },\n ),\n resource,\n \"getList\",\n );\n }\n\n /**\n * One page by keyset: ordered by the sort column and then the key, the\n * rows after the cursor's row, plus one more to tell whether a next page\n * exists. Counted only on the first page.\n */\n async function getCursorPage(\n resource: string,\n params: ListParams,\n key: string | false,\n ): Promise<{ data: unknown[]; total: number; nextCursor: string | null }> {\n const { cursor } = params.pagination!;\n // The look-ahead row must fit under PostgREST's max-rows (maxPerPage), or\n // it is dropped and the list would end after one page. A keyset page can\n // be shorter than asked without skipping or repeating rows.\n const perPage = Math.max(1, Math.min(params.pagination!.perPage, maxPerPage - 1));\n if (!key) {\n return refuseCursor(resource, \"cursor paging needs a unique key column to order by; its orderKey is false. Set orderKey to a unique, non-null column, or page by offset.\");\n }\n if (!PLAIN_COLUMN.test(key)) return refuseCursor(resource, `the key column \"${key}\" can't be used in a cursor.`);\n const sort = params.sort && params.sort.field !== key ? params.sort : undefined;\n if (sort && !PLAIN_COLUMN.test(sort.field)) {\n return refuseCursor(resource, `cursor paging can sort only by a plain column, not \"${sort.field}\".`);\n }\n const order: \"asc\" | \"desc\" = params.sort?.order ?? \"asc\";\n const sortField = sort ? sort.field : null;\n\n let after: CursorState | undefined;\n if (cursor) {\n after = decodeCursor(cursor);\n if (!after) return refuseCursor(resource, \"the cursor is not one this provider made.\");\n if (after.s !== sortField || after.o !== order || after.k !== key) {\n return refuseCursor(resource, \"the cursor was made for a different sort; start again from the first page (cursor: null).\");\n }\n }\n\n let query = read(resource, params.select, cursor ? undefined : \"exact\");\n query = applyFilters(query, params.filters);\n const search = searchClauses(resource, params);\n const keyset = after ? keysetClauses(after) : \"\";\n // Both are OR groups that must hold together: nest them in one `or`.\n if (search && keyset) query = query.or(`and(or(${search}),or(${keyset}))`);\n else if (search || keyset) query = query.or(search || keyset);\n\n if (sortField) {\n // Pinned to Postgres's default null placement, which the keyset assumes.\n query = query.order(sortField, { ascending: order === \"asc\", nullsFirst: order === \"desc\" });\n query = query.order(key, { ascending: true });\n } else {\n query = query.order(key, { ascending: order === \"asc\" });\n }\n query = query.range(0, perPage);\n\n const result = (await query) as unknown as { data: unknown[] | null; error: unknown; count?: number | null };\n await throwIfReadError(result, resource, \"getList\");\n const rows = (result.data ?? []) as Record<string, unknown>[];\n const page = rows.slice(0, perPage);\n let nextCursor: string | null = null;\n if (rows.length > perPage) {\n const last = page[page.length - 1]!;\n const id = last[key];\n const v = sortField ? last[sortField] : undefined;\n if (!isIdentifier(id) || (sortField && !(sortField in last))) {\n return refuseCursor(resource, `the selected columns must include \"${key}\"${sortField ? ` and \"${sortField}\"` : \"\"} to page by cursor.`);\n }\n if (v !== undefined && v !== null && typeof v === \"object\") {\n return refuseCursor(resource, `cursor paging can't sort by \"${sortField}\": its values aren't plain (text, number, date, boolean).`);\n }\n nextCursor = encodeCursor({\n s: sortField,\n o: order,\n k: key,\n ...(sortField ? { v: (v ?? null) as CursorState[\"v\"] } : {}),\n id,\n });\n }\n return { data: page, total: cursor ? -1 : (result.count ?? 0), nextCursor };\n }\n\n const provider: DataProvider = {\n async getList(resource, params) {\n // Refused, not cut short: a shorter page than the caller asked for\n // would shift every later page's boundary and skip or repeat rows.\n if (params.pagination && params.pagination.perPage > maxPerPage) {\n const { perPage } = params.pagination;\n await reportReadError(\n new DataReadError(\n \"invalid\",\n readFailureMessage(\"invalid\", nounFor(resource), false, configFor(resource).nounPlural),\n {\n cause: new Error(\n `[SupabaseProvider] \"${resource}\" asked for ${perPage} rows per page; the most is ${maxPerPage} (maxPerPage). Ask for at most ${maxPerPage} and page through the rest.`,\n ),\n },\n ),\n resource,\n \"getList\",\n );\n }\n\n const configuredKey = configFor(resource).orderKey;\n if (params.pagination && params.pagination.cursor !== undefined) {\n return getCursorPage(resource, params, configuredKey === undefined ? \"id\" : configuredKey) as never;\n }\n const run = (key: string | false) => {\n let query = read(resource, params.select, \"exact\");\n\n query = applyFilters(query, params.filters);\n\n // Search — convert to OR of ilike. A resource's configured\n // `searchFields` win over the caller's.\n const clauses = searchClauses(resource, params);\n if (clauses) {\n query = query.or(clauses);\n }\n\n // Sort, then the key column, so equal sort values keep one order\n // across pages (otherwise a row can repeat on page 2 or be skipped).\n // An unsorted page is ordered by the key alone: without an ORDER BY\n // the database may return pages in any order.\n if (params.sort) {\n query = query.order(params.sort.field, {\n ascending: params.sort.order === \"asc\",\n });\n if (key && key !== params.sort.field) query = query.order(key, { ascending: true });\n } else if (params.pagination && key) {\n query = query.order(key, { ascending: true });\n }\n\n if (params.pagination) {\n const { page, perPage } = params.pagination;\n const from = (page - 1) * perPage;\n const to = from + perPage - 1;\n query = query.range(from, to);\n }\n\n return query as unknown as Promise<{\n data: unknown[];\n error: unknown;\n count?: number | null;\n }>;\n };\n\n // The default key (\"id\") is a guess: a view without that column reads\n // as before, without the key order, and is not ordered by it again.\n const guessKey = configuredKey === undefined && !keylessResources.has(resource);\n let result = await run(configuredKey ?? (keylessResources.has(resource) ? false : \"id\"));\n if (guessKey && isMissingColumn(result.error, readName(resource), \"id\")) {\n keylessResources.add(resource);\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\n `[SupabaseProvider] \"${resource}\" has no \"id\" column, so its pages have no stable order. Set resources.${resource}.orderKey to a unique column (or false to silence this).`,\n );\n }\n result = await run(false);\n }\n await throwIfReadError(result, resource, \"getList\");\n\n return { data: result.data ?? [], total: result.count ?? 0 } as never;\n },\n\n async getOne(resource, params) {\n const result = (await read(resource, params.select)\n .eq(\"id\", params.id)\n .single()) as { data: unknown; error: unknown };\n await throwIfReadError(result, resource, \"getOne\");\n return { data: result.data } as never;\n },\n\n async getMany(resource, params) {\n if (params.ids.length === 0) return { data: [] } as never;\n const result = (await read(resource, undefined)\n .in(\"id\", params.ids)) as { data: unknown[]; error: unknown };\n await throwIfReadError(result, resource, \"getMany\");\n return { data: result.data ?? [] } as never;\n },\n\n async capabilities(resource?: string): Promise<ProviderCapabilities> {\n return {\n search: resource ? configFor(resource).searchFields?.length !== 0 : true,\n sort: true,\n filterOperators: SERVED_OPERATORS,\n bulkWrites: false,\n versionedWrites: false,\n compositeKeys: false,\n multiSort: false,\n create: true,\n delete: true,\n maxPerPage,\n softDelete: resource ? isBinTable(resource) : false,\n cursorPagination: resource ? configFor(resource).orderKey !== false : true,\n realtime: resource\n ? realtimeEnabled(resource)\n : typeof client.channel === \"function\" &&\n (!!options.realtime ||\n Object.values(options.resources ?? {}).some((r) => r.realtime === true)),\n };\n },\n\n subscribe(resource, params, callback) {\n if (!realtimeEnabled(resource)) {\n if (process.env.NODE_ENV !== \"production\" && !warnedRealtime.has(resource)) {\n warnedRealtime.add(resource);\n console.warn(\n typeof client.channel !== \"function\"\n ? `[SupabaseProvider] \"${resource}\" was subscribed to, but the client has no channel() (Supabase Realtime), so nothing will be reported.`\n : `[SupabaseProvider] \"${resource}\" was subscribed to, but realtime is off for it. Set resources.${resource}.realtime (or the realtime option) to true.`,\n );\n }\n return () => {};\n }\n const { schema, table } = realtimeTable(resource);\n // No server-side `id=eq.` filter for one record: Realtime never\n // delivers DELETE events through a filter, so the id is matched below.\n // A unique topic: supabase-js hands back an existing channel for a\n // topic already open, and removing it would end the other subscriber.\n const channel = client.channel!(\n `genesis:${resource}:${++realtimeChannelSeq}`,\n ) as SupabaseRealtimeChannel;\n let closed = false;\n let subscribedOnce = false;\n let interrupted = false;\n const emit = (event: ResourceChangeEvent) => {\n if (closed) return;\n try {\n callback(event);\n } catch (error) {\n console.error(`[SupabaseProvider] a realtime callback for \"${resource}\" threw:`, error);\n }\n };\n channel\n .on(\n \"postgres_changes\",\n { event: \"*\", schema, table },\n (payload) => {\n // Only the id: the payload is a hint, never data to show. Realtime\n // applies RLS to inserts and updates, but a delete's old key is\n // sent to every subscriber, so nothing else is passed on.\n const row = payload.eventType === \"DELETE\" ? payload.old : payload.new;\n const id = row?.[\"id\"];\n if (params.id != null && isIdentifier(id) && String(id) !== String(params.id)) return;\n const type =\n payload.eventType === \"INSERT\" ? \"created\" : payload.eventType === \"UPDATE\" ? \"updated\" : \"deleted\";\n emit(isIdentifier(id) ? { type, id } : { type });\n },\n )\n .subscribe((status) => {\n if (status === \"SUBSCRIBED\") {\n // Back after a drop: changes made meanwhile were not sent.\n if (subscribedOnce && interrupted) emit({ type: \"changed\" });\n subscribedOnce = true;\n interrupted = false;\n } else if (status === \"CHANNEL_ERROR\" || status === \"TIMED_OUT\" || status === \"CLOSED\") {\n interrupted = true;\n }\n });\n return () => {\n if (closed) return;\n closed = true;\n try {\n const done =\n typeof client.removeChannel === \"function\"\n ? client.removeChannel(channel)\n : channel.unsubscribe?.();\n // A failed removal (socket already gone) is nothing to report.\n if (done && typeof (done as Promise<unknown>).catch === \"function\") {\n (done as Promise<unknown>).catch(() => {});\n }\n } catch {\n // As above.\n }\n };\n },\n\n async create(resource, params) {\n const row = await tableValues(\n resource,\n await prepare(resource, params.data as Record<string, unknown>, { resource, action: \"create\" }),\n );\n const override = configFor(resource).create;\n let record: BaseRecord;\n if (override) {\n let returned: BaseRecord | Identifier;\n try {\n returned = await override(row);\n } catch (error) {\n throw toDataWriteError(error);\n }\n if (isIdentifier(returned)) {\n // The row exists from here on. A failed read-back must not report\n // the create as failed: the user would retry and make a second one.\n record = (await readBack(resource, returned).catch(() => undefined)) ?? { id: returned };\n } else if (returned && typeof returned === \"object\" && isIdentifier(returned.id)) {\n record = returned;\n } else {\n throw new DataWriteError(\n \"error\",\n `[SupabaseProvider] The create rule for \"${resource}\" returned neither the new row nor its id.`,\n );\n }\n } else {\n const rows = await run(from(resource).insert(row).select(\"*\").single());\n record = rows[0] as BaseRecord;\n }\n await committed({ resource, kind: \"create\", id: record.id, record });\n return { data: record } as never;\n },\n\n async update(resource, params) {\n const { id } = params;\n const row = await tableValues(\n resource,\n await prepare(resource, params.data as Record<string, unknown>, { resource, action: \"update\", id }),\n id,\n );\n const override = configFor(resource).update;\n let record: BaseRecord;\n if (override) {\n let returned: BaseRecord | Identifier | boolean | null | undefined | void;\n try {\n returned = await override(id, row);\n } catch (error) {\n throw toDataWriteError(error);\n }\n const result: unknown = returned;\n if (result == null || result === false) throw await noRowsError(resource, id, \"change\");\n if (isIdentifier(result) || result === true) {\n // The change committed; a failed read-back still reports it saved.\n const readId = result === true ? id : result;\n record = (await readBack(resource, readId).catch(() => undefined)) ?? { ...row, id: readId };\n } else if (typeof result === \"object\") {\n record = { id, ...(result as Record<string, unknown>) } as BaseRecord;\n } else {\n throw new DataWriteError(\n \"error\",\n `[SupabaseProvider] The update rule for \"${resource}\" returned neither the row, its id, nor nothing.`,\n );\n }\n } else {\n const rows = await run(from(resource).update(row).eq(\"id\", id).select(\"*\"));\n if (rows.length === 0) throw await noRowsError(resource, id, \"change\");\n record = rows[0] as BaseRecord;\n }\n await committed({ resource, kind: \"update\", id, record });\n return { data: record } as never;\n },\n\n async deleteOne(resource, params) {\n const { id } = params;\n let deletedId: Identifier = id;\n if (isBinTable(resource)) {\n // A binned delete reports zero rows whether or not it worked, so the\n // answer comes from visibility before and after.\n if (!(await isVisible(resource, id))) throw goneError(resource);\n await run(from(resource).delete().eq(\"id\", id));\n let stillVisible: boolean;\n try {\n stillVisible = await isVisible(resource, id);\n } catch (error) {\n const cause = toDataWriteError(error);\n throw new DataWriteError(\n \"error\",\n `The ${nounFor(resource)} may not have been deleted: checking it failed (${cause.message}).`,\n { code: cause.code, cause: error },\n );\n }\n if (stillVisible) {\n throw new DataWriteError(\"forbidden\", `You can't delete this ${nounFor(resource)}.`);\n }\n } else {\n const rows = await run(from(resource).delete().eq(\"id\", id).select(\"id\"));\n if (rows.length === 0) throw await noRowsError(resource, id, \"delete\");\n const returnedId = (rows[0] as { id?: unknown }).id;\n if (isIdentifier(returnedId)) deletedId = returnedId;\n }\n await committed({ resource, kind: \"delete\", id: deletedId });\n return { data: { id: deletedId } };\n },\n\n toFormValues(resource, record) {\n const map = configFor(resource).toFormValues;\n return map ? map(record) : record;\n },\n\n invalidates(event) {\n const keys = configFor(event.resource).invalidates;\n if (!keys) return [];\n return typeof keys === \"function\" ? keys(event) : keys;\n },\n };\n\n return provider;\n}\n","// ---------------------------------------------------------------------------\n// Write helpers (README \"One-off writes\")\n//\n// The writes a resource page doesn't cover: a database function (RPC) with\n// plain error words, and \"one live row per key\" (create, or adopt the row\n// that's already there). Both fail with a DataWriteError, like the provider.\n// ---------------------------------------------------------------------------\n\nimport { DataWriteError, isDataWriteError } from \"../schema/write-outcome\";\nimport { toDataWriteError } from \"./postgrest-errors\";\nimport type { BaseRecord, DataProvider, FilterParam } from \"./types\";\n\n/** Anything with Supabase's `rpc`. */\nexport interface RpcClient {\n rpc(fn: string, args?: Record<string, unknown>): PromiseLike<{ data: unknown; error: unknown }>;\n}\n\n/** The words shown for a code when the caller gives none. A guard's own `raise exception` (P0001) keeps its words. */\nexport const DEFAULT_RPC_MESSAGES: Readonly<Record<string, string>> = {\n \"42501\": \"You can't do that.\",\n \"22023\": \"That request isn't valid.\",\n \"23505\": \"That already exists.\",\n \"28000\": \"Sign in to continue.\",\n PGRST202: \"That action isn't available.\",\n PGRST301: \"Sign in to continue.\",\n};\n\nexport const RPC_FAILED = \"That didn't work. Try again.\";\n\nexport interface CallRpcOptions {\n /** Words per error code, e.g. `{ \"55000\": \"This course has already started.\" }`; these win over the defaults. */\n messages?: Record<string, string>;\n}\n\n/**\n * Calls a database function and returns its result. A failure throws a\n * DataWriteError with the usual outcome and code, and words a person can\n * read: yours for the code, a guard's own message (P0001), the defaults\n * above, or a generic sentence. The raw error stays on `cause`.\n */\nexport async function callRpc<T = unknown>(\n client: RpcClient,\n fn: string,\n args: Record<string, unknown> = {},\n options: CallRpcOptions = {},\n): Promise<T> {\n let result: { data: unknown; error: unknown };\n try {\n result = await client.rpc(fn, args);\n } catch (error) {\n // A client that already speaks DataWriteError (signed out, a refusal) keeps its outcome and code.\n if (isDataWriteError(error)) throw error;\n throw new DataWriteError(\"error\", RPC_FAILED, { cause: error });\n }\n if (!result || typeof result !== \"object\") {\n throw new DataWriteError(\"error\", RPC_FAILED, { cause: new Error(`rpc ${fn} returned ${String(result)}`) });\n }\n if (!result.error) return result.data as T;\n const mapped = toDataWriteError(result.error);\n const code = mapped.code;\n const custom = code !== undefined ? options.messages?.[code] : undefined;\n const raw = (result.error as { message?: unknown }).message;\n const guardWords = typeof raw === \"string\" && raw.trim() ? raw : undefined;\n const message =\n custom ??\n (code === \"P0001\" ? guardWords : undefined) ??\n (mapped.fields ? mapped.message : undefined) ??\n (code !== undefined ? DEFAULT_RPC_MESSAGES[code] : undefined) ??\n RPC_FAILED;\n throw new DataWriteError(mapped.outcome, message, { code, fields: mapped.fields, cause: result.error });\n}\n\nexport interface CreateOrAdoptOptions<T extends BaseRecord> {\n /** The fields that make a row unique (its unique index), read from `data`. */\n key: readonly (keyof T & string)[];\n /**\n * Changes to write over a row that was already there; return null to keep it\n * as it is. It runs on the row as read just now, and the update isn't\n * conditional: two callers merging into one row at once can each overwrite\n * the other. Where that matters, merge in a database function instead.\n */\n merge?: (existing: T) => Partial<T> | null;\n}\n\n/**\n * \"One live row per key\": creates the row, or, when one with the same key is\n * already there (a `duplicate`), adopts it, optionally merging changes in.\n * `adopted` says which. A duplicate you can't see is still an error.\n */\nexport async function createOrAdopt<T extends BaseRecord>(\n provider: DataProvider,\n resource: string,\n data: Partial<T>,\n options: CreateOrAdoptOptions<T>,\n): Promise<{ row: T; adopted: boolean }> {\n if (options.key.length === 0) throw new Error(`[genesis-core] createOrAdopt(\"${resource}\") needs a key`);\n try {\n return { row: (await provider.create<T>(resource, { data })).data, adopted: false };\n } catch (error) {\n if (!isDataWriteError(error) || error.outcome !== \"duplicate\") throw error;\n // A clash on some other unique index isn't this key's row.\n if (error.fields && Object.keys(error.fields).some((field) => !options.key.includes(field as keyof T & string))) throw error;\n const filters: FilterParam[] = options.key.map((field) => {\n const value = (data as Record<string, unknown>)[field];\n if (value === null || value === undefined) return { field, operator: \"is_null\" };\n if (typeof value !== \"string\" && typeof value !== \"number\" && typeof value !== \"boolean\") {\n throw new Error(`[genesis-core] createOrAdopt(\"${resource}\") key field ${field} must be a string, number or boolean`);\n }\n return { field, operator: \"eq\", value };\n });\n const { data: rows } = await provider.getList<T>(resource, { filters, pagination: { page: 1, perPage: 2 } });\n if (rows.length !== 1) throw error;\n const existing = rows[0]!;\n const changes = options.merge?.(existing);\n if (!changes || Object.keys(changes).length === 0) return { row: existing, adopted: true };\n return { row: (await provider.update<T>(resource, { id: existing.id, data: changes })).data, adopted: true };\n }\n}\n"]}
|