@marktiderman/genesis-core 2.14.0 → 2.16.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/aggregate-Y5IJ5aPn.d.ts +34 -0
- package/dist/{chunk-7PUFVNPB.js → chunk-2IGAUXYH.js} +5 -3
- package/dist/chunk-2IGAUXYH.js.map +1 -0
- package/dist/{chunk-KA3BUJ4H.js → chunk-42NVJJTT.js} +3 -3
- package/dist/{chunk-KA3BUJ4H.js.map → chunk-42NVJJTT.js.map} +1 -1
- package/dist/{chunk-JN47G4UE.js → chunk-7EFTWOMA.js} +56 -2
- package/dist/chunk-7EFTWOMA.js.map +1 -0
- package/dist/{chunk-P3FHXRS2.js → chunk-ALLWIK62.js} +6 -6
- package/dist/{chunk-P3FHXRS2.js.map → chunk-ALLWIK62.js.map} +1 -1
- package/dist/chunk-APFXV6FZ.js +130 -0
- package/dist/chunk-APFXV6FZ.js.map +1 -0
- package/dist/chunk-BDPRWVFW.js +17 -0
- package/dist/chunk-BDPRWVFW.js.map +1 -0
- package/dist/{chunk-S2VYJWB4.js → chunk-E3K2A3PK.js} +3 -3
- package/dist/{chunk-S2VYJWB4.js.map → chunk-E3K2A3PK.js.map} +1 -1
- package/dist/{chunk-OYDJGPDY.js → chunk-FXPODKCK.js} +5 -5
- package/dist/{chunk-OYDJGPDY.js.map → chunk-FXPODKCK.js.map} +1 -1
- package/dist/{chunk-SDAJSJNN.js → chunk-IYGVJFCV.js} +3 -3
- package/dist/{chunk-SDAJSJNN.js.map → chunk-IYGVJFCV.js.map} +1 -1
- package/dist/chunk-J54XXKQD.js +104 -0
- package/dist/chunk-J54XXKQD.js.map +1 -0
- package/dist/{chunk-KV2HW4G4.js → chunk-LB6FMQQM.js} +11 -3
- package/dist/chunk-LB6FMQQM.js.map +1 -0
- package/dist/{chunk-G6GQPXQS.js → chunk-M5IX7C6U.js} +5 -5
- package/dist/{chunk-G6GQPXQS.js.map → chunk-M5IX7C6U.js.map} +1 -1
- package/dist/{chunk-DFABPMEQ.js → chunk-POUI7GAI.js} +5 -5
- package/dist/{chunk-DFABPMEQ.js.map → chunk-POUI7GAI.js.map} +1 -1
- package/dist/{chunk-NE2D74BP.js → chunk-QGWQ6LK3.js} +5 -5
- package/dist/{chunk-NE2D74BP.js.map → chunk-QGWQ6LK3.js.map} +1 -1
- package/dist/{chunk-2K4747KX.js → chunk-R3YXYVWF.js} +7 -2
- package/dist/chunk-R3YXYVWF.js.map +1 -0
- package/dist/{chunk-RFHUOXZC.js → chunk-SOO54YYY.js} +4 -4
- package/dist/{chunk-RFHUOXZC.js.map → chunk-SOO54YYY.js.map} +1 -1
- package/dist/{chunk-YZV3Z6ZA.js → chunk-SQLM5CIJ.js} +3 -3
- package/dist/{chunk-YZV3Z6ZA.js.map → chunk-SQLM5CIJ.js.map} +1 -1
- package/dist/{chunk-WDPM5TBO.js → chunk-UDSTWXXZ.js} +3 -3
- package/dist/{chunk-WDPM5TBO.js.map → chunk-UDSTWXXZ.js.map} +1 -1
- package/dist/chunk-XPBS5YE4.js +24 -0
- package/dist/chunk-XPBS5YE4.js.map +1 -0
- package/dist/{chunk-AHFIS42U.js → chunk-ZYOJWU62.js} +5 -5
- package/dist/{chunk-AHFIS42U.js.map → chunk-ZYOJWU62.js.map} +1 -1
- package/dist/csv.d.ts +1 -1
- package/dist/form-types.d.ts +1 -1
- package/dist/headless/index.d.ts +334 -0
- package/dist/headless/index.js +490 -0
- package/dist/headless/index.js.map +1 -0
- package/dist/hooks/index.d.ts +4 -2
- package/dist/hooks/index.js +20 -17
- package/dist/hooks/mutation-mode.d.ts +1 -1
- package/dist/hooks/mutation-mode.js +5 -4
- package/dist/hooks/related-keys.d.ts +1 -1
- package/dist/hooks/use-aggregate.d.ts +25 -0
- package/dist/hooks/use-aggregate.js +10 -0
- package/dist/hooks/use-aggregate.js.map +1 -0
- package/dist/hooks/use-capabilities.d.ts +1 -1
- package/dist/hooks/use-capabilities.js +4 -2
- package/dist/hooks/use-draft.js +2 -2
- package/dist/hooks/use-infinite-resource.d.ts +1 -1
- package/dist/hooks/use-infinite-resource.js +6 -4
- package/dist/hooks/use-link-options.d.ts +1 -1
- package/dist/hooks/use-link-options.js +8 -6
- package/dist/hooks/use-live.d.ts +1 -1
- package/dist/hooks/use-live.js +4 -2
- package/dist/hooks/use-one.d.ts +1 -1
- package/dist/hooks/use-one.js +6 -4
- package/dist/hooks/use-persisted-ui-state.js +4 -2
- package/dist/hooks/use-relation-label.d.ts +1 -1
- package/dist/hooks/use-relation-label.js +4 -2
- package/dist/hooks/use-resource-form.d.ts +1 -1
- package/dist/hooks/use-resource-form.js +8 -7
- package/dist/hooks/use-resource.d.ts +1 -1
- package/dist/hooks/use-resource.js +7 -6
- package/dist/hooks/use-write.d.ts +1 -1
- package/dist/index.d.ts +110 -6
- package/dist/index.js +129 -20
- package/dist/index.js.map +1 -1
- package/dist/navigation.d.ts +77 -1
- package/dist/navigation.js +32 -2
- package/dist/navigation.js.map +1 -1
- package/dist/provider/index.d.ts +12 -4
- package/dist/provider/index.js +3 -2
- package/dist/resource-view/index.d.ts +456 -166
- package/dist/resource-view/index.js +251 -5
- package/dist/resource-view/index.js.map +1 -1
- package/dist/schema/index.d.ts +3 -3
- package/dist/schema/index.js +1 -2
- package/dist/testing/index.d.ts +2 -2
- package/dist/{types-CtJxwoyv.d.ts → types-BriIV4e_.d.ts} +78 -3
- package/dist/workspaces-CxpiFu2-.d.ts +263 -0
- package/dist/workspaces.d.ts +2 -160
- package/dist/workspaces.js +2 -1
- package/dist/{write-outcome-Goy1v39G.d.ts → write-outcome-CkQXgtJq.d.ts} +1 -1
- package/package.json +14 -4
- package/dist/chunk-2K4747KX.js.map +0 -1
- package/dist/chunk-7PUFVNPB.js.map +0 -1
- package/dist/chunk-JN47G4UE.js.map +0 -1
- package/dist/chunk-KV2HW4G4.js.map +0 -1
- package/dist/chunk-UHOMTFBD.js +0 -72
- package/dist/chunk-UHOMTFBD.js.map +0 -1
-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AK,YAAA,CAAa,YAAY,EAAE,CAA6B,CAAA;AAAA,IACtG,CAAC,MAAM,YAAY;AAAA,GACrB;AAEA,EAAA,MAAM,QAAA,GAAW,KAAK,SAAA,CAAU,YAAA;AAEhC,EAAA,OAAO;AAAA,IACL,IAAA;AAAA,IACA,cAAA;AAAA,IACA,QAAA;AAAA,IACA,UAAA,EAAY,YAAA;AAAA,IACZ,QAAA;AAAA,IACA,SAAA;AAAA,IACA,OAAA;AAAA,IACA,YAAA;AAAA,IACA,QAAA,EAAU,eAAe,QAAA,IAAY,IAAA;AAAA,IACrC,QAAA;AAAA,IACA,UAAA;AAAA,IACA;AAAA,GACF;AACF","file":"chunk-OYDJGPDY.js","sourcesContent":["import { useMemo, useCallback, useEffect, useRef, useState } from \"react\";\nimport { useForm, type UseFormReturn, type Resolver } from \"react-hook-form\";\nimport { zodResolver } from \"@hookform/resolvers/zod\";\nimport { z } from \"zod\";\nimport { useOne } from \"./use-one\";\nimport { useDataProvider, useStorage } from \"../provider/context\";\nimport { useQueryClient } from \"@tanstack/react-query\";\nimport { titleCase } from \"../utils\";\nimport type { ResourceFormFieldDef, FieldType } from \"../form-types\";\nimport type { BaseRecord, InvalidationKey } from \"../provider/types\";\nimport { relatedKeys } from \"./related-keys\";\nimport { isDataWriteError } from \"../schema/write-outcome\";\nimport { writeConflict, type WriteConflict } from \"../schema/write-state\";\nimport { patchCachedRow } from \"./live-cache\";\nimport {\n cachedRecord,\n executeWrite,\n invalidateResource,\n sameValue,\n type MutationModeOptions,\n} from \"./mutation-mode\";\nimport { useUnsavedChangesGuard } from \"./use-unsaved-changes-guard\";\n\n/** A deep copy where the platform allows one (form values are plain data). */\nfunction structuredCloneSafe<T>(value: T): T {\n try {\n return typeof structuredClone === \"function\" ? structuredClone(value) : value;\n } catch {\n return value;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface UseResourceFormOptions extends MutationModeOptions {\n resource: string;\n action: \"create\" | \"edit\";\n id?: string;\n initialData?: Record<string, unknown>;\n fields?: ResourceFormFieldDef[];\n /**\n * Infer fields from the row's keys when `fields` is empty (or unset). Default true, as before.\n * False: `fields` is the whole form even when empty, so a description that leaves nothing\n * writable (a view) never turns into one input per column of the row being edited.\n */\n inferFields?: boolean;\n /** Full dataset used to auto-detect select fields from unique values. */\n listData?: Record<string, unknown>[];\n /**\n * The form is done. After the save in `pessimistic` mode (with the stored\n * row); at once in `optimistic` and `undoable` modes (with the submitted\n * values over the record, and no `id` for a create).\n */\n onSuccess?: (data: Record<string, unknown>) => void;\n /**\n * The save failed. In `optimistic` and `undoable` modes the form may be\n * gone by then, so show the error from here (genesis-ui's ResourceForm\n * toasts it when no `onError` is given).\n */\n onError?: (error: Error) => void;\n /**\n * Warn before unsaved changes are lost. Default false. While the form is\n * dirty, closing or reloading the tab shows the browser's prompt, and\n * `confirmLeave()` asks before in-app navigation (wire it to a router\n * blocker; see SKILL.md \"Unsaved changes\").\n */\n warnWhenUnsaved?: boolean | { message?: string };\n /**\n * Whether the form is on screen. Default true. Pass false while it is\n * hidden but still mounted (a closed dialog). An optimistic or undoable\n * save that fails later is put back on the form (field errors, unsaved\n * again) only while the form is mounted, visible and still holds the\n * values it saved; otherwise the failure only reaches `onError`.\n */\n visible?: boolean;\n /**\n * Pre-fill create form defaults from URL query params: a param named like a\n * field (`?status=draft`) becomes that field's starting value. Default true.\n * Pass false for a form that should not read the page's URL, e.g. one\n * opened from a list whose own filters live in the query string.\n */\n prefillFromUrl?: boolean;\n /**\n * Generate a placeholder (\"Enter name\", \"name@example.com\") for a field\n * whose `placeholder` is unset. Default true. A placeholder that only\n * repeats the label adds noise without information, so `ResourceForm`\n * turns this off unless asked.\n */\n autoPlaceholder?: boolean;\n /** Validation trigger mode. Default \"onBlur\". */\n validationMode?: \"onBlur\" | \"onChange\" | \"onSubmit\";\n /** Enable autosave drafts to localStorage for create mode. */\n autosave?: boolean | { debounceMs?: number };\n /**\n * Other query keys to invalidate after a save, on top of `[resource]` and\n * the provider's own `invalidates`.\n */\n invalidates?: InvalidationKey[];\n /**\n * What an edit sends. `\"loaded\"` (default): every field of the record the form opened with,\n * plus any field the person changed, but never a field the record didn't carry and nobody\n * touched. So a list that didn't load a column (or a value the server left out) can't be\n * overwritten with an empty one. `\"all\"`: every form field, as before.\n */\n updates?: \"loaded\" | \"all\";\n}\n\nexport interface UseResourceFormReturn {\n form: UseFormReturn<Record<string, unknown>>;\n resolvedFields: ResourceFormFieldDef[];\n onSubmit: (e?: { preventDefault?: () => void }) => Promise<void>;\n /** Raw save handler — use with form.handleSubmit(handleSave, onInvalid). */\n handleSave: (data: Record<string, unknown>) => Promise<void>;\n isSaving: boolean;\n isLoading: boolean;\n /**\n * The form has changes that have not been saved. False again once a save\n * succeeds (or, in optimistic / undoable modes, is handed off).\n */\n isDirty: boolean;\n /**\n * For in-app navigation: true when it is fine to leave (nothing unsaved,\n * `warnWhenUnsaved` off, or the user confirmed). Asks with\n * `window.confirm` otherwise.\n */\n confirmLeave: () => boolean;\n /**\n * Set when a save met someone else's change (a versioned resource's\n * `conflict`): their row beside what this form tried to save. Show it with\n * ConflictSheet; null otherwise.\n */\n conflict: WriteConflict | null;\n /** Save this form's values over theirs, at the version the conflict reported. */\n keepMine: () => Promise<void>;\n /** Drop this form's changes and show their row. */\n takeTheirs: () => void;\n /** Close the conflict without choosing: the form keeps its unsaved values. */\n dismissConflict: () => void;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/** Infer a field type from a value */\nfunction inferFieldType(value: unknown): FieldType {\n if (typeof value === \"boolean\") return \"switch\";\n if (typeof value === \"number\") return \"number\";\n if (typeof value === \"string\") {\n if (/^\\d{4}-\\d{2}-\\d{2}/.test(value)) return \"date\";\n if (value.includes(\"@\") && value.includes(\".\")) return \"email\";\n if (/^https?:\\/\\//.test(value)) return \"url\";\n if (value.length > 100) return \"textarea\";\n }\n return \"text\";\n}\n\n/** Try to infer a select field from unique values across the full dataset */\nfunction inferSelectFromData(\n key: string,\n allData: Record<string, unknown>[] | undefined,\n): { type: \"select\"; options: { value: string; label: string }[] } | null {\n if (!allData || allData.length === 0) return null;\n const uniqueValues = new Set<string>();\n for (const row of allData) {\n const v = row[key];\n if (typeof v === \"string\" && v.length > 0) uniqueValues.add(v);\n }\n if (uniqueValues.size > 0 && uniqueValues.size <= 10) {\n return {\n type: \"select\" as const,\n options: Array.from(uniqueValues)\n .sort()\n .map((v) => ({ value: v, label: v })),\n };\n }\n return null;\n}\n\n/** Generate a sensible placeholder for an auto-inferred field */\nfunction defaultPlaceholder(key: string, type: FieldType): string {\n switch (type) {\n case \"email\": return \"name@example.com\";\n case \"url\": return \"https://...\";\n case \"number\": return \"0\";\n case \"date\": return \"YYYY-MM-DD\";\n case \"textarea\": return `Enter ${titleCase(key).toLowerCase()}...`;\n default: return `Enter ${titleCase(key).toLowerCase()}`;\n }\n}\n\n/** Resolve fields from data keys when none provided */\nfunction resolveFields(\n fields: ResourceFormFieldDef[] | undefined,\n data: Record<string, unknown> | undefined,\n allData?: Record<string, unknown>[],\n autoPlaceholder = true,\n infer = true,\n): ResourceFormFieldDef[] {\n const placeholderFor = (key: string, type: FieldType): string | undefined =>\n autoPlaceholder ? defaultPlaceholder(key, type) : undefined;\n if ((fields && fields.length > 0) || (fields && !infer)) {\n return fields.map((f) => {\n const inferred = f.type ?? (data ? inferFieldType(data[f.key]) : \"text\");\n return {\n ...f,\n label: f.label ?? titleCase(f.key),\n type: inferred,\n placeholder: f.placeholder ?? placeholderFor(f.key, inferred),\n required: f.required ?? (inferred !== \"switch\" && inferred !== \"checkbox\" && inferred !== \"hidden\"),\n };\n });\n }\n\n if (!data || !infer) return [];\n\n return Object.keys(data)\n .filter((key) => key !== \"id\" && key !== \"created_at\" && key !== \"updated_at\")\n .map((key) => {\n // Check for select-like field first (string with few unique values)\n if (typeof data[key] === \"string\") {\n const selectInfo = inferSelectFromData(key, allData);\n if (selectInfo) {\n return {\n key,\n label: titleCase(key),\n type: selectInfo.type,\n options: selectInfo.options,\n placeholder: autoPlaceholder\n ? `Select ${titleCase(key).toLowerCase()}...`\n : undefined,\n required: true,\n };\n }\n }\n\n const inferred = inferFieldType(data[key]);\n return {\n key,\n label: titleCase(key),\n type: inferred,\n placeholder: placeholderFor(key, inferred),\n required: inferred !== \"switch\" && inferred !== \"checkbox\" && inferred !== \"hidden\",\n };\n });\n}\n\n/** Build a zod schema from resolved fields */\nfunction buildSchema(fields: ResourceFormFieldDef[], action: \"create\" | \"edit\" = \"create\") {\n const shape: Record<string, z.ZodTypeAny> = {};\n\n for (const field of fields) {\n const fieldType = field.type ?? \"text\";\n\n if (field.hidden || fieldType === \"hidden\") continue;\n // An edit never sends a field read-only on edit, so it isn't checked either: a row loaded\n // without it would otherwise fail \"required\" on a field the person can't fill.\n if (action === \"edit\" && field.readOnlyOnEdit) continue;\n\n // File/image fields store File objects — z.any() is intentional here because\n // the File API shape varies by platform (browser File, React Native asset, etc.)\n // and form libraries may wrap files differently.\n if (fieldType === \"file\" || fieldType === \"image\") {\n shape[field.key] = field.required !== false ? z.unknown().refine((v) => v != null, { message: `${field.label ?? titleCase(field.key)} is required` }) : z.unknown().optional();\n continue;\n }\n\n switch (fieldType) {\n case \"number\": {\n let schema = z.coerce.number({ message: \"Must be a number\" });\n if (field.min != null) schema = schema.min(field.min);\n if (field.max != null) schema = schema.max(field.max);\n // An optional field may start at null (a screen's `filter` of null): accept it as is,\n // before coercion would turn it into 0.\n shape[field.key] = field.required !== false\n ? schema\n : z.null().or(schema).optional();\n break;\n }\n case \"relation\": {\n // A linked row's key, as the row holds it: text (a uuid) or a number. Cleared, it is null.\n const message = `${field.label ?? titleCase(field.key)} is required`;\n shape[field.key] = field.required !== false\n ? z.unknown().refine((v) => (typeof v === \"string\" && v !== \"\") || (typeof v === \"number\" && Number.isFinite(v)), { message })\n : z.union([z.string(), z.number()]).nullable().optional();\n break;\n }\n case \"array\": {\n if (field.arrayFields) {\n const itemShape: Record<string, z.ZodTypeAny> = {};\n for (const sub of field.arrayFields) {\n const subType = sub.type ?? \"text\";\n if (subType === \"number\") {\n let s = z.coerce.number({ message: \"Must be a number\" });\n if (sub.min != null) s = s.min(sub.min);\n if (sub.max != null) s = s.max(sub.max);\n itemShape[sub.key] = sub.required !== false ? s : s.optional();\n } else if (subType === \"switch\" || subType === \"checkbox\") {\n itemShape[sub.key] = z.boolean().optional();\n } else {\n let s = z.string();\n if (sub.required !== false) {\n s = s.min(1, `${sub.label ?? titleCase(sub.key)} is required`);\n }\n if (subType === \"email\") s = s.email(\"Invalid email address\");\n if (subType === \"url\") s = s.url(\"Invalid URL\");\n if (sub.maxLength != null) {\n s = s.max(\n sub.maxLength,\n `${sub.label ?? titleCase(sub.key)} must be ${sub.maxLength} characters or fewer`,\n );\n }\n itemShape[sub.key] = sub.required === false ? s.optional().or(z.literal(\"\")) : s;\n }\n }\n let arraySchema: z.ZodTypeAny = z.array(z.object(itemShape));\n if (field.arrayMin != null) arraySchema = (arraySchema as z.ZodArray<z.ZodTypeAny>).min(field.arrayMin, `Minimum ${field.arrayMin} items required`);\n if (field.arrayMax != null) arraySchema = (arraySchema as z.ZodArray<z.ZodTypeAny>).max(field.arrayMax, `Maximum ${field.arrayMax} items allowed`);\n shape[field.key] = arraySchema;\n }\n break;\n }\n case \"switch\":\n case \"checkbox\": {\n shape[field.key] = z.boolean().optional();\n break;\n }\n default: {\n // text, email, url, textarea, date, select\n let schema = z.string();\n if (field.required !== false) {\n schema = schema.min(1, `${field.label ?? titleCase(field.key)} is required`);\n }\n if (fieldType === \"email\") {\n schema = schema.email(\"Invalid email address\");\n }\n if (fieldType === \"url\") {\n schema = schema.url(\"Invalid URL\");\n }\n if (field.maxLength != null) {\n schema = schema.max(\n field.maxLength,\n `${field.label ?? titleCase(field.key)} must be ${field.maxLength} characters or fewer`,\n );\n }\n // An optional field may start at null (a screen's `filter` of null); \"\" is an empty input.\n shape[field.key] = field.required === false\n ? schema.optional().nullable().or(z.literal(\"\"))\n : schema;\n break;\n }\n }\n }\n\n return z.object(shape).passthrough();\n}\n\n/** Build default values for a single array item from its sub-field definitions */\nexport function buildArrayItemDefaults(\n arrayFields: ResourceFormFieldDef[],\n): Record<string, unknown> {\n const defaults: Record<string, unknown> = {};\n for (const sub of arrayFields) {\n const subType = sub.type ?? \"text\";\n if (subType === \"number\") defaults[sub.key] = undefined;\n else if (subType === \"switch\" || subType === \"checkbox\") defaults[sub.key] = false;\n else defaults[sub.key] = sub.defaultValue ?? \"\";\n }\n return defaults;\n}\n\n// Input types whose empty value (\"\") can be a real value of the column.\nconst TEXT_TYPES: ReadonlySet<string> = new Set([\"text\", \"textarea\", \"email\", \"tel\", \"url\", \"hidden\"]);\n\n/**\n * What a save sends for an input left empty: `\"\"`, or `undefined` (a cleared number input). Only a field whose column the form knows\n * about (`nullable` set, as ResourceView sets it from a generated contract) is changed:\n * a create leaves it out, so the column's default (or null) applies, and an edit the person\n * made clears it to null. Everything else goes as before, `\"\"` included: a field without\n * `nullable`, an edit of a field nobody touched (`changed` doesn't list it), a value the\n * screen started the field at (its `defaultValue`), and a text column that can't be null\n * (on a create, only when it has no default to fall back on).\n */\nexport function blankValues(\n values: Record<string, unknown>,\n fields: readonly ResourceFormFieldDef[],\n action: \"create\" | \"edit\",\n changed?: ReadonlySet<string>,\n): Record<string, unknown> {\n const byKey = new Map(fields.map((f) => [f.key, f]));\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(values)) {\n const field = byKey.get(key);\n const asBefore =\n (value !== \"\" && value !== undefined) ||\n field?.nullable === undefined ||\n field.defaultValue === \"\" ||\n (action === \"edit\" && changed !== undefined && !changed.has(key)) ||\n (TEXT_TYPES.has(field.type ?? \"text\") && !field.nullable && !(action === \"create\" && field.hasDefault));\n if (asBefore) out[key] = value;\n else if (action === \"edit\") out[key] = null;\n }\n return out;\n}\n\n/** Build default values from fields and existing data */\nfunction buildDefaults(\n fields: ResourceFormFieldDef[],\n data: Record<string, unknown> | undefined,\n action: \"create\" | \"edit\",\n prefillFromUrl: boolean,\n): Record<string, unknown> {\n const defaults: Record<string, unknown> = {};\n for (const field of fields) {\n // A create's blank template (every column as \"\") never hides a field's own default.\n const blankOnCreate = action === \"create\" && data?.[field.key] === \"\" && field.defaultValue !== undefined;\n if (data && field.key in data && !blankOnCreate) {\n defaults[field.key] = data[field.key];\n } else if (field.defaultValue !== undefined) {\n defaults[field.key] = field.defaultValue;\n } else {\n const fieldType = field.type ?? \"text\";\n switch (fieldType) {\n case \"array\":\n defaults[field.key] = field.arrayMin\n ? Array.from({ length: field.arrayMin }, () =>\n buildArrayItemDefaults(field.arrayFields ?? []),\n )\n : [];\n break;\n case \"number\":\n defaults[field.key] = undefined;\n break;\n case \"switch\":\n case \"checkbox\":\n defaults[field.key] = false;\n break;\n default:\n defaults[field.key] = \"\";\n break;\n }\n }\n }\n\n // URL pre-fill for create mode\n if (typeof window !== \"undefined\" && typeof window.location !== \"undefined\" && typeof window.location.search === \"string\" && action === \"create\" && prefillFromUrl !== false) {\n const params = new URLSearchParams(window.location.search);\n for (const field of fields) {\n // A hidden field is the screen's (its filter or defaults), never the URL's; so is one\n // that says so (a value the screen's filter fixes).\n if (field.hidden || field.type === \"hidden\" || field.fromUrl === false) continue;\n const val = params.get(field.key);\n if (val != null) {\n defaults[field.key] = field.type === \"number\" ? Number(val) : val;\n }\n }\n }\n\n return defaults;\n}\n\n// ---------------------------------------------------------------------------\n// Hook\n// ---------------------------------------------------------------------------\n\nexport function useResourceForm(options: UseResourceFormOptions): UseResourceFormReturn {\n const {\n resource,\n action,\n id,\n initialData,\n fields: fieldsProp,\n inferFields = true,\n listData,\n onSuccess,\n onError,\n prefillFromUrl = true,\n autoPlaceholder = true,\n validationMode,\n autosave,\n invalidates,\n warnWhenUnsaved = false,\n mutationMode = \"pessimistic\",\n undoDelayMs,\n onUndoable,\n visible = true,\n updates = \"loaded\",\n } = options;\n\n const autosaveEnabled = !!autosave;\n const debounceMs = typeof autosave === \"object\" ? autosave.debounceMs ?? 1000 : 1000;\n\n const provider = useDataProvider();\n const storage = useStorage();\n const queryClient = useQueryClient();\n\n // Fetch record for edit mode when no initialData\n const needsFetch = action === \"edit\" && !initialData && !!id;\n const fetchResult = useOne(\n resource,\n needsFetch ? id : undefined,\n { enabled: needsFetch },\n );\n\n const fetchedData = fetchResult.data ?? undefined;\n const effectiveData = initialData ?? fetchedData;\n const isLoading = needsFetch && fetchResult.isLoading;\n\n // In edit mode the form starts from the provider's form shape of the row\n // (`DataProvider.toFormValues`), for a resource whose form differs from\n // its table. The record id still comes from the row itself.\n const formSource = useMemo(\n () =>\n action === \"edit\" && effectiveData && provider.toFormValues\n ? provider.toFormValues(resource, effectiveData)\n : effectiveData,\n [action, effectiveData, provider, resource],\n );\n\n // Resolve fields\n const resolvedFields = useMemo(\n () => resolveFields(fieldsProp, formSource, listData, autoPlaceholder, inferFields),\n [fieldsProp, formSource, listData, autoPlaceholder, inferFields],\n );\n\n // Build schema\n const schema = useMemo(\n () => buildSchema(resolvedFields, action),\n [resolvedFields, action],\n );\n\n // Build defaults (with optional draft restoration)\n const defaultValues = useMemo(() => {\n const defaults = buildDefaults(resolvedFields, formSource, action, prefillFromUrl);\n if (autosaveEnabled && action === \"create\") {\n const key = `genesis-draft:${resource}:new`;\n const saved = storage.getItem(key);\n if (saved) {\n try {\n const draft = JSON.parse(saved);\n if (draft && typeof draft === \"object\" && !Array.isArray(draft)) {\n // Only restore keys that exist in the field definitions\n const validKeys = new Set(resolvedFields.map((f) => f.key));\n for (const k of Object.keys(draft)) {\n if (validKeys.has(k)) {\n defaults[k] = draft[k];\n }\n }\n } else {\n console.warn(`[useResourceForm] Draft for \"${resource}\" has unexpected shape, removing`);\n storage.removeItem(key);\n }\n } catch {\n console.warn(`[useResourceForm] Corrupt draft for \"${resource}\", removing`);\n storage.removeItem(key);\n }\n }\n }\n return defaults;\n }, [resolvedFields, formSource, action, prefillFromUrl, autosaveEnabled, resource, storage]);\n\n // Form\n // Cast the resolver because zod v4's passthrough() produces `unknown` for input,\n // but react-hook-form expects FieldValues (Record<string, any>).\n const resolver = useMemo(\n () => zodResolver(schema) as unknown as Resolver<Record<string, unknown>>,\n [schema],\n );\n\n const form = useForm<Record<string, unknown>>({\n resolver,\n defaultValues,\n values: action === \"edit\" ? defaultValues : undefined,\n mode: validationMode ?? \"onBlur\",\n reValidateMode: \"onChange\",\n shouldUnregister: true,\n });\n\n // A create form that stays mounted follows its defaults: the screen's hidden values (a new\n // filter or defaults) always, the rest only while the person hasn't typed anything.\n const firstDefaults = useRef(defaultValues);\n useEffect(() => {\n // By value: a screen may hand a new but equal object every render.\n if (action !== \"create\" || sameValue(firstDefaults.current, defaultValues)) return;\n firstDefaults.current = defaultValues;\n if (!form.formState.isDirty) {\n form.reset(defaultValues);\n return;\n }\n for (const field of resolvedFields) {\n if (field.hidden || field.type === \"hidden\") form.setValue(field.key, defaultValues[field.key]);\n }\n }, [action, defaultValues, form, resolvedFields]);\n\n // Autosave effect — persist form values to storage for create mode\n useEffect(() => {\n if (!autosaveEnabled || action !== \"create\") return;\n const key = `genesis-draft:${resource}:new`;\n let timer: ReturnType<typeof setTimeout>;\n\n const subscription = form.watch((values) => {\n clearTimeout(timer);\n timer = setTimeout(() => {\n try {\n storage.setItem(key, JSON.stringify(values));\n } catch (err) {\n console.warn(`[useResourceForm] Autosave failed for \"${resource}\":`, err instanceof Error ? err.message : String(err));\n }\n }, debounceMs);\n });\n\n return () => {\n clearTimeout(timer);\n subscription.unsubscribe();\n };\n }, [autosaveEnabled, resource, action, form, debounceMs, storage]);\n\n // Unsaved changes: RHF's isDirty, cleared by a successful save until the\n // next edit (a create form keeps its values after saving, so RHF alone\n // would still call it dirty).\n const rhfDirty = form.formState.isDirty;\n const [savedClean, setSavedClean] = useState(false);\n const savedCleanRef = useRef(false);\n useEffect(() => {\n const subscription = form.watch((_values, info) => {\n // `watch` also reports resets (no field name); only an edit dirties.\n if (!info.name) return;\n savedCleanRef.current = false;\n setSavedClean(false);\n });\n return () => subscription.unsubscribe();\n }, [form]);\n const isDirty = rhfDirty && !savedClean;\n const warn = !!warnWhenUnsaved;\n const { confirmLeave: guardConfirm } = useUnsavedChangesGuard({\n when: warn && isDirty,\n message: typeof warnWhenUnsaved === \"object\" ? warnWhenUnsaved.message : undefined,\n });\n const confirmLeave = useCallback(\n // The ref, not state: a router blocker may ask in the same tick as the\n // save's onSuccess navigates, before a re-render.\n () => (!warn || savedCleanRef.current ? true : guardConfirm()),\n [warn, guardConfirm],\n );\n const markSaved = useCallback(() => {\n savedCleanRef.current = true;\n setSavedClean(true);\n }, []);\n\n // A save that fails after it was handed off only comes back to the form\n // while the user can still see it.\n const mountedRef = useRef(true);\n useEffect(() => {\n mountedRef.current = true;\n return () => {\n mountedRef.current = false;\n };\n }, []);\n const visibleRef = useRef(visible);\n visibleRef.current = visible;\n\n /** A failed save, on the form: per-field messages and a root summary. */\n const showError = useCallback(\n (error: Error) => {\n const fieldErrors = isDataWriteError(error) ? error.fields : undefined;\n const known = new Set(resolvedFields.map((f) => f.key));\n let first: string | undefined;\n if (fieldErrors) {\n for (const [field, message] of Object.entries(fieldErrors)) {\n if (!known.has(field)) continue;\n form.setError(field, { type: \"server\", message });\n first ??= field;\n }\n }\n form.setError(\"root\", { type: \"server\", message: error.message });\n if (first) {\n try {\n form.setFocus(first);\n } catch {\n // Not rendered (hidden or custom renderForm): the summary still says it.\n }\n }\n },\n [form, resolvedFields],\n );\n\n const reportError = useCallback(\n (error: Error, handedOff?: Record<string, unknown>) => {\n // A save handed off optimistically and then refused is unsaved again,\n // if the form still shows what it saved; a closed, hidden or reset\n // form is left alone.\n const onForm =\n !handedOff ||\n (mountedRef.current && visibleRef.current && sameValue(form.getValues(), handedOff));\n if (onForm) {\n savedCleanRef.current = false;\n setSavedClean(false);\n showError(error);\n }\n if (onError) {\n onError(error);\n } else {\n console.error(`[useResourceForm] ${action} failed for \"${resource}\":`, error);\n }\n },\n [form, showError, onError, action, resource],\n );\n\n // A save that met someone else's change: the values it tried to save, the fields the person\n // changed, and their row as it is now.\n const [conflictState, setConflictState] = useState<{\n conflict: WriteConflict;\n submitted: Record<string, unknown>;\n changed: readonly string[];\n row: Record<string, unknown>;\n } | null>(null);\n // After \"take theirs\": their row, as the record the next save is checked against, until the\n // form's own record changes.\n const [rebased, setRebased] = useState<BaseRecord | null>(null);\n // Counts conflicts found, so \"keep mine\" can tell a new conflict from a plain failure.\n const conflictsFound = useRef(0);\n // Cleared when the form's record really changes, not when a screen hands an equal object again.\n const rebasedFor = useRef(effectiveData);\n useEffect(() => {\n if (sameValue(rebasedFor.current, effectiveData)) return;\n rebasedFor.current = effectiveData;\n setRebased(null);\n }, [effectiveData]);\n // What this person typed that a conflict hasn't settled: kept on the form across the refetch a\n // rolled-back optimistic save starts (which resets the form to their row), until they save or\n // take theirs, so neither a second conflict nor closing the sheet loses it.\n const [unsettled, setUnsettled] = useState<{ changed: readonly string[]; values: Record<string, unknown> } | null>(null);\n useEffect(() => {\n if (!unsettled) return;\n for (const key of unsettled.changed) {\n if (!sameValue(form.getValues(key), unsettled.values[key])) form.setValue(key, unsettled.values[key], { shouldDirty: true });\n }\n }, [unsettled, defaultValues, form]);\n\n // Submit handler. Resolves true when the save went through (or had nothing to send).\n const save = useCallback(\n async (\n submitted: Record<string, unknown>,\n expectedVersion?: string,\n /** \"Keep mine\": the fields this person changed, as the conflict recorded them. */\n keep?: readonly string[],\n ): Promise<boolean> => {\n // \"Keep mine\" leaves the conflict up until this save settles.\n if (expectedVersion === undefined) setConflictState(null);\n // What the form shows as this save goes out (raw input values, before\n // any resolver coercion), to tell later whether it still does.\n const shown = structuredCloneSafe(form.getValues());\n // A field the opened record didn't carry goes only when the person changed it (compared by\n // value: RHF's dirtyFields updates only when read during render).\n const opened = formSource as Record<string, unknown> | undefined;\n // A field read-only when editing is never written by an edit: sending even its unchanged\n // value would fail on a column the person may not update.\n const lockedOnEdit = new Set(action === \"edit\" ? resolvedFields.filter((f) => f.readOnlyOnEdit).map((f) => f.key) : []);\n const writable = lockedOnEdit.size\n ? Object.fromEntries(Object.entries(submitted).filter(([k]) => !lockedOnEdit.has(k)))\n : submitted;\n const changed =\n action === \"edit\" && updates === \"loaded\" && opened\n ? Object.fromEntries(\n Object.entries(writable).filter(\n // Changed: what an input shows differs from where it started, or, for a value saved\n // without an input (a direct handleSave), the value itself does.\n ([k, v]) =>\n k in opened ||\n !sameValue(k in (shown as object) ? (shown as Record<string, unknown>)[k] : v, defaultValues[k]),\n ),\n )\n : writable;\n // An empty input the person left or made empty is no value (see `blankValues`).\n const touched = new Set(\n keep ??\n Object.entries(changed)\n .filter(([k, v]) => !sameValue(k in (shown as object) ? (shown as Record<string, unknown>)[k] : v, defaultValues[k]))\n .map(([k]) => k),\n );\n const formData = blankValues(changed, resolvedFields, action, touched);\n // A conflict offers only what this person changed, compared in the form's shape.\n const conflictOf = (error: unknown) => {\n const found = writeConflict(error, formData, {\n changed: touched,\n ...(provider.toFormValues && formSource !== effectiveData\n ? { view: (row: Record<string, unknown>) => provider.toFormValues!(resource, row as BaseRecord) as Record<string, unknown> }\n : {}),\n });\n if (found && isDataWriteError(error) && error.current) {\n conflictsFound.current += 1;\n setUnsettled({ changed: [...touched], values: { ...submitted } });\n setConflictState({ conflict: found, submitted, changed: [...touched], row: error.current as Record<string, unknown> });\n }\n return found;\n };\n // An edit with nothing left to write (only read-only fields) has nothing to send.\n if (action === \"edit\" && Object.keys(formData).length === 0) {\n setConflictState(null);\n markSaved();\n onSuccess?.({ ...(effectiveData ?? {}), ...(id != null && id !== \"\" ? { id } : {}) });\n return true;\n }\n try {\n let recordId: string | number | undefined;\n if (action === \"edit\") {\n recordId = id ?? String((effectiveData as Record<string, unknown>)?.id ?? \"\");\n if (!recordId) {\n throw new Error(\"Cannot update record: no ID available. Provide an id prop or ensure the record has an id field.\");\n }\n }\n const before = recordId != null ? cachedRecord(queryClient, resource, recordId) : undefined;\n const outcome = await executeWrite<BaseRecord>({\n queryClient,\n provider,\n resource,\n kind: action === \"create\" ? \"create\" : \"update\",\n id: recordId,\n // The cache holds rows; patch it only when the form's values are\n // row-shaped (no provider.toFormValues reshaping this record).\n data: formSource === effectiveData ? formData : undefined,\n // The record the form shows: its version is the one this edit is checked against, even\n // when the cache has since refetched a newer one.\n ...(action === \"edit\" && (rebased ?? effectiveData) ? { base: (rebased ?? effectiveData) as BaseRecord } : {}),\n ...(expectedVersion !== undefined ? { expectedVersion } : {}),\n mode: mutationMode,\n undoDelayMs,\n onUndoable,\n send: async (ctx) => {\n const keepalive = ctx.keepalive ? { keepalive: true } : {};\n const res =\n action === \"create\"\n ? await provider.create(resource, { data: formData, ...keepalive })\n : await provider.update(resource, {\n id: recordId!,\n data: ctx.data ?? formData,\n ...keepalive,\n ...(ctx.expectedVersion !== undefined ? { expectedVersion: ctx.expectedVersion } : {}),\n });\n return { record: res.data, audit: res.audit };\n },\n committed: async (result) => {\n // The next save from this form is checked against the version this one left, not the\n // record it opened with (a form that stays open after a save, such as a native sheet).\n if (action === \"edit\" && mountedRef.current && result && typeof result === \"object\") {\n const saved = result as BaseRecord;\n setRebased((prev) => ({ ...((prev ?? effectiveData ?? {}) as BaseRecord), ...saved }));\n }\n // Clear draft on successful save\n if (autosaveEnabled && action === \"create\") {\n try {\n storage.removeItem(`genesis-draft:${resource}:new`);\n } catch (err) {\n console.warn(`[useResourceForm] Draft cleanup failed for \"${resource}\":`, err instanceof Error ? err.message : String(err));\n }\n }\n // Invalidate queries to refresh data: the resource's own, then any\n // related keys the provider or the caller named.\n await invalidateResource(queryClient, resource);\n const related = relatedKeys(\n provider,\n {\n resource,\n kind: action === \"create\" ? \"create\" : \"update\",\n id: (recordId ?? result.id) as string | number,\n record: result,\n },\n invalidates,\n );\n await Promise.all(related.map((queryKey) => queryClient.invalidateQueries({ queryKey: [...queryKey] })));\n },\n failedLater: (error) => {\n if (mountedRef.current) conflictOf(error);\n reportError(error, shown);\n },\n });\n setConflictState(null);\n setUnsettled(null);\n markSaved();\n if (outcome.status === \"committed\") {\n onSuccess?.(outcome.record);\n } else {\n onSuccess?.(\n action === \"edit\"\n ? { ...(before ?? effectiveData ?? {}), ...formData, id: recordId }\n : { ...formData },\n );\n }\n return true;\n } catch (err) {\n conflictOf(err);\n reportError(err instanceof Error ? err : new Error(String(err)));\n return false;\n }\n },\n [form, action, provider, resource, id, effectiveData, rebased, formSource, queryClient, onSuccess, autosaveEnabled, storage, invalidates, mutationMode, undoDelayMs, onUndoable, reportError, markSaved, updates, defaultValues, resolvedFields],\n );\n\n const handleSubmit = useCallback(async (submitted: Record<string, unknown>) => {\n await save(submitted);\n }, [save]);\n\n const keepMine = useCallback(async () => {\n if (!conflictState) return;\n const { conflict, submitted, changed } = conflictState;\n // Only what this person changed is theirs to keep: every other field the form sends takes\n // their value, so \"keep mine\" never puts back a stale copy of a field nobody touched here.\n const values = { ...submitted };\n for (const key of Object.keys(values)) {\n if (!changed.includes(key) && key in conflict.theirs) values[key] = conflict.theirs[key];\n }\n form.clearErrors(\"root\");\n const found = conflictsFound.current;\n const ok = await save(values, conflict.currentVersion ?? undefined, changed);\n // Failed without a new conflict (which replaces this one): say why, on the sheet.\n if (!ok && conflictsFound.current === found) throw new Error(form.getFieldState(\"root\").error?.message ?? \"Not saved.\");\n }, [conflictState, form, save]);\n\n const dismissConflict = useCallback(() => setConflictState(null), []);\n\n const takeTheirs = useCallback(() => {\n if (!conflictState) return;\n const { row: theirs } = conflictState;\n setConflictState(null);\n setUnsettled(null);\n // The next save is checked against their row's version, not the one the form opened at.\n setRebased({ ...((effectiveData ?? {}) as BaseRecord), ...(theirs as BaseRecord) });\n form.clearErrors();\n const recordId = id ?? (effectiveData as Record<string, unknown> | undefined)?.id;\n if (recordId != null && recordId !== \"\") {\n // Every cached copy shows their row now; the refetch confirms it.\n patchCachedRow(queryClient, resource, { ...theirs, id: recordId as string | number });\n void invalidateResource(queryClient, resource);\n }\n const shown = action === \"edit\" && provider.toFormValues ? provider.toFormValues(resource, theirs as BaseRecord) : theirs;\n // Every field the form shows, from their row; anything else the form holds stays.\n const next = { ...form.getValues() };\n for (const key of new Set([...resolvedFields.map((f) => f.key), ...Object.keys(next)])) {\n if (key in shown) next[key] = (shown as Record<string, unknown>)[key];\n }\n form.reset(next);\n }, [conflictState, form, id, effectiveData, queryClient, resource, action, provider, resolvedFields]);\n\n const onSubmit = useCallback(\n (e?: { preventDefault?: () => void }) => form.handleSubmit(handleSubmit)(e as React.BaseSyntheticEvent),\n [form, handleSubmit],\n );\n\n const isSaving = form.formState.isSubmitting;\n\n return {\n form,\n resolvedFields,\n onSubmit,\n handleSave: handleSubmit,\n isSaving,\n isLoading,\n isDirty,\n confirmLeave,\n conflict: conflictState?.conflict ?? null,\n keepMine,\n takeTheirs,\n dismissConflict,\n };\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/hooks/use-resource-form.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;AAwBA,SAAS,oBAAuB,KAAA,EAAa;AAC3C,EAAA,IAAI;AACF,IAAA,OAAO,OAAO,eAAA,KAAoB,UAAA,GAAa,eAAA,CAAgB,KAAK,CAAA,GAAI,KAAA;AAAA,EAC1E,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,KAAA;AAAA,EACT;AACF;AAqHA,SAAS,eAAe,KAAA,EAA2B;AACjD,EAAA,IAAI,OAAO,KAAA,KAAU,SAAA,EAAW,OAAO,QAAA;AACvC,EAAA,IAAI,OAAO,KAAA,KAAU,QAAA,EAAU,OAAO,QAAA;AACtC,EAAA,IAAI,OAAO,UAAU,QAAA,EAAU;AAC7B,IAAA,IAAI,oBAAA,CAAqB,IAAA,CAAK,KAAK,CAAA,EAAG,OAAO,MAAA;AAC7C,IAAA,IAAI,KAAA,CAAM,SAAS,GAAG,CAAA,IAAK,MAAM,QAAA,CAAS,GAAG,GAAG,OAAO,OAAA;AACvD,IAAA,IAAI,cAAA,CAAe,IAAA,CAAK,KAAK,CAAA,EAAG,OAAO,KAAA;AACvC,IAAA,IAAI,KAAA,CAAM,MA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IAAI,CAAC,CAAC,CAAA,EAAG;AACtF,MAAA,IAAI,OAAO,KAAA,EAAO,IAAA,CAAK,GAAG,CAAA,GAAK,MAAkC,GAAG,CAAA;AAAA,IACtE;AACA,IAAA,IAAA,CAAK,MAAM,IAAI,CAAA;AAAA,EACjB,CAAA,EAAG,CAAC,aAAA,EAAe,IAAA,EAAM,EAAA,EAAI,aAAA,EAAe,WAAA,EAAa,QAAA,EAAU,MAAA,EAAQ,QAAA,EAAU,cAAc,CAAC,CAAA;AAEpG,EAAA,MAAM,QAAA,GAAW,WAAA;AAAA,IACf,CAAC,CAAA,KAAwC,IAAA,CAAK,YAAA,CAAa,YAAY,EAAE,CAA6B,CAAA;AAAA,IACtG,CAAC,MAAM,YAAY;AAAA,GACrB;AAEA,EAAA,MAAM,QAAA,GAAW,KAAK,SAAA,CAAU,YAAA;AAEhC,EAAA,OAAO;AAAA,IACL,IAAA;AAAA,IACA,cAAA;AAAA,IACA,QAAA;AAAA,IACA,UAAA,EAAY,YAAA;AAAA,IACZ,QAAA;AAAA,IACA,SAAA;AAAA,IACA,OAAA;AAAA,IACA,YAAA;AAAA,IACA,QAAA,EAAU,eAAe,QAAA,IAAY,IAAA;AAAA,IACrC,QAAA;AAAA,IACA,UAAA;AAAA,IACA;AAAA,GACF;AACF","file":"chunk-FXPODKCK.js","sourcesContent":["import { useMemo, useCallback, useEffect, useRef, useState } from \"react\";\nimport { useForm, type UseFormReturn, type Resolver } from \"react-hook-form\";\nimport { zodResolver } from \"@hookform/resolvers/zod\";\nimport { z } from \"zod\";\nimport { useOne } from \"./use-one\";\nimport { useDataProvider, useStorage } from \"../provider/context\";\nimport { useQueryClient } from \"@tanstack/react-query\";\nimport { titleCase } from \"../utils\";\nimport type { ResourceFormFieldDef, FieldType } from \"../form-types\";\nimport type { BaseRecord, InvalidationKey } from \"../provider/types\";\nimport { relatedKeys } from \"./related-keys\";\nimport { isDataWriteError } from \"../schema/write-outcome\";\nimport { writeConflict, type WriteConflict } from \"../schema/write-state\";\nimport { patchCachedRow } from \"./live-cache\";\nimport {\n cachedRecord,\n executeWrite,\n invalidateResource,\n sameValue,\n type MutationModeOptions,\n} from \"./mutation-mode\";\nimport { useUnsavedChangesGuard } from \"./use-unsaved-changes-guard\";\n\n/** A deep copy where the platform allows one (form values are plain data). */\nfunction structuredCloneSafe<T>(value: T): T {\n try {\n return typeof structuredClone === \"function\" ? structuredClone(value) : value;\n } catch {\n return value;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Types\n// ---------------------------------------------------------------------------\n\nexport interface UseResourceFormOptions extends MutationModeOptions {\n resource: string;\n action: \"create\" | \"edit\";\n id?: string;\n initialData?: Record<string, unknown>;\n fields?: ResourceFormFieldDef[];\n /**\n * Infer fields from the row's keys when `fields` is empty (or unset). Default true, as before.\n * False: `fields` is the whole form even when empty, so a description that leaves nothing\n * writable (a view) never turns into one input per column of the row being edited.\n */\n inferFields?: boolean;\n /** Full dataset used to auto-detect select fields from unique values. */\n listData?: Record<string, unknown>[];\n /**\n * The form is done. After the save in `pessimistic` mode (with the stored\n * row); at once in `optimistic` and `undoable` modes (with the submitted\n * values over the record, and no `id` for a create).\n */\n onSuccess?: (data: Record<string, unknown>) => void;\n /**\n * The save failed. In `optimistic` and `undoable` modes the form may be\n * gone by then, so show the error from here (genesis-ui's ResourceForm\n * toasts it when no `onError` is given).\n */\n onError?: (error: Error) => void;\n /**\n * Warn before unsaved changes are lost. Default false. While the form is\n * dirty, closing or reloading the tab shows the browser's prompt, and\n * `confirmLeave()` asks before in-app navigation (wire it to a router\n * blocker; see SKILL.md \"Unsaved changes\").\n */\n warnWhenUnsaved?: boolean | { message?: string };\n /**\n * Whether the form is on screen. Default true. Pass false while it is\n * hidden but still mounted (a closed dialog). An optimistic or undoable\n * save that fails later is put back on the form (field errors, unsaved\n * again) only while the form is mounted, visible and still holds the\n * values it saved; otherwise the failure only reaches `onError`.\n */\n visible?: boolean;\n /**\n * Pre-fill create form defaults from URL query params: a param named like a\n * field (`?status=draft`) becomes that field's starting value. Default true.\n * Pass false for a form that should not read the page's URL, e.g. one\n * opened from a list whose own filters live in the query string.\n */\n prefillFromUrl?: boolean;\n /**\n * Generate a placeholder (\"Enter name\", \"name@example.com\") for a field\n * whose `placeholder` is unset. Default true. A placeholder that only\n * repeats the label adds noise without information, so `ResourceForm`\n * turns this off unless asked.\n */\n autoPlaceholder?: boolean;\n /** Validation trigger mode. Default \"onBlur\". */\n validationMode?: \"onBlur\" | \"onChange\" | \"onSubmit\";\n /** Enable autosave drafts to localStorage for create mode. */\n autosave?: boolean | { debounceMs?: number };\n /**\n * Other query keys to invalidate after a save, on top of `[resource]` and\n * the provider's own `invalidates`.\n */\n invalidates?: InvalidationKey[];\n /**\n * What an edit sends. `\"loaded\"` (default): every field of the record the form opened with,\n * plus any field the person changed, but never a field the record didn't carry and nobody\n * touched. So a list that didn't load a column (or a value the server left out) can't be\n * overwritten with an empty one. `\"all\"`: every form field, as before.\n */\n updates?: \"loaded\" | \"all\";\n}\n\nexport interface UseResourceFormReturn {\n form: UseFormReturn<Record<string, unknown>>;\n resolvedFields: ResourceFormFieldDef[];\n onSubmit: (e?: { preventDefault?: () => void }) => Promise<void>;\n /** Raw save handler — use with form.handleSubmit(handleSave, onInvalid). */\n handleSave: (data: Record<string, unknown>) => Promise<void>;\n isSaving: boolean;\n isLoading: boolean;\n /**\n * The form has changes that have not been saved. False again once a save\n * succeeds (or, in optimistic / undoable modes, is handed off).\n */\n isDirty: boolean;\n /**\n * For in-app navigation: true when it is fine to leave (nothing unsaved,\n * `warnWhenUnsaved` off, or the user confirmed). Asks with\n * `window.confirm` otherwise.\n */\n confirmLeave: () => boolean;\n /**\n * Set when a save met someone else's change (a versioned resource's\n * `conflict`): their row beside what this form tried to save. Show it with\n * ConflictSheet; null otherwise.\n */\n conflict: WriteConflict | null;\n /** Save this form's values over theirs, at the version the conflict reported. */\n keepMine: () => Promise<void>;\n /** Drop this form's changes and show their row. */\n takeTheirs: () => void;\n /** Close the conflict without choosing: the form keeps its unsaved values. */\n dismissConflict: () => void;\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n// ---------------------------------------------------------------------------\n\n/** Infer a field type from a value */\nfunction inferFieldType(value: unknown): FieldType {\n if (typeof value === \"boolean\") return \"switch\";\n if (typeof value === \"number\") return \"number\";\n if (typeof value === \"string\") {\n if (/^\\d{4}-\\d{2}-\\d{2}/.test(value)) return \"date\";\n if (value.includes(\"@\") && value.includes(\".\")) return \"email\";\n if (/^https?:\\/\\//.test(value)) return \"url\";\n if (value.length > 100) return \"textarea\";\n }\n return \"text\";\n}\n\n/** Try to infer a select field from unique values across the full dataset */\nfunction inferSelectFromData(\n key: string,\n allData: Record<string, unknown>[] | undefined,\n): { type: \"select\"; options: { value: string; label: string }[] } | null {\n if (!allData || allData.length === 0) return null;\n const uniqueValues = new Set<string>();\n for (const row of allData) {\n const v = row[key];\n if (typeof v === \"string\" && v.length > 0) uniqueValues.add(v);\n }\n if (uniqueValues.size > 0 && uniqueValues.size <= 10) {\n return {\n type: \"select\" as const,\n options: Array.from(uniqueValues)\n .sort()\n .map((v) => ({ value: v, label: v })),\n };\n }\n return null;\n}\n\n/** Generate a sensible placeholder for an auto-inferred field */\nfunction defaultPlaceholder(key: string, type: FieldType): string {\n switch (type) {\n case \"email\": return \"name@example.com\";\n case \"url\": return \"https://...\";\n case \"number\": return \"0\";\n case \"date\": return \"YYYY-MM-DD\";\n case \"textarea\": return `Enter ${titleCase(key).toLowerCase()}...`;\n default: return `Enter ${titleCase(key).toLowerCase()}`;\n }\n}\n\n/** Resolve fields from data keys when none provided */\nfunction resolveFields(\n fields: ResourceFormFieldDef[] | undefined,\n data: Record<string, unknown> | undefined,\n allData?: Record<string, unknown>[],\n autoPlaceholder = true,\n infer = true,\n): ResourceFormFieldDef[] {\n const placeholderFor = (key: string, type: FieldType): string | undefined =>\n autoPlaceholder ? defaultPlaceholder(key, type) : undefined;\n if ((fields && fields.length > 0) || (fields && !infer)) {\n return fields.map((f) => {\n const inferred = f.type ?? (data ? inferFieldType(data[f.key]) : \"text\");\n return {\n ...f,\n label: f.label ?? titleCase(f.key),\n type: inferred,\n placeholder: f.placeholder ?? placeholderFor(f.key, inferred),\n required: f.required ?? (inferred !== \"switch\" && inferred !== \"checkbox\" && inferred !== \"hidden\"),\n };\n });\n }\n\n if (!data || !infer) return [];\n\n return Object.keys(data)\n .filter((key) => key !== \"id\" && key !== \"created_at\" && key !== \"updated_at\")\n .map((key) => {\n // Check for select-like field first (string with few unique values)\n if (typeof data[key] === \"string\") {\n const selectInfo = inferSelectFromData(key, allData);\n if (selectInfo) {\n return {\n key,\n label: titleCase(key),\n type: selectInfo.type,\n options: selectInfo.options,\n placeholder: autoPlaceholder\n ? `Select ${titleCase(key).toLowerCase()}...`\n : undefined,\n required: true,\n };\n }\n }\n\n const inferred = inferFieldType(data[key]);\n return {\n key,\n label: titleCase(key),\n type: inferred,\n placeholder: placeholderFor(key, inferred),\n required: inferred !== \"switch\" && inferred !== \"checkbox\" && inferred !== \"hidden\",\n };\n });\n}\n\n/** Build a zod schema from resolved fields */\nfunction buildSchema(fields: ResourceFormFieldDef[], action: \"create\" | \"edit\" = \"create\") {\n const shape: Record<string, z.ZodTypeAny> = {};\n\n for (const field of fields) {\n const fieldType = field.type ?? \"text\";\n\n if (field.hidden || fieldType === \"hidden\") continue;\n // An edit never sends a field read-only on edit, so it isn't checked either: a row loaded\n // without it would otherwise fail \"required\" on a field the person can't fill.\n if (action === \"edit\" && field.readOnlyOnEdit) continue;\n\n // File/image fields store File objects — z.any() is intentional here because\n // the File API shape varies by platform (browser File, React Native asset, etc.)\n // and form libraries may wrap files differently.\n if (fieldType === \"file\" || fieldType === \"image\") {\n shape[field.key] = field.required !== false ? z.unknown().refine((v) => v != null, { message: `${field.label ?? titleCase(field.key)} is required` }) : z.unknown().optional();\n continue;\n }\n\n switch (fieldType) {\n case \"number\": {\n let schema = z.coerce.number({ message: \"Must be a number\" });\n if (field.min != null) schema = schema.min(field.min);\n if (field.max != null) schema = schema.max(field.max);\n // An optional field may start at null (a screen's `filter` of null): accept it as is,\n // before coercion would turn it into 0.\n shape[field.key] = field.required !== false\n ? schema\n : z.null().or(schema).optional();\n break;\n }\n case \"relation\": {\n // A linked row's key, as the row holds it: text (a uuid) or a number. Cleared, it is null.\n const message = `${field.label ?? titleCase(field.key)} is required`;\n shape[field.key] = field.required !== false\n ? z.unknown().refine((v) => (typeof v === \"string\" && v !== \"\") || (typeof v === \"number\" && Number.isFinite(v)), { message })\n : z.union([z.string(), z.number()]).nullable().optional();\n break;\n }\n case \"array\": {\n if (field.arrayFields) {\n const itemShape: Record<string, z.ZodTypeAny> = {};\n for (const sub of field.arrayFields) {\n const subType = sub.type ?? \"text\";\n if (subType === \"number\") {\n let s = z.coerce.number({ message: \"Must be a number\" });\n if (sub.min != null) s = s.min(sub.min);\n if (sub.max != null) s = s.max(sub.max);\n itemShape[sub.key] = sub.required !== false ? s : s.optional();\n } else if (subType === \"switch\" || subType === \"checkbox\") {\n itemShape[sub.key] = z.boolean().optional();\n } else {\n let s = z.string();\n if (sub.required !== false) {\n s = s.min(1, `${sub.label ?? titleCase(sub.key)} is required`);\n }\n if (subType === \"email\") s = s.email(\"Invalid email address\");\n if (subType === \"url\") s = s.url(\"Invalid URL\");\n if (sub.maxLength != null) {\n s = s.max(\n sub.maxLength,\n `${sub.label ?? titleCase(sub.key)} must be ${sub.maxLength} characters or fewer`,\n );\n }\n itemShape[sub.key] = sub.required === false ? s.optional().or(z.literal(\"\")) : s;\n }\n }\n let arraySchema: z.ZodTypeAny = z.array(z.object(itemShape));\n if (field.arrayMin != null) arraySchema = (arraySchema as z.ZodArray<z.ZodTypeAny>).min(field.arrayMin, `Minimum ${field.arrayMin} items required`);\n if (field.arrayMax != null) arraySchema = (arraySchema as z.ZodArray<z.ZodTypeAny>).max(field.arrayMax, `Maximum ${field.arrayMax} items allowed`);\n shape[field.key] = arraySchema;\n }\n break;\n }\n case \"switch\":\n case \"checkbox\": {\n shape[field.key] = z.boolean().optional();\n break;\n }\n default: {\n // text, email, url, textarea, date, select\n let schema = z.string();\n if (field.required !== false) {\n schema = schema.min(1, `${field.label ?? titleCase(field.key)} is required`);\n }\n if (fieldType === \"email\") {\n schema = schema.email(\"Invalid email address\");\n }\n if (fieldType === \"url\") {\n schema = schema.url(\"Invalid URL\");\n }\n if (field.maxLength != null) {\n schema = schema.max(\n field.maxLength,\n `${field.label ?? titleCase(field.key)} must be ${field.maxLength} characters or fewer`,\n );\n }\n // An optional field may start at null (a screen's `filter` of null); \"\" is an empty input.\n shape[field.key] = field.required === false\n ? schema.optional().nullable().or(z.literal(\"\"))\n : schema;\n break;\n }\n }\n }\n\n return z.object(shape).passthrough();\n}\n\n/** Build default values for a single array item from its sub-field definitions */\nexport function buildArrayItemDefaults(\n arrayFields: ResourceFormFieldDef[],\n): Record<string, unknown> {\n const defaults: Record<string, unknown> = {};\n for (const sub of arrayFields) {\n const subType = sub.type ?? \"text\";\n if (subType === \"number\") defaults[sub.key] = undefined;\n else if (subType === \"switch\" || subType === \"checkbox\") defaults[sub.key] = false;\n else defaults[sub.key] = sub.defaultValue ?? \"\";\n }\n return defaults;\n}\n\n// Input types whose empty value (\"\") can be a real value of the column.\nconst TEXT_TYPES: ReadonlySet<string> = new Set([\"text\", \"textarea\", \"email\", \"tel\", \"url\", \"hidden\"]);\n\n/**\n * What a save sends for an input left empty: `\"\"`, or `undefined` (a cleared number input). Only a field whose column the form knows\n * about (`nullable` set, as ResourceView sets it from a generated contract) is changed:\n * a create leaves it out, so the column's default (or null) applies, and an edit the person\n * made clears it to null. Everything else goes as before, `\"\"` included: a field without\n * `nullable`, an edit of a field nobody touched (`changed` doesn't list it), a value the\n * screen started the field at (its `defaultValue`), and a text column that can't be null\n * (on a create, only when it has no default to fall back on).\n */\nexport function blankValues(\n values: Record<string, unknown>,\n fields: readonly ResourceFormFieldDef[],\n action: \"create\" | \"edit\",\n changed?: ReadonlySet<string>,\n): Record<string, unknown> {\n const byKey = new Map(fields.map((f) => [f.key, f]));\n const out: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(values)) {\n const field = byKey.get(key);\n const asBefore =\n (value !== \"\" && value !== undefined) ||\n field?.nullable === undefined ||\n field.defaultValue === \"\" ||\n (action === \"edit\" && changed !== undefined && !changed.has(key)) ||\n (TEXT_TYPES.has(field.type ?? \"text\") && !field.nullable && !(action === \"create\" && field.hasDefault));\n if (asBefore) out[key] = value;\n else if (action === \"edit\") out[key] = null;\n }\n return out;\n}\n\n/** Build default values from fields and existing data */\nfunction buildDefaults(\n fields: ResourceFormFieldDef[],\n data: Record<string, unknown> | undefined,\n action: \"create\" | \"edit\",\n prefillFromUrl: boolean,\n): Record<string, unknown> {\n const defaults: Record<string, unknown> = {};\n for (const field of fields) {\n // A create's blank template (every column as \"\") never hides a field's own default.\n const blankOnCreate = action === \"create\" && data?.[field.key] === \"\" && field.defaultValue !== undefined;\n if (data && field.key in data && !blankOnCreate) {\n defaults[field.key] = data[field.key];\n } else if (field.defaultValue !== undefined) {\n defaults[field.key] = field.defaultValue;\n } else {\n const fieldType = field.type ?? \"text\";\n switch (fieldType) {\n case \"array\":\n defaults[field.key] = field.arrayMin\n ? Array.from({ length: field.arrayMin }, () =>\n buildArrayItemDefaults(field.arrayFields ?? []),\n )\n : [];\n break;\n case \"number\":\n defaults[field.key] = undefined;\n break;\n case \"switch\":\n case \"checkbox\":\n defaults[field.key] = false;\n break;\n default:\n defaults[field.key] = \"\";\n break;\n }\n }\n }\n\n // URL pre-fill for create mode\n if (typeof window !== \"undefined\" && typeof window.location !== \"undefined\" && typeof window.location.search === \"string\" && action === \"create\" && prefillFromUrl !== false) {\n const params = new URLSearchParams(window.location.search);\n for (const field of fields) {\n // A hidden field is the screen's (its filter or defaults), never the URL's; so is one\n // that says so (a value the screen's filter fixes).\n if (field.hidden || field.type === \"hidden\" || field.fromUrl === false) continue;\n const val = params.get(field.key);\n if (val != null) {\n defaults[field.key] = field.type === \"number\" ? Number(val) : val;\n }\n }\n }\n\n return defaults;\n}\n\n// ---------------------------------------------------------------------------\n// Hook\n// ---------------------------------------------------------------------------\n\nexport function useResourceForm(options: UseResourceFormOptions): UseResourceFormReturn {\n const {\n resource,\n action,\n id,\n initialData,\n fields: fieldsProp,\n inferFields = true,\n listData,\n onSuccess,\n onError,\n prefillFromUrl = true,\n autoPlaceholder = true,\n validationMode,\n autosave,\n invalidates,\n warnWhenUnsaved = false,\n mutationMode = \"pessimistic\",\n undoDelayMs,\n onUndoable,\n visible = true,\n updates = \"loaded\",\n } = options;\n\n const autosaveEnabled = !!autosave;\n const debounceMs = typeof autosave === \"object\" ? autosave.debounceMs ?? 1000 : 1000;\n\n const provider = useDataProvider();\n const storage = useStorage();\n const queryClient = useQueryClient();\n\n // Fetch record for edit mode when no initialData\n const needsFetch = action === \"edit\" && !initialData && !!id;\n const fetchResult = useOne(\n resource,\n needsFetch ? id : undefined,\n { enabled: needsFetch },\n );\n\n const fetchedData = fetchResult.data ?? undefined;\n const effectiveData = initialData ?? fetchedData;\n const isLoading = needsFetch && fetchResult.isLoading;\n\n // In edit mode the form starts from the provider's form shape of the row\n // (`DataProvider.toFormValues`), for a resource whose form differs from\n // its table. The record id still comes from the row itself.\n const formSource = useMemo(\n () =>\n action === \"edit\" && effectiveData && provider.toFormValues\n ? provider.toFormValues(resource, effectiveData)\n : effectiveData,\n [action, effectiveData, provider, resource],\n );\n\n // Resolve fields\n const resolvedFields = useMemo(\n () => resolveFields(fieldsProp, formSource, listData, autoPlaceholder, inferFields),\n [fieldsProp, formSource, listData, autoPlaceholder, inferFields],\n );\n\n // Build schema\n const schema = useMemo(\n () => buildSchema(resolvedFields, action),\n [resolvedFields, action],\n );\n\n // Build defaults (with optional draft restoration)\n const defaultValues = useMemo(() => {\n const defaults = buildDefaults(resolvedFields, formSource, action, prefillFromUrl);\n if (autosaveEnabled && action === \"create\") {\n const key = `genesis-draft:${resource}:new`;\n const saved = storage.getItem(key);\n if (saved) {\n try {\n const draft = JSON.parse(saved);\n if (draft && typeof draft === \"object\" && !Array.isArray(draft)) {\n // Only restore keys that exist in the field definitions\n const validKeys = new Set(resolvedFields.map((f) => f.key));\n for (const k of Object.keys(draft)) {\n if (validKeys.has(k)) {\n defaults[k] = draft[k];\n }\n }\n } else {\n console.warn(`[useResourceForm] Draft for \"${resource}\" has unexpected shape, removing`);\n storage.removeItem(key);\n }\n } catch {\n console.warn(`[useResourceForm] Corrupt draft for \"${resource}\", removing`);\n storage.removeItem(key);\n }\n }\n }\n return defaults;\n }, [resolvedFields, formSource, action, prefillFromUrl, autosaveEnabled, resource, storage]);\n\n // Form\n // Cast the resolver because zod v4's passthrough() produces `unknown` for input,\n // but react-hook-form expects FieldValues (Record<string, any>).\n const resolver = useMemo(\n () => zodResolver(schema) as unknown as Resolver<Record<string, unknown>>,\n [schema],\n );\n\n const form = useForm<Record<string, unknown>>({\n resolver,\n defaultValues,\n values: action === \"edit\" ? defaultValues : undefined,\n mode: validationMode ?? \"onBlur\",\n reValidateMode: \"onChange\",\n shouldUnregister: true,\n });\n\n // A create form that stays mounted follows its defaults: the screen's hidden values (a new\n // filter or defaults) always, the rest only while the person hasn't typed anything.\n const firstDefaults = useRef(defaultValues);\n useEffect(() => {\n // By value: a screen may hand a new but equal object every render.\n if (action !== \"create\" || sameValue(firstDefaults.current, defaultValues)) return;\n firstDefaults.current = defaultValues;\n if (!form.formState.isDirty) {\n form.reset(defaultValues);\n return;\n }\n for (const field of resolvedFields) {\n if (field.hidden || field.type === \"hidden\") form.setValue(field.key, defaultValues[field.key]);\n }\n }, [action, defaultValues, form, resolvedFields]);\n\n // Autosave effect — persist form values to storage for create mode\n useEffect(() => {\n if (!autosaveEnabled || action !== \"create\") return;\n const key = `genesis-draft:${resource}:new`;\n let timer: ReturnType<typeof setTimeout>;\n\n const subscription = form.watch((values) => {\n clearTimeout(timer);\n timer = setTimeout(() => {\n try {\n storage.setItem(key, JSON.stringify(values));\n } catch (err) {\n console.warn(`[useResourceForm] Autosave failed for \"${resource}\":`, err instanceof Error ? err.message : String(err));\n }\n }, debounceMs);\n });\n\n return () => {\n clearTimeout(timer);\n subscription.unsubscribe();\n };\n }, [autosaveEnabled, resource, action, form, debounceMs, storage]);\n\n // Unsaved changes: RHF's isDirty, cleared by a successful save until the\n // next edit (a create form keeps its values after saving, so RHF alone\n // would still call it dirty).\n const rhfDirty = form.formState.isDirty;\n const [savedClean, setSavedClean] = useState(false);\n const savedCleanRef = useRef(false);\n useEffect(() => {\n const subscription = form.watch((_values, info) => {\n // `watch` also reports resets (no field name); only an edit dirties.\n if (!info.name) return;\n savedCleanRef.current = false;\n setSavedClean(false);\n });\n return () => subscription.unsubscribe();\n }, [form]);\n const isDirty = rhfDirty && !savedClean;\n const warn = !!warnWhenUnsaved;\n const { confirmLeave: guardConfirm } = useUnsavedChangesGuard({\n when: warn && isDirty,\n message: typeof warnWhenUnsaved === \"object\" ? warnWhenUnsaved.message : undefined,\n });\n const confirmLeave = useCallback(\n // The ref, not state: a router blocker may ask in the same tick as the\n // save's onSuccess navigates, before a re-render.\n () => (!warn || savedCleanRef.current ? true : guardConfirm()),\n [warn, guardConfirm],\n );\n const markSaved = useCallback(() => {\n savedCleanRef.current = true;\n setSavedClean(true);\n }, []);\n\n // A save that fails after it was handed off only comes back to the form\n // while the user can still see it.\n const mountedRef = useRef(true);\n useEffect(() => {\n mountedRef.current = true;\n return () => {\n mountedRef.current = false;\n };\n }, []);\n const visibleRef = useRef(visible);\n visibleRef.current = visible;\n\n /** A failed save, on the form: per-field messages and a root summary. */\n const showError = useCallback(\n (error: Error) => {\n const fieldErrors = isDataWriteError(error) ? error.fields : undefined;\n const known = new Set(resolvedFields.map((f) => f.key));\n let first: string | undefined;\n if (fieldErrors) {\n for (const [field, message] of Object.entries(fieldErrors)) {\n if (!known.has(field)) continue;\n form.setError(field, { type: \"server\", message });\n first ??= field;\n }\n }\n form.setError(\"root\", { type: \"server\", message: error.message });\n if (first) {\n try {\n form.setFocus(first);\n } catch {\n // Not rendered (hidden or custom renderForm): the summary still says it.\n }\n }\n },\n [form, resolvedFields],\n );\n\n const reportError = useCallback(\n (error: Error, handedOff?: Record<string, unknown>) => {\n // A save handed off optimistically and then refused is unsaved again,\n // if the form still shows what it saved; a closed, hidden or reset\n // form is left alone.\n const onForm =\n !handedOff ||\n (mountedRef.current && visibleRef.current && sameValue(form.getValues(), handedOff));\n if (onForm) {\n savedCleanRef.current = false;\n setSavedClean(false);\n showError(error);\n }\n if (onError) {\n onError(error);\n } else {\n console.error(`[useResourceForm] ${action} failed for \"${resource}\":`, error);\n }\n },\n [form, showError, onError, action, resource],\n );\n\n // A save that met someone else's change: the values it tried to save, the fields the person\n // changed, and their row as it is now.\n const [conflictState, setConflictState] = useState<{\n conflict: WriteConflict;\n submitted: Record<string, unknown>;\n changed: readonly string[];\n row: Record<string, unknown>;\n } | null>(null);\n // After \"take theirs\": their row, as the record the next save is checked against, until the\n // form's own record changes.\n const [rebased, setRebased] = useState<BaseRecord | null>(null);\n // Counts conflicts found, so \"keep mine\" can tell a new conflict from a plain failure.\n const conflictsFound = useRef(0);\n // Cleared when the form's record really changes, not when a screen hands an equal object again.\n const rebasedFor = useRef(effectiveData);\n useEffect(() => {\n if (sameValue(rebasedFor.current, effectiveData)) return;\n rebasedFor.current = effectiveData;\n setRebased(null);\n }, [effectiveData]);\n // What this person typed that a conflict hasn't settled: kept on the form across the refetch a\n // rolled-back optimistic save starts (which resets the form to their row), until they save or\n // take theirs, so neither a second conflict nor closing the sheet loses it.\n const [unsettled, setUnsettled] = useState<{ changed: readonly string[]; values: Record<string, unknown> } | null>(null);\n useEffect(() => {\n if (!unsettled) return;\n for (const key of unsettled.changed) {\n if (!sameValue(form.getValues(key), unsettled.values[key])) form.setValue(key, unsettled.values[key], { shouldDirty: true });\n }\n }, [unsettled, defaultValues, form]);\n\n // Submit handler. Resolves true when the save went through (or had nothing to send).\n const save = useCallback(\n async (\n submitted: Record<string, unknown>,\n expectedVersion?: string,\n /** \"Keep mine\": the fields this person changed, as the conflict recorded them. */\n keep?: readonly string[],\n ): Promise<boolean> => {\n // \"Keep mine\" leaves the conflict up until this save settles.\n if (expectedVersion === undefined) setConflictState(null);\n // What the form shows as this save goes out (raw input values, before\n // any resolver coercion), to tell later whether it still does.\n const shown = structuredCloneSafe(form.getValues());\n // A field the opened record didn't carry goes only when the person changed it (compared by\n // value: RHF's dirtyFields updates only when read during render).\n const opened = formSource as Record<string, unknown> | undefined;\n // A field read-only when editing is never written by an edit: sending even its unchanged\n // value would fail on a column the person may not update.\n const lockedOnEdit = new Set(action === \"edit\" ? resolvedFields.filter((f) => f.readOnlyOnEdit).map((f) => f.key) : []);\n const writable = lockedOnEdit.size\n ? Object.fromEntries(Object.entries(submitted).filter(([k]) => !lockedOnEdit.has(k)))\n : submitted;\n const changed =\n action === \"edit\" && updates === \"loaded\" && opened\n ? Object.fromEntries(\n Object.entries(writable).filter(\n // Changed: what an input shows differs from where it started, or, for a value saved\n // without an input (a direct handleSave), the value itself does.\n ([k, v]) =>\n k in opened ||\n !sameValue(k in (shown as object) ? (shown as Record<string, unknown>)[k] : v, defaultValues[k]),\n ),\n )\n : writable;\n // An empty input the person left or made empty is no value (see `blankValues`).\n const touched = new Set(\n keep ??\n Object.entries(changed)\n .filter(([k, v]) => !sameValue(k in (shown as object) ? (shown as Record<string, unknown>)[k] : v, defaultValues[k]))\n .map(([k]) => k),\n );\n const formData = blankValues(changed, resolvedFields, action, touched);\n // A conflict offers only what this person changed, compared in the form's shape.\n const conflictOf = (error: unknown) => {\n const found = writeConflict(error, formData, {\n changed: touched,\n ...(provider.toFormValues && formSource !== effectiveData\n ? { view: (row: Record<string, unknown>) => provider.toFormValues!(resource, row as BaseRecord) as Record<string, unknown> }\n : {}),\n });\n if (found && isDataWriteError(error) && error.current) {\n conflictsFound.current += 1;\n setUnsettled({ changed: [...touched], values: { ...submitted } });\n setConflictState({ conflict: found, submitted, changed: [...touched], row: error.current as Record<string, unknown> });\n }\n return found;\n };\n // An edit with nothing left to write (only read-only fields) has nothing to send.\n if (action === \"edit\" && Object.keys(formData).length === 0) {\n setConflictState(null);\n markSaved();\n onSuccess?.({ ...(effectiveData ?? {}), ...(id != null && id !== \"\" ? { id } : {}) });\n return true;\n }\n try {\n let recordId: string | number | undefined;\n if (action === \"edit\") {\n recordId = id ?? String((effectiveData as Record<string, unknown>)?.id ?? \"\");\n if (!recordId) {\n throw new Error(\"Cannot update record: no ID available. Provide an id prop or ensure the record has an id field.\");\n }\n }\n const before = recordId != null ? cachedRecord(queryClient, resource, recordId) : undefined;\n const outcome = await executeWrite<BaseRecord>({\n queryClient,\n provider,\n resource,\n kind: action === \"create\" ? \"create\" : \"update\",\n id: recordId,\n // The cache holds rows; patch it only when the form's values are\n // row-shaped (no provider.toFormValues reshaping this record).\n data: formSource === effectiveData ? formData : undefined,\n // The record the form shows: its version is the one this edit is checked against, even\n // when the cache has since refetched a newer one.\n ...(action === \"edit\" && (rebased ?? effectiveData) ? { base: (rebased ?? effectiveData) as BaseRecord } : {}),\n ...(expectedVersion !== undefined ? { expectedVersion } : {}),\n mode: mutationMode,\n undoDelayMs,\n onUndoable,\n send: async (ctx) => {\n const keepalive = ctx.keepalive ? { keepalive: true } : {};\n const res =\n action === \"create\"\n ? await provider.create(resource, { data: formData, ...keepalive })\n : await provider.update(resource, {\n id: recordId!,\n data: ctx.data ?? formData,\n ...keepalive,\n ...(ctx.expectedVersion !== undefined ? { expectedVersion: ctx.expectedVersion } : {}),\n });\n return { record: res.data, audit: res.audit };\n },\n committed: async (result) => {\n // The next save from this form is checked against the version this one left, not the\n // record it opened with (a form that stays open after a save, such as a native sheet).\n if (action === \"edit\" && mountedRef.current && result && typeof result === \"object\") {\n const saved = result as BaseRecord;\n setRebased((prev) => ({ ...((prev ?? effectiveData ?? {}) as BaseRecord), ...saved }));\n }\n // Clear draft on successful save\n if (autosaveEnabled && action === \"create\") {\n try {\n storage.removeItem(`genesis-draft:${resource}:new`);\n } catch (err) {\n console.warn(`[useResourceForm] Draft cleanup failed for \"${resource}\":`, err instanceof Error ? err.message : String(err));\n }\n }\n // Invalidate queries to refresh data: the resource's own, then any\n // related keys the provider or the caller named.\n await invalidateResource(queryClient, resource);\n const related = relatedKeys(\n provider,\n {\n resource,\n kind: action === \"create\" ? \"create\" : \"update\",\n id: (recordId ?? result.id) as string | number,\n record: result,\n },\n invalidates,\n );\n await Promise.all(related.map((queryKey) => queryClient.invalidateQueries({ queryKey: [...queryKey] })));\n },\n failedLater: (error) => {\n if (mountedRef.current) conflictOf(error);\n reportError(error, shown);\n },\n });\n setConflictState(null);\n setUnsettled(null);\n markSaved();\n if (outcome.status === \"committed\") {\n onSuccess?.(outcome.record);\n } else {\n onSuccess?.(\n action === \"edit\"\n ? { ...(before ?? effectiveData ?? {}), ...formData, id: recordId }\n : { ...formData },\n );\n }\n return true;\n } catch (err) {\n conflictOf(err);\n reportError(err instanceof Error ? err : new Error(String(err)));\n return false;\n }\n },\n [form, action, provider, resource, id, effectiveData, rebased, formSource, queryClient, onSuccess, autosaveEnabled, storage, invalidates, mutationMode, undoDelayMs, onUndoable, reportError, markSaved, updates, defaultValues, resolvedFields],\n );\n\n const handleSubmit = useCallback(async (submitted: Record<string, unknown>) => {\n await save(submitted);\n }, [save]);\n\n const keepMine = useCallback(async () => {\n if (!conflictState) return;\n const { conflict, submitted, changed } = conflictState;\n // Only what this person changed is theirs to keep: every other field the form sends takes\n // their value, so \"keep mine\" never puts back a stale copy of a field nobody touched here.\n const values = { ...submitted };\n for (const key of Object.keys(values)) {\n if (!changed.includes(key) && key in conflict.theirs) values[key] = conflict.theirs[key];\n }\n form.clearErrors(\"root\");\n const found = conflictsFound.current;\n const ok = await save(values, conflict.currentVersion ?? undefined, changed);\n // Failed without a new conflict (which replaces this one): say why, on the sheet.\n if (!ok && conflictsFound.current === found) throw new Error(form.getFieldState(\"root\").error?.message ?? \"Not saved.\");\n }, [conflictState, form, save]);\n\n const dismissConflict = useCallback(() => setConflictState(null), []);\n\n const takeTheirs = useCallback(() => {\n if (!conflictState) return;\n const { row: theirs } = conflictState;\n setConflictState(null);\n setUnsettled(null);\n // The next save is checked against their row's version, not the one the form opened at.\n setRebased({ ...((effectiveData ?? {}) as BaseRecord), ...(theirs as BaseRecord) });\n form.clearErrors();\n const recordId = id ?? (effectiveData as Record<string, unknown> | undefined)?.id;\n if (recordId != null && recordId !== \"\") {\n // Every cached copy shows their row now; the refetch confirms it.\n patchCachedRow(queryClient, resource, { ...theirs, id: recordId as string | number });\n void invalidateResource(queryClient, resource);\n }\n const shown = action === \"edit\" && provider.toFormValues ? provider.toFormValues(resource, theirs as BaseRecord) : theirs;\n // Every field the form shows, from their row; anything else the form holds stays.\n const next = { ...form.getValues() };\n for (const key of new Set([...resolvedFields.map((f) => f.key), ...Object.keys(next)])) {\n if (key in shown) next[key] = (shown as Record<string, unknown>)[key];\n }\n form.reset(next);\n }, [conflictState, form, id, effectiveData, queryClient, resource, action, provider, resolvedFields]);\n\n const onSubmit = useCallback(\n (e?: { preventDefault?: () => void }) => form.handleSubmit(handleSubmit)(e as React.BaseSyntheticEvent),\n [form, handleSubmit],\n );\n\n const isSaving = form.formState.isSubmitting;\n\n return {\n form,\n resolvedFields,\n onSubmit,\n handleSave: handleSubmit,\n isSaving,\n isLoading,\n isDirty,\n confirmLeave,\n conflict: conflictState?.conflict ?? null,\n keepMine,\n takeTheirs,\n dismissConflict,\n };\n}\n"]}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { useStorage } from './chunk-
|
|
1
|
+
import { useStorage } from './chunk-R3YXYVWF.js';
|
|
2
2
|
import { useCallback, useSyncExternalStore, useMemo, useState, useRef } from 'react';
|
|
3
3
|
|
|
4
4
|
var listeners = /* @__PURE__ */ new Map();
|
|
@@ -81,5 +81,5 @@ function usePersistedUiState(key, initial, options = {}) {
|
|
|
81
81
|
}
|
|
82
82
|
|
|
83
83
|
export { usePersistedUiState };
|
|
84
|
-
//# sourceMappingURL=chunk-
|
|
85
|
-
//# sourceMappingURL=chunk-
|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AAW,OAAO;AAAA,GACnC;AAEA,EAAA,OAAO,CAAC,OAAO,GAAG,CAAA;AACpB","file":"chunk-IYGVJFCV.js","sourcesContent":["\"use client\";\n/**\n * usePersistedUiState: a piece of UI state that outlives the page (a collapsed sidebar, a table's\n * column widths, a dock's size), kept in the app's storage adapter (`useStorage()`: localStorage\n * on the web, MMKV or AsyncStorage on a phone).\n *\n * - SSR-safe: the server renders `initial`, and the client hydrates against it before reading\n * storage (useSyncExternalStore), so there's no hydration mismatch. A client-only render reads\n * storage directly, with no flash.\n * - In step: every hook on the same key, in this tab or another, sees a write.\n * - Never writes `initial`: a default stays a default, so changing it later reaches everyone who\n * hasn't chosen. `set(undefined)` clears the stored value back to the default.\n * - Forgiving: a stored value `parse` refuses falls back to `initial`, and a write storage won't\n * keep (quota, private mode, a no-op adapter) still applies for this hook's lifetime. Only for\n * this hook: with nothing stored, another hook on the key can't see it, so the two can disagree\n * until this hook successfully stores or clears the key.\n * - Optional: a `null` key is plain state that isn't stored, for a component whose persistence\n * the caller turns on with a key prop.\n *\n * @stability Beta\n */\nimport { useCallback, useMemo, useRef, useState, useSyncExternalStore } from \"react\";\nimport { useStorage } from \"../provider/context\";\n\nexport interface PersistedUiStateOptions<T> {\n /**\n * Turns the stored string into a value; return `undefined` for one you don't accept, and the\n * hook falls back to `initial`. Default: `JSON.parse`, any value.\n */\n parse?: (raw: string) => T | undefined;\n /** Turns a value into the string stored. Default: `JSON.stringify`. */\n serialize?: (value: T) => string;\n}\n\n/** Same-tab subscribers by key: one hook's write reaches every other hook on that key. */\nconst listeners = new Map<string, Set<() => void>>();\n\nfunction notify(key: string): void {\n for (const listener of listeners.get(key) ?? []) listener();\n}\n\nconst jsonParse = <T,>(raw: string): T | undefined => {\n try {\n return JSON.parse(raw) as T;\n } catch {\n return undefined;\n }\n};\n\n/** The server has nothing stored: it renders, and the client hydrates against, `initial`. */\nconst serverSnapshot = (): null => null;\n\nexport function usePersistedUiState<T>(\n key: string | null,\n initial: T,\n options: PersistedUiStateOptions<T> = {},\n): [T, (next: T | undefined | ((current: T) => T | undefined)) => void] {\n const storage = useStorage();\n const { parse = jsonParse as (raw: string) => T | undefined, serialize = JSON.stringify as (value: T) => string } = options;\n\n const subscribe = useCallback(\n (onChange: () => void) => {\n if (key === null) return () => undefined;\n let set = listeners.get(key);\n if (!set) listeners.set(key, (set = new Set()));\n set.add(onChange);\n const onStorage = (event: StorageEvent) => {\n if (event.key === null || event.key === key) onChange();\n };\n if (typeof window !== \"undefined\") window.addEventListener(\"storage\", onStorage);\n return () => {\n set.delete(onChange);\n if (set.size === 0) listeners.delete(key);\n if (typeof window !== \"undefined\") window.removeEventListener(\"storage\", onStorage);\n };\n },\n [key],\n );\n const getSnapshot = useCallback(() => {\n if (key === null) return null;\n try {\n return storage.getItem(key);\n } catch {\n return null;\n }\n }, [storage, key]);\n const raw = useSyncExternalStore(subscribe, getSnapshot, serverSnapshot);\n\n // The parsed value changes only when the stored string does, so a consumer's effects on it\n // don't run on every render.\n const stored = useMemo(() => (raw === null ? undefined : parse(raw)), [raw, parse]);\n\n // A write storage didn't keep, held for this hook's lifetime and only for the key it was made\n // under: a new key reads its own stored value. `value: undefined` is \"cleared\".\n const [unsavedState, setUnsavedState] = useState<{ key: string | null; value: T | undefined } | undefined>(undefined);\n const unsaved = unsavedState && unsavedState.key === key ? unsavedState : undefined;\n const value = unsaved === undefined ? (stored === undefined ? initial : stored) : unsaved.value === undefined ? initial : unsaved.value;\n // The latest value, for a function update: two updates in one tick (before a re-render) each\n // build on the one before, as useState's do.\n const latest = useRef(value);\n latest.current = value;\n\n const set = useCallback(\n (next: T | undefined | ((current: T) => T | undefined)) => {\n const resolved = typeof next === \"function\" ? (next as (current: T) => T | undefined)(latest.current) : next;\n latest.current = resolved === undefined ? initial : resolved;\n let kept = false;\n if (key === null) {\n setUnsavedState({ key, value: resolved });\n return;\n }\n try {\n if (resolved === undefined) {\n storage.removeItem(key);\n kept = storage.getItem(key) === null;\n } else {\n const text = serialize(resolved);\n storage.setItem(key, text);\n kept = storage.getItem(key) === text;\n }\n } catch {\n kept = false;\n }\n setUnsavedState(kept ? undefined : { key, value: resolved });\n notify(key);\n },\n // `initial` only matters when a write clears the value; read through a ref, it would be\n // stale after a re-render with a new default, so it's a dependency like the rest.\n [storage, key, serialize, initial],\n );\n\n return [value, set];\n}\n"]}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { DataReadError } from './chunk-HUNGCTRA.js';
|
|
2
|
+
|
|
3
|
+
// src/provider/aggregate.ts
|
|
4
|
+
function numeric(value) {
|
|
5
|
+
if (typeof value === "number") return Number.isFinite(value) ? value : void 0;
|
|
6
|
+
if (typeof value === "string" && value.trim() !== "") {
|
|
7
|
+
const n = Number(value);
|
|
8
|
+
return Number.isFinite(n) ? n : void 0;
|
|
9
|
+
}
|
|
10
|
+
return void 0;
|
|
11
|
+
}
|
|
12
|
+
function toAggregateValues(rows, metrics) {
|
|
13
|
+
const values = {};
|
|
14
|
+
for (const [name, metric] of Object.entries(metrics)) {
|
|
15
|
+
if (metric.fn === "count") {
|
|
16
|
+
values[name] = rows.length;
|
|
17
|
+
continue;
|
|
18
|
+
}
|
|
19
|
+
const nums = [];
|
|
20
|
+
for (const row of rows) {
|
|
21
|
+
const n = numeric(row[metric.field]);
|
|
22
|
+
if (n !== void 0) nums.push(n);
|
|
23
|
+
}
|
|
24
|
+
if (nums.length === 0) {
|
|
25
|
+
values[name] = null;
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
switch (metric.fn) {
|
|
29
|
+
case "sum":
|
|
30
|
+
values[name] = nums.reduce((a, b) => a + b, 0);
|
|
31
|
+
break;
|
|
32
|
+
case "avg":
|
|
33
|
+
values[name] = nums.reduce((a, b) => a + b, 0) / nums.length;
|
|
34
|
+
break;
|
|
35
|
+
case "min":
|
|
36
|
+
values[name] = Math.min(...nums);
|
|
37
|
+
break;
|
|
38
|
+
case "max":
|
|
39
|
+
values[name] = Math.max(...nums);
|
|
40
|
+
break;
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
return values;
|
|
44
|
+
}
|
|
45
|
+
function aggregateProblems(params) {
|
|
46
|
+
const problems = [];
|
|
47
|
+
const entries = Object.entries(params?.metrics ?? {});
|
|
48
|
+
if (entries.length === 0) problems.push("metrics: at least one");
|
|
49
|
+
for (const [name, metric] of entries) {
|
|
50
|
+
if (!metric || typeof metric !== "object") problems.push(`metrics.${name}: expected { fn }`);
|
|
51
|
+
else if (metric.fn === "count") continue;
|
|
52
|
+
else if (!["sum", "avg", "min", "max"].includes(metric.fn)) problems.push(`metrics.${name}.fn: one of count, sum, avg, min, max`);
|
|
53
|
+
else if (typeof metric.field !== "string" || !metric.field) problems.push(`metrics.${name}.field: the numeric field to ${metric.fn}`);
|
|
54
|
+
}
|
|
55
|
+
return problems;
|
|
56
|
+
}
|
|
57
|
+
async function resolveAggregate(provider, resource, params, options = {}) {
|
|
58
|
+
const problems = aggregateProblems(params);
|
|
59
|
+
if (problems.length) {
|
|
60
|
+
throw new DataReadError("invalid", "These totals couldn't be worked out.", {
|
|
61
|
+
cause: new Error(`[genesis-core] aggregate of "${resource}": ${problems.join("; ")}`)
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
if (typeof provider.aggregate === "function") return provider.aggregate(resource, params);
|
|
65
|
+
const { filters, search } = params;
|
|
66
|
+
const metrics = Object.values(params.metrics);
|
|
67
|
+
if (metrics.every((m) => m.fn === "count")) {
|
|
68
|
+
const page = await provider.getList(resource, {
|
|
69
|
+
filters,
|
|
70
|
+
search,
|
|
71
|
+
pagination: { page: 1, perPage: 1 },
|
|
72
|
+
count: params.count ?? "exact"
|
|
73
|
+
});
|
|
74
|
+
if (page.total >= 0) {
|
|
75
|
+
const values = Object.fromEntries(Object.keys(params.metrics).map((name) => [name, page.total]));
|
|
76
|
+
return page.totalIsEstimate ? { values, isEstimate: true } : { values };
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
const pageSize = Math.max(1, options.pageSize ?? 500);
|
|
80
|
+
const maxRows = Math.max(1, options.maxRows ?? 1e4);
|
|
81
|
+
const rows = [];
|
|
82
|
+
for (let page = 1; ; page++) {
|
|
83
|
+
const result = await provider.getList(resource, {
|
|
84
|
+
filters,
|
|
85
|
+
search,
|
|
86
|
+
pagination: { page, perPage: pageSize },
|
|
87
|
+
count: "none"
|
|
88
|
+
});
|
|
89
|
+
rows.push(...result.data);
|
|
90
|
+
if (rows.length > maxRows) {
|
|
91
|
+
throw new DataReadError("invalid", "These totals couldn't be worked out.", {
|
|
92
|
+
cause: new Error(
|
|
93
|
+
`[genesis-core] aggregate of "${resource}" would read more than ${maxRows} rows; give the provider an aggregate() or narrow the filters.`
|
|
94
|
+
)
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
if (result.data.length < pageSize) break;
|
|
98
|
+
}
|
|
99
|
+
return { values: toAggregateValues(rows, params.metrics) };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export { aggregateProblems, resolveAggregate, toAggregateValues };
|
|
103
|
+
//# sourceMappingURL=chunk-J54XXKQD.js.map
|
|
104
|
+
//# sourceMappingURL=chunk-J54XXKQD.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/provider/aggregate.ts"],"names":[],"mappings":";;;AAgBA,SAAS,QAAQ,KAAA,EAAoC;AACnD,EAAA,IAAI,OAAO,UAAU,QAAA,EAAU,OAAO,OAAO,QAAA,CAAS,KAAK,IAAI,KAAA,GAAQ,MAAA;AACvE,EAAA,IAAI,OAAO,KAAA,KAAU,QAAA,IAAY,KAAA,CAAM,IAAA,OAAW,EAAA,EAAI;AACpD,IAAA,MAAM,CAAA,GAAI,OAAO,KAAK,CAAA;AACtB,IAAA,OAAO,MAAA,CAAO,QAAA,CAAS,CAAC,CAAA,GAAI,CAAA,GAAI,MAAA;AAAA,EAClC;AACA,EAAA,OAAO,MAAA;AACT;AASO,SAAS,iBAAA,CACd,MACA,OAAA,EAC+B;A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A,MAAM,OAAc,EAAC;AACrB,EAAA,KAAA,IAAS,IAAA,GAAO,KAAK,IAAA,EAAA,EAAQ;AAC3B,IAAA,MAAM,MAAA,GAAS,MAAM,QAAA,CAAS,OAAA,CAAuC,QAAA,EAAU;AAAA,MAC7E,OAAA;AAAA,MACA,MAAA;AAAA,MACA,UAAA,EAAY,EAAE,IAAA,EAAM,OAAA,EAAS,QAAA,EAAS;AAAA,MACtC,KAAA,EAAO;AAAA,KACR,CAAA;AACD,IAAA,IAAA,CAAK,IAAA,CAAK,GAAG,MAAA,CAAO,IAAI,CAAA;AACxB,IAAA,IAAI,IAAA,CAAK,SAAS,OAAA,EAAS;AACzB,MAAA,MAAM,IAAI,aAAA,CAAc,SAAA,EAAW,sCAAA,EAAwC;AAAA,QACzE,OAAO,IAAI,KAAA;AAAA,UACT,CAAA,6BAAA,EAAgC,QAAQ,CAAA,uBAAA,EAA0B,OAAO,CAAA,8DAAA;AAAA;AAC3E,OACD,CAAA;AAAA,IACH;AACA,IAAA,IAAI,MAAA,CAAO,IAAA,CAAK,MAAA,GAAS,QAAA,EAAU;AAAA,EACrC;AACA,EAAA,OAAO,EAAE,MAAA,EAAQ,iBAAA,CAAkB,IAAA,EAAM,MAAA,CAAO,OAAO,CAAA,EAAE;AAC3D","file":"chunk-J54XXKQD.js","sourcesContent":["// ---------------------------------------------------------------------------\n// Totals over a list (ADR 0023): count, and sum / avg / min / max of a field\n//\n// A provider that can total in the store implements `DataProvider.aggregate`.\n// `resolveAggregate` uses it when it's there, and otherwise works the totals\n// out from the provider's own reads: a count from `getList`'s total, anything\n// else from the rows, paged, up to a limit. Either way the rows are the ones\n// `getList` would return for the same filters, so row security still decides.\n// ---------------------------------------------------------------------------\n\nimport { DataReadError } from \"../schema/read-outcome\";\nimport type { AggregateMetric, AggregateParams, AggregateResult, DataProvider } from \"./types\";\n\ntype Row = Record<string, unknown>;\n\n/** The numbers a row's value stands for: a number, or numeric text (Postgres `numeric` arrives as text). */\nfunction numeric(value: unknown): number | undefined {\n if (typeof value === \"number\") return Number.isFinite(value) ? value : undefined;\n if (typeof value === \"string\" && value.trim() !== \"\") {\n const n = Number(value);\n return Number.isFinite(n) ? n : undefined;\n }\n return undefined;\n}\n\n/**\n * The metrics' values over rows already in hand: what an in-memory provider, a test, or the\n * paged fallback computes. `count` counts every row; the others skip rows with no number in the\n * field and are `null` when none has one.\n *\n * @stability Beta\n */\nexport function toAggregateValues(\n rows: readonly Row[],\n metrics: Readonly<Record<string, AggregateMetric>>,\n): Record<string, number | null> {\n const values: Record<string, number | null> = {};\n for (const [name, metric] of Object.entries(metrics)) {\n if (metric.fn === \"count\") {\n values[name] = rows.length;\n continue;\n }\n const nums: number[] = [];\n for (const row of rows) {\n const n = numeric(row[metric.field]);\n if (n !== undefined) nums.push(n);\n }\n if (nums.length === 0) {\n values[name] = null;\n continue;\n }\n switch (metric.fn) {\n case \"sum\":\n values[name] = nums.reduce((a, b) => a + b, 0);\n break;\n case \"avg\":\n values[name] = nums.reduce((a, b) => a + b, 0) / nums.length;\n break;\n case \"min\":\n values[name] = Math.min(...nums);\n break;\n case \"max\":\n values[name] = Math.max(...nums);\n break;\n }\n }\n return values;\n}\n\n/** Every problem with an aggregate request; empty when it is sound. */\nexport function aggregateProblems(params: AggregateParams): string[] {\n const problems: string[] = [];\n const entries = Object.entries(params?.metrics ?? {});\n if (entries.length === 0) problems.push(\"metrics: at least one\");\n for (const [name, metric] of entries) {\n if (!metric || typeof metric !== \"object\") problems.push(`metrics.${name}: expected { fn }`);\n else if (metric.fn === \"count\") continue;\n else if (![\"sum\", \"avg\", \"min\", \"max\"].includes(metric.fn)) problems.push(`metrics.${name}.fn: one of count, sum, avg, min, max`);\n else if (typeof metric.field !== \"string\" || !metric.field) problems.push(`metrics.${name}.field: the numeric field to ${metric.fn}`);\n }\n return problems;\n}\n\nexport interface ResolveAggregateOptions {\n /** Rows per page when the totals come from the rows (no `aggregate` on the provider). Default 500. */\n pageSize?: number;\n /**\n * The most rows the fallback reads before it gives up with a `DataReadError` (\"invalid\"),\n * rather than a total that quietly leaves rows out. Default 10 000. A provider with its own\n * `aggregate` has no such limit.\n */\n maxRows?: number;\n}\n\n/**\n * Totals over a resource's rows through any provider: its `aggregate` when it has one, else a\n * count from `getList`'s total (one row read), else the rows themselves, paged\n * (`toAggregateValues`). Throws `DataReadError` for a request that isn't sound, and when the\n * fallback would have to read more than `maxRows`.\n *\n * @stability Beta\n */\nexport async function resolveAggregate(\n provider: DataProvider,\n resource: string,\n params: AggregateParams,\n options: ResolveAggregateOptions = {},\n): Promise<AggregateResult> {\n const problems = aggregateProblems(params);\n if (problems.length) {\n throw new DataReadError(\"invalid\", \"These totals couldn't be worked out.\", {\n cause: new Error(`[genesis-core] aggregate of \"${resource}\": ${problems.join(\"; \")}`),\n });\n }\n if (typeof provider.aggregate === \"function\") return provider.aggregate(resource, params);\n\n const { filters, search } = params;\n const metrics = Object.values(params.metrics);\n if (metrics.every((m) => m.fn === \"count\")) {\n const page = await provider.getList(resource, {\n filters,\n search,\n pagination: { page: 1, perPage: 1 },\n count: params.count ?? \"exact\",\n });\n if (page.total >= 0) {\n const values = Object.fromEntries(Object.keys(params.metrics).map((name) => [name, page.total]));\n return page.totalIsEstimate ? { values, isEstimate: true } : { values };\n }\n }\n\n const pageSize = Math.max(1, options.pageSize ?? 500);\n const maxRows = Math.max(1, options.maxRows ?? 10_000);\n const rows: Row[] = [];\n for (let page = 1; ; page++) {\n const result = await provider.getList<Row & { id: string | number }>(resource, {\n filters,\n search,\n pagination: { page, perPage: pageSize },\n count: \"none\",\n });\n rows.push(...result.data);\n if (rows.length > maxRows) {\n throw new DataReadError(\"invalid\", \"These totals couldn't be worked out.\", {\n cause: new Error(\n `[genesis-core] aggregate of \"${resource}\" would read more than ${maxRows} rows; give the provider an aggregate() or narrow the filters.`,\n ),\n });\n }\n if (result.data.length < pageSize) break;\n }\n return { values: toAggregateValues(rows, params.metrics) };\n}\n"]}
|
|
@@ -36,6 +36,14 @@ function decodeRecordKey(contract, id) {
|
|
|
36
36
|
return out;
|
|
37
37
|
}
|
|
38
38
|
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
39
|
+
// src/schema/types.ts
|
|
40
|
+
function defineResource() {
|
|
41
|
+
return (contract) => contract;
|
|
42
|
+
}
|
|
43
|
+
function fieldControl(field) {
|
|
44
|
+
return field?.control ?? field?.widget;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export { decodeRecordKey, defineResource, encodeRecordKey, fieldControl, keyFields };
|
|
48
|
+
//# sourceMappingURL=chunk-LB6FMQQM.js.map
|
|
49
|
+
//# sourceMappingURL=chunk-LB6FMQQM.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/schema/keys.ts","../src/schema/types.ts"],"names":[],"mappings":";AAYO,SAAS,UAAU,QAAA,EAA4D;AACpF,EAAA,OAAO,OAAO,SAAS,GAAA,KAAQ,QAAA,GAAW,CAAC,QAAA,CAAS,GAAG,IAAI,QAAA,CAAS,GAAA;AACtE;AAEA,SAAS,QAAA,CAAS,KAAc,KAAA,EAAgC;AAC9D,EAAA,MAAM,KAAA,GAAQ,IAAI,KAAK,CAAA;AACvB,EAAA,IAAI,OAAO,KAAA,KAAU,QAAA,IAAY,OAAO,KAAA,KAAU,UAAU,OAAO,KAAA;AACnE,EAAA,IAAI,OAAO,UAAU,QAAA,IAAY,OAAO,UAAU,SAAA,EAAW,OAAO,OAAO,KAAK,CAAA;AAChF,EAAA,MAAM,IAAI,KAAA;AAAA,IACR,qBAAqB,KAAK,CAAA,KAAA,EAAQ,UAAU,IAAA,GAAO,MAAA,GAAS,OAAO,KAAK,CAAA,2CAAA;AAAA,GAE1E;AACF;AASO,SAAS,eAAA,CACd,UACA,GAAA,EACY;AACZ,EAAA,MAAM,MAAA,GAAS,UAAU,QAAQ,CAAA;AACjC,EAAA,IAAI,OAAO,MAAA,KAAW,CAAA,EAAG,MAAM,IAAI,MAAM,4DAA4D,CAAA;AAC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C9C,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"]}
|