@marktiderman/genesis-core 1.15.0 → 1.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (38) hide show
  1. package/README.md +20 -8
  2. package/dist/{chunk-RF6YVWHX.js → chunk-CZOFWG54.js} +4 -4
  3. package/dist/{chunk-RF6YVWHX.js.map → chunk-CZOFWG54.js.map} +1 -1
  4. package/dist/{chunk-4VRVVN2S.js → chunk-E4777JKI.js} +3 -3
  5. package/dist/{chunk-4VRVVN2S.js.map → chunk-E4777JKI.js.map} +1 -1
  6. package/dist/{chunk-K7K6NY3C.js → chunk-IOTHEKO7.js} +69 -59
  7. package/dist/chunk-IOTHEKO7.js.map +1 -0
  8. package/dist/{chunk-YFTGLQDQ.js → chunk-J2EIM7FC.js} +33 -12
  9. package/dist/chunk-J2EIM7FC.js.map +1 -0
  10. package/dist/{chunk-UV3ROHQA.js → chunk-K4ZNAF3G.js} +3 -3
  11. package/dist/{chunk-UV3ROHQA.js.map → chunk-K4ZNAF3G.js.map} +1 -1
  12. package/dist/{chunk-3LZAZ5KB.js → chunk-K7WEY5WR.js} +3 -3
  13. package/dist/{chunk-3LZAZ5KB.js.map → chunk-K7WEY5WR.js.map} +1 -1
  14. package/dist/{chunk-BQOJX67X.js → chunk-LGTXQTHA.js} +3 -3
  15. package/dist/{chunk-BQOJX67X.js.map → chunk-LGTXQTHA.js.map} +1 -1
  16. package/dist/{chunk-GGSXSI6Z.js → chunk-VDEW4AOS.js} +9 -6
  17. package/dist/chunk-VDEW4AOS.js.map +1 -0
  18. package/dist/{chunk-7YHGNPPO.js → chunk-VMRLCTZR.js} +5 -5
  19. package/dist/{chunk-7YHGNPPO.js.map → chunk-VMRLCTZR.js.map} +1 -1
  20. package/dist/{chunk-UGGMJUFQ.js → chunk-Y452U45I.js} +15 -7
  21. package/dist/chunk-Y452U45I.js.map +1 -0
  22. package/dist/form-types.d.ts +1 -0
  23. package/dist/hooks/index.js +9 -9
  24. package/dist/hooks/mutation-mode.js +3 -3
  25. package/dist/hooks/use-capabilities.js +2 -2
  26. package/dist/hooks/use-infinite-resource.d.ts +8 -0
  27. package/dist/hooks/use-infinite-resource.js +3 -3
  28. package/dist/hooks/use-live.js +2 -2
  29. package/dist/hooks/use-one.js +3 -3
  30. package/dist/hooks/use-resource-form.js +6 -6
  31. package/dist/hooks/use-resource.js +5 -5
  32. package/dist/index.js +10 -10
  33. package/dist/provider/index.js +2 -2
  34. package/package.json +1 -1
  35. package/dist/chunk-GGSXSI6Z.js.map +0 -1
  36. package/dist/chunk-K7K6NY3C.js.map +0 -1
  37. package/dist/chunk-UGGMJUFQ.js.map +0 -1
  38. package/dist/chunk-YFTGLQDQ.js.map +0 -1
