@marktiderman/genesis-core 2.16.0 → 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.
Files changed (124) hide show
  1. package/README.md +3 -2
  2. package/dist/{aggregate-Y5IJ5aPn.d.ts → aggregate-v_r-nZbH.d.ts} +1 -1
  3. package/dist/{chunk-M5IX7C6U.js → chunk-24X4HWL5.js} +4 -4
  4. package/dist/{chunk-M5IX7C6U.js.map → chunk-24X4HWL5.js.map} +1 -1
  5. package/dist/chunk-2ORQLYVW.js +115 -0
  6. package/dist/chunk-2ORQLYVW.js.map +1 -0
  7. package/dist/{chunk-XPBS5YE4.js → chunk-4POVYF6P.js} +4 -4
  8. package/dist/{chunk-XPBS5YE4.js.map → chunk-4POVYF6P.js.map} +1 -1
  9. package/dist/{chunk-IYGVJFCV.js → chunk-5KLIFJYG.js} +3 -3
  10. package/dist/{chunk-IYGVJFCV.js.map → chunk-5KLIFJYG.js.map} +1 -1
  11. package/dist/{chunk-ALLWIK62.js → chunk-6B4CN2TC.js} +8 -6
  12. package/dist/chunk-6B4CN2TC.js.map +1 -0
  13. package/dist/chunk-6JOWGO2X.js +266 -0
  14. package/dist/chunk-6JOWGO2X.js.map +1 -0
  15. package/dist/{chunk-E3K2A3PK.js → chunk-6SHGMEA6.js} +3 -3
  16. package/dist/{chunk-E3K2A3PK.js.map → chunk-6SHGMEA6.js.map} +1 -1
  17. package/dist/chunk-6VNM6KAX.js +59 -0
  18. package/dist/chunk-6VNM6KAX.js.map +1 -0
  19. package/dist/{chunk-SOO54YYY.js → chunk-AQX5HQD6.js} +3 -3
  20. package/dist/{chunk-SOO54YYY.js.map → chunk-AQX5HQD6.js.map} +1 -1
  21. package/dist/chunk-BNKP2H7J.js +11 -0
  22. package/dist/chunk-BNKP2H7J.js.map +1 -0
  23. package/dist/{chunk-FXPODKCK.js → chunk-FBMKI22S.js} +6 -6
  24. package/dist/{chunk-FXPODKCK.js.map → chunk-FBMKI22S.js.map} +1 -1
  25. package/dist/{chunk-POUI7GAI.js → chunk-JF7FXSQB.js} +5 -5
  26. package/dist/{chunk-POUI7GAI.js.map → chunk-JF7FXSQB.js.map} +1 -1
  27. package/dist/chunk-JNWTHDGF.js +892 -0
  28. package/dist/chunk-JNWTHDGF.js.map +1 -0
  29. package/dist/chunk-K33LWVUF.js +31 -0
  30. package/dist/chunk-K33LWVUF.js.map +1 -0
  31. package/dist/chunk-KRRESUXT.js +192 -0
  32. package/dist/chunk-KRRESUXT.js.map +1 -0
  33. package/dist/{chunk-LB6FMQQM.js → chunk-KV2HW4G4.js} +3 -11
  34. package/dist/chunk-KV2HW4G4.js.map +1 -0
  35. package/dist/{chunk-42NVJJTT.js → chunk-MMMC37AP.js} +3 -3
  36. package/dist/{chunk-42NVJJTT.js.map → chunk-MMMC37AP.js.map} +1 -1
  37. package/dist/chunk-MZVFOTAE.js +96 -0
  38. package/dist/chunk-MZVFOTAE.js.map +1 -0
  39. package/dist/{chunk-R3YXYVWF.js → chunk-OIZNABG4.js} +5 -4
  40. package/dist/chunk-OIZNABG4.js.map +1 -0
  41. package/dist/{chunk-QGWQ6LK3.js → chunk-QJOKZZKY.js} +9 -6
  42. package/dist/chunk-QJOKZZKY.js.map +1 -0
  43. package/dist/chunk-TWLPC4S3.js +53 -0
  44. package/dist/chunk-TWLPC4S3.js.map +1 -0
  45. package/dist/{chunk-7EFTWOMA.js → chunk-UNEZF3ZP.js} +73 -15
  46. package/dist/chunk-UNEZF3ZP.js.map +1 -0
  47. package/dist/chunk-WNOCPV4A.js +220 -0
  48. package/dist/chunk-WNOCPV4A.js.map +1 -0
  49. package/dist/{chunk-ZYOJWU62.js → chunk-XIBQ5BTZ.js} +12 -53
  50. package/dist/chunk-XIBQ5BTZ.js.map +1 -0
  51. package/dist/chunk-YMFJLBIZ.js +159 -0
  52. package/dist/chunk-YMFJLBIZ.js.map +1 -0
  53. package/dist/{chunk-UDSTWXXZ.js → chunk-ZKLB2HB5.js} +3 -3
  54. package/dist/{chunk-UDSTWXXZ.js.map → chunk-ZKLB2HB5.js.map} +1 -1
  55. package/dist/csv.d.ts +12 -3
  56. package/dist/csv.js +4 -4
  57. package/dist/csv.js.map +1 -1
  58. package/dist/form-types.d.ts +1 -1
  59. package/dist/headless/index.d.ts +1 -1
  60. package/dist/hooks/index.d.ts +16 -6
  61. package/dist/hooks/index.js +27 -15
  62. package/dist/hooks/mutation-mode.d.ts +1 -1
  63. package/dist/hooks/mutation-mode.js +3 -3
  64. package/dist/hooks/related-keys.d.ts +1 -1
  65. package/dist/hooks/use-aggregate.d.ts +2 -2
  66. package/dist/hooks/use-aggregate.js +3 -3
  67. package/dist/hooks/use-board-columns.d.ts +79 -0
  68. package/dist/hooks/use-board-columns.js +4 -0
  69. package/dist/hooks/use-board-columns.js.map +1 -0
  70. package/dist/hooks/use-capabilities.d.ts +1 -1
  71. package/dist/hooks/use-capabilities.js +2 -2
  72. package/dist/hooks/use-infinite-resource.d.ts +1 -1
  73. package/dist/hooks/use-infinite-resource.js +3 -3
  74. package/dist/hooks/use-link-options.d.ts +1 -1
  75. package/dist/hooks/use-link-options.js +5 -5
  76. package/dist/hooks/use-list-state.d.ts +103 -0
  77. package/dist/hooks/use-list-state.js +21 -0
  78. package/dist/hooks/use-list-state.js.map +1 -0
  79. package/dist/hooks/use-live.d.ts +1 -1
  80. package/dist/hooks/use-live.js +2 -2
  81. package/dist/hooks/use-one.d.ts +7 -1
  82. package/dist/hooks/use-one.js +3 -3
  83. package/dist/hooks/use-persisted-ui-state.js +2 -2
  84. package/dist/hooks/use-relation-label.d.ts +1 -1
  85. package/dist/hooks/use-relation-label.js +2 -2
  86. package/dist/hooks/use-resource-form.d.ts +1 -1
  87. package/dist/hooks/use-resource-form.js +7 -7
  88. package/dist/hooks/use-resource.d.ts +7 -1
  89. package/dist/hooks/use-resource.js +5 -5
  90. package/dist/hooks/use-segment-counts.d.ts +23 -0
  91. package/dist/hooks/use-segment-counts.js +19 -0
  92. package/dist/hooks/use-segment-counts.js.map +1 -0
  93. package/dist/hooks/use-view-board.d.ts +120 -0
  94. package/dist/hooks/use-view-board.js +29 -0
  95. package/dist/hooks/use-view-board.js.map +1 -0
  96. package/dist/hooks/use-view-calendar-range.d.ts +91 -0
  97. package/dist/hooks/use-view-calendar-range.js +22 -0
  98. package/dist/hooks/use-view-calendar-range.js.map +1 -0
  99. package/dist/hooks/use-write.d.ts +1 -1
  100. package/dist/index.d.ts +41 -11
  101. package/dist/index.js +119 -26
  102. package/dist/index.js.map +1 -1
  103. package/dist/provider/index.d.ts +61 -8
  104. package/dist/provider/index.js +2 -2
  105. package/dist/resource-view/index.d.ts +162 -757
  106. package/dist/resource-view/index.js +31 -686
  107. package/dist/resource-view/index.js.map +1 -1
  108. package/dist/saved-views-C45lRm7i.d.ts +155 -0
  109. package/dist/schema/index.d.ts +3 -3
  110. package/dist/schema/index.js +2 -1
  111. package/dist/testing/index.d.ts +2 -2
  112. package/dist/types-BAhcze_-.d.ts +1063 -0
  113. package/dist/{types-BriIV4e_.d.ts → types-CiQY6hUy.d.ts} +11 -1
  114. package/dist/{viewer-scope-Dx0N9AYk.d.ts → viewer-oOk0ZZk9.d.ts} +36 -34
  115. package/dist/{workspaces-CxpiFu2-.d.ts → workspaces-DeaFix5Z.d.ts} +1 -1
  116. package/dist/workspaces.d.ts +2 -2
  117. package/dist/{write-outcome-CkQXgtJq.d.ts → write-outcome-DuwfsnyO.d.ts} +1 -1
  118. package/package.json +11 -1
  119. package/dist/chunk-7EFTWOMA.js.map +0 -1
  120. package/dist/chunk-ALLWIK62.js.map +0 -1
  121. package/dist/chunk-LB6FMQQM.js.map +0 -1
  122. package/dist/chunk-QGWQ6LK3.js.map +0 -1
  123. package/dist/chunk-R3YXYVWF.js.map +0 -1
  124. package/dist/chunk-ZYOJWU62.js.map +0 -1
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/schema/keys.ts","../src/schema/types.ts"],"names":[],"mappings":";AAYO,SAAS,UAAU,QAAA,E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AAI,MAAA;AACJ,EAAA,IAAI;AACF,IAAA,MAAA,GAAS,IAAA,CAAK,KAAA,CAAM,MAAA,CAAO,EAAE,CAAC,CAAA;AAAA,EAChC,CAAA,CAAA,MAAQ;AACN,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,CAAA,EAAI,MAAA,CAAO,EAAE,CAAC,CAAA,8BAAA,EAAiC,MAAA,CAAO,IAAA,CAAK,IAAI,CAAC,CAAA,EAAA,CAAI,CAAA;AAAA,EACtF;AACA,EAAA,IACE,CAAC,MAAM,OAAA,CAAQ,MAAM,KACrB,MAAA,CAAO,MAAA,KAAW,OAAO,MAAA,IACzB,CAAC,OAAO,KAAA,CAAM,CAAC,MAAM,OAAO,CAAA,KAAM,YAAY,OAAO,CAAA,KAAM,QAAQ,CAAA,EACnE;AACA,IAAA,MAAM,IAAI,KAAA,CAAM,CAAA,CAAA,EAAI,MAAA,CAAO,EAAE,CAAC,CAAA,8BAAA,EAAiC,MAAA,CAAO,IAAA,CAAK,IAAI,CAAC,CAAA,EAAA,CAAI,CAAA;AAAA,EACtF;AACA,EAAA,MAAM,MAAuC,EAAC;AAC9C,EAAA,MAAA,CAAO,OAAA,CAAQ,CAAC,KAAA,EAAO,CAAA,KAAM;AAC3B,IAAA,GAAA,CAAI,KAAK,CAAA,GAAI,MAAA,CAAO,CAAC,CAAA;AAAA,EACvB,CAAC,CAAA;AACD,EAAA,OAAO,GAAA;AACT;;;ACwFO,SAAS,cAAA,GAAsC;AACpD,EAAA,OAAO,CACL,QAAA,KACiC,QAAA;AACrC;AAwOO,SAAS,aAAa,KAAA,EAA6H;AACxJ,EAAA,OAAQ,KAAA,EAAO,WAAW,KAAA,EAAO,MAAA;AACnC","file":"chunk-LB6FMQQM.js","sourcesContent":["// ---------------------------------------------------------------------------\n// Record identity for single and composite keys (DATA-STUDIO.md decision 13)\n//\n// `DataProvider` methods take one `Identifier`. A composite key travels\n// through that same slot as a canonical string, so every existing provider\n// signature stays as it is and a junction table still has one id per row.\n// ---------------------------------------------------------------------------\n\nimport type { Identifier } from \"../provider/types\";\nimport type { DataRow, ResourceContract } from \"./types\";\n\n/** The key of a contract as a list, whichever form `key` was declared in. */\nexport function keyFields(contract: Pick<ResourceContract, \"key\">): readonly string[] {\n return typeof contract.key === \"string\" ? [contract.key] : contract.key;\n}\n\nfunction keyValue(row: DataRow, field: string): string | number {\n const value = row[field];\n if (typeof value === \"string\" || typeof value === \"number\") return value;\n if (typeof value === \"bigint\" || typeof value === \"boolean\") return String(value);\n throw new Error(\n `Record key field \"${field}\" is ${value === null ? \"null\" : typeof value}; ` +\n \"a key value must be a string or a number.\",\n );\n}\n\n/**\n * One `Identifier` for a row.\n *\n * A single-field key returns the raw value, so `id`-keyed resources look\n * exactly as they always have. A composite key returns a JSON array of the\n * values in key order, e.g. `'[\"c-1\",\"u-7\"]'`.\n */\nexport function encodeRecordKey(\n contract: Pick<ResourceContract, \"key\">,\n row: DataRow,\n): Identifier {\n const fields = keyFields(contract);\n if (fields.length === 0) throw new Error(\"This resource has no key, so its rows cannot be addressed.\");\n if (fields.length === 1) return keyValue(row, fields[0]!);\n return JSON.stringify(fields.map((field) => keyValue(row, field)));\n}\n\n/**\n * The inverse of {@link encodeRecordKey}: field name → value.\n *\n * Throws on an id that does not fit the key, rather than guessing, because a\n * guessed key addresses the wrong row.\n */\nexport function decodeRecordKey(\n contract: Pick<ResourceContract, \"key\">,\n id: Identifier,\n): Record<string, string | number> {\n const fields = keyFields(contract);\n if (fields.length === 0) throw new Error(\"This resource has no key, so its rows cannot be addressed.\");\n if (fields.length === 1) return { [fields[0]!]: id };\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(String(id));\n } catch {\n throw new Error(`\"${String(id)}\" is not a composite key for (${fields.join(\", \")}).`);\n }\n if (\n !Array.isArray(parsed) ||\n parsed.length !== fields.length ||\n !parsed.every((v) => typeof v === \"string\" || typeof v === \"number\")\n ) {\n throw new Error(`\"${String(id)}\" is not a composite key for (${fields.join(\", \")}).`);\n }\n const out: Record<string, string | number> = {};\n fields.forEach((field, i) => {\n out[field] = parsed[i] as string | number;\n });\n return out;\n}\n","// ---------------------------------------------------------------------------\n// The one schema model (docs/DATA-STUDIO.md decisions 11, 12, 13, 30)\n//\n// Promoted from @marktiderman/genesis-switchboard, which keeps deprecated\n// aliases for one deprecation window. Everything here is a type or a pure\n// helper with no React, no runtime dependency and no I/O, so a server, an\n// edge function or the switchboard can import it without pulling in the\n// React half of this package.\n// ---------------------------------------------------------------------------\n\nimport type { FieldType } from \"../form-types\";\n\n/**\n * Which form control fits a field (`text`, `textarea`, `date`, `tel`…): a hint a form reads.\n * The field's `control` (decision F, ADR 0021).\n *\n * @stability Beta\n */\nexport type ControlHint = FieldType;\n\n/**\n * @deprecated Renamed `ControlHint`: \"widget\" now means a dashboard tile (docs/GLOSSARY.md).\n * Kept as an alias; removed in the next major.\n */\nexport type WidgetHint = ControlHint;\n\n/**\n * Portable storage type of a field — what kind of value the store holds,\n * independent of how a UI should edit it. The exact native type, when the\n * store reports one, is on {@link FieldSchema.dbType}.\n *\n * Exactly the six types the switchboard shipped as `FieldType`, so existing\n * exhaustive maps over it keep compiling. Finer distinctions (date versus\n * timestamp, enum, uuid) live in `dbType` and `widget`, not here.\n */\nexport type StorageType = \"string\" | \"number\" | \"boolean\" | \"datetime\" | \"json\" | \"relation\";\n\n/** A canonical, provider-agnostic row. Keys are field names from the schema. */\nexport type DataRow = Record<string, unknown>;\n\n/**\n * What the CURRENT user may do with one field. Reported by a provider's\n * `describe()`; never inferred in the browser.\n *\n * `read: false` means the value is never sent to this user, so the column\n * must not render at all (an answer key, a payout amount). `update: false`\n * with `read: true` renders the column read-only.\n */\nexport interface FieldPermissions {\n readonly read: boolean;\n readonly update: boolean;\n /** Why `update` (or `read`) is false, in one human sentence. */\n readonly reason?: string;\n}\n\n/** A foreign-key style link from this field to another resource's field. */\nexport interface FieldReference {\n readonly resource: string;\n readonly field: string;\n}\n\nexport interface FieldSchema {\n /** Canonical field name in the resource's shape (provider-agnostic). */\n readonly name: string;\n /** Portable storage type. */\n readonly type: StorageType;\n /** True when a row may omit this field. */\n readonly optional?: boolean;\n /**\n * True when the field holds an ORDERED LIST of `type` values (e.g. a\n * multi-relation like `deps`/`serves`). Promotion emits a Postgres ARRAY\n * column (`<base>[]`) instead of a lossy scalar, so the cardinality survives\n * L1→L3 (CMT-1742-014).\n */\n readonly array?: boolean;\n /** Human note (surfaces in describe()/drift reports). */\n readonly description?: string;\n /** Human label, e.g. \"Date of birth\". Absent means a UI derives one from `name`. */\n readonly label?: string;\n /** The store's exact type, e.g. `timestamp with time zone` or `public.status`. */\n readonly dbType?: string;\n /**\n * Which form control fits this field (`textarea`, `date`, `tel`…). A hint: a UI may still\n * choose another. Read it with `fieldControl(field)`, which also reads the old `widget`.\n */\n readonly control?: ControlHint;\n /**\n * @deprecated Renamed `control` (\"widget\" now means a dashboard tile). Still read wherever\n * `control` is (`fieldControl`); `control` wins when both are set. Removed in the next major.\n */\n readonly widget?: ControlHint;\n /** True when the store accepts null for this field. */\n readonly nullable?: boolean;\n /** True when the store fills the field itself on insert. */\n readonly hasDefault?: boolean;\n /** True when the store computes the field; it is never written. */\n readonly generated?: boolean;\n /** Allowed values, for enum-like fields. */\n readonly enumValues?: readonly string[];\n /** The resource and field this one points at, when it is a link. */\n readonly references?: FieldReference;\n /** The current user's rights on this field, when a provider reports them. */\n readonly permissions?: FieldPermissions;\n /**\n * The server owns this field (a status it derives, a total, an audit stamp): clients never write\n * it, so a UI shows it read-only. Declared once (`@genesis {\"readonly\": true}`); the database's\n * own guards still enforce it.\n */\n readonly readOnly?: boolean;\n /**\n * The value is sensitive (a note for staff, a health detail): a UI leaves it out of lists, exports\n * and previews unless a screen asks for it. Hiding it from a user is the database's job.\n */\n readonly sensitive?: boolean;\n}\n\n/**\n * One declaration of a resource: its fields and its identity.\n *\n * `key` names the identity field, or several for a composite key (a junction\n * table keyed on `(team_id, user_id)`). Use {@link keyFields} to read it as\n * a list without caring which form it took.\n */\nexport interface ResourceContract<Row extends DataRow = DataRow> {\n /** Resource name the app addresses, e.g. \"tickets\" or \"public.tickets\". */\n readonly name: string;\n /**\n * Identity field name, or names for a composite key, in key order.\n *\n * Typed `string` (not `keyof Row & string`) on purpose: `keyof Row` is a\n * dependent type that TypeScript checks contravariantly, which would make\n * `ResourceContract<WorkCycleRow>` non-assignable to the erased\n * `ResourceContract<DataRow>` that generic consumers accept. The key is\n * validated against the field schema at runtime instead.\n */\n readonly key: string | readonly string[];\n readonly fields: readonly FieldSchema[];\n /** Optional doc string. */\n readonly description?: string;\n /** Human label, e.g. \"Clients\". */\n readonly label?: string;\n /** The field that best names a row to a person (a name or title), for links and pickers. */\n readonly labelField?: string;\n /** What one row is called in sentences (\"brand\"), and several (\"brands\") when not `noun` + \"s\". */\n readonly noun?: string;\n readonly nounPlural?: string;\n /** Phantom marker so `Row` is inferable from a contract. */\n readonly __row?: Row;\n}\n\n/** The row type a contract describes (its phantom `__row`), or `DataRow` when it carries none. */\nexport type RowOf<C> = C extends { readonly __row?: infer R } ? (unknown extends R ? DataRow : NonNullable<R>) : DataRow;\n\n/**\n * Declares a resource contract for a row type, keeping the literal contract (field names, key,\n * labelField) and attaching the row type so views can read it with `RowOf`. `labelField` must be\n * one of the row's fields.\n *\n * ```ts\n * export const publicBrands = defineResource<PublicBrandsRow>()({ name: \"public.brands\", key: \"id\", fields: [...] });\n * type Row = RowOf<typeof publicBrands>; // PublicBrandsRow\n * ```\n */\nexport function defineResource<Row extends DataRow>() {\n return <const C extends ResourceContract<Row> & { readonly labelField?: keyof Row & string }>(\n contract: C,\n ): C & { readonly __row?: Row } => contract;\n}\n\n/** What the current user may do with a whole resource. */\nexport interface ResourceAccess {\n readonly read: boolean;\n /** True when at least one field can be updated on rows this user can see. */\n readonly update: boolean;\n /** Why `update` (or `read`) is false, in one human sentence. */\n readonly reason?: string;\n /** True when this user may add rows. Absent means the provider doesn't say. */\n readonly create?: boolean;\n /** True when this user may delete rows they can see. */\n readonly delete?: boolean;\n /** True when this user may read a row's audit history. */\n readonly history?: boolean;\n /** True when this user may read and add comments on rows they can see. */\n readonly comment?: boolean;\n /** Why `create`, `delete`, `history` or `comment` is false, in one human sentence each. */\n readonly reasons?: {\n readonly create?: string;\n readonly delete?: string;\n readonly history?: string;\n readonly comment?: string;\n };\n}\n\n/**\n * How another resource relates to this one, from the store's foreign keys.\n *\n * - `one`: a field on THIS resource points at one row of `resource`.\n * - `many`: rows of `resource` point at this row through their `field`.\n * - `through`: many rows of `resource`, linked by the junction resource in\n * `through` (a table whose key is two foreign keys).\n */\nexport interface ResourceRelation {\n readonly kind: \"one\" | \"many\" | \"through\";\n /** The related resource. */\n readonly resource: string;\n /**\n * `one`: the field on this resource. `many`: the field on `resource` that\n * holds this row's key. `through`: the junction's field holding this row's key.\n */\n readonly field: string;\n /** For `through`: the junction resource, and its field pointing at `resource`. */\n readonly through?: { readonly resource: string; readonly otherField: string };\n /** True when at most one related row can exist (a unique foreign key). */\n readonly unique?: boolean;\n}\n\n/**\n * The column a provider checks on every update so an edit never silently\n * overwrites someone else's. Only reported when the store itself advances it\n * on every successful update (a trigger such as `moddatetime`), because a\n * column nothing advances detects nothing.\n */\nexport interface VersionField {\n /**\n * The field holding the version. A provider with versioned writes returns\n * each row with its exact version token in this field, as a string, and\n * `expectedVersion` echoes `String(row[field])` back unchanged.\n */\n readonly field: string;\n /**\n * `row`: no column tracks versions, so the token is a fingerprint of the\n * row's values, and `field` is a name the provider adds to each record\n * (it is not one of the resource's fields).\n */\n readonly kind: \"integer\" | \"timestamp\" | \"row\";\n}\n\n/**\n * A resource as `describe()` reports it for the CURRENT user: the contract,\n * plus what this user may do. Fields the user may not read are left out\n * entirely, not marked hidden.\n */\nexport interface ResourceSchema<Row extends DataRow = DataRow> extends ResourceContract<Row> {\n /** Human label, e.g. \"Clients\". */\n readonly label?: string;\n readonly access: ResourceAccess;\n /** Present only when writes can be version-checked. */\n readonly version?: VersionField;\n /** The field that best names a row to a person (a name or title), for links and pickers. */\n readonly labelField?: string;\n /** Resources this one links to or is linked from. Only ones this user may see. */\n readonly relations?: readonly ResourceRelation[];\n /** Fields the user may set when creating a row. Absent when creating isn't allowed. */\n readonly createFields?: readonly string[];\n /** Row actions this user may run: each calls the app's own function on one row. */\n readonly actions?: readonly RowAction[];\n}\n\n/** A named operation on one row, carried out by the app's own database function. */\nexport interface RowAction {\n readonly name: string;\n readonly label: string;\n /** Ask before running, with this question. */\n readonly confirm?: string;\n /** One sentence on what it does. */\n readonly description?: string;\n}\n\n/** A comment on a record. */\nexport interface RecordComment {\n readonly id: string;\n /** The signed-in user who wrote it (the token's `sub`). */\n readonly author: string;\n readonly body: string;\n /** ISO 8601, as the store recorded it. */\n readonly createdAt: string;\n}\n\n/** One entry of `listResources()`: enough to draw a sidebar. */\nexport interface ResourceSummary {\n readonly name: string;\n readonly label?: string;\n readonly description?: string;\n readonly access: ResourceAccess;\n}\n\n/** Filter operators a provider may support. Mirrors `FilterParam[\"operator\"]`. */\nexport type FilterOperator =\n | \"eq\"\n | \"neq\"\n | \"gt\"\n | \"lt\"\n | \"gte\"\n | \"lte\"\n | \"contains\"\n | \"in\"\n | \"between\"\n | \"is_null\"\n | \"is_not_null\";\n\n/**\n * What a provider can do. A UI hides any control the provider cannot serve,\n * instead of letting it error (DATA-STUDIO.md decision 9).\n */\nexport interface ProviderCapabilities {\n /** Server-side text search across fields. */\n readonly search: boolean;\n /** Server-side sort. */\n readonly sort: boolean;\n /** Server-side filter operators. Empty means no server filtering. */\n readonly filterOperators: readonly FilterOperator[];\n /** `updateMany` / `deleteMany` in one transaction. */\n readonly bulkWrites: boolean;\n /** Updates honour `expectedVersion` and reject stale writes. */\n readonly versionedWrites: boolean;\n /**\n * The version field the resource's writes are checked against, asked per\n * resource (`capabilities(resource)`). Present only with `versionedWrites`.\n * The Genesis write hooks send `String(row[version.field])` from the row\n * they last read as `expectedVersion`, so an edit made on a stale copy is\n * refused as a `conflict` instead of overwriting someone else's.\n */\n readonly version?: VersionField;\n /** Records may be keyed by more than one field. */\n readonly compositeKeys: boolean;\n /** Server-side sort by several fields at once (`ListParams.sorts`). */\n readonly multiSort?: boolean;\n /** `create` and `deleteOne` are served, subject to each resource's access. */\n readonly create?: boolean;\n readonly delete?: boolean;\n /** `history` is served, subject to each resource's access. */\n readonly history?: boolean;\n /** `importRows` is served, with a dry run. */\n readonly import?: boolean;\n /** `undo` is served. */\n readonly undo?: boolean;\n /** `runAction` is served. */\n readonly actions?: boolean;\n /** `comments` and `addComment` are served. */\n readonly comments?: boolean;\n /**\n * The most rows one `getList` page may ask for. A request for more is\n * refused (it is not cut short, which would shift later page boundaries),\n * so a client that wants every row must page at this size or less.\n */\n readonly maxPerPage?: number;\n /**\n * A delete moves the record to a recycle bin (it can be restored) instead\n * of removing it. Asked per resource: `capabilities(resource)`.\n */\n readonly softDelete?: boolean;\n /**\n * `create`, `update` and `deleteOne` honour `keepalive: true` in their\n * params (e.g. `fetch(url, { keepalive: true })`), so a write sent while\n * the page unloads still reaches the server. Without it, closing the tab\n * while an optimistic or undoable write is being sent shows the browser's\n * \"Leave site?\" prompt.\n */\n readonly keepaliveWrites?: boolean;\n /**\n * `getList` serves cursor (keyset) paging: `pagination.cursor` in,\n * `nextCursor` out. Pages stay correct while rows are added or removed,\n * and a deep page costs no more than the first.\n */\n readonly cursorPagination?: boolean;\n /**\n * `subscribe` reports changes to this resource (asked per resource:\n * `capabilities(resource)`), so `live` lists and records refresh when\n * someone else changes them.\n */\n readonly realtime?: boolean;\n}\n\n/** One audit record, as committed alongside the edit it describes. */\nexport interface AuditEntry {\n readonly id: string;\n /** ISO 8601 timestamp, as the store recorded it. */\n readonly occurredAt: string;\n /** The signed-in user who made the edit (the token's `sub`). */\n readonly actor: string | null;\n readonly resource: string;\n /** The record's key, field name → value. */\n readonly key: DataRow;\n /** `run` is a row action; `rowAction` names it. */\n readonly action: \"create\" | \"update\" | \"delete\" | \"run\";\n /** For `run`: which row action. */\n readonly rowAction?: string;\n /** Values of the changed fields before the edit. */\n readonly before: DataRow | null;\n /** Values of the changed fields after the edit. */\n readonly after: DataRow | null;\n}\n\n/**\n * A field's form-control hint: its `control`, else the deprecated `widget`. Every reader goes\n * through this, so a contract written with either name works.\n *\n * @stability Beta\n */\nexport function fieldControl(field: { readonly control?: string | undefined; readonly widget?: string | undefined } | undefined): ControlHint | undefined {\n return (field?.control ?? field?.widget) as ControlHint | undefined;\n}\n"]}
@@ -1 +0,0 @@
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-QGWQ6LK3.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 +0,0 @@
1
- {"version":3,"sources":["../src/provider/mock-provider.ts","../src/provider/context.tsx"],"names":[],"mappings":";;;;;;;AAkBO,SAAS,kBAAA,CACd,QAAA,EACA,OAAA,GAA+B,EAAC,EAClB;AACd,EAAA,MAAM,EAAE,KAAA,GAAQ,CAAA,EAAE,GAAI,OAAA;AAGtB,EAAA,MAAM,QAA+B,IAAA,CAAK,KAAA,CAAM,IAAA,CAAK,SAAA,CAAU,QAAQ,CAAC,CAAA;AAGxE,EAAA,IAAI,MAAA,GAAS,CAAA;AAMb,EAAA,SAAS,SAAS,QAAA,EAAyB;AACzC,IAAA,IAAI,CAAC,KAAA,CAAM,QAAQ,CAAA,EAAG;AACpB,MAAA,KAAA,CAAM,QAAQ,IAAI,EAAC;AAAA,IACrB;AACA,IAAA,OAAO,MAAM,QAAQ,CAAA;AAAA,EACvB;AAEA,EAAA,eAAe,UAAa,KAAA,EAAsB;AAChD,IAAA,IAAI,QAAQ,CAAA,EAAG;AACb,MAAA,MAAM,IAAI,OAAA,CAAQ,CAAC,MAAM,UAAA,CAAW,CAAA,EAAG,KAAK,CAAC,CAAA;AAAA,IAC/C;AACA,IAAA,OAAO,KAAA;AAAA,EACT;AAEA,EAAA,SAAS,aAAA,CAAc,KAAU,MAAA,EAA8B;AAC7D,IAAA,MAAM,GAAA,GAAM,GAAA,CAAI,MAAA,CAAO,KAAK,CAAA;AAE5B,IAAA,QAAQ,OAAO,QAAA;AAAU,MACvB,KAAK,IAAA;AACH,QAAA,OAAO,QAAQ,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,YAAA,CAAa,IAAI,CAAA;AACjB,MAAA,IAAA,EAAK;AAAA,IACP,CAAC,CAAA;AACH,IAAA,OAAO,MAAM;AACX,MAAA,KAAA,CAAM,KAAA,EAAM;AACZ,MAAA,YAAA,CAAa,IAAI,CAAA;AACjB,MAAA,IAAA,EAAK;AAAA,IACP,CAAA;AAAA,EACF,CAAA,EAAG,CAAC,WAAA,EAAa,KAAK,CAAC,CAAA;AACvB,EAAA,OAAO,KAAA;AACT;AAMO,IAAM,sBAAA,GAAyB,cAAkC,MAAS","file":"chunk-R3YXYVWF.js","sourcesContent":["import type {\n DataProvider,\n ListParams,\n FilterParam,\n} from \"./types\";\nimport { toAggregateValues } from \"./aggregate\";\n\n// ---------------------------------------------------------------------------\n// Mock DataProvider — operates on in-memory arrays, deep-cloned on creation\n// ---------------------------------------------------------------------------\n\nexport interface MockProviderOptions {\n /** Simulated latency in ms (default 0). */\n delay?: number;\n}\n\ntype Row = Record<string, unknown>;\n\nexport function createMockProvider(\n datasets: Record<string, Row[]>,\n options: MockProviderOptions = {},\n): DataProvider {\n const { delay = 0 } = options;\n\n // Deep clone so mutations don't affect the original data.\n const store: Record<string, Row[]> = JSON.parse(JSON.stringify(datasets));\n\n // Instance-scoped ID counter (NOT module-level).\n let nextId = 1;\n\n // ---------------------------------------------------------------------------\n // Helpers\n // ---------------------------------------------------------------------------\n\n function getTable(resource: string): Row[] {\n if (!store[resource]) {\n store[resource] = [];\n }\n return store[resource];\n }\n\n async function withDelay<T>(value: T): Promise<T> {\n if (delay > 0) {\n await new Promise((r) => setTimeout(r, delay));\n }\n return value;\n }\n\n function matchesFilter(row: Row, filter: FilterParam): boolean {\n const val = row[filter.field];\n\n switch (filter.operator) {\n case \"eq\":\n return val === filter.value;\n case \"neq\":\n return val !== filter.value;\n case \"gt\":\n return (val as number) > (filter.value as number);\n case \"lt\":\n return (val as number) < (filter.value as number);\n case \"gte\":\n return (val as number) >= (filter.value as number);\n case \"lte\":\n return (val as number) <= (filter.value as number);\n case \"contains\":\n return typeof val === \"string\" &&\n val.toLowerCase().includes(String(filter.value).toLowerCase());\n case \"in\":\n return filter.value.includes(val as string | number | boolean);\n case \"is_null\":\n return val === null || val === undefined;\n case \"is_not_null\":\n return val !== null && val !== undefined;\n case \"between\": {\n const [lo, hi] = filter.value;\n return (val as number) >= (lo as number) && (val as number) <= (hi as number);\n }\n }\n }\n\n function matchesSearch(\n row: Row,\n search: { query: string; fields: string[] },\n ): boolean {\n const q = search.query.toLowerCase();\n return search.fields.some((field) => {\n const val = row[field];\n return typeof val === \"string\" && val.toLowerCase().includes(q);\n });\n }\n\n function compareValues(a: unknown, b: unknown): number {\n if (typeof a === \"string\" && typeof b === \"string\") {\n return a.localeCompare(b, undefined, { numeric: true });\n }\n if (typeof a === \"number\" && typeof b === \"number\") {\n return a - b;\n }\n // Fallback: coerce to string.\n return String(a ?? \"\").localeCompare(String(b ?? \"\"), undefined, {\n numeric: true,\n });\n }\n\n function applyListParams(table: Row[], params: ListParams): { data: Row[]; total: number } {\n let rows = [...table];\n\n // Filters (AND).\n if (params.filters) {\n for (const f of params.filters) {\n rows = rows.filter((r) => matchesFilter(r, f));\n }\n }\n\n // Search (OR across fields, AND with filters).\n if (params.search && params.search.query) {\n rows = rows.filter((r) => matchesSearch(r, params.search!));\n }\n\n const total = rows.length;\n\n // Sort.\n // By each sort field in turn (`sorts`, else `sort`).\n const sorts = params.sorts && params.sorts.length > 0 ? params.sorts : params.sort ? [params.sort] : [];\n if (sorts.length > 0) {\n rows.sort((a, b) => {\n for (const { field, order, nulls } of sorts) {\n if (nulls && (a[field] == null) !== (b[field] == null)) {\n return (a[field] == null) === (nulls === \"first\") ? -1 : 1;\n }\n const cmp = compareValues(a[field], b[field]);\n if (cmp !== 0) return order === \"desc\" ? -cmp : cmp;\n }\n return 0;\n });\n }\n\n // Pagination (offset-based).\n if (params.pagination) {\n const { page, perPage } = params.pagination;\n const start = (page - 1) * perPage;\n rows = rows.slice(start, start + perPage);\n }\n\n return { data: rows, total };\n }\n\n // ---------------------------------------------------------------------------\n // DataProvider implementation\n // ---------------------------------------------------------------------------\n\n const provider: DataProvider = {\n async getList(_resource, params) {\n const table = getTable(_resource);\n const result = applyListParams(table, params);\n return withDelay(result) as never;\n },\n\n async aggregate(_resource, params) {\n const { data } = applyListParams(getTable(_resource), { filters: params.filters, search: params.search });\n return withDelay({ values: toAggregateValues(data, params.metrics) });\n },\n\n async getOne(_resource, params) {\n const table = getTable(_resource);\n const row = table.find((r) => String(r.id) === String(params.id));\n if (!row) {\n throw new Error(\n `[MockProvider] Record not found: ${_resource}#${params.id}`,\n );\n }\n return withDelay({ data: JSON.parse(JSON.stringify(row)) }) as never;\n },\n\n async getMany(_resource, params) {\n const table = getTable(_resource);\n const idSet = new Set(params.ids.map(String));\n const rows = table.filter((r) => idSet.has(String(r.id)));\n return withDelay({ data: JSON.parse(JSON.stringify(rows)) }) as never;\n },\n\n async create(_resource, params) {\n const table = getTable(_resource);\n const id = String(nextId++);\n const row = { id, ...params.data } as Row;\n table.push(row);\n return withDelay({ data: JSON.parse(JSON.stringify(row)) }) as never;\n },\n\n async update(_resource, params) {\n const table = getTable(_resource);\n const idx = table.findIndex((r) => String(r.id) === String(params.id));\n if (idx === -1) {\n throw new Error(\n `[MockProvider] Record not found: ${_resource}#${params.id}`,\n );\n }\n table[idx] = { ...table[idx], ...params.data };\n return withDelay({ data: JSON.parse(JSON.stringify(table[idx])) }) as never;\n },\n\n async deleteOne(_resource, params) {\n const table = getTable(_resource);\n const idx = table.findIndex((r) => String(r.id) === String(params.id));\n if (idx === -1) {\n throw new Error(\n `[MockProvider] Record not found: ${_resource}#${params.id}`,\n );\n }\n table.splice(idx, 1);\n return withDelay({ data: { id: params.id } });\n },\n };\n\n return provider;\n}\n","import {\n createContext,\n useContext,\n useEffect,\n useMemo,\n useRef,\n useState,\n type ReactNode,\n} from \"react\";\nimport { QueryClient, QueryClientProvider } from \"@tanstack/react-query\";\nimport type { DataProvider } from \"./types\";\nimport { createMockProvider, type MockProviderOptions } from \"./mock-provider\";\nimport type { StorageAdapter } from \"../storage/types\";\nimport { createLocalStorageAdapter } from \"../storage/adapters\";\nimport type { QueryPersistence } from \"../offline/types\";\n\n// ---------------------------------------------------------------------------\n// Context\n// ---------------------------------------------------------------------------\n\nconst DataProviderContext = createContext<DataProvider | null>(null);\nconst StorageContext = createContext<StorageAdapter>(createLocalStorageAdapter());\n\n// ---------------------------------------------------------------------------\n// DataProviderRoot — thin context wrapper\n// ---------------------------------------------------------------------------\n\n/**\n * Puts a `DataProvider` in context, and nothing else. Mount it inside your\n * app's own `QueryClientProvider` and the Genesis hooks share that cache:\n * the same query keys (`[resource, \"list\", params]`,\n * `[resource, \"detail\", id, select]`), so invalidating `[resource]` from app\n * code refreshes Genesis lists too, and vice versa.\n */\nexport interface DataProviderRootProps {\n provider: DataProvider;\n children: ReactNode;\n}\n\nexport function DataProviderRoot({ provider, children }: DataProviderRootProps) {\n return (\n <DataProviderContext.Provider value={provider}>\n {children}\n </DataProviderContext.Provider>\n );\n}\n\n// ---------------------------------------------------------------------------\n// Hook\n// ---------------------------------------------------------------------------\n\nexport function useDataProvider(): DataProvider {\n const ctx = useContext(DataProviderContext);\n if (!ctx) {\n throw new Error(\n \"useDataProvider must be used inside <DataProviderRoot> or <GenesisProvider>. \" +\n \"Wrap your app (or the relevant subtree) in one of these providers.\",\n );\n }\n return ctx;\n}\n\nexport function useStorage(): StorageAdapter {\n return useContext(StorageContext);\n}\n\n// ---------------------------------------------------------------------------\n// GenesisProvider — convenience wrapper\n// ---------------------------------------------------------------------------\n\ntype Row = Record<string, unknown>;\n\nexport type GenesisProviderProps =\n | {\n children: ReactNode;\n /** Pass a ready-made DataProvider. Mutually exclusive with `mock`. */\n provider: DataProvider;\n mock?: never;\n /** Platform-specific storage adapter. Defaults to localStorage (SSR-safe). */\n storage?: StorageAdapter;\n /**\n * Keep reads on the device and restore them on the next start, so lists and records open at\n * once: `persistOffline({ cache: indexedDbLocalCache(), resources, buster })` from\n * `@marktiderman/genesis-core/offline`. Needs `persistScope`. Give it from the first render:\n * the provider keeps the first one it's given.\n */\n persist?: (client: QueryClient) => QueryPersistence;\n /**\n * Whose cache this is: `cacheScope(user.id, workspaceKey)` once someone is signed in,\n * `null` once nobody is, and `undefined` while that isn't known yet (the session loading).\n * A device is one person's: restoring someone deletes everyone else's kept reads, and\n * `null` deletes them all, so a session that ended outside the app (it expired, or was\n * signed out elsewhere) leaves nothing on the device. Undefined does nothing. A change of\n * scope restores the new one's reads. Clear the QueryClient yourself when the person\n * changes, as a sign-out already does; a `ViewerScope` inside keeps the restored reads for\n * this person. Restoring is client-only: in a server-rendered app, give it after hydration\n * (undefined on the server and the first client render), and the screens restore in the\n * background. Change it only once the provider's session has: a scope must never name a\n * person before the data provider's requests are made as them.\n */\n persistScope?: string | null;\n /**\n * The TanStack Query client to use. Without it, GenesisProvider creates\n * its OWN client — a second cache beside any the app already has, so app\n * queries and Genesis queries would not see each other's invalidations.\n * An app with a `QueryClientProvider` should pass its client here, or\n * use `DataProviderRoot` inside that provider instead.\n */\n queryClient?: QueryClient;\n }\n | {\n children: ReactNode;\n provider?: never;\n /** Pass mock datasets. Mutually exclusive with `provider`. */\n mock: {\n datasets: Record<string, Row[]>;\n options?: MockProviderOptions;\n };\n /** Platform-specific storage adapter. Defaults to localStorage (SSR-safe). */\n storage?: StorageAdapter;\n /** See the `provider` variant. */\n queryClient?: QueryClient;\n /** See the `provider` variant. */\n persist?: (client: QueryClient) => QueryPersistence;\n /** See the `provider` variant. */\n persistScope?: string | null;\n };\n\nconst defaultStorage = createLocalStorageAdapter();\n\n/**\n * Convenience root: a `QueryClientProvider`, storage, and a data provider\n * (yours, or a mock built from datasets). It creates its own `QueryClient`\n * unless you pass `queryClient`; an app that already has one should pass it,\n * or mount `DataProviderRoot` inside its existing `QueryClientProvider`.\n */\nexport function GenesisProvider({\n children,\n provider,\n mock,\n storage,\n queryClient: queryClientProp,\n persist,\n persistScope,\n}: GenesisProviderProps) {\n if (provider && mock) {\n if (process.env.NODE_ENV !== \"production\") {\n console.warn(\"[GenesisProvider] Both `provider` and `mock` were passed. `provider` takes precedence. This is likely a mistake.\");\n }\n }\n\n // Build provider from mock datasets when no explicit provider is given.\n const resolvedProvider = useMemo(() => {\n if (provider) return provider;\n if (mock) return createMockProvider(mock.datasets, mock.options);\n throw new Error(\n \"<GenesisProvider> requires either a `provider` or `mock` prop.\",\n );\n }, [provider, mock]);\n\n // The caller's QueryClient, or an internal one with sensible defaults.\n const queryClient = useMemo(\n () =>\n queryClientProp ??\n new QueryClient({\n defaultOptions: {\n queries: {\n staleTime: 5 * 60 * 1000, // 5 minutes\n },\n },\n }),\n [queryClientProp],\n );\n\n const resolvedStorage = storage ?? defaultStorage;\n const restored = useRestoredReads(queryClient, persist, persistScope);\n\n return (\n <QueryClientProvider client={queryClient}>\n <StorageContext.Provider value={resolvedStorage}>\n <DataProviderRoot provider={resolvedProvider}>\n <PersistedViewerContext.Provider value={persist && typeof persistScope === \"string\" ? userOf(persistScope) : undefined}>\n {restored ? children : null}\n </PersistedViewerContext.Provider>\n </DataProviderRoot>\n </StorageContext.Provider>\n </QueryClientProvider>\n );\n}\n\n/** How long the first render waits for the device's reads before it goes on without them. */\nconst RESTORE_WAIT_MS = 400;\n\n/** The person a scope belongs to (`u:<user>|<workspace>`, or a bare user id). */\nconst userOf = (scope: string) => (scope.startsWith(\"u:\") ? scope.slice(2, scope.indexOf(\"|\") < 0 ? undefined : scope.indexOf(\"|\")) : scope);\n\n/**\n * Restores `scope`'s kept reads before the screens first render (so they open from the device),\n * waiting at most RESTORE_WAIT_MS, then saves new reads. Only the first render waits, and never on\n * the server; a later scope change restores in the background. When the person changes or signs\n * out, their reads are deleted from the device before anything of the next scope is restored.\n */\nfunction useRestoredReads(\n queryClient: QueryClient,\n persist: ((client: QueryClient) => QueryPersistence) | undefined,\n scope: string | null | undefined,\n): boolean {\n // The first `persist` given is kept (one given only later is ignored), so a screen that writes\n // it inline doesn't restart the restore on every render.\n const persistRef = useRef(persist);\n const persistence = useMemo(() => (persistRef.current ? persistRef.current(queryClient) : null), [queryClient]);\n const [ready, setReady] = useState(!persistence || !scope || typeof window === \"undefined\");\n // Whose reads this provider last restored or saved, and the clear of them still running.\n const person = useRef<string | null>(null);\n const clearing = useRef<Promise<void>>(Promise.resolve());\n // The scope the last run of the effect saw (\"not known yet\" at mount). A scope that arrives from\n // there is saved only from reads fetched once it's known: whatever the client already holds or\n // is reading may be another session's (the session was loading, or the client outlived this\n // provider and someone else's session), so it's fetched again (`refresh`), never adopted.\n const previous = useRef<string | null | undefined>(undefined);\n useEffect(() => {\n const from = previous.current;\n previous.current = scope;\n if (!persistence || scope === undefined) {\n // Not known yet who's signed in: nothing is restored, saved or deleted.\n setReady(true);\n return;\n }\n if (scope === null) {\n // Nobody signed in: nothing of anyone's stays on the device.\n person.current = null;\n clearing.current = persistence.restore(\"\").catch(() => undefined);\n setReady(true);\n return;\n }\n const next = userOf(scope);\n if (person.current !== null && person.current !== next) {\n clearing.current = persistence.clear().catch(() => undefined);\n }\n person.current = next;\n const abort = new AbortController();\n // Saving starts with the scope. A read made before it is saved only when the scope before was\n // \"not known yet\" (the same session, loading); from another person or workspace, never.\n const stop = persistence.subscribe(scope, { refresh: from === undefined });\n const open = () => {\n if (!abort.signal.aborted) setReady(true);\n };\n const wait = setTimeout(open, RESTORE_WAIT_MS);\n void clearing.current\n .then(() => (abort.signal.aborted ? undefined : persistence.restore(scope, abort.signal)))\n .catch(() => undefined)\n .finally(() => {\n clearTimeout(wait);\n open();\n });\n return () => {\n abort.abort();\n clearTimeout(wait);\n stop();\n };\n }, [persistence, scope]);\n return ready;\n}\n\n/**\n * The person whose kept reads `GenesisProvider` restored (`persistScope`'s user), so a\n * `ViewerScope` inside keeps them for that viewer instead of emptying the cache.\n */\nexport const PersistedViewerContext = createContext<string | undefined>(undefined);\n\n"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/hooks/viewer-scope.tsx","../src/hoo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A,CAAC,OAAA,EAAS,UAAA,EAAY,QAAA,EAAU,IAAI;AAAA,GACtC;AACA,EAAA,MAAM,SAAS,WAAA,CAAY,MAAA;AAC3B,EAAAC,UAAU,MAAM;AACd,IAAA,IAAI,MAAA,IAAU,OAAA,EAAS,QAAA,CAAS,MAAA,EAAQ,QAAQ,EAAE,CAAA;AAAA,EACpD,CAAA,EAAG,CAAC,MAAA,EAAQ,OAAO,CAAC,CAAA;AACpB,EAAA,uBACEC,GAAAA,CAAC,qBAAA,CAAsB,QAAA,EAAtB,EAA+B,OAC9B,QAAA,kBAAAA,GAAAA;AAAA,IAAC,WAAA;AAAA,IAAA;AAAA,MACE,GAAG,WAAA;AAAA,MACJ,OAAO,EAAE,GAAG,KAAA,EAAO,GAAG,SAAS,KAAA,EAAM;AAAA,MACpC,GAAI,SAAS,KAAA,KAAU,MAAA,GAAY,EAAE,KAAA,EAAO,OAAA,CAAQ,KAAA,EAAM,GAAI,EAAC;AAAA,MAC/D,GAAI,SAAS,QAAA,KAAa,MAAA,GAAY,EAAE,aAAA,EAAe,OAAA,CAAQ,QAAA,EAAS,GAAI,EAAC;AAAA,MAE7E;AAAA;AAAA,GACH,EACF,CAAA;AAEJ","file":"chunk-ZYOJWU62.js","sourcesContent":["import { useQueryClient, type QueryClient } from \"@tanstack/react-query\";\nimport { createContext, Fragment, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from \"react\";\nimport { dayIn, isTimeZone, 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\";\nimport { PersistedViewerContext } from \"../provider/context\";\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 person, space or set of people Genesis knows by name, plus\n * whatever the app scopes to under its own key (`{ orgId }`, `{ leagueId }`, `{ locationId }`).\n * Screens turn it into server filters and create defaults (a view's `scope: [\"league_id\"]` reads\n * `league_id`, then `leagueId`); it never decides access (row-level security does).\n */\nexport interface ResourceScope {\n personId?: string;\n spaceId?: string;\n /** Several people at once (a coach's client list, a group). */\n personIds?: readonly string[];\n /** The app's own scope keys: `orgId`, `leagueId`, `locationId`, … */\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 * The zone of whatever the viewer is scoped to (a location, a league), for columns with\n * `timeZone: \"scope\"`: ViewerScope's `scopeTimeZone` when valid, else {@link timeZone}.\n */\n scopeTimeZone?: 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. Inside a\n * `GenesisProvider` with `persist`, it defaults to its `persistScope`'s user.\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 /**\n * The IANA zone of whatever the viewer is scoped to (a location, a league), when it has one.\n * Columns with `timeZone: \"scope\"` read on it; without it they read on the viewer's clock.\n */\n scopeTimeZone?: 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 * The scope's clock: `scopeTimeZone` when the runtime knows it, else the viewer's. A zone it\n * doesn't know is never a quiet fallback: it throws in development, and in production it is\n * reported (`reportError`, once per zone) before the viewer's clock is used, so a misspelt zone can't show\n * times on the wrong clock unnoticed.\n */\nexport function scopeClock(scopeTimeZone: string | null | undefined, viewerZone: string): string {\n if (scopeTimeZone === undefined || scopeTimeZone === null || scopeTimeZone === \"\") return viewerZone;\n if (isTimeZone(scopeTimeZone)) return scopeTimeZone;\n const error = new RangeError(`[genesis-core] scopeTimeZone \"${scopeTimeZone}\" isn't a time zone this runtime knows (an IANA name such as \"Europe/Berlin\")`);\n if (process.env.NODE_ENV !== \"production\") throw error;\n // Once per zone: a bad zone in a long-lived screen must not flood the error reporter.\n if (!reportedScopeZones.has(scopeTimeZone)) {\n reportedScopeZones.add(scopeTimeZone);\n reportError(error, \"core:viewer-scope\");\n }\n return viewerZone;\n}\n\n/** The unknown scope zones already reported, so each is reported once per page load. */\nconst reportedScopeZones = new Set<string>();\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: persistedViewerProp, scope, roles, timeZone, scopeTimeZone, fallback = null, children }: ViewerScopeProps) {\n const queryClient = useQueryClient();\n const restoredFor = useContext(PersistedViewerContext);\n const persistedViewer = persistedViewerProp !== undefined ? persistedViewerProp : restoredFor;\n const zone = personTimeZone({ timeZone });\n // Memoised, and scopeClock reports a zone once, so a bad zone isn't reported on every render.\n const scopeZone = useMemo(() => scopeClock(scopeTimeZone, zone), [scopeTimeZone, zone]);\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, scopeTimeZone: scopeZone, day }),\n // eslint-disable-next-line react-hooks/exhaustive-deps\n [viewer, scopeKey, rolesKey, zone, scopeZone, 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","import { createContext, useContext, useEffect, useMemo } from \"react\";\nimport { ViewerScope, type ViewerScopeProps } from \"./viewer-scope\";\nimport { workspaceAt, workspaceHref, type Workspace, type WorkspaceHrefOptions } from \"../workspaces\";\n\n/**\n * The workspace the viewer is in, and where each of their others is from here.\n *\n * @stability Beta\n */\nexport interface WorkspaceContext<W extends Workspace = Workspace> {\n /** Undefined when the URL is in no workspace (the app's front door, a sign-in page). */\n current: W | undefined;\n workspaces: readonly W[];\n /** Where switching to `to` goes from the current URL, keeping the viewer's place when it can. */\n hrefFor: (to: W) => string;\n}\n\nconst WorkspaceContextValue = createContext<WorkspaceContext | null>(null);\n\n/**\n * The nearest `WorkspaceScope`'s workspaces, or null outside one.\n *\n * @stability Beta\n */\nexport function useWorkspace<W extends Workspace = Workspace>(): WorkspaceContext<W> | null {\n return useContext(WorkspaceContextValue) as WorkspaceContext<W> | null;\n}\n\nconst STORAGE_PREFIX = \"genesis:workspace:\";\n\n/**\n * The workspace this viewer was last in on this device, for the app's front door\n * (`defaultWorkspace(workspaces, rememberedWorkspaceId(viewer))`). Null when unknown.\n *\n * @stability Beta\n */\nexport function rememberedWorkspaceId(viewer: string | null | undefined): string | null {\n if (!viewer || typeof window === \"undefined\") return null;\n try {\n return window.localStorage.getItem(STORAGE_PREFIX + viewer);\n } catch {\n return null;\n }\n}\n\nfunction remember(viewer: string, id: string) {\n try {\n window.localStorage.setItem(STORAGE_PREFIX + viewer, id);\n } catch {\n // private mode or full: the front door falls back to the first tenant.\n }\n}\n\n/** @stability Beta */\nexport interface WorkspaceScopeProps<W extends Workspace = Workspace> extends Omit<ViewerScopeProps, \"scope\" | \"roles\" | \"scopeTimeZone\"> {\n /** Every workspace this viewer has. */\n workspaces: readonly W[];\n /** The current URL's path (`useLocation().pathname`): the workspace is read from it. */\n pathname: string;\n /** Scope keys every workspace adds to its own (rarely needed). */\n scope?: ViewerScopeProps[\"scope\"];\n /** How switching keeps the viewer's place (see `workspaceHref`). */\n keep?: WorkspaceHrefOptions[\"keep\"];\n}\n\n/**\n * `ViewerScope` for an app with workspaces: use it in place of `ViewerScope`. It reads the current\n * workspace from the URL and scopes everything under it to that workspace (its `scope`, `roles` and\n * `timeZone`), so every view with `scope: [\"org_id\"]` follows the switcher with no screen code. It\n * remembers the workspace per viewer on this device, and gives `WorkspaceSwitcher` its list.\n *\n * ```tsx\n * <WorkspaceScope viewer={userId} workspaces={workspaces} pathname={location.pathname}>\n * <AppShell headerSlot={<WorkspaceSwitcher linkComponent={Link} />} …>\n * </WorkspaceScope>\n * ```\n *\n * @stability Beta\n */\nexport function WorkspaceScope<W extends Workspace>({ workspaces, pathname, scope, keep, children, ...viewerProps }: WorkspaceScopeProps<W>) {\n const current = workspaceAt(workspaces, pathname);\n const value = useMemo<WorkspaceContext<W>>(\n () => ({\n current,\n workspaces,\n hrefFor: (to) => workspaceHref(workspaces, to, pathname, keep ? { keep } : {}),\n }),\n [current, workspaces, pathname, keep],\n );\n const viewer = viewerProps.viewer;\n useEffect(() => {\n if (viewer && current) remember(viewer, current.id);\n }, [viewer, current]);\n return (\n <WorkspaceContextValue.Provider value={value as unknown as WorkspaceContext}>\n <ViewerScope\n {...viewerProps}\n scope={{ ...scope, ...current?.scope }}\n {...(current?.roles !== undefined ? { roles: current.roles } : {})}\n {...(current?.timeZone !== undefined ? { scopeTimeZone: current.timeZone } : {})}\n >\n {children}\n </ViewerScope>\n </WorkspaceContextValue.Provider>\n );\n}\n\n"]}