@constructive-io/sheets 0.13.0 → 0.14.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.
Files changed (45) hide show
  1. package/README.md +10 -1
  2. package/dist/advanced.cjs +555 -680
  3. package/dist/advanced.cjs.map +1 -1
  4. package/dist/advanced.d.cts +2 -2
  5. package/dist/advanced.d.ts +2 -2
  6. package/dist/advanced.js +4 -4
  7. package/dist/auth.cjs.map +1 -1
  8. package/dist/auth.js +2 -2
  9. package/dist/{chunk-PZL2BCWF.js → chunk-6Y7CZ5VS.js} +2 -2
  10. package/dist/chunk-6Y7CZ5VS.js.map +1 -0
  11. package/dist/{chunk-26J3DVW7.js → chunk-BGL6EBTE.js} +116 -173
  12. package/dist/chunk-BGL6EBTE.js.map +1 -0
  13. package/dist/{chunk-MXVNIKES.js → chunk-BYAYBXVB.js} +2 -2
  14. package/dist/{chunk-CBXNKMN6.js → chunk-ER3FIDK7.js} +444 -458
  15. package/dist/chunk-ER3FIDK7.js.map +1 -0
  16. package/dist/chunk-GZM2CSTR.js +279 -0
  17. package/dist/chunk-GZM2CSTR.js.map +1 -0
  18. package/dist/{chunk-H5HR5HUJ.js → chunk-YJZFHL2D.js} +1 -1
  19. package/dist/chunk-YJZFHL2D.js.map +1 -0
  20. package/dist/{date-editor-ZFNDKYBD.js → date-editor-G26WKILO.js} +2 -2
  21. package/dist/{grid-cell-types-Pbe2m2tE.d.ts → grid-cell-types-C2-ocDS7.d.cts} +45 -5
  22. package/dist/{grid-cell-types-Pbe2m2tE.d.cts → grid-cell-types-C2-ocDS7.d.ts} +45 -5
  23. package/dist/index.cjs +789 -607
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.d.cts +106 -112
  26. package/dist/index.d.ts +106 -112
  27. package/dist/index.js +234 -134
  28. package/dist/index.js.map +1 -1
  29. package/dist/{sheets-context-Cu3Ec_ca.d.ts → sheets-context-CHUVJCff.d.ts} +32 -31
  30. package/dist/{sheets-context-CY1RmDKL.d.cts → sheets-context-C_MkTxXm.d.cts} +32 -31
  31. package/dist/testing.cjs +128 -57
  32. package/dist/testing.cjs.map +1 -1
  33. package/dist/testing.d.cts +2 -2
  34. package/dist/testing.d.ts +2 -2
  35. package/dist/testing.js +16 -4
  36. package/dist/testing.js.map +1 -1
  37. package/package.json +5 -4
  38. package/dist/chunk-26J3DVW7.js.map +0 -1
  39. package/dist/chunk-CBXNKMN6.js.map +0 -1
  40. package/dist/chunk-H5HR5HUJ.js.map +0 -1
  41. package/dist/chunk-HETVHNMD.js +0 -123
  42. package/dist/chunk-HETVHNMD.js.map +0 -1
  43. package/dist/chunk-PZL2BCWF.js.map +0 -1
  44. /package/dist/{chunk-MXVNIKES.js.map → chunk-BYAYBXVB.js.map} +0 -0
  45. /package/dist/{date-editor-ZFNDKYBD.js.map → date-editor-G26WKILO.js.map} +0 -0
@@ -2,19 +2,26 @@ import * as react from 'react';
2
2
  import { QueryClient } from '@tanstack/react-query';
3
3
  import { DocumentNode } from 'graphql';
4
4
  import { TypedDocumentString, FieldSelection, CleanTable, MetaQuery, MutationOptions } from '@constructive-io/data';
5
- import { b as CellType, S as SheetsCell, C as CellCreationMetadata, c as CellCategory, E as EditorProps } from './grid-cell-types-Pbe2m2tE.js';
5
+ import { b as CellType, S as SheetsCell, C as CellCreationMetadata, c as CellCategory, E as EditorProps } from './grid-cell-types-C2-ocDS7.js';
6
6
 
7
7
  type ExecutableDocument = TypedDocumentString<any, any> | DocumentNode | string | unknown;
8
8
  type SheetsExecuteFn = <T = unknown>(document: ExecutableDocument, variables?: Record<string, unknown>) => Promise<T>;
