@constructive-io/sheets 0.3.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -24
- package/dist/advanced.cjs +659 -474
- package/dist/advanced.cjs.map +1 -1
- package/dist/advanced.d.cts +9 -10
- package/dist/advanced.d.ts +9 -10
- package/dist/advanced.js +3 -3
- package/dist/auth.cjs +10 -10
- package/dist/auth.cjs.map +1 -1
- package/dist/auth.d.cts +5 -4
- package/dist/auth.d.ts +5 -4
- package/dist/auth.js +3 -3
- package/dist/{chunk-GLVZSPV2.js → chunk-4EZ6A23C.js} +4 -3
- package/dist/chunk-4EZ6A23C.js.map +1 -0
- package/dist/{chunk-FNVHSOQQ.js → chunk-KKAWMVEG.js} +11 -11
- package/dist/chunk-KKAWMVEG.js.map +1 -0
- package/dist/{chunk-4PGPVMZB.js → chunk-KOZAW264.js} +4 -3
- package/dist/chunk-KOZAW264.js.map +1 -0
- package/dist/{chunk-ODUBS2NL.js → chunk-KVPVEXWB.js} +40 -17
- package/dist/chunk-KVPVEXWB.js.map +1 -0
- package/dist/{chunk-TU7ATZ4X.js → chunk-LR64FLWO.js} +301 -410
- package/dist/chunk-LR64FLWO.js.map +1 -0
- package/dist/chunk-ZETPUEXH.js +494 -0
- package/dist/chunk-ZETPUEXH.js.map +1 -0
- package/dist/{date-editor-CXKKGNL6.js → date-editor-QT47WY5T.js} +5 -3
- package/dist/date-editor-QT47WY5T.js.map +1 -0
- package/dist/{editor-props-M6Dh0P9f.d.ts → grid-cell-types-C3ARj148.d.cts} +70 -62
- package/dist/{editor-props-M6Dh0P9f.d.cts → grid-cell-types-C3ARj148.d.ts} +70 -62
- package/dist/index.cjs +1150 -703
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +123 -35
- package/dist/index.d.ts +123 -35
- package/dist/index.js +323 -99
- package/dist/index.js.map +1 -1
- package/dist/{sheets-context-CojEFlaY.d.cts → sheets-context-B03WDhZ9.d.cts} +36 -6
- package/dist/{sheets-context-Da55TTR9.d.ts → sheets-context-DmVCOgiX.d.ts} +36 -6
- package/dist/styles.css +6 -0
- package/dist/testing.cjs +476 -108
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.d.cts +11 -7
- package/dist/testing.d.ts +11 -7
- package/dist/testing.js +34 -8
- package/dist/testing.js.map +1 -1
- package/package.json +15 -16
- package/dist/chunk-4PGPVMZB.js.map +0 -1
- package/dist/chunk-FNVHSOQQ.js.map +0 -1
- package/dist/chunk-GLVZSPV2.js.map +0 -1
- package/dist/chunk-H4JJTMP5.js +0 -160
- package/dist/chunk-H4JJTMP5.js.map +0 -1
- package/dist/chunk-ODUBS2NL.js.map +0 -1
- package/dist/chunk-TU7ATZ4X.js.map +0 -1
- package/dist/date-editor-CXKKGNL6.js.map +0 -1
package/dist/testing.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/testing/index.ts","../src/testing/mock-sheets-provider.tsx","../src/context/sheets-provider.tsx","../src/context/sheets-context.ts","../src/context/sheets-execute.ts","../src/store/sheets-store.ts","../src/store/draft-rows-slice.ts","../src/store/relation-info-slice.ts","../src/utils/relation-utils.ts","../src/auth/utils/token-store.ts","../src/utils/sheets-logger.ts","../src/utils/sheets-i18n.ts"],"sourcesContent":["// Public '/testing' subpath — consumer test harness for @constructive-io/sheets.\n// Not part of the core graph; bundled separately so production consumers never\n// pull in the in-memory mock backend.\nexport * from './mock-sheets-provider';\n","// Consumer test harness for @constructive-io/sheets.\n//\n// Shipped at the '/testing' subpath — NOT part of the core graph. Lets a\n// consumer mount a <Sheets> grid in jsdom/vitest with zero network: a tiny\n// in-memory PostGraphile-shaped backend that serves the `_meta` introspection,\n// list connections, and create/update/delete mutations, while recording every\n// mutation for assertions.\n//\n// This file intentionally uses a few test-grade casts on the mock GraphQL\n// responses (see the `as unknown as MetaQuery` in `buildMetaResponse` and the\n// `as File` narrowing in `executeUpload`). It is a deliberately partial\n// PostGraphile emulator — just enough to render a grid and assert mutations —\n// so the casts are scoped, documented, and never leak into the core graph.\nimport { useMemo } from 'react';\nimport { print } from 'graphql';\nimport type { DocumentNode } from 'graphql';\nimport { QueryClient } from '@tanstack/react-query';\n\nimport {\n\ttoCamelCasePlural,\n\ttoCamelCaseSingular,\n\ttoCreateMutationName,\n\ttoUpdateMutationName,\n\ttoDeleteMutationName,\n} from '@constructive-io/data';\nimport type { MetaQuery } from '@constructive-io/data';\n\nimport { SheetsProvider } from '../context/sheets-provider';\nimport type { SheetsExecuteFn, SheetsUploadFn, SheetsUploadOptions } from '../context/sheets-execute';\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface MockTableField {\n\tname: string;\n\tgqlType: string;\n\tisArray?: boolean;\n\tpgType?: string;\n\tsubtype?: string;\n}\n\nexport interface MockTable {\n\tname: string;\n\tfields: MockTableField[];\n\trows: Record<string, unknown>[];\n}\n\nexport interface RecordedMutation {\n\top: 'create' | 'update' | 'delete' | 'upload';\n\ttableName: string;\n\tvariables: Record<string, unknown>;\n\tat: number;\n}\n\nexport interface MockSheetsOptions {\n\ttables: MockTable[];\n\tonMutation?: (m: RecordedMutation) => void;\n}\n\nexport interface MockExecuteHandle {\n\texecute: SheetsExecuteFn;\n\texecuteUpload: SheetsUploadFn;\n\tmutations: RecordedMutation[];\n\treset(): void;\n}\n\n// ============================================================================\n// Document stringification (mirrors context/sheets-execute.ts)\n// ============================================================================\n\ntype ExecutableDocument = DocumentNode | string | unknown;\n\nfunction documentToString(document: ExecutableDocument): string {\n\tif (typeof document === 'string') return document;\n\tif (document instanceof String) return document.toString();\n\tif (document && typeof document === 'object' && 'kind' in (document as DocumentNode)) {\n\t\treturn print(document as DocumentNode);\n\t}\n\treturn String(document ?? '');\n}\n\n// ============================================================================\n// Meta response synthesis\n// ============================================================================\n\nfunction buildMetaField(field: MockTableField) {\n\treturn {\n\t\tname: field.name,\n\t\tisNotNull: false,\n\t\thasDefault: false,\n\t\ttype: {\n\t\t\tgqlType: field.gqlType,\n\t\t\tisArray: field.isArray ?? false,\n\t\t\tpgType: field.pgType ?? 'text',\n\t\t\tisNotNull: false,\n\t\t\thasDefault: false,\n\t\t\tsubtype: field.subtype ?? null,\n\t\t},\n\t};\n}\n\nfunction buildMetaTable(table: MockTable) {\n\treturn {\n\t\tname: table.name,\n\t\tschemaName: 'public',\n\t\tquery: {\n\t\t\tall: toCamelCasePlural(table.name),\n\t\t\tcreate: toCreateMutationName(table.name),\n\t\t\tdelete: toDeleteMutationName(table.name),\n\t\t\tone: toCamelCaseSingular(table.name),\n\t\t\tupdate: toUpdateMutationName(table.name),\n\t\t},\n\t\tfields: table.fields.map(buildMetaField),\n\t\tinflection: {\n\t\t\tallRows: toCamelCasePlural(table.name),\n\t\t\tconnection: toCamelCasePlural(table.name),\n\t\t\ttableType: table.name,\n\t\t},\n\t\tindexes: [],\n\t\tconstraints: { primaryKey: null, unique: [], foreignKey: [] },\n\t\tforeignKeyConstraints: [],\n\t\tprimaryKeyConstraints: [],\n\t\tuniqueConstraints: [],\n\t\trelations: { belongsTo: [], has: [], hasOne: [], hasMany: [], manyToMany: [] },\n\t};\n}\n\n// Pragmatic test-grade cast: we synthesize a loose subset of the `_meta`\n// introspection shape (enough for cleanTable + the grid render path). The full\n// MetaschemaTable union has many optional v4/v5 fields we don't populate, so a\n// single structural cast keeps this fixture readable without re-declaring the\n// entire schema. This is test-only code on a separate subpath.\nfunction buildMetaResponse(tables: MockTable[]): MetaQuery {\n\treturn {\n\t\t_meta: {\n\t\t\ttables: tables.map(buildMetaTable),\n\t\t},\n\t} as unknown as MetaQuery;\n}\n\n// ============================================================================\n// List response synthesis\n// ============================================================================\n\nfunction buildListResponse(table: MockTable): Record<string, unknown> {\n\tconst field = toCamelCasePlural(table.name);\n\treturn {\n\t\t[field]: {\n\t\t\tnodes: table.rows,\n\t\t\ttotalCount: table.rows.length,\n\t\t\tpageInfo: {\n\t\t\t\thasNextPage: false,\n\t\t\t\thasPreviousPage: false,\n\t\t\t\tendCursor: null,\n\t\t\t\tstartCursor: null,\n\t\t\t},\n\t\t},\n\t};\n}\n\n// ============================================================================\n// Mutation row synthesis\n// ============================================================================\n\nlet mockIdCounter = 0;\n\nfunction synthesizeId(): string {\n\tmockIdCounter += 1;\n\treturn `mock-${mockIdCounter}`;\n}\n\nfunction extractMutationInput(variables: Record<string, unknown> | undefined): Record<string, unknown> {\n\tconst input = variables?.input;\n\treturn input && typeof input === 'object' ? (input as Record<string, unknown>) : {};\n}\n\nfunction synthesizeCreatedRow(\n\ttable: MockTable,\n\tsingular: string,\n\tvariables: Record<string, unknown> | undefined,\n): Record<string, unknown> {\n\tconst input = extractMutationInput(variables);\n\tconst data = (input[singular] as Record<string, unknown>) ?? {};\n\tconst row: Record<string, unknown> = { id: synthesizeId(), ...data };\n\ttable.rows.push(row);\n\treturn row;\n}\n\nfunction synthesizeUpdatedRow(\n\ttable: MockTable,\n\tvariables: Record<string, unknown> | undefined,\n): Record<string, unknown> {\n\tconst input = extractMutationInput(variables);\n\tconst id = input.id;\n\t// Patch field name varies by entity (e.g. `userPatch`); take the first\n\t// object-valued non-id key as the patch payload.\n\tlet patch: Record<string, unknown> = {};\n\tfor (const [key, value] of Object.entries(input)) {\n\t\tif (key === 'id') continue;\n\t\tif (value && typeof value === 'object') {\n\t\t\tpatch = value as Record<string, unknown>;\n\t\t\tbreak;\n\t\t}\n\t}\n\tconst existing = table.rows.find((r) => r.id === id);\n\tconst merged: Record<string, unknown> = { ...(existing ?? { id }), ...patch };\n\tif (existing) {\n\t\tObject.assign(existing, patch);\n\t} else {\n\t\ttable.rows.push(merged);\n\t}\n\treturn merged;\n}\n\n// ============================================================================\n// Detection helpers\n// ============================================================================\n\nfunction isMetaQuery(query: string): boolean {\n\treturn query.includes('_meta');\n}\n\nfunction isMutationDocument(query: string): boolean {\n\t// PostGraphile mutation docs are `mutation Xxx(...) { ... }`; a leading\n\t// `mutation` keyword disambiguates them from list queries that may select a\n\t// relation field whose name collides with a mutation name as a substring.\n\treturn /(^|\\s)mutation(\\s|\\{)/.test(query);\n}\n\nfunction findMutationTable(\n\tquery: string,\n\ttables: MockTable[],\n): { table: MockTable; op: 'create' | 'update' | 'delete'; mutationName: string; singular: string } | null {\n\t// Longest-match: a table whose mutation name is a substring of another's\n\t// (e.g. createUser vs createUserProfile) must not win over the exact one.\n\tlet best: { table: MockTable; op: 'create' | 'update' | 'delete'; mutationName: string; singular: string } | null = null;\n\tfor (const table of tables) {\n\t\tconst candidates: Array<{ op: 'create' | 'update' | 'delete'; mutationName: string }> = [\n\t\t\t{ op: 'create', mutationName: toCreateMutationName(table.name) },\n\t\t\t{ op: 'update', mutationName: toUpdateMutationName(table.name) },\n\t\t\t{ op: 'delete', mutationName: toDeleteMutationName(table.name) },\n\t\t];\n\t\tfor (const c of candidates) {\n\t\t\tif (query.includes(c.mutationName) && (!best || c.mutationName.length > best.mutationName.length)) {\n\t\t\t\tbest = { table, op: c.op, mutationName: c.mutationName, singular: toCamelCaseSingular(table.name) };\n\t\t\t}\n\t\t}\n\t}\n\treturn best;\n}\n\nfunction findListTable(query: string, tables: MockTable[]): MockTable | null {\n\t// Longest-match for the same substring-collision reason.\n\tlet best: MockTable | null = null;\n\tlet bestLen = 0;\n\tfor (const table of tables) {\n\t\tconst plural = toCamelCasePlural(table.name);\n\t\tif (query.includes(plural) && plural.length > bestLen) {\n\t\t\tbest = table;\n\t\t\tbestLen = plural.length;\n\t\t}\n\t}\n\treturn best;\n}\n\n// ============================================================================\n// Factory\n// ============================================================================\n\nexport function createMockExecute(opts: MockSheetsOptions): MockExecuteHandle {\n\tconst mutations: RecordedMutation[] = [];\n\n\tfunction record(m: RecordedMutation) {\n\t\tmutations.push(m);\n\t\topts.onMutation?.(m);\n\t}\n\n\tconst execute: SheetsExecuteFn = async <T = unknown>(\n\t\tdocument: ExecutableDocument,\n\t\tvariables?: Record<string, unknown>,\n\t): Promise<T> => {\n\t\tconst query = documentToString(document);\n\n\t\t// 1. Introspection (_meta) — detected by the `_meta` selection.\n\t\tif (isMetaQuery(query)) {\n\t\t\treturn buildMetaResponse(opts.tables) as T;\n\t\t}\n\n\t\t// 2. Mutations — detected by a create/update/delete mutation name.\n\t\tconst mutationMatch = isMutationDocument(query) ? findMutationTable(query, opts.tables) : null;\n\t\tif (mutationMatch) {\n\t\t\tconst { table, op, mutationName, singular } = mutationMatch;\n\t\t\trecord({ op, tableName: table.name, variables: variables ?? {}, at: Date.now() });\n\n\t\t\tif (op === 'delete') {\n\t\t\t\tconst input = extractMutationInput(variables);\n\t\t\t\tconst id = input.id ?? null;\n\t\t\t\ttable.rows = table.rows.filter((r) => r.id !== id);\n\t\t\t\treturn { [mutationName]: { deletedNodeId: id, clientMutationId: null } } as T;\n\t\t\t}\n\n\t\t\tconst row =\n\t\t\t\top === 'create'\n\t\t\t\t\t? synthesizeCreatedRow(table, singular, variables)\n\t\t\t\t\t: synthesizeUpdatedRow(table, variables);\n\t\t\treturn { [mutationName]: { [singular]: row } } as T;\n\t\t}\n\n\t\t// 3. List query (table connection) — detected by the camelPlural field.\n\t\tconst listTable = findListTable(query, opts.tables);\n\t\tif (listTable) {\n\t\t\treturn buildListResponse(listTable) as T;\n\t\t}\n\n\t\t// Unknown operation: return an empty object so callers degrade gracefully.\n\t\treturn {} as T;\n\t};\n\n\tconst executeUpload: SheetsUploadFn = async (\n\t\tfile: File,\n\t\tpath?: string,\n\t\toptions?: SheetsUploadOptions,\n\t): Promise<{ url: string }> => {\n\t\tconst name = (file as File)?.name ?? 'file';\n\t\trecord({\n\t\t\top: 'upload',\n\t\t\ttableName: options?.tableName ?? '',\n\t\t\tvariables: {\n\t\t\t\tname,\n\t\t\t\t...(path !== undefined && { path }),\n\t\t\t\t...(options?.fieldName !== undefined && { fieldName: options.fieldName }),\n\t\t\t\t...(options?.recordId !== undefined && { recordId: options.recordId }),\n\t\t\t},\n\t\t\tat: Date.now(),\n\t\t});\n\t\treturn { url: 'mock://uploaded/' + name };\n\t};\n\n\tfunction reset() {\n\t\tmutations.length = 0;\n\t}\n\n\treturn { execute, executeUpload, mutations, reset };\n}\n\n// ============================================================================\n// Provider\n// ============================================================================\n\nexport interface MockSheetsProviderProps {\n\toptions: MockSheetsOptions;\n\tchildren: React.ReactNode;\n}\n\nexport function MockSheetsProvider({ options, children }: MockSheetsProviderProps) {\n\t// Build the mock backend + an isolated QueryClient ONCE per mount. Tests that\n\t// need a fresh harness should remount (e.g. via `key`), so an empty dep array\n\t// is correct — `options` is treated as mount-time configuration.\n\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\tconst { execute, executeUpload } = useMemo(() => createMockExecute(options), []);\n\n\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\tconst queryClient = useMemo(\n\t\t() =>\n\t\t\tnew QueryClient({\n\t\t\t\tdefaultOptions: {\n\t\t\t\t\tqueries: { retry: false, gcTime: 0 },\n\t\t\t\t\tmutations: { retry: false },\n\t\t\t\t},\n\t\t\t}),\n\t\t[],\n\t);\n\n\treturn (\n\t\t<SheetsProvider\n\t\t\tconfig={{\n\t\t\t\tendpoint: 'mock://sheets',\n\t\t\t\tauth: { mode: 'embedded', getToken: () => 'test' },\n\t\t\t\texecute,\n\t\t\t\texecuteUpload,\n\t\t\t\tqueryClient,\n\t\t\t}}\n\t\t>\n\t\t\t{children}\n\t\t</SheetsProvider>\n\t);\n}\n\n// ============================================================================\n// Ready fixture\n// ============================================================================\n\nexport const usersFixture: MockTable = {\n\tname: 'users',\n\tfields: [\n\t\t{ name: 'id', gqlType: 'UUID', pgType: 'uuid' },\n\t\t{ name: 'name', gqlType: 'String', pgType: 'text' },\n\t\t{ name: 'email', gqlType: 'String', pgType: 'text' },\n\t\t{ name: 'isActive', gqlType: 'Boolean', pgType: 'boolean' },\n\t\t{ name: 'createdAt', gqlType: 'Datetime', pgType: 'timestamptz' },\n\t],\n\trows: [\n\t\t{\n\t\t\tid: '00000000-0000-0000-0000-000000000001',\n\t\t\tname: 'Ada Lovelace',\n\t\t\temail: 'ada@example.com',\n\t\t\tisActive: true,\n\t\t\tcreatedAt: '2024-01-01T00:00:00Z',\n\t\t},\n\t\t{\n\t\t\tid: '00000000-0000-0000-0000-000000000002',\n\t\t\tname: 'Alan Turing',\n\t\t\temail: 'alan@example.com',\n\t\t\tisActive: false,\n\t\t\tcreatedAt: '2024-01-02T00:00:00Z',\n\t\t},\n\t],\n};\n","import { useEffect, useMemo, useRef } from 'react';\nimport { QueryClient, QueryClientProvider } from '@tanstack/react-query';\n\nimport { SheetsContext, type SheetsConfig, type SheetsContextValue, type SheetsScopeKey } from './sheets-context';\nimport { createSheetsExecute, createSheetsUpload, type SheetsExecuteFn, type SheetsUploadFn } from './sheets-execute';\nimport { createSheetsStore, SheetsStoreContext, type SheetsStoreState } from '../store/sheets-store';\nimport { getStoredToken } from '../auth/utils/token-store';\nimport { setSheetsLogger } from '../utils/sheets-logger';\nimport { setSheetsLocale } from '../utils/sheets-i18n';\n\nimport type { StoreApi } from 'zustand';\n\ninterface SheetsProviderProps {\n\tconfig: SheetsConfig;\n\tchildren: React.ReactNode;\n}\n\nexport function SheetsProvider({ config, children }: SheetsProviderProps) {\n\t// Create store once\n\tconst storeRef = useRef<StoreApi<SheetsStoreState> | null>(null);\n\tif (!storeRef.current) {\n\t\tstoreRef.current = createSheetsStore();\n\t}\n\n\t// Install the host logger + locale synchronously so they apply before first paint.\n\tsetSheetsLogger(config.logger);\n\tsetSheetsLocale(config.locale);\n\n\t// Keep the module singletons in sync if the host swaps them across renders.\n\tuseEffect(() => {\n\t\tsetSheetsLogger(config.logger);\n\t\tsetSheetsLocale(config.locale);\n\t}, [config.logger, config.locale]);\n\n\t// Restore persisted token for standalone mode\n\tuseEffect(() => {\n\t\tconst store = storeRef.current?.getState();\n\t\tif (!store) return;\n\n\t\tif (config.auth.mode !== 'standalone') {\n\t\t\t// Prevent leaking stale standalone tokens when switching auth modes.\n\t\t\tstore.setUnauthenticated();\n\t\t\treturn;\n\t\t}\n\t\tconst databaseId = config.databaseId || 'default';\n\t\tconst stored = getStoredToken(databaseId);\n\t\tif (!stored) {\n\t\t\tstore.setUnauthenticated();\n\t\t\treturn;\n\t\t}\n\n\t\t// Only restore if not expired\n\t\tconst expiresAt = new Date(stored.expiresAt);\n\t\tif (expiresAt > new Date()) {\n\t\t\tstore.setAuthenticated(stored.accessToken, stored.expiresAt);\n\t\t\treturn;\n\t\t}\n\n\t\tstore.setUnauthenticated();\n\t}, [config.auth.mode, config.databaseId]);\n\n\t// Always provide a QueryClient context. If consumer injects one, reuse it.\n\tconst internalQueryClient = useMemo(\n\t\t() =>\n\t\t\tnew QueryClient({\n\t\t\t\tdefaultOptions: {\n\t\t\t\t\tqueries: {\n\t\t\t\t\t\tstaleTime: 5 * 60 * 1000,\n\t\t\t\t\t\tgcTime: 30 * 60 * 1000,\n\t\t\t\t\t\tretry: 1,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}),\n\t\t[],\n\t);\n\tconst queryClient = config.queryClient ?? internalQueryClient;\n\n\t// Token getter: embedded mode uses config.auth.getToken, standalone uses store\n\tconst getToken = useMemo(() => {\n\t\tif (config.auth.mode === 'embedded') {\n\t\t\treturn config.auth.getToken;\n\t\t}\n\t\t// Standalone: read from store\n\t\treturn () => storeRef.current?.getState().accessToken ?? null;\n\t}, [config.auth]);\n\n\t// Create execute function\n\tconst execute: SheetsExecuteFn = useMemo(() => {\n\t\tif (config.execute) return config.execute;\n\t\treturn createSheetsExecute(config, getToken);\n\t}, [config, getToken]);\n\n\t// Create upload function\n\tconst executeUpload: SheetsUploadFn = useMemo(() => {\n\t\tif (config.executeUpload) return config.executeUpload;\n\t\treturn createSheetsUpload(config, getToken);\n\t}, [config, getToken]);\n\n\t// Scope key for React Query cache isolation\n\tconst scopeKey: SheetsScopeKey = useMemo(\n\t\t() => ({\n\t\t\tdatabaseId: config.databaseId ?? null,\n\t\t\tendpoint: config.endpoint,\n\t\t}),\n\t\t[config.databaseId, config.endpoint],\n\t);\n\n\tconst contextValue: SheetsContextValue = useMemo(\n\t\t() => ({ config, execute, executeUpload, scopeKey }),\n\t\t[config, execute, executeUpload, scopeKey],\n\t);\n\n\treturn (\n\t\t<QueryClientProvider client={queryClient}>\n\t\t\t<SheetsStoreContext.Provider value={storeRef.current}>\n\t\t\t\t<SheetsContext.Provider value={contextValue}>{children}</SheetsContext.Provider>\n\t\t\t</SheetsStoreContext.Provider>\n\t\t</QueryClientProvider>\n\t);\n}\n","import { createContext, useContext } from 'react';\nimport type { QueryClient } from '@tanstack/react-query';\n\nimport type { SheetsExecuteFn, SheetsUploadFn } from './sheets-execute';\nimport type { SheetsLogger } from '../utils/sheets-logger';\nimport type { CellTypePlugin } from '../cell-types/define-cell-type';\nimport type { SheetsBackendAdapter } from '../adapter/sheets-adapter';\n\nexport interface SheetsAuthEmbedded {\n\tmode: 'embedded';\n\tgetToken: () => string | null;\n}\n\nexport interface SheetsAuthStandalone {\n\tmode: 'standalone';\n}\n\nexport interface SheetsConfig {\n\t/** Data endpoint (app-public GraphQL) */\n\tendpoint: string;\n\t/** Auth endpoint (auth GraphQL) — required for standalone mode */\n\tauthEndpoint?: string;\n\t/** Database ID for multi-tenant scoping */\n\tdatabaseId?: string;\n\t/** Auth mode */\n\tauth: SheetsAuthEmbedded | SheetsAuthStandalone;\n\t/** Field type overrides (replaces schema-builder smart tags) */\n\tfieldTypeOverrides?: Record<string, string>;\n\t/** Optional: BCP-47 locale for locale-aware date/number formatting (default 'en-US'). */\n\tlocale?: string;\n\t/** Optional: inject custom execute function */\n\texecute?: SheetsExecuteFn;\n\t/** Optional: inject custom upload function */\n\texecuteUpload?: SheetsUploadFn;\n\t/** Optional: inject existing QueryClient */\n\tqueryClient?: QueryClient;\n\t/** Optional: inject a custom backend adapter. Defaults to the PostGraphile adapter. */\n\tadapter?: SheetsBackendAdapter;\n\t/** Optional: provider-level cell-type plugins (consumer override layer). */\n\tplugins?: CellTypePlugin[];\n\t/** Called on 401/UNAUTHENTICATED before the error is thrown. Host app handles token cleanup. */\n\tonAuthError?: () => void;\n\t/** Optional: inject a custom logger. Installed into the module logger singleton by the provider. */\n\tlogger?: SheetsLogger;\n\t/** Optional: called when a grid/editor/mutation/upload error surfaces. Host app handles reporting. */\n\tonError?: (\n\t\terror: unknown,\n\t\tctx?: { source?: 'grid' | 'editor' | 'mutation' | 'upload'; tableName?: string },\n\t) => void;\n}\n\nexport interface SheetsContextValue {\n\tconfig: SheetsConfig;\n\texecute: SheetsExecuteFn;\n\texecuteUpload: SheetsUploadFn;\n\tscopeKey: SheetsScopeKey;\n}\n\nexport interface SheetsScopeKey {\n\tdatabaseId: string | null;\n\tendpoint: string;\n}\n\nexport const SheetsContext = createContext<SheetsContextValue | null>(null);\n\nexport function useSheetsContext(): SheetsContextValue {\n\tconst ctx = useContext(SheetsContext);\n\tif (!ctx) {\n\t\tthrow new Error('useSheetsContext must be used within a <SheetsProvider>');\n\t}\n\treturn ctx;\n}\n","import type { DocumentNode } from 'graphql';\nimport { print } from 'graphql';\n\nimport { createError, DataError, TypedDocumentString } from '@constructive-io/data';\n\nimport type { SheetsConfig } from './sheets-context';\n\n// ============================================================================\n// Types\n// ============================================================================\n\ntype ExecutableDocument = TypedDocumentString<any, any> | DocumentNode | string | unknown;\n\nexport type SheetsExecuteFn = <T = unknown>(\n\tdocument: ExecutableDocument,\n\tvariables?: Record<string, unknown>,\n) => Promise<T>;\n\n/**\n * Result of an upload through the seam. `url` is the only guaranteed field;\n * the REST upload endpoint also returns `{ filename, mime, size }` (and may\n * return server-internal extras). Keeping it open-ended lets callers read the\n * richer metadata while a bare `{ url }` (e.g. the mock) still satisfies it.\n */\nexport type SheetsUploadResult = { url: string } & Record<string, unknown>;\n\n/**\n * Optional upload metadata carried through the seam (third arg). Lets an\n * injected `executeUpload` see the destination field/row and report progress.\n * All fields optional, so existing `(file, path?)` callers stay valid.\n */\nexport interface SheetsUploadOptions {\n\ttableName?: string;\n\tfieldName?: string;\n\trecordId?: string | number;\n\tonProgress?: (progress: { loaded: number; total: number; percentage: number }) => void;\n}\n\nexport type SheetsUploadFn = (\n\tfile: File,\n\tpath?: string,\n\toptions?: SheetsUploadOptions,\n) => Promise<SheetsUploadResult>;\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\nfunction documentToString(document: ExecutableDocument): string {\n\tif (typeof document === 'string') return document;\n\tif (document instanceof String) return document.toString();\n\tif (document && typeof document === 'object' && 'kind' in (document as DocumentNode)) {\n\t\treturn print(document as DocumentNode);\n\t}\n\tif (document === null || document === undefined) {\n\t\tthrow createError.badRequest('Invalid GraphQL document: null or undefined');\n\t}\n\treturn String(document);\n}\n\n// ============================================================================\n// GraphQL Response Parsing\n// ============================================================================\n\ninterface GraphQLResponseError {\n\tmessage: string;\n\textensions?: { code?: string };\n}\n\ninterface GraphQLResponse {\n\tdata?: unknown;\n\terrors?: GraphQLResponseError[];\n}\n\nfunction hasAuthMessage(message: string | undefined): boolean {\n\tconst normalized = String(message ?? '').toLowerCase();\n\treturn (\n\t\tnormalized.includes('unauthenticated') ||\n\t\tnormalized.includes('unauthorized') ||\n\t\tnormalized.includes('authentication')\n\t);\n}\n\nfunction parseGraphQLResponse(response: GraphQLResponse, onAuthError?: () => void): DataError | null {\n\tif (!response.errors?.length) return null;\n\n\tconst error = response.errors[0];\n\tconst code = error.extensions?.code;\n\tconst message = error.message || 'GraphQL query failed';\n\n\tif (code === 'UNAUTHENTICATED' || hasAuthMessage(message)) {\n\t\tonAuthError?.();\n\t\treturn createError.unauthorized('Authentication required. Please log in again.');\n\t}\n\n\tif (code === 'FORBIDDEN') {\n\t\treturn createError.forbidden('You do not have permission to perform this action.');\n\t}\n\n\treturn createError.graphql(message, code);\n}\n\n// ============================================================================\n// Factory\n// ============================================================================\n\nexport function createSheetsExecute(\n\tconfig: SheetsConfig,\n\tgetToken: () => string | null,\n): SheetsExecuteFn {\n\treturn async <T = unknown>(\n\t\tdocument: ExecutableDocument,\n\t\tvariables?: Record<string, unknown>,\n\t): Promise<T> => {\n\t\tconst url = config.endpoint;\n\t\tif (!url) {\n\t\t\tthrow createError.badRequest('No GraphQL endpoint configured.');\n\t\t}\n\n\t\tconst token = getToken();\n\t\tconst headers: Record<string, string> = {\n\t\t\t'Content-Type': 'application/json',\n\t\t\tAccept: 'application/graphql-response+json',\n\t\t};\n\t\tif (token) {\n\t\t\theaders['Authorization'] = `Bearer ${token}`;\n\t\t}\n\n\t\tlet response: Response;\n\t\ttry {\n\t\t\tresponse = await fetch(url, {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders,\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tquery: documentToString(document),\n\t\t\t\t\t...(variables !== undefined && { variables }),\n\t\t\t\t}),\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthrow createError.network(error instanceof Error ? error : undefined);\n\t\t}\n\n\t\tif (!response.ok) {\n\t\t\tconst { status, statusText } = response;\n\t\t\tif (status === 401) {\n\t\t\t\tconfig.onAuthError?.();\n\t\t\t\tthrow createError.unauthorized('Authentication required. Please log in again.');\n\t\t\t}\n\t\t\tif (status === 403) {\n\t\t\t\tthrow createError.forbidden('You do not have permission to perform this action.');\n\t\t\t}\n\t\t\tif (status === 404) {\n\t\t\t\tthrow createError.notFound('The requested endpoint does not exist.');\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst body = await response.json();\n\t\t\t\tif (body.errors?.length) {\n\t\t\t\t\tthrow createError.graphql(body.errors[0].message || `Request failed: ${status}`, body.errors[0].extensions?.code);\n\t\t\t\t}\n\t\t\t} catch (e) {\n\t\t\t\tif (e instanceof DataError) throw e;\n\t\t\t}\n\t\t\tthrow createError.badRequest(`Request failed: ${status} ${statusText}`);\n\t\t}\n\n\t\tconst result: GraphQLResponse = await response.json();\n\t\tconst graphqlError = parseGraphQLResponse(result, config.onAuthError);\n\t\tif (graphqlError) {\n\t\t\tthrow graphqlError;\n\t\t}\n\n\t\treturn result.data as T;\n\t};\n}\n\nexport function createSheetsUpload(config: SheetsConfig, getToken: () => string | null): SheetsUploadFn {\n\t// `path` is appended to the form when present; `options` carries optional\n\t// field/row metadata + progress for injected implementations. The default\n\t// REST transport has no progress channel, so onProgress is a no-op here.\n\treturn async (file: File, path?: string): Promise<SheetsUploadResult> => {\n\t\tif (!config.endpoint) {\n\t\t\tthrow createError.badRequest('No GraphQL endpoint configured.');\n\t\t}\n\t\tconst url = config.endpoint.replace(/\\/graphql\\/?$/, '/upload');\n\t\tconst token = getToken();\n\n\t\tconst formData = new FormData();\n\t\tformData.append('file', file);\n\t\tif (path) formData.append('path', path);\n\n\t\tconst headers: Record<string, string> = {};\n\t\tif (token) {\n\t\t\theaders['Authorization'] = `Bearer ${token}`;\n\t\t}\n\n\t\tlet response: Response;\n\t\ttry {\n\t\t\tresponse = await fetch(url, {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders,\n\t\t\t\tbody: formData,\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthrow createError.network(error instanceof Error ? error : undefined);\n\t\t}\n\n\t\tif (!response.ok) {\n\t\t\tif (response.status === 401) {\n\t\t\t\tconfig.onAuthError?.();\n\t\t\t\tthrow createError.unauthorized('Authentication required. Please log in again.');\n\t\t\t}\n\t\t\tif (response.status === 403) {\n\t\t\t\tthrow createError.forbidden('You do not have permission to perform this action.');\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst body = (await response.json()) as GraphQLResponse;\n\t\t\t\tconst graphqlError = parseGraphQLResponse(body, config.onAuthError);\n\t\t\t\tif (graphqlError) {\n\t\t\t\t\tthrow graphqlError;\n\t\t\t\t}\n\t\t\t\tif (body.errors?.length) {\n\t\t\t\t\tconst firstError = body.errors[0];\n\t\t\t\t\tthrow createError.graphql(firstError.message || 'Upload failed', firstError.extensions?.code);\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\tif (error instanceof DataError) throw error;\n\t\t\t}\n\t\t\t// Specific user-facing messages for the common REST upload failures.\n\t\t\t// Reached only when the body carried no GraphQL auth/error to surface.\n\t\t\tif (response.status === 400) throw createError.badRequest('No file provided for upload.');\n\t\t\tif (response.status === 413) throw createError.badRequest('File is too large. Maximum size is 10 MB.');\n\t\t\tthrow createError.badRequest(`Upload failed: ${response.status} ${response.statusText}`);\n\t\t}\n\n\t\tconst result = (await response.json()) as GraphQLResponse;\n\t\tif (result.errors?.length) {\n\t\t\tconst graphqlError = parseGraphQLResponse(result, config.onAuthError);\n\t\t\tif (graphqlError) {\n\t\t\t\tthrow graphqlError;\n\t\t\t}\n\t\t\tconst firstError = result.errors[0];\n\t\t\tthrow createError.graphql(firstError.message || 'Upload failed', firstError.extensions?.code);\n\t\t}\n\n\t\treturn result as SheetsUploadResult;\n\t};\n}\n\nexport { DataError } from '@constructive-io/data';\n","import { createContext, useContext } from 'react';\nimport { createStore, useStore as useZustandStore, type StoreApi } from 'zustand';\n\nimport { createDraftRowsSlice, type DraftRowsSlice } from './draft-rows-slice';\nimport { createRelationInfoSlice, type RelationInfoSlice } from './relation-info-slice';\n\nexport interface SheetsAuthState {\n isAuthenticated: boolean;\n accessToken: string | null;\n expiresAt: string | null;\n setAuthenticated: (token: string, expiresAt: string) => void;\n setUnauthenticated: () => void;\n}\n\nexport type SheetsStoreState = DraftRowsSlice & RelationInfoSlice & SheetsAuthState;\n\nexport function createSheetsStore(): StoreApi<SheetsStoreState> {\n return createStore<SheetsStoreState>((set, get) => ({\n // Draft rows\n ...createDraftRowsSlice(set),\n\n // Relation info cache\n ...createRelationInfoSlice(set, get),\n\n // Auth state (standalone mode)\n isAuthenticated: false,\n accessToken: null,\n expiresAt: null,\n setAuthenticated: (token: string, expiresAt: string) =>\n set({ isAuthenticated: true, accessToken: token, expiresAt }),\n setUnauthenticated: () => set({ isAuthenticated: false, accessToken: null, expiresAt: null }),\n }));\n}\n\nexport const SheetsStoreContext = createContext<StoreApi<SheetsStoreState> | null>(null);\n\nexport function useSheetsStore<T>(selector: (state: SheetsStoreState) => T): T {\n const store = useContext(SheetsStoreContext);\n if (!store) {\n throw new Error('useSheetsStore must be used within a <SheetsProvider>');\n }\n return useZustandStore(store, selector);\n}\n\nexport function useSheetsStoreApi(): StoreApi<SheetsStoreState> {\n const store = useContext(SheetsStoreContext);\n if (!store) {\n throw new Error('useSheetsStoreApi must be used within a <SheetsProvider>');\n }\n return store;\n}\n","import type { RelationInfo } from './relation-info-slice';\n\ntype DraftRowStatus = 'idle' | 'saving' | 'error';\n\nexport interface DraftRow {\n id: string;\n values: Record<string, unknown>;\n status: DraftRowStatus;\n errors: Record<string, string> | null;\n createdAt: number;\n metaVersion: string;\n}\n\ninterface DraftRowsTableState {\n order: string[];\n map: Record<string, DraftRow>;\n template: Record<string, unknown>;\n metaVersion: string;\n columnOrder: string[];\n}\n\nexport function parseDraftTableKey(tableKey: string): { databaseId: string | null; tableName: string } | null {\n const parts = tableKey.split('::');\n if (parts.length === 2) {\n const [databaseId, tableName] = parts;\n if (!databaseId || !tableName) return null;\n return { databaseId, tableName };\n }\n return null;\n}\n\nexport interface DraftRowCreationArgs {\n tableKey: string;\n columnOrder: readonly string[];\n fieldMetaByKey: Record<string, DraftFieldMetadata | undefined>;\n relationInfoByKey?: Record<string, RelationInfo | undefined>;\n metaVersion: string;\n}\n\nexport type DraftRowsSyncArgs = DraftRowCreationArgs;\n\nexport interface DraftRowUpdateArgs {\n tableKey: string;\n draftRowId: string;\n columnKey: string;\n value: unknown;\n extraValues?: Record<string, unknown>;\n}\n\nexport interface DraftRowsSlice {\n draftRowsByTable: Record<string, DraftRowsTableState | undefined>;\n createDraftRow: (args: DraftRowCreationArgs) => string;\n updateDraftCell: (args: DraftRowUpdateArgs) => void;\n removeDraftRow: (tableKey: string, draftRowId: string) => void;\n clearDraftRowsForTable: (tableKey: string) => void;\n clearDraftRowsForDatabase: (databaseId: string) => void;\n clearAllDraftRows: () => void;\n syncDraftRowsWithMeta: (args: DraftRowsSyncArgs) => void;\n setDraftRowStatus: (args: {\n tableKey: string;\n draftRowId: string;\n status: DraftRowStatus;\n errors?: Record<string, string> | null;\n }) => void;\n}\n\ntype DraftFieldMetadata = {\n name?: string | null;\n isNotNull?: boolean | null;\n hasDefault?: boolean | null;\n type?: {\n gqlType?: string | null;\n isArray?: boolean | null;\n pgAlias?: string | null;\n pgType?: string | null;\n subtype?: string | null;\n } | null;\n};\n\ntype DraftRowsSetState = (\n\tpartial: Partial<DraftRowsSlice> | ((state: DraftRowsSlice) => Partial<DraftRowsSlice> | DraftRowsSlice),\n) => void;\n\nexport function createDraftRowsSlice(set: DraftRowsSetState): DraftRowsSlice {\n\treturn {\n draftRowsByTable: {},\n\n createDraftRow: (args) => {\n const { tableKey, columnOrder, fieldMetaByKey, relationInfoByKey, metaVersion } = args;\n\n const effectiveColumnOrder = ensureColumnOrder(columnOrder, fieldMetaByKey, relationInfoByKey);\n const template = buildTemplate(effectiveColumnOrder, relationInfoByKey);\n const draftRowId = `draft:${generateDraftSuffix()}`;\n const values = initializeValuesFromTemplate(template, draftRowId);\n\n set((state: DraftRowsSlice) => {\n const existing = state.draftRowsByTable[tableKey];\n\n const nextOrder = existing ? [...existing.order, draftRowId] : [draftRowId];\n const nextMap = {\n ...(existing?.map ?? {}),\n [draftRowId]: {\n id: draftRowId,\n values,\n status: 'idle' as const,\n errors: null,\n createdAt: Date.now(),\n metaVersion,\n },\n };\n\n return {\n draftRowsByTable: {\n ...state.draftRowsByTable,\n [tableKey]: {\n order: nextOrder,\n map: nextMap,\n template,\n metaVersion,\n columnOrder: [...effectiveColumnOrder],\n },\n },\n };\n });\n\n return draftRowId;\n },\n\n\t updateDraftCell: ({ tableKey, draftRowId, columnKey, value, extraValues }) => {\n\t set((state: DraftRowsSlice) => {\n\t const tableState = state.draftRowsByTable[tableKey];\n\t if (!tableState) return state;\n\n\t const existingRow = tableState.map[draftRowId];\n\t if (!existingRow) return state;\n\n\t let hasValueChanges = !deepEqual(existingRow.values[columnKey], value);\n\t if (!hasValueChanges && extraValues) {\n\t for (const [key, extraValue] of Object.entries(extraValues)) {\n\t if (!deepEqual(existingRow.values[key], extraValue)) {\n\t hasValueChanges = true;\n\t break;\n\t }\n\t }\n\t }\n\n\t const shouldResetErrors = existingRow.status === 'error' || existingRow.errors !== null;\n\t if (!hasValueChanges && !shouldResetErrors) return state;\n\n\t const updatedValues = hasValueChanges ? { ...existingRow.values, [columnKey]: deepClone(value) } : existingRow.values;\n\t if (hasValueChanges && extraValues) {\n\t for (const [key, extraValue] of Object.entries(extraValues)) {\n\t updatedValues[key] = deepClone(extraValue);\n\t }\n\t }\n\n\t const nextMap = {\n\t ...tableState.map,\n [draftRowId]: {\n ...existingRow,\n values: updatedValues,\n status: existingRow.status === 'error' ? ('idle' as const) : existingRow.status,\n errors: null,\n },\n };\n\n return {\n draftRowsByTable: {\n ...state.draftRowsByTable,\n [tableKey]: {\n ...tableState,\n map: nextMap,\n },\n },\n };\n });\n },\n\n removeDraftRow: (tableKey, draftRowId) => {\n set((state: DraftRowsSlice) => {\n const tableState = state.draftRowsByTable[tableKey];\n if (!tableState) return state;\n if (!tableState.map[draftRowId]) return state;\n\n const nextOrder = tableState.order.filter((id) => id !== draftRowId);\n const nextMap = { ...tableState.map };\n delete nextMap[draftRowId];\n\n const nextTableState: DraftRowsTableState | undefined = nextOrder.length\n ? { ...tableState, order: nextOrder, map: nextMap }\n : undefined;\n\n const nextByTable = { ...state.draftRowsByTable };\n if (nextTableState) {\n nextByTable[tableKey] = nextTableState;\n } else {\n delete nextByTable[tableKey];\n }\n\n return { draftRowsByTable: nextByTable };\n });\n },\n\n clearDraftRowsForTable: (tableKey) => {\n set((state: DraftRowsSlice) => {\n if (!state.draftRowsByTable[tableKey]) return state;\n const nextByTable = { ...state.draftRowsByTable };\n delete nextByTable[tableKey];\n return { draftRowsByTable: nextByTable };\n });\n },\n\n clearDraftRowsForDatabase: (databaseId) => {\n set((state: DraftRowsSlice) => {\n if (!databaseId || !Object.keys(state.draftRowsByTable).length) return state;\n let changed = false;\n const nextByTable: Record<string, DraftRowsTableState | undefined> = { ...state.draftRowsByTable };\n\n for (const tableKey of Object.keys(nextByTable)) {\n const parsed = parseDraftTableKey(tableKey);\n const matchesDatabase = parsed ? parsed.databaseId === databaseId : tableKey.includes(`${databaseId}::`);\n\n if (matchesDatabase) {\n delete nextByTable[tableKey];\n changed = true;\n }\n }\n\n return changed ? { draftRowsByTable: nextByTable } : state;\n });\n },\n\n clearAllDraftRows: () => {\n set((state: DraftRowsSlice) => {\n if (!Object.keys(state.draftRowsByTable).length) return state;\n return { draftRowsByTable: {} };\n });\n },\n\n\t syncDraftRowsWithMeta: (args) => {\n\t const { tableKey, columnOrder, fieldMetaByKey, relationInfoByKey, metaVersion } = args;\n\n\t set((state: DraftRowsSlice) => {\n\t const tableState = state.draftRowsByTable[tableKey];\n\t const effectiveColumnOrder = ensureColumnOrder(columnOrder, fieldMetaByKey, relationInfoByKey);\n\t const template = buildTemplate(effectiveColumnOrder, relationInfoByKey);\n\n\t if (!tableState) {\n\t return state;\n\t }\n\n\t if (tableState.order.length === 0) {\n\t const nextByTable = { ...state.draftRowsByTable };\n\t delete nextByTable[tableKey];\n\t return { draftRowsByTable: nextByTable };\n\t }\n\n\t const isSameMeta =\n\t tableState.metaVersion === metaVersion && shallowEqualArrays(tableState.columnOrder, effectiveColumnOrder);\n\n if (isSameMeta) return state;\n\n const nextMap: Record<string, DraftRow> = {};\n for (const draftId of tableState.order) {\n const row = tableState.map[draftId];\n if (!row) continue;\n\n const mergedValues: Record<string, unknown> = initializeValuesFromTemplate(template, draftId);\n for (const key of Object.keys(row.values)) {\n if (Object.prototype.hasOwnProperty.call(template, key)) {\n mergedValues[key] = deepClone(row.values[key]);\n }\n }\n\n nextMap[draftId] = {\n ...row,\n values: mergedValues,\n metaVersion,\n status: row.status === 'error' ? 'idle' as const : row.status,\n errors: row.status === 'error' ? null : row.errors,\n };\n }\n\n return {\n draftRowsByTable: {\n ...state.draftRowsByTable,\n [tableKey]: {\n order: [...tableState.order],\n map: nextMap,\n template,\n metaVersion,\n columnOrder: [...effectiveColumnOrder],\n },\n },\n };\n });\n },\n\n\t setDraftRowStatus: ({ tableKey, draftRowId, status, errors }) => {\n\t set((state: DraftRowsSlice) => {\n\t const tableState = state.draftRowsByTable[tableKey];\n\t if (!tableState) return state;\n\t const row = tableState.map[draftRowId];\n\t if (!row) return state;\n\t const nextErrors = errors ?? null;\n\t if (row.status === status && shallowEqualRecords(row.errors, nextErrors)) return state;\n\n\t const nextMap = {\n\t ...tableState.map,\n\t [draftRowId]: { ...row, status, errors: nextErrors },\n\t };\n\n return {\n draftRowsByTable: {\n ...state.draftRowsByTable,\n [tableKey]: { ...tableState, map: nextMap },\n },\n };\n });\n },\n };\n}\n\nfunction ensureColumnOrder(\n columnOrder: readonly string[],\n fieldMetaByKey: Record<string, DraftFieldMetadata | undefined>,\n relationInfoByKey?: Record<string, RelationInfo | undefined>,\n): string[] {\n if (columnOrder.length > 0) return [...columnOrder];\n\n const keys = new Set<string>();\n Object.keys(fieldMetaByKey).forEach((key) => {\n if (key) keys.add(key);\n });\n if (relationInfoByKey) {\n Object.keys(relationInfoByKey).forEach((key) => {\n if (key) keys.add(key);\n });\n }\n return Array.from(keys).sort((a, b) => a.localeCompare(b));\n}\n\nfunction buildTemplate(\n columnOrder: readonly string[],\n relationInfoByKey?: Record<string, RelationInfo | undefined>,\n): Record<string, unknown> {\n const template: Record<string, unknown> = {};\n\n for (const column of columnOrder) {\n if (!column) continue;\n const relationInfo = relationInfoByKey?.[column];\n\n if (relationInfo && (relationInfo.kind === 'hasMany' || relationInfo.kind === 'manyToMany')) {\n template[column] = [];\n } else {\n template[column] = null;\n }\n }\n\n return template;\n}\n\nfunction generateDraftSuffix(): string {\n const cryptoObj = typeof globalThis !== 'undefined' ? (globalThis as any).crypto : undefined;\n if (cryptoObj && typeof cryptoObj.getRandomValues === 'function') {\n const buffer = new Uint32Array(1);\n cryptoObj.getRandomValues(buffer);\n return buffer[0].toString(36).slice(0, 8);\n }\n return Math.random().toString(36).slice(2, 10);\n}\n\nfunction initializeValuesFromTemplate(template: Record<string, unknown>, draftRowId: string): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(template)) {\n result[key] = deepClone(value);\n }\n if (!result.id) result.id = draftRowId;\n return result;\n}\n\nfunction deepClone<T>(value: T): T {\n if (Array.isArray(value)) return value.map((item) => deepClone(item)) as unknown as T;\n if (value instanceof Date) return new Date(value.getTime()) as unknown as T;\n if (value && typeof value === 'object') {\n const result: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value as Record<string, unknown>)) {\n result[key] = deepClone(val);\n }\n return result as unknown as T;\n }\n\treturn value;\n}\n\nfunction deepEqual(a: unknown, b: unknown): boolean {\n\tif (Object.is(a, b)) return true;\n\tif (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();\n\tif (Array.isArray(a) && Array.isArray(b)) {\n\t\tif (a.length !== b.length) return false;\n\t\tfor (let i = 0; i < a.length; i += 1) {\n\t\t\tif (!deepEqual(a[i], b[i])) return false;\n\t\t}\n\t\treturn true;\n\t}\n\tif (a && b && typeof a === 'object' && typeof b === 'object') {\n\t\tconst keysA = Object.keys(a as Record<string, unknown>);\n\t\tconst keysB = Object.keys(b as Record<string, unknown>);\n\t\tif (keysA.length !== keysB.length) return false;\n\t\tfor (const key of keysA) {\n\t\t\tif (!(key in (b as Record<string, unknown>))) return false;\n\t\t\tif (!deepEqual((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key])) return false;\n\t\t}\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nfunction shallowEqualRecords(\n\ta: Record<string, string> | null,\n\tb: Record<string, string> | null,\n): boolean {\n\tif (a === b) return true;\n\tif (!a || !b) return false;\n\tconst keysA = Object.keys(a);\n\tconst keysB = Object.keys(b);\n\tif (keysA.length !== keysB.length) return false;\n\tfor (const key of keysA) {\n\t\tif (a[key] !== b[key]) return false;\n\t}\n\treturn true;\n}\n\nfunction shallowEqualArrays(a: readonly string[], b: readonly string[]): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i += 1) {\n if (a[i] !== b[i]) return false;\n }\n return true;\n}\n\nexport function computeDraftMetaSignature(\n columnOrder: readonly string[],\n fieldMetaByKey: Record<string, DraftFieldMetadata | undefined>,\n relationInfoByKey?: Record<string, RelationInfo | undefined>,\n): string {\n const signatureParts = columnOrder.map((column) => {\n const typeMeta = fieldMetaByKey[column]?.type;\n const relationMeta = relationInfoByKey?.[column];\n\n const typePart = typeMeta\n ? [\n typeMeta.gqlType ?? '',\n typeMeta.isArray ? '1' : '0',\n typeMeta.pgAlias ?? '',\n typeMeta.pgType ?? '',\n typeMeta.subtype ?? '',\n ].join(':')\n : '';\n\n const relationPart = relationMeta\n ? [relationMeta.kind ?? '', relationMeta.foreignKeyField ?? '', relationMeta.relationField ?? ''].join(':')\n : '';\n\n return `${column}|${typePart}|${relationPart}`;\n });\n\n return hashString(signatureParts.join('||'));\n}\n\nfunction hashString(input: string): string {\n let hash = 0;\n for (let i = 0; i < input.length; i += 1) {\n hash = (hash << 5) - hash + input.charCodeAt(i);\n hash |= 0;\n }\n return hash.toString(16);\n}\n","import { pluralize } from 'inflekt';\nimport { cleanTable, pgFieldToCamelCase, type CleanTable, type MetaQuery } from '@constructive-io/data';\nimport { getJunctionTableNames, isJunctionTablePure } from '../utils/relation-utils';\n\nexport type RelationKind = 'belongsTo' | 'hasOne' | 'hasMany' | 'manyToMany';\n\nexport interface RelationInfo {\n kind: RelationKind;\n relatedTable?: string;\n displayCandidates: string[];\n relationField?: string;\n foreignKeyField?: string;\n junctionTable?: string;\n junctionLeftKeyField?: string;\n junctionRightKeyField?: string;\n displayName?: string;\n}\n\nexport interface RelationInfoSlice {\n relationInfoCache: Record<string, Record<string, RelationInfo>>;\n relationInfoMapCache: Record<string, Map<string, RelationInfo>>;\n setRelationInfoForTable: (tableName: string, info: Record<string, RelationInfo>) => void;\n getRelationInfoForTable: (tableName: string) => Record<string, RelationInfo> | undefined;\n getRelationInfoMapForTable: (tableName: string) => Map<string, RelationInfo> | undefined;\n rebuildRelationInfo: (tableName: string, meta: MetaQuery | undefined) => void;\n ensureRelationInfo: (tableName: string, meta: MetaQuery | undefined) => Record<string, RelationInfo>;\n clearRelationInfoCache: () => void;\n}\n\ninterface RelationInfoState {\n relationInfoCache: Record<string, Record<string, RelationInfo>>;\n relationInfoMapCache: Record<string, Map<string, RelationInfo>>;\n}\n\ntype RelationInfoSetState = (\n partial: Partial<RelationInfoState> | ((state: RelationInfoState) => Partial<RelationInfoState>),\n) => void;\n\ntype RelationInfoGetState = () => RelationInfoState;\n\nfunction toRelationInfoMap(info: Record<string, RelationInfo>): Map<string, RelationInfo> {\n return new Map(Object.entries(info));\n}\n\nfunction setTableRelationInfo(set: RelationInfoSetState, tableName: string, info: Record<string, RelationInfo>): void {\n set((state) => ({\n relationInfoCache: { ...state.relationInfoCache, [tableName]: info },\n relationInfoMapCache: { ...state.relationInfoMapCache, [tableName]: toRelationInfoMap(info) },\n }));\n}\n\nexport function createRelationInfoSlice(set: RelationInfoSetState, get: RelationInfoGetState): RelationInfoSlice {\n return {\n relationInfoCache: {},\n relationInfoMapCache: {},\n setRelationInfoForTable: (tableName, info) => setTableRelationInfo(set, tableName, info),\n getRelationInfoForTable: (tableName) => get().relationInfoCache[tableName],\n getRelationInfoMapForTable: (tableName) => get().relationInfoMapCache[tableName],\n clearRelationInfoCache: () => set({ relationInfoCache: {}, relationInfoMapCache: {} }),\n rebuildRelationInfo: (tableName: string, meta: MetaQuery | undefined) => {\n try {\n const info = buildRelationInfoFromMeta(tableName, meta);\n if (!info) return;\n setTableRelationInfo(set, tableName, info);\n } catch {\n // ignore\n }\n },\n ensureRelationInfo: (tableName: string, meta: MetaQuery | undefined) => {\n const existing = get().relationInfoCache[tableName];\n if (existing) return existing;\n const info = buildRelationInfoFromMeta(tableName, meta) || {};\n if (Object.keys(info).length) {\n setTableRelationInfo(set, tableName, info);\n }\n return info;\n },\n };\n}\n\ntype MetaTableNode = NonNullable<NonNullable<NonNullable<MetaQuery['_meta']>['tables']>[number]>;\n\nfunction toCleanTables(meta: MetaQuery | undefined): CleanTable[] {\n const tables = meta?._meta?.tables ?? [];\n return tables.filter((table): table is MetaTableNode => table != null).map((table) => cleanTable(table));\n}\n\nfunction firstFieldName(fields: Array<{ name: string }>): string | undefined {\n return fields[0]?.name;\n}\n\n/**\n * For hasOne/hasMany relations, find the FK field in the RELATED table that\n * references the current table. relation.keys contains the PK of the current\n * table (e.g. \"id\"), but the relation editor needs the FK in the child table\n * (e.g. \"questionnaireId\") to link/unlink records.\n *\n * Resolution chain:\n * 1. Related table's belongsTo relations (from cleanTable)\n * 2. Related table's foreignKeyConstraints (from raw _meta)\n */\nfunction findForeignKeyInRelatedTable(\n currentTableName: string,\n relatedTableName: string,\n allTables: CleanTable[],\n rawMetaTables: readonly MetaTableNode[],\n): string | undefined {\n // 1. Try belongsTo on the related cleaned table\n const relatedTable = allTables.find((t) => t.name === relatedTableName);\n if (relatedTable) {\n const belongsTo = relatedTable.relations.belongsTo.find(\n (rel) => rel.referencesTable === currentTableName,\n );\n if (belongsTo?.keys?.[0]?.name) return belongsTo.keys[0].name;\n }\n\n // 2. Fall back to foreignKeyConstraints on the raw _meta related table\n const rawRelated = rawMetaTables.find((t) => t.name === relatedTableName);\n if (rawRelated) {\n // v5 nested: constraints.foreignKey[]\n const v5Fks = Array.isArray(rawRelated.constraints) ? [] : rawRelated.constraints?.foreignKey;\n // v4 flat: foreignKeyConstraints[]\n const fks = v5Fks ?? rawRelated.foreignKeyConstraints ?? [];\n for (const fk of fks) {\n if (!fk) continue;\n const refName = fk.refTable?.name;\n // refTable.name is a codec name (camelCase) — match case-insensitively\n if (refName && refName.toLowerCase() === currentTableName.toLowerCase()) {\n const fieldName = fk.fields?.[0]?.name;\n if (fieldName) return pgFieldToCamelCase(fieldName);\n }\n }\n }\n\n return undefined;\n}\n\nexport function buildRelationInfoFromMeta(\n tableName: string,\n meta: MetaQuery | undefined,\n): Record<string, RelationInfo> | null {\n const tables = toCleanTables(meta);\n const table = tables.find((candidate) => candidate.name === tableName);\n if (!table) return null;\n\n const rawMetaTables = (meta?._meta?.tables ?? []).filter(\n (t): t is MetaTableNode => t != null,\n );\n\n const PRIORITY_FIELDS = [\n 'displayName',\n 'fullName',\n 'preferredName',\n 'nickname',\n 'firstName',\n 'lastName',\n 'givenName',\n 'familyName',\n 'username',\n 'handle',\n 'email',\n 'phone',\n 'title',\n 'label',\n 'slug',\n 'code',\n 'name',\n ];\n const NAME_PATTERN = /name/i;\n\n const computeCandidates = (relatedTableName?: string): string[] => {\n if (!relatedTableName) return [];\n const related = tables.find((candidate) => candidate.name === relatedTableName);\n if (!related) return [];\n\n const fieldNamesSet = new Set<string>(related.fields.map((field) => field.name));\n const explicit = PRIORITY_FIELDS.filter((k) => fieldNamesSet.has(k));\n const explicitSet = new Set(explicit);\n\n const nameLike: string[] = [];\n for (const name of fieldNamesSet) {\n if (NAME_PATTERN.test(name) && !explicitSet.has(name)) {\n nameLike.push(name);\n }\n }\n nameLike.sort((a, b) => a.length - b.length);\n\n return Array.from(new Set([...explicit, ...nameLike]));\n };\n\n const info: Record<string, RelationInfo> = {};\n table.relations.belongsTo.forEach((relation) => {\n const displayCandidates = computeCandidates(relation.referencesTable);\n const foreignKeys = relation.keys.map((key) => key.name).filter(Boolean);\n const primaryForeignKey = foreignKeys[0];\n\n if (relation.fieldName) {\n info[relation.fieldName] = {\n kind: 'belongsTo',\n relatedTable: relation.referencesTable,\n displayCandidates,\n relationField: relation.fieldName,\n foreignKeyField: primaryForeignKey,\n };\n }\n\n foreignKeys.forEach((fk) => {\n if (!fk) return;\n info[fk] = {\n kind: 'belongsTo',\n relatedTable: relation.referencesTable,\n displayCandidates,\n relationField: relation.fieldName ?? undefined,\n foreignKeyField: fk,\n };\n });\n });\n table.relations.hasOne.forEach((relation) => {\n if (relation.fieldName) {\n // relation.keys contains the PK of the CURRENT table, not the FK in the\n // related table. Resolve the actual FK field via:\n // 1. Related table's belongsTo (cleanTable)\n // 2. Related table's foreignKeyConstraints (raw _meta)\n const fkInRelated = findForeignKeyInRelatedTable(tableName, relation.referencedByTable, tables, rawMetaTables);\n info[relation.fieldName] = {\n kind: 'hasOne',\n relatedTable: relation.referencedByTable,\n displayCandidates: computeCandidates(relation.referencedByTable),\n relationField: relation.fieldName,\n foreignKeyField: fkInRelated,\n };\n }\n });\n const junctionTableNames = getJunctionTableNames(table.relations, rawMetaTables);\n\n table.relations.hasMany.forEach((relation) => {\n if (!relation.fieldName) return;\n // Skip hasMany relations pointing to junction tables (M:N covers these)\n if (junctionTableNames.has(relation.referencedByTable)) return;\n const fkInRelated = findForeignKeyInRelatedTable(tableName, relation.referencedByTable, tables, rawMetaTables);\n info[relation.fieldName] = {\n kind: 'hasMany',\n relatedTable: relation.referencedByTable,\n displayCandidates: computeCandidates(relation.referencedByTable),\n relationField: relation.fieldName,\n foreignKeyField: fkInRelated,\n };\n });\n table.relations.manyToMany.forEach((relation) => {\n if (relation.fieldName) {\n // Prefer direct key fields from enriched cleanTable()\n let junctionLeftKeyField = relation.junctionLeftKeyFields?.[0];\n let junctionRightKeyField = relation.junctionRightKeyFields?.[0];\n\n // Fallback: derive from junction table's belongsTo relations\n if (!junctionLeftKeyField || !junctionRightKeyField) {\n const junctionTableName = relation.junctionTable;\n const junctionTable = junctionTableName\n ? tables.find((candidate) => candidate.name === junctionTableName)\n : undefined;\n const junctionBelongsTo = junctionTable?.relations.belongsTo ?? [];\n if (!junctionLeftKeyField) {\n const leftRelation = junctionBelongsTo.find((entry) => entry.referencesTable === tableName);\n junctionLeftKeyField = firstFieldName(leftRelation?.keys ?? []);\n }\n if (!junctionRightKeyField) {\n const rightRelation = junctionBelongsTo.find((entry) => entry.referencesTable === relation.rightTable);\n junctionRightKeyField = firstFieldName(rightRelation?.keys ?? []);\n }\n }\n\n // Skip non-pure junction tables — they have required fields beyond the\n // two FK columns, so the manyToMany editor cannot produce valid mutations.\n if (!isJunctionTablePure(relation.junctionTable, junctionLeftKeyField, junctionRightKeyField, rawMetaTables)) {\n return;\n }\n\n info[relation.fieldName] = {\n kind: 'manyToMany',\n relatedTable: relation.rightTable,\n displayCandidates: computeCandidates(relation.rightTable),\n relationField: relation.fieldName,\n junctionTable: relation.junctionTable,\n junctionLeftKeyField,\n junctionRightKeyField,\n displayName: pluralize(relation.rightTable),\n };\n }\n });\n\n return info;\n}\n","import { singularize } from \"inflekt\";\nimport { pgFieldToCamelCase, type CleanTable, type CleanRelations, type MetaQuery } from \"@constructive-io/data\";\n\ntype PrimitiveId = string | number | null;\n\ntype MetaTable = NonNullable<NonNullable<NonNullable<MetaQuery[\"_meta\"]>[\"tables\"]>[number]>;\n\n\n/**\n * Convert a camelCase plural codec name (as used in raw _meta relation references)\n * to PascalCase singular (matching `_meta.tables[].name` format).\n * e.g. \"formResponses\" → \"FormResponse\"\n */\nfunction codecNameToTableName(name: string): string {\n if (!name) return name;\n const singular = singularize(name);\n return singular.charAt(0).toUpperCase() + singular.slice(1);\n}\n\n/**\n * Derive all relation field names from raw table metadata relations.\n * Filters out hasMany entries that point to junction tables (those are surfaced via manyToMany),\n * and deduplicates manyToMany entries targeting the same table.\n */\nexport function getAllRelationFields(\n relations: MetaTable[\"relations\"] | null | undefined,\n metaTables?: readonly MetaTable[],\n): string[] {\n if (!relations) return [];\n\n const out: string[] = [];\n const push = (fieldName?: string | null) => {\n if (fieldName) out.push(fieldName);\n };\n\n relations.belongsTo?.forEach((rel) => push(rel?.fieldName));\n relations.hasOne?.forEach((rel) => push(rel?.fieldName));\n\n const junctionNames = new Set<string>();\n relations.manyToMany?.forEach((rel) => {\n const jtName = rel?.junctionTable?.name;\n if (!jtName) return;\n // When meta tables are available, skip non-pure junction tables\n if (metaTables) {\n const leftFk = rel?.junctionLeftKeyAttributes?.[0]?.name;\n const rightFk = rel?.junctionRightKeyAttributes?.[0]?.name;\n const leftFkCamel = leftFk ? pgFieldToCamelCase(leftFk) : undefined;\n const rightFkCamel = rightFk ? pgFieldToCamelCase(rightFk) : undefined;\n // Raw _meta codec names need conversion to match MetaTable.name format\n const jtTableName = codecNameToTableName(jtName);\n if (!isJunctionTablePure(jtTableName, leftFkCamel, rightFkCamel, metaTables)) return;\n }\n junctionNames.add(jtName);\n });\n relations.hasMany?.forEach((rel) => {\n const refName = rel?.referencedBy?.name;\n if (refName && junctionNames.has(refName)) return;\n push(rel?.fieldName);\n });\n\n const seenM2N = new Map<string, { fieldName?: string | null }>();\n relations.manyToMany?.forEach((rel) => {\n const target = rel?.rightTable?.name;\n if (!target) return;\n // Skip non-pure junction table M:N relations\n if (metaTables) {\n const jtName = rel?.junctionTable?.name;\n if (jtName) {\n const leftFk = rel?.junctionLeftKeyAttributes?.[0]?.name;\n const rightFk = rel?.junctionRightKeyAttributes?.[0]?.name;\n const leftFkCamel = leftFk ? pgFieldToCamelCase(leftFk) : undefined;\n const rightFkCamel = rightFk ? pgFieldToCamelCase(rightFk) : undefined;\n const jtTableName = codecNameToTableName(jtName);\n if (!isJunctionTablePure(jtTableName, leftFkCamel, rightFkCamel, metaTables)) return;\n }\n }\n seenM2N.set(target, rel);\n });\n seenM2N.forEach((rel) => push(rel?.fieldName));\n\n return Array.from(new Set(out));\n}\n\n/**\n * Check whether a junction table is \"pure\" — i.e. it has no required fields\n * beyond the two FK columns that form the M:N link.\n *\n * Rich entity tables that PostGraphile incidentally detects as junction tables\n * (e.g. `form_response` which has FKs to both `form_question` and `form_section`\n * but also requires `entity_id`, `session_id`, etc.) should NOT be treated as\n * simple junction tables because the manyToMany editor can only set the two FK\n * fields and would produce invalid mutations.\n */\nexport function isJunctionTablePure(\n junctionTableName: string,\n leftFkField: string | undefined,\n rightFkField: string | undefined,\n metaTables: readonly MetaTable[],\n): boolean {\n if (!leftFkField || !rightFkField) return true; // Can't verify, assume pure\n const junctionMeta = metaTables.find((t) => t?.name === junctionTableName);\n if (!junctionMeta?.fields) return true; // No field info available, assume pure\n\n const exemptFields = new Set(['id', leftFkField, rightFkField]);\n\n for (const field of junctionMeta.fields) {\n if (!field?.name) continue;\n const camelName = pgFieldToCamelCase(field.name);\n if (exemptFields.has(camelName)) continue;\n if (field.isNotNull && !field.hasDefault) return false;\n }\n return true;\n}\n\n/**\n * Collect junction table names from M:N relations.\n * Used to suppress hasMany-to-junction columns and hide junction tables from UIs.\n *\n * When `metaTables` is provided, non-pure junction tables (those with extra required\n * fields beyond the two FK columns) are excluded — their hasMany entries should remain\n * visible since the manyToMany editor cannot handle them.\n */\nexport function getJunctionTableNames(\n relations: CleanRelations,\n metaTables?: readonly MetaTable[],\n): Set<string> {\n const names = new Set<string>();\n for (const rel of relations.manyToMany) {\n if (!rel.junctionTable) continue;\n if (metaTables) {\n const leftFk = rel.junctionLeftKeyFields?.[0];\n const rightFk = rel.junctionRightKeyFields?.[0];\n if (!isJunctionTablePure(rel.junctionTable, leftFk, rightFk, metaTables)) continue;\n }\n names.add(rel.junctionTable);\n }\n return names;\n}\n\nfunction extractPrimitiveId(candidate: unknown): PrimitiveId {\n if (candidate === null || candidate === undefined) return null;\n if (typeof candidate === \"string\" || typeof candidate === \"number\") {\n return candidate;\n }\n if (typeof candidate === \"object\") {\n const record = candidate as Record<string, unknown>;\n const id = record.id;\n if (typeof id === \"string\" || typeof id === \"number\") {\n return id;\n }\n }\n return null;\n}\n\nexport function normalizeForeignKeyValue(input: unknown): unknown {\n if (input === undefined) return undefined;\n if (input === null) return null;\n\n if (Array.isArray(input)) {\n return input\n .map((entry) => extractPrimitiveId(entry))\n .filter((entry): entry is PrimitiveId => entry !== undefined);\n }\n\n return extractPrimitiveId(input);\n}\n\n/**\n * Find the foreign key field in a related table that references the current table\n */\nfunction findForeignKeyField(\n currentTableName: string,\n relatedTableName: string,\n allTables?: CleanTable[],\n): string | undefined {\n if (!allTables) return undefined;\n\n // Find the related table\n const relatedTable = allTables.find((table) => table.name === relatedTableName);\n if (!relatedTable) return undefined;\n\n // Look for a belongsTo relation in the related table that references our current table\n const belongsToRelation = relatedTable.relations.belongsTo.find(\n (relation) => relation.referencesTable === currentTableName,\n );\n\n if (belongsToRelation && belongsToRelation.keys?.[0]?.name) {\n return belongsToRelation.keys[0].name;\n }\n\n return undefined;\n}\n\nexport interface RelationshipInfo {\n relationType: \"belongsTo\" | \"hasOne\" | \"hasMany\" | \"manyToMany\";\n relationField: string;\n relatedTableName: string;\n foreignKeyField?: string;\n junctionTableName?: string;\n junctionLeftKey?: string;\n junctionRightKey?: string;\n}\n\n/**\n * Extract relationship information from table metadata for a specific field\n * For hasMany/hasOne relations, we need to find the actual foreign key field in the related table\n */\nexport function getRelationshipInfo(\n currentTable: CleanTable,\n relationFieldName: string,\n allTables?: CleanTable[],\n): RelationshipInfo | null {\n const { relations } = currentTable;\n\n // Check belongsTo relations\n const belongsToRelation = relations.belongsTo.find((rel) => rel.fieldName === relationFieldName);\n if (belongsToRelation) {\n // For belongsTo: get the foreign key field name from the keys array\n const foreignKeyField = belongsToRelation.keys?.[0]?.name;\n return {\n relationType: \"belongsTo\",\n relationField: relationFieldName,\n relatedTableName: belongsToRelation.referencesTable,\n foreignKeyField: foreignKeyField,\n };\n }\n\n // Check hasOne relations\n const hasOneRelation = relations.hasOne.find((rel) => rel.fieldName === relationFieldName);\n if (hasOneRelation) {\n // For hasOne: find the foreign key field in the related table that references our current table\n const foreignKeyField = findForeignKeyField(\n currentTable.name,\n hasOneRelation.referencedByTable,\n allTables,\n );\n return {\n relationType: \"hasOne\",\n relationField: relationFieldName,\n relatedTableName: hasOneRelation.referencedByTable,\n foreignKeyField: foreignKeyField,\n };\n }\n\n // Check hasMany relations\n const hasManyRelation = relations.hasMany.find((rel) => rel.fieldName === relationFieldName);\n if (hasManyRelation) {\n // For hasMany: find the foreign key field in the related table that references our current table\n const foreignKeyField = findForeignKeyField(\n currentTable.name,\n hasManyRelation.referencedByTable,\n allTables,\n );\n return {\n relationType: \"hasMany\",\n relationField: relationFieldName,\n relatedTableName: hasManyRelation.referencedByTable,\n foreignKeyField: foreignKeyField,\n };\n }\n\n // Check manyToMany relations\n const manyToManyRelation = relations.manyToMany.find(\n (rel) => rel.fieldName === relationFieldName,\n );\n if (manyToManyRelation) {\n return {\n relationType: \"manyToMany\",\n relationField: relationFieldName,\n relatedTableName: manyToManyRelation.rightTable,\n junctionTableName: manyToManyRelation.junctionTable,\n junctionLeftKey: manyToManyRelation.junctionLeftKeyFields?.[0],\n junctionRightKey: manyToManyRelation.junctionRightKeyFields?.[0],\n };\n }\n\n return null;\n}\n\n/**\n * Get a display-friendly label from a record using common field patterns\n */\nconst DISPLAY_LABEL_FIELDS = [\n \"name\", \"title\", \"label\", \"displayName\", \"fullName\",\n \"email\", \"username\", \"description\", \"code\",\n];\n\nexport function getRecordDisplayLabel(record: any): string {\n if (!record || typeof record !== \"object\") {\n return String(record || \"\");\n }\n\n // Try common display field patterns\n for (const field of DISPLAY_LABEL_FIELDS) {\n if (record[field] != null && String(record[field]).trim()) {\n return String(record[field]);\n }\n }\n\n // Fallback to ID\n if (record.id != null) {\n return `Record ${record.id}`;\n }\n\n return \"Unknown Record\";\n}\n\n/**\n * Get record ID, handling different ID field patterns\n */\nexport function getRecordId(record: any): string {\n if (!record || typeof record !== \"object\") {\n return String(record || \"\");\n }\n\n // Try common ID field patterns\n const idFields = [\"id\", \"uuid\", \"_id\", \"pk\"];\n\n for (const field of idFields) {\n if (record[field] != null) {\n return String(record[field]);\n }\n }\n\n // Fallback to first field value\n const keys = Object.keys(record);\n if (keys.length > 0) {\n return String(record[keys[0]] || \"\");\n }\n\n return \"\";\n}\n","const KEY_PREFIX = 'sheets-auth-token';\n\nfunction storageKey(databaseId: string): string {\n\treturn `${KEY_PREFIX}:${databaseId}`;\n}\n\nfunction getStorage(): Storage | null {\n\tif (typeof window === 'undefined') return null;\n\ttry {\n\t\treturn window.localStorage;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport interface StoredToken {\n\taccessToken: string;\n\texpiresAt: string;\n}\n\nexport function getStoredToken(databaseId: string): StoredToken | null {\n\tconst storage = getStorage();\n\tif (!storage) return null;\n\n\ttry {\n\t\tconst raw = storage.getItem(storageKey(databaseId));\n\t\tif (!raw) return null;\n\t\tconst parsed = JSON.parse(raw) as StoredToken;\n\t\tif (!parsed.accessToken || !parsed.expiresAt) return null;\n\t\treturn parsed;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport function setStoredToken(databaseId: string, accessToken: string, expiresAt: string): void {\n\tconst storage = getStorage();\n\tif (!storage) return;\n\n\ttry {\n\t\tconst data: StoredToken = { accessToken, expiresAt };\n\t\tstorage.setItem(storageKey(databaseId), JSON.stringify(data));\n\t} catch {\n\t\t// Silently fail — localStorage might be full or unavailable\n\t}\n}\n\nexport function clearStoredToken(databaseId: string): void {\n\tconst storage = getStorage();\n\tif (!storage) return;\n\n\ttry {\n\t\tstorage.removeItem(storageKey(databaseId));\n\t} catch {\n\t\t// Silently fail\n\t}\n}\n","/**\n * Injectable logger seam for @constructive-io/sheets.\n *\n * The host app may provide a custom logger via SheetsConfig.logger. The provider\n * installs it into this module singleton (see sheets-provider.tsx), so any module\n * or hook can log without threading the logger through props/context.\n *\n * Default behaviour matches the prior console.* calls. `debug` is omitted from the\n * default logger (no-op) so verbose diagnostics stay silent unless a host opts in.\n */\nexport interface SheetsLogger {\n\tdebug?(msg: string, ctx?: unknown): void;\n\twarn(msg: string, ctx?: unknown): void;\n\terror(msg: string, ctx?: unknown): void;\n}\n\nconst defaultLogger: SheetsLogger = {\n\twarn: (...a) => console.warn(...a),\n\terror: (...a) => console.error(...a),\n\t// debug omitted = no-op\n};\n\nlet active: SheetsLogger = defaultLogger;\n\n/**\n * Install (or reset) the active logger. Pass a host logger to override; pass\n * null/undefined to restore the default. Host overrides are merged over the\n * default so a partial logger still gets working warn/error.\n */\nexport function setSheetsLogger(l?: SheetsLogger | null): void {\n\tactive = l ? { ...defaultLogger, ...l } : defaultLogger;\n}\n\n/** Get the active logger. Safe to call anywhere (returns the default until set). */\nexport function sheetsLogger(): SheetsLogger {\n\treturn active;\n}\n","/**\n * Locale seam for @constructive-io/sheets.\n *\n * The host app may set a BCP-47 locale via SheetsConfig.locale. The provider\n * installs it into this module singleton (see sheets-provider.tsx), so any cell\n * renderer / editor can format dates and numbers locale-aware without threading\n * the locale through props/context. Defaults to 'en-US' (the prior hardcoded\n * behavior), so omitting `locale` changes nothing.\n */\nconst DEFAULT_LOCALE = 'en-US';\n\nlet active: string = DEFAULT_LOCALE;\n\n/** Install (or reset) the active locale. Pass null/undefined to restore the default. */\nexport function setSheetsLocale(locale?: string | null): void {\n\tactive = locale || DEFAULT_LOCALE;\n}\n\n/** Get the active locale (BCP-47). Safe to call anywhere; returns 'en-US' until set. */\nexport function sheetsLocale(): string {\n\treturn active;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACaA,IAAAA,gBAAwB;AACxB,IAAAC,kBAAsB;AAEtB,IAAAC,sBAA4B;AAE5B,IAAAC,eAMO;;;ACxBP,IAAAC,gBAA2C;AAC3C,yBAAiD;;;ACDjD,mBAA0C;AA+DnC,IAAM,oBAAgB,4BAAyC,IAAI;;;AC9D1E,qBAAsB;AAEtB,kBAA4D;AAqP5D,IAAAC,eAA0B;AAxM1B,SAAS,iBAAiB,UAAsC;AAC/D,MAAI,OAAO,aAAa,SAAU,QAAO;AACzC,MAAI,oBAAoB,OAAQ,QAAO,SAAS,SAAS;AACzD,MAAI,YAAY,OAAO,aAAa,YAAY,UAAW,UAA2B;AACrF,eAAO,sBAAM,QAAwB;AAAA,EACtC;AACA,MAAI,aAAa,QAAQ,aAAa,QAAW;AAChD,UAAM,wBAAY,WAAW,6CAA6C;AAAA,EAC3E;AACA,SAAO,OAAO,QAAQ;AACvB;AAgBA,SAAS,eAAe,SAAsC;AAC7D,QAAM,aAAa,OAAO,WAAW,EAAE,EAAE,YAAY;AACrD,SACC,WAAW,SAAS,iBAAiB,KACrC,WAAW,SAAS,cAAc,KAClC,WAAW,SAAS,gBAAgB;AAEtC;AAEA,SAAS,qBAAqB,UAA2B,aAA4C;AACpG,MAAI,CAAC,SAAS,QAAQ,OAAQ,QAAO;AAErC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M,SAAS,QAAQ,QAAQ,OAAO;AAAA,IAC9C,EAAE,MAAM,QAAQ,SAAS,UAAU,QAAQ,OAAO;AAAA,IAClD,EAAE,MAAM,SAAS,SAAS,UAAU,QAAQ,OAAO;AAAA,IACnD,EAAE,MAAM,YAAY,SAAS,WAAW,QAAQ,UAAU;AAAA,IAC1D,EAAE,MAAM,aAAa,SAAS,YAAY,QAAQ,cAAc;AAAA,EACjE;AAAA,EACA,MAAM;AAAA,IACL;AAAA,MACC,IAAI;AAAA,MACJ,MAAM;AAAA,MACN,OAAO;AAAA,MACP,UAAU;AAAA,MACV,WAAW;AAAA,IACZ;AAAA,IACA;AAAA,MACC,IAAI;AAAA,MACJ,MAAM;AAAA,MACN,OAAO;AAAA,MACP,UAAU;AAAA,MACV,WAAW;AAAA,IACZ;AAAA,EACD;AACD;","names":["import_react","import_graphql","import_react_query","import_data","import_react","import_data","import_react","import_inflekt","import_data","import_data","active","import_jsx_runtime","documentToString"]}
|
|
1
|
+
{"version":3,"sources":["../src/testing/index.ts","../src/testing/mock-sheets-provider.tsx","../src/context/sheets-provider.tsx","../src/context/sheets-context.ts","../src/context/sheets-execute.ts","../src/context/sheets-upload-presigned.ts","../src/store/sheets-store.ts","../src/store/draft-rows-slice.ts","../src/store/relation-info-slice.ts","../src/utils/relation-utils.ts","../src/auth/utils/token-store.ts","../src/utils/sheets-logger.ts","../src/utils/sheets-i18n.ts","../src/hooks/query-keys.ts","../src/testing/meta-contract-fixture.ts"],"sourcesContent":["// Public '/testing' subpath — consumer test harness for @constructive-io/sheets.\n// Not part of the core graph; bundled separately so production consumers never\n// pull in the in-memory mock backend.\nexport * from './mock-sheets-provider';\nexport * from './meta-contract-fixture';\n","// Consumer test harness for @constructive-io/sheets.\n//\n// Shipped at the '/testing' subpath — NOT part of the core graph. Lets a\n// consumer mount a <Sheets> grid in jsdom/vitest with zero network: a tiny\n// in-memory PostGraphile-shaped backend that serves the `_meta` introspection,\n// list connections, and create/update/delete mutations, while recording every\n// mutation for assertions.\n//\n// This file intentionally uses a few test-grade casts on the mock GraphQL\n// responses (see the `as unknown as MetaQuery` in `buildMetaResponse` and the\n// `as File` narrowing in `executeUpload`). It is a deliberately partial\n// PostGraphile emulator — just enough to render a grid and assert mutations —\n// so the casts are scoped, documented, and never leak into the core graph.\nimport { useMemo } from 'react';\nimport { print } from 'graphql';\nimport type { DocumentNode } from 'graphql';\nimport { QueryClient } from '@tanstack/react-query';\n\nimport {\n\ttoCamelCasePlural,\n\ttoCamelCaseSingular,\n\ttoCreateMutationName,\n\ttoUpdateMutationName,\n\ttoDeleteMutationName,\n} from '@constructive-io/data';\nimport type { MetaQuery } from '@constructive-io/data';\n\nimport { SheetsProvider } from '../context/sheets-provider';\nimport type { SheetsExecuteFn, SheetsUploadFn, SheetsUploadOptions } from '../context/sheets-execute';\nimport { createMetaContractFixture } from './meta-contract-fixture';\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface MockTableField {\n\tname: string;\n\tgqlType: string;\n\tisArray?: boolean;\n\tpgType?: string;\n\tsubtype?: string;\n}\n\nexport interface MockTable {\n\tname: string;\n\tfields: MockTableField[];\n\trows: Record<string, unknown>[];\n\t/** GraphQL field names in PK order. Defaults to `['id']` when an id field exists. */\n\tprimaryKeyFields?: string[];\n}\n\nexport interface RecordedMutation {\n\top: 'create' | 'update' | 'delete' | 'upload';\n\ttableName: string;\n\tvariables: Record<string, unknown>;\n\tat: number;\n}\n\nexport interface MockSheetsOptions {\n\ttables: MockTable[];\n\tonMutation?: (m: RecordedMutation) => void;\n}\n\nexport interface MockExecuteHandle {\n\texecute: SheetsExecuteFn;\n\texecuteUpload: SheetsUploadFn;\n\tmutations: RecordedMutation[];\n\treset(): void;\n}\n\n// ============================================================================\n// Document stringification (mirrors context/sheets-execute.ts)\n// ============================================================================\n\ntype ExecutableDocument = DocumentNode | string | unknown;\n\nfunction documentToString(document: ExecutableDocument): string {\n\tif (typeof document === 'string') return document;\n\tif (document instanceof String) return document.toString();\n\tif (document && typeof document === 'object' && 'kind' in (document as DocumentNode)) {\n\t\treturn print(document as DocumentNode);\n\t}\n\treturn String(document ?? '');\n}\n\n// ============================================================================\n// Meta response synthesis\n// ============================================================================\n\nfunction buildMetaField(field: MockTableField, primaryKeyFields: ReadonlySet<string>) {\n\treturn {\n\t\tname: field.name,\n\t\tisPrimaryKey: primaryKeyFields.has(field.name),\n\t\tisNotNull: false,\n\t\thasDefault: false,\n\t\ttype: {\n\t\t\tgqlType: field.gqlType,\n\t\t\tisArray: field.isArray ?? false,\n\t\t\tpgType: field.pgType ?? 'text',\n\t\t\tisNotNull: false,\n\t\t\thasDefault: false,\n\t\t\tsubtype: field.subtype ?? null,\n\t\t},\n\t};\n}\n\nfunction buildMetaTable(table: MockTable) {\n\tconst primaryKeyFields = table.primaryKeyFields ?? (\n\t\ttable.fields.some((field) => field.name === 'id') ? ['id'] : []\n\t);\n\tconst primaryKeySet = new Set(primaryKeyFields);\n\tconst primaryKeyMetaFields = table.fields\n\t\t.filter((field) => primaryKeySet.has(field.name))\n\t\t.map((field) => buildMetaField(field, primaryKeySet));\n\treturn {\n\t\tname: table.name,\n\t\tschemaName: 'public',\n\t\tquery: {\n\t\t\tall: toCamelCasePlural(table.name),\n\t\t\tcreate: toCreateMutationName(table.name),\n\t\t\tdelete: toDeleteMutationName(table.name),\n\t\t\tone: toCamelCaseSingular(table.name),\n\t\t\tupdate: toUpdateMutationName(table.name),\n\t\t},\n\t\tfields: table.fields.map((field) => buildMetaField(field, primaryKeySet)),\n\t\tinflection: {\n\t\t\tallRows: toCamelCasePlural(table.name),\n\t\t\tconnection: toCamelCasePlural(table.name),\n\t\t\ttableType: table.name,\n\t\t},\n\t\tindexes: [],\n\t\tconstraints: {\n\t\t\tprimaryKey: primaryKeyMetaFields.length > 0\n\t\t\t\t? { name: `${table.name}_pkey`, fields: primaryKeyMetaFields }\n\t\t\t\t: null,\n\t\t\tunique: [],\n\t\t\tforeignKey: [],\n\t\t},\n\t\tforeignKeyConstraints: [],\n\t\tprimaryKeyConstraints: primaryKeyMetaFields.length > 0\n\t\t\t? [{ name: `${table.name}_pkey`, fields: primaryKeyMetaFields }]\n\t\t\t: [],\n\t\tuniqueConstraints: [],\n\t\trelations: { belongsTo: [], has: [], hasOne: [], hasMany: [], manyToMany: [] },\n\t};\n}\n\n// Pragmatic test-grade cast: we synthesize a loose subset of the `_meta`\n// introspection shape (enough for cleanTable + the grid render path). The full\n// MetaschemaTable union has many optional v4/v5 fields we don't populate, so a\n// single structural cast keeps this fixture readable without re-declaring the\n// entire schema. This is test-only code on a separate subpath.\nfunction buildMetaResponse(tables: MockTable[]): MetaQuery {\n\treturn {\n\t\t_meta: {\n\t\t\ttables: tables.map(buildMetaTable),\n\t\t},\n\t} as unknown as MetaQuery;\n}\n\n// ============================================================================\n// List response synthesis\n// ============================================================================\n\nfunction buildListResponse(table: MockTable): Record<string, unknown> {\n\tconst field = toCamelCasePlural(table.name);\n\treturn {\n\t\t[field]: {\n\t\t\tnodes: table.rows,\n\t\t\ttotalCount: table.rows.length,\n\t\t\tpageInfo: {\n\t\t\t\thasNextPage: false,\n\t\t\t\thasPreviousPage: false,\n\t\t\t\tendCursor: null,\n\t\t\t\tstartCursor: null,\n\t\t\t},\n\t\t},\n\t};\n}\n\n// ============================================================================\n// Mutation row synthesis\n// ============================================================================\n\nlet mockIdCounter = 0;\n\nfunction synthesizeId(): string {\n\tmockIdCounter += 1;\n\treturn `mock-${mockIdCounter}`;\n}\n\nfunction extractMutationInput(variables: Record<string, unknown> | undefined): Record<string, unknown> {\n\tconst input = variables?.input;\n\treturn input && typeof input === 'object' ? (input as Record<string, unknown>) : {};\n}\n\nfunction synthesizeCreatedRow(\n\ttable: MockTable,\n\tsingular: string,\n\tvariables: Record<string, unknown> | undefined,\n): Record<string, unknown> {\n\tconst input = extractMutationInput(variables);\n\tconst data = (input[singular] as Record<string, unknown>) ?? {};\n\tconst row: Record<string, unknown> = { id: synthesizeId(), ...data };\n\ttable.rows.push(row);\n\treturn row;\n}\n\nfunction synthesizeUpdatedRow(\n\ttable: MockTable,\n\tvariables: Record<string, unknown> | undefined,\n): Record<string, unknown> {\n\tconst input = extractMutationInput(variables);\n\tconst id = input.id;\n\t// Patch field name varies by entity (e.g. `userPatch`); take the first\n\t// object-valued non-id key as the patch payload.\n\tlet patch: Record<string, unknown> = {};\n\tfor (const [key, value] of Object.entries(input)) {\n\t\tif (key === 'id') continue;\n\t\tif (value && typeof value === 'object') {\n\t\t\tpatch = value as Record<string, unknown>;\n\t\t\tbreak;\n\t\t}\n\t}\n\tconst existing = table.rows.find((r) => r.id === id);\n\tconst merged: Record<string, unknown> = { ...(existing ?? { id }), ...patch };\n\tif (existing) {\n\t\tObject.assign(existing, patch);\n\t} else {\n\t\ttable.rows.push(merged);\n\t}\n\treturn merged;\n}\n\n// ============================================================================\n// Detection helpers\n// ============================================================================\n\nfunction isMetaQuery(query: string): boolean {\n\treturn query.includes('_meta');\n}\n\nfunction isMutationDocument(query: string): boolean {\n\t// PostGraphile mutation docs are `mutation Xxx(...) { ... }`; a leading\n\t// `mutation` keyword disambiguates them from list queries that may select a\n\t// relation field whose name collides with a mutation name as a substring.\n\treturn /(^|\\s)mutation(\\s|\\{)/.test(query);\n}\n\nfunction findMutationTable(\n\tquery: string,\n\ttables: MockTable[],\n): { table: MockTable; op: 'create' | 'update' | 'delete'; mutationName: string; singular: string } | null {\n\t// Longest-match: a table whose mutation name is a substring of another's\n\t// (e.g. createUser vs createUserProfile) must not win over the exact one.\n\tlet best: { table: MockTable; op: 'create' | 'update' | 'delete'; mutationName: string; singular: string } | null = null;\n\tfor (const table of tables) {\n\t\tconst candidates: Array<{ op: 'create' | 'update' | 'delete'; mutationName: string }> = [\n\t\t\t{ op: 'create', mutationName: toCreateMutationName(table.name) },\n\t\t\t{ op: 'update', mutationName: toUpdateMutationName(table.name) },\n\t\t\t{ op: 'delete', mutationName: toDeleteMutationName(table.name) },\n\t\t];\n\t\tfor (const c of candidates) {\n\t\t\tif (query.includes(c.mutationName) && (!best || c.mutationName.length > best.mutationName.length)) {\n\t\t\t\tbest = { table, op: c.op, mutationName: c.mutationName, singular: toCamelCaseSingular(table.name) };\n\t\t\t}\n\t\t}\n\t}\n\treturn best;\n}\n\nfunction findListTable(query: string, tables: MockTable[]): MockTable | null {\n\t// Longest-match for the same substring-collision reason.\n\tlet best: MockTable | null = null;\n\tlet bestLen = 0;\n\tfor (const table of tables) {\n\t\tconst plural = toCamelCasePlural(table.name);\n\t\tif (query.includes(plural) && plural.length > bestLen) {\n\t\t\tbest = table;\n\t\t\tbestLen = plural.length;\n\t\t}\n\t}\n\treturn best;\n}\n\n// ============================================================================\n// Factory\n// ============================================================================\n\nexport function createMockExecute(opts: MockSheetsOptions): MockExecuteHandle {\n\tconst mutations: RecordedMutation[] = [];\n\n\tfunction record(m: RecordedMutation) {\n\t\tmutations.push(m);\n\t\topts.onMutation?.(m);\n\t}\n\n\tconst execute: SheetsExecuteFn = async <T = unknown>(\n\t\tdocument: ExecutableDocument,\n\t\tvariables?: Record<string, unknown>,\n\t): Promise<T> => {\n\t\tconst query = documentToString(document);\n\n\t\t// 1. Contract preflight, then `_meta` data.\n\t\tif (query.includes('ConstructiveMetaContract')) {\n\t\t\treturn createMetaContractFixture() as T;\n\t\t}\n\n\t\tif (isMetaQuery(query)) {\n\t\t\treturn buildMetaResponse(opts.tables) as T;\n\t\t}\n\n\t\t// 2. Mutations — detected by a create/update/delete mutation name.\n\t\tconst mutationMatch = isMutationDocument(query) ? findMutationTable(query, opts.tables) : null;\n\t\tif (mutationMatch) {\n\t\t\tconst { table, op, mutationName, singular } = mutationMatch;\n\t\t\trecord({ op, tableName: table.name, variables: variables ?? {}, at: Date.now() });\n\n\t\t\tif (op === 'delete') {\n\t\t\t\tconst input = extractMutationInput(variables);\n\t\t\t\tconst id = input.id ?? null;\n\t\t\t\ttable.rows = table.rows.filter((r) => r.id !== id);\n\t\t\t\treturn { [mutationName]: { deletedNodeId: id, clientMutationId: null } } as T;\n\t\t\t}\n\n\t\t\tconst row =\n\t\t\t\top === 'create'\n\t\t\t\t\t? synthesizeCreatedRow(table, singular, variables)\n\t\t\t\t\t: synthesizeUpdatedRow(table, variables);\n\t\t\treturn { [mutationName]: { [singular]: row } } as T;\n\t\t}\n\n\t\t// 3. List query (table connection) — detected by the camelPlural field.\n\t\tconst listTable = findListTable(query, opts.tables);\n\t\tif (listTable) {\n\t\t\treturn buildListResponse(listTable) as T;\n\t\t}\n\n\t\t// Unknown operation: return an empty object so callers degrade gracefully.\n\t\treturn {} as T;\n\t};\n\n\tconst executeUpload: SheetsUploadFn = async (\n\t\tfile: File,\n\t\tpath?: string,\n\t\toptions?: SheetsUploadOptions,\n\t): Promise<{ url: string }> => {\n\t\tconst name = (file as File)?.name ?? 'file';\n\t\trecord({\n\t\t\top: 'upload',\n\t\t\ttableName: options?.tableName ?? '',\n\t\t\tvariables: {\n\t\t\t\tname,\n\t\t\t\t...(path !== undefined && { path }),\n\t\t\t\t...(options?.fieldName !== undefined && { fieldName: options.fieldName }),\n\t\t\t\t...(options?.recordId !== undefined && { recordId: options.recordId }),\n\t\t\t},\n\t\t\tat: Date.now(),\n\t\t});\n\t\treturn { url: 'mock://uploaded/' + name };\n\t};\n\n\tfunction reset() {\n\t\tmutations.length = 0;\n\t}\n\n\treturn { execute, executeUpload, mutations, reset };\n}\n\n// ============================================================================\n// Provider\n// ============================================================================\n\nexport interface MockSheetsProviderProps {\n\toptions: MockSheetsOptions;\n\tchildren: React.ReactNode;\n}\n\nexport function MockSheetsProvider({ options, children }: MockSheetsProviderProps) {\n\t// Build the mock backend + an isolated QueryClient ONCE per mount. Tests that\n\t// need a fresh harness should remount (e.g. via `key`), so an empty dep array\n\t// is correct — `options` is treated as mount-time configuration.\n\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\tconst { execute, executeUpload } = useMemo(() => createMockExecute(options), []);\n\n\t// eslint-disable-next-line react-hooks/exhaustive-deps\n\tconst queryClient = useMemo(\n\t\t() =>\n\t\t\tnew QueryClient({\n\t\t\t\tdefaultOptions: {\n\t\t\t\t\tqueries: { retry: false, gcTime: 0 },\n\t\t\t\t\tmutations: { retry: false },\n\t\t\t\t},\n\t\t\t}),\n\t\t[],\n\t);\n\n\treturn (\n\t\t<SheetsProvider\n\t\t\tconfig={{\n\t\t\t\tendpoint: 'mock://sheets',\n\t\t\t\tauth: { mode: 'embedded', getToken: () => 'test' },\n\t\t\t\texecute,\n\t\t\t\texecuteUpload,\n\t\t\t\tqueryClient,\n\t\t\t}}\n\t\t>\n\t\t\t{children}\n\t\t</SheetsProvider>\n\t);\n}\n\n// ============================================================================\n// Ready fixture\n// ============================================================================\n\nexport const usersFixture: MockTable = {\n\tname: 'users',\n\tfields: [\n\t\t{ name: 'id', gqlType: 'UUID', pgType: 'uuid' },\n\t\t{ name: 'name', gqlType: 'String', pgType: 'text' },\n\t\t{ name: 'email', gqlType: 'String', pgType: 'text' },\n\t\t{ name: 'isActive', gqlType: 'Boolean', pgType: 'boolean' },\n\t\t{ name: 'createdAt', gqlType: 'Datetime', pgType: 'timestamptz' },\n\t],\n\trows: [\n\t\t{\n\t\t\tid: '00000000-0000-0000-0000-000000000001',\n\t\t\tname: 'Ada Lovelace',\n\t\t\temail: 'ada@example.com',\n\t\t\tisActive: true,\n\t\t\tcreatedAt: '2024-01-01T00:00:00Z',\n\t\t},\n\t\t{\n\t\t\tid: '00000000-0000-0000-0000-000000000002',\n\t\t\tname: 'Alan Turing',\n\t\t\temail: 'alan@example.com',\n\t\t\tisActive: false,\n\t\t\tcreatedAt: '2024-01-02T00:00:00Z',\n\t\t},\n\t],\n};\n","import { useEffect, useId, useMemo, useRef } from 'react';\nimport { QueryClient, QueryClientProvider } from '@tanstack/react-query';\nimport { useStore as useZustandStore, type StoreApi } from 'zustand';\n\nimport { SheetsContext, type SheetsConfig, type SheetsContextValue, type SheetsScopeKey } from './sheets-context';\nimport { createSheetsExecute, createSheetsUpload, type SheetsExecuteFn, type SheetsUploadFn } from './sheets-execute';\nimport { createSheetsStore, SheetsStoreContext, type SheetsStoreState } from '../store/sheets-store';\nimport { getStoredToken } from '../auth/utils/token-store';\nimport { setSheetsLogger } from '../utils/sheets-logger';\nimport { setSheetsLocale } from '../utils/sheets-i18n';\nimport { sheetsQueryKeys } from '../hooks/query-keys';\n\ninterface SheetsProviderProps {\n\tconfig: SheetsConfig;\n\tchildren: React.ReactNode;\n}\n\nexport function SheetsProvider({ config, children }: SheetsProviderProps) {\n\tconst providerInstanceId = useId();\n\t// Create store once\n\tconst storeRef = useRef<StoreApi<SheetsStoreState> | null>(null);\n\tif (!storeRef.current) {\n\t\tstoreRef.current = createSheetsStore();\n\t}\n\tconst store = storeRef.current;\n\tconst standaloneIdentityKey = useZustandStore(store, (state) => state.identityKey);\n\tconst standaloneAccessToken = useZustandStore(store, (state) => state.accessToken);\n\n\t// Install the host logger + locale synchronously so they apply before first paint.\n\tsetSheetsLogger(config.logger);\n\tsetSheetsLocale(config.locale);\n\n\t// Keep the module singletons in sync if the host swaps them across renders.\n\tuseEffect(() => {\n\t\tsetSheetsLogger(config.logger);\n\t\tsetSheetsLocale(config.locale);\n\t}, [config.logger, config.locale]);\n\n\t// Restore persisted token for standalone mode\n\tuseEffect(() => {\n\t\tconst store = storeRef.current?.getState();\n\t\tif (!store) return;\n\n\t\tif (config.auth.mode !== 'standalone') {\n\t\t\t// Prevent leaking stale standalone tokens when switching auth modes.\n\t\t\tstore.setUnauthenticated();\n\t\t\treturn;\n\t\t}\n\t\tconst databaseId = config.databaseId || 'default';\n\t\tconst stored = getStoredToken(databaseId);\n\t\tif (!stored) {\n\t\t\tstore.setUnauthenticated();\n\t\t\treturn;\n\t\t}\n\n\t\t// Only restore if not expired\n\t\tconst expiresAt = new Date(stored.expiresAt);\n\t\tif (expiresAt > new Date()) {\n\t\t\tstore.setAuthenticated(stored.accessToken, stored.expiresAt, stored.identityKey ?? null);\n\t\t\treturn;\n\t\t}\n\n\t\tstore.setUnauthenticated();\n\t}, [config.auth.mode, config.databaseId]);\n\n\t// Always provide a QueryClient context. If consumer injects one, reuse it.\n\tconst internalQueryClient = useMemo(\n\t\t() =>\n\t\t\tnew QueryClient({\n\t\t\t\tdefaultOptions: {\n\t\t\t\t\tqueries: {\n\t\t\t\t\t\tstaleTime: 5 * 60 * 1000,\n\t\t\t\t\t\tgcTime: 30 * 60 * 1000,\n\t\t\t\t\t\tretry: 1,\n\t\t\t\t\t},\n\t\t\t\t},\n\t\t\t}),\n\t\t[],\n\t);\n\tconst queryClient = config.queryClient ?? internalQueryClient;\n\n\t// Token getter: embedded mode uses config.auth.getToken, standalone uses store\n\tconst getToken = useMemo(() => {\n\t\tif (config.auth.mode === 'embedded') {\n\t\t\treturn config.auth.getToken;\n\t\t}\n\t\t// Standalone: read from store\n\t\treturn () => store.getState().accessToken ?? null;\n\t}, [config.auth, store]);\n\n\t// Create execute function\n\tconst execute: SheetsExecuteFn = useMemo(() => {\n\t\tif (config.execute) return config.execute;\n\t\treturn createSheetsExecute(config, getToken);\n\t}, [config, getToken]);\n\n\t// Create upload function\n\tconst executeUpload: SheetsUploadFn = useMemo(() => {\n\t\tif (config.executeUpload) return config.executeUpload;\n\t\treturn createSheetsUpload(config, getToken);\n\t}, [config, getToken]);\n\n\tconst configuredIdentityKey =\n\t\tconfig.auth.mode === 'embedded'\n\t\t\t? (config.auth.getIdentityKey?.() ?? null)\n\t\t\t: standaloneIdentityKey;\n\tconst activeToken = config.auth.mode === 'embedded' ? config.auth.getToken() : standaloneAccessToken;\n\tconst authGenerationRef = useRef({ mode: config.auth.mode, token: activeToken, generation: 0 });\n\tif (\n\t\tauthGenerationRef.current.mode !== config.auth.mode ||\n\t\tauthGenerationRef.current.token !== activeToken\n\t) {\n\t\tauthGenerationRef.current = {\n\t\t\tmode: config.auth.mode,\n\t\t\ttoken: activeToken,\n\t\t\tgeneration: authGenerationRef.current.generation + 1,\n\t\t};\n\t}\n\t// If an older host has not supplied a user id, isolate each observed auth\n\t// token generation behind an opaque provider-local key. Tokens never enter\n\t// TanStack Query keys or devtools.\n\tconst identityKey =\n\t\tconfiguredIdentityKey ??\n\t\t`anonymous:${providerInstanceId}:${authGenerationRef.current.generation}`;\n\n\t// Scope metadata, rows, and mutations by endpoint and non-secret identity.\n\tconst scopeKey: SheetsScopeKey = useMemo(\n\t\t() => ({\n\t\t\tdatabaseId: config.databaseId ?? null,\n\t\t\tendpoint: config.endpoint,\n\t\t\tidentityKey,\n\t\t}),\n\t\t[config.databaseId, config.endpoint, identityKey],\n\t);\n\n\t// Changing database, endpoint, or user invalidates in-flight work from the\n\t// previous scope. Its cached data remains isolated under its old key.\n\tuseEffect(() => {\n\t\treturn () => {\n\t\t\tvoid queryClient.cancelQueries({ queryKey: sheetsQueryKeys.scope(scopeKey) });\n\t\t};\n\t}, [queryClient, scopeKey]);\n\n\tconst contextValue: SheetsContextValue = useMemo(\n\t\t() => ({ config, execute, executeUpload, scopeKey }),\n\t\t[config, execute, executeUpload, scopeKey],\n\t);\n\n\treturn (\n\t\t<QueryClientProvider client={queryClient}>\n\t\t\t<SheetsStoreContext.Provider value={store}>\n\t\t\t\t<SheetsContext.Provider value={contextValue}>{children}</SheetsContext.Provider>\n\t\t\t</SheetsStoreContext.Provider>\n\t\t</QueryClientProvider>\n\t);\n}\n","import { createContext, useContext } from 'react';\nimport type { QueryClient } from '@tanstack/react-query';\n\nimport type { SheetsExecuteFn, SheetsUploadFn } from './sheets-execute';\nimport type { SheetsLogger } from '../utils/sheets-logger';\nimport type { CellTypePlugin } from '../cell-types/define-cell-type';\nimport type { SheetsBackendAdapter } from '../adapter/sheets-adapter';\n\nexport interface SheetsAuthEmbedded {\n\tmode: 'embedded';\n\tgetToken: () => string | null;\n\t/**\n\t * Stable, non-secret identity used to isolate cached data between users.\n\t * Hosts should return the authenticated user/session id, never the token.\n\t * When omitted, the provider uses an opaque key that changes with the token.\n\t */\n\tgetIdentityKey?: () => string | null;\n}\n\nexport interface SheetsAuthStandalone {\n\tmode: 'standalone';\n}\n\nexport interface SheetsConfig {\n\t/** Data endpoint (app-public GraphQL) */\n\tendpoint: string;\n\t/** Auth endpoint (auth GraphQL) — required for standalone mode */\n\tauthEndpoint?: string;\n\t/** Database ID for multi-tenant scoping */\n\tdatabaseId?: string;\n\t/** Auth mode */\n\tauth: SheetsAuthEmbedded | SheetsAuthStandalone;\n\t/** Field type overrides (replaces schema-builder smart tags) */\n\tfieldTypeOverrides?: Record<string, string>;\n\t/** Optional: BCP-47 locale for locale-aware date/number formatting (default 'en-US'). */\n\tlocale?: string;\n\t/** Optional: inject custom execute function */\n\texecute?: SheetsExecuteFn;\n\t/** Optional: inject custom upload function */\n\texecuteUpload?: SheetsUploadFn;\n\t/** Optional upload settings. `bucketKey` defaults to \"public\". */\n\tupload?: { bucketKey?: string };\n\t/** Optional: inject existing QueryClient */\n\tqueryClient?: QueryClient;\n\t/** Optional: inject a custom backend adapter. Defaults to the PostGraphile adapter. */\n\tadapter?: SheetsBackendAdapter;\n\t/** Optional: provider-level cell-type plugins (consumer override layer). */\n\tplugins?: CellTypePlugin[];\n\t/** Called on 401/UNAUTHENTICATED before the error is thrown. Host app handles token cleanup. */\n\tonAuthError?: () => void;\n\t/** Optional: inject a custom logger. Installed into the module logger singleton by the provider. */\n\tlogger?: SheetsLogger;\n\t/** Optional: called when a grid/editor/mutation/upload error surfaces. Host app handles reporting. */\n\tonError?: (\n\t\terror: unknown,\n\t\tctx?: { source?: 'grid' | 'editor' | 'mutation' | 'upload'; tableName?: string },\n\t) => void;\n}\n\nexport interface SheetsContextValue {\n\tconfig: SheetsConfig;\n\texecute: SheetsExecuteFn;\n\texecuteUpload: SheetsUploadFn;\n\tscopeKey: SheetsScopeKey;\n}\n\nexport interface SheetsScopeKey {\n\tdatabaseId: string | null;\n\tendpoint: string;\n\tidentityKey: string | null;\n}\n\nexport const SheetsContext = createContext<SheetsContextValue | null>(null);\n\nexport function useSheetsContext(): SheetsContextValue {\n\tconst ctx = useContext(SheetsContext);\n\tif (!ctx) {\n\t\tthrow new Error('useSheetsContext must be used within a <SheetsProvider>');\n\t}\n\treturn ctx;\n}\n","import type { DocumentNode } from 'graphql';\nimport { print } from 'graphql';\n\nimport { createError, DataError, TypedDocumentString } from '@constructive-io/data';\n\nimport type { SheetsConfig } from './sheets-context';\nimport {\n\tcallUploadOp,\n\tdiscoverUploadCapability,\n\tfetchDownloadUrl,\n\tpresignedPut,\n\tsha256HexFromBuffer,\n} from './sheets-upload-presigned';\n\n// ============================================================================\n// Types\n// ============================================================================\n\ntype ExecutableDocument = TypedDocumentString<any, any> | DocumentNode | string | unknown;\n\nexport type SheetsExecuteFn = <T = unknown>(\n\tdocument: ExecutableDocument,\n\tvariables?: Record<string, unknown>,\n) => Promise<T>;\n\n/**\n * Result of an upload through the seam. `url` is the only guaranteed field;\n * the REST upload endpoint also returns `{ filename, mime, size }` (and may\n * return server-internal extras). Keeping it open-ended lets callers read the\n * richer metadata while a bare `{ url }` (e.g. the mock) still satisfies it.\n */\nexport type SheetsUploadResult = { url: string } & Record<string, unknown>;\n\n/**\n * Optional upload metadata carried through the seam (third arg). Lets an\n * injected `executeUpload` see the destination field/row and report progress.\n * All fields optional, so existing `(file, path?)` callers stay valid.\n */\nexport interface SheetsUploadOptions {\n\ttableName?: string;\n\tfieldName?: string;\n\trecordId?: string | number;\n\tonProgress?: (progress: { loaded: number; total: number; percentage: number }) => void;\n}\n\nexport type SheetsUploadFn = (\n\tfile: File,\n\tpath?: string,\n\toptions?: SheetsUploadOptions,\n) => Promise<SheetsUploadResult>;\n\n// ============================================================================\n// Helpers\n// ============================================================================\n\nfunction documentToString(document: ExecutableDocument): string {\n\tif (typeof document === 'string') return document;\n\tif (document instanceof String) return document.toString();\n\tif (document && typeof document === 'object' && 'kind' in (document as DocumentNode)) {\n\t\treturn print(document as DocumentNode);\n\t}\n\tif (document === null || document === undefined) {\n\t\tthrow createError.badRequest('Invalid GraphQL document: null or undefined');\n\t}\n\treturn String(document);\n}\n\n// ============================================================================\n// GraphQL Response Parsing\n// ============================================================================\n\ninterface GraphQLResponseError {\n\tmessage: string;\n\textensions?: { code?: string };\n}\n\ninterface GraphQLResponse {\n\tdata?: unknown;\n\terrors?: GraphQLResponseError[];\n}\n\nfunction hasAuthMessage(message: string | undefined): boolean {\n\tconst normalized = String(message ?? '').toLowerCase();\n\treturn (\n\t\tnormalized.includes('unauthenticated') ||\n\t\tnormalized.includes('unauthorized') ||\n\t\tnormalized.includes('authentication')\n\t);\n}\n\nfunction parseGraphQLResponse(response: GraphQLResponse, onAuthError?: () => void): DataError | null {\n\tif (!response.errors?.length) return null;\n\n\tconst error = response.errors[0];\n\tconst code = error.extensions?.code;\n\tconst message = error.message || 'GraphQL query failed';\n\n\tif (code === 'UNAUTHENTICATED' || hasAuthMessage(message)) {\n\t\tonAuthError?.();\n\t\treturn createError.unauthorized('Authentication required. Please log in again.');\n\t}\n\n\tif (code === 'FORBIDDEN') {\n\t\treturn createError.forbidden('You do not have permission to perform this action.');\n\t}\n\n\treturn createError.graphql(message, code);\n}\n\n// ============================================================================\n// Factory\n// ============================================================================\n\nexport function createSheetsExecute(\n\tconfig: SheetsConfig,\n\tgetToken: () => string | null,\n): SheetsExecuteFn {\n\treturn async <T = unknown>(\n\t\tdocument: ExecutableDocument,\n\t\tvariables?: Record<string, unknown>,\n\t): Promise<T> => {\n\t\tconst url = config.endpoint;\n\t\tif (!url) {\n\t\t\tthrow createError.badRequest('No GraphQL endpoint configured.');\n\t\t}\n\n\t\tconst token = getToken();\n\t\tconst headers: Record<string, string> = {\n\t\t\t'Content-Type': 'application/json',\n\t\t\tAccept: 'application/graphql-response+json',\n\t\t};\n\t\tif (token) {\n\t\t\theaders['Authorization'] = `Bearer ${token}`;\n\t\t}\n\n\t\tlet response: Response;\n\t\ttry {\n\t\t\tresponse = await fetch(url, {\n\t\t\t\tmethod: 'POST',\n\t\t\t\theaders,\n\t\t\t\tbody: JSON.stringify({\n\t\t\t\t\tquery: documentToString(document),\n\t\t\t\t\t...(variables !== undefined && { variables }),\n\t\t\t\t}),\n\t\t\t});\n\t\t} catch (error) {\n\t\t\tthrow createError.network(error instanceof Error ? error : undefined);\n\t\t}\n\n\t\tif (!response.ok) {\n\t\t\tconst { status, statusText } = response;\n\t\t\tif (status === 401) {\n\t\t\t\tconfig.onAuthError?.();\n\t\t\t\tthrow createError.unauthorized('Authentication required. Please log in again.');\n\t\t\t}\n\t\t\tif (status === 403) {\n\t\t\t\tthrow createError.forbidden('You do not have permission to perform this action.');\n\t\t\t}\n\t\t\tif (status === 404) {\n\t\t\t\tthrow createError.notFound('The requested endpoint does not exist.');\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tconst body = await response.json();\n\t\t\t\tif (body.errors?.length) {\n\t\t\t\t\tthrow createError.graphql(body.errors[0].message || `Request failed: ${status}`, body.errors[0].extensions?.code);\n\t\t\t\t}\n\t\t\t} catch (e) {\n\t\t\t\tif (e instanceof DataError) throw e;\n\t\t\t}\n\t\t\tthrow createError.badRequest(`Request failed: ${status} ${statusText}`);\n\t\t}\n\n\t\tconst result: GraphQLResponse = await response.json();\n\t\tconst graphqlError = parseGraphQLResponse(result, config.onAuthError);\n\t\tif (graphqlError) {\n\t\t\tthrow graphqlError;\n\t\t}\n\n\t\treturn result.data as T;\n\t};\n}\n\n/**\n * Presigned-URL cell-upload seam.\n *\n * Replaces the legacy multipart `<endpoint>/upload` POST entirely. The flow:\n * 1. Read + SHA-256 hash the file bytes (Web Crypto)\n * 2. Discover (cached per endpoint) the upload op + downloadUrl-by-id field\n * via GraphQL introspection — the root `upload<Type>File` mutation, matched\n * by FIELD/TYPE SHAPE (LOCKED: no hardcoded names)\n * 3. Call the upload op with input `{ bucketKey, contentHash, contentType,\n * size, filename }` — NO `ownerId` (app-scoped buckets have no owner_id)\n * 4. If `uploadUrl` is non-null, PUT the raw bytes to it with ONLY the signed\n * `Content-Type` header (NO Authorization). Skipped when `deduplicated`.\n * 5. Resolve the stable public `downloadUrl` for the returned fileId.\n *\n * Returns `{ url, filename, mime, size, key, fileId }` where `url` is the stable\n * download URL — the same cell value shape callers/Step-2 already consume.\n *\n * `path` is ignored (content-addressed buckets key on `contentHash`).\n */\nexport function createSheetsUpload(config: SheetsConfig, getToken: () => string | null): SheetsUploadFn {\n\t// Reuse the kept GraphQL executor so DataError normalization + onAuthError\n\t// (401/UNAUTHENTICATED) apply to introspection, the upload op, and the\n\t// downloadUrl query alike.\n\tconst execute = config.execute ?? createSheetsExecute(config, getToken);\n\n\treturn async (file: File, _path?: string, options?: SheetsUploadOptions): Promise<SheetsUploadResult> => {\n\t\tif (!config.endpoint) {\n\t\t\tthrow createError.badRequest('No GraphQL endpoint configured.');\n\t\t}\n\n\t\tconst bucketKey = config.upload?.bucketKey ?? 'public';\n\t\tconst contentType = file.type || 'application/octet-stream';\n\n\t\t// Single read of the bytes — reused for both hashing and the PUT body.\n\t\tconst buffer = await file.arrayBuffer();\n\t\tconst contentHash = await sha256HexFromBuffer(buffer);\n\n\t\tconst cap = await discoverUploadCapability(config.endpoint, execute);\n\n\t\tconst payload = await callUploadOp(execute, cap, {\n\t\t\tbucketKey,\n\t\t\tcontentHash,\n\t\t\tcontentType,\n\t\t\tsize: file.size,\n\t\t\tfilename: file.name,\n\t\t});\n\n\t\t// Dedup (deduplicated ⇒ uploadUrl === null) means the row + S3 object already\n\t\t// exist; skip the PUT. A non-deduplicated payload MUST carry an uploadUrl — a\n\t\t// null there is a server-contract violation, so fail loudly rather than\n\t\t// resolving a downloadUrl for an object that was never uploaded.\n\t\tif (!payload.deduplicated) {\n\t\t\tif (!payload.uploadUrl) {\n\t\t\t\tthrow createError.badRequest('Upload failed: server returned no uploadUrl for a non-deduplicated file.');\n\t\t\t}\n\t\t\tawait presignedPut(payload.uploadUrl, buffer, contentType, options?.onProgress);\n\t\t} else {\n\t\t\toptions?.onProgress?.({ loaded: file.size, total: file.size, percentage: 100 });\n\t\t}\n\n\t\tconst url = await fetchDownloadUrl(execute, cap, payload.fileId);\n\n\t\treturn {\n\t\t\turl,\n\t\t\tfilename: file.name,\n\t\t\tmime: file.type,\n\t\t\tsize: file.size,\n\t\t\tkey: payload.key,\n\t\t\tfileId: payload.fileId,\n\t\t};\n\t};\n}\n\nexport { DataError } from '@constructive-io/data';\n","/**\n * Presigned-URL upload helpers for the sheets cell-upload seam.\n *\n * Replaces the legacy multipart `<endpoint>/upload` POST. The flow is:\n * 1. SHA-256 hash the file bytes (Web Crypto, zero new deps)\n * 2. Call the presigned upload op (discovered via introspection) to get a\n * presigned PUT url + fileId\n * 3. PUT the raw bytes to that url (only Content-Type, NO Authorization)\n * 4. Resolve the stable public `downloadUrl` for the fileId\n *\n * `confirmUpload` is intentionally skipped: the backend plugin creates the file\n * row inside the upload op, so `downloadUrl` resolves immediately.\n *\n * The upload op is discovered via runtime introspection, matched by FIELD/TYPE\n * SHAPE (never a hardcoded name): a root mutation `upload<Type>File(input: {...})`\n * whose input + payload carry the upload shape.\n *\n * The downloadUrl-by-id field is likewise shape-discovered. Three read shapes,\n * preferred in order: the inflected singular `appFile(id:)`; a filtered\n * connection `appFiles(where:{id:{equalTo:$id}}){ nodes { downloadUrl } }`\n * (Relay-disabled backends); and the Relay `node(nodeId:)` fallback.\n */\n\nimport { getIntrospectionQuery } from 'graphql';\n\nimport { createError } from '@constructive-io/data';\n\nimport type { SheetsExecuteFn } from './sheets-execute';\n\n// ============================================================================\n// Capability discovery types\n// ============================================================================\n\nexport interface UploadCapability {\n\t/** Upload mutation field name, discovered by shape, e.g. 'uploadAppFile'. */\n\tuploadFieldName: string;\n\t/** The upload input object type name, e.g. 'UploadAppFileInput'. */\n\tinputTypeName: string;\n\t/** Query field used to resolve the stable downloadUrl by id, e.g. 'appFile' | 'node' | 'appFiles'. */\n\tfileByIdField: string;\n\t/**\n\t * Which downloadUrl-by-id resolution shape was discovered:\n\t * - 'id' inflected singular `appFile(id:)`\n\t * - 'connection' filtered connection `appFiles(where:{id:{equalTo:$id}}){ nodes { downloadUrl } }`\n\t * - 'nodeId' Relay `node(nodeId:)` (last-resort fallback)\n\t */\n\tfileByIdArgName: 'id' | 'nodeId' | 'connection';\n\t/** The file object type name (used to spread `... on <Type>` on the Relay node path). */\n\tfileTypeName: string;\n\t/** The GraphQL scalar type name for the `$id` variable (e.g. 'UUID'), discovered by shape. */\n\tidScalarName?: string;\n\t/** connection kind only — the filter arg name on the connection field, e.g. 'where' | 'filter' | 'condition'. */\n\tconnectionFilterArgName?: string;\n\t/** connection kind only — the id field name inside the filter input, e.g. 'id'. */\n\tconnectionIdField?: string;\n\t/** connection kind only — the equality operator field for style (a), e.g. 'equalTo'. Absent for condition style (b). */\n\tconnectionIdOperator?: string;\n\t/** connection kind only — the field on the connection object holding the file rows, e.g. 'nodes'. */\n\tconnectionNodesField?: string;\n}\n\ninterface UploadPayload {\n\tuploadUrl: string | null;\n\tfileId: string;\n\tkey: string;\n\tdeduplicated: boolean;\n}\n\n// ============================================================================\n// SHA-256 (Web Crypto)\n// ============================================================================\n\n/**\n * SHA-256 hex digest of an already-read ArrayBuffer. Lowercase, 64 chars —\n * matches the server regex `^[a-f0-9]{64}$`. We reuse the same buffer for the\n * PUT body to avoid a second `file.arrayBuffer()` read.\n */\nexport async function sha256HexFromBuffer(buffer: ArrayBuffer): Promise<string> {\n\tif (!globalThis.crypto?.subtle) {\n\t\tthrow createError.badRequest('Web Crypto (crypto.subtle) is unavailable; cannot hash file for upload.');\n\t}\n\tconst digest = await crypto.subtle.digest('SHA-256', buffer);\n\tconst bytes = new Uint8Array(digest);\n\tlet hex = '';\n\tfor (let i = 0; i < bytes.length; i++) {\n\t\thex += bytes[i].toString(16).padStart(2, '0');\n\t}\n\treturn hex;\n}\n\n// ============================================================================\n// Introspection-based capability discovery (cached per endpoint)\n// ============================================================================\n\nconst capabilityCache = new Map<string, Promise<UploadCapability>>();\n\n/** Test-only: clear the per-endpoint capability cache between cases. */\nexport function __resetUploadCapabilityCache(): void {\n\tcapabilityCache.clear();\n}\n\n/**\n * Discover the upload op + downloadUrl-by-id field for an endpoint, by shape.\n * Cached per `endpoint`; concurrent uploads share one in-flight introspection.\n */\nexport function discoverUploadCapability(endpoint: string, execute: SheetsExecuteFn): Promise<UploadCapability> {\n\tconst cached = capabilityCache.get(endpoint);\n\tif (cached) return cached;\n\n\tconst promise = (async () => {\n\t\tconst data = await execute<{ __schema: IntrospectionSchema }>(getIntrospectionQuery());\n\t\tconst schema = data?.__schema;\n\t\tif (!schema) {\n\t\t\tthrow createError.badRequest('Uploads are not enabled for this endpoint.');\n\t\t}\n\t\treturn resolveUploadCapability(schema);\n\t})();\n\n\t// Don't cache a rejected discovery — let the next attempt retry.\n\tpromise.catch(() => capabilityCache.delete(endpoint));\n\tcapabilityCache.set(endpoint, promise);\n\treturn promise;\n}\n\n// --- Minimal introspection shapes (only what discovery reads) ---\n\n// Loose, structural shapes for the slice of introspection that discovery\n// reads. `ofType` recurses with `any` so hand-built fixtures and the real\n// `IntrospectionQuery['__schema']` (from `graphql`) both satisfy these without\n// exact-match friction — discovery validates by runtime shape regardless.\ninterface IntrospectionTypeRef {\n\tkind: string;\n\tname?: string | null;\n\tofType?: any;\n}\n\ninterface IntrospectionInputValue {\n\tname: string;\n\ttype: IntrospectionTypeRef;\n}\n\ninterface IntrospectionField {\n\tname: string;\n\targs: ReadonlyArray<IntrospectionInputValue>;\n\ttype: IntrospectionTypeRef;\n}\n\ninterface IntrospectionType {\n\tkind: string;\n\tname?: string | null;\n\tfields?: ReadonlyArray<IntrospectionField> | null;\n\tinputFields?: ReadonlyArray<IntrospectionInputValue> | null;\n}\n\n/** Loose structural shape of an introspection `__schema` (accepts fixtures + real). */\nexport interface IntrospectionSchema {\n\tqueryType?: { name: string } | null;\n\tmutationType?: { name: string } | null;\n\ttypes: ReadonlyArray<IntrospectionType>;\n}\n\n/** Unwrap NON_NULL / LIST wrappers down to the named type. */\nfunction namedTypeName(ref: IntrospectionTypeRef | null | undefined): string | null {\n\tlet cur = ref;\n\twhile (cur && (cur.kind === 'NON_NULL' || cur.kind === 'LIST')) {\n\t\tcur = cur.ofType ?? null;\n\t}\n\treturn cur?.name ?? null;\n}\n\n/**\n * True if `ref` is a LIST (optionally NON_NULL-wrapped) at the outer level, i.e.\n * the field is plural. Unwraps only leading NON_NULL wrappers (e.g. `[AppFile]!`)\n * before checking for the LIST — distinguishes `nodes: [AppFile]` from a singular\n * `appFile: AppFile`.\n */\nfunction isListTypeRef(ref: IntrospectionTypeRef | null | undefined): boolean {\n\tlet cur = ref;\n\twhile (cur && cur.kind === 'NON_NULL') {\n\t\tcur = cur.ofType ?? null;\n\t}\n\treturn cur?.kind === 'LIST';\n}\n\n/**\n * PostGraphile names the primary-key column `id` on every row type, so the\n * filter input field that selects a single file by primary key is `id`. This is\n * the same convention the singular by-id branch (`appFile(id:)`) relies on.\n */\nconst PK_FIELD_NAME = 'id';\n\n/**\n * Pure resolver over an introspection __schema. Exported for direct unit tests\n * (no fetch). Matches by field/type SHAPE, never by a literal name.\n */\nexport function resolveUploadCapability(schema: IntrospectionSchema): UploadCapability {\n\tconst typeByName = new Map<string, IntrospectionType>();\n\tfor (const t of schema.types) {\n\t\tif (t.name) typeByName.set(t.name, t);\n\t}\n\n\tconst objectHasFields = (typeName: string | null, names: string[]): boolean => {\n\t\tif (!typeName) return false;\n\t\tconst t = typeByName.get(typeName);\n\t\tif (!t?.fields) return false;\n\t\tconst present = new Set(t.fields.map((f) => f.name));\n\t\treturn names.every((n) => present.has(n));\n\t};\n\n\tconst inputHasFields = (typeName: string | null, names: string[]): boolean => {\n\t\tif (!typeName) return false;\n\t\tconst t = typeByName.get(typeName);\n\t\tif (!t?.inputFields) return false;\n\t\tconst present = new Set(t.inputFields.map((f) => f.name));\n\t\treturn names.every((n) => present.has(n));\n\t};\n\n\tconst PAYLOAD_FIELDS = ['uploadUrl', 'fileId', 'deduplicated'];\n\tconst INPUT_FIELDS = ['contentHash', 'bucketKey', 'contentType', 'size'];\n\n\tconst mutationType = schema.mutationType ? typeByName.get(schema.mutationType.name) : null;\n\tconst queryType = schema.queryType ? typeByName.get(schema.queryType.name) : null;\n\n\t// rootUpload discovery: a Mutation field with a single `input` arg whose input\n\t// type carries the upload-input shape and whose payload carries the\n\t// upload-payload shape. (The legacy bucket-centric `requestUploadUrl` shape was\n\t// removed from the backend on 2026-05-08; only the root upload mutation exists.)\n\tlet upload: Pick<UploadCapability, 'uploadFieldName' | 'inputTypeName'> | null = null;\n\n\tfor (const field of mutationType?.fields ?? []) {\n\t\tconst inputArg = field.args.find((a) => a.name === 'input');\n\t\tif (!inputArg) continue;\n\t\tconst inputTypeName = namedTypeName(inputArg.type);\n\t\tconst payloadTypeName = namedTypeName(field.type);\n\t\tif (\n\t\t\tinputHasFields(inputTypeName, INPUT_FIELDS) &&\n\t\t\tobjectHasFields(payloadTypeName, PAYLOAD_FIELDS)\n\t\t) {\n\t\t\tupload = { uploadFieldName: field.name, inputTypeName: inputTypeName as string };\n\t\t\tbreak;\n\t\t}\n\t}\n\n\tif (!upload) {\n\t\tthrow createError.badRequest('Uploads are not enabled for this endpoint.');\n\t}\n\n\t// --- File object type + by-id field for downloadUrl ---\n\tconst downloadById = resolveDownloadByIdField(schema, typeByName, queryType, upload.uploadFieldName);\n\n\treturn {\n\t\t...upload,\n\t\t...downloadById,\n\t};\n}\n\ntype DownloadByIdResult = Omit<UploadCapability, 'uploadFieldName' | 'inputTypeName'>;\n\nfunction resolveDownloadByIdField(\n\tschema: IntrospectionSchema,\n\ttypeByName: Map<string, IntrospectionType>,\n\tqueryType: IntrospectionType | null | undefined,\n\tuploadFieldName: string,\n): DownloadByIdResult {\n\t// The file object type carries a `downloadUrl` field (grounded on\n\t// download-url-field.ts which adds `downloadUrl: String` to @storageFiles).\n\tconst fileTypesWithDownloadUrl = new Set<string>();\n\tfor (const t of schema.types) {\n\t\tif (t.kind === 'OBJECT' && t.name && t.fields?.some((f) => f.name === 'downloadUrl')) {\n\t\t\tfileTypesWithDownloadUrl.add(t.name);\n\t\t}\n\t}\n\n\t// 1. Prefer the inflected by-id form: a Query field whose return type has a\n\t// `downloadUrl` field and that takes a single `id` arg. e.g. appFile(id:).\n\t// The `$id` variable type is the actual scalar of that id arg (NOT a\n\t// hardcoded UUID) — derived by shape.\n\tfor (const field of queryType?.fields ?? []) {\n\t\tconst returnTypeName = namedTypeName(field.type);\n\t\tif (!returnTypeName || !fileTypesWithDownloadUrl.has(returnTypeName)) continue;\n\t\tif (field.args.length === 1 && field.args[0].name === PK_FIELD_NAME) {\n\t\t\treturn {\n\t\t\t\tfileByIdField: field.name,\n\t\t\t\tfileByIdArgName: 'id',\n\t\t\t\tfileTypeName: returnTypeName,\n\t\t\t\tidScalarName: namedTypeName(field.args[0].type) ?? undefined,\n\t\t\t};\n\t\t}\n\t}\n\n\t// 2. Connection fallback (Relay-disabled backends, incl. the live tenant API):\n\t// a Query field returning a connection whose `nodes` element is a\n\t// downloadUrl-bearing file type, filtered by id. e.g.\n\t// appFiles(where: { id: { equalTo: $id } }, first: 1) { nodes { downloadUrl } }\n\t// All names (connection field, filter arg, id field, equality operator,\n\t// nodes field, id scalar) are discovered by SHAPE, never hardcoded.\n\t// Preferred over the Relay node path: it consumes the raw fileId directly,\n\t// so it needs no client-side global-id construction.\n\tconst connection = resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, uploadFieldName);\n\tif (connection) return connection;\n\n\t// 3. Relay fallback: `node(nodeId: ID!)`. Last resort — only when neither a\n\t// singular `id` accessor nor a filtered connection exists. Caller spreads\n\t// `... on <FileType> { downloadUrl }` and encodes the global id.\n\tconst nodeField = queryType?.fields?.find(\n\t\t(f) => f.name === 'node' && f.args.some((a) => a.name === 'nodeId'),\n\t);\n\tif (nodeField && fileTypesWithDownloadUrl.size > 0) {\n\t\t// Deterministic file type for the inline fragment: prefer the type named\n\t\t// after the upload op (uploadAppFile → AppFile); else the first-declared\n\t\t// downloadUrl-bearing type. (Was alphabetical `.sort()[0]`, which could pick\n\t\t// the wrong type when several expose downloadUrl, e.g. DataRoomFile.)\n\t\tconst preferred = uploadFieldName.replace(/^upload/, '');\n\t\tconst fileTypeName = fileTypesWithDownloadUrl.has(preferred)\n\t\t\t? preferred\n\t\t\t: [...fileTypesWithDownloadUrl][0];\n\t\treturn { fileByIdField: 'node', fileByIdArgName: 'nodeId', fileTypeName };\n\t}\n\n\tthrow createError.badRequest('Uploads are not enabled for this endpoint.');\n}\n\n/**\n * Discover a filtered-connection downloadUrl-by-id path. Returns null if the\n * schema exposes no such connection. Supports two filter input styles:\n * (a) operator filter — `where: { id: { equalTo: $id } }` (connection-filter\n * plugin): the id field's input type carries an equality operator.\n * (b) condition filter — `condition: { id: $id }`: the id field is the scalar\n * directly.\n */\nfunction resolveConnectionDownloadField(\n\ttypeByName: Map<string, IntrospectionType>,\n\tqueryType: IntrospectionType | null | undefined,\n\tfileTypesWithDownloadUrl: Set<string>,\n\tuploadFieldName: string,\n): DownloadByIdResult | null {\n\t// Equality operator names we recognize on a filter-input field, in priority\n\t// order (exact-match equality first).\n\tconst EQUALITY_OPERATORS = ['equalTo', 'eq'];\n\n\t// Collect every matching connection, then pick deterministically — a tenant\n\t// with multiple @storageFiles tables exposes several file connections\n\t// (appFiles, dataRoomFiles, …), all carrying downloadUrl-bearing nodes.\n\tconst candidates: DownloadByIdResult[] = [];\n\n\tfor (const field of queryType?.fields ?? []) {\n\t\tconst connTypeName = namedTypeName(field.type);\n\t\tif (!connTypeName) continue;\n\t\tconst connType = typeByName.get(connTypeName);\n\t\tif (connType?.kind !== 'OBJECT' || !connType.fields) continue;\n\n\t\t// Find the `nodes` field whose element type is a downloadUrl-bearing file.\n\t\t// Require it to be a LIST (plural) so a singular `appFile: AppFile` field on\n\t\t// some object does NOT false-match as a connection (fetchDownloadUrl indexes\n\t\t// [nodesField][0], which only makes sense on an array).\n\t\tconst nodesField = connType.fields.find((f) => {\n\t\t\tif (!isListTypeRef(f.type)) return false;\n\t\t\tconst elem = namedTypeName(f.type);\n\t\t\treturn elem != null && fileTypesWithDownloadUrl.has(elem);\n\t\t});\n\t\tif (!nodesField) continue;\n\t\tconst fileTypeName = namedTypeName(nodesField.type) as string;\n\n\t\t// Find a filter arg whose input type has an `id` field.\n\t\tfor (const arg of field.args) {\n\t\t\tconst filterTypeName = namedTypeName(arg.type);\n\t\t\tconst filterType = filterTypeName ? typeByName.get(filterTypeName) : null;\n\t\t\tif (filterType?.kind !== 'INPUT_OBJECT' || !filterType.inputFields) continue;\n\t\t\tconst idField = filterType.inputFields.find((f) => f.name === PK_FIELD_NAME);\n\t\t\tif (!idField) continue;\n\n\t\t\tconst idFieldTypeName = namedTypeName(idField.type);\n\t\t\tconst idFieldType = idFieldTypeName ? typeByName.get(idFieldTypeName) : null;\n\n\t\t\t// Style (a): the id field is itself an input type carrying an equality\n\t\t\t// operator (e.g. UUIDFilter.equalTo). The `$id` scalar is the operator's\n\t\t\t// type.\n\t\t\tif (idFieldType?.kind === 'INPUT_OBJECT' && idFieldType.inputFields) {\n\t\t\t\tconst opField = EQUALITY_OPERATORS.map((op) =>\n\t\t\t\t\tidFieldType.inputFields!.find((f) => f.name === op),\n\t\t\t\t).find((f) => f != null);\n\t\t\t\tif (opField) {\n\t\t\t\t\tcandidates.push({\n\t\t\t\t\t\tfileByIdField: field.name,\n\t\t\t\t\t\tfileByIdArgName: 'connection',\n\t\t\t\t\t\tfileTypeName,\n\t\t\t\t\t\tidScalarName: namedTypeName(opField.type) ?? undefined,\n\t\t\t\t\t\tconnectionFilterArgName: arg.name,\n\t\t\t\t\t\tconnectionIdField: idField.name,\n\t\t\t\t\t\tconnectionIdOperator: opField.name,\n\t\t\t\t\t\tconnectionNodesField: nodesField.name,\n\t\t\t\t\t});\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\t// id field is an input object but with no recognized equality op — skip.\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\t// Style (b): the id field is a scalar directly (condition style). The\n\t\t\t// `$id` scalar is that field's type.\n\t\t\tif (idFieldType?.kind === 'SCALAR' || (!idFieldType && idFieldTypeName)) {\n\t\t\t\tcandidates.push({\n\t\t\t\t\tfileByIdField: field.name,\n\t\t\t\t\tfileByIdArgName: 'connection',\n\t\t\t\t\tfileTypeName,\n\t\t\t\t\tidScalarName: idFieldTypeName ?? undefined,\n\t\t\t\t\tconnectionFilterArgName: arg.name,\n\t\t\t\t\tconnectionIdField: idField.name,\n\t\t\t\t\tconnectionNodesField: nodesField.name,\n\t\t\t\t});\n\t\t\t\tbreak;\n\t\t\t}\n\t\t}\n\t}\n\n\tif (candidates.length === 0) return null;\n\n\t// Deterministic pick: prefer the connection whose file type matches the upload\n\t// op (uploadAppFile → AppFile), else the first-declared. This is the LIVE\n\t// production path — the only downloadUrl shape on a Relay-disabled, unique-\n\t// lookup-disabled tenant API — so resolving the WRONG file connection (e.g.\n\t// reading a DataRoomFile id through appFiles) yields 0 nodes and fails every\n\t// upload. Mirrors the node-branch determinism, where it matters far more.\n\tconst preferred = uploadFieldName.replace(/^upload/, '');\n\treturn candidates.find((c) => c.fileTypeName === preferred) ?? candidates[0];\n}\n\n// ============================================================================\n// Upload op call\n// ============================================================================\n\ninterface UploadOpInput {\n\tbucketKey: string;\n\tcontentHash: string;\n\tcontentType: string;\n\tsize: number;\n\tfilename: string;\n}\n\n/**\n * Invoke the discovered upload op and normalize its payload.\n * App-scoped buckets have NO owner_id column, so `ownerId` is NEVER sent.\n */\nexport async function callUploadOp(\n\texecute: SheetsExecuteFn,\n\tcap: UploadCapability,\n\tinput: UploadOpInput,\n): Promise<UploadPayload> {\n\tconst mutation = `\n\t\tmutation SheetsUpload($input: ${cap.inputTypeName}!) {\n\t\t\t${cap.uploadFieldName}(input: $input) {\n\t\t\t\tuploadUrl\n\t\t\t\tfileId\n\t\t\t\tkey\n\t\t\t\tdeduplicated\n\t\t\t}\n\t\t}\n\t`.trim();\n\tconst data = await execute<Record<string, UploadPayload | null>>(mutation, {\n\t\tinput: {\n\t\t\tbucketKey: input.bucketKey,\n\t\t\tcontentHash: input.contentHash,\n\t\t\tcontentType: input.contentType,\n\t\t\tsize: input.size,\n\t\t\tfilename: input.filename,\n\t\t},\n\t});\n\tconst payload = data?.[cap.uploadFieldName];\n\tif (!payload) {\n\t\tthrow createError.badRequest('Upload failed: no payload returned from upload mutation.');\n\t}\n\treturn payload;\n}\n\n// ============================================================================\n// Presigned PUT\n// ============================================================================\n\n/**\n * PUT the raw bytes to the presigned url. Sends ONLY the signed `Content-Type`\n * header — NO Authorization (the signature lives in the url query string), no\n * cookies, no Accept override. The browser supplies Content-Length from the body.\n *\n * When `onProgress` is provided and XHR is available, uses XHR for byte\n * progress; otherwise a plain fetch PUT.\n */\nexport async function presignedPut(\n\turl: string,\n\tbuffer: ArrayBuffer,\n\tcontentType: string,\n\tonProgress?: (progress: { loaded: number; total: number; percentage: number }) => void,\n): Promise<void> {\n\tconst total = buffer.byteLength;\n\n\tif (onProgress && typeof XMLHttpRequest !== 'undefined') {\n\t\tawait putWithXHR(url, buffer, contentType, total, onProgress);\n\t\treturn;\n\t}\n\n\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(url, {\n\t\t\tmethod: 'PUT',\n\t\t\theaders: { 'Content-Type': contentType },\n\t\t\tbody: buffer,\n\t\t});\n\t} catch (error) {\n\t\tthrow createError.network(error instanceof Error ? error : undefined);\n\t}\n\n\tif (!response.ok) {\n\t\tconst body = await response.text().catch(() => '');\n\t\tthrow createError.badRequest(`Upload failed: ${response.status} ${response.statusText}${body ? ` — ${body}` : ''}`);\n\t}\n\tonProgress?.({ loaded: total, total, percentage: 100 });\n}\n\nfunction putWithXHR(\n\turl: string,\n\tbuffer: ArrayBuffer,\n\tcontentType: string,\n\ttotal: number,\n\tonProgress: (progress: { loaded: number; total: number; percentage: number }) => void,\n): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst xhr = new XMLHttpRequest();\n\t\txhr.open('PUT', url);\n\t\txhr.setRequestHeader('Content-Type', contentType);\n\n\t\txhr.upload.addEventListener('progress', (event) => {\n\t\t\tif (event.lengthComputable) {\n\t\t\t\tonProgress({\n\t\t\t\t\tloaded: event.loaded,\n\t\t\t\t\ttotal: event.total,\n\t\t\t\t\tpercentage: Math.round((event.loaded / event.total) * 100),\n\t\t\t\t});\n\t\t\t}\n\t\t});\n\n\t\txhr.addEventListener('load', () => {\n\t\t\tif (xhr.status >= 200 && xhr.status < 300) {\n\t\t\t\tonProgress({ loaded: total, total, percentage: 100 });\n\t\t\t\tresolve();\n\t\t\t} else {\n\t\t\t\treject(createError.badRequest(`Upload failed: ${xhr.status} ${xhr.statusText}${xhr.responseText ? ` — ${xhr.responseText}` : ''}`));\n\t\t\t}\n\t\t});\n\n\t\txhr.addEventListener('error', () => reject(createError.network()));\n\n\t\txhr.send(buffer);\n\t});\n}\n\n// ============================================================================\n// downloadUrl resolution\n// ============================================================================\n\n/**\n * Encode a PostGraphile global id (Relay `node` id) from a row's primary key,\n * using the default base64JSON codec: `base64(JSON.stringify([typeName, pk]))`.\n */\nfunction toGlobalId(typeName: string, id: string): string {\n\tif (typeof btoa !== 'function') {\n\t\tthrow createError.badRequest('Cannot encode the file node id: btoa is unavailable in this environment.');\n\t}\n\treturn btoa(JSON.stringify([typeName, id]));\n}\n\n/**\n * Resolve the stable public download URL for a file id via the discovered\n * by-id field. For public files the backend returns a permanent public URL\n * (its exact path shape is the backend's concern) — stored opaquely in the cell.\n */\nexport async function fetchDownloadUrl(\n\texecute: SheetsExecuteFn,\n\tcap: UploadCapability,\n\tfileId: string,\n): Promise<string> {\n\tif (cap.fileByIdArgName === 'nodeId') {\n\t\t// The upload payload returns the RAW primary key as `fileId`, but\n\t\t// `node(nodeId:)` expects the opaque PostGraphile global id. Encode it with\n\t\t// the default base64JSON codec (`base64([typeName, pk])`). NOTE: the live\n\t\t// tenant API is Relay-disabled and resolves via the connection branch; this\n\t\t// path is mock-covered only and assumes the default node-id codec.\n\t\tconst nodeId = toGlobalId(cap.fileTypeName, fileId);\n\t\tconst query = `\n\t\t\tquery SheetsDownloadUrl($nodeId: ID!) {\n\t\t\t\t${cap.fileByIdField}(nodeId: $nodeId) {\n\t\t\t\t\t... on ${cap.fileTypeName} {\n\t\t\t\t\t\tdownloadUrl\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t`.trim();\n\t\tconst data = await execute<Record<string, { downloadUrl?: string | null } | null>>(query, { nodeId });\n\t\tconst node = data?.[cap.fileByIdField];\n\t\tconst url = node?.downloadUrl;\n\t\tif (!url) {\n\t\t\tthrow createError.badRequest('Upload succeeded but no downloadUrl was returned for the file.');\n\t\t}\n\t\treturn url;\n\t}\n\n\t// Connection fallback (Relay-disabled): filter the connection by id and read\n\t// the first node's downloadUrl. The filter literal is built per the discovered\n\t// style — operator (`{ id: { equalTo: $id } }`) or condition (`{ id: $id }`).\n\tif (cap.fileByIdArgName === 'connection') {\n\t\tconst idScalar = cap.idScalarName ?? 'ID';\n\t\tconst filterArg = cap.connectionFilterArgName as string;\n\t\tconst idField = cap.connectionIdField as string;\n\t\tconst nodesField = cap.connectionNodesField as string;\n\t\tconst filterLiteral = cap.connectionIdOperator\n\t\t\t? `{ ${idField}: { ${cap.connectionIdOperator}: $id } }`\n\t\t\t: `{ ${idField}: $id }`;\n\t\tconst query = `\n\t\t\tquery SheetsDownloadUrl($id: ${idScalar}!) {\n\t\t\t\t${cap.fileByIdField}(${filterArg}: ${filterLiteral}, first: 1) {\n\t\t\t\t\t${nodesField} {\n\t\t\t\t\t\tdownloadUrl\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t}\n\t\t`.trim();\n\t\tconst data = await execute<Record<string, Record<string, Array<{ downloadUrl?: string | null }> | null> | null>>(\n\t\t\tquery,\n\t\t\t{ id: fileId },\n\t\t);\n\t\tconst conn = data?.[cap.fileByIdField];\n\t\tconst url = conn?.[nodesField]?.[0]?.downloadUrl;\n\t\tif (!url) {\n\t\t\tthrow createError.badRequest('Upload succeeded but no downloadUrl was returned for the file.');\n\t\t}\n\t\treturn url;\n\t}\n\n\tconst idScalar = cap.idScalarName ?? 'ID';\n\tconst query = `\n\t\tquery SheetsDownloadUrl($id: ${idScalar}!) {\n\t\t\t${cap.fileByIdField}(id: $id) {\n\t\t\t\tid\n\t\t\t\tdownloadUrl\n\t\t\t}\n\t\t}\n\t`.trim();\n\tconst data = await execute<Record<string, { downloadUrl?: string | null } | null>>(query, { id: fileId });\n\tconst file = data?.[cap.fileByIdField];\n\tconst url = file?.downloadUrl;\n\tif (!url) {\n\t\tthrow createError.badRequest('Upload succeeded but no downloadUrl was returned for the file.');\n\t}\n\treturn url;\n}\n\n/**\n * Resolve a file's signed `downloadUrl` by id — the public entry point for callers\n * OUTSIDE the upload flow (e.g. a storage browser fetching the preview/copy link for\n * an already-uploaded file).\n *\n * `downloadUrl` is a Grafast computed field, so it cannot be selected through the\n * runtime query builder (`buildSelect` intersects the select against pg columns and\n * drops computed fields). This discovers the by-id field once per endpoint (cached)\n * and reads it through the SAME resolver the upload path uses. Returns null on any\n * failure — a missing url is not exceptional for the caller (it just disables\n * copy/download), so the throwing internals are swallowed here.\n */\nexport async function resolveDownloadUrl(\n\texecute: SheetsExecuteFn,\n\tendpoint: string,\n\tfileId: string,\n): Promise<string | null> {\n\ttry {\n\t\tconst cap = await discoverUploadCapability(endpoint, execute);\n\t\treturn await fetchDownloadUrl(execute, cap, fileId);\n\t} catch {\n\t\treturn null;\n\t}\n}\n","import { createContext, useContext } from 'react';\nimport { createStore, useStore as useZustandStore, type StoreApi } from 'zustand';\n\nimport { createDraftRowsSlice, type DraftRowsSlice } from './draft-rows-slice';\nimport { createRelationInfoSlice, type RelationInfoSlice } from './relation-info-slice';\n\nexport interface SheetsAuthState {\n isAuthenticated: boolean;\n accessToken: string | null;\n expiresAt: string | null;\n identityKey: string | null;\n setAuthenticated: (token: string, expiresAt: string, identityKey?: string | null) => void;\n setUnauthenticated: () => void;\n}\n\nexport type SheetsStoreState = DraftRowsSlice & RelationInfoSlice & SheetsAuthState;\n\nexport function createSheetsStore(): StoreApi<SheetsStoreState> {\n return createStore<SheetsStoreState>((set, get) => ({\n // Draft rows\n ...createDraftRowsSlice(set),\n\n // Relation info cache\n ...createRelationInfoSlice(set, get),\n\n // Auth state (standalone mode)\n isAuthenticated: false,\n accessToken: null,\n expiresAt: null,\n identityKey: null,\n setAuthenticated: (token: string, expiresAt: string, identityKey = null) =>\n set({ isAuthenticated: true, accessToken: token, expiresAt, identityKey }),\n setUnauthenticated: () => set({ isAuthenticated: false, accessToken: null, expiresAt: null, identityKey: null }),\n }));\n}\n\nexport const SheetsStoreContext = createContext<StoreApi<SheetsStoreState> | null>(null);\n\nexport function useSheetsStore<T>(selector: (state: SheetsStoreState) => T): T {\n const store = useContext(SheetsStoreContext);\n if (!store) {\n throw new Error('useSheetsStore must be used within a <SheetsProvider>');\n }\n return useZustandStore(store, selector);\n}\n\nexport function useSheetsStoreApi(): StoreApi<SheetsStoreState> {\n const store = useContext(SheetsStoreContext);\n if (!store) {\n throw new Error('useSheetsStoreApi must be used within a <SheetsProvider>');\n }\n return store;\n}\n","import type { RelationInfo } from './relation-info-slice';\n\ntype DraftRowStatus = 'idle' | 'saving' | 'error';\n\nexport interface DraftRow {\n id: string;\n values: Record<string, unknown>;\n status: DraftRowStatus;\n errors: Record<string, string> | null;\n createdAt: number;\n metaVersion: string;\n}\n\ninterface DraftRowsTableState {\n order: string[];\n map: Record<string, DraftRow>;\n template: Record<string, unknown>;\n metaVersion: string;\n columnOrder: string[];\n}\n\nexport function parseDraftTableKey(tableKey: string): { databaseId: string | null; tableName: string } | null {\n const parts = tableKey.split('::');\n if (parts.length === 2) {\n const [databaseId, tableName] = parts;\n if (!databaseId || !tableName) return null;\n return { databaseId, tableName };\n }\n return null;\n}\n\nexport interface DraftRowCreationArgs {\n tableKey: string;\n columnOrder: readonly string[];\n fieldMetaByKey: Record<string, DraftFieldMetadata | undefined>;\n relationInfoByKey?: Record<string, RelationInfo | undefined>;\n metaVersion: string;\n}\n\nexport type DraftRowsSyncArgs = DraftRowCreationArgs;\n\nexport interface DraftRowUpdateArgs {\n tableKey: string;\n draftRowId: string;\n columnKey: string;\n value: unknown;\n extraValues?: Record<string, unknown>;\n}\n\nexport interface DraftRowsSlice {\n draftRowsByTable: Record<string, DraftRowsTableState | undefined>;\n createDraftRow: (args: DraftRowCreationArgs) => string;\n updateDraftCell: (args: DraftRowUpdateArgs) => void;\n removeDraftRow: (tableKey: string, draftRowId: string) => void;\n clearDraftRowsForTable: (tableKey: string) => void;\n clearDraftRowsForDatabase: (databaseId: string) => void;\n clearAllDraftRows: () => void;\n syncDraftRowsWithMeta: (args: DraftRowsSyncArgs) => void;\n setDraftRowStatus: (args: {\n tableKey: string;\n draftRowId: string;\n status: DraftRowStatus;\n errors?: Record<string, string> | null;\n }) => void;\n}\n\ntype DraftFieldMetadata = {\n name?: string | null;\n isNotNull?: boolean | null;\n hasDefault?: boolean | null;\n type?: {\n gqlType?: string | null;\n isArray?: boolean | null;\n pgAlias?: string | null;\n pgType?: string | null;\n subtype?: string | null;\n } | null;\n};\n\ntype DraftRowsSetState = (\n\tpartial: Partial<DraftRowsSlice> | ((state: DraftRowsSlice) => Partial<DraftRowsSlice> | DraftRowsSlice),\n) => void;\n\nexport function createDraftRowsSlice(set: DraftRowsSetState): DraftRowsSlice {\n\treturn {\n draftRowsByTable: {},\n\n createDraftRow: (args) => {\n const { tableKey, columnOrder, fieldMetaByKey, relationInfoByKey, metaVersion } = args;\n\n const effectiveColumnOrder = ensureColumnOrder(columnOrder, fieldMetaByKey, relationInfoByKey);\n const template = buildTemplate(effectiveColumnOrder, relationInfoByKey);\n const draftRowId = `draft:${generateDraftSuffix()}`;\n const values = initializeValuesFromTemplate(template, draftRowId);\n\n set((state: DraftRowsSlice) => {\n const existing = state.draftRowsByTable[tableKey];\n\n const nextOrder = existing ? [...existing.order, draftRowId] : [draftRowId];\n const nextMap = {\n ...(existing?.map ?? {}),\n [draftRowId]: {\n id: draftRowId,\n values,\n status: 'idle' as const,\n errors: null,\n createdAt: Date.now(),\n metaVersion,\n },\n };\n\n return {\n draftRowsByTable: {\n ...state.draftRowsByTable,\n [tableKey]: {\n order: nextOrder,\n map: nextMap,\n template,\n metaVersion,\n columnOrder: [...effectiveColumnOrder],\n },\n },\n };\n });\n\n return draftRowId;\n },\n\n\t updateDraftCell: ({ tableKey, draftRowId, columnKey, value, extraValues }) => {\n\t set((state: DraftRowsSlice) => {\n\t const tableState = state.draftRowsByTable[tableKey];\n\t if (!tableState) return state;\n\n\t const existingRow = tableState.map[draftRowId];\n\t if (!existingRow) return state;\n\n\t let hasValueChanges = !deepEqual(existingRow.values[columnKey], value);\n\t if (!hasValueChanges && extraValues) {\n\t for (const [key, extraValue] of Object.entries(extraValues)) {\n\t if (!deepEqual(existingRow.values[key], extraValue)) {\n\t hasValueChanges = true;\n\t break;\n\t }\n\t }\n\t }\n\n\t const shouldResetErrors = existingRow.status === 'error' || existingRow.errors !== null;\n\t if (!hasValueChanges && !shouldResetErrors) return state;\n\n\t const updatedValues = hasValueChanges ? { ...existingRow.values, [columnKey]: deepClone(value) } : existingRow.values;\n\t if (hasValueChanges && extraValues) {\n\t for (const [key, extraValue] of Object.entries(extraValues)) {\n\t updatedValues[key] = deepClone(extraValue);\n\t }\n\t }\n\n\t const nextMap = {\n\t ...tableState.map,\n [draftRowId]: {\n ...existingRow,\n values: updatedValues,\n status: existingRow.status === 'error' ? ('idle' as const) : existingRow.status,\n errors: null,\n },\n };\n\n return {\n draftRowsByTable: {\n ...state.draftRowsByTable,\n [tableKey]: {\n ...tableState,\n map: nextMap,\n },\n },\n };\n });\n },\n\n removeDraftRow: (tableKey, draftRowId) => {\n set((state: DraftRowsSlice) => {\n const tableState = state.draftRowsByTable[tableKey];\n if (!tableState) return state;\n if (!tableState.map[draftRowId]) return state;\n\n const nextOrder = tableState.order.filter((id) => id !== draftRowId);\n const nextMap = { ...tableState.map };\n delete nextMap[draftRowId];\n\n const nextTableState: DraftRowsTableState | undefined = nextOrder.length\n ? { ...tableState, order: nextOrder, map: nextMap }\n : undefined;\n\n const nextByTable = { ...state.draftRowsByTable };\n if (nextTableState) {\n nextByTable[tableKey] = nextTableState;\n } else {\n delete nextByTable[tableKey];\n }\n\n return { draftRowsByTable: nextByTable };\n });\n },\n\n clearDraftRowsForTable: (tableKey) => {\n set((state: DraftRowsSlice) => {\n if (!state.draftRowsByTable[tableKey]) return state;\n const nextByTable = { ...state.draftRowsByTable };\n delete nextByTable[tableKey];\n return { draftRowsByTable: nextByTable };\n });\n },\n\n clearDraftRowsForDatabase: (databaseId) => {\n set((state: DraftRowsSlice) => {\n if (!databaseId || !Object.keys(state.draftRowsByTable).length) return state;\n let changed = false;\n const nextByTable: Record<string, DraftRowsTableState | undefined> = { ...state.draftRowsByTable };\n\n for (const tableKey of Object.keys(nextByTable)) {\n const parsed = parseDraftTableKey(tableKey);\n const matchesDatabase = parsed ? parsed.databaseId === databaseId : tableKey.includes(`${databaseId}::`);\n\n if (matchesDatabase) {\n delete nextByTable[tableKey];\n changed = true;\n }\n }\n\n return changed ? { draftRowsByTable: nextByTable } : state;\n });\n },\n\n clearAllDraftRows: () => {\n set((state: DraftRowsSlice) => {\n if (!Object.keys(state.draftRowsByTable).length) return state;\n return { draftRowsByTable: {} };\n });\n },\n\n\t syncDraftRowsWithMeta: (args) => {\n\t const { tableKey, columnOrder, fieldMetaByKey, relationInfoByKey, metaVersion } = args;\n\n\t set((state: DraftRowsSlice) => {\n\t const tableState = state.draftRowsByTable[tableKey];\n\t const effectiveColumnOrder = ensureColumnOrder(columnOrder, fieldMetaByKey, relationInfoByKey);\n\t const template = buildTemplate(effectiveColumnOrder, relationInfoByKey);\n\n\t if (!tableState) {\n\t return state;\n\t }\n\n\t if (tableState.order.length === 0) {\n\t const nextByTable = { ...state.draftRowsByTable };\n\t delete nextByTable[tableKey];\n\t return { draftRowsByTable: nextByTable };\n\t }\n\n\t const isSameMeta =\n\t tableState.metaVersion === metaVersion && shallowEqualArrays(tableState.columnOrder, effectiveColumnOrder);\n\n if (isSameMeta) return state;\n\n const nextMap: Record<string, DraftRow> = {};\n for (const draftId of tableState.order) {\n const row = tableState.map[draftId];\n if (!row) continue;\n\n const mergedValues: Record<string, unknown> = initializeValuesFromTemplate(template, draftId);\n for (const key of Object.keys(row.values)) {\n if (Object.prototype.hasOwnProperty.call(template, key)) {\n mergedValues[key] = deepClone(row.values[key]);\n }\n }\n\n nextMap[draftId] = {\n ...row,\n values: mergedValues,\n metaVersion,\n status: row.status === 'error' ? 'idle' as const : row.status,\n errors: row.status === 'error' ? null : row.errors,\n };\n }\n\n return {\n draftRowsByTable: {\n ...state.draftRowsByTable,\n [tableKey]: {\n order: [...tableState.order],\n map: nextMap,\n template,\n metaVersion,\n columnOrder: [...effectiveColumnOrder],\n },\n },\n };\n });\n },\n\n\t setDraftRowStatus: ({ tableKey, draftRowId, status, errors }) => {\n\t set((state: DraftRowsSlice) => {\n\t const tableState = state.draftRowsByTable[tableKey];\n\t if (!tableState) return state;\n\t const row = tableState.map[draftRowId];\n\t if (!row) return state;\n\t const nextErrors = errors ?? null;\n\t if (row.status === status && shallowEqualRecords(row.errors, nextErrors)) return state;\n\n\t const nextMap = {\n\t ...tableState.map,\n\t [draftRowId]: { ...row, status, errors: nextErrors },\n\t };\n\n return {\n draftRowsByTable: {\n ...state.draftRowsByTable,\n [tableKey]: { ...tableState, map: nextMap },\n },\n };\n });\n },\n };\n}\n\nfunction ensureColumnOrder(\n columnOrder: readonly string[],\n fieldMetaByKey: Record<string, DraftFieldMetadata | undefined>,\n relationInfoByKey?: Record<string, RelationInfo | undefined>,\n): string[] {\n if (columnOrder.length > 0) return [...columnOrder];\n\n const keys = new Set<string>();\n Object.keys(fieldMetaByKey).forEach((key) => {\n if (key) keys.add(key);\n });\n if (relationInfoByKey) {\n Object.keys(relationInfoByKey).forEach((key) => {\n if (key) keys.add(key);\n });\n }\n return Array.from(keys).sort((a, b) => a.localeCompare(b));\n}\n\nfunction buildTemplate(\n columnOrder: readonly string[],\n relationInfoByKey?: Record<string, RelationInfo | undefined>,\n): Record<string, unknown> {\n const template: Record<string, unknown> = {};\n\n for (const column of columnOrder) {\n if (!column) continue;\n const relationInfo = relationInfoByKey?.[column];\n\n if (relationInfo && (relationInfo.kind === 'hasMany' || relationInfo.kind === 'manyToMany')) {\n template[column] = [];\n } else {\n template[column] = null;\n }\n }\n\n return template;\n}\n\nfunction generateDraftSuffix(): string {\n const cryptoObj = typeof globalThis !== 'undefined' ? (globalThis as any).crypto : undefined;\n if (cryptoObj && typeof cryptoObj.getRandomValues === 'function') {\n const buffer = new Uint32Array(1);\n cryptoObj.getRandomValues(buffer);\n return buffer[0].toString(36).slice(0, 8);\n }\n return Math.random().toString(36).slice(2, 10);\n}\n\nfunction initializeValuesFromTemplate(template: Record<string, unknown>, draftRowId: string): Record<string, unknown> {\n const result: Record<string, unknown> = {};\n for (const [key, value] of Object.entries(template)) {\n result[key] = deepClone(value);\n }\n if (!result.id) result.id = draftRowId;\n return result;\n}\n\nfunction deepClone<T>(value: T): T {\n if (Array.isArray(value)) return value.map((item) => deepClone(item)) as unknown as T;\n if (value instanceof Date) return new Date(value.getTime()) as unknown as T;\n if (value && typeof value === 'object') {\n const result: Record<string, unknown> = {};\n for (const [key, val] of Object.entries(value as Record<string, unknown>)) {\n result[key] = deepClone(val);\n }\n return result as unknown as T;\n }\n\treturn value;\n}\n\nfunction deepEqual(a: unknown, b: unknown): boolean {\n\tif (Object.is(a, b)) return true;\n\tif (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();\n\tif (Array.isArray(a) && Array.isArray(b)) {\n\t\tif (a.length !== b.length) return false;\n\t\tfor (let i = 0; i < a.length; i += 1) {\n\t\t\tif (!deepEqual(a[i], b[i])) return false;\n\t\t}\n\t\treturn true;\n\t}\n\tif (a && b && typeof a === 'object' && typeof b === 'object') {\n\t\tconst keysA = Object.keys(a as Record<string, unknown>);\n\t\tconst keysB = Object.keys(b as Record<string, unknown>);\n\t\tif (keysA.length !== keysB.length) return false;\n\t\tfor (const key of keysA) {\n\t\t\tif (!(key in (b as Record<string, unknown>))) return false;\n\t\t\tif (!deepEqual((a as Record<string, unknown>)[key], (b as Record<string, unknown>)[key])) return false;\n\t\t}\n\t\treturn true;\n\t}\n\treturn false;\n}\n\nfunction shallowEqualRecords(\n\ta: Record<string, string> | null,\n\tb: Record<string, string> | null,\n): boolean {\n\tif (a === b) return true;\n\tif (!a || !b) return false;\n\tconst keysA = Object.keys(a);\n\tconst keysB = Object.keys(b);\n\tif (keysA.length !== keysB.length) return false;\n\tfor (const key of keysA) {\n\t\tif (a[key] !== b[key]) return false;\n\t}\n\treturn true;\n}\n\nfunction shallowEqualArrays(a: readonly string[], b: readonly string[]): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i += 1) {\n if (a[i] !== b[i]) return false;\n }\n return true;\n}\n\nexport function computeDraftMetaSignature(\n columnOrder: readonly string[],\n fieldMetaByKey: Record<string, DraftFieldMetadata | undefined>,\n relationInfoByKey?: Record<string, RelationInfo | undefined>,\n): string {\n const signatureParts = columnOrder.map((column) => {\n const typeMeta = fieldMetaByKey[column]?.type;\n const relationMeta = relationInfoByKey?.[column];\n\n const typePart = typeMeta\n ? [\n typeMeta.gqlType ?? '',\n typeMeta.isArray ? '1' : '0',\n typeMeta.pgAlias ?? '',\n typeMeta.pgType ?? '',\n typeMeta.subtype ?? '',\n ].join(':')\n : '';\n\n const relationPart = relationMeta\n ? [relationMeta.kind ?? '', relationMeta.foreignKeyField ?? '', relationMeta.relationField ?? ''].join(':')\n : '';\n\n return `${column}|${typePart}|${relationPart}`;\n });\n\n return hashString(signatureParts.join('||'));\n}\n\nfunction hashString(input: string): string {\n let hash = 0;\n for (let i = 0; i < input.length; i += 1) {\n hash = (hash << 5) - hash + input.charCodeAt(i);\n hash |= 0;\n }\n return hash.toString(16);\n}\n","import { pluralize } from 'inflekt';\nimport { cleanTable, pgFieldToCamelCase, type CleanTable, type MetaQuery } from '@constructive-io/data';\nimport { getJunctionTableNames, isJunctionTablePure } from '../utils/relation-utils';\n\nexport type RelationKind = 'belongsTo' | 'hasOne' | 'hasMany' | 'manyToMany';\n\nexport interface RelationInfo {\n kind: RelationKind;\n relatedTable?: string;\n displayCandidates: string[];\n relationField?: string;\n foreignKeyField?: string;\n junctionTable?: string;\n junctionLeftKeyField?: string;\n junctionRightKeyField?: string;\n displayName?: string;\n}\n\nexport interface RelationInfoSlice {\n relationInfoCache: Record<string, Record<string, RelationInfo>>;\n relationInfoMapCache: Record<string, Map<string, RelationInfo>>;\n setRelationInfoForTable: (tableName: string, info: Record<string, RelationInfo>) => void;\n getRelationInfoForTable: (tableName: string) => Record<string, RelationInfo> | undefined;\n getRelationInfoMapForTable: (tableName: string) => Map<string, RelationInfo> | undefined;\n rebuildRelationInfo: (tableName: string, meta: MetaQuery | undefined) => void;\n ensureRelationInfo: (tableName: string, meta: MetaQuery | undefined) => Record<string, RelationInfo>;\n clearRelationInfoCache: () => void;\n}\n\ninterface RelationInfoState {\n relationInfoCache: Record<string, Record<string, RelationInfo>>;\n relationInfoMapCache: Record<string, Map<string, RelationInfo>>;\n}\n\ntype RelationInfoSetState = (\n partial: Partial<RelationInfoState> | ((state: RelationInfoState) => Partial<RelationInfoState>),\n) => void;\n\ntype RelationInfoGetState = () => RelationInfoState;\n\nfunction toRelationInfoMap(info: Record<string, RelationInfo>): Map<string, RelationInfo> {\n return new Map(Object.entries(info));\n}\n\nfunction setTableRelationInfo(set: RelationInfoSetState, tableName: string, info: Record<string, RelationInfo>): void {\n set((state) => ({\n relationInfoCache: { ...state.relationInfoCache, [tableName]: info },\n relationInfoMapCache: { ...state.relationInfoMapCache, [tableName]: toRelationInfoMap(info) },\n }));\n}\n\nexport function createRelationInfoSlice(set: RelationInfoSetState, get: RelationInfoGetState): RelationInfoSlice {\n return {\n relationInfoCache: {},\n relationInfoMapCache: {},\n setRelationInfoForTable: (tableName, info) => setTableRelationInfo(set, tableName, info),\n getRelationInfoForTable: (tableName) => get().relationInfoCache[tableName],\n getRelationInfoMapForTable: (tableName) => get().relationInfoMapCache[tableName],\n clearRelationInfoCache: () => set({ relationInfoCache: {}, relationInfoMapCache: {} }),\n rebuildRelationInfo: (tableName: string, meta: MetaQuery | undefined) => {\n try {\n const info = buildRelationInfoFromMeta(tableName, meta);\n if (!info) return;\n setTableRelationInfo(set, tableName, info);\n } catch {\n // ignore\n }\n },\n ensureRelationInfo: (tableName: string, meta: MetaQuery | undefined) => {\n const existing = get().relationInfoCache[tableName];\n if (existing) return existing;\n const info = buildRelationInfoFromMeta(tableName, meta) || {};\n if (Object.keys(info).length) {\n setTableRelationInfo(set, tableName, info);\n }\n return info;\n },\n };\n}\n\ntype MetaTableNode = NonNullable<NonNullable<NonNullable<MetaQuery['_meta']>['tables']>[number]>;\n\nfunction toCleanTables(meta: MetaQuery | undefined): CleanTable[] {\n const tables = meta?._meta?.tables ?? [];\n return tables.filter((table): table is MetaTableNode => table != null).map((table) => cleanTable(table));\n}\n\nfunction firstFieldName(fields: Array<{ name: string }>): string | undefined {\n return fields[0]?.name;\n}\n\n/**\n * For hasOne/hasMany relations, find the FK field in the RELATED table that\n * references the current table. relation.keys contains the PK of the current\n * table (e.g. \"id\"), but the relation editor needs the FK in the child table\n * (e.g. \"questionnaireId\") to link/unlink records.\n *\n * Resolution chain:\n * 1. Related table's belongsTo relations (from cleanTable)\n * 2. Related table's foreignKeyConstraints (from raw _meta)\n */\nfunction findForeignKeyInRelatedTable(\n currentTableName: string,\n relatedTableName: string,\n allTables: CleanTable[],\n rawMetaTables: readonly MetaTableNode[],\n): string | undefined {\n // 1. Try belongsTo on the related cleaned table\n const relatedTable = allTables.find((t) => t.name === relatedTableName);\n if (relatedTable) {\n const belongsTo = relatedTable.relations.belongsTo.find(\n (rel) => rel.referencesTable === currentTableName,\n );\n if (belongsTo?.keys?.[0]?.name) return belongsTo.keys[0].name;\n }\n\n // 2. Fall back to foreignKeyConstraints on the raw _meta related table\n const rawRelated = rawMetaTables.find((t) => t.name === relatedTableName);\n if (rawRelated) {\n // v5 nested: constraints.foreignKey[]\n const v5Fks = Array.isArray(rawRelated.constraints) ? [] : rawRelated.constraints?.foreignKey;\n // v4 flat: foreignKeyConstraints[]\n const fks = v5Fks ?? rawRelated.foreignKeyConstraints ?? [];\n for (const fk of fks) {\n if (!fk) continue;\n const refName = fk.refTable?.name;\n // refTable.name is a codec name (camelCase) — match case-insensitively\n if (refName && refName.toLowerCase() === currentTableName.toLowerCase()) {\n const fieldName = fk.fields?.[0]?.name;\n if (fieldName) return pgFieldToCamelCase(fieldName);\n }\n }\n }\n\n return undefined;\n}\n\nexport function buildRelationInfoFromMeta(\n tableName: string,\n meta: MetaQuery | undefined,\n): Record<string, RelationInfo> | null {\n const tables = toCleanTables(meta);\n const table = tables.find((candidate) => candidate.name === tableName);\n if (!table) return null;\n\n const rawMetaTables = (meta?._meta?.tables ?? []).filter(\n (t): t is MetaTableNode => t != null,\n );\n\n const PRIORITY_FIELDS = [\n 'displayName',\n 'fullName',\n 'preferredName',\n 'nickname',\n 'firstName',\n 'lastName',\n 'givenName',\n 'familyName',\n 'username',\n 'handle',\n 'email',\n 'phone',\n 'title',\n 'label',\n 'slug',\n 'code',\n 'name',\n ];\n const NAME_PATTERN = /name/i;\n\n const computeCandidates = (relatedTableName?: string): string[] => {\n if (!relatedTableName) return [];\n const related = tables.find((candidate) => candidate.name === relatedTableName);\n if (!related) return [];\n\n const fieldNamesSet = new Set<string>(related.fields.map((field) => field.name));\n const explicit = PRIORITY_FIELDS.filter((k) => fieldNamesSet.has(k));\n const explicitSet = new Set(explicit);\n\n const nameLike: string[] = [];\n for (const name of fieldNamesSet) {\n if (NAME_PATTERN.test(name) && !explicitSet.has(name)) {\n nameLike.push(name);\n }\n }\n nameLike.sort((a, b) => a.length - b.length);\n\n return Array.from(new Set([...explicit, ...nameLike]));\n };\n\n const info: Record<string, RelationInfo> = {};\n table.relations.belongsTo.forEach((relation) => {\n const displayCandidates = computeCandidates(relation.referencesTable);\n const foreignKeys = relation.keys.map((key) => key.name).filter(Boolean);\n const primaryForeignKey = foreignKeys[0];\n\n if (relation.fieldName) {\n info[relation.fieldName] = {\n kind: 'belongsTo',\n relatedTable: relation.referencesTable,\n displayCandidates,\n relationField: relation.fieldName,\n foreignKeyField: primaryForeignKey,\n };\n }\n\n foreignKeys.forEach((fk) => {\n if (!fk) return;\n info[fk] = {\n kind: 'belongsTo',\n relatedTable: relation.referencesTable,\n displayCandidates,\n relationField: relation.fieldName ?? undefined,\n foreignKeyField: fk,\n };\n });\n });\n table.relations.hasOne.forEach((relation) => {\n if (relation.fieldName) {\n // relation.keys contains the PK of the CURRENT table, not the FK in the\n // related table. Resolve the actual FK field via:\n // 1. Related table's belongsTo (cleanTable)\n // 2. Related table's foreignKeyConstraints (raw _meta)\n const fkInRelated = findForeignKeyInRelatedTable(tableName, relation.referencedByTable, tables, rawMetaTables);\n info[relation.fieldName] = {\n kind: 'hasOne',\n relatedTable: relation.referencedByTable,\n displayCandidates: computeCandidates(relation.referencedByTable),\n relationField: relation.fieldName,\n foreignKeyField: fkInRelated,\n };\n }\n });\n const junctionTableNames = getJunctionTableNames(table.relations, rawMetaTables);\n\n table.relations.hasMany.forEach((relation) => {\n if (!relation.fieldName) return;\n // Skip hasMany relations pointing to junction tables (M:N covers these)\n if (junctionTableNames.has(relation.referencedByTable)) return;\n const fkInRelated = findForeignKeyInRelatedTable(tableName, relation.referencedByTable, tables, rawMetaTables);\n info[relation.fieldName] = {\n kind: 'hasMany',\n relatedTable: relation.referencedByTable,\n displayCandidates: computeCandidates(relation.referencedByTable),\n relationField: relation.fieldName,\n foreignKeyField: fkInRelated,\n };\n });\n table.relations.manyToMany.forEach((relation) => {\n if (relation.fieldName) {\n // Prefer direct key fields from enriched cleanTable()\n let junctionLeftKeyField = relation.junctionLeftKeyFields?.[0];\n let junctionRightKeyField = relation.junctionRightKeyFields?.[0];\n\n // Fallback: derive from junction table's belongsTo relations\n if (!junctionLeftKeyField || !junctionRightKeyField) {\n const junctionTableName = relation.junctionTable;\n const junctionTable = junctionTableName\n ? tables.find((candidate) => candidate.name === junctionTableName)\n : undefined;\n const junctionBelongsTo = junctionTable?.relations.belongsTo ?? [];\n if (!junctionLeftKeyField) {\n const leftRelation = junctionBelongsTo.find((entry) => entry.referencesTable === tableName);\n junctionLeftKeyField = firstFieldName(leftRelation?.keys ?? []);\n }\n if (!junctionRightKeyField) {\n const rightRelation = junctionBelongsTo.find((entry) => entry.referencesTable === relation.rightTable);\n junctionRightKeyField = firstFieldName(rightRelation?.keys ?? []);\n }\n }\n\n // Skip non-pure junction tables — they have required fields beyond the\n // two FK columns, so the manyToMany editor cannot produce valid mutations.\n if (!isJunctionTablePure(relation.junctionTable, junctionLeftKeyField, junctionRightKeyField, rawMetaTables)) {\n return;\n }\n\n info[relation.fieldName] = {\n kind: 'manyToMany',\n relatedTable: relation.rightTable,\n displayCandidates: computeCandidates(relation.rightTable),\n relationField: relation.fieldName,\n junctionTable: relation.junctionTable,\n junctionLeftKeyField,\n junctionRightKeyField,\n displayName: pluralize(relation.rightTable),\n };\n }\n });\n\n return info;\n}\n","import { singularize } from \"inflekt\";\nimport { pgFieldToCamelCase, type CleanTable, type CleanRelations, type MetaQuery } from \"@constructive-io/data\";\n\ntype PrimitiveId = string | number | null;\n\ntype MetaTable = NonNullable<NonNullable<NonNullable<MetaQuery[\"_meta\"]>[\"tables\"]>[number]>;\n\n\n/**\n * Convert a camelCase plural codec name (as used in raw _meta relation references)\n * to PascalCase singular (matching `_meta.tables[].name` format).\n * e.g. \"formResponses\" → \"FormResponse\"\n */\nfunction codecNameToTableName(name: string): string {\n if (!name) return name;\n const singular = singularize(name);\n return singular.charAt(0).toUpperCase() + singular.slice(1);\n}\n\n/**\n * Derive all relation field names from raw table metadata relations.\n * Filters out hasMany entries that point to junction tables (those are surfaced via manyToMany),\n * and deduplicates manyToMany entries targeting the same table.\n */\nexport function getAllRelationFields(\n relations: MetaTable[\"relations\"] | null | undefined,\n metaTables?: readonly MetaTable[],\n): string[] {\n if (!relations) return [];\n\n const out: string[] = [];\n const push = (fieldName?: string | null) => {\n if (fieldName) out.push(fieldName);\n };\n\n relations.belongsTo?.forEach((rel) => push(rel?.fieldName));\n relations.hasOne?.forEach((rel) => push(rel?.fieldName));\n\n const junctionNames = new Set<string>();\n relations.manyToMany?.forEach((rel) => {\n const jtName = rel?.junctionTable?.name;\n if (!jtName) return;\n // When meta tables are available, skip non-pure junction tables\n if (metaTables) {\n const leftFk = rel?.junctionLeftKeyAttributes?.[0]?.name;\n const rightFk = rel?.junctionRightKeyAttributes?.[0]?.name;\n const leftFkCamel = leftFk ? pgFieldToCamelCase(leftFk) : undefined;\n const rightFkCamel = rightFk ? pgFieldToCamelCase(rightFk) : undefined;\n // Raw _meta codec names need conversion to match MetaTable.name format\n const jtTableName = codecNameToTableName(jtName);\n if (!isJunctionTablePure(jtTableName, leftFkCamel, rightFkCamel, metaTables)) return;\n }\n junctionNames.add(jtName);\n });\n relations.hasMany?.forEach((rel) => {\n const refName = rel?.referencedBy?.name;\n if (refName && junctionNames.has(refName)) return;\n push(rel?.fieldName);\n });\n\n const seenM2N = new Map<string, { fieldName?: string | null }>();\n relations.manyToMany?.forEach((rel) => {\n const target = rel?.rightTable?.name;\n if (!target) return;\n // Skip non-pure junction table M:N relations\n if (metaTables) {\n const jtName = rel?.junctionTable?.name;\n if (jtName) {\n const leftFk = rel?.junctionLeftKeyAttributes?.[0]?.name;\n const rightFk = rel?.junctionRightKeyAttributes?.[0]?.name;\n const leftFkCamel = leftFk ? pgFieldToCamelCase(leftFk) : undefined;\n const rightFkCamel = rightFk ? pgFieldToCamelCase(rightFk) : undefined;\n const jtTableName = codecNameToTableName(jtName);\n if (!isJunctionTablePure(jtTableName, leftFkCamel, rightFkCamel, metaTables)) return;\n }\n }\n seenM2N.set(target, rel);\n });\n seenM2N.forEach((rel) => push(rel?.fieldName));\n\n return Array.from(new Set(out));\n}\n\n/**\n * Check whether a junction table is \"pure\" — i.e. it has no required fields\n * beyond the two FK columns that form the M:N link.\n *\n * Rich entity tables that PostGraphile incidentally detects as junction tables\n * (e.g. `form_response` which has FKs to both `form_question` and `form_section`\n * but also requires `entity_id`, `session_id`, etc.) should NOT be treated as\n * simple junction tables because the manyToMany editor can only set the two FK\n * fields and would produce invalid mutations.\n */\nexport function isJunctionTablePure(\n junctionTableName: string,\n leftFkField: string | undefined,\n rightFkField: string | undefined,\n metaTables: readonly MetaTable[],\n): boolean {\n if (!leftFkField || !rightFkField) return true; // Can't verify, assume pure\n const junctionMeta = metaTables.find((t) => t?.name === junctionTableName);\n if (!junctionMeta?.fields) return true; // No field info available, assume pure\n\n const exemptFields = new Set(['id', leftFkField, rightFkField]);\n\n for (const field of junctionMeta.fields) {\n if (!field?.name) continue;\n const camelName = pgFieldToCamelCase(field.name);\n if (exemptFields.has(camelName)) continue;\n if (field.isNotNull && !field.hasDefault) return false;\n }\n return true;\n}\n\n/**\n * Collect junction table names from M:N relations.\n * Used to suppress hasMany-to-junction columns and hide junction tables from UIs.\n *\n * When `metaTables` is provided, non-pure junction tables (those with extra required\n * fields beyond the two FK columns) are excluded — their hasMany entries should remain\n * visible since the manyToMany editor cannot handle them.\n */\nexport function getJunctionTableNames(\n relations: CleanRelations,\n metaTables?: readonly MetaTable[],\n): Set<string> {\n const names = new Set<string>();\n for (const rel of relations.manyToMany) {\n if (!rel.junctionTable) continue;\n if (metaTables) {\n const leftFk = rel.junctionLeftKeyFields?.[0];\n const rightFk = rel.junctionRightKeyFields?.[0];\n if (!isJunctionTablePure(rel.junctionTable, leftFk, rightFk, metaTables)) continue;\n }\n names.add(rel.junctionTable);\n }\n return names;\n}\n\nfunction extractPrimitiveId(candidate: unknown): PrimitiveId {\n if (candidate === null || candidate === undefined) return null;\n if (typeof candidate === \"string\" || typeof candidate === \"number\") {\n return candidate;\n }\n if (typeof candidate === \"object\") {\n const record = candidate as Record<string, unknown>;\n const id = record.id;\n if (typeof id === \"string\" || typeof id === \"number\") {\n return id;\n }\n }\n return null;\n}\n\nexport function normalizeForeignKeyValue(input: unknown): unknown {\n if (input === undefined) return undefined;\n if (input === null) return null;\n\n if (Array.isArray(input)) {\n return input\n .map((entry) => extractPrimitiveId(entry))\n .filter((entry): entry is PrimitiveId => entry !== undefined);\n }\n\n return extractPrimitiveId(input);\n}\n\n/**\n * Find the foreign key field in a related table that references the current table\n */\nfunction findForeignKeyField(\n currentTableName: string,\n relatedTableName: string,\n allTables?: CleanTable[],\n): string | undefined {\n if (!allTables) return undefined;\n\n // Find the related table\n const relatedTable = allTables.find((table) => table.name === relatedTableName);\n if (!relatedTable) return undefined;\n\n // Look for a belongsTo relation in the related table that references our current table\n const belongsToRelation = relatedTable.relations.belongsTo.find(\n (relation) => relation.referencesTable === currentTableName,\n );\n\n if (belongsToRelation && belongsToRelation.keys?.[0]?.name) {\n return belongsToRelation.keys[0].name;\n }\n\n return undefined;\n}\n\nexport interface RelationshipInfo {\n relationType: \"belongsTo\" | \"hasOne\" | \"hasMany\" | \"manyToMany\";\n relationField: string;\n relatedTableName: string;\n foreignKeyField?: string;\n junctionTableName?: string;\n junctionLeftKey?: string;\n junctionRightKey?: string;\n}\n\n/**\n * Extract relationship information from table metadata for a specific field\n * For hasMany/hasOne relations, we need to find the actual foreign key field in the related table\n */\nexport function getRelationshipInfo(\n currentTable: CleanTable,\n relationFieldName: string,\n allTables?: CleanTable[],\n): RelationshipInfo | null {\n const { relations } = currentTable;\n\n // Check belongsTo relations\n const belongsToRelation = relations.belongsTo.find((rel) => rel.fieldName === relationFieldName);\n if (belongsToRelation) {\n // For belongsTo: get the foreign key field name from the keys array\n const foreignKeyField = belongsToRelation.keys?.[0]?.name;\n return {\n relationType: \"belongsTo\",\n relationField: relationFieldName,\n relatedTableName: belongsToRelation.referencesTable,\n foreignKeyField: foreignKeyField,\n };\n }\n\n // Check hasOne relations\n const hasOneRelation = relations.hasOne.find((rel) => rel.fieldName === relationFieldName);\n if (hasOneRelation) {\n // For hasOne: find the foreign key field in the related table that references our current table\n const foreignKeyField = findForeignKeyField(\n currentTable.name,\n hasOneRelation.referencedByTable,\n allTables,\n );\n return {\n relationType: \"hasOne\",\n relationField: relationFieldName,\n relatedTableName: hasOneRelation.referencedByTable,\n foreignKeyField: foreignKeyField,\n };\n }\n\n // Check hasMany relations\n const hasManyRelation = relations.hasMany.find((rel) => rel.fieldName === relationFieldName);\n if (hasManyRelation) {\n // For hasMany: find the foreign key field in the related table that references our current table\n const foreignKeyField = findForeignKeyField(\n currentTable.name,\n hasManyRelation.referencedByTable,\n allTables,\n );\n return {\n relationType: \"hasMany\",\n relationField: relationFieldName,\n relatedTableName: hasManyRelation.referencedByTable,\n foreignKeyField: foreignKeyField,\n };\n }\n\n // Check manyToMany relations\n const manyToManyRelation = relations.manyToMany.find(\n (rel) => rel.fieldName === relationFieldName,\n );\n if (manyToManyRelation) {\n return {\n relationType: \"manyToMany\",\n relationField: relationFieldName,\n relatedTableName: manyToManyRelation.rightTable,\n junctionTableName: manyToManyRelation.junctionTable,\n junctionLeftKey: manyToManyRelation.junctionLeftKeyFields?.[0],\n junctionRightKey: manyToManyRelation.junctionRightKeyFields?.[0],\n };\n }\n\n return null;\n}\n\n/**\n * Get a display-friendly label from a record using common field patterns\n */\nconst DISPLAY_LABEL_FIELDS = [\n \"name\", \"title\", \"label\", \"displayName\", \"fullName\",\n \"email\", \"username\", \"description\", \"code\",\n];\n\nexport function getRecordDisplayLabel(record: any): string {\n if (!record || typeof record !== \"object\") {\n return String(record || \"\");\n }\n\n // Try common display field patterns\n for (const field of DISPLAY_LABEL_FIELDS) {\n if (record[field] != null && String(record[field]).trim()) {\n return String(record[field]);\n }\n }\n\n // Fallback to ID\n if (record.id != null) {\n return `Record ${record.id}`;\n }\n\n return \"Unknown Record\";\n}\n\n/**\n * Get record ID, handling different ID field patterns\n */\nexport function getRecordId(record: any): string {\n if (!record || typeof record !== \"object\") {\n return String(record || \"\");\n }\n\n // Try common ID field patterns\n const idFields = [\"id\", \"uuid\", \"_id\", \"pk\"];\n\n for (const field of idFields) {\n if (record[field] != null) {\n return String(record[field]);\n }\n }\n\n // Fallback to first field value\n const keys = Object.keys(record);\n if (keys.length > 0) {\n return String(record[keys[0]] || \"\");\n }\n\n return \"\";\n}\n","const KEY_PREFIX = 'sheets-auth-token';\n\nfunction storageKey(databaseId: string): string {\n\treturn `${KEY_PREFIX}:${databaseId}`;\n}\n\nfunction getStorage(): Storage | null {\n\tif (typeof window === 'undefined') return null;\n\ttry {\n\t\treturn window.localStorage;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport interface StoredToken {\n\taccessToken: string;\n\texpiresAt: string;\n\tidentityKey?: string | null;\n}\n\nexport function getStoredToken(databaseId: string): StoredToken | null {\n\tconst storage = getStorage();\n\tif (!storage) return null;\n\n\ttry {\n\t\tconst raw = storage.getItem(storageKey(databaseId));\n\t\tif (!raw) return null;\n\t\tconst parsed = JSON.parse(raw) as StoredToken;\n\t\tif (!parsed.accessToken || !parsed.expiresAt) return null;\n\t\tif (parsed.identityKey != null && typeof parsed.identityKey !== 'string') return null;\n\t\treturn parsed;\n\t} catch {\n\t\treturn null;\n\t}\n}\n\nexport function setStoredToken(\n\tdatabaseId: string,\n\taccessToken: string,\n\texpiresAt: string,\n\tidentityKey?: string | null,\n): void {\n\tconst storage = getStorage();\n\tif (!storage) return;\n\n\ttry {\n\t\tconst data: StoredToken = { accessToken, expiresAt, identityKey };\n\t\tstorage.setItem(storageKey(databaseId), JSON.stringify(data));\n\t} catch {\n\t\t// Silently fail — localStorage might be full or unavailable\n\t}\n}\n\nexport function clearStoredToken(databaseId: string): void {\n\tconst storage = getStorage();\n\tif (!storage) return;\n\n\ttry {\n\t\tstorage.removeItem(storageKey(databaseId));\n\t} catch {\n\t\t// Silently fail\n\t}\n}\n","/**\n * Injectable logger seam for @constructive-io/sheets.\n *\n * The host app may provide a custom logger via SheetsConfig.logger. The provider\n * installs it into this module singleton (see sheets-provider.tsx), so any module\n * or hook can log without threading the logger through props/context.\n *\n * Default behaviour matches the prior console.* calls. `debug` is omitted from the\n * default logger (no-op) so verbose diagnostics stay silent unless a host opts in.\n */\nexport interface SheetsLogger {\n\tdebug?(msg: string, ctx?: unknown): void;\n\twarn(msg: string, ctx?: unknown): void;\n\terror(msg: string, ctx?: unknown): void;\n}\n\nconst defaultLogger: SheetsLogger = {\n\twarn: (...a) => console.warn(...a),\n\terror: (...a) => console.error(...a),\n\t// debug omitted = no-op\n};\n\nlet active: SheetsLogger = defaultLogger;\n\n/**\n * Install (or reset) the active logger. Pass a host logger to override; pass\n * null/undefined to restore the default. Host overrides are merged over the\n * default so a partial logger still gets working warn/error.\n */\nexport function setSheetsLogger(l?: SheetsLogger | null): void {\n\tactive = l ? { ...defaultLogger, ...l } : defaultLogger;\n}\n\n/** Get the active logger. Safe to call anywhere (returns the default until set). */\nexport function sheetsLogger(): SheetsLogger {\n\treturn active;\n}\n","/**\n * Locale seam for @constructive-io/sheets.\n *\n * The host app may set a BCP-47 locale via SheetsConfig.locale. The provider\n * installs it into this module singleton (see sheets-provider.tsx), so any cell\n * renderer / editor can format dates and numbers locale-aware without threading\n * the locale through props/context. Defaults to 'en-US' (the prior hardcoded\n * behavior), so omitting `locale` changes nothing.\n */\nconst DEFAULT_LOCALE = 'en-US';\n\nlet active: string = DEFAULT_LOCALE;\n\n/** Install (or reset) the active locale. Pass null/undefined to restore the default. */\nexport function setSheetsLocale(locale?: string | null): void {\n\tactive = locale || DEFAULT_LOCALE;\n}\n\n/** Get the active locale (BCP-47). Safe to call anywhere; returns 'en-US' until set. */\nexport function sheetsLocale(): string {\n\treturn active;\n}\n","import type { SheetsScopeKey } from '../context/sheets-context';\n\nexport function isSheetsScopeKey(value: unknown): value is SheetsScopeKey {\n\tif (!value || typeof value !== 'object') return false;\n\tconst candidate = value as Record<string, unknown>;\n\treturn 'databaseId' in candidate && 'endpoint' in candidate && 'identityKey' in candidate;\n}\n\nexport const sheetsQueryKeys = {\n\troot: ['sheets'] as const,\n\tscope: (scope: SheetsScopeKey) => ['sheets', scope] as const,\n\tmeta: (scope: SheetsScopeKey) => [...sheetsQueryKeys.scope(scope), 'meta'] as const,\n\ttypeFields: (scope: SheetsScopeKey, typeName: string) =>\n\t\t[...sheetsQueryKeys.scope(scope), 'type-fields', typeName] as const,\n\tenumValues: (scope: SheetsScopeKey, typeName: string) =>\n\t\t[...sheetsQueryKeys.scope(scope), 'enum-values', typeName] as const,\n\trelations: (scope: SheetsScopeKey, tableName: string) =>\n\t\t[...sheetsQueryKeys.scope(scope), 'relations', tableName] as const,\n\ttable: (scope: SheetsScopeKey, tableName: string) => [...sheetsQueryKeys.scope(scope), 'table', tableName] as const,\n\ttableRows: (scope: SheetsScopeKey, tableName: string, options?: unknown) =>\n\t\t[...sheetsQueryKeys.table(scope, tableName), 'rows', options] as const,\n\ttableRow: (scope: SheetsScopeKey, tableName: string, id: unknown) =>\n\t\t[...sheetsQueryKeys.table(scope, tableName), 'row', id] as const,\n\ttableCount: (scope: SheetsScopeKey, tableName: string, where?: Record<string, unknown> | null) =>\n\t\t[...sheetsQueryKeys.table(scope, tableName), 'count', where] as const,\n\tinfiniteTable: (scope: SheetsScopeKey, tableName: string) =>\n\t\t[...sheetsQueryKeys.scope(scope), 'infinite-table', tableName] as const,\n\tinfiniteTablePage: (scope: SheetsScopeKey, tableName: string, pageIndex: number, options: unknown) =>\n\t\t[...sheetsQueryKeys.infiniteTable(scope, tableName), 'page', pageIndex, options] as const,\n\tinfiniteTableTotalCount: (scope: SheetsScopeKey, tableName: string, where?: Record<string, unknown>) =>\n\t\t[...sheetsQueryKeys.infiniteTable(scope, tableName), 'totalCount', where] as const,\n\tcursorTable: (scope: SheetsScopeKey, tableName: string, options?: unknown) =>\n\t\t[...sheetsQueryKeys.scope(scope), 'cursor-table', tableName, options] as const,\n} as const;\n","import { META_CONTRACT_REQUIREMENTS, type MetaContractIntrospectionQuery } from '@constructive-io/data';\n\nconst fields = (names: readonly string[]) => names.map((name) => ({ name }));\n\n/** Current `_meta` type signature for tests using an injected execute seam. */\nexport function createMetaContractFixture(): MetaContractIntrospectionQuery {\n\treturn Object.fromEntries(\n\t\tObject.entries(META_CONTRACT_REQUIREMENTS).map(([alias, requirement]) => [\n\t\t\talias,\n\t\t\t{ name: requirement.typeName, fields: fields(requirement.fields) },\n\t\t]),\n\t) as MetaContractIntrospectionQuery;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACaA,IAAAA,gBAAwB;AACxB,IAAAC,kBAAsB;AAEtB,IAAAC,sBAA4B;AAE5B,IAAAC,eAMO;;;ACxBP,IAAAC,gBAAkD;AAClD,yBAAiD;AACjD,IAAAC,kBAA2D;;;ACF3D,mBAA0C;AAwEnC,IAAM,oBAAgB,4BAAyC,IAAI;;;ACvE1E,IAAAC,kBAAsB;AAEtB,IAAAC,eAA4D;;;ACoB5D,qBAAsC;AAEtC,kBAA4B;AAoD5B,eAAsB,oBAAoB,QAAsC;AAC/E,MAAI,CAAC,WAAW,QAAQ,QAAQ;AAC/B,UAAM,wBAAY,WAAW,yEAAyE;AAAA,EACvG;AACA,QAAM,SAAS,MAAM,OAAO,OAAO,OAAO,WAAW,MAAM;AAC3D,QAAM,QAAQ,IAAI,WAAW,MAAM;AACnC,MAAI,MAAM;AACV,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACtC,WAAO,MAAM,CAAC,EAAE,SAAS,EAAE,EAAE,SAAS,GAAG,GAAG;AAAA,EAC7C;AACA,SAAO;AACR;AAMA,IAAM,kBAAkB,oBAAI,IAAuC;AAW5D,SAAS,yBAAyB,UAAkB,SAAqD;AAC/G,QAAM,SAAS,gBAAgB,IAAI,QAAQ;AAC3C,MAAI,OAAQ,QAAO;AAEnB,QAAM,WAAW,YAAY;AAC5B,UAAM,OAAO,MAAM,YAA2C,sCAAsB,CAAC;AACrF,UAAM,SAAS,MAAM;AACrB,QAAI,CAAC,QAAQ;AACZ,YAAM,wBAAY,WAAW,4CAA4C;AAAA,IAC1E;AACA,WAAO,wBAAwB,MAAM;AAAA,EACtC,GAAG;AAGH,UA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;AAEA,SAAO,EAAE,SAAS,eAAe,WAAW,MAAM;AACnD;AAWO,SAAS,mBAAmB,EAAE,SAAS,SAAS,GAA4B;AAKlF,QAAM,EAAE,SAAS,cAAc,QAAI,uBAAQ,MAAM,kBAAkB,OAAO,GAAG,CAAC,CAAC;AAG/E,QAAM,kBAAc;AAAA,IACnB,MACC,IAAI,gCAAY;AAAA,MACf,gBAAgB;AAAA,QACf,SAAS,EAAE,OAAO,OAAO,QAAQ,EAAE;AAAA,QACnC,WAAW,EAAE,OAAO,MAAM;AAAA,MAC3B;AAAA,IACD,CAAC;AAAA,IACF,CAAC;AAAA,EACF;AAEA,SACC;AAAA,IAAC;AAAA;AAAA,MACA,QAAQ;AAAA,QACP,UAAU;AAAA,QACV,MAAM,EAAE,MAAM,YAAY,UAAU,MAAM,OAAO;AAAA,QACjD;AAAA,QACA;AAAA,QACA;AAAA,MACD;AAAA,MAEC;AAAA;AAAA,EACF;AAEF;AAMO,IAAM,eAA0B;AAAA,EACtC,MAAM;AAAA,EACN,QAAQ;AAAA,IACP,EAAE,MAAM,MAAM,SAAS,QAAQ,QAAQ,OAAO;AAAA,IAC9C,EAAE,MAAM,QAAQ,SAAS,UAAU,QAAQ,OAAO;AAAA,IAClD,EAAE,MAAM,SAAS,SAAS,UAAU,QAAQ,OAAO;AAAA,IACnD,EAAE,MAAM,YAAY,SAAS,WAAW,QAAQ,UAAU;AAAA,IAC1D,EAAE,MAAM,aAAa,SAAS,YAAY,QAAQ,cAAc;AAAA,EACjE;AAAA,EACA,MAAM;AAAA,IACL;AAAA,MACC,IAAI;AAAA,MACJ,MAAM;AAAA,MACN,OAAO;AAAA,MACP,UAAU;AAAA,MACV,WAAW;AAAA,IACZ;AAAA,IACA;AAAA,MACC,IAAI;AAAA,MACJ,MAAM;AAAA,MACN,OAAO;AAAA,MACP,UAAU;AAAA,MACV,WAAW;AAAA,IACZ;AAAA,EACD;AACD;","names":["import_react","import_graphql","import_react_query","import_data","import_react","import_zustand","import_graphql","import_data","query","data","url","idScalar","import_data","import_react","import_inflekt","import_data","import_data","fields","active","useZustandStore","store","import_data","import_jsx_runtime","documentToString"]}
|