package/README.md CHANGED
@@ -328,6 +328,15 @@ const tasks = useInfiniteResource("tasks", {
328
328
  tasks.rows; // every loaded row
329
329
  tasks.total; // from the first page's count
330
330
  tasks.hasNextPage && tasks.fetchNextPage();
331
+
332
+ // A grouped list: by the group, then the order within it.
333
+ const steps = useInfiniteResource("steps", {
334
+ defaultSorts: [
335
+ { field: "stage", order: "asc" },
336
+ { field: "position", order: "desc" },
337
+ ],
338
+ });
339
+ steps.setSorts([{ field: "stage", order: "desc" }]); // setSort(one) replaces them too
331
340
  ```
332
341
 
333
342
  - **The contract.** `getList` with `pagination: { page, perPage, cursor }`,
@@ -338,21 +347,24 @@ tasks.hasNextPage && tasks.fetchNextPage();
338
347
  A provider that doesn't ignores `cursor` and pages by `page`;
339
348
  `useInfiniteResource` then pages by offset until `total` rows are loaded.
340
349
  - **Supabase.**
341
- - It orders by the sort column and then the `orderKey` (default `id`) and
350
+ - It orders by each sort column (`sorts`, first one first, else `sort`)
351
+ and then the `orderKey` (default `id`), and
342
352
  fetches one row more than the page to tell whether there is a next
343
353
  page. A page is at most `maxPerPage - 1` rows, so that extra row fits
344
354
  under PostgREST's `max-rows`.
345
355
  - The cursor (opaque, base64 JSON) holds the last row's sort and key
346
- values and the sort it was made for. A cursor from another sort is
356
+ values and the sorts it was made for. A cursor from other sorts is
347
357
  refused.
348
- - The keyset filter handles ascending and descending sorts, ties (broken
349
- by the key) and null sort values, matching Postgres's default null
350
- placement (last when ascending, first when descending, pinned in the
351
- query).
358
+ - The keyset filter handles ascending and descending sorts, mixed across
359
+ columns, ties (broken by the key) and null sort values, matching
360
+ Postgres's default null placement (last when ascending, first when
361
+ descending, pinned in the query). It is spelled out one column at a
362
+ time: a row comparison `(a, b) > (x, y)` wouldn't follow that null
363
+ placement, and PostgREST's filters can't express one.
352
364
  - It refuses, with an `invalid` `DataReadError` whose `cause` says why:
353
365
  `orderKey: false`, a sort on an embedded field (`author.name`), a sort
354
- column with non-scalar values, and a `select` that leaves out the sort
355
- or key column.
366
+ column with non-scalar values, and a `select` that leaves out a sort
367
+ column or the key.
356
368
  - Only the first page is counted.
357
369
  - **Writes and pending patches.** Pages live under
358
370
  `[resource, "infinite", params]`, so writes (which invalidate `[resource]`)
@@ -1,6 +1,6 @@
1
- import { useLiveInvalidation } from './chunk-UV3ROHQA.js';
1
+ import { useLiveInvalidation } from './chunk-K4ZNAF3G.js';
2
2
  import { resourceKeys } from './chunk-OYIUIW7C.js';
3
- import { useDataProvider } from './chunk-GGSXSI6Z.js';
3
+ import { useDataProvider } from './chunk-VDEW4AOS.js';
4
4
  import { useQuery } from '@tanstack/react-query';
5
5
 
6
6
  function useOne(resource, id, options = {}) {
@@ -35,5 +35,5 @@ function useOne(resource, id, options = {}) {
35
35
  }
36
36
 
37
37
  export { useOne };
38
- //# sourceMappingURL=chunk-RF6YVWHX.js.map
39
- //# sourceMappingURL=chunk-RF6YVWHX.js.map
38
+ //# sourceMappingURL=chunk-CZOFWG54.js.map
39
+ //# sourceMappingURL=chunk-CZOFWG54.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/hooks/use-one.ts"],"names":[],"mappings":";;;;;AAiCO,SAAS,MAAA,CACd,QAAA,EACA,EAAA,EACA,OAAA,GAAyB,EAAC,EACP;AACnB,EAAA,MAAM,WAAW,eAAA,EAAgB;AAEjC,EAAA,MAAM,EAAE,MAAA,EAAQ,OAAA,EAAS,IAAA,EAAK,GAAI,OAAA;AAClC,EAAA,MAAM,SAAA,GAAY,OAAA,IAAW,CAAC,CAAC,EAAA;AAG/B,EAAA,mBAAA;AAAA,IACE,QAAA;AAAA,IACA,IAAA;AAAA,IACA,aAAa,EAAA,IAAM,IAAA;AAAA,IACnB,EAAA,IAAM,IAAA,GAAO,EAAE,EAAA,KAAO,EAAC;AAAA,IACvB,YAAA,CAAa,QAAQ,CAAA,CAAE,SAAA,CAAU,EAAE,CAAA;AAAA,IACnC,CAAC,KAAA,KAAU,KAAA,CAAM,IAAA,KAAS,SAAA,IAAa,EAAE,IAAA,IAAQ,KAAA,CAAA,IAAU,KAAA,CAAM,EAAA,IAAM,QAAQ,MAAA,CAAO,KAAA,CAAM,EAAE,CAAA,KAAM,OAAO,EAAE;AAAA,GAC/G;AAEA,EAAA,OAAO,QAAA,CAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IASjB,UAAU,YAAA,CAAa,QAAQ,CAAA,CAAE,MAAA,CAAO,IAAI,MAAM,CAAA;AAAA,IAClD,SAAS,YAAY;AACnB,MAAA,IAAI,EAAA,IAAM,IAAA,EAAM,MAAM,IAAI,MAAM,YAAY,CAAA;AAC5C,MAAA,MAAM,MAAA,GAAS,MAAM,QAAA,CAAS,MAAA,CAAU,UAAU,EAAE,EAAA,EAAI,QAAQ,CAAA;AAChE,MAAA,OAAO,MAAA,CAAO,IAAA;AAAA,IAChB,CAAA;AAAA,IACA,OAAA,EAAS;AAAA,GACV,CAAA;AACH","file":"chunk-RF6YVWHX.js","sourcesContent":["import { useQuery, type UseQueryResult } from \"@tanstack/react-query\";\nimport { useDataProvider } from \"../provider/context\";\nimport type { BaseRecord, Identifier } from \"../provider/types\";\nimport { useLiveInvalidation, type LiveOptions } from \"./use-live\";\nimport { resourceKeys } from \"../query-keys\";\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\nexport interface UseOneOptions {\n /** Supabase select/join syntax, e.g. \"*, author:profiles(name)\". */\n select?: string;\n /** Defaults to `!!id` — won't fetch when id is falsy. */\n enabled?: boolean;\n /**\n * Keep the record current while mounted: refetch it when the provider\n * reports a change to it (`DataProvider.subscribe`). See\n * `UseResourceOptions.live`. Off by default.\n */\n live?: boolean | LiveOptions;\n}\n\n// ---------------------------------------------------------------------------\n// Hook\n// ---------------------------------------------------------------------------\n\n/**\n * Fetch a single record by id, powered by TanStack Query.\n *\n * Returns the full `UseQueryResult<T>` with the data unwrapped from the\n * provider's `GetOneResult` wrapper.\n */\nexport function useOne<T extends BaseRecord = BaseRecord>(\n resource: string,\n id: Identifier | undefined | null,\n options: UseOneOptions = {},\n): UseQueryResult<T> {\n const provider = useDataProvider();\n\n const { select, enabled, live } = options;\n const isEnabled = enabled ?? !!id;\n\n // Only this record's events; `changed` (events may have been missed) too.\n useLiveInvalidation(\n resource,\n live,\n isEnabled && id != null,\n id != null ? { id } : {},\n resourceKeys(resource).detailsOf(id),\n (event) => event.type === \"changed\" || !(\"id\" in event) || event.id == null || String(event.id) === String(id),\n );\n\n return useQuery<T>({\n // `select` is part of the key because it is part of the REQUEST: two pages\n // asking for the same record with different projections get different\n // rows back, and keying only on the id makes them share one cache entry.\n // Whichever mounted first wins for the whole staleTime window, and the\n // other silently renders a record missing the joined fields it asked for\n // — no error, no refetch, just absent data. `useResource`'s list key has\n // always included `select` (it keys on the whole `params` object); this\n // was the one place it did not.\n queryKey: resourceKeys(resource).detail(id, select),\n queryFn: async () => {\n if (id == null) throw new Error(\"Missing id\");\n const result = await provider.getOne<T>(resource, { id, select });\n return result.data;\n },\n enabled: isEnabled,\n });\n}\n"]}
1
+ {"version":3,"sources":["../src/hooks/use-one.ts"],"names":[],"mappings":";;;;;AAiCO,SAAS,MAAA,CACd,QAAA,EACA,EAAA,EACA,OAAA,GAAyB,EAAC,EACP;AACnB,EAAA,MAAM,WAAW,eAAA,EAAgB;AAEjC,EAAA,MAAM,EAAE,MAAA,EAAQ,OAAA,EAAS,IAAA,EAAK,GAAI,OAAA;AAClC,EAAA,MAAM,SAAA,GAAY,OAAA,IAAW,CAAC,CAAC,EAAA;AAG/B,EAAA,mBAAA;AAAA,IACE,QAAA;AAAA,IACA,IAAA;AAAA,IACA,aAAa,EAAA,IAAM,IAAA;AAAA,IACnB,EAAA,IAAM,IAAA,GAAO,EAAE,EAAA,KAAO,EAAC;AAAA,IACvB,YAAA,CAAa,QAAQ,CAAA,CAAE,SAAA,CAAU,EAAE,CAAA;AAAA,IACnC,CAAC,KAAA,KAAU,KAAA,CAAM,IAAA,KAAS,SAAA,IAAa,EAAE,IAAA,IAAQ,KAAA,CAAA,IAAU,KAAA,CAAM,EAAA,IAAM,QAAQ,MAAA,CAAO,KAAA,CAAM,EAAE,CAAA,KAAM,OAAO,EAAE;AAAA,GAC/G;AAEA,EAAA,OAAO,QAAA,CAAY;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,IASjB,UAAU,YAAA,CAAa,QAAQ,CAAA,CAAE,MAAA,CAAO,IAAI,MAAM,CAAA;AAAA,IAClD,SAAS,YAAY;AACnB,MAAA,IAAI,EAAA,IAAM,IAAA,EAAM,MAAM,IAAI,MAAM,YAAY,CAAA;AAC5C,MAAA,MAAM,MAAA,GAAS,MAAM,QAAA,CAAS,MAAA,CAAU,UAAU,EAAE,EAAA,EAAI,QAAQ,CAAA;AAChE,MAAA,OAAO,MAAA,CAAO,IAAA;AAAA,IAChB,CAAA;AAAA,IACA,OAAA,EAAS;AAAA,GACV,CAAA;AACH","file":"chunk-CZOFWG54.js","sourcesContent":["import { useQuery, type UseQueryResult } from \"@tanstack/react-query\";\nimport { useDataProvider } from \"../provider/context\";\nimport type { BaseRecord, Identifier } from \"../provider/types\";\nimport { useLiveInvalidation, type LiveOptions } from \"./use-live\";\nimport { resourceKeys } from \"../query-keys\";\n\n// ---------------------------------------------------------------------------\n// Options\n// ---------------------------------------------------------------------------\n\nexport interface UseOneOptions {\n /** Supabase select/join syntax, e.g. \"*, author:profiles(name)\". */\n select?: string;\n /** Defaults to `!!id` — won't fetch when id is falsy. */\n enabled?: boolean;\n /**\n * Keep the record current while mounted: refetch it when the provider\n * reports a change to it (`DataProvider.subscribe`). See\n * `UseResourceOptions.live`. Off by default.\n */\n live?: boolean | LiveOptions;\n}\n\n// ---------------------------------------------------------------------------\n// Hook\n// ---------------------------------------------------------------------------\n\n/**\n * Fetch a single record by id, powered by TanStack Query.\n *\n * Returns the full `UseQueryResult<T>` with the data unwrapped from the\n * provider's `GetOneResult` wrapper.\n */\nexport function useOne<T extends BaseRecord = BaseRecord>(\n resource: string,\n id: Identifier | undefined | null,\n options: UseOneOptions = {},\n): UseQueryResult<T> {\n const provider = useDataProvider();\n\n const { select, enabled, live } = options;\n const isEnabled = enabled ?? !!id;\n\n // Only this record's events; `changed` (events may have been missed) too.\n useLiveInvalidation(\n resource,\n live,\n isEnabled && id != null,\n id != null ? { id } : {},\n resourceKeys(resource).detailsOf(id),\n (event) => event.type === \"changed\" || !(\"id\" in event) || event.id == null || String(event.id) === String(id),\n );\n\n return useQuery<T>({\n // `select` is part of the key because it is part of the REQUEST: two pages\n // asking for the same record with different projections get different\n // rows back, and keying only on the id makes them share one cache entry.\n // Whichever mounted first wins for the whole staleTime window, and the\n // other silently renders a record missing the joined fields it asked for\n // — no error, no refetch, just absent data. `useResource`'s list key has\n // always included `select` (it keys on the whole `params` object); this\n // was the one place it did not.\n queryKey: resourceKeys(resource).detail(id, select),\n queryFn: async () => {\n if (id == null) throw new Error(\"Missing id\");\n const result = await provider.getOne<T>(resource, { id, select });\n return result.data;\n },\n enabled: isEnabled,\n });\n}\n"]}
@@ -1,5 +1,5 @@
1
1
  import { NO_VIEWER } from './chunk-OZYF55E3.js';
2
- import { flushPendingWrites, dropPendingWrites } from './chunk-3LZAZ5KB.js';
2
+ import { flushPendingWrites, dropPendingWrites } from './chunk-K7WEY5WR.js';
3
3
  import { stableJson } from './chunk-HBAPYA5K.js';
4
4
  import { personTimeZone, dayIn } from './chunk-3B4IFDMK.js';
5
5
  import { reportError } from './chunk-ZIMQUFXD.js';
@@ -105,5 +105,5 @@ function ViewerScope({ viewer, persistedViewer, scope, roles, timeZone, fallback
105
105
  }
106
106
 
107
107
  export { ViewerScope, clearViewerCache, useOptionalViewerScope, useViewer, useViewerScope };
108
- //# sourceMappingURL=chunk-4VRVVN2S.js.map
109
- //# sourceMappingURL=chunk-4VRVVN2S.js.map
108
+ //# sourceMappingURL=chunk-E4777JKI.js.map
109
+ //# sourceMappingURL=chunk-E4777JKI.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/hooks/viewer-scope.tsx"],"names":["Fragment"],"mappings":";;;;;;;;;AAUA,IAAI,cAAA,GAAiB,KAAA;AAOrB,SAAS,WAAW,KAAA,EAA+C;AACjE,EAAA,IAAI,QAAA,GAAW,KAAA;AACf,EAAA,MAAM,KAAA,GAAQ,CAAC,CAAA,KAAwB;AACrC,IAAA,IAAI,MAAM,OAAA,CAAQ,CAAC,GAAG,OAAO,CAAA,CAAE,IAAI,KAAK,CAAA,CAAE,GAAA,CAAI,CAAC,MAAM,CAAC,UAAA,CAAW,CAAC,CAAA,EAAG,CAAC,CAAU,CAAA,CAAE,IAAA,CAAK,CAAC,CAAC,CAAC,CAAA,EAAG,CAAC,CAAC,CAAA,KAAO,CAAA,GAAI,IAAI,EAAA,GAAK,CAAA,GAAI,IAAI,CAAA,GAAI,CAAE,EAAE,GAAA,CAAI,CAAC,GAAG,CAAC,MAAM,CAAC,CAAA;AACnJ,IAAA,IAAI,CAAA,IAAK,OAAO,CAAA,KAAM,QAAA,EAAU;AAC9B,MAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,cAAA,CAAe,CAAC,CAAA;AACrC,MAAA,IAAI,KAAA,KAAU,MAAA,CAAO,SAAA,IAAa,KAAA,KAAU,IAAA,EAAM;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,CAAA,GAAI,SAA+D,MAAS,CAAA;AACtG,EAAA,IAAI,WAAW,MAAA,EAAW,uBAAO,GAAA,CAAAA,QAAAA,EAAA,EAAG,QAAA,EAAA,QAAA,EAAS,CAAA;AAC7C,EAAA,IAAI,OAAA,KAAY,MAAA,IAAa,OAAA,CAAQ,MAAA,KAAW,MAAA,EAAQ;AACtD,IAAA,MAAM,IAAA,GAAO,OAAA,KAAY,MAAA,IAAa,eAAA,KAAoB,UAAa,eAAA,KAAoB,MAAA;AAG3F,IAAA,IAAI,CAAC,IAAA,EAAM;AAIT,MAAA,iBAAA,CAAkB,WAAW,CAAA;AAC7B,MAAA,KAAK,YAAY,aAAA,EAAc;AAC/B,MAAA,WAAA,CAAY,KAAA,EAAM;AAAA,IACpB;AACA,IAAA,UAAA,CAAW,EAAE,MAAA,EAAQ,KAAA,EAAA,CAAQ,SAAS,KAAA,IAAS,CAAA,IAAK,GAAG,CAAA;AACvD,IAAA,uBAAO,GAAA,CAAAA,QAAAA,EAAA,EAAG,QAAA,EAAA,QAAA,EAAS,CAAA;AAAA,EACrB;AACA,EAAA,uBACE,GAAA,CAAC,kBAAA,CAAmB,QAAA,EAAnB,EAA4B,OAC3B,QAAA,kBAAA,GAAA,CAACA,UAAA,EAAA,EAA6D,QAAA,EAAA,EAA/C,CAAA,EAAG,UAAU,YAAY,CAAA,CAAA,EAAI,OAAA,CAAQ,KAAK,EAAc,CAAA,EACzE,CAAA;AAEJ","file":"chunk-4VRVVN2S.js","sourcesContent":["import { useQueryClient, type QueryClient } from \"@tanstack/react-query\";\nimport { createContext, Fragment, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from \"react\";\nimport { dayIn, personTimeZone, type Day } from \"../dates\";\nimport { reportError } from \"../errors\";\nimport { stableJson } from \"./draft-controller\";\nimport { NO_VIEWER, type GenesisViewerRoles, type Viewer } from \"../viewer\";\nimport { dropPendingWrites, flushPendingWrites } from \"./mutation-mode\";\n\nexport { NO_VIEWER, type GenesisViewerRoles, type Viewer };\n\nlet warnedNotPlain = false;\n\n/**\n * Roles as a value: object keys and lists sorted, so `[\"editor\", \"owner\"]` equals\n * `[\"owner\", \"editor\"]`. A Set, Map or class would stringify as `{}` and hide a change: in\n * development that throws; in production it warns once and the roles count as unknown (undefined).\n */\nfunction rolesKeyOf(roles: GenesisViewerRoles): string | undefined {\n let notPlain = false;\n const plain = (v: unknown): unknown => {\n if (Array.isArray(v)) return v.map(plain).map((x) => [stableJson(x), x] as const).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([, x]) => x);\n if (v && typeof v === \"object\") {\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) {\n if (process.env.NODE_ENV !== \"production\") throw new TypeError(\"[genesis-core] ViewerScope roles must be plain JSON (no Set, Map or class)\");\n notPlain = true;\n return null;\n }\n return Object.fromEntries(Object.entries(v as Record<string, unknown>).map(([k, x]) => [k, plain(x)]));\n }\n return v;\n };\n const key = stableJson(plain(roles));\n if (!notPlain) return key;\n if (!warnedNotPlain) {\n warnedNotPlain = true;\n reportError(new TypeError(\"ViewerScope roles must be plain JSON (no Set, Map or class); treating them as unknown, so guards that need them refuse\"), \"core:viewer-scope\");\n }\n return undefined;\n}\n\n/** Today in `zone`, rechecked when the page comes back into view and at the next minute boundary while it's open. */\nfunction useToday(zone: string): Day {\n const [day, setDay] = useState(() => dayIn(zone));\n useEffect(() => {\n const check = () => setDay(dayIn(zone));\n check();\n const onVisible = () => {\n if (typeof document === \"undefined\" || document.visibilityState === \"visible\") check();\n };\n if (typeof document !== \"undefined\") document.addEventListener(\"visibilitychange\", onVisible);\n // A page left open over midnight rolls over within a minute.\n const timer = setInterval(check, 60_000);\n return () => {\n if (typeof document !== \"undefined\") document.removeEventListener(\"visibilitychange\", onVisible);\n clearInterval(timer);\n };\n }, [zone]);\n return day;\n}\n\n/**\n * Empties the query cache for a new viewer: sends the old viewer's waiting\n * undoable writes (the session is still theirs), cancels reads in flight,\n * then removes every query. Call it in the sign-in and sign-out actions,\n * before the session changes.\n */\nexport async function clearViewerCache(queryClient: QueryClient): Promise<void> {\n await flushPendingWrites(queryClient);\n await queryClient.cancelQueries();\n queryClient.clear();\n}\n\n/**\n * Where the viewer is working: the current practice, person or space, or a set\n * of people. Screens turn it into server filters and create defaults; it never\n * decides access (row-level security does).\n */\nexport interface ResourceScope {\n practiceId?: string;\n personId?: string;\n spaceId?: string;\n /** Several people at once (a coach's client list, a group). */\n personIds?: readonly string[];\n [key: string]: unknown;\n}\n\nexport interface ViewerContext {\n viewer: string | null;\n scope: ResourceScope;\n /** The viewer's roles (see `GenesisViewerRoles`), when ViewerScope was given them. */\n roles?: GenesisViewerRoles;\n /** The zone the viewer's days are counted in: theirs if known, else the device's. */\n timeZone: string;\n /**\n * Today on the viewer's clock (YYYY-MM-DD), kept current when the page comes back into view.\n * Use it for every \"today\" read and as query keys' `day`: `keys.for(useViewerScope())`.\n */\n day: Day;\n}\n\nconst ViewerContextValue = createContext<ViewerContext | null>(null);\n\n/** The viewer and scope from the nearest `ViewerScope`. Throws without one: screens that cache per viewer need it. */\nexport function useViewerScope(): ViewerContext {\n const value = useContext(ViewerContextValue);\n if (!value) throw new Error(\"[genesis-core] useViewerScope needs a <ViewerScope> above it\");\n return value;\n}\n\n/** Like useViewerScope, or null outside a ViewerScope. */\nexport function useOptionalViewerScope(): ViewerContext | null {\n return useContext(ViewerContextValue);\n}\n\n/**\n * The viewer for guards: `{ id, scope, roles }` from the nearest ViewerScope, or\n * {@link NO_VIEWER} without one. The object is stable while those are equal by value, so it can\n * sit in a memo's dependencies.\n */\nexport function useViewer(): Viewer {\n const context = useContext(ViewerContextValue);\n return useMemo<Viewer>(\n () =>\n context\n ? Object.freeze({ id: context.viewer, scope: context.scope, ...(context.roles !== undefined ? { roles: context.roles } : {}) })\n : NO_VIEWER,\n [context],\n );\n}\n\nexport interface ViewerScopeProps {\n /** The signed-in viewer's id, null when signed out, undefined while the session loads. */\n viewer: string | null | undefined;\n /**\n * The viewer a persisted cache was saved for. When the first known viewer\n * is this one, the restored cache is kept; otherwise it's emptied.\n */\n persistedViewer?: string | null;\n /** Where the viewer is working (see `ResourceScope`). Changing it doesn't remount or clear anything. */\n scope?: ResourceScope;\n /**\n * What the viewer may do there (see `GenesisViewerRoles`), for view guards. Compared by value,\n * so a new object with the same roles changes nothing. Undefined while they load: guards that\n * need them refuse. Arriving (undefined → roles) or going back to undefined changes nothing;\n * different roles send the person's waiting writes, then reread every query, with nothing\n * remounted. Plain JSON values only (lists are compared as sets, in any order): a Set, Map or\n * class instance throws in development; in production it warns once and the roles count as\n * unknown (as if undefined), so guards that need them refuse.\n */\n roles?: GenesisViewerRoles;\n /**\n * The viewer's saved time zone (IANA), when known; else the device's is used. Pass it when\n * rendering on a server, whose own zone is rarely the viewer's.\n */\n timeZone?: string | null;\n /** Shown while the session loads (and for the one render a change takes). */\n fallback?: ReactNode;\n children: ReactNode;\n}\n\n/**\n * Keeps one viewer's cached data from ever showing to the next. Children\n * render only once the viewer is known, under a key of that viewer, so a\n * sign-out or a new person signing in unmounts every screen and its queries\n * before the cache is emptied and the new viewer's screens mount fresh. The\n * first known viewer empties a restored cache too, unless it's the\n * `persistedViewer` it was saved for.\n *\n * ```tsx\n * <ViewerScope viewer={session === undefined ? undefined : (session?.user.id ?? null)}>\n * <App />\n * </ViewerScope>\n * ```\n */\nexport function ViewerScope({ viewer, persistedViewer, scope, roles, timeZone, fallback = null, children }: ViewerScopeProps) {\n const queryClient = useQueryClient();\n const zone = personTimeZone({ timeZone });\n const day = useToday(zone);\n // A new scope object each render shouldn't re-render every reader: compare by value.\n const scopeKey = stableJson(scope ?? {});\n // Roles by value too: undefined stays undefined, so \"not known yet\" never equals \"none\".\n // Roles that aren't plain JSON count as unknown in production (rolesKeyOf warns; development throws).\n const rolesKey = roles === undefined ? undefined : rolesKeyOf(roles);\n const value = useMemo<ViewerContext>(\n () => ({ viewer: viewer ?? null, scope: scope ?? {}, ...(rolesKey !== undefined ? { roles } : {}), timeZone: zone, day }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [viewer, scopeKey, rolesKey, zone, day],\n );\n // The last roles known for this viewer. Arriving (undefined → roles) or going back to undefined\n // changes nothing; different roles for the same person send their waiting writes, then reread\n // everything under the new roles. Nothing remounts: the person, their drafts and their\n // navigation are the same.\n const known = useRef<{ viewer: string | null | undefined; roles: string | undefined }>({ viewer, roles: undefined });\n useEffect(() => {\n if (known.current.viewer !== viewer) known.current = { viewer, roles: undefined };\n if (rolesKey === undefined) return;\n const previous = known.current.roles;\n known.current.roles = rolesKey;\n if (previous === undefined || previous === rolesKey) return;\n // The session is still theirs: their writes go out, and the database decides each one with the\n // roles as they are when it arrives (a refused one fails as any refused write does).\n void flushPendingWrites(queryClient).then(() => queryClient.invalidateQueries());\n }, [viewer, rolesKey, queryClient]);\n // Who the children were last mounted for, and how many times they were reset. Undefined before\n // the first mount.\n const [mounted, setMounted] = useState<{ viewer: string | null; epoch: number } | undefined>(undefined);\n if (viewer === undefined) return <>{fallback}</>;\n if (mounted === undefined || mounted.viewer !== viewer) {\n const keep = mounted === undefined && persistedViewer !== undefined && persistedViewer === viewer;\n // Nothing for the new viewer is mounted yet, so emptying now can't strand\n // a fetch; the old viewer's screens unmount with this render.\n if (!keep) {\n // The session already belongs to the new viewer: the old one's unsent\n // writes must never go out under it. (clearViewerCache, run before the\n // session changes, sends them instead.)\n dropPendingWrites(queryClient);\n void queryClient.cancelQueries();\n queryClient.clear();\n }\n setMounted({ viewer, epoch: (mounted?.epoch ?? 0) + 1 });\n return <>{fallback}</>;\n }\n return (\n <ViewerContextValue.Provider value={value}>\n <Fragment key={`${viewer ?? \"signed-out\"}#${mounted.epoch}`}>{children}</Fragment>\n </ViewerContextValue.Provider>\n );\n}\n"]}
1
+ {"version":3,"sources":["../src/hooks/viewer-scope.tsx"],"names":["Fragment"],"mappings":";;;;;;;;;AAUA,IAAI,cAAA,GAAiB,KAAA;AAOrB,SAAS,WAAW,KAAA,EAA+C;AACjE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vD,IAAA,uBAAO,GAAA,CAAAA,QAAAA,EAAA,EAAG,QAAA,EAAA,QAAA,EAAS,CAAA;AAAA,EACrB;AACA,EAAA,uBACE,GAAA,CAAC,kBAAA,CAAmB,QAAA,EAAnB,EAA4B,OAC3B,QAAA,kBAAA,GAAA,CAACA,UAAA,EAAA,EAA6D,QAAA,EAAA,EAA/C,CAAA,EAAG,UAAU,YAAY,CAAA,CAAA,EAAI,OAAA,CAAQ,KAAK,EAAc,CAAA,EACzE,CAAA;AAEJ","file":"chunk-E4777JKI.js","sourcesContent":["import { useQueryClient, type QueryClient } from \"@tanstack/react-query\";\nimport { createContext, Fragment, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from \"react\";\nimport { dayIn, personTimeZone, type Day } from \"../dates\";\nimport { reportError } from \"../errors\";\nimport { stableJson } from \"./draft-controller\";\nimport { NO_VIEWER, type GenesisViewerRoles, type Viewer } from \"../viewer\";\nimport { dropPendingWrites, flushPendingWrites } from \"./mutation-mode\";\n\nexport { NO_VIEWER, type GenesisViewerRoles, type Viewer };\n\nlet warnedNotPlain = false;\n\n/**\n * Roles as a value: object keys and lists sorted, so `[\"editor\", \"owner\"]` equals\n * `[\"owner\", \"editor\"]`. A Set, Map or class would stringify as `{}` and hide a change: in\n * development that throws; in production it warns once and the roles count as unknown (undefined).\n */\nfunction rolesKeyOf(roles: GenesisViewerRoles): string | undefined {\n let notPlain = false;\n const plain = (v: unknown): unknown => {\n if (Array.isArray(v)) return v.map(plain).map((x) => [stableJson(x), x] as const).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([, x]) => x);\n if (v && typeof v === \"object\") {\n const proto = Object.getPrototypeOf(v);\n if (proto !== Object.prototype && proto !== null) {\n if (process.env.NODE_ENV !== \"production\") throw new TypeError(\"[genesis-core] ViewerScope roles must be plain JSON (no Set, Map or class)\");\n notPlain = true;\n return null;\n }\n return Object.fromEntries(Object.entries(v as Record<string, unknown>).map(([k, x]) => [k, plain(x)]));\n }\n return v;\n };\n const key = stableJson(plain(roles));\n if (!notPlain) return key;\n if (!warnedNotPlain) {\n warnedNotPlain = true;\n reportError(new TypeError(\"ViewerScope roles must be plain JSON (no Set, Map or class); treating them as unknown, so guards that need them refuse\"), \"core:viewer-scope\");\n }\n return undefined;\n}\n\n/** Today in `zone`, rechecked when the page comes back into view and at the next minute boundary while it's open. */\nfunction useToday(zone: string): Day {\n const [day, setDay] = useState(() => dayIn(zone));\n useEffect(() => {\n const check = () => setDay(dayIn(zone));\n check();\n const onVisible = () => {\n if (typeof document === \"undefined\" || document.visibilityState === \"visible\") check();\n };\n if (typeof document !== \"undefined\") document.addEventListener(\"visibilitychange\", onVisible);\n // A page left open over midnight rolls over within a minute.\n const timer = setInterval(check, 60_000);\n return () => {\n if (typeof document !== \"undefined\") document.removeEventListener(\"visibilitychange\", onVisible);\n clearInterval(timer);\n };\n }, [zone]);\n return day;\n}\n\n/**\n * Empties the query cache for a new viewer: sends the old viewer's waiting\n * undoable writes (the session is still theirs), cancels reads in flight,\n * then removes every query. Call it in the sign-in and sign-out actions,\n * before the session changes.\n */\nexport async function clearViewerCache(queryClient: QueryClient): Promise<void> {\n await flushPendingWrites(queryClient);\n await queryClient.cancelQueries();\n queryClient.clear();\n}\n\n/**\n * Where the viewer is working: the current practice, person or space, or a set\n * of people. Screens turn it into server filters and create defaults; it never\n * decides access (row-level security does).\n */\nexport interface ResourceScope {\n practiceId?: string;\n personId?: string;\n spaceId?: string;\n /** Several people at once (a coach's client list, a group). */\n personIds?: readonly string[];\n [key: string]: unknown;\n}\n\nexport interface ViewerContext {\n viewer: string | null;\n scope: ResourceScope;\n /** The viewer's roles (see `GenesisViewerRoles`), when ViewerScope was given them. */\n roles?: GenesisViewerRoles;\n /** The zone the viewer's days are counted in: theirs if known, else the device's. */\n timeZone: string;\n /**\n * Today on the viewer's clock (YYYY-MM-DD), kept current when the page comes back into view.\n * Use it for every \"today\" read and as query keys' `day`: `keys.for(useViewerScope())`.\n */\n day: Day;\n}\n\nconst ViewerContextValue = createContext<ViewerContext | null>(null);\n\n/** The viewer and scope from the nearest `ViewerScope`. Throws without one: screens that cache per viewer need it. */\nexport function useViewerScope(): ViewerContext {\n const value = useContext(ViewerContextValue);\n if (!value) throw new Error(\"[genesis-core] useViewerScope needs a <ViewerScope> above it\");\n return value;\n}\n\n/** Like useViewerScope, or null outside a ViewerScope. */\nexport function useOptionalViewerScope(): ViewerContext | null {\n return useContext(ViewerContextValue);\n}\n\n/**\n * The viewer for guards: `{ id, scope, roles }` from the nearest ViewerScope, or\n * {@link NO_VIEWER} without one. The object is stable while those are equal by value, so it can\n * sit in a memo's dependencies.\n */\nexport function useViewer(): Viewer {\n const context = useContext(ViewerContextValue);\n return useMemo<Viewer>(\n () =>\n context\n ? Object.freeze({ id: context.viewer, scope: context.scope, ...(context.roles !== undefined ? { roles: context.roles } : {}) })\n : NO_VIEWER,\n [context],\n );\n}\n\nexport interface ViewerScopeProps {\n /** The signed-in viewer's id, null when signed out, undefined while the session loads. */\n viewer: string | null | undefined;\n /**\n * The viewer a persisted cache was saved for. When the first known viewer\n * is this one, the restored cache is kept; otherwise it's emptied.\n */\n persistedViewer?: string | null;\n /** Where the viewer is working (see `ResourceScope`). Changing it doesn't remount or clear anything. */\n scope?: ResourceScope;\n /**\n * What the viewer may do there (see `GenesisViewerRoles`), for view guards. Compared by value,\n * so a new object with the same roles changes nothing. Undefined while they load: guards that\n * need them refuse. Arriving (undefined → roles) or going back to undefined changes nothing;\n * different roles send the person's waiting writes, then reread every query, with nothing\n * remounted. Plain JSON values only (lists are compared as sets, in any order): a Set, Map or\n * class instance throws in development; in production it warns once and the roles count as\n * unknown (as if undefined), so guards that need them refuse.\n */\n roles?: GenesisViewerRoles;\n /**\n * The viewer's saved time zone (IANA), when known; else the device's is used. Pass it when\n * rendering on a server, whose own zone is rarely the viewer's.\n */\n timeZone?: string | null;\n /** Shown while the session loads (and for the one render a change takes). */\n fallback?: ReactNode;\n children: ReactNode;\n}\n\n/**\n * Keeps one viewer's cached data from ever showing to the next. Children\n * render only once the viewer is known, under a key of that viewer, so a\n * sign-out or a new person signing in unmounts every screen and its queries\n * before the cache is emptied and the new viewer's screens mount fresh. The\n * first known viewer empties a restored cache too, unless it's the\n * `persistedViewer` it was saved for.\n *\n * ```tsx\n * <ViewerScope viewer={session === undefined ? undefined : (session?.user.id ?? null)}>\n * <App />\n * </ViewerScope>\n * ```\n */\nexport function ViewerScope({ viewer, persistedViewer, scope, roles, timeZone, fallback = null, children }: ViewerScopeProps) {\n const queryClient = useQueryClient();\n const zone = personTimeZone({ timeZone });\n const day = useToday(zone);\n // A new scope object each render shouldn't re-render every reader: compare by value.\n const scopeKey = stableJson(scope ?? {});\n // Roles by value too: undefined stays undefined, so \"not known yet\" never equals \"none\".\n // Roles that aren't plain JSON count as unknown in production (rolesKeyOf warns; development throws).\n const rolesKey = roles === undefined ? undefined : rolesKeyOf(roles);\n const value = useMemo<ViewerContext>(\n () => ({ viewer: viewer ?? null, scope: scope ?? {}, ...(rolesKey !== undefined ? { roles } : {}), timeZone: zone, day }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [viewer, scopeKey, rolesKey, zone, day],\n );\n // The last roles known for this viewer. Arriving (undefined → roles) or going back to undefined\n // changes nothing; different roles for the same person send their waiting writes, then reread\n // everything under the new roles. Nothing remounts: the person, their drafts and their\n // navigation are the same.\n const known = useRef<{ viewer: string | null | undefined; roles: string | undefined }>({ viewer, roles: undefined });\n useEffect(() => {\n if (known.current.viewer !== viewer) known.current = { viewer, roles: undefined };\n if (rolesKey === undefined) return;\n const previous = known.current.roles;\n known.current.roles = rolesKey;\n if (previous === undefined || previous === rolesKey) return;\n // The session is still theirs: their writes go out, and the database decides each one with the\n // roles as they are when it arrives (a refused one fails as any refused write does).\n void flushPendingWrites(queryClient).then(() => queryClient.invalidateQueries());\n }, [viewer, rolesKey, queryClient]);\n // Who the children were last mounted for, and how many times they were reset. Undefined before\n // the first mount.\n const [mounted, setMounted] = useState<{ viewer: string | null; epoch: number } | undefined>(undefined);\n if (viewer === undefined) return <>{fallback}</>;\n if (mounted === undefined || mounted.viewer !== viewer) {\n const keep = mounted === undefined && persistedViewer !== undefined && persistedViewer === viewer;\n // Nothing for the new viewer is mounted yet, so emptying now can't strand\n // a fetch; the old viewer's screens unmount with this render.\n if (!keep) {\n // The session already belongs to the new viewer: the old one's unsent\n // writes must never go out under it. (clearViewerCache, run before the\n // session changes, sends them instead.)\n dropPendingWrites(queryClient);\n void queryClient.cancelQueries();\n queryClient.clear();\n }\n setMounted({ viewer, epoch: (mounted?.epoch ?? 0) + 1 });\n return <>{fallback}</>;\n }\n return (\n <ViewerContextValue.Provider value={value}>\n <Fragment key={`${viewer ?? \"signed-out\"}#${mounted.epoch}`}>{children}</Fragment>\n </ViewerContextValue.Provider>\n );\n}\n"]}
@@ -46,6 +46,10 @@ function decodeCursor(cursor) {
46
46
  if (!state || typeof state !== "object" || typeof state.k !== "string" || !isIdentifier(state.id)) return void 0;
47
47
  if (state.o !== "asc" && state.o !== "desc") return void 0;
48
48
  if (state.d !== void 0 && state.d !== "b") return void 0;
49
+ if (state.c !== void 0) {
50
+ if (!Array.isArray(state.c) || !Array.isArray(state.vs) || state.c.length !== state.vs.length) return void 0;
51
+ if (!state.c.every((col) => col && typeof col.s === "string" && (col.o === "asc" || col.o === "desc"))) return void 0;
52
+ }
49
53
  return state;
50
54
  } catch {
51
55
  return void 0;
@@ -54,36 +58,44 @@ function decodeCursor(cursor) {
54
58
  function quoteFilterValue(value) {
55
59
  return `"${String(value).replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
56
60
  }
57
- function keysetClauses(state) {
58
- if (state.d === "b") return keysetClausesBefore(state);
59
- const k = state.k;
60
- const K = quoteFilterValue(state.id);
61
- if (state.s === null) return `${k}.${state.o === "asc" ? "gt" : "lt"}.${K}`;
62
- const s = state.s;
63
- const v = state.v;
64
- const afterInTies = (eq) => `and(${eq},${k}.gt.${K})`;
65
- if (v === null || v === void 0) {
66
- const ties2 = afterInTies(`${s}.is.null`);
67
- return state.o === "asc" ? ties2 : `${s}.not.is.null,${ties2}`;
61
+ function cursorColumns(state) {
62
+ if (state.c) return { cols: state.c.map((col, i) => ({ ...col, v: state.vs[i] ?? null })), keyOrder: "asc" };
63
+ if (state.s === null) return { cols: [], keyOrder: state.o };
64
+ return { cols: [{ s: state.s, o: state.o, v: state.v ?? null }], keyOrder: "asc" };
65
+ }
66
+ function sortColumns(params, key) {
67
+ const requested = params.sorts && params.sorts.length > 0 ? params.sorts : params.sort ? [params.sort] : [];
68
+ const columns = [];
69
+ for (const sort of requested) {
70
+ if (sort.field === key) return { columns, keyOrder: sort.order ?? "asc" };
71
+ if (!columns.some((c) => c.field === sort.field)) columns.push({ field: sort.field, order: sort.order ?? "asc" });
68
72
  }
69
- const V = quoteFilterValue(v);
70
- const ties = afterInTies(`${s}.eq.${V}`);
71
- return state.o === "asc" ? `${s}.gt.${V},${ties},${s}.is.null` : `${s}.lt.${V},${ties}`;
73
+ return { columns, keyOrder: "asc" };
72
74
  }
73
- function keysetClausesBefore(state) {
75
+ function keysetClauses(state) {
76
+ const back = state.d === "b";
74
77
  const k = state.k;
75
78
  const K = quoteFilterValue(state.id);
76
- if (state.s === null) return `${k}.${state.o === "asc" ? "lt" : "gt"}.${K}`;
77
- const s = state.s;
78
- const v = state.v;
79
- const beforeInTies = (eq) => `and(${eq},${k}.lt.${K})`;
80
- if (v === null || v === void 0) {
81
- const ties2 = beforeInTies(`${s}.is.null`);
82
- return state.o === "asc" ? `${s}.not.is.null,${ties2}` : ties2;
79
+ const { cols, keyOrder } = cursorColumns(state);
80
+ const keyAhead = `${k}.${keyOrder === "asc" !== back ? "gt" : "lt"}.${K}`;
81
+ if (cols.length === 0) return keyAhead;
82
+ const main = [];
83
+ const tail = [];
84
+ const equal = [];
85
+ const within = (piece) => equal.length ? `and(${equal.join(",")},${piece})` : piece;
86
+ for (const { s, o, v } of cols) {
87
+ const nullsAhead = o === "asc" !== back;
88
+ if (v === null) {
89
+ if (!nullsAhead) main.push(within(`${s}.not.is.null`));
90
+ equal.push(`${s}.is.null`);
91
+ } else {
92
+ const V = quoteFilterValue(v);
93
+ main.push(within(`${s}.${o === "asc" !== back ? "gt" : "lt"}.${V}`));
94
+ if (nullsAhead) tail.push(within(`${s}.is.null`));
95
+ equal.push(`${s}.eq.${V}`);
96
+ }
83
97
  }
84
- const V = quoteFilterValue(v);
85
- const ties = beforeInTies(`${s}.eq.${V}`);
86
- return state.o === "asc" ? `${s}.lt.${V},${ties}` : `${s}.gt.${V},${ties},${s}.is.null`;
98
+ return [...main, `and(${equal.join(",")},${keyAhead})`, ...tail].join(",");
87
99
  }
88
100
  function realtimeTable(resource) {
89
101
  const dot = resource.indexOf(".");
@@ -327,17 +339,18 @@ function createSupabaseProvider(client, options = {}) {
327
339
  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.");
328
340
  }
329
341
  if (!PLAIN_COLUMN.test(key)) return refuseCursor(resource, `the key column "${key}" can't be used in a cursor.`);
330
- const sort = params.sort && params.sort.field !== key ? params.sort : void 0;
331
- if (sort && !PLAIN_COLUMN.test(sort.field)) {
332
- return refuseCursor(resource, `cursor paging can sort only by a plain column, not "${sort.field}".`);
333
- }
334
- const order = params.sort?.order ?? "asc";
335
- const sortField = sort ? sort.field : null;
342
+ const { columns, keyOrder } = sortColumns(params, key);
343
+ const unplain = columns.find((c) => !PLAIN_COLUMN.test(c.field));
344
+ if (unplain) return refuseCursor(resource, `cursor paging can sort only by a plain column, not "${unplain.field}".`);
345
+ const sortFields = columns.map((c) => c.field);
346
+ const shape = (values) => columns.length === 0 ? { s: null, o: keyOrder } : columns.length === 1 ? { s: columns[0].field, o: columns[0].order, v: values[0] ?? null } : { s: null, o: "asc", c: columns.map((c) => ({ s: c.field, o: c.order })), vs: values };
347
+ const sortId = JSON.stringify([columns.map((c) => [c.field, c.order]), keyOrder]);
336
348
  let after;
337
349
  if (cursor) {
338
350
  after = decodeCursor(cursor);
339
351
  if (!after) return refuseCursor(resource, "the cursor is not one this provider made.");
340
- if (after.s !== sortField || after.o !== order || after.k !== key) {
352
+ const made = cursorColumns(after);
353
+ if (JSON.stringify([made.cols.map((c) => [c.s, c.o]), made.keyOrder]) !== sortId || after.k !== key) {
341
354
  return refuseCursor(resource, "the cursor was made for a different sort; start again from the first page (cursor: null).");
342
355
  }
343
356
  }
@@ -349,13 +362,11 @@ function createSupabaseProvider(client, options = {}) {
349
362
  if (search && keyset) query = query.or(`and(or(${search}),or(${keyset}))`);
350
363
  else if (search || keyset) query = query.or(search || keyset);
351
364
  const back = after?.d === "b";
352
- if (sortField) {
365
+ for (const { field, order } of columns) {
353
366
  const ascending = order === "asc" !== back;
354
- query = query.order(sortField, { ascending, nullsFirst: !ascending });
355
- query = query.order(key, { ascending: !back });
356
- } else {
357
- query = query.order(key, { ascending: order === "asc" !== back });
367
+ query = query.order(field, { ascending, nullsFirst: !ascending });
358
368
  }
369
+ query = query.order(key, { ascending: keyOrder === "asc" !== back });
359
370
  query = query.range(0, perPage);
360
371
  const result = await query;
361
372
  await throwIfReadError(result, resource, "getList");
@@ -366,26 +377,23 @@ function createSupabaseProvider(client, options = {}) {
366
377
  const cursorAt = (row, direction) => {
367
378
  if (!row) return null;
368
379
  const id = row[key];
369
- const v = sortField ? row[sortField] : void 0;
370
- if (!isIdentifier(id) || sortField && !(sortField in row)) return false;
371
- if (v !== void 0 && v !== null && typeof v === "object") return false;
372
- return encodeCursor({
373
- s: sortField,
374
- o: order,
375
- k: key,
376
- ...sortField ? { v: v ?? null } : {},
377
- id,
378
- ...direction ? { d: direction } : {}
379
- });
380
+ if (!isIdentifier(id) || sortFields.some((f) => !(f in row))) return false;
381
+ const values = sortFields.map((f) => row[f] ?? null);
382
+ if (values.some((v) => v !== null && typeof v === "object")) return false;
383
+ return encodeCursor({ ...shape(values), k: key, id, ...direction ? { d: direction } : {} });
380
384
  };
381
385
  const next = back ? cursorAt(page[page.length - 1]) : more ? cursorAt(page[page.length - 1]) : null;
382
386
  const prev = back ? more ? cursorAt(page[0], "b") : null : cursor ? cursorAt(page[0], "b") : null;
383
387
  if (next === false || prev === false) {
384
- const objectValued = !!sortField && page.some((row) => sortField in row && row[sortField] !== null && typeof row[sortField] === "object");
388
+ const objectValued = sortFields.find(
389
+ (f) => page.some((row) => f in row && row[f] !== null && typeof row[f] === "object")
390
+ );
385
391
  if (objectValued) {
386
- return refuseCursor(resource, `cursor paging can't sort by "${sortField}": its values aren't plain (text, number, date, boolean).`);
392
+ return refuseCursor(resource, `cursor paging can't sort by "${objectValued}": its values aren't plain (text, number, date, boolean).`);
387
393
  }
388
- return refuseCursor(resource, `the selected columns must include "${key}"${sortField ? ` and "${sortField}"` : ""} to page by cursor.`);
394
+ const needed = [key, ...sortFields].map((f) => `"${f}"`);
395
+ const list = needed.length === 1 ? needed[0] : `${needed.slice(0, -1).join(", ")} and ${needed[needed.length - 1]}`;
396
+ return refuseCursor(resource, `the selected columns must include ${list} to page by cursor.`);
389
397
  }
390
398
  return {
391
399
  data: page,
@@ -425,11 +433,13 @@ function createSupabaseProvider(client, options = {}) {
425
433
  if (clauses) {
426
434
  query = query.or(clauses);
427
435
  }
428
- if (params.sort) {
429
- query = query.order(params.sort.field, {
430
- ascending: params.sort.order === "asc"
431
- });
432
- if (key && key !== params.sort.field) query = query.order(key, { ascending: true });
436
+ const requested = params.sorts && params.sorts.length > 0 ? params.sorts : params.sort ? [params.sort] : [];
437
+ if (requested.length > 0 && key) {
438
+ const { columns, keyOrder } = sortColumns(params, key);
439
+ for (const { field, order } of columns) query = query.order(field, { ascending: order === "asc" });
440
+ query = query.order(key, { ascending: keyOrder === "asc" });
441
+ } else if (requested.length > 0) {
442
+ for (const { field, order } of requested) query = query.order(field, { ascending: order === "asc" });
433
443
  } else if (params.pagination && key) {
434
444
  query = query.order(key, { ascending: true });
435
445
  }
@@ -478,7 +488,7 @@ function createSupabaseProvider(client, options = {}) {
478
488
  bulkWrites: false,
479
489
  versionedWrites: false,
480
490
  compositeKeys: false,
481
- multiSort: false,
491
+ multiSort: true,
482
492
  create: true,
483
493
  delete: true,
484
494
  maxPerPage,
@@ -751,5 +761,5 @@ async function createOrAdopt(provider, resource, data, options) {
751
761
  }
752
762
 
753
763
  export { DEFAULT_RPC_MESSAGES, RPC_FAILED, callRpc, createOrAdopt, createSupabaseProvider };
754
- //# sourceMappingURL=chunk-K7K6NY3C.js.map
755
- //# sourceMappingURL=chunk-K7K6NY3C.js.map
764
+ //# sourceMappingURL=chunk-IOTHEKO7.js.map
765
+ //# sourceMappingURL=chunk-IOTHEKO7.js.map