9
- /**
10
- * Result of an upload through the seam. `url` is the only guaranteed field;
11
- * the REST upload endpoint also returns `{ filename, mime, size }` (and may
12
- * return server-internal extras). Keeping it open-ended lets callers read the
13
- * richer metadata while a bare `{ url }` (e.g. the mock) still satisfies it.
14
- */
15
- type SheetsUploadResult = {
16
- url: string;
17
- } & Record<string, unknown>;
9
+ /** Durable file metadata for image and upload columns. */
10
+ interface SheetsFileValue {
11
+ id: string;
12
+ key: string;
13
+ bucket_id: string;
14
+ mime: string;
15
+ size: number;
16
+ filename: string;
17
+ /** Public URL supplied by storage, when available. */
18
+ url?: string;
19
+ }
20
+ interface SheetsUploadResult {
21
+ file: SheetsFileValue;
22
+ /** Optional download URL for immediate use. It can expire. */
23
+ url?: string;
24
+ }
18
25
  /**
19
26
  * Optional upload metadata carried through the seam (third arg). Lets an
20
27
  * injected `executeUpload` see the destination field/row and report progress.
@@ -32,25 +39,7 @@ interface SheetsUploadOptions {
32
39
  }
33
40
  type SheetsUploadFn = (file: File, path?: string, options?: SheetsUploadOptions) => Promise<SheetsUploadResult>;
34
41
  declare function createSheetsExecute(config: SheetsConfig, getToken: () => string | null): SheetsExecuteFn;
35
- /**
36
- * Presigned-URL cell-upload seam.
37
- *
38
- * Replaces the legacy multipart `<endpoint>/upload` POST entirely. The flow:
39
- * 1. Read + SHA-256 hash the file bytes (Web Crypto)
40
- * 2. Discover (cached per endpoint) the upload op + downloadUrl-by-id field
41
- * via GraphQL introspection — the root `upload<Type>File` mutation, matched
42
- * by FIELD/TYPE SHAPE (LOCKED: no hardcoded names)
43
- * 3. Call the upload op with input `{ bucketKey, contentHash, contentType,
44
- * size, filename }` — NO `ownerId` (app-scoped buckets have no owner_id)
45
- * 4. If `uploadUrl` is non-null, PUT the raw bytes to it with ONLY the signed
46
- * `Content-Type` header (NO Authorization). Skipped when `deduplicated`.
47
- * 5. Resolve the stable public `downloadUrl` for the returned fileId.
48
- *
49
- * Returns `{ url, filename, mime, size, key, fileId }` where `url` is the stable
50
- * download URL — the same cell value shape callers/Step-2 already consume.
51
- *
52
- * `path` is ignored (content-addressed buckets key on `contentHash`).
53
- */
42
+ /** Creates an uploader for storage. Direct callers may use the supplied endpoint as storage. */
54
43
  declare function createSheetsUpload(config: SheetsConfig, getToken: () => string | null): SheetsUploadFn;
55
44
 
56
45
  /**
@@ -86,6 +75,7 @@ interface CellProps {
86
75
  isEditing: boolean;
87
76
  onStartEdit: () => void;
88
77
  disabled: boolean;
78
+ readOnlyReason?: string;
89
79
  }
90
80
 
91
81
  /** Schema-only inputs used to DETECT a cell type. Never the runtime value. */
