@constructive-io/sheets 0.14.1 → 0.15.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 +231 -157
- package/dist/advanced.cjs +7192 -3840
- package/dist/advanced.cjs.map +1 -1
- package/dist/advanced.d.cts +2 -2
- package/dist/advanced.d.ts +2 -2
- package/dist/advanced.js +5 -5
- package/dist/auth.cjs.map +1 -1
- package/dist/auth.js +3 -3
- package/dist/chunk-CJ4PRA64.js +312 -0
- package/dist/chunk-CJ4PRA64.js.map +1 -0
- package/dist/chunk-II3MSNRO.js +18 -0
- package/dist/chunk-II3MSNRO.js.map +1 -0
- package/dist/{chunk-BYAYBXVB.js → chunk-J7KK4UWI.js} +6 -6
- package/dist/chunk-MBSHDF55.js +839 -0
- package/dist/chunk-MBSHDF55.js.map +1 -0
- package/dist/chunk-MOFFS5WQ.js +128 -0
- package/dist/chunk-MOFFS5WQ.js.map +1 -0
- package/dist/chunk-VCBY2AMT.js +8920 -0
- package/dist/chunk-VCBY2AMT.js.map +1 -0
- package/dist/{chunk-YJZFHL2D.js → chunk-ZOQDSOMO.js} +50 -312
- package/dist/chunk-ZOQDSOMO.js.map +1 -0
- package/dist/date-editor-ORCB43ZM.js +346 -0
- package/dist/date-editor-ORCB43ZM.js.map +1 -0
- package/dist/{grid-cell-types-C2-ocDS7.d.cts → grid-cell-types-YNIVK4hN.d.cts} +71 -18
- package/dist/{grid-cell-types-C2-ocDS7.d.ts → grid-cell-types-YNIVK4hN.d.ts} +71 -18
- package/dist/index.cjs +22733 -12052
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1432 -266
- package/dist/index.d.ts +1432 -266
- package/dist/index.js +12688 -6097
- package/dist/index.js.map +1 -1
- package/dist/sheets-context-Bb7ZoNBg.d.cts +436 -0
- package/dist/sheets-context-CPuf31LS.d.ts +436 -0
- package/dist/testing.cjs +1170 -589
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.d.cts +80 -11
- package/dist/testing.d.ts +80 -11
- package/dist/testing.js +778 -147
- package/dist/testing.js.map +1 -1
- package/package.json +4 -5
- package/dist/chunk-4EZ6A23C.js +0 -44
- package/dist/chunk-4EZ6A23C.js.map +0 -1
- package/dist/chunk-6Y7CZ5VS.js +0 -168
- package/dist/chunk-6Y7CZ5VS.js.map +0 -1
- package/dist/chunk-BGL6EBTE.js +0 -446
- package/dist/chunk-BGL6EBTE.js.map +0 -1
- package/dist/chunk-ER3FIDK7.js +0 -4383
- package/dist/chunk-ER3FIDK7.js.map +0 -1
- package/dist/chunk-GZM2CSTR.js +0 -279
- package/dist/chunk-GZM2CSTR.js.map +0 -1
- package/dist/chunk-X7DHTSOX.js +0 -21
- package/dist/chunk-X7DHTSOX.js.map +0 -1
- package/dist/chunk-YJZFHL2D.js.map +0 -1
- package/dist/date-editor-G26WKILO.js +0 -358
- package/dist/date-editor-G26WKILO.js.map +0 -1
- package/dist/map-picker-ZUGGOIZS.js +0 -290
- package/dist/map-picker-ZUGGOIZS.js.map +0 -1
- package/dist/sheets-context-CHUVJCff.d.ts +0 -245
- package/dist/sheets-context-C_MkTxXm.d.cts +0 -245
- /package/dist/{chunk-BYAYBXVB.js.map → chunk-J7KK4UWI.js.map} +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/context/sheets-upload-discovery.ts","../src/context/sheets-upload-presigned.ts","../src/context/sheets-execute.ts","../src/hooks/query-keys.ts","../src/utils/sheets-logger.ts"],"sourcesContent":["/**\n * The FALLBACK upload path: shape discovery over the full introspection.\n *\n * Used only for a storage service whose `_meta` names no upload mutation (an\n * older server), and by hosts that call `createSheetsUpload` directly. It reads\n * the full introspection once per endpoint and finds root mutations with the\n * upload input and payload shape, and the fields that resolve a download URL by\n * file id. The model-driven path in `uploads/` replaces all of this when the\n * storage `_meta` names the upload mutation.\n */\n\nimport { getIntrospectionQuery } from 'graphql';\n\nimport { createError } from '@constructive-io/data';\n\nimport type { SheetsStorageTransport } from './sheets-context';\nimport type { SheetsExecuteFn, SheetsFileValue, SheetsUploadFn, SheetsUploadResult } from './sheets-execute';\nimport {\n\tUPLOAD_PAYLOAD_FIELDS,\n\treadUploadPayload,\n\ttransferFile,\n\twithUnfinishedUpload,\n\ttype FileProjection,\n\ttype UploadPayload,\n} from './sheets-upload-presigned';\n\n// ============================================================================\n// Shape discovery over the full introspection (cached per endpoint)\n// ============================================================================\n\nexport interface UploadCapability {\n\t/** Upload mutation field name, discovered by shape. */\n\tuploadFieldName: string;\n\t/** The upload input object type name. */\n\tinputTypeName: string;\n\thasFileProjection: boolean;\n\t/** Payload fields the mutation returns. Discovery sets it; a capability built by hand may leave it out. */\n\tpayloadFieldNames?: readonly string[];\n\t/** Input fields the mutation accepts. Discovery sets it; a capability built by hand may leave it out. */\n\tinputFieldNames?: readonly string[];\n\tdownload: DownloadByIdResult | null;\n}\n\ninterface DownloadByIdResult {\n\t/** Query field used to resolve downloadUrl by id. */\n\tfileByIdField: string;\n\t/** 'id' singular accessor, 'connection' filtered connection, 'nodeId' Relay node. */\n\tfileByIdArgName: 'id' | 'nodeId' | 'connection';\n\t/** The file object type name. */\n\tfileTypeName: string;\n\tidScalarName?: string;\n\tconnectionFilterArgName?: string;\n\tconnectionIdField?: string;\n\tconnectionIdOperator?: string;\n\tconnectionNodesField?: string;\n\tconnectionHasFirst?: boolean;\n}\n\ninterface StorageCapabilities {\n\t/** The op `discoverUploadCapability(endpoint, execute)` returns: `uploadAppFile`, else the first op that takes a `bucketKey`. */\n\tupload: UploadCapability | null;\n\t/** Every root upload op the endpoint exposes, one per storage plane. */\n\tuploads: Omit<UploadCapability, 'download'>[];\n\t/** The endpoint's only upload op, with its download lookup; null when it has none or several. */\n\tsole: UploadCapability | null;\n\tdownload: DownloadByIdResult | null;\n\tbatch: DownloadByIdResult | null;\n}\n\nlet capabilityCache = new WeakMap<SheetsExecuteFn, Map<string, Promise<StorageCapabilities>>>();\n\n/** Test-only: clear cached storage capabilities between cases. */\nexport function __resetUploadCapabilityCache(): void {\n\tcapabilityCache = new WeakMap();\n}\n\nasync function discoverStorageCapabilities(endpoint: string, execute: SheetsExecuteFn): Promise<StorageCapabilities> {\n\tlet endpoints = capabilityCache.get(execute);\n\tif (!endpoints) {\n\t\tendpoints = new Map();\n\t\tcapabilityCache.set(execute, endpoints);\n\t}\n\tconst cached = endpoints.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) throw createError.badRequest('Uploads are not enabled for this endpoint.');\n\t\treturn resolveStorageCapabilities(schema);\n\t})();\n\t// Don't cache a rejected discovery: let the next attempt retry.\n\tpromise.catch(() => endpoints.delete(endpoint));\n\tendpoints.set(endpoint, promise);\n\treturn promise;\n}\n\n/**\n * The endpoint's upload op. Name it when the endpoint serves several storage\n * planes; the named op must still carry the upload shape.\n */\nexport async function discoverUploadCapability(\n\tendpoint: string,\n\texecute: SheetsExecuteFn,\n\tuploadFieldName?: string,\n): Promise<UploadCapability> {\n\tconst { upload, uploads } = await discoverStorageCapabilities(endpoint, execute);\n\tif (uploadFieldName) {\n\t\tconst named = uploads.find((candidate) => candidate.uploadFieldName === uploadFieldName);\n\t\tif (!named) throw createError.badRequest(`Uploads are not enabled for this endpoint: it has no ${uploadFieldName}.`);\n\t\treturn { ...named, download: null };\n\t}\n\tif (!upload) capabilityCache.get(execute)?.delete(endpoint);\n\treturn requireUploadCapability(upload);\n}\n\n/**\n * The fallback's upload op for the grid: exactly one plane, or a reason. The\n * grid never picks between several planes by name.\n */\nexport async function discoverSoleUploadCapability(storage: SheetsStorageTransport): Promise<UploadCapability> {\n\tconst { uploads, sole } = await discoverStorageCapabilities(storage.endpoint, storage.execute);\n\tif (uploads.length > 1) {\n\t\tthrow createError.badRequest('The storage service has several file stores, and none is chosen for this column.');\n\t}\n\tif (!sole) {\n\t\tcapabilityCache.get(storage.execute)?.delete(storage.endpoint);\n\t\tthrow createError.badRequest('Uploads are not enabled for this storage service.');\n\t}\n\treturn sole;\n}\n\nfunction requireUploadCapability(upload: UploadCapability | null): UploadCapability {\n\tif (!upload) throw createError.badRequest('Uploads are not enabled for this endpoint.');\n\treturn upload;\n}\n\n// --- Minimal introspection shapes (only what discovery reads) ---\n\ninterface IntrospectionTypeRef {\n\tkind: string;\n\tname?: string | null;\n\tofType?: IntrospectionTypeRef | null;\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 and real results). */\nexport interface IntrospectionSchema {\n\tqueryType?: { name: string } | null;\n\tmutationType?: { name: string } | null;\n\ttypes: ReadonlyArray<IntrospectionType>;\n}\n\nfunction namedTypeName(ref: IntrospectionTypeRef | null | undefined): string | null {\n\tlet cur = ref;\n\twhile (cur && (cur.kind === 'NON_NULL' || cur.kind === 'LIST')) cur = cur.ofType ?? null;\n\treturn cur?.name ?? null;\n}\n\n/** True when the outer wrapper (after NON_NULL) is a LIST. */\nfunction isListTypeRef(ref: IntrospectionTypeRef | null | undefined): boolean {\n\tlet cur = ref;\n\twhile (cur && cur.kind === 'NON_NULL') cur = cur.ofType ?? null;\n\treturn cur?.kind === 'LIST';\n}\n\n/**\n * The fallback reads the file row by an `id` field, as the projection names it.\n * The model-driven path reads the files table's real key instead.\n */\nconst PK_FIELD_NAME = 'id';\n\n/** Pure resolver over an introspection `__schema`, for direct tests. */\nexport function resolveUploadCapability(schema: IntrospectionSchema): UploadCapability {\n\treturn requireUploadCapability(resolveStorageCapabilities(schema).upload);\n}\n\nfunction resolveStorageCapabilities(schema: IntrospectionSchema): StorageCapabilities {\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\tconst t = typeName ? typeByName.get(typeName) : undefined;\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\tconst t = typeName ? typeByName.get(typeName) : undefined;\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', 'key', 'deduplicated'];\n\tconst INPUT_FIELDS = ['contentHash', 'contentType', 'size'];\n\t// The earlier API only knew ops that take a `bucketKey`; its pick keeps that rule.\n\tconst LEGACY_INPUT_FIELDS = [...INPUT_FIELDS, 'bucketKey'];\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\tlet upload: Omit<UploadCapability, 'download'> | null = null;\n\tconst uploads: Omit<UploadCapability, 'download'>[] = [];\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 (inputTypeName && inputHasFields(inputTypeName, INPUT_FIELDS) && objectHasFields(payloadTypeName, PAYLOAD_FIELDS)) {\n\t\t\tconst payloadFields = typeByName.get(payloadTypeName ?? '')?.fields ?? [];\n\t\t\tconst candidate = {\n\t\t\t\tuploadFieldName: field.name,\n\t\t\t\tinputTypeName,\n\t\t\t\thasFileProjection: payloadFields.some(\n\t\t\t\t\t(f) => f.name === 'file' && !isListTypeRef(f.type) && namedTypeName(f.type) === 'JSON',\n\t\t\t\t),\n\t\t\t\tpayloadFieldNames: payloadFields.map((f) => f.name),\n\t\t\t\tinputFieldNames: (typeByName.get(inputTypeName)?.inputFields ?? []).map((f) => f.name),\n\t\t\t};\n\t\t\tuploads.push(candidate);\n\t\t\t// The pick of the earlier API (`discoverUploadCapability` without a name, and\n\t\t\t// `createSheetsUpload`). The grid's fallback (`discoverSoleUploadCapability`)\n\t\t\t// refuses to choose between planes.\n\t\t\tif (!inputHasFields(inputTypeName, LEGACY_INPUT_FIELDS) || (upload?.uploadFieldName === 'uploadAppFile')) continue;\n\t\t\tif (field.name === 'uploadAppFile') upload = candidate;\n\t\t\telse upload ??= candidate;\n\t\t}\n\t}\n\n\tconst fileTypes = 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')) fileTypes.add(t.name);\n\t}\n\n\t// Legacy: the file type is read from the upload op's name (uploadAppFile → AppFile).\n\t// Only this fallback does so; the model-driven path reads it from `_meta`.\n\tconst uploadType = upload?.uploadFieldName.replace(/^upload/, '') ?? 'AppFile';\n\tconst uploadDownload = resolveDownloadByIdField(typeByName, queryType, fileTypes, uploadType);\n\tconst preferredPreviewType = fileTypes.has('AppFile') ? 'AppFile' : uploadType;\n\tconst previewType = fileTypes.has(preferredPreviewType)\n\t\t? preferredPreviewType\n\t\t: uploadDownload?.fileTypeName ?? preferredPreviewType;\n\tconst download = previewType === uploadType\n\t\t? uploadDownload\n\t\t: resolveDownloadByIdField(typeByName, queryType, fileTypes, previewType);\n\tconst batch = resolveConnectionDownloadField(typeByName, queryType, fileTypes, previewType, true);\n\n\tconst only = uploads.length === 1 ? uploads[0]! : null;\n\tconst sole = only\n\t\t? {\n\t\t\t...only,\n\t\t\tdownload: only === upload\n\t\t\t\t? uploadDownload\n\t\t\t\t: resolveDownloadByIdField(typeByName, queryType, fileTypes, only.uploadFieldName.replace(/^upload/, '')),\n\t\t}\n\t\t: null;\n\n\treturn {\n\t\tupload: upload ? { ...upload, download: uploadDownload } : null,\n\t\tuploads,\n\t\tsole,\n\t\tdownload,\n\t\tbatch,\n\t};\n}\n\nfunction resolveDownloadByIdField(\n\ttypeByName: Map<string, IntrospectionType>,\n\tqueryType: IntrospectionType | null | undefined,\n\tfileTypesWithDownloadUrl: Set<string>,\n\tpreferred: string,\n): DownloadByIdResult | null {\n\t// 1. A singular by-id accessor, e.g. appFile(id:).\n\tlet singular: DownloadByIdResult | null = null;\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\tconst candidate: DownloadByIdResult = {\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\tif (returnTypeName === preferred) return candidate;\n\t\t\tsingular ??= candidate;\n\t\t}\n\t}\n\n\t// 2. A connection filtered by id (Relay-disabled backends).\n\tconst connection = resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, preferred);\n\tif (connection?.fileTypeName === preferred) return connection;\n\tif (singular || connection) return singular ?? connection;\n\n\t// 3. Relay `node(nodeId:)`, last resort.\n\tconst nodeField = queryType?.fields?.find((f) => f.name === 'node' && f.args.some((a) => a.name === 'nodeId'));\n\tif (nodeField && fileTypesWithDownloadUrl.size > 0) {\n\t\tconst fileTypeName = fileTypesWithDownloadUrl.has(preferred) ? preferred : [...fileTypesWithDownloadUrl][0]!;\n\t\treturn { fileByIdField: 'node', fileByIdArgName: 'nodeId', fileTypeName };\n\t}\n\treturn null;\n}\n\nfunction resolveConnectionDownloadField(\n\ttypeByName: Map<string, IntrospectionType>,\n\tqueryType: IntrospectionType | null | undefined,\n\tfileTypesWithDownloadUrl: Set<string>,\n\tpreferred: string,\n\tbatch = false,\n): DownloadByIdResult | null {\n\tconst EQUALITY_OPERATORS = ['equalTo', 'eq'];\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\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\t\tif (batch && (fileTypeName !== preferred ||\n\t\t\t!typeByName.get(fileTypeName)?.fields?.some((candidate) => candidate.name === PK_FIELD_NAME))) continue;\n\t\tconst connectionHasFirst = field.args.some((arg) => arg.name === 'first');\n\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\tif (idFieldType?.kind === 'INPUT_OBJECT' && idFieldType.inputFields) {\n\t\t\t\tconst inputFields = idFieldType.inputFields;\n\t\t\t\tconst opField = batch\n\t\t\t\t\t? inputFields.find((f) => f.name === 'in' && isListTypeRef(f.type))\n\t\t\t\t\t: EQUALITY_OPERATORS.map((op) => inputFields.find((f) => f.name === op)).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\tconnectionHasFirst,\n\t\t\t\t\t});\n\t\t\t\t\tbreak;\n\t\t\t\t}\n\t\t\t\tcontinue;\n\t\t\t}\n\n\t\t\tif (!batch && (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\tconnectionHasFirst,\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\treturn candidates.find((c) => c.fileTypeName === preferred) ?? candidates[0]!;\n}\n\n// ============================================================================\n// Fallback: upload op call\n// ============================================================================\n\ninterface UploadOpInput {\n\tbucketKey?: string;\n\tisPublic?: boolean;\n\tdatabaseId?: string;\n\tcontentHash: string;\n\tcontentType: string;\n\tsize: number;\n\tfilename: string;\n}\n\n/**\n * The upload input for a discovered op. Only input fields the op really has are\n * sent (all of them when the capability lists none); `ownerId` never is (the\n * fallback cannot know an owner, so an entity-scoped plane fails there with the\n * server's message).\n */\nfunction uploadInputOf(cap: UploadCapability, input: UploadOpInput): Record<string, unknown> {\n\tconst inputFields = new Set(cap.inputFieldNames ?? []);\n\tconst has = (name: string) => inputFields.size === 0 || inputFields.has(name);\n\tconst bucket = input.bucketKey !== undefined\n\t\t? (has('bucketKey') ? { bucketKey: input.bucketKey } : {})\n\t\t: (has('isPublic') ? { isPublic: input.isPublic ?? true } : {});\n\treturn {\n\t\t...bucket,\n\t\t...(input.databaseId !== undefined && inputFields.has('databaseId') ? { databaseId: input.databaseId } : {}),\n\t\tcontentHash: input.contentHash,\n\t\tcontentType: input.contentType,\n\t\tsize: input.size,\n\t\t...(has('filename') ? { filename: input.filename } : {}),\n\t};\n}\n\nfunction uploadMutation(cap: UploadCapability, payloadFields: readonly string[]): string {\n\treturn `\n\t\tmutation SheetsUpload($input: ${cap.inputTypeName}!) {\n\t\t\t${cap.uploadFieldName}(input: $input) {\n\t\t\t\t${payloadFields.join('\\n\\t\\t\\t\\t')}\n\t\t\t}\n\t\t}\n\t`.trim();\n}\n\n/** Payload fields of the earlier API, selected when the op's payload fields are not known. */\nconst LEGACY_PAYLOAD_FIELDS = ['uploadUrl', 'fileId', 'key', 'deduplicated', 'file'] as const;\n\n/** Invoke a discovered upload op and normalize its payload (strict: see `readUploadPayload`). */\nexport async function requestDiscoveredUpload(\n\texecute: SheetsExecuteFn,\n\tcap: UploadCapability,\n\tinput: UploadOpInput,\n\tsignal?: AbortSignal,\n): Promise<UploadPayload> {\n\tconst payloadFields = cap.payloadFieldNames?.length\n\t\t? UPLOAD_PAYLOAD_FIELDS.filter((name) => cap.payloadFieldNames!.includes(name))\n\t\t: LEGACY_PAYLOAD_FIELDS;\n\tconst data = await execute<Record<string, unknown>>(uploadMutation(cap, payloadFields), { input: uploadInputOf(cap, input) }, { signal });\n\treturn readUploadPayload(data?.[cap.uploadFieldName]);\n}\n\n/** The payload of the earlier API: the server's answer as it was sent. */\nexport interface LegacyUploadPayload {\n\tuploadUrl: string | null;\n\tfileId: string;\n\tkey: string;\n\tdeduplicated: boolean;\n\tfile: Omit<SheetsFileValue, 'filename'> & { filename?: string | null };\n}\n\n/**\n * Earlier API: send the discovered upload op and return its payload as the\n * server sent it. The file projection must carry an id, key, bucket, type and\n * size, and nothing is added to it. A new file without an `uploadUrl` is left\n * to the caller, which knows the `fileId` and can remove the row.\n */\nexport async function callUploadOp(\n\texecute: SheetsExecuteFn,\n\tcap: UploadCapability,\n\tinput: UploadOpInput,\n): Promise<LegacyUploadPayload> {\n\tconst data = await execute<Record<string, LegacyUploadPayload | null>>(uploadMutation(cap, LEGACY_PAYLOAD_FIELDS), {\n\t\tinput: uploadInputOf(cap, input),\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\tconst file = payload.file;\n\tif (\n\t\t!file || typeof file.id !== 'string' || typeof file.key !== 'string' ||\n\t\ttypeof file.bucket_id !== 'string' || typeof file.mime !== 'string' || typeof file.size !== 'number'\n\t) {\n\t\tthrow createError.badRequest('Upload failed: server returned an invalid file projection.');\n\t}\n\treturn payload;\n}\n\nfunction projectionToFileValue(file: FileProjection, fallbackName: string, fallbackMime: string): SheetsFileValue {\n\treturn {\n\t\t...file,\n\t\tbucket_id: typeof file.bucket_id === 'string' ? file.bucket_id : '',\n\t\tmime: typeof file.mime === 'string' ? file.mime : fallbackMime,\n\t\tsize: typeof file.size === 'number' ? file.size : 0,\n\t\tfilename: typeof file.filename === 'string' ? file.filename : fallbackName,\n\t};\n}\n\n/**\n * An uploader over the fallback discovery, for hosts that call\n * `createSheetsUpload` directly. The grid uses the model-driven path instead.\n */\nexport function createPresignedSheetsUpload(\n\t{ endpoint, execute }: SheetsStorageTransport,\n\tbucketKey?: string,\n): SheetsUploadFn {\n\treturn async (file, _path, options) => {\n\t\tif (!endpoint) throw createError.badRequest('No GraphQL endpoint configured.');\n\t\tconst cap = await discoverUploadCapability(endpoint, execute);\n\t\tif (!cap.hasFileProjection) {\n\t\t\tthrow createError.badRequest('Uploads require a storage mutation that returns a file projection.');\n\t\t}\n\t\tlet payload: UploadPayload;\n\t\ttry {\n\t\t\tpayload = await transferFile(\n\t\t\t\tfile,\n\t\t\t\t(input) => requestDiscoveredUpload(execute, cap, { ...input, bucketKey }),\n\t\t\t\t{ onProgress: options?.onProgress },\n\t\t\t);\n\t\t} catch (error) {\n\t\t\tthrow withUnfinishedUpload(error, { filesType: cap.download?.fileTypeName ?? null });\n\t\t}\n\t\tconst result: SheetsUploadResult = {\n\t\t\tfile: projectionToFileValue(payload.file, file.name, file.type || 'application/octet-stream'),\n\t\t};\n\t\tif (!cap.download) return result;\n\t\ttry {\n\t\t\treturn { ...result, url: await fetchDownloadUrl(execute, cap.download, payload.fileId) };\n\t\t} catch {\n\t\t\t// The upload succeeded. The download URL can be requested again later.\n\t\t\treturn result;\n\t\t}\n\t};\n}\n\n// ============================================================================\n// Fallback: downloadUrl resolution\n// ============================================================================\n\n/** Encode a PostGraphile global id with the default base64JSON codec. */\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/** Resolve one file's download URL through a discovered accessor. The URL can expire. */\nexport async function fetchDownloadUrl(execute: SheetsExecuteFn, cap: DownloadByIdResult, fileId: string): Promise<string> {\n\tconst missing = () => createError.badRequest('Upload succeeded but no downloadUrl was returned for the file.');\n\tif (cap.fileByIdArgName === 'nodeId') {\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 url = data?.[cap.fileByIdField]?.downloadUrl;\n\t\tif (!url) throw missing();\n\t\treturn url;\n\t}\n\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}${cap.connectionHasFirst ? ', 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 url = data?.[cap.fileByIdField]?.[nodesField]?.[0]?.downloadUrl;\n\t\tif (!url) throw missing();\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 url = data?.[cap.fileByIdField]?.downloadUrl;\n\tif (!url) throw missing();\n\treturn url;\n}\n\n/** Resolve URLs for one batch of visible files through the fallback discovery. Missing IDs have no entry. */\nexport async function fetchMediaDownloadUrls(\n\t{ endpoint, execute }: SheetsStorageTransport,\n\tgetActiveIds: () => readonly string[],\n): Promise<Map<string, string>> {\n\tconst { batch, download } = await discoverStorageCapabilities(endpoint, execute);\n\tconst ids = getActiveIds();\n\tconst urls = new Map<string, string>();\n\tif (ids.length === 0) return urls;\n\tif (batch) {\n\t\tconst first = batch.connectionHasFirst ? `, first: ${ids.length}` : '';\n\t\tconst query = `query SheetsMediaDownloadUrls($ids: [${batch.idScalarName ?? 'ID'}!]!) {\n\t\t\t${batch.fileByIdField}(${batch.connectionFilterArgName}: {\n\t\t\t\t${batch.connectionIdField}: { in: $ids }\n\t\t\t}${first}) { ${batch.connectionNodesField} { id downloadUrl } }\n\t\t}`;\n\t\ttype FileNode = { id: string; downloadUrl: string | null };\n\t\tconst data = await execute<Record<string, Record<string, (FileNode | null)[] | null> | null>>(query, { ids });\n\t\tfor (const row of data?.[batch.fileByIdField]?.[batch.connectionNodesField!] ?? []) {\n\t\t\tif (row?.downloadUrl) urls.set(row.id, row.downloadUrl);\n\t\t}\n\t} else if (download) {\n\t\tconst results = await Promise.allSettled(ids.map((id) => fetchDownloadUrl(execute, download, id)));\n\t\tresults.forEach((result, index) => {\n\t\t\tif (result.status === 'fulfilled') urls.set(ids[index]!, result.value);\n\t\t});\n\t}\n\treturn urls;\n}\n\n/**\n * Resolve a file's signed `downloadUrl` by id, for callers outside the grid\n * (a storage browser's copy link). Returns null on any failure.\n */\nexport async function resolveDownloadUrl(execute: SheetsExecuteFn, endpoint: string, fileId: string): Promise<string | null> {\n\ttry {\n\t\tconst { download } = await discoverStorageCapabilities(endpoint, execute);\n\t\treturn download ? await fetchDownloadUrl(execute, download, fileId) : null;\n\t} catch {\n\t\treturn null;\n\t}\n}\n","/**\n * The presigned upload protocol, shared by every upload path.\n *\n * 1. Hash the file (SHA-256, Web Crypto). The server needs the hash before it\n * issues the URL: it names the object and is signed into the PUT.\n * 2. Ask the upload mutation for a presigned PUT URL. A `deduplicated` answer\n * means the bytes are already stored: no PUT.\n * 3. PUT the bytes with the payload's `uploadHeaders`, unchanged (the URL is\n * signed over them: Content-Type, the checksum, the file row id). No\n * Authorization header; the signature is in the URL.\n * 4. An expired URL is requested again once.\n *\n * The server confirms the PUT later (a background job) and expires rows that\n * never received one, so a cancelled or failed PUT leaves nothing behind.\n *\n * The model-driven path (`uploads/`) names the upload mutation from the storage\n * service's `_meta`. The shape discovery in `sheets-upload-discovery.ts` is the\n * FALLBACK for a storage service whose `_meta` names no upload mutation.\n */\n\nimport { createError } from '@constructive-io/data';\n\n// ============================================================================\n// Upload payload\n// ============================================================================\n\n/**\n * The file projection the upload mutation returns: what an image or upload\n * column stores. The server may add keys (image `versions`); they are kept as returned.\n */\nexport interface FileProjection {\n\tid: string;\n\tkey: string;\n\tbucket_id?: string;\n\tmime?: string;\n\tsize?: number;\n\tfilename?: string;\n\t/** Durable public URL; set only for a public bucket. */\n\turl?: string;\n}\n\n/** The upload mutation's answer, normalized. */\nexport interface UploadPayload {\n\tuploadUrl: string | null;\n\t/** Headers the PUT must send unchanged, or null on a server that does not return them. */\n\tuploadHeaders: Record<string, string> | null;\n\tfileId: string;\n\tkey: string;\n\tdeduplicated: boolean;\n\t/** When the upload URL expires (ISO time), or null. */\n\texpiresAt: string | null;\n\tfile: FileProjection;\n}\n\n/** Payload fields the client selects when the payload type has them. */\nexport const UPLOAD_PAYLOAD_FIELDS = ['uploadUrl', 'uploadHeaders', 'fileId', 'key', 'deduplicated', 'expiresAt', 'file'] as const;\n\nfunction headersOf(value: unknown): Record<string, string> | null {\n\tlet parsed = value;\n\tif (typeof parsed === 'string') {\n\t\ttry {\n\t\t\tparsed = JSON.parse(parsed) as unknown;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\tif (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;\n\tconst entries = Object.entries(parsed as Record<string, unknown>);\n\tif (!entries.every(([, header]) => typeof header === 'string')) return null;\n\treturn Object.fromEntries(entries) as Record<string, string>;\n}\n\nfunction projectionOf(value: unknown): FileProjection | null {\n\tlet parsed = value;\n\tif (typeof parsed === 'string') {\n\t\ttry {\n\t\t\tparsed = JSON.parse(parsed) as unknown;\n\t\t} catch {\n\t\t\treturn null;\n\t\t}\n\t}\n\tif (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null;\n\tconst projection = parsed as Record<string, unknown>;\n\treturn isFileProjection(projection) ? projection : null;\n}\n\n/** A projection names its file by `id` and `key`; the server may add more keys, which are kept. */\nfunction isFileProjection(value: Record<string, unknown>): value is Record<string, unknown> & FileProjection {\n\treturn typeof value.id === 'string' && typeof value.key === 'string';\n}\n\n// ============================================================================\n// Unfinished uploads: the file row an upload left behind\n// ============================================================================\n\n/**\n * The file row the storage service created for an upload that did not finish\n * (a refused or blocked PUT, a cancel, an answer without an upload URL). Sheets\n * never deletes it: the storage service expires a row that never received its\n * bytes. A host with its own cleanup rule reads it from the error.\n */\nexport interface UnfinishedUpload {\n\t/** Id of the files table row. */\n\tfileId: string;\n\t/** GraphQL type name of the files table, or null when the upload path does not know it. */\n\tfilesType: string | null;\n\t/** `TableModel.key` of the files table, or null when the upload path does not know it. */\n\tfilesTableKey: string | null;\n}\n\nconst UNFINISHED_UPLOAD = 'unfinishedUpload';\n\n/** The file row an upload error left on the storage service, or null when the server issued none. */\nexport function unfinishedUploadOf(error: unknown): UnfinishedUpload | null {\n\tconst value = error && typeof error === 'object' ? (error as Record<string, unknown>)[UNFINISHED_UPLOAD] : null;\n\treturn value && typeof value === 'object' ? (value as UnfinishedUpload) : null;\n}\n\n/**\n * Record on `error` the file row its upload left. An id already recorded is kept\n * (it is the newest one); a files table is filled in when the error has none. An\n * error without a file id is returned unchanged.\n */\nexport function withUnfinishedUpload(error: unknown, upload: Partial<UnfinishedUpload>): unknown {\n\tif (!error || typeof error !== 'object') return error;\n\tconst recorded = unfinishedUploadOf(error);\n\tconst fileId = recorded?.fileId ?? upload.fileId;\n\tif (!fileId) return error;\n\tconst value: UnfinishedUpload = {\n\t\tfileId,\n\t\tfilesType: recorded?.filesType ?? upload.filesType ?? null,\n\t\tfilesTableKey: recorded?.filesTableKey ?? upload.filesTableKey ?? null,\n\t};\n\tObject.defineProperty(error, UNFINISHED_UPLOAD, { value, enumerable: false, configurable: true, writable: true });\n\treturn error;\n}\n\n/** Normalize a raw upload payload. Throws when it cannot be used. */\nexport function readUploadPayload(raw: unknown): UploadPayload {\n\tif (!raw || typeof raw !== 'object') {\n\t\tthrow createError.badRequest('Upload failed: the storage service returned no answer.');\n\t}\n\tconst payload = raw as Record<string, unknown>;\n\tconst file = projectionOf(payload.file);\n\tif (!file) {\n\t\tthrow createError.badRequest('Upload failed: the server returned an invalid file projection.');\n\t}\n\tconst deduplicated = payload.deduplicated === true;\n\tconst uploadUrl = typeof payload.uploadUrl === 'string' && payload.uploadUrl ? payload.uploadUrl : null;\n\tif (!deduplicated && !uploadUrl) {\n\t\t// The server created the row; it is left to expire, and the error names it.\n\t\tthrow withUnfinishedUpload(createError.badRequest('Upload failed: the server returned no uploadUrl for a new file.'), {\n\t\t\tfileId: typeof payload.fileId === 'string' ? payload.fileId : file.id,\n\t\t});\n\t}\n\treturn {\n\t\tuploadUrl,\n\t\tuploadHeaders: headersOf(payload.uploadHeaders),\n\t\tfileId: typeof payload.fileId === 'string' ? payload.fileId : file.id,\n\t\tkey: typeof payload.key === 'string' ? payload.key : file.key,\n\t\tdeduplicated,\n\t\texpiresAt: typeof payload.expiresAt === 'string' ? payload.expiresAt : null,\n\t\tfile,\n\t};\n}\n\n// ============================================================================\n// SHA-256 (Web Crypto)\n// ============================================================================\n\n/**\n * Largest file the browser hashes. Web Crypto has no streaming digest, so the\n * whole file is read into memory once to hash it (the digest may copy it once\n * more). The PUT then sends the `File` itself, which the browser streams from\n * disk, so no second copy is kept for the upload. A streaming digest would need\n * a JavaScript SHA-256 implementation; until one is worth a dependency, files\n * above this size are refused with a clear message.\n */\nexport const MAX_HASHED_FILE_BYTES = 512 * 1024 * 1024;\n\nfunction hex(digest: ArrayBuffer): string {\n\tconst bytes = new Uint8Array(digest);\n\tlet out = '';\n\tfor (let i = 0; i < bytes.length; i++) out += bytes[i]!.toString(16).padStart(2, '0');\n\treturn out;\n}\n\nfunction requireSubtle(): SubtleCrypto {\n\tif (!globalThis.crypto?.subtle) {\n\t\tthrow createError.badRequest('This browser cannot hash files (Web Crypto is unavailable), so it cannot upload them.');\n\t}\n\treturn globalThis.crypto.subtle;\n}\n\n/** Lowercase hex SHA-256 of an already-read buffer (64 chars, as the server expects). */\nexport async function sha256HexFromBuffer(buffer: ArrayBuffer): Promise<string> {\n\treturn hex(await requireSubtle().digest('SHA-256', buffer));\n}\n\n/** The bytes of a blob. `Blob.arrayBuffer` where the browser has it, else a FileReader. */\nfunction readBytes(file: Blob): Promise<ArrayBuffer> {\n\tif (typeof file.arrayBuffer === 'function') return file.arrayBuffer();\n\treturn new Promise((resolve, reject) => {\n\t\tconst reader = new FileReader();\n\t\treader.onload = () => resolve(reader.result as ArrayBuffer);\n\t\treader.onerror = () => reject(reader.error ?? new Error('The file could not be read.'));\n\t\treader.readAsArrayBuffer(file);\n\t});\n}\n\n/** Lowercase hex SHA-256 of a file. Refuses files above {@link MAX_HASHED_FILE_BYTES}. */\nexport async function sha256HexOfFile(file: Blob): Promise<string> {\n\tif (file.size > MAX_HASHED_FILE_BYTES) {\n\t\tthrow createError.badRequest(\n\t\t\t`This file is too large to upload from the browser (the limit is ${MAX_HASHED_FILE_BYTES / (1024 * 1024)} MB).`,\n\t\t);\n\t}\n\tconst subtle = requireSubtle();\n\treturn hex(await subtle.digest('SHA-256', await readBytes(file)));\n}\n\n// ============================================================================\n// Presigned PUT\n// ============================================================================\n\n/** Header a checksum-bound presigned PUT carries (base64 of the raw digest). */\nexport const CHECKSUM_SHA256_HEADER = 'x-amz-checksum-sha256';\n/** Header a row-bound presigned PUT carries (the file row id). */\nexport const UPLOAD_ID_HEADER = 'x-amz-meta-upload-id';\n\n/** Hex SHA-256 to base64 of the raw digest, the encoding `x-amz-checksum-sha256` carries. */\nexport function sha256HexToBase64(contentHash: string): string {\n\tconst pairs = contentHash.match(/.{2}/g) ?? [];\n\tlet binary = '';\n\tfor (const pair of pairs) binary += String.fromCharCode(parseInt(pair, 16));\n\treturn btoa(binary);\n}\n\n/**\n * Headers for a server that signs the checksum and the row id but does not\n * return `uploadHeaders` yet. A current server returns them, and they are sent\n * as returned.\n */\nexport function fallbackPutHeaders(contentType: string, contentHash?: string, uploadId?: string): Record<string, string> {\n\treturn {\n\t\t'Content-Type': contentType,\n\t\t...(contentHash ? { [CHECKSUM_SHA256_HEADER]: sha256HexToBase64(contentHash) } : {}),\n\t\t...(uploadId ? { [UPLOAD_ID_HEADER]: uploadId } : {}),\n\t};\n}\n\n/**\n * A PUT the browser could not complete. The API answered moments ago, so the\n * usual cause is the bucket's CORS rule (no allowed origin for this site);\n * browsers do not say which. The words are for the person uploading; the code\n * `STORAGE_UPLOAD_BLOCKED` is for hosts and logs.\n */\nexport const STORAGE_UPLOAD_BLOCKED_MESSAGE =\n\t\"Upload failed: file storage didn't accept uploads from this site, or the connection dropped. If it keeps failing, ask an admin to allow this site in the storage settings.\";\n\nconst PUT_RESPONSE = 'putResponse';\n\n/** The storage server answered the PUT with an error status. The response is kept on the error. */\nfunction putRejected(status: number, statusText: string, body: string) {\n\tconst error = createError.badRequest(`Upload failed: ${status} ${statusText}${body ? ` — ${body}` : ''}`);\n\tObject.defineProperty(error, PUT_RESPONSE, { value: { status, body }, enumerable: false });\n\treturn error;\n}\n\n/** The status and body of a rejected PUT, or null for any other error. */\nexport function putResponseOf(error: unknown): { status: number; body: string } | null {\n\tconst response = error && typeof error === 'object' ? (error as Record<string, unknown>)[PUT_RESPONSE] : null;\n\treturn response && typeof response === 'object' ? (response as { status: number; body: string }) : null;\n}\n\nexport interface UploadProgressEvent {\n\tloaded: number;\n\ttotal: number;\n\tpercentage: number;\n}\n\nexport interface PutFileOptions {\n\theaders: Record<string, string>;\n\tonProgress?: (progress: UploadProgressEvent) => void;\n\tsignal?: AbortSignal;\n}\n\nfunction abortError(): Error {\n\treturn typeof DOMException === 'function'\n\t\t? new DOMException('The upload was cancelled.', 'AbortError')\n\t\t: Object.assign(new Error('The upload was cancelled.'), { name: 'AbortError' });\n}\n\n/** True for the error a cancelled upload rejects with. */\nexport function isAbortError(error: unknown): boolean {\n\treturn Boolean(error && typeof error === 'object' && (error as { name?: unknown }).name === 'AbortError');\n}\n\nfunction blockedError() {\n\treturn createError.graphql(STORAGE_UPLOAD_BLOCKED_MESSAGE, 'STORAGE_UPLOAD_BLOCKED');\n}\n\nfunction putWithXhr(url: string, body: Blob | ArrayBuffer, options: PutFileOptions, total: number): Promise<void> {\n\treturn new Promise((resolve, reject) => {\n\t\tconst xhr = new XMLHttpRequest();\n\t\tconst onAbort = () => xhr.abort();\n\t\tconst done = () => options.signal?.removeEventListener('abort', onAbort);\n\t\txhr.open('PUT', url);\n\t\tfor (const [name, value] of Object.entries(options.headers)) xhr.setRequestHeader(name, value);\n\t\txhr.upload.addEventListener('progress', (event) => {\n\t\t\tif (!event.lengthComputable || event.total === 0) return;\n\t\t\toptions.onProgress?.({ loaded: event.loaded, total: event.total, percentage: Math.round((event.loaded / event.total) * 100) });\n\t\t});\n\t\txhr.addEventListener('load', () => {\n\t\t\tdone();\n\t\t\tif (xhr.status >= 200 && xhr.status < 300) {\n\t\t\t\toptions.onProgress?.({ loaded: total, total, percentage: 100 });\n\t\t\t\tresolve();\n\t\t\t} else {\n\t\t\t\treject(putRejected(xhr.status, xhr.statusText, xhr.responseText ?? ''));\n\t\t\t}\n\t\t});\n\t\txhr.addEventListener('error', () => {\n\t\t\tdone();\n\t\t\treject(blockedError());\n\t\t});\n\t\txhr.addEventListener('abort', () => {\n\t\t\tdone();\n\t\t\treject(abortError());\n\t\t});\n\t\toptions.signal?.addEventListener('abort', onAbort, { once: true });\n\t\txhr.send(body);\n\t});\n}\n\n/** PUT bytes to a presigned URL with exactly the given headers. Uses XHR when progress is wanted and XHR exists. */\nexport async function putFile(url: string, body: Blob | ArrayBuffer, options: PutFileOptions): Promise<void> {\n\tif (options.signal?.aborted) throw abortError();\n\tconst total = body instanceof ArrayBuffer ? body.byteLength : body.size;\n\tif (options.onProgress && typeof XMLHttpRequest !== 'undefined') {\n\t\tawait putWithXhr(url, body, options, total);\n\t\treturn;\n\t}\n\tlet response: Response;\n\ttry {\n\t\tresponse = await fetch(url, {\n\t\t\tmethod: 'PUT',\n\t\t\theaders: options.headers,\n\t\t\tbody,\n\t\t\t...(options.signal ? { signal: options.signal } : {}),\n\t\t});\n\t} catch (error) {\n\t\tif (isAbortError(error)) throw abortError();\n\t\tthrow blockedError();\n\t}\n\tif (!response.ok) {\n\t\tthrow putRejected(response.status, response.statusText, await response.text().catch(() => ''));\n\t}\n\toptions.onProgress?.({ loaded: total, total, percentage: 100 });\n}\n\n/**\n * PUT an already-read buffer. Kept for callers of the earlier API; new code\n * uses {@link putFile} with the payload's `uploadHeaders`.\n */\nexport async function presignedPut(\n\turl: string,\n\tbuffer: ArrayBuffer,\n\tcontentType: string,\n\tonProgress?: (progress: UploadProgressEvent) => void,\n\tcontentHash?: string,\n\tuploadId?: string,\n): Promise<void> {\n\tawait putFile(url, buffer, { headers: fallbackPutHeaders(contentType, contentHash, uploadId), onProgress });\n}\n\n// ============================================================================\n// Transfer: hash, request, PUT, one renewal of an expired URL\n// ============================================================================\n\nexport interface UploadRequestInput {\n\tcontentHash: string;\n\tcontentType: string;\n\tsize: number;\n\tfilename: string;\n}\n\n/** Sends the upload mutation for one file. The signal aborts the request when the user cancels. */\nexport type UploadRequester = (input: UploadRequestInput, signal?: AbortSignal) => Promise<UploadPayload>;\n\nfunction isExpired(payload: UploadPayload, now = Date.now()): boolean {\n\tif (!payload.expiresAt) return false;\n\tconst expiry = Date.parse(payload.expiresAt);\n\treturn Number.isFinite(expiry) && expiry <= now;\n}\n\n/** S3 answers an expired presigned URL with 403 (\"Request has expired\"). */\nfunction looksExpired(error: unknown, payload: UploadPayload): boolean {\n\tconst response = putResponseOf(error);\n\tif (response?.status !== 403) return false;\n\treturn isExpired(payload) || /expired/i.test(response.body);\n}\n\nexport interface TransferOptions {\n\tonProgress?: (progress: UploadProgressEvent) => void;\n\tsignal?: AbortSignal;\n}\n\n/**\n * Upload one file through a requester: hash, request, PUT with the returned\n * headers. A URL that expired before or during the PUT is requested again once.\n * Any error after the server issued a file id carries it (`unfinishedUploadOf`);\n * the row itself is left for the storage service to expire.\n */\nexport async function transferFile(file: File, request: UploadRequester, options: TransferOptions = {}): Promise<UploadPayload> {\n\tconst contentType = file.type || 'application/octet-stream';\n\tconst contentHash = await sha256HexOfFile(file);\n\tif (options.signal?.aborted) throw abortError();\n\tconst input: UploadRequestInput = { contentHash, contentType, size: file.size, filename: file.name };\n\n\tlet payload = await request(input, options.signal);\n\t// From here on the server has issued a file id: the newest `payload` names it.\n\tconst putOrRenew = async (): Promise<UploadPayload> => {\n\t\tfor (let renewals = 0; ; renewals += 1) {\n\t\t\tif (payload.deduplicated) {\n\t\t\t\toptions.onProgress?.({ loaded: file.size, total: file.size, percentage: 100 });\n\t\t\t\treturn payload;\n\t\t\t}\n\t\t\tif (options.signal?.aborted) throw abortError();\n\t\t\tif (isExpired(payload) && renewals === 0) {\n\t\t\t\tpayload = await request(input, options.signal);\n\t\t\t\tcontinue;\n\t\t\t}\n\t\t\ttry {\n\t\t\t\tawait putFile(payload.uploadUrl!, file, {\n\t\t\t\t\theaders: payload.uploadHeaders ?? fallbackPutHeaders(contentType, contentHash, payload.fileId),\n\t\t\t\t\tonProgress: options.onProgress,\n\t\t\t\t\tsignal: options.signal,\n\t\t\t\t});\n\t\t\t\treturn payload;\n\t\t\t} catch (error) {\n\t\t\t\tif (renewals > 0 || !looksExpired(error, payload)) throw error;\n\t\t\t\tpayload = await request(input, options.signal);\n\t\t\t}\n\t\t}\n\t};\n\ttry {\n\t\treturn await putOrRenew();\n\t} catch (error) {\n\t\tthrow withUnfinishedUpload(error, { fileId: payload.fileId });\n\t}\n}\n\n// ============================================================================\n// The fallback discovery, re-exported for callers of the earlier API\n// ============================================================================\n\nexport {\n\t__resetUploadCapabilityCache,\n\tcallUploadOp,\n\tcreatePresignedSheetsUpload,\n\tdiscoverSoleUploadCapability,\n\tdiscoverUploadCapability,\n\tfetchDownloadUrl,\n\tfetchMediaDownloadUrls,\n\trequestDiscoveredUpload,\n\tresolveDownloadUrl,\n\tresolveUploadCapability,\n} from './sheets-upload-discovery';\nexport type { IntrospectionSchema, LegacyUploadPayload, UploadCapability } from './sheets-upload-discovery';\n","import type { DocumentNode } from 'graphql';\nimport { print } from 'graphql';\n\nimport { ConstructiveError, createError, isAuthenticationCode, parseGraphQLError, TypedDocumentString } from '@constructive-io/data';\n\nimport type { SheetsConfig, SheetsStorageTransport } from './sheets-context';\nimport { createPresignedSheetsUpload } from './sheets-upload-presigned';\n\n// The presigned uploader lives with the upload protocol; it stays importable from here.\nexport { createPresignedSheetsUpload };\n\n// ============================================================================\n// Types\n// ============================================================================\n\ntype ExecutableDocument = TypedDocumentString<any, any> | DocumentNode | string | unknown;\n\n/** Per-request options. An executor that does not support one ignores it. */\nexport interface SheetsExecuteOptions {\n\t/** Aborts the request, for example when the filter or sort it was for has changed. */\n\tsignal?: AbortSignal;\n}\n\nexport type SheetsExecuteFn = <T = unknown>(\n\tdocument: ExecutableDocument,\n\tvariables?: Record<string, unknown>,\n\toptions?: SheetsExecuteOptions,\n) => Promise<T>;\n\n/** Durable file metadata for image and upload columns. */\nexport interface SheetsFileValue {\n\tid: string;\n\tkey: string;\n\tbucket_id: string;\n\tmime: string;\n\tsize: number;\n\tfilename: string;\n\t/** Public URL supplied by storage, when available. */\n\turl?: string;\n}\n\nexport interface SheetsUploadResult {\n\tfile: SheetsFileValue;\n\t/** Optional download URL for immediate use. It can expire. */\n\turl?: string;\n}\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\n/** One error of a GraphQL response. */\nexport interface SheetsResponseError {\n\tmessage: string;\n\tpath?: ReadonlyArray<string | number>;\n\textensions?: { code?: string; context?: Record<string, unknown> };\n}\n\ninterface GraphQLResponse {\n\tdata?: unknown;\n\terrors?: SheetsResponseError[];\n}\n\n/** The data a response carried beside its errors. */\nexport interface SheetsPartialResult {\n\tdata: unknown;\n\terrors: readonly SheetsResponseError[];\n}\n\nconst PARTIAL_RESULT = 'partialResult';\nconst RESPONSE_ERRORS = 'responseErrors';\n\n/**\n * Keep a response's errors, and its data when it has some, on the error thrown\n * for it. Every error of the response stays readable (`responseErrorsOf`), and\n * a read whose rows came back with field errors (a float NaN cell) can keep\n * the rows (`partialResultOf`). Callers that only look at the thrown error see\n * it as before.\n */\nexport function withResponseErrors<E extends Error>(error: E, data: unknown, errors: readonly SheetsResponseError[]): E {\n\tObject.defineProperty(error, RESPONSE_ERRORS, { value: errors, enumerable: false, configurable: true });\n\tif (data != null) {\n\t\tObject.defineProperty(error, PARTIAL_RESULT, {\n\t\t\tvalue: { data, errors } satisfies SheetsPartialResult,\n\t\t\tenumerable: false,\n\t\t\tconfigurable: true,\n\t\t});\n\t}\n\treturn error;\n}\n\n/** Every error of the response an error was thrown for, or null when it did not come from a GraphQL response. */\nexport function responseErrorsOf(error: unknown): readonly SheetsResponseError[] | null {\n\tconst errors = error && typeof error === 'object' ? (error as Record<string, unknown>)[RESPONSE_ERRORS] : null;\n\treturn Array.isArray(errors) ? (errors as SheetsResponseError[]) : null;\n}\n\n/** The data an error's response carried, or null. */\nexport function partialResultOf(error: unknown): SheetsPartialResult | null {\n\tconst partial = error && typeof error === 'object' ? (error as Record<string, unknown>)[PARTIAL_RESULT] : null;\n\treturn partial && typeof partial === 'object' ? (partial as SheetsPartialResult) : null;\n}\n\nfunction parseGraphQLResponse(response: GraphQLResponse, onAuthError?: () => void): ConstructiveError | null {\n\tif (!response.errors?.length) return null;\n\n\t// Only an explicit code (the shared list in @constructive-io/data) means the session is\n\t// gone. A permission error that mentions \"unauthorized\" in its text must not log the user out.\n\tif (response.errors.some((candidate) => isAuthenticationCode(candidate.extensions?.code))) {\n\t\tonAuthError?.();\n\t\treturn createError.unauthorized('Authentication required. Please log in again.');\n\t}\n\n\tconst error = response.errors[0];\n\tconst code = error.extensions?.code;\n\tconst message = error.message || 'GraphQL query failed';\n\n\t// A suspended database keeps its `context.reason` (billing or admin) for the paused screen.\n\tif (code === 'ACCESS_SUSPENDED') return parseGraphQLError(error);\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\toptions?: SheetsExecuteOptions,\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\t...(options?.signal ? { signal: options.signal } : {}),\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\tconst body = (await response.json().catch((): null => null)) as GraphQLResponse | null;\n\t\t\t\tconst refusal = body?.errors?.[0];\n\t\t\t\tconst forbidden = refusal?.extensions?.code === 'ACCESS_SUSPENDED'\n\t\t\t\t\t? parseGraphQLError(refusal)\n\t\t\t\t\t: createError.forbidden('You do not have permission to perform this action.');\n\t\t\t\tthrow body?.errors?.length ? withResponseErrors(forbidden, null, body.errors) : forbidden;\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()) as GraphQLResponse;\n\t\t\t\tif (body.errors?.length) {\n\t\t\t\t\tthrow withResponseErrors(\n\t\t\t\t\t\tcreateError.graphql(body.errors[0]!.message || `Request failed: ${status}`, body.errors[0]!.extensions?.code),\n\t\t\t\t\t\tnull,\n\t\t\t\t\t\tbody.errors,\n\t\t\t\t\t);\n\t\t\t\t}\n\t\t\t} catch (e) {\n\t\t\t\tif (e instanceof ConstructiveError) 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\t// A lost session or a suspended database never hands back partial rows.\n\t\t\tconst keepsData = !['UNAUTHENTICATED', 'ACCESS_SUSPENDED'].includes(graphqlError.code);\n\t\t\tthrow withResponseErrors(graphqlError, keepsData ? result.data : null, result.errors ?? []);\n\t\t}\n\n\t\treturn result.data as T;\n\t};\n}\n\nexport function resolveStorageTransport(\n\tconfig: SheetsConfig,\n\tgetToken: () => string | null,\n): SheetsStorageTransport | undefined {\n\tconst endpoint = config.storage?.endpoint;\n\tif (!endpoint) return undefined;\n\n\treturn {\n\t\tendpoint,\n\t\texecute: config.storage?.execute ?? createSheetsExecute({ ...config, endpoint }, getToken),\n\t};\n}\n\n/** Creates an uploader for storage. Direct callers may use the supplied endpoint as storage. */\nexport function createSheetsUpload(config: SheetsConfig, getToken: () => string | null): SheetsUploadFn {\n\tconst transport = resolveStorageTransport(config, getToken) ?? {\n\t\tendpoint: config.endpoint,\n\t\texecute: config.execute ?? createSheetsExecute(config, getToken),\n\t};\n\treturn createPresignedSheetsUpload(transport, config.upload?.bucketKey);\n}\n\nexport { ConstructiveError } from '@constructive-io/data';\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 function reuseSheetsPlaceholderData<T>(\n\tpreviousData: T | undefined,\n\tpreviousQueryKey: readonly unknown[] | undefined,\n\tcurrentScope: SheetsScopeKey,\n): T | undefined {\n\tconst previousScope = previousQueryKey?.[1];\n\tif (!isSheetsScopeKey(previousScope)) return undefined;\n\tif (previousScope.databaseId !== currentScope.databaseId) return undefined;\n\tif (previousScope.endpoint !== currentScope.endpoint) return undefined;\n\tif (previousScope.identityKey !== currentScope.identityKey) return undefined;\n\treturn previousData;\n}\n\n/**\n * Cache-key segments for a table reference. A `TableModel.key`\n * (`schema.Name`) becomes `[Name, schema]`, a bare name `[Name]`. Tables in\n * different schemas get different entries, and a key built from a bare name is\n * a prefix of every schema's entry, so invalidating by name still reaches them.\n */\nexport function tableKeySegments(tableRef: string): readonly string[] {\n\tconst dot = tableRef.lastIndexOf('.');\n\treturn dot === -1 ? [tableRef] : [tableRef.slice(dot + 1), tableRef.slice(0, dot)];\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\t/** One table model, per `_meta` version and display override. */\n\ttableModel: (scope: SheetsScopeKey, tableKey: string, metaVersion: number, displayKey: string | null) =>\n\t\t[...sheetsQueryKeys.scope(scope), 'table-model', ...tableKeySegments(tableKey), metaVersion, displayKey] as const,\n\tmediaUrl: (scope: SheetsScopeKey, endpoint: string | undefined, id: string | null) =>\n\t\t[...sheetsQueryKeys.scope(scope), 'media-url', endpoint, id] as const,\n\trelations: (scope: SheetsScopeKey, tableName: string) =>\n\t\t[...sheetsQueryKeys.scope(scope), 'relations', ...tableKeySegments(tableName)] as const,\n\ttable: (scope: SheetsScopeKey, tableRef: string) =>\n\t\t[...sheetsQueryKeys.scope(scope), 'table', ...tableKeySegments(tableRef)] as const,\n\ttableRows: (scope: SheetsScopeKey, tableRef: string, options?: unknown) =>\n\t\t[...sheetsQueryKeys.table(scope, tableRef), 'rows', options] as const,\n\ttableRow: (scope: SheetsScopeKey, tableRef: string, id: unknown) =>\n\t\t[...sheetsQueryKeys.table(scope, tableRef), 'row', id] as const,\n\ttableCount: (scope: SheetsScopeKey, tableRef: string, where?: Readonly<Record<string, unknown>> | null) =>\n\t\t[...sheetsQueryKeys.table(scope, tableRef), 'count', where] as const,\n\tinfiniteTable: (scope: SheetsScopeKey, tableRef: string) =>\n\t\t[...sheetsQueryKeys.scope(scope), 'infinite-table', ...tableKeySegments(tableRef)] as const,\n\tinfiniteTablePage: (scope: SheetsScopeKey, tableRef: string, pageIndex: number, options: unknown) =>\n\t\t[...sheetsQueryKeys.infiniteTable(scope, tableRef), 'page', pageIndex, options] as const,\n\tinfiniteTableTotalCount: (scope: SheetsScopeKey, tableRef: string, where?: Readonly<Record<string, unknown>>) =>\n\t\t[...sheetsQueryKeys.infiniteTable(scope, tableRef), 'totalCount', where] as const,\n\tcursorTable: (scope: SheetsScopeKey, tableRef: string, options?: unknown) =>\n\t\t[...sheetsQueryKeys.scope(scope), 'cursor-table', ...tableKeySegments(tableRef), options] as const,\n} as const;\n\n/**\n * Mutation keys. Every mutation a Sheets hook creates sits under its table's\n * query key, `[...table(scope, tableRef), 'mutation', operation, ...detail]`, so\n * `useIsMutating({ mutationKey: sheetsMutationKeys.table(scope, ref) })` counts\n * every write in flight on that table.\n */\nexport const sheetsMutationKeys = {\n\t/** Every mutation of a table, or one operation of it when `operation` is given. */\n\ttable: (scope: SheetsScopeKey, tableRef: string, operation?: string, ...detail: readonly unknown[]) =>\n\t\toperation === undefined\n\t\t\t? ([...sheetsQueryKeys.table(scope, tableRef), 'mutation'] as const)\n\t\t\t: ([...sheetsQueryKeys.table(scope, tableRef), 'mutation', operation, ...detail] as const),\n} as const;\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"],"mappings":";;;AAWA,SAAS,6BAA6B;AAEtC,SAAS,eAAAA,oBAAmB;;;ACO5B,SAAS,mBAAmB;AAmCrB,IAAM,wBAAwB,CAAC,aAAa,iBAAiB,UAAU,OAAO,gBAAgB,aAAa,MAAM;AAExH,SAAS,UAAU,OAA+C;AACjE,MAAI,SAAS;AACb,MAAI,OAAO,WAAW,UAAU;AAC/B,QAAI;AACH,eAAS,KAAK,MAAM,MAAM;AAAA,IAC3B,QAAQ;AACP,aAAO;AAAA,IACR;AAAA,EACD;AACA,MAAI,CAAC,UAAU,OAAO,WAAW,YAAY,MAAM,QAAQ,MAAM,EAAG,QAAO;AAC3E,QAAM,UAAU,OAAO,QAAQ,MAAiC;AAChE,MAAI,CAAC,QAAQ,MAAM,CAAC,CAAC,EAAE,MAAM,MAAM,OAAO,WAAW,QAAQ,EAAG,QAAO;AACvE,SAAO,OAAO,YAAY,OAAO;AAClC;AAEA,SAAS,aAAa,OAAuC;AAC5D,MAAI,SAAS;AACb,MAAI,OAAO,WAAW,UAAU;AAC/B,QAAI;AACH,eAAS,KAAK,MAAM,MAAM;AAAA,IAC3B,QAAQ;AACP,aAAO;AAAA,IACR;AAAA,EACD;AACA,MAAI,CAAC,UAAU,OAAO,WAAW,YAAY,MAAM,QAAQ,MAAM,EAAG,QAAO;AAC3E,QAAM,aAAa;AACnB,SAAO,iBAAiB,UAAU,IAAI,aAAa;AACpD;AAGA,SAAS,iBAAiB,OAAmF;AAC5G,SAAO,OAAO,MAAM,OAAO,YAAY,OAAO,MAAM,QAAQ;AAC7D;AAqBA,IAAM,oBAAoB;AAGnB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createError"]}
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import {
|
|
3
|
+
createPresignedSheetsUpload,
|
|
4
|
+
createSheetsExecute,
|
|
5
|
+
resolveStorageTransport,
|
|
6
|
+
setSheetsLogger,
|
|
7
|
+
sheetsQueryKeys
|
|
8
|
+
} from "./chunk-MBSHDF55.js";
|
|
9
|
+
import {
|
|
10
|
+
SheetsStoreContext,
|
|
11
|
+
createSheetsStore,
|
|
12
|
+
getStoredToken
|
|
13
|
+
} from "./chunk-ZOQDSOMO.js";
|
|
14
|
+
import {
|
|
15
|
+
SheetsContext
|
|
16
|
+
} from "./chunk-II3MSNRO.js";
|
|
17
|
+
import {
|
|
18
|
+
setSheetsLocale
|
|
19
|
+
} from "./chunk-GGECS2BP.js";
|
|
20
|
+
|
|
21
|
+
// src/context/sheets-provider.tsx
|
|
22
|
+
import { useEffect, useId, useMemo, useRef } from "react";
|
|
23
|
+
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
|
24
|
+
import { useStore as useZustandStore } from "zustand";
|
|
25
|
+
import { jsx } from "react/jsx-runtime";
|
|
26
|
+
var unavailableUpload = async () => {
|
|
27
|
+
throw new Error("Uploads need a storage endpoint");
|
|
28
|
+
};
|
|
29
|
+
function SheetsProvider({ config, children }) {
|
|
30
|
+
const providerInstanceId = useId();
|
|
31
|
+
const storeRef = useRef(null);
|
|
32
|
+
if (!storeRef.current) {
|
|
33
|
+
storeRef.current = createSheetsStore();
|
|
34
|
+
}
|
|
35
|
+
const store = storeRef.current;
|
|
36
|
+
const standaloneIdentityKey = useZustandStore(store, (state) => state.identityKey);
|
|
37
|
+
const standaloneAccessToken = useZustandStore(store, (state) => state.accessToken);
|
|
38
|
+
setSheetsLogger(config.logger);
|
|
39
|
+
setSheetsLocale(config.locale);
|
|
40
|
+
useEffect(() => {
|
|
41
|
+
setSheetsLogger(config.logger);
|
|
42
|
+
setSheetsLocale(config.locale);
|
|
43
|
+
}, [config.logger, config.locale]);
|
|
44
|
+
useEffect(() => {
|
|
45
|
+
const store2 = storeRef.current?.getState();
|
|
46
|
+
if (!store2) return;
|
|
47
|
+
if (config.auth.mode !== "standalone") {
|
|
48
|
+
store2.setUnauthenticated();
|
|
49
|
+
return;
|
|
50
|
+
}
|
|
51
|
+
const databaseId = config.databaseId || "default";
|
|
52
|
+
const stored = getStoredToken(databaseId);
|
|
53
|
+
if (!stored) {
|
|
54
|
+
store2.setUnauthenticated();
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
const expiresAt = new Date(stored.expiresAt);
|
|
58
|
+
if (expiresAt > /* @__PURE__ */ new Date()) {
|
|
59
|
+
store2.setAuthenticated(stored.accessToken, stored.expiresAt, stored.identityKey ?? null);
|
|
60
|
+
return;
|
|
61
|
+
}
|
|
62
|
+
store2.setUnauthenticated();
|
|
63
|
+
}, [config.auth.mode, config.databaseId]);
|
|
64
|
+
const internalQueryClient = useMemo(
|
|
65
|
+
() => new QueryClient({
|
|
66
|
+
defaultOptions: {
|
|
67
|
+
queries: {
|
|
68
|
+
staleTime: 5 * 60 * 1e3,
|
|
69
|
+
gcTime: 30 * 60 * 1e3,
|
|
70
|
+
retry: 1
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
}),
|
|
74
|
+
[]
|
|
75
|
+
);
|
|
76
|
+
const queryClient = config.queryClient ?? internalQueryClient;
|
|
77
|
+
const getToken = useMemo(() => {
|
|
78
|
+
if (config.auth.mode === "embedded") {
|
|
79
|
+
return config.auth.getToken;
|
|
80
|
+
}
|
|
81
|
+
return () => store.getState().accessToken ?? null;
|
|
82
|
+
}, [config.auth, store]);
|
|
83
|
+
const execute = useMemo(() => {
|
|
84
|
+
if (config.execute) return config.execute;
|
|
85
|
+
return createSheetsExecute(config, getToken);
|
|
86
|
+
}, [config, getToken]);
|
|
87
|
+
const storage = useMemo(() => resolveStorageTransport(config, getToken), [config, getToken]);
|
|
88
|
+
const bucketKey = config.upload?.bucketKey;
|
|
89
|
+
const executeUpload = useMemo(() => {
|
|
90
|
+
if (config.executeUpload) return config.executeUpload;
|
|
91
|
+
return storage ? createPresignedSheetsUpload(storage, bucketKey) : unavailableUpload;
|
|
92
|
+
}, [config.executeUpload, storage, bucketKey]);
|
|
93
|
+
const canUpload = Boolean(config.executeUpload || storage);
|
|
94
|
+
const configuredIdentityKey = config.auth.mode === "embedded" ? config.auth.getIdentityKey?.() ?? null : standaloneIdentityKey;
|
|
95
|
+
const activeToken = config.auth.mode === "embedded" ? config.auth.getToken() : standaloneAccessToken;
|
|
96
|
+
const authGenerationRef = useRef({ mode: config.auth.mode, token: activeToken, generation: 0 });
|
|
97
|
+
if (authGenerationRef.current.mode !== config.auth.mode || authGenerationRef.current.token !== activeToken) {
|
|
98
|
+
authGenerationRef.current = {
|
|
99
|
+
mode: config.auth.mode,
|
|
100
|
+
token: activeToken,
|
|
101
|
+
generation: authGenerationRef.current.generation + 1
|
|
102
|
+
};
|
|
103
|
+
}
|
|
104
|
+
const identityKey = configuredIdentityKey ?? `anonymous:${providerInstanceId}:${authGenerationRef.current.generation}`;
|
|
105
|
+
const scopeKey = useMemo(
|
|
106
|
+
() => ({
|
|
107
|
+
databaseId: config.databaseId ?? null,
|
|
108
|
+
endpoint: config.endpoint,
|
|
109
|
+
identityKey
|
|
110
|
+
}),
|
|
111
|
+
[config.databaseId, config.endpoint, identityKey]
|
|
112
|
+
);
|
|
113
|
+
useEffect(() => {
|
|
114
|
+
return () => {
|
|
115
|
+
void queryClient.cancelQueries({ queryKey: sheetsQueryKeys.scope(scopeKey) });
|
|
116
|
+
};
|
|
117
|
+
}, [queryClient, scopeKey]);
|
|
118
|
+
const contextValue = useMemo(
|
|
119
|
+
() => ({ config, execute, executeUpload, storage, canUpload, scopeKey }),
|
|
120
|
+
[config, execute, executeUpload, storage, canUpload, scopeKey]
|
|
121
|
+
);
|
|
122
|
+
return /* @__PURE__ */ jsx(QueryClientProvider, { client: queryClient, children: /* @__PURE__ */ jsx(SheetsStoreContext.Provider, { value: store, children: /* @__PURE__ */ jsx(SheetsContext.Provider, { value: contextValue, children }) }) });
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export {
|
|
126
|
+
SheetsProvider
|
|
127
|
+
};
|
|
128
|
+
//# sourceMappingURL=chunk-MOFFS5WQ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/context/sheets-provider.tsx"],"sourcesContent":["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 {\n\tcreatePresignedSheetsUpload,\n\tcreateSheetsExecute,\n\tresolveStorageTransport,\n\ttype SheetsExecuteFn,\n\ttype SheetsUploadFn,\n} 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\nconst unavailableUpload: SheetsUploadFn = async () => {\n\tthrow new Error('Uploads need a storage endpoint');\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\tconst storage = useMemo(() => resolveStorageTransport(config, getToken), [config, getToken]);\n\tconst bucketKey = config.upload?.bucketKey;\n\tconst executeUpload: SheetsUploadFn = useMemo(() => {\n\t\tif (config.executeUpload) return config.executeUpload;\n\t\treturn storage ? createPresignedSheetsUpload(storage, bucketKey) : unavailableUpload;\n\t}, [config.executeUpload, storage, bucketKey]);\n\tconst canUpload = Boolean(config.executeUpload || storage);\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, storage, canUpload, scopeKey }),\n\t\t[config, execute, executeUpload, storage, canUpload, 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"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAAA,SAAS,WAAW,OAAO,SAAS,cAAc;AAClD,SAAS,aAAa,2BAA2B;AACjD,SAAS,YAAY,uBAAsC;AAiKvD;AA5IJ,IAAM,oBAAoC,YAAY;AACrD,QAAM,IAAI,MAAM,iCAAiC;AAClD;AAEO,SAAS,eAAe,EAAE,QAAQ,SAAS,GAAwB;AACzE,QAAM,qBAAqB,MAAM;AAEjC,QAAM,WAAW,OAA0C,IAAI;AAC/D,MAAI,CAAC,SAAS,SAAS;AACtB,aAAS,UAAU,kBAAkB;AAAA,EACtC;AACA,QAAM,QAAQ,SAAS;AACvB,QAAM,wBAAwB,gBAAgB,OAAO,CAAC,UAAU,MAAM,WAAW;AACjF,QAAM,wBAAwB,gBAAgB,OAAO,CAAC,UAAU,MAAM,WAAW;AAGjF,kBAAgB,OAAO,MAAM;AAC7B,kBAAgB,OAAO,MAAM;AAG7B,YAAU,MAAM;AACf,oBAAgB,OAAO,MAAM;AAC7B,oBAAgB,OAAO,MAAM;AAAA,EAC9B,GAAG,CAAC,OAAO,QAAQ,OAAO,MAAM,CAAC;AAGjC,YAAU,MAAM;AACf,UAAMA,SAAQ,SAAS,SAAS,SAAS;AACzC,QAAI,CAACA,OAAO;AAEZ,QAAI,OAAO,KAAK,SAAS,cAAc;AAEtC,MAAAA,OAAM,mBAAmB;AACzB;AAAA,IACD;AACA,UAAM,aAAa,OAAO,cAAc;AACxC,UAAM,SAA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