@marktiderman/genesis-core 1.17.0 → 2.1.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 +7 -4
- package/dist/{chunk-Y452U45I.js → chunk-2VVZ2KX3.js} +3 -3
- package/dist/{chunk-Y452U45I.js.map → chunk-2VVZ2KX3.js.map} +1 -1
- package/dist/{chunk-M4SPLFLL.js → chunk-3FFBW4XC.js} +21 -8
- package/dist/chunk-3FFBW4XC.js.map +1 -0
- package/dist/{chunk-IOTHEKO7.js → chunk-7GW3QR63.js} +45 -12
- package/dist/chunk-7GW3QR63.js.map +1 -0
- package/dist/{chunk-OYIUIW7C.js → chunk-7PUFVNPB.js} +2 -2
- package/dist/chunk-7PUFVNPB.js.map +1 -0
- package/dist/{chunk-VMRLCTZR.js → chunk-CC37H7O2.js} +4 -4
- package/dist/{chunk-VMRLCTZR.js.map → chunk-CC37H7O2.js.map} +1 -1
- package/dist/{chunk-CZOFWG54.js → chunk-GWQHP3RC.js} +3 -3
- package/dist/{chunk-CZOFWG54.js.map → chunk-GWQHP3RC.js.map} +1 -1
- package/dist/{chunk-K7WEY5WR.js → chunk-OSFG3GFY.js} +3 -3
- package/dist/{chunk-K7WEY5WR.js.map → chunk-OSFG3GFY.js.map} +1 -1
- package/dist/{chunk-J2EIM7FC.js → chunk-X6EO3XBB.js} +24 -8
- package/dist/chunk-X6EO3XBB.js.map +1 -0
- package/dist/form-types.d.ts +13 -0
- package/dist/hooks/index.d.ts +2 -2
- package/dist/hooks/index.js +7 -7
- package/dist/hooks/mutation-mode.js +2 -2
- package/dist/hooks/use-infinite-resource.js +2 -2
- package/dist/hooks/use-one.js +2 -2
- package/dist/hooks/use-resource-form.d.ts +11 -1
- package/dist/hooks/use-resource-form.js +4 -4
- package/dist/hooks/use-resource.js +3 -3
- package/dist/index.d.ts +5 -5
- package/dist/index.js +8 -8
- package/dist/provider/index.d.ts +18 -3
- package/dist/provider/index.js +1 -1
- package/dist/resource-view/index.d.ts +141 -10
- package/dist/resource-view/index.js +146 -2
- package/dist/resource-view/index.js.map +1 -1
- package/dist/{viewer-scope-77MqxvmZ.d.ts → viewer-scope-bthEYSOB.d.ts} +24 -6
- package/package.json +52 -1
- package/dist/chunk-IOTHEKO7.js.map +0 -1
- package/dist/chunk-J2EIM7FC.js.map +0 -1
- package/dist/chunk-M4SPLFLL.js.map +0 -1
- package/dist/chunk-OYIUIW7C.js.map +0 -1
|
@@ -42,16 +42,17 @@ declare const NO_VIEWER: Viewer;
|
|
|
42
42
|
*/
|
|
43
43
|
declare function clearViewerCache(queryClient: QueryClient): Promise<void>;
|
|
44
44
|
/**
|
|
45
|
-
* Where the viewer is working: the
|
|
46
|
-
*
|
|
47
|
-
*
|
|
45
|
+
* Where the viewer is working: the person, space or set of people Genesis knows by name, plus
|
|
46
|
+
* whatever the app scopes to under its own key (`{ orgId }`, `{ leagueId }`, `{ locationId }`).
|
|
47
|
+
* Screens turn it into server filters and create defaults (a view's `scope: ["league_id"]` reads
|
|
48
|
+
* `league_id`, then `leagueId`); it never decides access (row-level security does).
|
|
48
49
|
*/
|
|
49
50
|
interface ResourceScope {
|
|
50
|
-
practiceId?: string;
|
|
51
51
|
personId?: string;
|
|
52
52
|
spaceId?: string;
|
|
53
53
|
/** Several people at once (a coach's client list, a group). */
|
|
54
54
|
personIds?: readonly string[];
|
|
55
|
+
/** The app's own scope keys: `orgId`, `leagueId`, `locationId`, … */
|
|
55
56
|
[key: string]: unknown;
|
|
56
57
|
}
|
|
57
58
|
interface ViewerContext {
|
|
@@ -61,6 +62,11 @@ interface ViewerContext {
|
|
|
61
62
|
roles?: GenesisViewerRoles;
|
|
62
63
|
/** The zone the viewer's days are counted in: theirs if known, else the device's. */
|
|
63
64
|
timeZone: string;
|
|
65
|
+
/**
|
|
66
|
+
* The zone of whatever the viewer is scoped to (a location, a league), for columns with
|
|
67
|
+
* `timeZone: "scope"`: ViewerScope's `scopeTimeZone` when valid, else {@link timeZone}.
|
|
68
|
+
*/
|
|
69
|
+
scopeTimeZone?: string;
|
|
64
70
|
/**
|
|
65
71
|
* Today on the viewer's clock (YYYY-MM-DD), kept current when the page comes back into view.
|
|
66
72
|
* Use it for every "today" read and as query keys' `day`: `keys.for(useViewerScope())`.
|
|
@@ -102,10 +108,22 @@ interface ViewerScopeProps {
|
|
|
102
108
|
* rendering on a server, whose own zone is rarely the viewer's.
|
|
103
109
|
*/
|
|
104
110
|
timeZone?: string | null;
|
|
111
|
+
/**
|
|
112
|
+
* The IANA zone of whatever the viewer is scoped to (a location, a league), when it has one.
|
|
113
|
+
* Columns with `timeZone: "scope"` read on it; without it they read on the viewer's clock.
|
|
114
|
+
*/
|
|
115
|
+
scopeTimeZone?: string | null;
|
|
105
116
|
/** Shown while the session loads (and for the one render a change takes). */
|
|
106
117
|
fallback?: ReactNode;
|
|
107
118
|
children: ReactNode;
|
|
108
119
|
}
|
|
120
|
+
/**
|
|
121
|
+
* The scope's clock: `scopeTimeZone` when the runtime knows it, else the viewer's. A zone it
|
|
122
|
+
* doesn't know is never a quiet fallback: it throws in development, and in production it is
|
|
123
|
+
* reported (`reportError`, once per zone) before the viewer's clock is used, so a misspelt zone can't show
|
|
124
|
+
* times on the wrong clock unnoticed.
|
|
125
|
+
*/
|
|
126
|
+
declare function scopeClock(scopeTimeZone: string | null | undefined, viewerZone: string): string;
|
|
109
127
|
/**
|
|
110
128
|
* Keeps one viewer's cached data from ever showing to the next. Children
|
|
111
129
|
* render only once the viewer is known, under a key of that viewer, so a
|
|
@@ -120,6 +138,6 @@ interface ViewerScopeProps {
|
|
|
120
138
|
* </ViewerScope>
|
|
121
139
|
* ```
|
|
122
140
|
*/
|
|
123
|
-
declare function ViewerScope({ viewer, persistedViewer, scope, roles, timeZone, fallback, children }: ViewerScopeProps): react.JSX.Element;
|
|
141
|
+
declare function ViewerScope({ viewer, persistedViewer, scope, roles, timeZone, scopeTimeZone, fallback, children }: ViewerScopeProps): react.JSX.Element;
|
|
124
142
|
|
|
125
|
-
export { type GenesisViewerRoles as G, NO_VIEWER as N, type ResourceScope as R, type Viewer as V, type ViewerContext as a, ViewerScope as b, type ViewerScopeProps as c, clearViewerCache as d, useViewer as e, useViewerScope as f, useOptionalViewerScope as u };
|
|
143
|
+
export { type GenesisViewerRoles as G, NO_VIEWER as N, type ResourceScope as R, type Viewer as V, type ViewerContext as a, ViewerScope as b, type ViewerScopeProps as c, clearViewerCache as d, useViewer as e, useViewerScope as f, scopeClock as s, useOptionalViewerScope as u };
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@marktiderman/genesis-core",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "2.1.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -106,6 +106,57 @@
|
|
|
106
106
|
"vitest": "^4.1.12",
|
|
107
107
|
"zod": "^3.25.67"
|
|
108
108
|
},
|
|
109
|
+
"genesis": {
|
|
110
|
+
"doctor": {
|
|
111
|
+
"prefer": [
|
|
112
|
+
{
|
|
113
|
+
"id": "direct-data-access",
|
|
114
|
+
"need": "data access",
|
|
115
|
+
"level": "warn",
|
|
116
|
+
"files": [
|
|
117
|
+
"**/*.tsx",
|
|
118
|
+
"**/*.jsx"
|
|
119
|
+
],
|
|
120
|
+
"exclude": [
|
|
121
|
+
"src/lib/**",
|
|
122
|
+
"**/*.server.*",
|
|
123
|
+
"**/server/**",
|
|
124
|
+
"**/api/**"
|
|
125
|
+
],
|
|
126
|
+
"forbid": {
|
|
127
|
+
"pattern": "(?:\\b[\\w$]*(?:supabase|Supabase|client|Client|db)[\\w$]*(?:\\(\\))?\\s*\\.\\s*(?:from|rpc)\\s*\\(|\\.schema\\s*\\([^)]*\\)\\s*\\.\\s*(?:from|rpc)\\s*\\(|\\.rpc\\s*\\()"
|
|
128
|
+
},
|
|
129
|
+
"use": "a view (defineView + ResourceView) for reads, the resource's provider writes (useWrite, ResourceForm) for writes, or a named data function in src/lib",
|
|
130
|
+
"import": "@marktiderman/genesis-core",
|
|
131
|
+
"docs": "https://github.com/marktiderman/genesis/blob/main/docs/RESOURCE-VIEW.md",
|
|
132
|
+
"why": "A screen that queries the database hand-writes the data layer the provider and views already are, and its rules drift from the resource's. Server files and src/lib aren't checked; doctor.packageRules can widen or narrow that."
|
|
133
|
+
}
|
|
134
|
+
],
|
|
135
|
+
"primitives": [
|
|
136
|
+
{
|
|
137
|
+
"need": "dates and days",
|
|
138
|
+
"use": "personDay(person), dayIn(zone), never toISOString().slice(0, 10)",
|
|
139
|
+
"import": "@marktiderman/genesis-core/dates"
|
|
140
|
+
},
|
|
141
|
+
{
|
|
142
|
+
"need": "a record's create or edit form",
|
|
143
|
+
"use": "the view's form (ResourceForm), or useResourceForm",
|
|
144
|
+
"import": "@marktiderman/genesis-core/hooks",
|
|
145
|
+
"docs": "https://github.com/marktiderman/genesis/blob/main/docs/RESOURCE-VIEW.md"
|
|
146
|
+
},
|
|
147
|
+
{
|
|
148
|
+
"need": "CSV export and import",
|
|
149
|
+
"use": "the CSV helpers (paged through the provider, formula-safe)",
|
|
150
|
+
"import": "@marktiderman/genesis-core/csv"
|
|
151
|
+
},
|
|
152
|
+
{
|
|
153
|
+
"need": "write errors and refusals",
|
|
154
|
+
"use": "DataWriteError and readFailureMessage",
|
|
155
|
+
"import": "@marktiderman/genesis-core/errors"
|
|
156
|
+
}
|
|
157
|
+
]
|
|
158
|
+
}
|
|
159
|
+
},
|
|
109
160
|
"scripts": {
|
|
110
161
|
"build": "tsup && node ../../scripts/check-exports-resolve.mjs",
|
|
111
162
|
"clean": "rm -rf dist",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/provider/supabase-provider.ts","../src/provider/write-helpers.ts"],"names":["run","from"],"mappings":";;;;;AA+RA,SAAS,eAAA,CAAgB,KAAA,EAAgB,KAAA,EAAe,MAAA,EAAyB;AAC/E,EAAA,IAAI,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AAC,CAAA;AACD,IAAA,MAAM,EAAE,IAAA,EAAM,IAAA,KAAS,MAAM,QAAA,CAAS,QAAW,QAAA,EAAU;AAAA,MACzD,OAAA,EAAS,CAAC,GAAG,OAAA,EAAS,GAAI,OAAA,CAAQ,KAAA,IAAS,EAAG,CAAA;AAAA,MAC9C,UAAA,EAAY,EAAE,IAAA,EAAM,CAAA,EAAG,SAAS,CAAA;AAAE,KACnC,CAAA;AACD,IAAA,IAAI,IAAA,CAAK,MAAA,KAAW,CAAA,EAAG,MAAM,KAAA;AAC7B,IAAA,MAAM,QAAA,GAAW,KAAK,CAAC,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-IOTHEKO7.js","sourcesContent":["import type {\n BaseRecord,\n CountMode,\n DataProvider,\n FilterParam,\n Identifier,\n InvalidationKey,\n ListParams,\n ResourceChangeEvent,\n SortParam,\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 /**\n * How lists of this resource count their total (default `exact`). Use\n * `estimated` for large tables, or `none` when no screen shows a count.\n */\n count?: CountMode;\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\ntype CursorValue = string | number | boolean | null;\n\n/** One sort column a cursor was made for. */\ninterface CursorColumn {\n s: string;\n o: \"asc\" | \"desc\";\n}\n\n/**\n * What a cursor holds: the sort it was made for, and the last row's values.\n * A cursor for one sort column is written as `s`/`o`/`v`; for several, as\n * `c` (the columns) and `vs` (their values, in order).\n */\ninterface CursorState {\n /** Sort field, or null when ordered by the key alone (or by several columns, in `c`). */\n s: string | null;\n /** The sort's order; the key's own order when `s` is null and there is no `c`. */\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?: CursorValue;\n /** Several sort columns, first one first. */\n c?: CursorColumn[];\n /** The last row's values for `c`. */\n vs?: CursorValue[];\n /** The last row's key value (the first row's, for a cursor going back). */\n id: string | number;\n /** \"b\": the rows before this one (a previous page). Absent: the rows after it. */\n d?: \"b\";\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 if (state.d !== undefined && state.d !== \"b\") return undefined;\n if (state.c !== undefined) {\n if (!Array.isArray(state.c) || !Array.isArray(state.vs) || state.c.length !== state.vs.length) return undefined;\n if (!state.c.every((col) => col && typeof col.s === \"string\" && (col.o === \"asc\" || col.o === \"desc\"))) return undefined;\n }\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/** A cursor's sort columns with the row's values, and the key's order. */\nfunction cursorColumns(state: CursorState): { cols: (CursorColumn & { v: CursorValue })[]; keyOrder: \"asc\" | \"desc\" } {\n if (state.c) return { cols: state.c.map((col, i) => ({ ...col, v: state.vs![i] ?? null })), keyOrder: \"asc\" };\n if (state.s === null) return { cols: [], keyOrder: state.o };\n return { cols: [{ s: state.s, o: state.o, v: state.v ?? null }], keyOrder: \"asc\" };\n}\n\n/**\n * The columns a list is ordered by, first one first, before the key: `sorts`\n * when given, else `sort`. A sort on the key ends the list there (the key is\n * unique, so nothing after it can matter) and sets the key's own order;\n * otherwise the key comes last, ascending. A repeated column counts once.\n */\nfunction sortColumns(params: ListParams, key: string): { columns: SortParam[]; keyOrder: \"asc\" | \"desc\" } {\n const requested = params.sorts && params.sorts.length > 0 ? params.sorts : params.sort ? [params.sort] : [];\n const columns: SortParam[] = [];\n for (const sort of requested) {\n if (sort.field === key) return { columns, keyOrder: sort.order ?? \"asc\" };\n if (!columns.some((c) => c.field === sort.field)) columns.push({ field: sort.field, order: sort.order ?? \"asc\" });\n }\n return { columns, keyOrder: \"asc\" };\n}\n\n/**\n * The PostgREST `or` clauses selecting the rows after `state` (before it, for\n * a cursor going back), for a list ordered by each sort column (nulls last\n * when ascending and first when descending, as Postgres orders them by\n * default) and then by the key. Spelled out one column at a time: Postgres's\n * row comparison `(a, b) > (x, y)` doesn't follow that null placement, and\n * PostgREST's filters can't express it anyway.\n * @internal Exported for tests.\n */\nexport function keysetClauses(state: CursorState): string {\n const back = state.d === \"b\";\n const k = state.k;\n const K = quoteFilterValue(state.id);\n const { cols, keyOrder } = cursorColumns(state);\n // The key is unique: within ties on every column, the rows after (or before) by the key.\n const keyAhead = `${k}.${(keyOrder === \"asc\") !== back ? \"gt\" : \"lt\"}.${K}`;\n if (cols.length === 0) return keyAhead;\n // Rows that come later on one column, given equal values on the columns before it. The\n // `is.null` pieces go last, so a one-column cursor reads as it always has.\n const main: string[] = [];\n const tail: string[] = [];\n const equal: string[] = [];\n const within = (piece: string) => (equal.length ? `and(${equal.join(\",\")},${piece})` : piece);\n for (const { s, o, v } of cols) {\n // Ascending puts nulls last; going back mirrors which side is \"ahead\".\n const nullsAhead = (o === \"asc\") !== back;\n if (v === null) {\n if (!nullsAhead) main.push(within(`${s}.not.is.null`));\n equal.push(`${s}.is.null`);\n } else {\n const V = quoteFilterValue(v);\n main.push(within(`${s}.${(o === \"asc\") !== back ? \"gt\" : \"lt\"}.${V}`));\n if (nullsAhead) tail.push(within(`${s}.is.null`));\n equal.push(`${s}.eq.${V}`);\n }\n }\n return [...main, `and(${equal.join(\",\")},${keyAhead})`, ...tail].join(\",\");\n}\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;\n\n/** How long after this client's own write a realtime event for that row is taken as its echo. */\nexport const REALTIME_ECHO_MS = 2000;\n\n/** The realtime filter for a list's first equality filter on a plain column, or undefined. */\nfunction realtimeFilter(filters: FilterParam[] | undefined): string | undefined {\n for (const f of filters ?? []) {\n if (f.operator !== \"eq\" || !/^[a-zA-Z_][a-zA-Z0-9_]*$/.test(f.field)) continue;\n const v = f.value;\n if (typeof v !== \"string\" && typeof v !== \"number\" && typeof v !== \"boolean\") continue;\n // Realtime's filter grammar has no quoting: skip a value it would misread, or an empty one.\n if (typeof v === \"string\" && (v === \"\" || /[,()]/.test(v))) continue;\n return `${f.field}=eq.${String(v)}`;\n }\n return undefined;\n}\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 /** How a list of `resource` counts its total: the caller's, else the resource's, else exact. */\n function countMode(resource: string, params: ListParams): CountMode {\n return params.count ?? configFor(resource).count ?? \"exact\";\n }\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(\n resource: string,\n columns: string | undefined,\n count?: \"exact\" | \"estimated\" | \"planned\",\n ): 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 /**\n * Rows this client wrote just now, `${resource}\\0${id}` → the realtime event their write sends\n * and when. Each channel (one per filter) skips the first matching event once, so a later change\n * to the same row (a trigger, a job, another person) is still heard.\n */\n const recentWrites = new Map<\n string,\n { eventType: \"INSERT\" | \"UPDATE\" | \"DELETE\"; at: number; heardOn: Set<string>; openChannels: Set<object> }\n >();\n\n function noteWrite(event: WriteEvent): void {\n const now = Date.now();\n for (const [key, mark] of recentWrites) if (now - mark.at > REALTIME_ECHO_MS) recentWrites.delete(key);\n const eventType = event.kind === \"create\" ? \"INSERT\" : event.kind === \"delete\" ? \"DELETE\" : \"UPDATE\";\n // Only the channels open now carry this write's echo; one opened later never saw the write.\n const openChannels = new Set(\n [...sharedChannels.entries()].filter(([t]) => t.startsWith(`${event.resource}\\u0000`)).map(([, c]) => c as object),\n );\n recentWrites.set(`${event.resource}\\u0000${String(event.id)}`, { eventType, at: now, heardOn: new Set(), openChannels });\n }\n /** One realtime channel per resource and server filter, shared by every subscriber to it. */\n const sharedChannels = new Map<\n string,\n { listeners: Set<{ emit: (event: ResourceChangeEvent) => void; id?: Identifier }>; close: () => void }\n >();\n\n function isEcho(\n resource: string,\n id: unknown,\n eventType: SupabaseRealtimePayload[\"eventType\"],\n topic: string,\n channelObject: object | undefined,\n ): boolean {\n if (!isIdentifier(id)) return false;\n const key = `${resource}\\u0000${String(id)}`;\n const mark = recentWrites.get(key);\n // Only a channel that was open at the write carries its echo: one reopened on the same topic\n // since then is a different object and never saw it.\n if (!mark || mark.eventType !== eventType || mark.heardOn.has(topic) || !channelObject || !mark.openChannels.has(channelObject)) return false;\n if (Date.now() - mark.at > REALTIME_ECHO_MS) {\n recentWrites.delete(key);\n return false;\n }\n mark.heardOn.add(topic);\n return true;\n }\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 // Its realtime echo is this client's own write: it already refreshes through the write path.\n if (event.id != null) noteWrite(event);\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; prevCursor: 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 { columns, keyOrder } = sortColumns(params, key);\n const unplain = columns.find((c) => !PLAIN_COLUMN.test(c.field));\n if (unplain) return refuseCursor(resource, `cursor paging can sort only by a plain column, not \"${unplain.field}\".`);\n const sortFields = columns.map((c) => c.field);\n // One column keeps the cursor's original shape; several use `c`/`vs`.\n const shape = (values: CursorValue[]): Pick<CursorState, \"s\" | \"o\" | \"v\" | \"c\" | \"vs\"> =>\n columns.length === 0\n ? { s: null, o: keyOrder }\n : columns.length === 1\n ? { s: columns[0]!.field, o: columns[0]!.order, v: values[0] ?? null }\n : { s: null, o: \"asc\", c: columns.map((c) => ({ s: c.field, o: c.order })), vs: values };\n const sortId = JSON.stringify([columns.map((c) => [c.field, c.order]), keyOrder]);\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 const made = cursorColumns(after);\n if (JSON.stringify([made.cols.map((c) => [c.s, c.o]), made.keyOrder]) !== sortId || 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 const mode = countMode(resource, params);\n let query = read(resource, params.select, cursor || mode === \"none\" ? undefined : mode);\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 // Going back reads the rows before the cursor in the reverse order (nearest first), then\n // turns them around.\n const back = after?.d === \"b\";\n for (const { field, order } of columns) {\n // Pinned to Postgres's default null placement, which the keyset assumes.\n const ascending = (order === \"asc\") !== back;\n query = query.order(field, { ascending, nullsFirst: !ascending });\n }\n query = query.order(key, { ascending: (keyOrder === \"asc\") !== back });\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 more = rows.length > perPage;\n const page = rows.slice(0, perPage);\n if (back) page.reverse();\n // A cursor for the rows after or before `row`.\n const cursorAt = (row: Record<string, unknown> | undefined, direction?: \"b\"): string | null | false => {\n if (!row) return null;\n const id = row[key];\n if (!isIdentifier(id) || sortFields.some((f) => !(f in row))) return false;\n const values = sortFields.map((f) => row[f] ?? null);\n if (values.some((v) => v !== null && typeof v === \"object\")) return false;\n return encodeCursor({ ...shape(values as CursorValue[]), k: key, id, ...(direction ? { d: direction } : {}) });\n };\n // Forward: more after the last row when the look-ahead found one; rows before the first\n // whenever this wasn't the first page. Back: the mirror.\n const next = back ? cursorAt(page[page.length - 1]) : more ? cursorAt(page[page.length - 1]) : null;\n const prev = back ? (more ? cursorAt(page[0], \"b\") : null) : cursor ? cursorAt(page[0], \"b\") : null;\n if (next === false || prev === false) {\n const objectValued = sortFields.find((f) =>\n page.some((row) => f in row && row[f] !== null && typeof row[f] === \"object\"),\n );\n if (objectValued) {\n return refuseCursor(resource, `cursor paging can't sort by \"${objectValued}\": its values aren't plain (text, number, date, boolean).`);\n }\n const needed = [key, ...sortFields].map((f) => `\"${f}\"`);\n const list = needed.length === 1 ? needed[0] : `${needed.slice(0, -1).join(\", \")} and ${needed[needed.length - 1]}`;\n return refuseCursor(resource, `the selected columns must include ${list} to page by cursor.`);\n }\n return {\n data: page,\n total: cursor || mode === \"none\" ? -1 : (result.count ?? 0),\n ...(!cursor && (mode === \"estimated\" || mode === \"planned\") ? { totalIsEstimate: true } : {}),\n nextCursor: next,\n prevCursor: prev,\n };\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 mode = countMode(resource, params);\n const run = (key: string | false) => {\n let query = read(resource, params.select, mode === \"none\" ? undefined : mode);\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 // Each sort column, then the key column, so equal sort values keep\n // one order across pages (otherwise a row can repeat on page 2 or be\n // skipped). An unsorted page is ordered by the key alone: without an\n // ORDER BY the database may return pages in any order.\n const requested = params.sorts && params.sorts.length > 0 ? params.sorts : params.sort ? [params.sort] : [];\n if (requested.length > 0 && key) {\n const { columns, keyOrder } = sortColumns(params, key);\n for (const { field, order } of columns) query = query.order(field, { ascending: order === \"asc\" });\n query = query.order(key, { ascending: keyOrder === \"asc\" });\n } else if (requested.length > 0) {\n for (const { field, order } of requested) query = query.order(field, { ascending: order === \"asc\" });\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 {\n data: result.data ?? [],\n total: mode === \"none\" ? -1 : (result.count ?? 0),\n ...(mode === \"estimated\" || mode === \"planned\" ? { totalIsEstimate: true } : {}),\n } 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: true,\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 // One record is matched below, not with a server-side `id=eq.` filter, so it can share the\n // resource's channel. A list's first equality filter narrows the channel on the server.\n // Not for a resource read from a view or function: the filter may name a column only the view\n // has, and the channel watches the table.\n const serverFilter =\n params.id != null || configFor(resource).source !== undefined ? undefined : realtimeFilter(params.filters);\n const topic = `${resource}\\u0000${serverFilter ?? \"\"}`;\n // The row is passed on only where it is the resource's own row: a resource read from a view\n // or function shows other columns, so its listeners refetch instead.\n const sendRecord = configFor(resource).source === undefined;\n let shared = sharedChannels.get(topic);\n if (!shared) {\n const listeners = new Set<{ emit: (event: ResourceChangeEvent) => void; id?: Identifier }>();\n // A unique topic: supabase-js hands back an existing channel for a topic already open.\n const channel = client.channel!(`genesis:${resource}:${++realtimeChannelSeq}`) as SupabaseRealtimeChannel;\n let subscribedOnce = false;\n let interrupted = false;\n const broadcast = (event: ResourceChangeEvent, rowId?: unknown) => {\n for (const l of listeners) {\n if (l.id != null && isIdentifier(rowId) && String(rowId) !== String(l.id)) continue;\n l.emit(event);\n }\n };\n const onChange = (payload: SupabaseRealtimePayload) => {\n // Realtime applies RLS to inserts and updates; a delete's old key goes to every\n // subscriber, so a delete passes on only its id.\n const row = payload.eventType === \"DELETE\" ? payload.old : payload.new;\n const id = row?.[\"id\"];\n if (isEcho(resource, id, payload.eventType, topic, sharedChannels.get(topic))) return;\n const type =\n payload.eventType === \"INSERT\" ? \"created\" : payload.eventType === \"UPDATE\" ? \"updated\" : \"deleted\";\n const event: ResourceChangeEvent = isIdentifier(id)\n ? sendRecord && type !== \"deleted\" && row\n ? { type, id, record: row as BaseRecord }\n : { type, id }\n : { type };\n broadcast(event, id);\n };\n if (serverFilter) {\n // Only inserts are filtered. Realtime filters on the new row, so a filtered update would\n // never report a row leaving the list (status open → closed); and it never delivers\n // deletes through a filter. Both come unfiltered.\n channel.on(\"postgres_changes\", { event: \"INSERT\", schema, table, filter: serverFilter }, onChange);\n channel.on(\"postgres_changes\", { event: \"UPDATE\", schema, table }, onChange);\n channel.on(\"postgres_changes\", { event: \"DELETE\", schema, table }, onChange);\n } else {\n channel.on(\"postgres_changes\", { event: \"*\", schema, table }, onChange);\n }\n channel.subscribe((status) => {\n if (status === \"SUBSCRIBED\") {\n // Back after a drop: changes made meanwhile were not sent.\n if (subscribedOnce && interrupted) broadcast({ 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 shared = {\n listeners,\n close: () => {\n try {\n const done =\n typeof client.removeChannel === \"function\" ? client.removeChannel(channel) : 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 sharedChannels.set(topic, shared);\n }\n let closed = false;\n const listener = {\n id: params.id,\n 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 };\n shared.listeners.add(listener);\n const mine = shared;\n return () => {\n if (closed) return;\n closed = true;\n mine.listeners.delete(listener);\n if (mine.listeners.size === 0 && sharedChannels.get(topic) === mine) {\n sharedChannels.delete(topic);\n mine.close();\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 // How many write marks are held, for tests of the pruning. Not part of the provider contract.\n Object.defineProperty(provider, \"__recentWriteCount\", { value: () => recentWrites.size, enumerable: false });\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 * Extra filters on the lookup, for a partial unique index: the rows the index covers, e.g.\n * `[{ field: \"deleted_at\", operator: \"is_null\" }, { field: \"kind\", operator: \"eq\", value: \"worksheet\" }]`.\n * A clash on an index whose key is an expression reports no fields, so it's adopted by key and scope.\n */\n scope?: readonly FilterParam[];\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, {\n filters: [...filters, ...(options.scope ?? [])],\n pagination: { page: 1, perPage: 2 },\n });\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"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/hooks/use-resource-form.ts"],"names":[],"mappings":";;;;;;;;;;;;;AAsBA,SAAS,oBAAuB,KAAA,EAAa;AAC3C,EAAA,IAAI;AACF,IAAA,OAAO,OAAO,eAAA,KAAoB,UAAA,GAAa,eAAA,CAAgB,KAAK,CAAA,GAAI,KAAA;AAAA,EAC1E,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,KAAA;AAAA,EACT;AACF;AAmGA,SAAS,eAAe,KAAA,EAA2B;AACjD,EAAA,IAAI,OAAO,KAAA,KAAU,SAAA,EAAW,OAAO,QAAA;AACvC,EAAA,IAAI,OAAO,KAAA,KAAU,QAAA,EAAU,OAAO,QAAA;AACtC,EAAA,IAAI,OAAO,UAAU,QAAA,EAAU;AAC7B,IAAA,IAAI,oBAAA,CAAqB,IAAA,CAAK,KAAK,CAAA,EAAG,OAAO,MAAA;AAC7C,IAAA,IAAI,KAAA,CAAM,SAAS,GAAG,CAAA,IAAK,MAAM,QAAA,CAAS,GAAG,GAAG,OAAO,OAAA;AACvD,IAAA,IAAI,cAAA,CAAe,IAAA,CAAK,KAAK,CAAA,EAAG,OAAO,KAAA;AACvC,IAAA,IAAI,KAAA,CAAM,MAAA,GAAS,GAAA,EAAK,OAAO,UAAA;AAAA,EACjC;AACA,EAAA,OAAO,MAAA;AACT;AAGA,SAAS,mBAAA,CACP,KACA,OAAA,EACwE;AACxE,EAAA,IAAI,CAAC,OAAA,IAAW,OAAA,CAAQ,MAAA,KAAW,GAAG,OAAO,IAAA;AAC7C,EAAA,MAAM,YAAA,uBAAmB,GAAA,EAAY;AACrC,EAAA,KAAA,MAAW,OAAO,OAAA,EAAS;AACzB,IAAA,MAAM,CAAA,GAAI,IAAI,GAAG,CAAA;AACjB,IAAA,IAAI,OAAO,MAAM,QAAA,IAA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AM,QAAA,GAAW,WAAA;AAAA,IACf,CAAC,CAAA,KAAwC,IAAA,CAAK,YAAA,CAAa,YAAY,EAAE,CAA6B,CAAA;AAAA,IACtG,CAAC,MAAM,YAAY;AAAA,GACrB;AAEA,EAAA,MAAM,QAAA,GAAW,KAAK,SAAA,CAAU,YAAA;AAEhC,EAAA,OAAO;AAAA,IACL,IAAA;AAAA,IACA,cAAA;AAAA,IACA,QAAA;AAAA,IACA,UAAA,EAAY,YAAA;AAAA,IACZ,QAAA;AAAA,IACA,SAAA;AAAA,IACA,OAAA;AAAA,IACA;AAAA,GACF;AACF","file":"chunk-J2EIM7FC.js","sourcesContent":["import { useMemo, useCallback, useEffect, useRef, useState } from \"react\";\nimport { useForm, type UseFormReturn, type Resolver } from \"react-hook-form\";\nimport { zodResolver } from \"@hookform/resolvers/zod\";\nimport { z } from \"zod\";\nimport { useOne } from \"./use-one\";\nimport { useDataProvider, useStorage } from \"../provider/context\";\nimport { useQueryClient } from \"@tanstack/react-query\";\nimport { titleCase } from \"../utils\";\nimport type { ResourceFormFieldDef, FieldType } from \"../form-types\";\nimport type { BaseRecord, InvalidationKey } from \"../provider/types\";\nimport { relatedKeys } from \"./related-keys\";\nimport { isDataWriteError } from \"../schema/write-outcome\";\nimport {\n cachedRecord,\n executeWrite,\n invalidateResource,\n sameValue,\n type MutationModeOptions,\n} from \"./mutation-mode\";\nimport { useUnsavedChangesGuard } from \"./use-unsaved-changes-guard\";\n\n/** A deep copy where the platform allows one (form values are plain data). */\nfunction structuredCloneSafe<T>(value: T): T {\n try {\n return typeof structuredClone === \"function\" ? structuredClone(value) : value;\n } catch {\n return value;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface UseResourceFormOptions extends MutationModeOptions {\n resource: string;\n action: \"create\" | \"edit\";\n id?: string;\n initialData?: Record<string, unknown>;\n fields?: ResourceFormFieldDef[];\n /** Full dataset used to auto-detect select fields from unique values. */\n listData?: Record<string, unknown>[];\n /**\n * The form is done. After the save in `pessimistic` mode (with the stored\n * row); at once in `optimistic` and `undoable` modes (with the submitted\n * values over the record, and no `id` for a create).\n */\n onSuccess?: (data: Record<string, unknown>) => void;\n /**\n * The save failed. In `optimistic` and `undoable` modes the form may be\n * gone by then, so show the error from here (genesis-ui's ResourceForm\n * toasts it when no `onError` is given).\n */\n onError?: (error: Error) => void;\n /**\n * Warn before unsaved changes are lost. Default false. While the form is\n * dirty, closing or reloading the tab shows the browser's prompt, and\n * `confirmLeave()` asks before in-app navigation (wire it to a router\n * blocker; see SKILL.md \"Unsaved changes\").\n */\n warnWhenUnsaved?: boolean | { message?: string };\n /**\n * Whether the form is on screen. Default true. Pass false while it is\n * hidden but still mounted (a closed dialog). An optimistic or undoable\n * save that fails later is put back on the form (field errors, unsaved\n * again) only while the form is mounted, visible and still holds the\n * values it saved; otherwise the failure only reaches `onError`.\n */\n visible?: boolean;\n /**\n * Pre-fill create form defaults from URL query params: a param named like a\n * field (`?status=draft`) becomes that field's starting value. Default true.\n * Pass false for a form that should not read the page's URL, e.g. one\n * opened from a list whose own filters live in the query string.\n */\n prefillFromUrl?: boolean;\n /**\n * Generate a placeholder (\"Enter name\", \"name@example.com\") for a field\n * whose `placeholder` is unset. Default true. A placeholder that only\n * repeats the label adds noise without information, so `ResourceForm`\n * turns this off unless asked.\n */\n autoPlaceholder?: boolean;\n /** Validation trigger mode. Default \"onBlur\". */\n validationMode?: \"onBlur\" | \"onChange\" | \"onSubmit\";\n /** Enable autosave drafts to localStorage for create mode. */\n autosave?: boolean | { debounceMs?: number };\n /**\n * Other query keys to invalidate after a save, on top of `[resource]` and\n * the provider's own `invalidates`.\n */\n invalidates?: InvalidationKey[];\n /**\n * What an edit sends. `\"loaded\"` (default): every field of the record the form opened with,\n * plus any field the person changed, but never a field the record didn't carry and nobody\n * touched. So a list that didn't load a column (or a value the server left out) can't be\n * overwritten with an empty one. `\"all\"`: every form field, as before.\n */\n updates?: \"loaded\" | \"all\";\n}\n\nexport interface UseResourceFormReturn {\n form: UseFormReturn<Record<string, unknown>>;\n resolvedFields: ResourceFormFieldDef[];\n onSubmit: (e?: { preventDefault?: () => void }) => Promise<void>;\n /** Raw save handler — use with form.handleSubmit(handleSave, onInvalid). */\n handleSave: (data: Record<string, unknown>) => Promise<void>;\n isSaving: boolean;\n isLoading: boolean;\n /**\n * The form has changes that have not been saved. False again once a save\n * succeeds (or, in optimistic / undoable modes, is handed off).\n */\n isDirty: boolean;\n /**\n * For in-app navigation: true when it is fine to leave (nothing unsaved,\n * `warnWhenUnsaved` off, or the user confirmed). Asks with\n * `window.confirm` otherwise.\n */\n confirmLeave: () => boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/** Infer a field type from a value */\nfunction inferFieldType(value: unknown): FieldType {\n if (typeof value === \"boolean\") return \"switch\";\n if (typeof value === \"number\") return \"number\";\n if (typeof value === \"string\") {\n if (/^\\d{4}-\\d{2}-\\d{2}/.test(value)) return \"date\";\n if (value.includes(\"@\") && value.includes(\".\")) return \"email\";\n if (/^https?:\\/\\//.test(value)) return \"url\";\n if (value.length > 100) return \"textarea\";\n }\n return \"text\";\n}\n\n/** Try to infer a select field from unique values across the full dataset */\nfunction inferSelectFromData(\n key: string,\n allData: Record<string, unknown>[] | undefined,\n): { type: \"select\"; options: { value: string; label: string }[] } | null {\n if (!allData || allData.length === 0) return null;\n const uniqueValues = new Set<string>();\n for (const row of allData) {\n const v = row[key];\n if (typeof v === \"string\" && v.length > 0) uniqueValues.add(v);\n }\n if (uniqueValues.size > 0 && uniqueValues.size <= 10) {\n return {\n type: \"select\" as const,\n options: Array.from(uniqueValues)\n .sort()\n .map((v) => ({ value: v, label: v })),\n };\n }\n return null;\n}\n\n/** Generate a sensible placeholder for an auto-inferred field */\nfunction defaultPlaceholder(key: string, type: FieldType): string {\n switch (type) {\n case \"email\": return \"name@example.com\";\n case \"url\": return \"https://...\";\n case \"number\": return \"0\";\n case \"date\": return \"YYYY-MM-DD\";\n case \"textarea\": return `Enter ${titleCase(key).toLowerCase()}...`;\n default: return `Enter ${titleCase(key).toLowerCase()}`;\n }\n}\n\n/** Resolve fields from data keys when none provided */\nfunction resolveFields(\n fields: ResourceFormFieldDef[] | undefined,\n data: Record<string, unknown> | undefined,\n allData?: Record<string, unknown>[],\n autoPlaceholder = true,\n): ResourceFormFieldDef[] {\n const placeholderFor = (key: string, type: FieldType): string | undefined =>\n autoPlaceholder ? defaultPlaceholder(key, type) : undefined;\n if (fields && fields.length > 0) {\n return fields.map((f) => {\n const inferred = f.type ?? (data ? inferFieldType(data[f.key]) : \"text\");\n return {\n ...f,\n label: f.label ?? titleCase(f.key),\n type: inferred,\n placeholder: f.placeholder ?? placeholderFor(f.key, inferred),\n required: f.required ?? (inferred !== \"switch\" && inferred !== \"checkbox\" && inferred !== \"hidden\"),\n };\n });\n }\n\n if (!data) return [];\n\n return Object.keys(data)\n .filter((key) => key !== \"id\" && key !== \"created_at\" && key !== \"updated_at\")\n .map((key) => {\n // Check for select-like field first (string with few unique values)\n if (typeof data[key] === \"string\") {\n const selectInfo = inferSelectFromData(key, allData);\n if (selectInfo) {\n return {\n key,\n label: titleCase(key),\n type: selectInfo.type,\n options: selectInfo.options,\n placeholder: autoPlaceholder\n ? `Select ${titleCase(key).toLowerCase()}...`\n : undefined,\n required: true,\n };\n }\n }\n\n const inferred = inferFieldType(data[key]);\n return {\n key,\n label: titleCase(key),\n type: inferred,\n placeholder: placeholderFor(key, inferred),\n required: inferred !== \"switch\" && inferred !== \"checkbox\" && inferred !== \"hidden\",\n };\n });\n}\n\n/** Build a zod schema from resolved fields */\nfunction buildSchema(fields: ResourceFormFieldDef[], action: \"create\" | \"edit\" = \"create\") {\n const shape: Record<string, z.ZodTypeAny> = {};\n\n for (const field of fields) {\n const fieldType = field.type ?? \"text\";\n\n if (field.hidden || fieldType === \"hidden\") continue;\n // An edit never sends a field read-only on edit, so it isn't checked either: a row loaded\n // without it would otherwise fail \"required\" on a field the person can't fill.\n if (action === \"edit\" && field.readOnlyOnEdit) continue;\n\n // File/image fields store File objects — z.any() is intentional here because\n // the File API shape varies by platform (browser File, React Native asset, etc.)\n // and form libraries may wrap files differently.\n if (fieldType === \"file\" || fieldType === \"image\") {\n shape[field.key] = field.required !== false ? z.unknown().refine((v) => v != null, { message: `${field.label ?? titleCase(field.key)} is required` }) : z.unknown().optional();\n continue;\n }\n\n switch (fieldType) {\n case \"number\": {\n let schema = z.coerce.number({ message: \"Must be a number\" });\n if (field.min != null) schema = schema.min(field.min);\n if (field.max != null) schema = schema.max(field.max);\n shape[field.key] = field.required !== false\n ? schema\n : schema.optional();\n break;\n }\n case \"array\": {\n if (field.arrayFields) {\n const itemShape: Record<string, z.ZodTypeAny> = {};\n for (const sub of field.arrayFields) {\n const subType = sub.type ?? \"text\";\n if (subType === \"number\") {\n let s = z.coerce.number({ message: \"Must be a number\" });\n if (sub.min != null) s = s.min(sub.min);\n if (sub.max != null) s = s.max(sub.max);\n itemShape[sub.key] = sub.required !== false ? s : s.optional();\n } else if (subType === \"switch\" || subType === \"checkbox\") {\n itemShape[sub.key] = z.boolean().optional();\n } else {\n let s = z.string();\n if (sub.required !== false) {\n s = s.min(1, `${sub.label ?? titleCase(sub.key)} is required`);\n }\n if (subType === \"email\") s = s.email(\"Invalid email address\");\n if (subType === \"url\") s = s.url(\"Invalid URL\");\n if (sub.maxLength != null) {\n s = s.max(\n sub.maxLength,\n `${sub.label ?? titleCase(sub.key)} must be ${sub.maxLength} characters or fewer`,\n );\n }\n itemShape[sub.key] = sub.required === false ? s.optional().or(z.literal(\"\")) : s;\n }\n }\n let arraySchema: z.ZodTypeAny = z.array(z.object(itemShape));\n if (field.arrayMin != null) arraySchema = (arraySchema as z.ZodArray<z.ZodTypeAny>).min(field.arrayMin, `Minimum ${field.arrayMin} items required`);\n if (field.arrayMax != null) arraySchema = (arraySchema as z.ZodArray<z.ZodTypeAny>).max(field.arrayMax, `Maximum ${field.arrayMax} items allowed`);\n shape[field.key] = arraySchema;\n }\n break;\n }\n case \"switch\":\n case \"checkbox\": {\n shape[field.key] = z.boolean().optional();\n break;\n }\n default: {\n // text, email, url, textarea, date, select\n let schema = z.string();\n if (field.required !== false) {\n schema = schema.min(1, `${field.label ?? titleCase(field.key)} is required`);\n }\n if (fieldType === \"email\") {\n schema = schema.email(\"Invalid email address\");\n }\n if (fieldType === \"url\") {\n schema = schema.url(\"Invalid URL\");\n }\n if (field.maxLength != null) {\n schema = schema.max(\n field.maxLength,\n `${field.label ?? titleCase(field.key)} must be ${field.maxLength} characters or fewer`,\n );\n }\n shape[field.key] = field.required === false\n ? schema.optional().or(z.literal(\"\"))\n : schema;\n break;\n }\n }\n }\n\n return z.object(shape).passthrough();\n}\n\n/** Build default values for a single array item from its sub-field definitions */\nexport function buildArrayItemDefaults(\n arrayFields: ResourceFormFieldDef[],\n): Record<string, unknown> {\n const defaults: Record<string, unknown> = {};\n for (const sub of arrayFields) {\n const subType = sub.type ?? \"text\";\n if (subType === \"number\") defaults[sub.key] = undefined;\n else if (subType === \"switch\" || subType === \"checkbox\") defaults[sub.key] = false;\n else defaults[sub.key] = sub.defaultValue ?? \"\";\n }\n return defaults;\n}\n\n/** Build default values from fields and existing data */\nfunction buildDefaults(\n fields: ResourceFormFieldDef[],\n data: Record<string, unknown> | undefined,\n action: \"create\" | \"edit\",\n prefillFromUrl: boolean,\n): Record<string, unknown> {\n const defaults: Record<string, unknown> = {};\n for (const field of fields) {\n // A create's blank template (every column as \"\") never hides a field's own default.\n const blankOnCreate = action === \"create\" && data?.[field.key] === \"\" && field.defaultValue !== undefined;\n if (data && field.key in data && !blankOnCreate) {\n defaults[field.key] = data[field.key];\n } else if (field.defaultValue !== undefined) {\n defaults[field.key] = field.defaultValue;\n } else {\n const fieldType = field.type ?? \"text\";\n switch (fieldType) {\n case \"array\":\n defaults[field.key] = field.arrayMin\n ? Array.from({ length: field.arrayMin }, () =>\n buildArrayItemDefaults(field.arrayFields ?? []),\n )\n : [];\n break;\n case \"number\":\n defaults[field.key] = undefined;\n break;\n case \"switch\":\n case \"checkbox\":\n defaults[field.key] = false;\n break;\n default:\n defaults[field.key] = \"\";\n break;\n }\n }\n }\n\n // URL pre-fill for create mode\n if (typeof window !== \"undefined\" && typeof window.location !== \"undefined\" && typeof window.location.search === \"string\" && action === \"create\" && prefillFromUrl !== false) {\n const params = new URLSearchParams(window.location.search);\n for (const field of fields) {\n // A hidden field is the screen's (its filter or defaults), never the URL's.\n if (field.hidden || field.type === \"hidden\") continue;\n const val = params.get(field.key);\n if (val != null) {\n defaults[field.key] = field.type === \"number\" ? Number(val) : val;\n }\n }\n }\n\n return defaults;\n}\n\n// ---------------------------------------------------------------------------\n// Hook\n// ---------------------------------------------------------------------------\n\nexport function useResourceForm(options: UseResourceFormOptions): UseResourceFormReturn {\n const {\n resource,\n action,\n id,\n initialData,\n fields: fieldsProp,\n listData,\n onSuccess,\n onError,\n prefillFromUrl = true,\n autoPlaceholder = true,\n validationMode,\n autosave,\n invalidates,\n warnWhenUnsaved = false,\n mutationMode = \"pessimistic\",\n undoDelayMs,\n onUndoable,\n visible = true,\n updates = \"loaded\",\n } = options;\n\n const autosaveEnabled = !!autosave;\n const debounceMs = typeof autosave === \"object\" ? autosave.debounceMs ?? 1000 : 1000;\n\n const provider = useDataProvider();\n const storage = useStorage();\n const queryClient = useQueryClient();\n\n // Fetch record for edit mode when no initialData\n const needsFetch = action === \"edit\" && !initialData && !!id;\n const fetchResult = useOne(\n resource,\n needsFetch ? id : undefined,\n { enabled: needsFetch },\n );\n\n const fetchedData = fetchResult.data ?? undefined;\n const effectiveData = initialData ?? fetchedData;\n const isLoading = needsFetch && fetchResult.isLoading;\n\n // In edit mode the form starts from the provider's form shape of the row\n // (`DataProvider.toFormValues`), for a resource whose form differs from\n // its table. The record id still comes from the row itself.\n const formSource = useMemo(\n () =>\n action === \"edit\" && effectiveData && provider.toFormValues\n ? provider.toFormValues(resource, effectiveData)\n : effectiveData,\n [action, effectiveData, provider, resource],\n );\n\n // Resolve fields\n const resolvedFields = useMemo(\n () => resolveFields(fieldsProp, formSource, listData, autoPlaceholder),\n [fieldsProp, formSource, listData, autoPlaceholder],\n );\n\n // Build schema\n const schema = useMemo(\n () => buildSchema(resolvedFields, action),\n [resolvedFields, action],\n );\n\n // Build defaults (with optional draft restoration)\n const defaultValues = useMemo(() => {\n const defaults = buildDefaults(resolvedFields, formSource, action, prefillFromUrl);\n if (autosaveEnabled && action === \"create\") {\n const key = `genesis-draft:${resource}:new`;\n const saved = storage.getItem(key);\n if (saved) {\n try {\n const draft = JSON.parse(saved);\n if (draft && typeof draft === \"object\" && !Array.isArray(draft)) {\n // Only restore keys that exist in the field definitions\n const validKeys = new Set(resolvedFields.map((f) => f.key));\n for (const k of Object.keys(draft)) {\n if (validKeys.has(k)) {\n defaults[k] = draft[k];\n }\n }\n } else {\n console.warn(`[useResourceForm] Draft for \"${resource}\" has unexpected shape, removing`);\n storage.removeItem(key);\n }\n } catch {\n console.warn(`[useResourceForm] Corrupt draft for \"${resource}\", removing`);\n storage.removeItem(key);\n }\n }\n }\n return defaults;\n }, [resolvedFields, formSource, action, prefillFromUrl, autosaveEnabled, resource, storage]);\n\n // Form\n // Cast the resolver because zod v4's passthrough() produces `unknown` for input,\n // but react-hook-form expects FieldValues (Record<string, any>).\n const resolver = useMemo(\n () => zodResolver(schema) as unknown as Resolver<Record<string, unknown>>,\n [schema],\n );\n\n const form = useForm<Record<string, unknown>>({\n resolver,\n defaultValues,\n values: action === \"edit\" ? defaultValues : undefined,\n mode: validationMode ?? \"onBlur\",\n reValidateMode: \"onChange\",\n shouldUnregister: true,\n });\n\n // A create form that stays mounted follows its defaults: the screen's hidden values (a new\n // filter or defaults) always, the rest only while the person hasn't typed anything.\n const firstDefaults = useRef(defaultValues);\n useEffect(() => {\n // By value: a screen may hand a new but equal object every render.\n if (action !== \"create\" || sameValue(firstDefaults.current, defaultValues)) return;\n firstDefaults.current = defaultValues;\n if (!form.formState.isDirty) {\n form.reset(defaultValues);\n return;\n }\n for (const field of resolvedFields) {\n if (field.hidden || field.type === \"hidden\") form.setValue(field.key, defaultValues[field.key]);\n }\n }, [action, defaultValues, form, resolvedFields]);\n\n // Autosave effect — persist form values to storage for create mode\n useEffect(() => {\n if (!autosaveEnabled || action !== \"create\") return;\n const key = `genesis-draft:${resource}:new`;\n let timer: ReturnType<typeof setTimeout>;\n\n const subscription = form.watch((values) => {\n clearTimeout(timer);\n timer = setTimeout(() => {\n try {\n storage.setItem(key, JSON.stringify(values));\n } catch (err) {\n console.warn(`[useResourceForm] Autosave failed for \"${resource}\":`, err instanceof Error ? err.message : String(err));\n }\n }, debounceMs);\n });\n\n return () => {\n clearTimeout(timer);\n subscription.unsubscribe();\n };\n }, [autosaveEnabled, resource, action, form, debounceMs, storage]);\n\n // Unsaved changes: RHF's isDirty, cleared by a successful save until the\n // next edit (a create form keeps its values after saving, so RHF alone\n // would still call it dirty).\n const rhfDirty = form.formState.isDirty;\n const [savedClean, setSavedClean] = useState(false);\n const savedCleanRef = useRef(false);\n useEffect(() => {\n const subscription = form.watch((_values, info) => {\n // `watch` also reports resets (no field name); only an edit dirties.\n if (!info.name) return;\n savedCleanRef.current = false;\n setSavedClean(false);\n });\n return () => subscription.unsubscribe();\n }, [form]);\n const isDirty = rhfDirty && !savedClean;\n const warn = !!warnWhenUnsaved;\n const { confirmLeave: guardConfirm } = useUnsavedChangesGuard({\n when: warn && isDirty,\n message: typeof warnWhenUnsaved === \"object\" ? warnWhenUnsaved.message : undefined,\n });\n const confirmLeave = useCallback(\n // The ref, not state: a router blocker may ask in the same tick as the\n // save's onSuccess navigates, before a re-render.\n () => (!warn || savedCleanRef.current ? true : guardConfirm()),\n [warn, guardConfirm],\n );\n const markSaved = useCallback(() => {\n savedCleanRef.current = true;\n setSavedClean(true);\n }, []);\n\n // A save that fails after it was handed off only comes back to the form\n // while the user can still see it.\n const mountedRef = useRef(true);\n useEffect(() => {\n mountedRef.current = true;\n return () => {\n mountedRef.current = false;\n };\n }, []);\n const visibleRef = useRef(visible);\n visibleRef.current = visible;\n\n /** A failed save, on the form: per-field messages and a root summary. */\n const showError = useCallback(\n (error: Error) => {\n const fieldErrors = isDataWriteError(error) ? error.fields : undefined;\n const known = new Set(resolvedFields.map((f) => f.key));\n let first: string | undefined;\n if (fieldErrors) {\n for (const [field, message] of Object.entries(fieldErrors)) {\n if (!known.has(field)) continue;\n form.setError(field, { type: \"server\", message });\n first ??= field;\n }\n }\n form.setError(\"root\", { type: \"server\", message: error.message });\n if (first) {\n try {\n form.setFocus(first);\n } catch {\n // Not rendered (hidden or custom renderForm): the summary still says it.\n }\n }\n },\n [form, resolvedFields],\n );\n\n const reportError = useCallback(\n (error: Error, handedOff?: Record<string, unknown>) => {\n // A save handed off optimistically and then refused is unsaved again,\n // if the form still shows what it saved; a closed, hidden or reset\n // form is left alone.\n const onForm =\n !handedOff ||\n (mountedRef.current && visibleRef.current && sameValue(form.getValues(), handedOff));\n if (onForm) {\n savedCleanRef.current = false;\n setSavedClean(false);\n showError(error);\n }\n if (onError) {\n onError(error);\n } else {\n console.error(`[useResourceForm] ${action} failed for \"${resource}\":`, error);\n }\n },\n [form, showError, onError, action, resource],\n );\n\n // Submit handler\n const handleSubmit = useCallback(\n async (submitted: Record<string, unknown>) => {\n // What the form shows as this save goes out (raw input values, before\n // any resolver coercion), to tell later whether it still does.\n const shown = structuredCloneSafe(form.getValues());\n // A field the opened record didn't carry goes only when the person changed it (compared by\n // value: RHF's dirtyFields updates only when read during render).\n const opened = formSource as Record<string, unknown> | undefined;\n // A field read-only when editing is never written by an edit: sending even its unchanged\n // value would fail on a column the person may not update.\n const lockedOnEdit = new Set(action === \"edit\" ? resolvedFields.filter((f) => f.readOnlyOnEdit).map((f) => f.key) : []);\n const writable = lockedOnEdit.size\n ? Object.fromEntries(Object.entries(submitted).filter(([k]) => !lockedOnEdit.has(k)))\n : submitted;\n const formData =\n action === \"edit\" && updates === \"loaded\" && opened\n ? Object.fromEntries(\n Object.entries(writable).filter(\n // Changed: what an input shows differs from where it started, or, for a value saved\n // without an input (a direct handleSave), the value itself does.\n ([k, v]) =>\n k in opened ||\n !sameValue(k in (shown as object) ? (shown as Record<string, unknown>)[k] : v, defaultValues[k]),\n ),\n )\n : writable;\n // An edit with nothing left to write (only read-only fields) has nothing to send.\n if (action === \"edit\" && Object.keys(formData).length === 0) {\n markSaved();\n onSuccess?.({ ...(effectiveData ?? {}), ...(id != null && id !== \"\" ? { id } : {}) });\n return;\n }\n try {\n let recordId: string | number | undefined;\n if (action === \"edit\") {\n recordId = id ?? String((effectiveData as Record<string, unknown>)?.id ?? \"\");\n if (!recordId) {\n throw new Error(\"Cannot update record: no ID available. Provide an id prop or ensure the record has an id field.\");\n }\n }\n const before = recordId != null ? cachedRecord(queryClient, resource, recordId) : undefined;\n const outcome = await executeWrite<BaseRecord>({\n queryClient,\n provider,\n resource,\n kind: action === \"create\" ? \"create\" : \"update\",\n id: recordId,\n // The cache holds rows; patch it only when the form's values are\n // row-shaped (no provider.toFormValues reshaping this record).\n data: formSource === effectiveData ? formData : undefined,\n mode: mutationMode,\n undoDelayMs,\n onUndoable,\n send: async (ctx) => {\n const keepalive = ctx.keepalive ? { keepalive: true } : {};\n const res =\n action === \"create\"\n ? await provider.create(resource, { data: formData, ...keepalive })\n : await provider.update(resource, { id: recordId!, data: ctx.data ?? formData, ...keepalive });\n return { record: res.data, audit: res.audit };\n },\n committed: async (result) => {\n // Clear draft on successful save\n if (autosaveEnabled && action === \"create\") {\n try {\n storage.removeItem(`genesis-draft:${resource}:new`);\n } catch (err) {\n console.warn(`[useResourceForm] Draft cleanup failed for \"${resource}\":`, err instanceof Error ? err.message : String(err));\n }\n }\n // Invalidate queries to refresh data: the resource's own, then any\n // related keys the provider or the caller named.\n await invalidateResource(queryClient, resource);\n const related = relatedKeys(\n provider,\n {\n resource,\n kind: action === \"create\" ? \"create\" : \"update\",\n id: (recordId ?? result.id) as string | number,\n record: result,\n },\n invalidates,\n );\n await Promise.all(related.map((queryKey) => queryClient.invalidateQueries({ queryKey: [...queryKey] })));\n },\n failedLater: (error) => reportError(error, shown),\n });\n markSaved();\n if (outcome.status === \"committed\") {\n onSuccess?.(outcome.record);\n } else {\n onSuccess?.(\n action === \"edit\"\n ? { ...(before ?? effectiveData ?? {}), ...formData, id: recordId }\n : { ...formData },\n );\n }\n } catch (err) {\n reportError(err instanceof Error ? err : new Error(String(err)));\n }\n },\n [form, action, provider, resource, id, effectiveData, formSource, queryClient, onSuccess, autosaveEnabled, storage, invalidates, mutationMode, undoDelayMs, onUndoable, reportError, markSaved, updates, defaultValues, resolvedFields],\n );\n\n const onSubmit = useCallback(\n (e?: { preventDefault?: () => void }) => form.handleSubmit(handleSubmit)(e as React.BaseSyntheticEvent),\n [form, handleSubmit],\n );\n\n const isSaving = form.formState.isSubmitting;\n\n return {\n form,\n resolvedFields,\n onSubmit,\n handleSave: handleSubmit,\n isSaving,\n isLoading,\n isDirty,\n confirmLeave,\n };\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/hooks/viewer-scope.tsx"],"names":["Fragment"],"mappings":";;;;;;;;;AAUA,IAAI,cAAA,GAAiB,KAAA;AAOrB,SAAS,WAAW,KAAA,EAA+C;AACjE,EAAA,IAAI,QAAA,GAAW,KAAA;AACf,EAAA,MAAM,KAAA,GAAQ,CAAC,CAAA,KAAwB;AACrC,IAAA,IAAI,MAAM,OAAA,CAAQ,CAAC,GAAG,OAAO,CAAA,CAAE,IAAI,KAAK,CAAA,CAAE,GAAA,CAAI,CAAC,MAAM,CAAC,UAAA,CAAW,CAAC,CAAA,EAAG,CAAC,CAAU,CAAA,CAAE,IAAA,CAAK,CAAC,CAAC,CAAC,CAAA,EAAG,CAAC,CAAC,CAAA,KAAO,CAAA,GAAI,IAAI,EAAA,GAAK,CAAA,GAAI,IAAI,CAAA,GAAI,CAAE,EAAE,GAAA,CAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAA;AACn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AAU;AAGrD,IAAA,KAAK,mBAAmB,WAAW,CAAA,CAAE,KAAK,MAAM,WAAA,CAAY,mBAAmB,CAAA;AAAA,EACjF,CAAA,EAAG,CAAC,MAAA,EAAQ,QAAA,EAAU,WAAW,CAAC,CAAA;AAGlC,EAAA,MAAM,CAAC,OAAA,EAAS,UAAU,CAAA,GAAI,SAA+D,MAAS,CAAA;AACtG,EAAA,IAAI,WAAW,MAAA,EAAW,uBAAO,GAAA,CAAAA,QAAAA,EAAA,EAAG,QAAA,EAAA,QAAA,EAAS,CAAA;AAC7C,EAAA,IAAI,OAAA,KAAY,MAAA,IAAa,OAAA,CAAQ,MAAA,KAAW,MAAA,EAAQ;AACtD,IAAA,MAAM,IAAA,GAAO,OAAA,KAAY,MAAA,IAAa,eAAA,KAAoB,UAAa,eAAA,KAAoB,MAAA;AAG3F,IAAA,IAAI,CAAC,IAAA,EAAM;AAIT,MAAA,iBAAA,CAAkB,WAAW,CAAA;AAC7B,MAAA,KAAK,YAAY,aAAA,EAAc;AAC/B,MAAA,WAAA,CAAY,KAAA,EAAM;AAAA,IACpB;AACA,IAAA,UAAA,CAAW,EAAE,MAAA,EAAQ,KAAA,EAAA,CAAQ,SAAS,KAAA,IAAS,CAAA,IAAK,GAAG,CAAA;AACvD,IAAA,uBAAO,GAAA,CAAAA,QAAAA,EAAA,EAAG,QAAA,EAAA,QAAA,EAAS,CAAA;AAAA,EACrB;AACA,EAAA,uBACE,GAAA,CAAC,kBAAA,CAAmB,QAAA,EAAnB,EAA4B,OAC3B,QAAA,kBAAA,GAAA,CAACA,UAAA,EAAA,EAA6D,QAAA,EAAA,EAA/C,CAAA,EAAG,UAAU,YAAY,CAAA,CAAA,EAAI,OAAA,CAAQ,KAAK,EAAc,CAAA,EACzE,CAAA;AAEJ","file":"chunk-M4SPLFLL.js","sourcesContent":["import { useQueryClient, type QueryClient } from \"@tanstack/react-query\";\nimport { createContext, Fragment, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from \"react\";\nimport { dayIn, personTimeZone, type Day } from \"../dates\";\nimport { reportError } from \"../errors\";\nimport { stableJson } from \"./draft-controller\";\nimport { NO_VIEWER, type GenesisViewerRoles, type Viewer } from \"../viewer\";\nimport { dropPendingWrites, flushPendingWrites } from \"./mutation-mode\";\n\nexport { NO_VIEWER, type GenesisViewerRoles, type Viewer };\n\nlet warnedNotPlain = false;\n\n/**\n * Roles as a value: object keys and lists sorted, so `[\"editor\", \"owner\"]` equals\n * `[\"owner\", \"editor\"]`. A Set, Map or class would stringify as `{}` and hide a change: in\n * development that throws; in production it warns once and the roles count as unknown (undefined).\n */\nfunction rolesKeyOf(roles: GenesisViewerRoles): string | undefined {\n let notPlain = false;\n const plain = (v: unknown): unknown => {\n if (Array.isArray(v)) return v.map(plain).map((x) => [stableJson(x), x] as const).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([, x]) => x);\n if (v && typeof v === \"object\") {\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) {\n if (process.env.NODE_ENV !== \"production\") throw new TypeError(\"[genesis-core] ViewerScope roles must be plain JSON (no Set, Map or class)\");\n notPlain = true;\n return null;\n }\n return Object.fromEntries(Object.entries(v as Record<string, unknown>).map(([k, x]) => [k, plain(x)]));\n }\n return v;\n };\n const key = stableJson(plain(roles));\n if (!notPlain) return key;\n if (!warnedNotPlain) {\n warnedNotPlain = true;\n reportError(new TypeError(\"ViewerScope roles must be plain JSON (no Set, Map or class); treating them as unknown, so guards that need them refuse\"), \"core:viewer-scope\");\n }\n return undefined;\n}\n\n/** Today in `zone`, rechecked when the page comes back into view and at the next minute boundary while it's open. */\nfunction useToday(zone: string): Day {\n const [day, setDay] = useState(() => dayIn(zone));\n useEffect(() => {\n const check = () => setDay(dayIn(zone));\n check();\n const onVisible = () => {\n if (typeof document === \"undefined\" || document.visibilityState === \"visible\") check();\n };\n if (typeof document !== \"undefined\") document.addEventListener(\"visibilitychange\", onVisible);\n // A page left open over midnight rolls over within a minute.\n const timer = setInterval(check, 60_000);\n return () => {\n if (typeof document !== \"undefined\") document.removeEventListener(\"visibilitychange\", onVisible);\n clearInterval(timer);\n };\n }, [zone]);\n return day;\n}\n\n/**\n * Empties the query cache for a new viewer: sends the old viewer's waiting\n * undoable writes (the session is still theirs), cancels reads in flight,\n * then removes every query. Call it in the sign-in and sign-out actions,\n * before the session changes.\n */\nexport async function clearViewerCache(queryClient: QueryClient): Promise<void> {\n await flushPendingWrites(queryClient);\n await queryClient.cancelQueries();\n queryClient.clear();\n}\n\n/**\n * Where the viewer is working: the current practice, person or space, or a set\n * of people. Screens turn it into server filters and create defaults; it never\n * decides access (row-level security does).\n */\nexport interface ResourceScope {\n practiceId?: string;\n personId?: string;\n spaceId?: string;\n /** Several people at once (a coach's client list, a group). */\n personIds?: readonly string[];\n [key: string]: unknown;\n}\n\nexport interface ViewerContext {\n viewer: string | null;\n scope: ResourceScope;\n /** The viewer's roles (see `GenesisViewerRoles`), when ViewerScope was given them. */\n roles?: GenesisViewerRoles;\n /** The zone the viewer's days are counted in: theirs if known, else the device's. */\n timeZone: string;\n /**\n * Today on the viewer's clock (YYYY-MM-DD), kept current when the page comes back into view.\n * Use it for every \"today\" read and as query keys' `day`: `keys.for(useViewerScope())`.\n */\n day: Day;\n}\n\nconst ViewerContextValue = createContext<ViewerContext | null>(null);\n\n/** The viewer and scope from the nearest `ViewerScope`. Throws without one: screens that cache per viewer need it. */\nexport function useViewerScope(): ViewerContext {\n const value = useContext(ViewerContextValue);\n if (!value) throw new Error(\"[genesis-core] useViewerScope needs a <ViewerScope> above it\");\n return value;\n}\n\n/** Like useViewerScope, or null outside a ViewerScope. */\nexport function useOptionalViewerScope(): ViewerContext | null {\n return useContext(ViewerContextValue);\n}\n\n/**\n * The viewer for guards: `{ id, scope, roles }` from the nearest ViewerScope, or\n * {@link NO_VIEWER} without one. The object is stable while those are equal by value, so it can\n * sit in a memo's dependencies.\n */\nexport function useViewer(): Viewer {\n const context = useContext(ViewerContextValue);\n return useMemo<Viewer>(\n () =>\n context\n ? Object.freeze({ id: context.viewer, scope: context.scope, ...(context.roles !== undefined ? { roles: context.roles } : {}) })\n : NO_VIEWER,\n [context],\n );\n}\n\nexport interface ViewerScopeProps {\n /** The signed-in viewer's id, null when signed out, undefined while the session loads. */\n viewer: string | null | undefined;\n /**\n * The viewer a persisted cache was saved for. When the first known viewer\n * is this one, the restored cache is kept; otherwise it's emptied.\n */\n persistedViewer?: string | null;\n /** Where the viewer is working (see `ResourceScope`). Changing it doesn't remount or clear anything. */\n scope?: ResourceScope;\n /**\n * What the viewer may do there (see `GenesisViewerRoles`), for view guards. Compared by value,\n * so a new object with the same roles changes nothing. Undefined while they load: guards that\n * need them refuse. Arriving (undefined → roles) or going back to undefined changes nothing;\n * different roles send the person's waiting writes, then reread every query, with nothing\n * remounted. Plain JSON values only (lists are compared as sets, in any order): a Set, Map or\n * class instance throws in development; in production it warns once and the roles count as\n * unknown (as if undefined), so guards that need them refuse.\n */\n roles?: GenesisViewerRoles;\n /**\n * The viewer's saved time zone (IANA), when known; else the device's is used. Pass it when\n * rendering on a server, whose own zone is rarely the viewer's.\n */\n timeZone?: string | null;\n /** Shown while the session loads (and for the one render a change takes). */\n fallback?: ReactNode;\n children: ReactNode;\n}\n\n/**\n * Keeps one viewer's cached data from ever showing to the next. Children\n * render only once the viewer is known, under a key of that viewer, so a\n * sign-out or a new person signing in unmounts every screen and its queries\n * before the cache is emptied and the new viewer's screens mount fresh. The\n * first known viewer empties a restored cache too, unless it's the\n * `persistedViewer` it was saved for.\n *\n * ```tsx\n * <ViewerScope viewer={session === undefined ? undefined : (session?.user.id ?? null)}>\n * <App />\n * </ViewerScope>\n * ```\n */\nexport function ViewerScope({ viewer, persistedViewer, scope, roles, timeZone, fallback = null, children }: ViewerScopeProps) {\n const queryClient = useQueryClient();\n const zone = personTimeZone({ timeZone });\n const day = useToday(zone);\n // A new scope object each render shouldn't re-render every reader: compare by value.\n const scopeKey = stableJson(scope ?? {});\n // Roles by value too: undefined stays undefined, so \"not known yet\" never equals \"none\".\n // Roles that aren't plain JSON count as unknown in production (rolesKeyOf warns; development throws).\n const rolesKey = roles === undefined ? undefined : rolesKeyOf(roles);\n const value = useMemo<ViewerContext>(\n () => ({ viewer: viewer ?? null, scope: scope ?? {}, ...(rolesKey !== undefined ? { roles } : {}), timeZone: zone, day }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [viewer, scopeKey, rolesKey, zone, day],\n );\n // The last roles known for this viewer. Arriving (undefined → roles) or going back to undefined\n // changes nothing; different roles for the same person send their waiting writes, then reread\n // everything under the new roles. Nothing remounts: the person, their drafts and their\n // navigation are the same.\n const known = useRef<{ viewer: string | null | undefined; roles: string | undefined }>({ viewer, roles: undefined });\n useEffect(() => {\n if (known.current.viewer !== viewer) known.current = { viewer, roles: undefined };\n if (rolesKey === undefined) return;\n const previous = known.current.roles;\n known.current.roles = rolesKey;\n if (previous === undefined || previous === rolesKey) return;\n // The session is still theirs: their writes go out, and the database decides each one with the\n // roles as they are when it arrives (a refused one fails as any refused write does).\n void flushPendingWrites(queryClient).then(() => queryClient.invalidateQueries());\n }, [viewer, rolesKey, queryClient]);\n // Who the children were last mounted for, and how many times they were reset. Undefined before\n // the first mount.\n const [mounted, setMounted] = useState<{ viewer: string | null; epoch: number } | undefined>(undefined);\n if (viewer === undefined) return <>{fallback}</>;\n if (mounted === undefined || mounted.viewer !== viewer) {\n const keep = mounted === undefined && persistedViewer !== undefined && persistedViewer === viewer;\n // Nothing for the new viewer is mounted yet, so emptying now can't strand\n // a fetch; the old viewer's screens unmount with this render.\n if (!keep) {\n // The session already belongs to the new viewer: the old one's unsent\n // writes must never go out under it. (clearViewerCache, run before the\n // session changes, sends them instead.)\n dropPendingWrites(queryClient);\n void queryClient.cancelQueries();\n queryClient.clear();\n }\n setMounted({ viewer, epoch: (mounted?.epoch ?? 0) + 1 });\n return <>{fallback}</>;\n }\n return (\n <ViewerContextValue.Provider value={value}>\n <Fragment key={`${viewer ?? \"signed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AACvC,IAAA,IAAI,IAAA,IAAQ,MAAM,MAAM,IAAI,MAAM,CAAA,eAAA,EAAkB,MAAM,CAAA,2BAAA,EAA8B,IAAI,CAAA,CAAA,CAAG,CAAA;AAC/F,IAAA,IAAA,CAAK,IAAI,CAAA,GAAI,EAAE,KAAK,CAAC,MAAA,EAAQ,IAAI,CAAA,EAAW;AAAA,EAC9C;AACA,EAAA,OAAO,IAAA;AACT;AAMO,SAAS,aAAa,QAAA,EAAkB;AAC7C,EAAA,OAAO;AAAA,IACL,GAAA,EAAK,CAAC,QAAQ,CAAA;AAAA,IACd,KAAA,EAAO,CAAC,QAAA,EAAU,MAAM,CAAA;AAAA,IACxB,MAAM,CAAC,MAAA,KAAuB,CAAC,QAAA,EAAU,QAAQ,MAAM,CAAA;AAAA,IACvD,OAAA,EAAS,CAAC,QAAA,EAAU,QAAQ,CAAA;AAAA;AAAA,IAE5B,WAAW,CAAC,EAAA,KAAsC,CAAC,QAAA,EAAU,UAAU,EAAE,CAAA;AAAA,IACzE,MAAA,EAAQ,CAAC,EAAA,EAAmC,MAAA,KAAoB,CAAC,QAAA,EAAU,QAAA,EAAU,IAAI,MAAM,CAAA;AAAA,IAC/F,UAAU,CAAC,MAAA,KAAoB,CAAC,QAAA,EAAU,YAAY,MAAM;AAAA,GAC9D;AACF","file":"chunk-OYIUIW7C.js","sourcesContent":["// ---------------------------------------------------------------------------\n// Query keys (README \"Query keys\")\n//\n// One place that builds every cache key, so a write invalidates what it made\n// stale and nothing shows across people. Keys are `[domain, kind, fields]`:\n// TanStack matches keys by prefix and matches objects by their fields, so\n// `[domain]` and `[domain, kind]` invalidate everything under them, and\n// `where({...})` reaches keys by any field, including one person inside a\n// multi-person key.\n//\n// App keys are scoped to the signed-in viewer by default: `for({ viewer })`\n// is the only way to build one, and the scope (viewer, group, day) is part of\n// the fields. Resource keys carry no viewer: `ViewerScope` (or\n// `clearViewerCache` in the sign-in/out action) keeps those apart.\n// ---------------------------------------------------------------------------\n\nimport type { Query } from \"@tanstack/react-query\";\nimport type { Identifier, ListParams } from \"./provider/types\";\n\n/** Who and when a key is for. `viewer` is required; null means signed out. */\nexport interface KeyScope {\n viewer: string | null;\n /** The group, practice or space the screen is filtered to. */\n group?: string | null;\n /** The person-day (YYYY-MM-DD) a \"today\" read is for. */\n day?: string | null;\n /**\n * Where the viewer is working (ViewerScope's `scope`: practice, person, space…). Part of every\n * key, so the same query for two practices never shares a cache entry.\n */\n scope?: Readonly<Record<string, unknown>>;\n}\n\ntype Fields = Record<string, unknown>;\ntype QueryDefs = Record<string, (...args: never[]) => Fields>;\n\nexport type ScopedKey<D extends string, K> = readonly [D, K, Fields];\n\n/** A filter for `invalidateQueries` / `removeQueries` / `getQueriesData`. */\nexport interface KeyFilter {\n predicate: (query: Query) => boolean;\n}\n\nexport type QueryKeys<D extends string, Q extends QueryDefs> = {\n /** Every key in the domain: `[domain]`. */\n readonly all: readonly [D];\n /** Builds keys for one scope. */\n for(scope: KeyScope): { [K in keyof Q]: (...args: Parameters<Q[K]>) => ScopedKey<D, K> };\n /**\n * Keys whose fields match `fields`: an equal value (`1` matches `\"1\"`,\n * objects whatever their key order), an array field containing the value,\n * or, for an array value, an array field containing every item. `kind`\n * narrows it to one query.\n */\n where(fields: Fields, kind?: keyof Q): KeyFilter;\n} & { readonly [K in keyof Q]: { readonly all: readonly [D, K] } };\n\nfunction scopeFields(scope: KeyScope): Fields {\n const out: Fields = { viewer: scope.viewer };\n if (scope.group !== undefined) out.group = scope.group;\n if (scope.day !== undefined) out.day = scope.day;\n // Key order doesn't matter: TanStack hashes keys with object keys sorted.\n if (scope.scope && Object.keys(scope.scope).length > 0) out.scope = { ...scope.scope };\n return out;\n}\n\nconst stableText = (value: unknown) =>\n JSON.stringify(value, (_key, v: unknown) =>\n v && typeof v === \"object\" && !Array.isArray(v)\n ? Object.fromEntries(Object.entries(v as Fields).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)))\n : v,\n );\n\n/** Equal, with numbers and their text equal, and objects equal whatever their key order. */\nfunction same(a: unknown, b: unknown): boolean {\n if (a === b) return true;\n const scalar = (v: unknown) => typeof v === \"string\" || typeof v === \"number\" || typeof v === \"boolean\";\n if (scalar(a) && scalar(b)) return String(a) === String(b);\n return stableText(a) === stableText(b);\n}\n\nfunction fieldMatches(have: unknown, want: unknown): boolean {\n if (same(have, want)) return true;\n if (!Array.isArray(have)) return false;\n // An empty list asks for an empty list, not \"any list\".\n if (Array.isArray(want)) return want.length > 0 && want.every((w) => have.some((h) => same(h, w)));\n return have.some((h) => same(h, want));\n}\n\n/**\n * The keys of one domain. Each query maps its arguments to the fields that\n * make it distinct (sort arrays so order never makes two keys):\n *\n * ```ts\n * export const worksheetKeys = defineQueryKeys(\"worksheet-items\", {\n * lessonParts: (people: string[]) => ({ people: [...people].sort() }),\n * byEntry: (entryId: string) => ({ entryId }),\n * });\n * useQuery({ queryKey: worksheetKeys.for({ viewer }).lessonParts(people), … });\n * queryClient.invalidateQueries(worksheetKeys.where({ people: personId }));\n * queryClient.invalidateQueries(worksheetKeys.where({ entryId }, \"byEntry\"));\n * queryClient.invalidateQueries({ queryKey: worksheetKeys.lessonParts.all });\n * ```\n */\nexport function defineQueryKeys<const D extends string, Q extends QueryDefs>(domain: D, queries: Q): QueryKeys<D, Q> {\n const keys: Record<string, unknown> = {\n all: [domain] as const,\n for(scope: KeyScope) {\n if (!scope || !(\"viewer\" in scope)) throw new Error(`[genesis-core] ${domain} keys need a scope with a viewer`);\n const scoped = scopeFields(scope);\n return Object.fromEntries(\n Object.entries(queries).map(([kind, fields]) => [\n kind,\n (...args: never[]) => {\n const own = fields(...args);\n for (const name of Object.keys(scoped)) {\n if (name in own) throw new Error(`[genesis-core] ${domain}.${kind} can't name a field \"${name}\": it's the scope's`);\n }\n return [domain, kind, { ...own, ...scoped }] as const;\n },\n ]),\n );\n },\n where(fields: Fields, kind?: string): KeyFilter {\n return {\n predicate: (query) => {\n const [d, k, f] = query.queryKey as readonly unknown[];\n if (d !== domain || (kind !== undefined && k !== kind)) return false;\n if (!f || typeof f !== \"object\") return Object.keys(fields).length === 0;\n // A key without the field never matches it, even when the value asked for is undefined.\n return Object.entries(fields).every(([name, want]) => name in f && fieldMatches((f as Fields)[name], want));\n },\n };\n },\n };\n for (const kind of Object.keys(queries)) {\n if (kind in keys) throw new Error(`[genesis-core] ${domain} can't have a query named \"${kind}\"`);\n keys[kind] = { all: [domain, kind] as const };\n }\n return keys as QueryKeys<D, Q>;\n}\n\n/**\n * The keys Genesis's own hooks cache a resource under, for writing into or\n * invalidating them by hand: `[resource]` covers them all.\n */\nexport function resourceKeys(resource: string) {\n return {\n all: [resource] as const,\n lists: [resource, \"list\"] as const,\n list: (params: ListParams) => [resource, \"list\", params] as const,\n details: [resource, \"detail\"] as const,\n /** Every projection of one record: `detail(id, select)` for any `select`. */\n detailsOf: (id: Identifier | null | undefined) => [resource, \"detail\", id] as const,\n detail: (id: Identifier | null | undefined, select?: string) => [resource, \"detail\", id, select] as const,\n infinite: (params: unknown) => [resource, \"infinite\", params] as const,\n };\n}\n\n"]}
|