@marktiderman/genesis-core 2.16.1 → 2.17.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 +3 -2
- package/dist/{aggregate-Y5IJ5aPn.d.ts → aggregate-v_r-nZbH.d.ts} +1 -1
- package/dist/{chunk-M5IX7C6U.js → chunk-24X4HWL5.js} +4 -4
- package/dist/{chunk-M5IX7C6U.js.map → chunk-24X4HWL5.js.map} +1 -1
- package/dist/chunk-2ORQLYVW.js +115 -0
- package/dist/chunk-2ORQLYVW.js.map +1 -0
- package/dist/{chunk-XPBS5YE4.js → chunk-4POVYF6P.js} +4 -4
- package/dist/{chunk-XPBS5YE4.js.map → chunk-4POVYF6P.js.map} +1 -1
- package/dist/{chunk-IYGVJFCV.js → chunk-5KLIFJYG.js} +3 -3
- package/dist/{chunk-IYGVJFCV.js.map → chunk-5KLIFJYG.js.map} +1 -1
- package/dist/{chunk-ALLWIK62.js → chunk-6B4CN2TC.js} +8 -6
- package/dist/chunk-6B4CN2TC.js.map +1 -0
- package/dist/chunk-6JOWGO2X.js +266 -0
- package/dist/chunk-6JOWGO2X.js.map +1 -0
- package/dist/{chunk-E3K2A3PK.js → chunk-6SHGMEA6.js} +3 -3
- package/dist/{chunk-E3K2A3PK.js.map → chunk-6SHGMEA6.js.map} +1 -1
- package/dist/chunk-6VNM6KAX.js +59 -0
- package/dist/chunk-6VNM6KAX.js.map +1 -0
- package/dist/{chunk-SOO54YYY.js → chunk-AQX5HQD6.js} +3 -3
- package/dist/{chunk-SOO54YYY.js.map → chunk-AQX5HQD6.js.map} +1 -1
- package/dist/chunk-BNKP2H7J.js +11 -0
- package/dist/chunk-BNKP2H7J.js.map +1 -0
- package/dist/{chunk-FXPODKCK.js → chunk-FBMKI22S.js} +6 -6
- package/dist/{chunk-FXPODKCK.js.map → chunk-FBMKI22S.js.map} +1 -1
- package/dist/{chunk-POUI7GAI.js → chunk-JF7FXSQB.js} +5 -5
- package/dist/{chunk-POUI7GAI.js.map → chunk-JF7FXSQB.js.map} +1 -1
- package/dist/chunk-JNWTHDGF.js +892 -0
- package/dist/chunk-JNWTHDGF.js.map +1 -0
- package/dist/chunk-K33LWVUF.js +31 -0
- package/dist/chunk-K33LWVUF.js.map +1 -0
- package/dist/chunk-KRRESUXT.js +192 -0
- package/dist/chunk-KRRESUXT.js.map +1 -0
- package/dist/{chunk-LB6FMQQM.js → chunk-KV2HW4G4.js} +3 -11
- package/dist/chunk-KV2HW4G4.js.map +1 -0
- package/dist/{chunk-42NVJJTT.js → chunk-MMMC37AP.js} +3 -3
- package/dist/{chunk-42NVJJTT.js.map → chunk-MMMC37AP.js.map} +1 -1
- package/dist/chunk-MZVFOTAE.js +96 -0
- package/dist/chunk-MZVFOTAE.js.map +1 -0
- package/dist/{chunk-R3YXYVWF.js → chunk-OIZNABG4.js} +5 -4
- package/dist/chunk-OIZNABG4.js.map +1 -0
- package/dist/{chunk-QGWQ6LK3.js → chunk-QJOKZZKY.js} +9 -6
- package/dist/chunk-QJOKZZKY.js.map +1 -0
- package/dist/chunk-TWLPC4S3.js +53 -0
- package/dist/chunk-TWLPC4S3.js.map +1 -0
- package/dist/{chunk-7EFTWOMA.js → chunk-UNEZF3ZP.js} +73 -15
- package/dist/chunk-UNEZF3ZP.js.map +1 -0
- package/dist/chunk-WNOCPV4A.js +220 -0
- package/dist/chunk-WNOCPV4A.js.map +1 -0
- package/dist/{chunk-ZYOJWU62.js → chunk-XIBQ5BTZ.js} +12 -53
- package/dist/chunk-XIBQ5BTZ.js.map +1 -0
- package/dist/chunk-YMFJLBIZ.js +159 -0
- package/dist/chunk-YMFJLBIZ.js.map +1 -0
- package/dist/{chunk-UDSTWXXZ.js → chunk-ZKLB2HB5.js} +3 -3
- package/dist/{chunk-UDSTWXXZ.js.map → chunk-ZKLB2HB5.js.map} +1 -1
- package/dist/csv.d.ts +12 -3
- package/dist/csv.js +4 -4
- package/dist/csv.js.map +1 -1
- package/dist/form-types.d.ts +1 -1
- package/dist/headless/index.d.ts +1 -1
- package/dist/hooks/index.d.ts +16 -6
- package/dist/hooks/index.js +27 -15
- package/dist/hooks/mutation-mode.d.ts +1 -1
- package/dist/hooks/mutation-mode.js +3 -3
- package/dist/hooks/related-keys.d.ts +1 -1
- package/dist/hooks/use-aggregate.d.ts +2 -2
- package/dist/hooks/use-aggregate.js +3 -3
- package/dist/hooks/use-board-columns.d.ts +79 -0
- package/dist/hooks/use-board-columns.js +4 -0
- package/dist/hooks/use-board-columns.js.map +1 -0
- package/dist/hooks/use-capabilities.d.ts +1 -1
- package/dist/hooks/use-capabilities.js +2 -2
- package/dist/hooks/use-infinite-resource.d.ts +1 -1
- package/dist/hooks/use-infinite-resource.js +3 -3
- package/dist/hooks/use-link-options.d.ts +1 -1
- package/dist/hooks/use-link-options.js +5 -5
- package/dist/hooks/use-list-state.d.ts +103 -0
- package/dist/hooks/use-list-state.js +21 -0
- package/dist/hooks/use-list-state.js.map +1 -0
- package/dist/hooks/use-live.d.ts +1 -1
- package/dist/hooks/use-live.js +2 -2
- package/dist/hooks/use-one.d.ts +7 -1
- package/dist/hooks/use-one.js +3 -3
- package/dist/hooks/use-persisted-ui-state.js +2 -2
- package/dist/hooks/use-relation-label.d.ts +1 -1
- package/dist/hooks/use-relation-label.js +2 -2
- package/dist/hooks/use-resource-form.d.ts +1 -1
- package/dist/hooks/use-resource-form.js +7 -7
- package/dist/hooks/use-resource.d.ts +7 -1
- package/dist/hooks/use-resource.js +5 -5
- package/dist/hooks/use-segment-counts.d.ts +23 -0
- package/dist/hooks/use-segment-counts.js +19 -0
- package/dist/hooks/use-segment-counts.js.map +1 -0
- package/dist/hooks/use-view-board.d.ts +120 -0
- package/dist/hooks/use-view-board.js +29 -0
- package/dist/hooks/use-view-board.js.map +1 -0
- package/dist/hooks/use-view-calendar-range.d.ts +91 -0
- package/dist/hooks/use-view-calendar-range.js +22 -0
- package/dist/hooks/use-view-calendar-range.js.map +1 -0
- package/dist/hooks/use-write.d.ts +1 -1
- package/dist/index.d.ts +41 -11
- package/dist/index.js +119 -26
- package/dist/index.js.map +1 -1
- package/dist/provider/index.d.ts +61 -8
- package/dist/provider/index.js +2 -2
- package/dist/resource-view/index.d.ts +162 -757
- package/dist/resource-view/index.js +31 -686
- package/dist/resource-view/index.js.map +1 -1
- package/dist/saved-views-C45lRm7i.d.ts +155 -0
- package/dist/schema/index.d.ts +3 -3
- package/dist/schema/index.js +2 -1
- package/dist/testing/index.d.ts +2 -2
- package/dist/types-BAhcze_-.d.ts +1063 -0
- package/dist/{types-BriIV4e_.d.ts → types-CiQY6hUy.d.ts} +11 -1
- package/dist/{viewer-scope-Dx0N9AYk.d.ts → viewer-oOk0ZZk9.d.ts} +36 -34
- package/dist/{workspaces-CxpiFu2-.d.ts → workspaces-DeaFix5Z.d.ts} +1 -1
- package/dist/workspaces.d.ts +2 -2
- package/dist/{write-outcome-CkQXgtJq.d.ts → write-outcome-DuwfsnyO.d.ts} +1 -1
- package/package.json +11 -1
- package/dist/chunk-7EFTWOMA.js.map +0 -1
- package/dist/chunk-ALLWIK62.js.map +0 -1
- package/dist/chunk-LB6FMQQM.js.map +0 -1
- package/dist/chunk-QGWQ6LK3.js.map +0 -1
- package/dist/chunk-R3YXYVWF.js.map +0 -1
- package/dist/chunk-ZYOJWU62.js.map +0 -1
|
@@ -638,6 +638,14 @@ interface GetOneParams {
|
|
|
638
638
|
id: Identifier;
|
|
639
639
|
/** Supabase select syntax, e.g. "*, author:profiles(name)". Defaults to "*". */
|
|
640
640
|
select?: string;
|
|
641
|
+
/**
|
|
642
|
+
* The list's filters, when the record is opened from a list: a resource read from a function
|
|
643
|
+
* whose `args` take its scope from them (`take`) reads in that scope. They never narrow the
|
|
644
|
+
* record itself, and a provider without function sources ignores them. ResourceView's table
|
|
645
|
+
* (a deep-linked record), inbox (an off-page row) and NativeResourceView's peek and edit sheet pass
|
|
646
|
+
* them through `useOne`'s `scope`.
|
|
647
|
+
*/
|
|
648
|
+
scope?: FilterParam[];
|
|
641
649
|
}
|
|
642
650
|
/** Result of `getOne`. */
|
|
643
651
|
interface GetOneResult<T> {
|
|
@@ -646,6 +654,8 @@ interface GetOneResult<T> {
|
|
|
646
654
|
/** Parameters for `getMany`. */
|
|
647
655
|
interface GetManyParams {
|
|
648
656
|
ids: Identifier[];
|
|
657
|
+
/** As `GetOneParams.scope`: the list's filters a function source takes its scope from. */
|
|
658
|
+
scope?: FilterParam[];
|
|
649
659
|
}
|
|
650
660
|
/** Result of `getMany`. */
|
|
651
661
|
interface GetManyResult<T> {
|
|
@@ -900,4 +910,4 @@ interface DataProvider {
|
|
|
900
910
|
invalidates?(event: WriteEvent): InvalidationKey[];
|
|
901
911
|
}
|
|
902
912
|
|
|
903
|
-
export { type UpdateParams as $, type AggregateParams as A, type BaseRecord as B, type ControlHint as C, type DataProvider as D, type
|
|
913
|
+
export { type UpdateParams as $, type AggregateParams as A, type BaseRecord as B, type ControlHint as C, type DataProvider as D, type GetOneResult as E, type FieldSchema as F, type GetManyParams as G, type HistoryParams as H, type InvalidationKey as I, type ImportParams as J, type PaginationParam as K, type ListResult as L, type RangeFilter as M, type NullFilter as N, type RecordComment as O, type ProviderCapabilities as P, type ResourceAccess as Q, type ResourceContract as R, type SortParam as S, type ResourceRelation as T, type ResourceSchema as U, type ResourceSummary as V, type WriteEvent as W, type RowFailure as X, type ScalarFilter as Y, type SelectOption as Z, type StorageType as _, type FilterParam as a, type UpdateResult as a0, type VersionField as a1, type WidgetHint as a2, defineResource as a3, fieldControl as a4, type ListParams as b, type Identifier as c, type AggregateResult as d, type DataRow as e, type FieldReference as f, type SubscribeParams as g, type ResourceChangeEvent as h, type ResourceFormFieldDef as i, type AuditEntry as j, type AggregateMetric as k, type RowOf as l, type RowAction as m, type ArrayFilter as n, type BulkChange as o, type BulkResult as p, type CountMode as q, type CreateParams as r, type CreateResult as s, type DeleteParams as t, type DeleteResult as u, type FieldPermissions as v, type FieldType as w, type FilterOperator as x, type GetManyResult as y, type GetOneParams as z };
|
|
@@ -3,37 +3,6 @@ import { ReactNode } from 'react';
|
|
|
3
3
|
import { QueryClient } from '@tanstack/react-query';
|
|
4
4
|
import { Day } from './dates.js';
|
|
5
5
|
|
|
6
|
-
/**
|
|
7
|
-
* What the viewer may do where they are working, for guards that narrow what a page shows. Empty
|
|
8
|
-
* here: an app adds its own keys by module augmentation, so core never names an app's roles.
|
|
9
|
-
*
|
|
10
|
-
* ```ts
|
|
11
|
-
* declare module "@marktiderman/genesis-core" {
|
|
12
|
-
* interface GenesisViewerRoles {
|
|
13
|
-
* teamRoles?: readonly ("owner" | "editor" | "reader")[];
|
|
14
|
-
* }
|
|
15
|
-
* }
|
|
16
|
-
* ```
|
|
17
|
-
*
|
|
18
|
-
* Roles never decide access: row-level security does. A guard reading them only hides or refuses
|
|
19
|
-
* a control the server would refuse anyway.
|
|
20
|
-
*/
|
|
21
|
-
interface GenesisViewerRoles {
|
|
22
|
-
}
|
|
23
|
-
/**
|
|
24
|
-
* Who is looking, as a view's guards and `when` read it (`useViewer()`). Outside a `ViewerScope`
|
|
25
|
-
* it is `{ id: null, scope: {} }`, so a guard that needs the viewer refuses (fails closed).
|
|
26
|
-
*/
|
|
27
|
-
interface Viewer {
|
|
28
|
-
/** The signed-in viewer's id; null when signed out or outside a ViewerScope. */
|
|
29
|
-
readonly id: string | null;
|
|
30
|
-
readonly scope: ResourceScope;
|
|
31
|
-
/** Undefined until the app knows them; a guard that needs them refuses meanwhile. */
|
|
32
|
-
readonly roles?: GenesisViewerRoles;
|
|
33
|
-
}
|
|
34
|
-
/** The viewer outside any ViewerScope: no one, nowhere, no roles. */
|
|
35
|
-
declare const NO_VIEWER: Viewer;
|
|
36
|
-
|
|
37
6
|
/**
|
|
38
7
|
* Empties the query cache for a new viewer: sends the old viewer's waiting
|
|
39
8
|
* undoable writes (the session is still theirs), cancels reads in flight,
|
|
@@ -87,9 +56,11 @@ interface ViewerScopeProps {
|
|
|
87
56
|
/** The signed-in viewer's id, null when signed out, undefined while the session loads. */
|
|
88
57
|
viewer: string | null | undefined;
|
|
89
58
|
/**
|
|
90
|
-
* The viewer
|
|
91
|
-
*
|
|
92
|
-
*
|
|
59
|
+
* The viewer whose session filled the cache before this scope mounted: a persisted cache
|
|
60
|
+
* restored for them, or a router's loaders that prefetched under their session. When the first
|
|
61
|
+
* known viewer is this one, the cache is kept; otherwise it's emptied. Inside a
|
|
62
|
+
* `GenesisProvider` with `persist`, it defaults to its `persistScope`'s user. A ViewerScope
|
|
63
|
+
* nested inside another for the same viewer always keeps it: the outer one already guards it.
|
|
93
64
|
*/
|
|
94
65
|
persistedViewer?: string | null;
|
|
95
66
|
/** Where the viewer is working (see `ResourceScope`). Changing it doesn't remount or clear anything. */
|
|
@@ -141,4 +112,35 @@ declare function scopeClock(scopeTimeZone: string | null | undefined, viewerZone
|
|
|
141
112
|
*/
|
|
142
113
|
declare function ViewerScope({ viewer, persistedViewer: persistedViewerProp, scope, roles, timeZone, scopeTimeZone, fallback, children }: ViewerScopeProps): react.JSX.Element;
|
|
143
114
|
|
|
115
|
+
/**
|
|
116
|
+
* What the viewer may do where they are working, for guards that narrow what a page shows. Empty
|
|
117
|
+
* here: an app adds its own keys by module augmentation, so core never names an app's roles.
|
|
118
|
+
*
|
|
119
|
+
* ```ts
|
|
120
|
+
* declare module "@marktiderman/genesis-core" {
|
|
121
|
+
* interface GenesisViewerRoles {
|
|
122
|
+
* teamRoles?: readonly ("owner" | "editor" | "reader")[];
|
|
123
|
+
* }
|
|
124
|
+
* }
|
|
125
|
+
* ```
|
|
126
|
+
*
|
|
127
|
+
* Roles never decide access: row-level security does. A guard reading them only hides or refuses
|
|
128
|
+
* a control the server would refuse anyway.
|
|
129
|
+
*/
|
|
130
|
+
interface GenesisViewerRoles {
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Who is looking, as a view's guards and `when` read it (`useViewer()`). Outside a `ViewerScope`
|
|
134
|
+
* it is `{ id: null, scope: {} }`, so a guard that needs the viewer refuses (fails closed).
|
|
135
|
+
*/
|
|
136
|
+
interface Viewer {
|
|
137
|
+
/** The signed-in viewer's id; null when signed out or outside a ViewerScope. */
|
|
138
|
+
readonly id: string | null;
|
|
139
|
+
readonly scope: ResourceScope;
|
|
140
|
+
/** Undefined until the app knows them; a guard that needs them refuses meanwhile. */
|
|
141
|
+
readonly roles?: GenesisViewerRoles;
|
|
142
|
+
}
|
|
143
|
+
/** The viewer outside any ViewerScope: no one, nowhere, no roles. */
|
|
144
|
+
declare const NO_VIEWER: Viewer;
|
|
145
|
+
|
|
144
146
|
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 };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { R as ResourceScope, G as GenesisViewerRoles } from './viewer-
|
|
1
|
+
import { R as ResourceScope, G as GenesisViewerRoles } from './viewer-oOk0ZZk9.js';
|
|
2
2
|
|
|
3
3
|
/**
|
|
4
4
|
* Appearance preferences, as data (ADR 0024): the values and the order that decides which one
|
package/dist/workspaces.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import './viewer-
|
|
2
|
-
export { h as DEFAULT_WORKSPACE_KIND_LABELS, j as GenesisWorkspaceKinds, k as WORKSPACE_KIND_ORDER, l as WORKSPACE_SWITCHER_SEARCH_THRESHOLD, W as Workspace, m as WorkspaceGroup, g as WorkspaceHrefOptions, n as WorkspaceKind, o as WorkspaceTheme, p as defaultWorkspace, q as filterWorkspaces, s as groupWorkspaces, u as hasWorkspaceBadge, v as keepSection, w as orderedWorkspaces, x as pathInWorkspace, y as resolveWorkspaceAppearance, z as resolveWorkspaceBrand, B as workspaceAt, C as workspaceBadgeLabel, E as workspaceHref, F as workspaceInitials } from './workspaces-
|
|
1
|
+
import './viewer-oOk0ZZk9.js';
|
|
2
|
+
export { h as DEFAULT_WORKSPACE_KIND_LABELS, j as GenesisWorkspaceKinds, k as WORKSPACE_KIND_ORDER, l as WORKSPACE_SWITCHER_SEARCH_THRESHOLD, W as Workspace, m as WorkspaceGroup, g as WorkspaceHrefOptions, n as WorkspaceKind, o as WorkspaceTheme, p as defaultWorkspace, q as filterWorkspaces, s as groupWorkspaces, u as hasWorkspaceBadge, v as keepSection, w as orderedWorkspaces, x as pathInWorkspace, y as resolveWorkspaceAppearance, z as resolveWorkspaceBrand, B as workspaceAt, C as workspaceBadgeLabel, E as workspaceHref, F as workspaceInitials } from './workspaces-DeaFix5Z.js';
|
|
3
3
|
import 'react';
|
|
4
4
|
import '@tanstack/react-query';
|
|
5
5
|
import './dates.js';
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@marktiderman/genesis-core",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.17.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -236,6 +236,16 @@
|
|
|
236
236
|
"use": "DataWriteError and readFailureMessage",
|
|
237
237
|
"import": "@marktiderman/genesis-core/errors"
|
|
238
238
|
},
|
|
239
|
+
{
|
|
240
|
+
"need": "where saved views and each person's list choices are kept",
|
|
241
|
+
"use": "a SavedViewStore (createLocalSavedViewStore on the device, or the app's own over its table), passed to genesis-ui's ResourceViewDefaultsProvider savedViews",
|
|
242
|
+
"import": "@marktiderman/genesis-core/resource-view"
|
|
243
|
+
},
|
|
244
|
+
{
|
|
245
|
+
"need": "a list's segment and filters in the URL, or as provider filters",
|
|
246
|
+
"use": "readListUrl, listUrlParams and the view's filterParams and segmentFilters",
|
|
247
|
+
"import": "@marktiderman/genesis-core/resource-view"
|
|
248
|
+
},
|
|
239
249
|
{
|
|
240
250
|
"need": "an organization's own brand and defaults inside the app",
|
|
241
251
|
"use": "WorkspaceTheme's brand and defaults, read with resolveWorkspaceBrand and resolveWorkspaceAppearance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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\";\nimport { reportError } from \"../errors\";\nimport { resolveAggregate } from \"./aggregate\";\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 /** Another schema's tables, for a resource named `schema.table` outside `public`. */\n schema?(name: string): { 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 /** Another schema's tables, for a resource named `schema.table` outside `public`. Any real client's `schema` fits. */\n schema?(name: string): { 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/** What an `update` override is told besides the row. */\nexport interface SupabaseUpdateContext {\n /**\n * With a `version` rule and an `expectedVersion` from the caller: the\n * version the row must still be at. The override must apply the change\n * only at that version (e.g. `... where id = $1 and version = $2`) and\n * return nothing when no row matched; the provider then tells a\n * `conflict` from `forbidden` and `gone`.\n */\n expectedVersion?: string;\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 context?: SupabaseUpdateContext,\n ) => Promise<BaseRecord | Identifier | boolean | null | undefined | void>;\n /**\n * The column every update and delete of this resource is checked against,\n * so an edit made on a stale copy is refused as a `conflict` instead of\n * overwriting someone else's (`UpdateParams.expectedVersion`).\n *\n * The database must advance it on every update, or it detects nothing:\n * `integer` with genesis-supabase's `genesis_version_bump` trigger\n * (migration 0019), or `timestamp` with a trigger that sets it to `now()`\n * on update (`moddatetime`). The provider never writes it: a submitted\n * value is dropped. Writes without an `expectedVersion` are not checked,\n * so turning this on changes nothing for callers that don't send one.\n */\n version?: { field: string; kind: \"integer\" | \"timestamp\" };\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`. A list matches a `public` table under\n * either spelling; a test is asked once, with the name as the caller gives it.\n */\n binTables?: readonly string[] | ((resource: string) => boolean);\n /**\n * Per-resource rules, keyed by resource name. A `public` resource may be keyed either way\n * (`goals` or `public.goals`). The key spelled exactly as the caller names the resource wins;\n * the other spelling is used only when that key is absent. Rules are never merged.\n */\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). A list matches a `public` resource\n * under either spelling; a test is asked once, with the name as the caller\n * gives it.\n */\n realtime?: boolean | readonly string[] | ((resource: string) => boolean);\n /**\n * Work out `sum`, `avg`, `min` and `max` in the database with PostgREST's aggregate functions\n * (`amount.sum()`), which a project turns on with `pgrst.db_aggregates_enabled`. Off by\n * default: `aggregate` then counts in the database and totals the other metrics from the\n * rows, paged (`resolveAggregate`, up to 10 000 rows). A count is always the database's.\n */\n aggregateFunctions?: 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 /** Where empty values go, when the sort said (`SortParam.nulls`). */\n n?: \"first\" | \"last\";\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 /** Where the one sort column's empty values go, when the sort said. */\n n?: \"first\" | \"last\";\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.n !== undefined && state.n !== \"first\" && state.n !== \"last\") 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\") && (col.n === undefined || col.n === \"first\" || col.n === \"last\"))) 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, ...(state.n ? { n: state.n } : {}), 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 */\n/** A sort as `.order()`'s options: unset `nulls` stays unset, so the store's default holds. */\nfunction orderOptions({ order, nulls }: SortParam): { ascending: boolean; nullsFirst?: boolean } {\n return { ascending: order === \"asc\", ...(nulls ? { nullsFirst: nulls === \"first\" } : {}) };\n}\n\n/** Empty values last: what the sort says, else Postgres's own default for its order. */\nfunction nullsGoLast(order: \"asc\" | \"desc\", nulls: \"first\" | \"last\" | undefined): boolean {\n return nulls ? nulls === \"last\" : order === \"asc\";\n}\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)) {\n columns.push({ field: sort.field, order: sort.order ?? \"asc\", ...(sort.nulls ? { nulls: sort.nulls } : {}) });\n }\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 (empty values\n * where the sort put them; unset, last when ascending and first when\n * descending, as Postgres orders them by 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, n, v } of cols) {\n // Nulls placed last are ahead of every value; going back mirrors which side is \"ahead\".\n const nullsAhead = nullsGoLast(o, n) !== 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/**\n * `\"schema.table\"` or `\"table\"` (schema `public`): the name a generated\n * contract gives a resource, split the way PostgREST and Realtime name it.\n */\nexport function splitRelation(resource: string): { schema: string; table: string } {\n const dot = schemaDot(resource);\n return dot < 0\n ? { schema: \"public\", table: unquote(resource) }\n : { schema: unquote(resource.slice(0, dot)), table: unquote(resource.slice(dot + 1)) };\n}\n\n/** Where the schema ends: the first dot outside double quotes (`\"my.s\".\"we.ird\"`), or -1. */\nfunction schemaDot(resource: string): number {\n let quoted = false;\n for (let i = 0; i < resource.length; i++) {\n const c = resource[i];\n if (c === '\"') quoted = !quoted;\n else if (c === \".\" && !quoted) return i;\n }\n return -1;\n}\n\n/** A name part without its quotes: `\"we.ird\"` → `we.ird`, `\"a\"\"b\"` → `a\"b`. */\nfunction unquote(part: string): string {\n return part.length >= 2 && part.startsWith('\"') && part.endsWith('\"') ? part.slice(1, -1).replace(/\"\"/g, '\"') : part.replace(/\"/g, \"\");\n}\n\n/** A name part as a resource name spells it: quoted when it holds a dot or a quote. */\nfunction quotePart(part: string): string {\n return /[.\"]/.test(part) ? `\"${part.replace(/\"/g, '\"\"')}\"` : part;\n}\n\n/** The same `public` resource named the other way: `public.goals` ↔ `goals`; other schemas have one spelling. */\nfunction otherSpelling(resource: string): string {\n const { schema, table } = splitRelation(resource);\n if (schema !== \"public\") return resource;\n return schemaDot(resource) < 0 ? `public.${quotePart(table)}` : quotePart(table);\n}\n\n/** Every spelling of a resource, for a list given either: a `public` one bare first, then qualified. */\nfunction spellings(resource: string): string[] {\n const { schema } = splitRelation(resource);\n if (schema !== \"public\") return [resource];\n const other = otherSpelling(resource);\n return schemaDot(resource) < 0 ? [resource, other] : [other, resource];\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>();\nconst warnedUncheckedOverride = new Set<string>();\n\n/**\n * A Postgres or ISO timestamp as microseconds since the epoch (a string, to keep every digit), or\n * undefined when it doesn't read as one. Date.parse alone stops at milliseconds.\n */\nfunction instant(text: string): string | undefined {\n const m = /^(\\d{4}-\\d{2}-\\d{2})[T ](\\d{2}:\\d{2}:\\d{2})(?:\\.(\\d+))?(Z|[+-]\\d{2}(?::?\\d{2})?)?$/.exec(text.trim());\n if (!m) return undefined;\n const [, date, time, fraction = \"\", zone = \"Z\"] = m;\n const offset = zone === \"Z\" ? \"Z\" : zone.length === 3 ? `${zone}:00` : zone.includes(\":\") ? zone : `${zone.slice(0, 3)}:${zone.slice(3)}`;\n const ms = Date.parse(`${date}T${time}${offset}`);\n if (Number.isNaN(ms)) return undefined;\n return `${ms / 1000}.${fraction.padEnd(6, \"0\").slice(0, 6)}`;\n}\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 /** The table or view `name` names, in its schema: `public` through `from(table)`, any other through `schema(s).from(table)`. */\n function relation(name: string): SupabaseQueryBuilder {\n const { schema, table } = splitRelation(name);\n if (schema === \"public\") return client.from(table) as SupabaseQueryBuilder;\n // A client without schema() (not supabase-js) gets the name as given, as before.\n if (typeof client.schema !== \"function\") return client.from(name) as SupabaseQueryBuilder;\n return client.schema(schema).from(table) as SupabaseQueryBuilder;\n }\n\n const from = (resource: string) => relation(resource);\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 = relation(source ?? resource);\n return count ? table.select(cols, { count }) : table.select(cols);\n }\n /** A resource's rules, keyed either way: `\"public.goals\"` finds `goals`, and `goals` finds `\"public.goals\"`. */\n const configFor = (resource: string): SupabaseResourceConfig =>\n options.resources?.[resource] ?? options.resources?.[otherSpelling(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 // A test is asked once, as the caller names the resource: asking the other spelling too would\n // let `r => r !== \"x\"` say yes to `public.x`. Only a list matches either spelling.\n if (typeof all === \"function\") return all(resource);\n return spellings(resource).some((name) => all.includes(name));\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 if (typeof bin === \"function\") return bin(resource);\n return spellings(resource).some((name) => bin.includes(name));\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 function versionFor(resource: string): { field: string; kind: \"integer\" | \"timestamp\" } | undefined {\n return configFor(resource).version;\n }\n\n /** The version token a caller asked a write to be checked against, when the resource has one. */\n function expectedFor(resource: string, expectedVersion: string | null | undefined): string | undefined {\n return versionFor(resource) && expectedVersion != null ? String(expectedVersion) : undefined;\n }\n\n /**\n * Whether two version tokens name the same version. A timestamp is compared\n * as an instant to the microsecond, since a realtime payload and a PostgREST\n * read format the same value differently (\"2026-11-03 16:00:00.5+00\" and\n * \"2026-11-03T16:00:00.500000+00:00\").\n */\n function sameVersion(kind: \"integer\" | \"timestamp\", a: string | null, b: string): boolean {\n if (a === b) return true;\n if (a === null || kind !== \"timestamp\") return false;\n const x = instant(a);\n return x !== undefined && x === instant(b);\n }\n\n /**\n * A version-checked write matched no rows: read the row back to say why.\n * Not visible is `gone`; visible at another version is a `conflict` (with\n * the row as it is now, read the way the resource reads); visible at the\n * expected version means the change itself was refused (`forbidden`).\n * Without an expected version, as `noRowsError`. `known` is the row\n * already read back, when the caller has it.\n */\n async function staleOrNoRowsError(\n resource: string,\n id: Identifier,\n verb: \"change\" | \"delete\",\n expected: string | undefined,\n known?: BaseRecord,\n ): Promise<DataWriteError> {\n if (expected === undefined) return noRowsError(resource, id, verb);\n const { field, kind } = versionFor(resource)!;\n let current: BaseRecord | undefined = known;\n try {\n current ??= await readBack(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 (!current) return goneError(resource);\n const currentVersion = current[field] == null ? null : String(current[field]);\n if (sameVersion(kind, currentVersion, expected)) {\n return new DataWriteError(\"forbidden\", `You can't ${verb} this ${nounFor(resource)}.`);\n }\n // Their change, the way this resource is read (a view's joined columns too), so a screen can\n // show it. The table's row stands in when that read fails or finds nothing.\n const config = configFor(resource);\n if (config.source !== undefined || config.select !== undefined) {\n const viewed = await run(read(resource, undefined).eq(\"id\", id)).then((rows) => rows[0] as BaseRecord | undefined, () => undefined);\n if (viewed) current = viewed;\n }\n return new DataWriteError(\n \"conflict\",\n `Someone else changed this ${nounFor(resource)} after you opened it. Review their change, then make yours again.`,\n { current, currentVersion },\n );\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\" | \"n\" | \"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, ...(columns[0]!.nulls ? { n: columns[0]!.nulls } : {}), v: values[0] ?? null }\n : { s: null, o: \"asc\", c: columns.map((c) => ({ s: c.field, o: c.order, ...(c.nulls ? { n: c.nulls } : {}) })), vs: values };\n const sortId = JSON.stringify([columns.map((c) => [c.field, c.order, c.nulls ?? null]), 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, c.n ?? null]), 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, nulls } of columns) {\n // Always pinned: the keyset has to know where empty values are. Going back reverses them too.\n const ascending = (order === \"asc\") !== back;\n query = query.order(field, { ascending, nullsFirst: nullsGoLast(order, nulls) === back });\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 sort of columns) query = query.order(sort.field, orderOptions(sort));\n query = query.order(key, { ascending: keyOrder === \"asc\" });\n } else if (requested.length > 0) {\n for (const sort of requested) query = query.order(sort.field, orderOptions(sort));\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 aggregate(resource, params) {\n const entries = Object.entries(params.metrics);\n const counts = entries.filter(([, m]) => m.fn === \"count\");\n const others = entries.filter(([, m]) => m.fn !== \"count\");\n const values: Record<string, number | null> = {};\n let isEstimate = false;\n const SAFE = /^[a-zA-Z_][a-zA-Z0-9_]*$/;\n const refuse = (why: string) =>\n reportReadError(\n new DataReadError(\"invalid\", readFailureMessage(\"invalid\", nounFor(resource), false, configFor(resource).nounPlural), {\n cause: new Error(`[SupabaseProvider] aggregate of \"${resource}\": ${why}`),\n }),\n resource,\n \"getList\",\n );\n const narrow = (query: SupabaseQueryBuilder) => {\n query = applyFilters(query, params.filters);\n const clauses = searchClauses(resource, { search: params.search });\n return clauses ? query.or(clauses) : query;\n };\n if (counts.length > 0) {\n const mode = params.count ?? \"exact\";\n const result = (await narrow(read(resource, \"*\", mode)).range(0, 0)) as unknown as { error: unknown; count?: number | null };\n await throwIfReadError(result, resource, \"getList\");\n for (const [name] of counts) values[name] = result.count ?? 0;\n isEstimate = mode !== \"exact\";\n }\n if (others.length > 0) {\n if (options.aggregateFunctions) {\n for (const [name, m] of others) {\n if (!SAFE.test(name) || !(\"field\" in m) || !SAFE.test(m.field)) await refuse(`\"${name}\" and its field must be plain column names.`);\n }\n const cols = others.map(([name, m]) => `${name}:${(m as { field: string }).field}.${m.fn}()`).join(\",\");\n const result = (await narrow(read(resource, cols))) as unknown as { data: Record<string, unknown>[] | null; error: unknown };\n await throwIfReadError(result, resource, \"getList\");\n const row = result.data?.[0] ?? {};\n for (const [name] of others) {\n const raw = row[name];\n const n = raw == null || raw === \"\" ? NaN : Number(raw);\n values[name] = Number.isFinite(n) ? n : null;\n }\n } else {\n // The same reads without this method, so the fallback pages rows instead of calling back here.\n const { aggregate: _self, ...reads } = provider;\n // Pages no bigger than getList allows here (maxPerPage), so the fallback isn't refused.\n const rows = await resolveAggregate(\n reads,\n resource,\n { ...params, metrics: Object.fromEntries(others) },\n { pageSize: Math.max(1, Math.min(500, maxPerPage - 1)) },\n );\n Object.assign(values, rows.values);\n }\n }\n return isEstimate ? { values, isEstimate } : { values };\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: resource ? !!versionFor(resource) : false,\n ...(resource && versionFor(resource) ? { version: { ...versionFor(resource)! } } : {}),\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 } = splitRelation(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 // A copy: with no prepare step this is the caller's own object, and the version is taken out below.\n const row = {\n ...(await tableValues(\n resource,\n await prepare(resource, params.data as Record<string, unknown>, { resource, action: \"update\", id }),\n id,\n )),\n };\n const version = versionFor(resource);\n const expected = expectedFor(resource, params.expectedVersion);\n // The database advances the version; a submitted value is never written.\n if (version) delete row[version.field];\n const override = configFor(resource).update;\n let record: BaseRecord;\n if (override && version && override.length < 3 && !warnedUncheckedOverride.has(resource)) {\n warnedUncheckedOverride.add(resource);\n reportError(\n new Error(\n `[SupabaseProvider] \"${resource}\" has a version rule and an update rule that takes no third argument. ` +\n `The update rule is given { expectedVersion }: apply it (match the row at that version, return nothing when none matches), or updates go unchecked.`,\n ),\n { source: \"core:versioned-writes\", tags: { resource } },\n );\n }\n if (override) {\n let returned: BaseRecord | Identifier | boolean | null | undefined | void;\n try {\n returned = expected === undefined ? await override(id, row) : await override(id, row, { expectedVersion: expected });\n } catch (error) {\n throw toDataWriteError(error);\n }\n const result: unknown = returned;\n if (result == null || result === false) throw await staleOrNoRowsError(resource, id, \"change\", expected);\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 let query = from(resource).update(row).eq(\"id\", id);\n if (expected !== undefined) query = query.eq(version!.field, expected);\n const rows = await run(query.select(\"*\"));\n if (rows.length === 0) throw await staleOrNoRowsError(resource, id, \"change\", expected);\n record = rows[0] as BaseRecord;\n }\n await committed({ resource, kind: \"update\", id, record });\n const newVersion = version && record[version.field] != null ? String(record[version.field]) : undefined;\n return { data: record, ...(newVersion !== undefined ? { version: newVersion } : {}) } as never;\n },\n\n async deleteOne(resource, params) {\n const { id } = params;\n let deletedId: Identifier = id;\n const expected = expectedFor(resource, params.expectedVersion);\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. With a version, the\n // row is checked at it first (a binned delete can't carry the check).\n if (expected !== undefined) {\n const current = await readBack(resource, id);\n if (!current) throw goneError(resource);\n const { field, kind } = versionFor(resource)!;\n if (!sameVersion(kind, current[field] == null ? null : String(current[field]), expected)) {\n throw await staleOrNoRowsError(resource, id, \"delete\", expected, current);\n }\n } else if (!(await isVisible(resource, id))) throw goneError(resource);\n // The version goes on the delete too, so a change landing after the check above isn't\n // binned unseen: the row then stays, and the read-back says it's a conflict.\n let binning = from(resource).delete().eq(\"id\", id);\n if (expected !== undefined) binning = binning.eq(versionFor(resource)!.field, expected);\n await run(binning);\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 if (expected !== undefined) throw await staleOrNoRowsError(resource, id, \"delete\", expected);\n throw new DataWriteError(\"forbidden\", `You can't delete this ${nounFor(resource)}.`);\n }\n } else {\n let query = from(resource).delete().eq(\"id\", id);\n if (expected !== undefined) query = query.eq(versionFor(resource)!.field, expected);\n const rows = await run(query.select(\"id\"));\n if (rows.length === 0) throw await staleOrNoRowsError(resource, id, \"delete\", expected);\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.ts"],"names":["keepPreviousData","keepPreviousPlaceholder","options"],"mappings":";;;;;;;;;AA0JA,SAAS,gBAAgB,OAAA,EAAwD;AAC/E,EAAA,IAAI,CAAC,SAAS,OAAO,MAAA;AACrB,EAAA,OAAO,IAAA,CAAK,SAAA;AAAA,IACV,OAAA,CAAQ,GAAA,CAAI,CAAC,CAAA,KAAM;AACjB,MAAA,MAAM,SAAkC,EAAC;AACzC,MAAA,KAAA,MAAW,OAAO,MAAA,CAAO,IAAA,CAAK,CAAC,CAAA,CAAE,MAAK,EAAG;AACvC,QAAA,MAAA,CAAO,GAAG,CAAA,GAAK,CAAA,CAAyC,GAAG,CAAA;AAAA,MAC7D;AACA,MAAA,OAAO,MAAA;AAAA,IACT,CAAC;AAAA,GACH;AACF;AAMO,SAAS,WAAA,CACd,QAAA,EACA,OAAA,GAAiC,EAAC,EACZ;AACtB,EAAA,MAAM;AAAA,IACJ,WAAA;AAAA,IACA,cAAA;AAAA,IACA,cAAA,GAAiB,EAAA;AAAA,IACjB,WAAA,GAAc,CAAA;AAAA,IACd,aAAA,GAAgB,EAAA;AAAA,IAChB,MAAA;AAAA,IACA,YAAA,EAAc,kBAAA;AAAA,IACd,OAAA,GAAU,IAAA;AAAA,IACV,WAAA;AAAA,sBACAA,kBAAA,GAAmB,KAAA;AAAA,IACnB,IAAA;AAAA,IACA,eAAA;AAAA,IACA,eAAA;AAAA,IACA,eAAA;AAAA,IACA,OAAA;AAAA,IACA,YAAA,GAAe,aAAA;AAAA,IACf,WAAA;AAAA,IACA;AAAA,GACF,GAAI,OAAA;AAEJ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A,IACA,OAAA;AAAA,IACA,UAAA;AAAA,IACA,OAAA;AAAA,IACA,UAAA;AAAA,IACA,SAAA;AAAA,IACA,MAAA;AAAA,IACA,MAAA;AAAA,IACA,MAAA;AAAA,IACA,UAAA;AAAA,IACA,cAAA;AAAA,IACA,cAAA;AAAA,IACA;AAAA,GACF;AACF","file":"chunk-ALLWIK62.js","sourcesContent":["import { useState, useCallback, useMemo } from \"react\";\nimport {\n keepPreviousData as keepPreviousPlaceholder,\n useQuery,\n useMutation,\n useQueryClient,\n type UseQueryResult,\n type UseMutationResult,\n} from \"@tanstack/react-query\";\nimport { useDataProvider } from \"../provider/context\";\nimport type {\n BaseRecord,\n Identifier,\n SortParam,\n FilterParam,\n ListParams,\n ListResult,\n InvalidationKey,\n WriteEvent,\n} from \"../provider/types\";\nimport { relatedKeys } from \"./related-keys\";\nimport {\n cachedRecord,\n executeWrite,\n invalidateResource,\n type MutationModeOptions,\n} from \"./mutation-mode\";\nimport { useLiveInvalidation, type LiveOptions } from \"./use-live\";\nimport { resourceKeys } from \"../query-keys\";\nimport { DataWriteError, isDataWriteError, NO_ROWS_MATCHED } from \"../schema/write-outcome\";\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\nexport interface UseResourceOptions<T> extends MutationModeOptions {\n defaultSort?: SortParam;\n /**\n * Re-synced whenever its value changes (deep-equal, order-independent),\n * not just its identity — safe to pass a scope/audience-derived array that\n * changes across renders. This only covers CHANGES on an already-mounted\n * hook, though: if this starts `undefined` while the real value resolves\n * asynchronously, gate `enabled` on that same readiness signal too — the\n * hook cannot tell \"no defaultFilters intended\" apart from \"not resolved\n * yet,\" so an ungated hook's very first fetch can still run unscoped.\n */\n defaultFilters?: FilterParam[];\n defaultPerPage?: number;\n /** The page to start on (from 1), e.g. restored from the URL. Default 1. */\n defaultPage?: number;\n /** The search to start with, e.g. restored from the URL. Default \"\". */\n defaultSearch?: string;\n /** Supabase select/join syntax, e.g. \"*, author:profiles(name)\". */\n select?: string;\n /** Fields to search across when setSearch is called. Required for server-side search. */\n searchFields?: string[];\n /** Disable auto-fetching. */\n enabled?: boolean;\n /**\n * Other query keys to invalidate after a create, update or delete, on top\n * of `[resource]` and the provider's own `invalidates` (e.g. `[[\"me\"]]`\n * when a write changes the signed-in user's roles).\n */\n invalidates?: InvalidationKey[];\n /**\n * While the next page / sort / search is loading, keep returning the\n * previous result (`list.isPlaceholderData` is true meanwhile) instead of\n * dropping to `undefined`. A paged list then stays on screen between pages\n * rather than flashing a skeleton. Default false.\n */\n keepPreviousData?: boolean;\n /**\n * Keep the list current while mounted: subscribe to the provider's change\n * events (`DataProvider.subscribe`) and refetch this resource's cached\n * reads (lists and records) when it reports one, once per burst of\n * events. Events are hints: rows always come from the provider's normal\n * read. Pending optimistic and undoable writes stay applied over the\n * refetch. Needs a provider that serves `subscribe` for the resource\n * (`capabilities(resource).realtime`); otherwise it does nothing. Off by\n * default.\n */\n live?: boolean | LiveOptions;\n /**\n * After the write commits, with the provider's row. In `optimistic` and\n * `undoable` modes that is after `create` / `update` / `remove` have\n * already resolved.\n */\n onCreateSuccess?: (data: T) => void;\n onUpdateSuccess?: (data: T) => void;\n onDeleteSuccess?: () => void;\n /**\n * A write failed. In `optimistic` and `undoable` modes this is the only\n * place a failure is reported (the cache has already been put back), so\n * show it to the user here.\n */\n onError?: (error: Error) => void;\n}\n\n/** What `update` can take beside the change. */\nexport interface UpdateOptions {\n /**\n * Check the write against this version instead of the cached row's: \"keep mine\" after a\n * conflict, at the version the conflict reported (`WriteConflict.currentVersion`). A version\n * already chained for the row wins over it: a write sent while an earlier write of the same row\n * is still in flight is checked against the version that one commits (as\n * `ExecuteWriteArgs.expectedVersion`). The write\n * still goes through the resource's write path (queued behind any other write of the row, its\n * committed version recorded), so a move made right after it is checked against it.\n */\n expectedVersion?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Return type\n// ---------------------------------------------------------------------------\n\nexport interface UseResourceReturn<T> {\n /** TanStack Query result for the list query. */\n list: UseQueryResult<ListResult<T>>;\n /** Current list params (pagination, sort, filters, search). */\n params: ListParams;\n setSort: (sort: SortParam | undefined) => void;\n setFilters: (filters: FilterParam[]) => void;\n setPage: (page: number) => void;\n setPerPage: (perPage: number) => void;\n setSearch: (query: string) => void;\n /**\n * Create a new record. Returns the created item. In `optimistic` and\n * `undoable` modes it resolves at once with the values given (no `id` yet;\n * `onCreateSuccess` gets the stored row).\n */\n create: (data: Partial<T>) => Promise<T>;\n /**\n * Update an existing record by id. Returns the updated item. In\n * `optimistic` and `undoable` modes it resolves at once with the cached\n * row merged with `data`.\n */\n update: (id: Identifier, data: Partial<T>, options?: UpdateOptions) => Promise<T>;\n /** Delete a record by id. Resolves at once in `optimistic` / `undoable` modes. */\n remove: (id: Identifier) => Promise<void>;\n /** True when any mutation is in-flight. */\n isMutating: boolean;\n createMutation: UseMutationResult<T, Error, Partial<T>>;\n updateMutation: UseMutationResult<T, Error, { id: Identifier; data: Partial<T>; options?: UpdateOptions }>;\n deleteMutation: UseMutationResult<void, Error, Identifier>;\n}\n\n// ---------------------------------------------------------------------------\n// Filter identity — a deep-equality key independent of object-key order, so\n// a caller that rebuilds the same logical filters via a differently-ordered\n// spread (e.g. `{...base, operator: \"eq\"}` vs `{operator: \"eq\", ...base}`)\n// doesn't trip a spurious resync + pagination reset on an unrelated rerender.\n// ---------------------------------------------------------------------------\n\nfunction stableFilterKey(filters: FilterParam[] | undefined): string | undefined {\n if (!filters) return undefined;\n return JSON.stringify(\n filters.map((f) => {\n const sorted: Record<string, unknown> = {};\n for (const key of Object.keys(f).sort()) {\n sorted[key] = (f as unknown as Record<string, unknown>)[key];\n }\n return sorted;\n }),\n );\n}\n\n// ---------------------------------------------------------------------------\n// Hook\n// ---------------------------------------------------------------------------\n\nexport function useResource<T extends BaseRecord = BaseRecord>(\n resource: string,\n options: UseResourceOptions<T> = {},\n): UseResourceReturn<T> {\n const {\n defaultSort,\n defaultFilters,\n defaultPerPage = 25,\n defaultPage = 1,\n defaultSearch = \"\",\n select,\n searchFields: searchFieldsOption,\n enabled = true,\n invalidates,\n keepPreviousData = false,\n live,\n onCreateSuccess,\n onUpdateSuccess,\n onDeleteSuccess,\n onError,\n mutationMode = \"pessimistic\",\n undoDelayMs,\n onUndoable,\n } = options;\n\n const provider = useDataProvider();\n const queryClient = useQueryClient();\n\n // -------------------------------------------------------------------------\n // State\n // -------------------------------------------------------------------------\n\n const [sort, setSortRaw] = useState<SortParam | undefined>(defaultSort);\n const [filters, setFiltersRaw] = useState<FilterParam[]>(defaultFilters ?? []);\n const [page, setPage] = useState(Math.max(1, Math.floor(defaultPage)));\n const [perPage, setPerPageRaw] = useState(defaultPerPage);\n const [searchQuery, setSearchQuery] = useState(defaultSearch);\n\n // `defaultFilters` often resolves asynchronously — a caller's scope/audience\n // (team, project, ...) can still be loading on first render, so the array\n // it passes in changes value (not just identity) after mount, and may later\n // clear back to undefined (e.g. the scope itself is cleared). Re-syncing\n // here, during render rather than in an effect, means `filters` is already\n // correct by the time `params`/`list` below compute for this pass — no\n // stray unscoped fetch on the frame before an effect would have caught up.\n //\n // This only closes the gap for `defaultFilters` CHANGING across renders on\n // an already-mounted, already-enabled hook (e.g. a scope switch). It cannot\n // help the very first render: `filters` still seeds from whatever\n // `defaultFilters` is on mount, and `undefined` here is genuinely ambiguous\n // between \"this caller never uses defaultFilters\" (in which case forcing a\n // fetch to wait would break it forever) and \"the real value hasn't resolved\n // yet.\" A caller in the second case MUST also gate `enabled` on that same\n // readiness signal for its very first fetch to be correctly scoped — this\n // hook has no way to tell the two cases apart on its own.\n const defaultFiltersKey = stableFilterKey(defaultFilters);\n const [syncedFiltersKey, setSyncedFiltersKey] = useState(defaultFiltersKey);\n if (defaultFiltersKey !== syncedFiltersKey) {\n setSyncedFiltersKey(defaultFiltersKey);\n setFiltersRaw(defaultFilters ?? []);\n setPage(1);\n }\n\n const setSort = useCallback((s: SortParam | undefined) => {\n setSortRaw(s);\n setPage(1);\n }, []);\n\n const setFilters = useCallback((f: FilterParam[]) => {\n setFiltersRaw(f);\n setPage(1);\n }, []);\n\n const setPerPage = useCallback((value: number) => {\n setPerPageRaw(value);\n setPage(1);\n }, []);\n\n const setSearch = useCallback((query: string) => {\n setSearchQuery(query);\n setPage(1);\n }, []);\n\n // -------------------------------------------------------------------------\n // Params\n // -------------------------------------------------------------------------\n\n const params = useMemo<ListParams>(() => {\n const p: ListParams = {\n pagination: { page, perPage },\n sort,\n filters: filters.length > 0 ? filters : undefined,\n select,\n };\n if (searchQuery && searchFieldsOption && searchFieldsOption.length > 0) {\n p.search = { query: searchQuery, fields: searchFieldsOption };\n }\n return p;\n }, [page, perPage, sort, filters, select, searchQuery, searchFieldsOption]);\n\n // -------------------------------------------------------------------------\n // List query\n // -------------------------------------------------------------------------\n\n const listQueryKey = useMemo(\n () => resourceKeys(resource).list(params),\n [resource, params],\n );\n\n const list = useQuery<ListResult<T>>({\n queryKey: listQueryKey,\n queryFn: () => provider.getList<T>(resource, params),\n enabled,\n placeholderData: keepPreviousData ? keepPreviousPlaceholder : undefined,\n });\n\n // Every cached read of the resource: its lists, and the records a peek or\n // detail page shows from it.\n useLiveInvalidation(resource, live, enabled, { filters: params.filters }, [resource]);\n\n // -------------------------------------------------------------------------\n // Mutations\n // -------------------------------------------------------------------------\n\n const invalidateAfter = useCallback(\n (event: WriteEvent) => {\n // Pending optimistic/undoable patches are re-applied to the refetch.\n void invalidateResource(queryClient, resource);\n for (const queryKey of relatedKeys(provider, event, invalidates)) {\n void queryClient.invalidateQueries({ queryKey: [...queryKey] });\n }\n },\n [queryClient, resource, provider, invalidates],\n );\n\n const defaultOnError = useCallback(\n (error: Error) => {\n // A conflict is an outcome the caller shows (a conflict sheet), not a failure to log.\n if (isDataWriteError(error) && error.outcome === \"conflict\" && error.current) return;\n console.error(`[useResource] ${resource} mutation failed:`, error.message);\n },\n [resource],\n );\n const reportError = onError ?? defaultOnError;\n\n const modeArgs = {\n queryClient,\n provider,\n resource,\n mode: mutationMode,\n undoDelayMs,\n onUndoable,\n failedLater: reportError,\n };\n\n const createMutation = useMutation<T, Error, Partial<T>>({\n mutationFn: async (data) => {\n const outcome = await executeWrite<T>({\n ...modeArgs,\n kind: \"create\",\n data: data as Record<string, unknown>,\n send: async ({ keepalive }) => {\n const result = await provider.create<T>(resource, { data, ...(keepalive ? { keepalive } : {}) });\n return { record: result.data, audit: result.audit };\n },\n committed: (record) => {\n invalidateAfter({ resource, kind: \"create\", id: record.id, record });\n onCreateSuccess?.(record);\n },\n });\n return outcome.status === \"committed\" ? outcome.record : (data as T);\n },\n onError: reportError,\n });\n\n const updateMutation = useMutation<\n T,\n Error,\n { id: Identifier; data: Partial<T>; options?: UpdateOptions }\n >({\n mutationFn: async ({ id, data, options }) => {\n const before = cachedRecord(queryClient, resource, id);\n const outcome = await executeWrite<T>({\n ...modeArgs,\n kind: \"update\",\n id,\n data: data as Record<string, unknown>,\n ...(options?.expectedVersion !== undefined ? { expectedVersion: options.expectedVersion } : {}),\n send: async (ctx) => {\n const result = await provider.update<T>(resource, {\n id,\n data: (ctx.data ?? data) as Partial<T>,\n ...(ctx.keepalive ? { keepalive: true } : {}),\n ...(ctx.expectedVersion !== undefined ? { expectedVersion: ctx.expectedVersion } : {}),\n });\n // A write that matched no rows didn't save, whatever provider says so this way: it fails\n // here, before it counts as committed, so it never reads as a silent success.\n if (result.data === null || result.data === undefined) {\n throw new DataWriteError(\"forbidden\", \"This change wasn't saved: no row matched it.\", { code: NO_ROWS_MATCHED });\n }\n return { record: result.data, audit: result.audit };\n },\n committed: (record) => {\n invalidateAfter({ resource, kind: \"update\", id, record });\n onUpdateSuccess?.(record);\n },\n });\n return outcome.status === \"committed\"\n ? outcome.record\n : ({ ...(before ?? {}), ...data, id: before?.id ?? id } as T);\n },\n onError: reportError,\n });\n\n const deleteMutation = useMutation<void, Error, Identifier>({\n mutationFn: async (id) => {\n await executeWrite<void>({\n ...modeArgs,\n kind: \"delete\",\n id,\n send: async ({ keepalive, expectedVersion }) => {\n const result = await provider.deleteOne(resource, {\n id,\n ...(keepalive ? { keepalive } : {}),\n ...(expectedVersion !== undefined ? { expectedVersion } : {}),\n });\n return { record: undefined, audit: result?.audit };\n },\n committed: () => {\n invalidateAfter({ resource, kind: \"delete\", id });\n onDeleteSuccess?.();\n },\n });\n },\n onError: reportError,\n });\n\n // -------------------------------------------------------------------------\n // Convenience wrappers\n // -------------------------------------------------------------------------\n\n const create = useCallback(\n (data: Partial<T>) => createMutation.mutateAsync(data),\n [createMutation],\n );\n\n const update = useCallback(\n (id: Identifier, data: Partial<T>, options?: UpdateOptions) =>\n updateMutation.mutateAsync(options ? { id, data, options } : { id, data }),\n [updateMutation],\n );\n\n const remove = useCallback(\n (id: Identifier) => deleteMutation.mutateAsync(id),\n [deleteMutation],\n );\n\n const isMutating =\n createMutation.isPending ||\n updateMutation.isPending ||\n deleteMutation.isPending;\n\n return {\n list,\n params,\n setSort,\n setFilters,\n setPage,\n setPerPage,\n setSearch,\n create,\n update,\n remove,\n isMutating,\n createMutation,\n updateMutation,\n deleteMutation,\n };\n}\n"]}
|