@@ -190,6 +180,10 @@ interface SheetsAuthEmbedded {
190
180
  interface SheetsAuthStandalone {
191
181
  mode: 'standalone';
192
182
  }
183
+ interface SheetsStorageTransport {
184
+ endpoint: string;
185
+ execute: SheetsExecuteFn;
186
+ }
193
187
  interface SheetsConfig {
194
188
  /** Data endpoint (app-public GraphQL) */
195
189
  endpoint: string;
@@ -207,7 +201,12 @@ interface SheetsConfig {
207
201
  execute?: SheetsExecuteFn;
208
202
  /** Optional: inject custom upload function */
209
203
  executeUpload?: SheetsUploadFn;
210
- /** Optional upload settings. `bucketKey` defaults to "public". */
204
+ /** Storage endpoint for media uploads and download URL lookups. */
205
+ storage?: {
206
+ endpoint: string;
207
+ execute?: SheetsExecuteFn;
208
+ };
209
+ /** Explicit bucket override. Omit to use the tenant's public default. */
211
210
  upload?: {
212
211
  bucketKey?: string;
213
212
  };
@@ -231,6 +230,8 @@ interface SheetsContextValue {
231
230
  config: SheetsConfig;
232
231
  execute: SheetsExecuteFn;
233
232
  executeUpload: SheetsUploadFn;
233
+ storage?: SheetsStorageTransport;
234
+ canUpload: boolean;
234
235
  scopeKey: SheetsScopeKey;
235
236
  }
236
237
  interface SheetsScopeKey {
@@ -241,4 +242,4 @@ interface SheetsScopeKey {
241
242
  declare const SheetsContext: react.Context<SheetsContextValue | null>;
242
243
  declare function useSheetsContext(): SheetsContextValue;
243
244
 
244
- export { type AdapterListQuery as A, type CellProps as C, type SheetsExecuteFn as S, type SheetsUploadFn as a, type SheetsConfig as b, type CellTypeDefinition as c, type SheetsCellRenderContext as d, type CellTypeMatchInput as e, type SheetsScopeKey as f, type SheetsBackendAdapter as g, type AdapterListResult as h, type AdapterPageInfo as i, type AdapterTableContext as j, type CellColumnDescriptor as k, type CellTypePlugin as l, type SheetsAuthEmbedded as m, type SheetsAuthStandalone as n, SheetsContext as o, type SheetsContextValue as p, type SheetsLogger as q, createSheetsExecute as r, createSheetsUpload as s, defineCellType as t, useSheetsContext as u };
245
+ export { type AdapterListQuery as A, type CellProps as C, type SheetsExecuteFn as S, type SheetsUploadFn as a, type SheetsConfig as b, type CellTypeDefinition as c, type SheetsCellRenderContext as d, type CellTypeMatchInput as e, type SheetsScopeKey as f, type SheetsFileValue as g, type SheetsBackendAdapter as h, type AdapterListResult as i, type AdapterPageInfo as j, type AdapterTableContext as k, type CellColumnDescriptor as l, type CellTypePlugin as m, type SheetsAuthEmbedded as n, type SheetsAuthStandalone as o, SheetsContext as p, type SheetsContextValue as q, type SheetsLogger as r, type SheetsUploadResult as s, createSheetsExecute as t, createSheetsUpload as u, defineCellType as v, useSheetsContext as w };
@@ -2,19 +2,26 @@ import * as react from 'react';
2
2
  import { QueryClient } from '@tanstack/react-query';
3
3
  import { DocumentNode } from 'graphql';
4
4
  import { TypedDocumentString, FieldSelection, CleanTable, MetaQuery, MutationOptions } from '@constructive-io/data';
5
- import { b as CellType, S as SheetsCell, C as CellCreationMetadata, c as CellCategory, E as EditorProps } from './grid-cell-types-Pbe2m2tE.cjs';
5
+ import { b as CellType, S as SheetsCell, C as CellCreationMetadata, c as CellCategory, E as EditorProps } from './grid-cell-types-C2-ocDS7.cjs';
6
6
 
7
7
  type ExecutableDocument = TypedDocumentString<any, any> | DocumentNode | string | unknown;
8
8
  type SheetsExecuteFn = <T = unknown>(document: ExecutableDocument, variables?: Record<string, unknown>) => Promise<T>;
9
- /**
10
- * Result of an upload through the seam. `url` is the only guaranteed field;
11
- * the REST upload endpoint also returns `{ filename, mime, size }` (and may
12
- * return server-internal extras). Keeping it open-ended lets callers read the
13
- * richer metadata while a bare `{ url }` (e.g. the mock) still satisfies it.
14
- */
15
- type SheetsUploadResult = {
16
- url: string;
17
- } & Record<string, unknown>;
9
+ /** Durable file metadata for image and upload columns. */
10
+ interface SheetsFileValue {
11
+ id: string;
12
+ key: string;
13
+ bucket_id: string;
14
+ mime: string;
15
+ size: number;
16
+ filename: string;
17
+ /** Public URL supplied by storage, when available. */
18
+ url?: string;
19
+ }
20
+ interface SheetsUploadResult {
21
+ file: SheetsFileValue;
22
+ /** Optional download URL for immediate use. It can expire. */
23
+ url?: string;
24
+ }
18
25
  /**
19
26
  * Optional upload metadata carried through the seam (third arg). Lets an
20
27
  * injected `executeUpload` see the destination field/row and report progress.
@@ -32,25 +39,7 @@ interface SheetsUploadOptions {
32
39
  }
33
40
  type SheetsUploadFn = (file: File, path?: string, options?: SheetsUploadOptions) => Promise<SheetsUploadResult>;
34
41
  declare function createSheetsExecute(config: SheetsConfig, getToken: () => string | null): SheetsExecuteFn;
35
- /**
36
- * Presigned-URL cell-upload seam.
37
- *
38
- * Replaces the legacy multipart `<endpoint>/upload` POST entirely. The flow:
39
- * 1. Read + SHA-256 hash the file bytes (Web Crypto)
40
- * 2. Discover (cached per endpoint) the upload op + downloadUrl-by-id field
41
- * via GraphQL introspection — the root `upload<Type>File` mutation, matched
42
- * by FIELD/TYPE SHAPE (LOCKED: no hardcoded names)
43
- * 3. Call the upload op with input `{ bucketKey, contentHash, contentType,
44
- * size, filename }` — NO `ownerId` (app-scoped buckets have no owner_id)
45
- * 4. If `uploadUrl` is non-null, PUT the raw bytes to it with ONLY the signed
46
- * `Content-Type` header (NO Authorization). Skipped when `deduplicated`.
47
- * 5. Resolve the stable public `downloadUrl` for the returned fileId.
48
- *
49
- * Returns `{ url, filename, mime, size, key, fileId }` where `url` is the stable
50
- * download URL — the same cell value shape callers/Step-2 already consume.
51
- *
52
- * `path` is ignored (content-addressed buckets key on `contentHash`).
53
- */
42
+ /** Creates an uploader for storage. Direct callers may use the supplied endpoint as storage. */
54
43
  declare function createSheetsUpload(config: SheetsConfig, getToken: () => string | null): SheetsUploadFn;
55
44
 
56
45
  /**
@@ -86,6 +75,7 @@ interface CellProps {
86
75
  isEditing: boolean;
87
76
  onStartEdit: () => void;
88
77
  disabled: boolean;
78
+ readOnlyReason?: string;
89
79
  }
90
80
 
91
81
  /** Schema-only inputs used to DETECT a cell type. Never the runtime value. */
@@ -190,6 +180,10 @@ interface SheetsAuthEmbedded {
190
180
  interface SheetsAuthStandalone {
191
181
  mode: 'standalone';
192
182
  }
183
+ interface SheetsStorageTransport {
184
+ endpoint: string;
185
+ execute: SheetsExecuteFn;
186
+ }
193
187
  interface SheetsConfig {
194
188
  /** Data endpoint (app-public GraphQL) */
195
189
  endpoint: string;
@@ -207,7 +201,12 @@ interface SheetsConfig {
207
201
  execute?: SheetsExecuteFn;
208
202
  /** Optional: inject custom upload function */
209
203
  executeUpload?: SheetsUploadFn;
210
- /** Optional upload settings. `bucketKey` defaults to "public". */
204
+ /** Storage endpoint for media uploads and download URL lookups. */
205
+ storage?: {
206
+ endpoint: string;
207
+ execute?: SheetsExecuteFn;
208
+ };
209
+ /** Explicit bucket override. Omit to use the tenant's public default. */
211
210
  upload?: {
212
211
  bucketKey?: string;
213
212
  };
@@ -231,6 +230,8 @@ interface SheetsContextValue {
231
230
  config: SheetsConfig;
232
231
  execute: SheetsExecuteFn;
233
232
  executeUpload: SheetsUploadFn;
233
+ storage?: SheetsStorageTransport;
234
+ canUpload: boolean;
234
235
  scopeKey: SheetsScopeKey;
235
236
  }
236
237
  interface SheetsScopeKey {
@@ -241,4 +242,4 @@ interface SheetsScopeKey {
241
242
  declare const SheetsContext: react.Context<SheetsContextValue | null>;
242
243
  declare function useSheetsContext(): SheetsContextValue;
243
244
 
244
- export { type AdapterListQuery as A, type CellProps as C, type SheetsExecuteFn as S, type SheetsUploadFn as a, type SheetsConfig as b, type CellTypeDefinition as c, type SheetsCellRenderContext as d, type CellTypeMatchInput as e, type SheetsScopeKey as f, type SheetsBackendAdapter as g, type AdapterListResult as h, type AdapterPageInfo as i, type AdapterTableContext as j, type CellColumnDescriptor as k, type CellTypePlugin as l, type SheetsAuthEmbedded as m, type SheetsAuthStandalone as n, SheetsContext as o, type SheetsContextValue as p, type SheetsLogger as q, createSheetsExecute as r, createSheetsUpload as s, defineCellType as t, useSheetsContext as u };
245
+ export { type AdapterListQuery as A, type CellProps as C, type SheetsExecuteFn as S, type SheetsUploadFn as a, type SheetsConfig as b, type CellTypeDefinition as c, type SheetsCellRenderContext as d, type CellTypeMatchInput as e, type SheetsScopeKey as f, type SheetsFileValue as g, type SheetsBackendAdapter as h, type AdapterListResult as i, type AdapterPageInfo as j, type AdapterTableContext as k, type CellColumnDescriptor as l, type CellTypePlugin as m, type SheetsAuthEmbedded as n, type SheetsAuthStandalone as o, SheetsContext as p, type SheetsContextValue as q, type SheetsLogger as r, type SheetsUploadResult as s, createSheetsExecute as t, createSheetsUpload as u, defineCellType as v, useSheetsContext as w };
package/dist/testing.cjs CHANGED
@@ -62,9 +62,14 @@ async function sha256HexFromBuffer(buffer) {
62
62
  }
63
63
  return hex;
64
64
  }
65
- var capabilityCache = /* @__PURE__ */ new Map();
66
- function discoverUploadCapability(endpoint, execute) {
67
- const cached = capabilityCache.get(endpoint);
65
+ var capabilityCache = /* @__PURE__ */ new WeakMap();
66
+ async function discoverStorageCapabilities(endpoint, execute) {
67
+ let endpoints = capabilityCache.get(execute);
68
+ if (!endpoints) {
69
+ endpoints = /* @__PURE__ */ new Map();
70
+ capabilityCache.set(execute, endpoints);
71
+ }
72
+ const cached = endpoints.get(endpoint);
68
73
  if (cached) return cached;
69
74
  const promise = (async () => {
70
75
  const data = await execute((0, import_graphql.getIntrospectionQuery)());
@@ -72,12 +77,21 @@ function discoverUploadCapability(endpoint, execute) {
72
77
  if (!schema) {
73
78
  throw import_data.createError.badRequest("Uploads are not enabled for this endpoint.");
74
79
  }
75
- return resolveUploadCapability(schema);
80
+ return resolveStorageCapabilities(schema);
76
81
  })();
77
- promise.catch(() => capabilityCache.delete(endpoint));
78
- capabilityCache.set(endpoint, promise);
82
+ promise.catch(() => endpoints.delete(endpoint));
83
+ endpoints.set(endpoint, promise);
79
84
  return promise;
80
85
  }
86
+ async function discoverUploadCapability(endpoint, execute) {
87
+ const { upload } = await discoverStorageCapabilities(endpoint, execute);
88
+ if (!upload) capabilityCache.get(execute)?.delete(endpoint);
89
+ return requireUploadCapability(upload);
90
+ }
91
+ function requireUploadCapability(upload) {
92
+ if (!upload) throw import_data.createError.badRequest("Uploads are not enabled for this endpoint.");
93
+ return upload;
94
+ }
81
95
  function namedTypeName(ref) {
82
96
  let cur = ref;
83
97
  while (cur && (cur.kind === "NON_NULL" || cur.kind === "LIST")) {
@@ -93,7 +107,7 @@ function isListTypeRef(ref) {
93
107
  return cur?.kind === "LIST";
94
108
  }
95
109
  var PK_FIELD_NAME = "id";
96
- function resolveUploadCapability(schema) {
110
+ function resolveStorageCapabilities(schema) {
97
111
  const typeByName = /* @__PURE__ */ new Map();
98
112
  for (const t of schema.types) {
99
113
  if (t.name) typeByName.set(t.name, t);
@@ -112,7 +126,7 @@ function resolveUploadCapability(schema) {
112
126
  const present = new Set(t.inputFields.map((f) => f.name));
113
127
  return names.every((n) => present.has(n));
114
128
  };
115
- const PAYLOAD_FIELDS = ["uploadUrl", "fileId", "deduplicated"];
129
+ const PAYLOAD_FIELDS = ["uploadUrl", "fileId", "key", "deduplicated"];
116
130
  const INPUT_FIELDS = ["contentHash", "bucketKey", "contentType", "size"];
117
131
  const mutationType = schema.mutationType ? typeByName.get(schema.mutationType.name) : null;
118
132
  const queryType = schema.queryType ? typeByName.get(schema.queryType.name) : null;
@@ -122,52 +136,69 @@ function resolveUploadCapability(schema) {
122
136
  if (!inputArg) continue;
123
137
  const inputTypeName = namedTypeName(inputArg.type);
124
138
  const payloadTypeName = namedTypeName(field.type);
125
- if (inputHasFields(inputTypeName, INPUT_FIELDS) && objectHasFields(payloadTypeName, PAYLOAD_FIELDS)) {
126
- upload = { uploadFieldName: field.name, inputTypeName };
127
- break;
139
+ if (inputTypeName && inputHasFields(inputTypeName, INPUT_FIELDS) && objectHasFields(payloadTypeName, PAYLOAD_FIELDS)) {
140
+ const payloadFields = typeByName.get(payloadTypeName ?? "")?.fields;
141
+ const candidate = {
142
+ uploadFieldName: field.name,
143
+ inputTypeName,
144
+ hasFileProjection: payloadFields?.some(
145
+ (f) => f.name === "file" && !isListTypeRef(f.type) && namedTypeName(f.type) === "JSON"
146
+ ) ?? false
147
+ };
148
+ if (field.name === "uploadAppFile") {
149
+ upload = candidate;
150
+ break;
151
+ }
152
+ upload ??= candidate;
128
153
  }
129
154
  }
130
- if (!upload) {
131
- throw import_data.createError.badRequest("Uploads are not enabled for this endpoint.");
132
- }
133
- const downloadById = resolveDownloadByIdField(schema, typeByName, queryType, upload.uploadFieldName);
134
- return {
135
- ...upload,
136
- ...downloadById
137
- };
138
- }
139
- function resolveDownloadByIdField(schema, typeByName, queryType, uploadFieldName) {
140
- const fileTypesWithDownloadUrl = /* @__PURE__ */ new Set();
155
+ const fileTypes = /* @__PURE__ */ new Set();
141
156
  for (const t of schema.types) {
142
157
  if (t.kind === "OBJECT" && t.name && t.fields?.some((f) => f.name === "downloadUrl")) {
143
- fileTypesWithDownloadUrl.add(t.name);
158
+ fileTypes.add(t.name);
144
159
  }
145
160
  }
161
+ const uploadType = upload?.uploadFieldName.replace(/^upload/, "") ?? "AppFile";
162
+ const uploadDownload = resolveDownloadByIdField(typeByName, queryType, fileTypes, uploadType);
163
+ const preferredPreviewType = fileTypes.has("AppFile") ? "AppFile" : uploadType;
164
+ const previewType = fileTypes.has(preferredPreviewType) ? preferredPreviewType : uploadDownload?.fileTypeName ?? preferredPreviewType;
165
+ const download = previewType === uploadType ? uploadDownload : resolveDownloadByIdField(typeByName, queryType, fileTypes, previewType);
166
+ const batch = resolveConnectionDownloadField(typeByName, queryType, fileTypes, previewType, true);
167
+ return {
168
+ upload: upload ? { ...upload, download: uploadDownload } : null,
169
+ download,
170
+ batch
171
+ };
172
+ }
173
+ function resolveDownloadByIdField(typeByName, queryType, fileTypesWithDownloadUrl, preferred) {
174
+ let singular = null;
146
175
  for (const field of queryType?.fields ?? []) {
147
176
  const returnTypeName = namedTypeName(field.type);
148
177
  if (!returnTypeName || !fileTypesWithDownloadUrl.has(returnTypeName)) continue;
149
178
  if (field.args.length === 1 && field.args[0].name === PK_FIELD_NAME) {
150
- return {
179
+ const candidate = {
151
180
  fileByIdField: field.name,
152
181
  fileByIdArgName: "id",
153
182
  fileTypeName: returnTypeName,
154
183
  idScalarName: namedTypeName(field.args[0].type) ?? void 0
155
184
  };
185
+ if (returnTypeName === preferred) return candidate;
186
+ singular ??= candidate;
156
187
  }
157
188
  }
158
- const connection = resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, uploadFieldName);
159
- if (connection) return connection;
189
+ const connection = resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, preferred);
190
+ if (connection?.fileTypeName === preferred) return connection;
191
+ if (singular || connection) return singular ?? connection;
160
192
  const nodeField = queryType?.fields?.find(
161
193
  (f) => f.name === "node" && f.args.some((a) => a.name === "nodeId")
162
194
  );
163
195
  if (nodeField && fileTypesWithDownloadUrl.size > 0) {
164
- const preferred = uploadFieldName.replace(/^upload/, "");
165
196
  const fileTypeName = fileTypesWithDownloadUrl.has(preferred) ? preferred : [...fileTypesWithDownloadUrl][0];
166
197
  return { fileByIdField: "node", fileByIdArgName: "nodeId", fileTypeName };
167
198
  }
168
- throw import_data.createError.badRequest("Uploads are not enabled for this endpoint.");
199
+ return null;
169
200
  }
170
- function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, uploadFieldName) {
201
+ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, preferred, batch = false) {
171
202
  const EQUALITY_OPERATORS = ["equalTo", "eq"];
172
203
  const candidates = [];
173
204
  for (const field of queryType?.fields ?? []) {
@@ -182,6 +213,8 @@ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDown
182
213
  });
183
214
  if (!nodesField) continue;
184
215
  const fileTypeName = namedTypeName(nodesField.type);
216
+ if (batch && (fileTypeName !== preferred || !typeByName.get(fileTypeName)?.fields?.some((field2) => field2.name === PK_FIELD_NAME))) continue;
217
+ const connectionHasFirst = field.args.some((arg) => arg.name === "first");
185
218
  for (const arg of field.args) {
186
219
  const filterTypeName = namedTypeName(arg.type);
187
220
  const filterType = filterTypeName ? typeByName.get(filterTypeName) : null;
@@ -191,7 +224,7 @@ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDown
191
224
  const idFieldTypeName = namedTypeName(idField.type);
192
225
  const idFieldType = idFieldTypeName ? typeByName.get(idFieldTypeName) : null;
193
226
  if (idFieldType?.kind === "INPUT_OBJECT" && idFieldType.inputFields) {
194
- const opField = EQUALITY_OPERATORS.map(
227
+ const opField = batch ? idFieldType.inputFields.find((f) => f.name === "in" && isListTypeRef(f.type)) : EQUALITY_OPERATORS.map(
195
228
  (op) => idFieldType.inputFields.find((f) => f.name === op)
196
229
  ).find((f) => f != null);
197
230
  if (opField) {
@@ -203,13 +236,14 @@ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDown
203
236
  connectionFilterArgName: arg.name,
204
237
  connectionIdField: idField.name,
205
238
  connectionIdOperator: opField.name,
206
- connectionNodesField: nodesField.name
239
+ connectionNodesField: nodesField.name,
240
+ connectionHasFirst
207
241
  });
208
242
  break;
209
243
  }
210
244
  continue;
211
245
  }
212
- if (idFieldType?.kind === "SCALAR" || !idFieldType && idFieldTypeName) {
246
+ if (!batch && (idFieldType?.kind === "SCALAR" || !idFieldType && idFieldTypeName)) {
213
247
  candidates.push({
214
248
  fileByIdField: field.name,
215
249
  fileByIdArgName: "connection",
@@ -217,14 +251,14 @@ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDown
217
251
  idScalarName: idFieldTypeName ?? void 0,
218
252
  connectionFilterArgName: arg.name,
219
253
  connectionIdField: idField.name,
220
- connectionNodesField: nodesField.name
254
+ connectionNodesField: nodesField.name,
255
+ connectionHasFirst
221
256
  });
222
257
  break;
223
258
  }
224
259
  }
225
260
  }
226
261
  if (candidates.length === 0) return null;
227
- const preferred = uploadFieldName.replace(/^upload/, "");
228
262
  return candidates.find((c) => c.fileTypeName === preferred) ?? candidates[0];
229
263
  }
230
264
  async function callUploadOp(execute, cap, input) {
@@ -235,12 +269,13 @@ async function callUploadOp(execute, cap, input) {
235
269
  fileId
236
270
  key
237
271
  deduplicated
272
+ file
238
273
  }
239
274
  }
240
275
  `.trim();
241
276
  const data = await execute(mutation, {
242
277
  input: {
243
- bucketKey: input.bucketKey,
278
+ ...input.bucketKey === void 0 ? { isPublic: true } : { bucketKey: input.bucketKey },
244
279
  contentHash: input.contentHash,
245
280
  contentType: input.contentType,
246
281
  size: input.size,
@@ -251,8 +286,16 @@ async function callUploadOp(execute, cap, input) {
251
286
  if (!payload) {
252
287
  throw import_data.createError.badRequest("Upload failed: no payload returned from upload mutation.");
253
288
  }
289
+ const file = payload.file;
290
+ if (!file || typeof file.id !== "string" || typeof file.key !== "string" || typeof file.bucket_id !== "string" || typeof file.mime !== "string" || typeof file.size !== "number") {
291
+ throw import_data.createError.badRequest("Upload failed: server returned an invalid file projection.");
292
+ }
254
293
  return payload;
255
294
  }
295
+ var STORAGE_UPLOAD_BLOCKED_MESSAGE = "Upload failed: the storage server didn't accept the upload from this site. Check the bucket's allowed origins (CORS) and your connection.";
296
+ function storageUnreachableError() {
297
+ return import_data.createError.graphql(STORAGE_UPLOAD_BLOCKED_MESSAGE, "STORAGE_UPLOAD_BLOCKED");
298
+ }
256
299
  async function presignedPut(url, buffer, contentType, onProgress) {
257
300
  const total = buffer.byteLength;
258
301
  if (onProgress && typeof XMLHttpRequest !== "undefined") {
@@ -266,8 +309,8 @@ async function presignedPut(url, buffer, contentType, onProgress) {
266
309
  headers: { "Content-Type": contentType },
267
310
  body: buffer
268
311
  });
269
- } catch (error) {
270
- throw import_data.createError.network(error instanceof Error ? error : void 0);
312
+ } catch {
313
+ throw storageUnreachableError();
271
314
  }
272
315
  if (!response.ok) {
273
316
  const body = await response.text().catch(() => "");
@@ -297,7 +340,7 @@ function putWithXHR(url, buffer, contentType, total, onProgress) {
297
340
  reject(import_data.createError.badRequest(`Upload failed: ${xhr.status} ${xhr.statusText}${xhr.responseText ? ` \u2014 ${xhr.responseText}` : ""}`));
298
341
  }
299
342
  });
300
- xhr.addEventListener("error", () => reject(import_data.createError.network()));
343
+ xhr.addEventListener("error", () => reject(storageUnreachableError()));
301
344
  xhr.send(buffer);
302
345
  });
303
346
  }
@@ -335,7 +378,7 @@ async function fetchDownloadUrl(execute, cap, fileId) {
335
378
  const filterLiteral = cap.connectionIdOperator ? `{ ${idField}: { ${cap.connectionIdOperator}: $id } }` : `{ ${idField}: $id }`;
336
379
  const query2 = `
337
380
  query SheetsDownloadUrl($id: ${idScalar2}!) {
338
- ${cap.fileByIdField}(${filterArg}: ${filterLiteral}, first: 1) {
381
+ ${cap.fileByIdField}(${filterArg}: ${filterLiteral}${cap.connectionHasFirst ? ", first: 1" : ""}) {
339
382
  ${nodesField} {
340
383
  downloadUrl
341
384
  }
@@ -459,17 +502,26 @@ function createSheetsExecute(config, getToken) {
459
502
  return result.data;
460
503
  };
461
504
  }
462
- function createSheetsUpload(config, getToken) {
463
- const execute = config.execute ?? createSheetsExecute(config, getToken);
505
+ function resolveStorageTransport(config, getToken) {
506
+ const endpoint = config.storage?.endpoint;
507
+ if (!endpoint) return void 0;
508
+ return {
509
+ endpoint,
510
+ execute: config.storage?.execute ?? createSheetsExecute({ ...config, endpoint }, getToken)
511
+ };
512
+ }
513
+ function createPresignedSheetsUpload({ endpoint, execute }, bucketKey) {
464
514
  return async (file, _path, options) => {
465
- if (!config.endpoint) {
515
+ if (!endpoint) {
466
516
  throw import_data2.createError.badRequest("No GraphQL endpoint configured.");
467
517
  }
468
- const bucketKey = config.upload?.bucketKey ?? "public";
518
+ const cap = await discoverUploadCapability(endpoint, execute);
519
+ if (!cap.hasFileProjection) {
520
+ throw import_data2.createError.badRequest("Uploads require a storage mutation that returns a file projection.");
521
+ }
469
522
  const contentType = file.type || "application/octet-stream";
470
523
  const buffer = await file.arrayBuffer();
471
524
  const contentHash = await sha256HexFromBuffer(buffer);
472
- const cap = await discoverUploadCapability(config.endpoint, execute);
473
525
  const payload = await callUploadOp(execute, cap, {
474
526
  bucketKey,
475
527
  contentHash,
@@ -485,15 +537,15 @@ function createSheetsUpload(config, getToken) {
485
537
  } else {
486
538
  options?.onProgress?.({ loaded: file.size, total: file.size, percentage: 100 });
487
539
  }
488
- const url = await fetchDownloadUrl(execute, cap, payload.fileId);
489
- return {
490
- url,
491
- filename: file.name,
492
- mime: file.type,
493
- size: file.size,
494
- key: payload.key,
495
- fileId: payload.fileId
540
+ const result = {
541
+ file: { ...payload.file, filename: payload.file.filename ?? file.name }
496
542
  };
543
+ if (!cap.download) return result;
544
+ try {
545
+ return { ...result, url: await fetchDownloadUrl(execute, cap.download, payload.fileId) };
546
+ } catch {
547
+ return result;
548
+ }
497
549
  };
498
550
  }
499
551
 
@@ -1104,6 +1156,7 @@ var sheetsQueryKeys = {
1104
1156
  root: ["sheets"],
1105
1157
  scope: (scope) => ["sheets", scope],
1106
1158
  meta: (scope) => [...sheetsQueryKeys.scope(scope), "meta"],
1159
+ mediaUrl: (scope, endpoint, id) => [...sheetsQueryKeys.scope(scope), "media-url", endpoint, id],
1107
1160
  typeFields: (scope, typeName) => [...sheetsQueryKeys.scope(scope), "type-fields", typeName],
1108
1161
  enumValues: (scope, typeName) => [...sheetsQueryKeys.scope(scope), "enum-values", typeName],
1109
1162
  relations: (scope, tableName) => [...sheetsQueryKeys.scope(scope), "relations", tableName],
@@ -1119,6 +1172,9 @@ var sheetsQueryKeys = {
1119
1172
 
1120
1173
  // src/context/sheets-provider.tsx
1121
1174
  var import_jsx_runtime = require("react/jsx-runtime");
1175
+ var unavailableUpload = async () => {
1176
+ throw new Error("Uploads need a storage endpoint");
1177
+ };
1122
1178
  function SheetsProvider({ config, children }) {
1123
1179
  const providerInstanceId = (0, import_react3.useId)();
1124
1180
  const storeRef = (0, import_react3.useRef)(null);
@@ -1177,10 +1233,13 @@ function SheetsProvider({ config, children }) {
1177
1233
  if (config.execute) return config.execute;
1178
1234
  return createSheetsExecute(config, getToken);
1179
1235
  }, [config, getToken]);
1236
+ const storage = (0, import_react3.useMemo)(() => resolveStorageTransport(config, getToken), [config, getToken]);
1237
+ const bucketKey = config.upload?.bucketKey;
1180
1238
  const executeUpload = (0, import_react3.useMemo)(() => {
1181
1239
  if (config.executeUpload) return config.executeUpload;
1182
- return createSheetsUpload(config, getToken);
1183
- }, [config, getToken]);
1240
+ return storage ? createPresignedSheetsUpload(storage, bucketKey) : unavailableUpload;
1241
+ }, [config.executeUpload, storage, bucketKey]);
1242
+ const canUpload = Boolean(config.executeUpload || storage);
1184
1243
  const configuredIdentityKey = config.auth.mode === "embedded" ? config.auth.getIdentityKey?.() ?? null : standaloneIdentityKey;
1185
1244
  const activeToken = config.auth.mode === "embedded" ? config.auth.getToken() : standaloneAccessToken;
1186
1245
  const authGenerationRef = (0, import_react3.useRef)({ mode: config.auth.mode, token: activeToken, generation: 0 });
@@ -1206,8 +1265,8 @@ function SheetsProvider({ config, children }) {
1206
1265
  };
1207
1266
  }, [queryClient, scopeKey]);
1208
1267
  const contextValue = (0, import_react3.useMemo)(
1209
- () => ({ config, execute, executeUpload, scopeKey }),
1210
- [config, execute, executeUpload, scopeKey]
1268
+ () => ({ config, execute, executeUpload, storage, canUpload, scopeKey }),
1269
+ [config, execute, executeUpload, storage, canUpload, scopeKey]
1211
1270
  );
1212
1271
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_query.QueryClientProvider, { client: queryClient, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SheetsStoreContext.Provider, { value: store, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SheetsContext.Provider, { value: contextValue, children }) }) });
1213
1272
  }
@@ -1420,7 +1479,19 @@ function createMockExecute(opts) {
1420
1479
  },
1421
1480
  at: Date.now()
1422
1481
  });
1423
- return { url: "mock://uploaded/" + name };
1482
+ const url = "mock://uploaded/" + name;
1483
+ return {
1484
+ file: {
1485
+ id: "mock-file-" + mutations.length,
1486
+ key: name,
1487
+ bucket_id: "mock-bucket",
1488
+ filename: name,
1489
+ mime: file.type || "application/octet-stream",
1490
+ size: file.size,
1491
+ url
1492
+ },
1493
+ url
1494
+ };
1424
1495
  };
1425
1496
  function reset() {
1426
1497
  mutations.length = 0;