@constructive-io/sheets 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/context/sheets-upload-presigned.ts","../src/context/sheets-execute.ts"],"sourcesContent":["/**\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 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"],"mappings":";;;AAuBA,SAAS,6BAA6B;AAEtC,SAAS,mBAAmB;AAoD5B,eAAsB,oBAAoB,QAAsC;AAC/E,MAAI,CAAC,WAAW,QAAQ,QAAQ;AAC/B,UAAM,YAAY,WAAW,yEAAyE;AAAA,EACvG;AACA,QAAM,SAAS,MAAM,OAAO,OAAO,OAAO,WAAW,MAAM;AAC3D,QAAM,QAAQ,IAAI,WAAW,MAAM;AACnC,MAAI,MAAM;AACV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