@constructive-io/sheets 0.13.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.
Files changed (61) hide show
  1. package/README.md +231 -148
  2. package/dist/advanced.cjs +7220 -4030
  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 +5 -5
  7. package/dist/auth.cjs.map +1 -1
  8. package/dist/auth.js +3 -3
  9. package/dist/chunk-CJ4PRA64.js +312 -0
  10. package/dist/chunk-CJ4PRA64.js.map +1 -0
  11. package/dist/chunk-II3MSNRO.js +18 -0
  12. package/dist/chunk-II3MSNRO.js.map +1 -0
  13. package/dist/{chunk-MXVNIKES.js → chunk-J7KK4UWI.js} +6 -6
  14. package/dist/chunk-MBSHDF55.js +839 -0
  15. package/dist/chunk-MBSHDF55.js.map +1 -0
  16. package/dist/{chunk-ZKANUG3F.js → chunk-MOFFS5WQ.js} +20 -15
  17. package/dist/chunk-MOFFS5WQ.js.map +1 -0
  18. package/dist/chunk-VCBY2AMT.js +8920 -0
  19. package/dist/chunk-VCBY2AMT.js.map +1 -0
  20. package/dist/{chunk-H5HR5HUJ.js → chunk-ZOQDSOMO.js} +50 -312
  21. package/dist/chunk-ZOQDSOMO.js.map +1 -0
  22. package/dist/date-editor-ORCB43ZM.js +346 -0
  23. package/dist/date-editor-ORCB43ZM.js.map +1 -0
  24. package/dist/grid-cell-types-YNIVK4hN.d.cts +346 -0
  25. package/dist/grid-cell-types-YNIVK4hN.d.ts +346 -0
  26. package/dist/index.cjs +22910 -12084
  27. package/dist/index.cjs.map +1 -1
  28. package/dist/index.d.cts +1497 -337
  29. package/dist/index.d.ts +1497 -337
  30. package/dist/index.js +12833 -6142
  31. package/dist/index.js.map +1 -1
  32. package/dist/sheets-context-Bb7ZoNBg.d.cts +436 -0
  33. package/dist/sheets-context-CPuf31LS.d.ts +436 -0
  34. package/dist/testing.cjs +1253 -638
  35. package/dist/testing.cjs.map +1 -1
  36. package/dist/testing.d.cts +80 -11
  37. package/dist/testing.d.ts +80 -11
  38. package/dist/testing.js +791 -148
  39. package/dist/testing.js.map +1 -1
  40. package/package.json +5 -5
  41. package/dist/chunk-4EZ6A23C.js +0 -44
  42. package/dist/chunk-4EZ6A23C.js.map +0 -1
  43. package/dist/chunk-5QPNOKMA.js +0 -4397
  44. package/dist/chunk-5QPNOKMA.js.map +0 -1
  45. package/dist/chunk-AYMXT3ME.js +0 -540
  46. package/dist/chunk-AYMXT3ME.js.map +0 -1
  47. package/dist/chunk-H5HR5HUJ.js.map +0 -1
  48. package/dist/chunk-PZL2BCWF.js +0 -168
  49. package/dist/chunk-PZL2BCWF.js.map +0 -1
  50. package/dist/chunk-X7DHTSOX.js +0 -21
  51. package/dist/chunk-X7DHTSOX.js.map +0 -1
  52. package/dist/chunk-ZKANUG3F.js.map +0 -1
  53. package/dist/date-editor-ZFNDKYBD.js +0 -358
  54. package/dist/date-editor-ZFNDKYBD.js.map +0 -1
  55. package/dist/grid-cell-types-Pbe2m2tE.d.cts +0 -253
  56. package/dist/grid-cell-types-Pbe2m2tE.d.ts +0 -253
  57. package/dist/map-picker-ZUGGOIZS.js +0 -290
  58. package/dist/map-picker-ZUGGOIZS.js.map +0 -1
  59. package/dist/sheets-context-CY1RmDKL.d.cts +0 -244
  60. package/dist/sheets-context-Cu3Ec_ca.d.ts +0 -244
  61. /package/dist/{chunk-MXVNIKES.js.map → chunk-J7KK4UWI.js.map} +0 -0
package/dist/testing.cjs CHANGED
@@ -22,17 +22,19 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
22
22
  var testing_exports = {};
23
23
  __export(testing_exports, {
24
24
  MockSheetsProvider: () => MockSheetsProvider,
25
+ buildMetaSchemaSdl: () => buildMetaSchemaSdl,
25
26
  createMetaContractFixture: () => createMetaContractFixture,
26
27
  createMockExecute: () => createMockExecute,
28
+ createModelBackend: () => createModelBackend,
27
29
  usersFixture: () => usersFixture
28
30
  });
29
31
  module.exports = __toCommonJS(testing_exports);
30
32
 
31
33
  // src/testing/mock-sheets-provider.tsx
32
34
  var import_react4 = require("react");
33
- var import_graphql3 = require("graphql");
35
+ var import_graphql5 = require("graphql");
34
36
  var import_react_query2 = require("@tanstack/react-query");
35
- var import_data7 = require("@constructive-io/data");
37
+ var import_data8 = require("@constructive-io/data");
36
38
 
37
39
  // src/context/sheets-provider.tsx
38
40
  var import_react3 = require("react");
@@ -45,157 +47,154 @@ var SheetsContext = (0, import_react.createContext)(null);
45
47
 
46
48
  // src/context/sheets-execute.ts
47
49
  var import_graphql2 = require("graphql");
48
- var import_data2 = require("@constructive-io/data");
50
+ var import_data3 = require("@constructive-io/data");
49
51
 
50
52
  // src/context/sheets-upload-presigned.ts
53
+ var import_data2 = require("@constructive-io/data");
54
+
55
+ // src/context/sheets-upload-discovery.ts
51
56
  var import_graphql = require("graphql");
52
57
  var import_data = require("@constructive-io/data");
53
- async function sha256HexFromBuffer(buffer) {
54
- if (!globalThis.crypto?.subtle) {
55
- throw import_data.createError.badRequest("Web Crypto (crypto.subtle) is unavailable; cannot hash file for upload.");
58
+ var capabilityCache = /* @__PURE__ */ new WeakMap();
59
+ async function discoverStorageCapabilities(endpoint, execute) {
60
+ let endpoints = capabilityCache.get(execute);
61
+ if (!endpoints) {
62
+ endpoints = /* @__PURE__ */ new Map();
63
+ capabilityCache.set(execute, endpoints);
56
64
  }
57
- const digest = await crypto.subtle.digest("SHA-256", buffer);
58
- const bytes = new Uint8Array(digest);
59
- let hex = "";
60
- for (let i = 0; i < bytes.length; i++) {
61
- hex += bytes[i].toString(16).padStart(2, "0");
62
- }
63
- return hex;
64
- }
65
- var capabilityCache = /* @__PURE__ */ new Map();
66
- function discoverUploadCapability(endpoint, execute) {
67
- const cached = capabilityCache.get(endpoint);
65
+ const cached = endpoints.get(endpoint);
68
66
  if (cached) return cached;
69
67
  const promise = (async () => {
70
68
  const data = await execute((0, import_graphql.getIntrospectionQuery)());
71
69
  const schema = data?.__schema;
72
- if (!schema) {
73
- throw import_data.createError.badRequest("Uploads are not enabled for this endpoint.");
74
- }
75
- return resolveUploadCapability(schema);
70
+ if (!schema) throw import_data.createError.badRequest("Uploads are not enabled for this endpoint.");
71
+ return resolveStorageCapabilities(schema);
76
72
  })();
77
- promise.catch(() => capabilityCache.delete(endpoint));
78
- capabilityCache.set(endpoint, promise);
73
+ promise.catch(() => endpoints.delete(endpoint));
74
+ endpoints.set(endpoint, promise);
79
75
  return promise;
80
76
  }
77
+ async function discoverUploadCapability(endpoint, execute, uploadFieldName) {
78
+ const { upload, uploads } = await discoverStorageCapabilities(endpoint, execute);
79
+ if (uploadFieldName) {
80
+ const named = uploads.find((candidate) => candidate.uploadFieldName === uploadFieldName);
81
+ if (!named) throw import_data.createError.badRequest(`Uploads are not enabled for this endpoint: it has no ${uploadFieldName}.`);
82
+ return { ...named, download: null };
83
+ }
84
+ if (!upload) capabilityCache.get(execute)?.delete(endpoint);
85
+ return requireUploadCapability(upload);
86
+ }
87
+ function requireUploadCapability(upload) {
88
+ if (!upload) throw import_data.createError.badRequest("Uploads are not enabled for this endpoint.");
89
+ return upload;
90
+ }
81
91
  function namedTypeName(ref) {
82
92
  let cur = ref;
83
- while (cur && (cur.kind === "NON_NULL" || cur.kind === "LIST")) {
84
- cur = cur.ofType ?? null;
85
- }
93
+ while (cur && (cur.kind === "NON_NULL" || cur.kind === "LIST")) cur = cur.ofType ?? null;
86
94
  return cur?.name ?? null;
87
95
  }
88
96
  function isListTypeRef(ref) {
89
97
  let cur = ref;
90
- while (cur && cur.kind === "NON_NULL") {
91
- cur = cur.ofType ?? null;
92
- }
98
+ while (cur && cur.kind === "NON_NULL") cur = cur.ofType ?? null;
93
99
  return cur?.kind === "LIST";
94
100
  }
95
101
  var PK_FIELD_NAME = "id";
96
- function resolveUploadCapability(schema) {
102
+ function resolveStorageCapabilities(schema) {
97
103
  const typeByName = /* @__PURE__ */ new Map();
98
104
  for (const t of schema.types) {
99
105
  if (t.name) typeByName.set(t.name, t);
100
106
  }
101
107
  const objectHasFields = (typeName, names) => {
102
- if (!typeName) return false;
103
- const t = typeByName.get(typeName);
108
+ const t = typeName ? typeByName.get(typeName) : void 0;
104
109
  if (!t?.fields) return false;
105
110
  const present = new Set(t.fields.map((f) => f.name));
106
111
  return names.every((n) => present.has(n));
107
112
  };
108
113
  const inputHasFields = (typeName, names) => {
109
- if (!typeName) return false;
110
- const t = typeByName.get(typeName);
114
+ const t = typeName ? typeByName.get(typeName) : void 0;
111
115
  if (!t?.inputFields) return false;
112
116
  const present = new Set(t.inputFields.map((f) => f.name));
113
117
  return names.every((n) => present.has(n));
114
118
  };
115
- const PAYLOAD_FIELDS = ["uploadUrl", "fileId", "deduplicated"];
116
- const INPUT_FIELDS = ["contentHash", "bucketKey", "contentType", "size"];
119
+ const PAYLOAD_FIELDS = ["uploadUrl", "fileId", "key", "deduplicated"];
120
+ const INPUT_FIELDS = ["contentHash", "contentType", "size"];
121
+ const LEGACY_INPUT_FIELDS = [...INPUT_FIELDS, "bucketKey"];
117
122
  const mutationType = schema.mutationType ? typeByName.get(schema.mutationType.name) : null;
118
123
  const queryType = schema.queryType ? typeByName.get(schema.queryType.name) : null;
119
124
  let upload = null;
125
+ const uploads = [];
120
126
  for (const field of mutationType?.fields ?? []) {
121
127
  const inputArg = field.args.find((a) => a.name === "input");
122
128
  if (!inputArg) continue;
123
129
  const inputTypeName = namedTypeName(inputArg.type);
124
130
  const payloadTypeName = namedTypeName(field.type);
125
- if (inputHasFields(inputTypeName, INPUT_FIELDS) && objectHasFields(payloadTypeName, PAYLOAD_FIELDS)) {
126
- upload = { uploadFieldName: field.name, inputTypeName };
127
- break;
131
+ if (inputTypeName && inputHasFields(inputTypeName, INPUT_FIELDS) && objectHasFields(payloadTypeName, PAYLOAD_FIELDS)) {
132
+ const payloadFields = typeByName.get(payloadTypeName ?? "")?.fields ?? [];
133
+ const candidate = {
134
+ uploadFieldName: field.name,
135
+ inputTypeName,
136
+ hasFileProjection: payloadFields.some(
137
+ (f) => f.name === "file" && !isListTypeRef(f.type) && namedTypeName(f.type) === "JSON"
138
+ ),
139
+ payloadFieldNames: payloadFields.map((f) => f.name),
140
+ inputFieldNames: (typeByName.get(inputTypeName)?.inputFields ?? []).map((f) => f.name)
141
+ };
142
+ uploads.push(candidate);
143
+ if (!inputHasFields(inputTypeName, LEGACY_INPUT_FIELDS) || upload?.uploadFieldName === "uploadAppFile") continue;
144
+ if (field.name === "uploadAppFile") upload = candidate;
145
+ else upload ??= candidate;
128
146
  }
129
147
  }
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
- const uploadedTypeName = upload.uploadFieldName.replace(/^upload/, "");
135
- const fileTypeName = typeByName.has(uploadedTypeName) ? uploadedTypeName : downloadById.fileTypeName;
136
- let remove = {};
137
- for (const field of mutationType?.fields ?? []) {
138
- const inputArg = field.args.find((a) => a.name === "input");
139
- const inputTypeName = namedTypeName(inputArg?.type);
140
- const inputFields = inputTypeName ? typeByName.get(inputTypeName)?.inputFields : null;
141
- if (!inputTypeName || !inputFields?.some((f) => f.name === PK_FIELD_NAME)) continue;
142
- if (!inputFields.every((f) => f.name === PK_FIELD_NAME || f.name === "clientMutationId")) continue;
143
- const payload = typeByName.get(namedTypeName(field.type) ?? "");
144
- if (payload?.fields?.some((f) => namedTypeName(f.type) === fileTypeName)) {
145
- remove = { deleteFieldName: field.name, deleteInputTypeName: inputTypeName };
146
- break;
147
- }
148
+ const fileTypes = /* @__PURE__ */ new Set();
149
+ for (const t of schema.types) {
150
+ if (t.kind === "OBJECT" && t.name && t.fields?.some((f) => f.name === "downloadUrl")) fileTypes.add(t.name);
148
151
  }
152
+ const uploadType = upload?.uploadFieldName.replace(/^upload/, "") ?? "AppFile";
153
+ const uploadDownload = resolveDownloadByIdField(typeByName, queryType, fileTypes, uploadType);
154
+ const preferredPreviewType = fileTypes.has("AppFile") ? "AppFile" : uploadType;
155
+ const previewType = fileTypes.has(preferredPreviewType) ? preferredPreviewType : uploadDownload?.fileTypeName ?? preferredPreviewType;
156
+ const download = previewType === uploadType ? uploadDownload : resolveDownloadByIdField(typeByName, queryType, fileTypes, previewType);
157
+ const batch = resolveConnectionDownloadField(typeByName, queryType, fileTypes, previewType, true);
158
+ const only = uploads.length === 1 ? uploads[0] : null;
159
+ const sole = only ? {
160
+ ...only,
161
+ download: only === upload ? uploadDownload : resolveDownloadByIdField(typeByName, queryType, fileTypes, only.uploadFieldName.replace(/^upload/, ""))
162
+ } : null;
149
163
  return {
150
- ...upload,
151
- ...downloadById,
152
- ...remove
164
+ upload: upload ? { ...upload, download: uploadDownload } : null,
165
+ uploads,
166
+ sole,
167
+ download,
168
+ batch
153
169
  };
154
170
  }
155
- async function deleteUploadedFileRow(execute, cap, fileId) {
156
- if (!cap.deleteFieldName || !cap.deleteInputTypeName) return;
157
- const mutation = `
158
- mutation SheetsUploadCleanup($input: ${cap.deleteInputTypeName}!) {
159
- ${cap.deleteFieldName}(input: $input) { __typename }
160
- }
161
- `.trim();
162
- try {
163
- await execute(mutation, { input: { [PK_FIELD_NAME]: fileId } });
164
- } catch {
165
- }
166
- }
167
- function resolveDownloadByIdField(schema, typeByName, queryType, uploadFieldName) {
168
- const fileTypesWithDownloadUrl = /* @__PURE__ */ new Set();
169
- for (const t of schema.types) {
170
- if (t.kind === "OBJECT" && t.name && t.fields?.some((f) => f.name === "downloadUrl")) {
171
- fileTypesWithDownloadUrl.add(t.name);
172
- }
173
- }
171
+ function resolveDownloadByIdField(typeByName, queryType, fileTypesWithDownloadUrl, preferred) {
172
+ let singular = null;
174
173
  for (const field of queryType?.fields ?? []) {
175
174
  const returnTypeName = namedTypeName(field.type);
176
175
  if (!returnTypeName || !fileTypesWithDownloadUrl.has(returnTypeName)) continue;
177
176
  if (field.args.length === 1 && field.args[0].name === PK_FIELD_NAME) {
178
- return {
177
+ const candidate = {
179
178
  fileByIdField: field.name,
180
179
  fileByIdArgName: "id",
181
180
  fileTypeName: returnTypeName,
182
181
  idScalarName: namedTypeName(field.args[0].type) ?? void 0
183
182
  };
183
+ if (returnTypeName === preferred) return candidate;
184
+ singular ??= candidate;
184
185
  }
185
186
  }
186
- const connection = resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, uploadFieldName);
187
- if (connection) return connection;
188
- const nodeField = queryType?.fields?.find(
189
- (f) => f.name === "node" && f.args.some((a) => a.name === "nodeId")
190
- );
187
+ const connection = resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, preferred);
188
+ if (connection?.fileTypeName === preferred) return connection;
189
+ if (singular || connection) return singular ?? connection;
190
+ const nodeField = queryType?.fields?.find((f) => f.name === "node" && f.args.some((a) => a.name === "nodeId"));
191
191
  if (nodeField && fileTypesWithDownloadUrl.size > 0) {
192
- const preferred = uploadFieldName.replace(/^upload/, "");
193
192
  const fileTypeName = fileTypesWithDownloadUrl.has(preferred) ? preferred : [...fileTypesWithDownloadUrl][0];
194
193
  return { fileByIdField: "node", fileByIdArgName: "nodeId", fileTypeName };
195
194
  }
196
- throw import_data.createError.badRequest("Uploads are not enabled for this endpoint.");
195
+ return null;
197
196
  }
198
- function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, uploadFieldName) {
197
+ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, preferred, batch = false) {
199
198
  const EQUALITY_OPERATORS = ["equalTo", "eq"];
200
199
  const candidates = [];
201
200
  for (const field of queryType?.fields ?? []) {
@@ -210,6 +209,8 @@ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDown
210
209
  });
211
210
  if (!nodesField) continue;
212
211
  const fileTypeName = namedTypeName(nodesField.type);
212
+ if (batch && (fileTypeName !== preferred || !typeByName.get(fileTypeName)?.fields?.some((candidate) => candidate.name === PK_FIELD_NAME))) continue;
213
+ const connectionHasFirst = field.args.some((arg) => arg.name === "first");
213
214
  for (const arg of field.args) {
214
215
  const filterTypeName = namedTypeName(arg.type);
215
216
  const filterType = filterTypeName ? typeByName.get(filterTypeName) : null;
@@ -219,9 +220,8 @@ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDown
219
220
  const idFieldTypeName = namedTypeName(idField.type);
220
221
  const idFieldType = idFieldTypeName ? typeByName.get(idFieldTypeName) : null;
221
222
  if (idFieldType?.kind === "INPUT_OBJECT" && idFieldType.inputFields) {
222
- const opField = EQUALITY_OPERATORS.map(
223
- (op) => idFieldType.inputFields.find((f) => f.name === op)
224
- ).find((f) => f != null);
223
+ const inputFields = idFieldType.inputFields;
224
+ const opField = batch ? inputFields.find((f) => f.name === "in" && isListTypeRef(f.type)) : EQUALITY_OPERATORS.map((op) => inputFields.find((f) => f.name === op)).find((f) => f != null);
225
225
  if (opField) {
226
226
  candidates.push({
227
227
  fileByIdField: field.name,
@@ -231,13 +231,14 @@ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDown
231
231
  connectionFilterArgName: arg.name,
232
232
  connectionIdField: idField.name,
233
233
  connectionIdOperator: opField.name,
234
- connectionNodesField: nodesField.name
234
+ connectionNodesField: nodesField.name,
235
+ connectionHasFirst
235
236
  });
236
237
  break;
237
238
  }
238
239
  continue;
239
240
  }
240
- if (idFieldType?.kind === "SCALAR" || !idFieldType && idFieldTypeName) {
241
+ if (!batch && (idFieldType?.kind === "SCALAR" || !idFieldType && idFieldTypeName)) {
241
242
  candidates.push({
242
243
  fileByIdField: field.name,
243
244
  fileByIdArgName: "connection",
@@ -245,93 +246,80 @@ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDown
245
246
  idScalarName: idFieldTypeName ?? void 0,
246
247
  connectionFilterArgName: arg.name,
247
248
  connectionIdField: idField.name,
248
- connectionNodesField: nodesField.name
249
+ connectionNodesField: nodesField.name,
250
+ connectionHasFirst
249
251
  });
250
252
  break;
251
253
  }
252
254
  }
253
255
  }
254
256
  if (candidates.length === 0) return null;
255
- const preferred = uploadFieldName.replace(/^upload/, "");
256
257
  return candidates.find((c) => c.fileTypeName === preferred) ?? candidates[0];
257
258
  }
258
- async function callUploadOp(execute, cap, input) {
259
- const mutation = `
259
+ function uploadInputOf(cap, input) {
260
+ const inputFields = new Set(cap.inputFieldNames ?? []);
261
+ const has = (name) => inputFields.size === 0 || inputFields.has(name);
262
+ const bucket = input.bucketKey !== void 0 ? has("bucketKey") ? { bucketKey: input.bucketKey } : {} : has("isPublic") ? { isPublic: input.isPublic ?? true } : {};
263
+ return {
264
+ ...bucket,
265
+ ...input.databaseId !== void 0 && inputFields.has("databaseId") ? { databaseId: input.databaseId } : {},
266
+ contentHash: input.contentHash,
267
+ contentType: input.contentType,
268
+ size: input.size,
269
+ ...has("filename") ? { filename: input.filename } : {}
270
+ };
271
+ }
272
+ function uploadMutation(cap, payloadFields) {
273
+ return `
260
274
  mutation SheetsUpload($input: ${cap.inputTypeName}!) {
261
275
  ${cap.uploadFieldName}(input: $input) {
262
- uploadUrl
263
- fileId
264
- key
265
- deduplicated
276
+ ${payloadFields.join("\n ")}
266
277
  }
267
278
  }
268
279
  `.trim();
269
- const data = await execute(mutation, {
270
- input: {
271
- bucketKey: input.bucketKey,
272
- contentHash: input.contentHash,
273
- contentType: input.contentType,
274
- size: input.size,
275
- filename: input.filename
276
- }
277
- });
278
- const payload = data?.[cap.uploadFieldName];
279
- if (!payload) {
280
- throw import_data.createError.badRequest("Upload failed: no payload returned from upload mutation.");
281
- }
282
- return payload;
283
280
  }
284
- 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.";
285
- function storageUnreachableError() {
286
- return import_data.createError.graphql(STORAGE_UPLOAD_BLOCKED_MESSAGE, "STORAGE_UPLOAD_BLOCKED");
281
+ var LEGACY_PAYLOAD_FIELDS = ["uploadUrl", "fileId", "key", "deduplicated", "file"];
282
+ async function requestDiscoveredUpload(execute, cap, input, signal) {
283
+ const payloadFields = cap.payloadFieldNames?.length ? UPLOAD_PAYLOAD_FIELDS.filter((name) => cap.payloadFieldNames.includes(name)) : LEGACY_PAYLOAD_FIELDS;
284
+ const data = await execute(uploadMutation(cap, payloadFields), { input: uploadInputOf(cap, input) }, { signal });
285
+ return readUploadPayload(data?.[cap.uploadFieldName]);
287
286
  }
288
- async function presignedPut(url, buffer, contentType, onProgress) {
289
- const total = buffer.byteLength;
290
- if (onProgress && typeof XMLHttpRequest !== "undefined") {
291
- await putWithXHR(url, buffer, contentType, total, onProgress);
292
- return;
293
- }
294
- let response;
295
- try {
296
- response = await fetch(url, {
297
- method: "PUT",
298
- headers: { "Content-Type": contentType },
299
- body: buffer
300
- });
301
- } catch {
302
- throw storageUnreachableError();
303
- }
304
- if (!response.ok) {
305
- const body = await response.text().catch(() => "");
306
- throw import_data.createError.badRequest(`Upload failed: ${response.status} ${response.statusText}${body ? ` \u2014 ${body}` : ""}`);
307
- }
308
- onProgress?.({ loaded: total, total, percentage: 100 });
287
+ function projectionToFileValue(file, fallbackName, fallbackMime) {
288
+ return {
289
+ ...file,
290
+ bucket_id: typeof file.bucket_id === "string" ? file.bucket_id : "",
291
+ mime: typeof file.mime === "string" ? file.mime : fallbackMime,
292
+ size: typeof file.size === "number" ? file.size : 0,
293
+ filename: typeof file.filename === "string" ? file.filename : fallbackName
294
+ };
309
295
  }
310
- function putWithXHR(url, buffer, contentType, total, onProgress) {
311
- return new Promise((resolve, reject) => {
312
- const xhr = new XMLHttpRequest();
313
- xhr.open("PUT", url);
314
- xhr.setRequestHeader("Content-Type", contentType);
315
- xhr.upload.addEventListener("progress", (event) => {
316
- if (event.lengthComputable) {
317
- onProgress({
318
- loaded: event.loaded,
319
- total: event.total,
320
- percentage: Math.round(event.loaded / event.total * 100)
321
- });
322
- }
323
- });
324
- xhr.addEventListener("load", () => {
325
- if (xhr.status >= 200 && xhr.status < 300) {
326
- onProgress({ loaded: total, total, percentage: 100 });
327
- resolve();
328
- } else {
329
- reject(import_data.createError.badRequest(`Upload failed: ${xhr.status} ${xhr.statusText}${xhr.responseText ? ` \u2014 ${xhr.responseText}` : ""}`));
330
- }
331
- });
332
- xhr.addEventListener("error", () => reject(storageUnreachableError()));
333
- xhr.send(buffer);
334
- });
296
+ function createPresignedSheetsUpload({ endpoint, execute }, bucketKey) {
297
+ return async (file, _path, options) => {
298
+ if (!endpoint) throw import_data.createError.badRequest("No GraphQL endpoint configured.");
299
+ const cap = await discoverUploadCapability(endpoint, execute);
300
+ if (!cap.hasFileProjection) {
301
+ throw import_data.createError.badRequest("Uploads require a storage mutation that returns a file projection.");
302
+ }
303
+ let payload;
304
+ try {
305
+ payload = await transferFile(
306
+ file,
307
+ (input) => requestDiscoveredUpload(execute, cap, { ...input, bucketKey }),
308
+ { onProgress: options?.onProgress }
309
+ );
310
+ } catch (error) {
311
+ throw withUnfinishedUpload(error, { filesType: cap.download?.fileTypeName ?? null });
312
+ }
313
+ const result = {
314
+ file: projectionToFileValue(payload.file, file.name, file.type || "application/octet-stream")
315
+ };
316
+ if (!cap.download) return result;
317
+ try {
318
+ return { ...result, url: await fetchDownloadUrl(execute, cap.download, payload.fileId) };
319
+ } catch {
320
+ return result;
321
+ }
322
+ };
335
323
  }
336
324
  function toGlobalId(typeName, id) {
337
325
  if (typeof btoa !== "function") {
@@ -340,6 +328,7 @@ function toGlobalId(typeName, id) {
340
328
  return btoa(JSON.stringify([typeName, id]));
341
329
  }
342
330
  async function fetchDownloadUrl(execute, cap, fileId) {
331
+ const missing = () => import_data.createError.badRequest("Upload succeeded but no downloadUrl was returned for the file.");
343
332
  if (cap.fileByIdArgName === "nodeId") {
344
333
  const nodeId = toGlobalId(cap.fileTypeName, fileId);
345
334
  const query2 = `
@@ -352,11 +341,8 @@ async function fetchDownloadUrl(execute, cap, fileId) {
352
341
  }
353
342
  `.trim();
354
343
  const data2 = await execute(query2, { nodeId });
355
- const node = data2?.[cap.fileByIdField];
356
- const url2 = node?.downloadUrl;
357
- if (!url2) {
358
- throw import_data.createError.badRequest("Upload succeeded but no downloadUrl was returned for the file.");
359
- }
344
+ const url2 = data2?.[cap.fileByIdField]?.downloadUrl;
345
+ if (!url2) throw missing();
360
346
  return url2;
361
347
  }
362
348
  if (cap.fileByIdArgName === "connection") {
@@ -367,7 +353,7 @@ async function fetchDownloadUrl(execute, cap, fileId) {
367
353
  const filterLiteral = cap.connectionIdOperator ? `{ ${idField}: { ${cap.connectionIdOperator}: $id } }` : `{ ${idField}: $id }`;
368
354
  const query2 = `
369
355
  query SheetsDownloadUrl($id: ${idScalar2}!) {
370
- ${cap.fileByIdField}(${filterArg}: ${filterLiteral}, first: 1) {
356
+ ${cap.fileByIdField}(${filterArg}: ${filterLiteral}${cap.connectionHasFirst ? ", first: 1" : ""}) {
371
357
  ${nodesField} {
372
358
  downloadUrl
373
359
  }
@@ -378,11 +364,8 @@ async function fetchDownloadUrl(execute, cap, fileId) {
378
364
  query2,
379
365
  { id: fileId }
380
366
  );
381
- const conn = data2?.[cap.fileByIdField];
382
- const url2 = conn?.[nodesField]?.[0]?.downloadUrl;
383
- if (!url2) {
384
- throw import_data.createError.badRequest("Upload succeeded but no downloadUrl was returned for the file.");
385
- }
367
+ const url2 = data2?.[cap.fileByIdField]?.[nodesField]?.[0]?.downloadUrl;
368
+ if (!url2) throw missing();
386
369
  return url2;
387
370
  }
388
371
  const idScalar = cap.idScalarName ?? "ID";
@@ -395,16 +378,258 @@ async function fetchDownloadUrl(execute, cap, fileId) {
395
378
  }
396
379
  `.trim();
397
380
  const data = await execute(query, { id: fileId });
398
- const file = data?.[cap.fileByIdField];
399
- const url = file?.downloadUrl;
400
- if (!url) {
401
- throw import_data.createError.badRequest("Upload succeeded but no downloadUrl was returned for the file.");
402
- }
381
+ const url = data?.[cap.fileByIdField]?.downloadUrl;
382
+ if (!url) throw missing();
403
383
  return url;
404
384
  }
405
385
 
386
+ // src/context/sheets-upload-presigned.ts
387
+ var UPLOAD_PAYLOAD_FIELDS = ["uploadUrl", "uploadHeaders", "fileId", "key", "deduplicated", "expiresAt", "file"];
388
+ function headersOf(value) {
389
+ let parsed = value;
390
+ if (typeof parsed === "string") {
391
+ try {
392
+ parsed = JSON.parse(parsed);
393
+ } catch {
394
+ return null;
395
+ }
396
+ }
397
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
398
+ const entries = Object.entries(parsed);
399
+ if (!entries.every(([, header]) => typeof header === "string")) return null;
400
+ return Object.fromEntries(entries);
401
+ }
402
+ function projectionOf(value) {
403
+ let parsed = value;
404
+ if (typeof parsed === "string") {
405
+ try {
406
+ parsed = JSON.parse(parsed);
407
+ } catch {
408
+ return null;
409
+ }
410
+ }
411
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null;
412
+ const projection = parsed;
413
+ return isFileProjection(projection) ? projection : null;
414
+ }
415
+ function isFileProjection(value) {
416
+ return typeof value.id === "string" && typeof value.key === "string";
417
+ }
418
+ var UNFINISHED_UPLOAD = "unfinishedUpload";
419
+ function unfinishedUploadOf(error) {
420
+ const value = error && typeof error === "object" ? error[UNFINISHED_UPLOAD] : null;
421
+ return value && typeof value === "object" ? value : null;
422
+ }
423
+ function withUnfinishedUpload(error, upload) {
424
+ if (!error || typeof error !== "object") return error;
425
+ const recorded = unfinishedUploadOf(error);
426
+ const fileId = recorded?.fileId ?? upload.fileId;
427
+ if (!fileId) return error;
428
+ const value = {
429
+ fileId,
430
+ filesType: recorded?.filesType ?? upload.filesType ?? null,
431
+ filesTableKey: recorded?.filesTableKey ?? upload.filesTableKey ?? null
432
+ };
433
+ Object.defineProperty(error, UNFINISHED_UPLOAD, { value, enumerable: false, configurable: true, writable: true });
434
+ return error;
435
+ }
436
+ function readUploadPayload(raw) {
437
+ if (!raw || typeof raw !== "object") {
438
+ throw import_data2.createError.badRequest("Upload failed: the storage service returned no answer.");
439
+ }
440
+ const payload = raw;
441
+ const file = projectionOf(payload.file);
442
+ if (!file) {
443
+ throw import_data2.createError.badRequest("Upload failed: the server returned an invalid file projection.");
444
+ }
445
+ const deduplicated = payload.deduplicated === true;
446
+ const uploadUrl = typeof payload.uploadUrl === "string" && payload.uploadUrl ? payload.uploadUrl : null;
447
+ if (!deduplicated && !uploadUrl) {
448
+ throw withUnfinishedUpload(import_data2.createError.badRequest("Upload failed: the server returned no uploadUrl for a new file."), {
449
+ fileId: typeof payload.fileId === "string" ? payload.fileId : file.id
450
+ });
451
+ }
452
+ return {
453
+ uploadUrl,
454
+ uploadHeaders: headersOf(payload.uploadHeaders),
455
+ fileId: typeof payload.fileId === "string" ? payload.fileId : file.id,
456
+ key: typeof payload.key === "string" ? payload.key : file.key,
457
+ deduplicated,
458
+ expiresAt: typeof payload.expiresAt === "string" ? payload.expiresAt : null,
459
+ file
460
+ };
461
+ }
462
+ var MAX_HASHED_FILE_BYTES = 512 * 1024 * 1024;
463
+ function hex(digest) {
464
+ const bytes = new Uint8Array(digest);
465
+ let out = "";
466
+ for (let i = 0; i < bytes.length; i++) out += bytes[i].toString(16).padStart(2, "0");
467
+ return out;
468
+ }
469
+ function requireSubtle() {
470
+ if (!globalThis.crypto?.subtle) {
471
+ throw import_data2.createError.badRequest("This browser cannot hash files (Web Crypto is unavailable), so it cannot upload them.");
472
+ }
473
+ return globalThis.crypto.subtle;
474
+ }
475
+ function readBytes(file) {
476
+ if (typeof file.arrayBuffer === "function") return file.arrayBuffer();
477
+ return new Promise((resolve, reject) => {
478
+ const reader = new FileReader();
479
+ reader.onload = () => resolve(reader.result);
480
+ reader.onerror = () => reject(reader.error ?? new Error("The file could not be read."));
481
+ reader.readAsArrayBuffer(file);
482
+ });
483
+ }
484
+ async function sha256HexOfFile(file) {
485
+ if (file.size > MAX_HASHED_FILE_BYTES) {
486
+ throw import_data2.createError.badRequest(
487
+ `This file is too large to upload from the browser (the limit is ${MAX_HASHED_FILE_BYTES / (1024 * 1024)} MB).`
488
+ );
489
+ }
490
+ const subtle = requireSubtle();
491
+ return hex(await subtle.digest("SHA-256", await readBytes(file)));
492
+ }
493
+ var CHECKSUM_SHA256_HEADER = "x-amz-checksum-sha256";
494
+ var UPLOAD_ID_HEADER = "x-amz-meta-upload-id";
495
+ function sha256HexToBase64(contentHash) {
496
+ const pairs = contentHash.match(/.{2}/g) ?? [];
497
+ let binary = "";
498
+ for (const pair of pairs) binary += String.fromCharCode(parseInt(pair, 16));
499
+ return btoa(binary);
500
+ }
501
+ function fallbackPutHeaders(contentType, contentHash, uploadId) {
502
+ return {
503
+ "Content-Type": contentType,
504
+ ...contentHash ? { [CHECKSUM_SHA256_HEADER]: sha256HexToBase64(contentHash) } : {},
505
+ ...uploadId ? { [UPLOAD_ID_HEADER]: uploadId } : {}
506
+ };
507
+ }
508
+ var STORAGE_UPLOAD_BLOCKED_MESSAGE = "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.";
509
+ var PUT_RESPONSE = "putResponse";
510
+ function putRejected(status, statusText, body) {
511
+ const error = import_data2.createError.badRequest(`Upload failed: ${status} ${statusText}${body ? ` \u2014 ${body}` : ""}`);
512
+ Object.defineProperty(error, PUT_RESPONSE, { value: { status, body }, enumerable: false });
513
+ return error;
514
+ }
515
+ function putResponseOf(error) {
516
+ const response = error && typeof error === "object" ? error[PUT_RESPONSE] : null;
517
+ return response && typeof response === "object" ? response : null;
518
+ }
519
+ function abortError() {
520
+ return typeof DOMException === "function" ? new DOMException("The upload was cancelled.", "AbortError") : Object.assign(new Error("The upload was cancelled."), { name: "AbortError" });
521
+ }
522
+ function isAbortError(error) {
523
+ return Boolean(error && typeof error === "object" && error.name === "AbortError");
524
+ }
525
+ function blockedError() {
526
+ return import_data2.createError.graphql(STORAGE_UPLOAD_BLOCKED_MESSAGE, "STORAGE_UPLOAD_BLOCKED");
527
+ }
528
+ function putWithXhr(url, body, options, total) {
529
+ return new Promise((resolve, reject) => {
530
+ const xhr = new XMLHttpRequest();
531
+ const onAbort = () => xhr.abort();
532
+ const done = () => options.signal?.removeEventListener("abort", onAbort);
533
+ xhr.open("PUT", url);
534
+ for (const [name, value] of Object.entries(options.headers)) xhr.setRequestHeader(name, value);
535
+ xhr.upload.addEventListener("progress", (event) => {
536
+ if (!event.lengthComputable || event.total === 0) return;
537
+ options.onProgress?.({ loaded: event.loaded, total: event.total, percentage: Math.round(event.loaded / event.total * 100) });
538
+ });
539
+ xhr.addEventListener("load", () => {
540
+ done();
541
+ if (xhr.status >= 200 && xhr.status < 300) {
542
+ options.onProgress?.({ loaded: total, total, percentage: 100 });
543
+ resolve();
544
+ } else {
545
+ reject(putRejected(xhr.status, xhr.statusText, xhr.responseText ?? ""));
546
+ }
547
+ });
548
+ xhr.addEventListener("error", () => {
549
+ done();
550
+ reject(blockedError());
551
+ });
552
+ xhr.addEventListener("abort", () => {
553
+ done();
554
+ reject(abortError());
555
+ });
556
+ options.signal?.addEventListener("abort", onAbort, { once: true });
557
+ xhr.send(body);
558
+ });
559
+ }
560
+ async function putFile(url, body, options) {
561
+ if (options.signal?.aborted) throw abortError();
562
+ const total = body instanceof ArrayBuffer ? body.byteLength : body.size;
563
+ if (options.onProgress && typeof XMLHttpRequest !== "undefined") {
564
+ await putWithXhr(url, body, options, total);
565
+ return;
566
+ }
567
+ let response;
568
+ try {
569
+ response = await fetch(url, {
570
+ method: "PUT",
571
+ headers: options.headers,
572
+ body,
573
+ ...options.signal ? { signal: options.signal } : {}
574
+ });
575
+ } catch (error) {
576
+ if (isAbortError(error)) throw abortError();
577
+ throw blockedError();
578
+ }
579
+ if (!response.ok) {
580
+ throw putRejected(response.status, response.statusText, await response.text().catch(() => ""));
581
+ }
582
+ options.onProgress?.({ loaded: total, total, percentage: 100 });
583
+ }
584
+ function isExpired(payload, now = Date.now()) {
585
+ if (!payload.expiresAt) return false;
586
+ const expiry = Date.parse(payload.expiresAt);
587
+ return Number.isFinite(expiry) && expiry <= now;
588
+ }
589
+ function looksExpired(error, payload) {
590
+ const response = putResponseOf(error);
591
+ if (response?.status !== 403) return false;
592
+ return isExpired(payload) || /expired/i.test(response.body);
593
+ }
594
+ async function transferFile(file, request, options = {}) {
595
+ const contentType = file.type || "application/octet-stream";
596
+ const contentHash = await sha256HexOfFile(file);
597
+ if (options.signal?.aborted) throw abortError();
598
+ const input = { contentHash, contentType, size: file.size, filename: file.name };
599
+ let payload = await request(input, options.signal);
600
+ const putOrRenew = async () => {
601
+ for (let renewals = 0; ; renewals += 1) {
602
+ if (payload.deduplicated) {
603
+ options.onProgress?.({ loaded: file.size, total: file.size, percentage: 100 });
604
+ return payload;
605
+ }
606
+ if (options.signal?.aborted) throw abortError();
607
+ if (isExpired(payload) && renewals === 0) {
608
+ payload = await request(input, options.signal);
609
+ continue;
610
+ }
611
+ try {
612
+ await putFile(payload.uploadUrl, file, {
613
+ headers: payload.uploadHeaders ?? fallbackPutHeaders(contentType, contentHash, payload.fileId),
614
+ onProgress: options.onProgress,
615
+ signal: options.signal
616
+ });
617
+ return payload;
618
+ } catch (error) {
619
+ if (renewals > 0 || !looksExpired(error, payload)) throw error;
620
+ payload = await request(input, options.signal);
621
+ }
622
+ }
623
+ };
624
+ try {
625
+ return await putOrRenew();
626
+ } catch (error) {
627
+ throw withUnfinishedUpload(error, { fileId: payload.fileId });
628
+ }
629
+ }
630
+
406
631
  // src/context/sheets-execute.ts
407
- var import_data3 = require("@constructive-io/data");
632
+ var import_data4 = require("@constructive-io/data");
408
633
  function documentToString(document) {
409
634
  if (typeof document === "string") return document;
410
635
  if (document instanceof String) return document.toString();
@@ -412,33 +637,43 @@ function documentToString(document) {
412
637
  return (0, import_graphql2.print)(document);
413
638
  }
414
639
  if (document === null || document === void 0) {
415
- throw import_data2.createError.badRequest("Invalid GraphQL document: null or undefined");
640
+ throw import_data3.createError.badRequest("Invalid GraphQL document: null or undefined");
416
641
  }
417
642
  return String(document);
418
643
  }
419
- function hasAuthMessage(message) {
420
- const normalized = String(message ?? "").toLowerCase();
421
- return normalized.includes("unauthenticated") || normalized.includes("unauthorized") || normalized.includes("authentication");
644
+ var PARTIAL_RESULT = "partialResult";
645
+ var RESPONSE_ERRORS = "responseErrors";
646
+ function withResponseErrors(error, data, errors) {
647
+ Object.defineProperty(error, RESPONSE_ERRORS, { value: errors, enumerable: false, configurable: true });
648
+ if (data != null) {
649
+ Object.defineProperty(error, PARTIAL_RESULT, {
650
+ value: { data, errors },
651
+ enumerable: false,
652
+ configurable: true
653
+ });
654
+ }
655
+ return error;
422
656
  }
423
657
  function parseGraphQLResponse(response, onAuthError) {
424
658
  if (!response.errors?.length) return null;
659
+ if (response.errors.some((candidate) => (0, import_data3.isAuthenticationCode)(candidate.extensions?.code))) {
660
+ onAuthError?.();
661
+ return import_data3.createError.unauthorized("Authentication required. Please log in again.");
662
+ }
425
663
  const error = response.errors[0];
426
664
  const code = error.extensions?.code;
427
665
  const message = error.message || "GraphQL query failed";
428
- if (code === "UNAUTHENTICATED" || hasAuthMessage(message)) {
429
- onAuthError?.();
430
- return import_data2.createError.unauthorized("Authentication required. Please log in again.");
431
- }
666
+ if (code === "ACCESS_SUSPENDED") return (0, import_data3.parseGraphQLError)(error);
432
667
  if (code === "FORBIDDEN") {
433
- return import_data2.createError.forbidden("You do not have permission to perform this action.");
668
+ return import_data3.createError.forbidden("You do not have permission to perform this action.");
434
669
  }
435
- return import_data2.createError.graphql(message, code);
670
+ return import_data3.createError.graphql(message, code);
436
671
  }
437
672
  function createSheetsExecute(config, getToken) {
438
- return async (document, variables) => {
673
+ return async (document, variables, options) => {
439
674
  const url = config.endpoint;
440
675
  if (!url) {
441
- throw import_data2.createError.badRequest("No GraphQL endpoint configured.");
676
+ throw import_data3.createError.badRequest("No GraphQL endpoint configured.");
442
677
  }
443
678
  const token = getToken();
444
679
  const headers = {
@@ -456,81 +691,56 @@ function createSheetsExecute(config, getToken) {
456
691
  body: JSON.stringify({
457
692
  query: documentToString(document),
458
693
  ...variables !== void 0 && { variables }
459
- })
694
+ }),
695
+ ...options?.signal ? { signal: options.signal } : {}
460
696
  });
461
697
  } catch (error) {
462
- throw import_data2.createError.network(error instanceof Error ? error : void 0);
698
+ throw import_data3.createError.network(error instanceof Error ? error : void 0);
463
699
  }
464
700
  if (!response.ok) {
465
701
  const { status, statusText } = response;
466
702
  if (status === 401) {
467
703
  config.onAuthError?.();
468
- throw import_data2.createError.unauthorized("Authentication required. Please log in again.");
704
+ throw import_data3.createError.unauthorized("Authentication required. Please log in again.");
469
705
  }
470
706
  if (status === 403) {
471
- throw import_data2.createError.forbidden("You do not have permission to perform this action.");
707
+ const body = await response.json().catch(() => null);
708
+ const refusal = body?.errors?.[0];
709
+ const forbidden = refusal?.extensions?.code === "ACCESS_SUSPENDED" ? (0, import_data3.parseGraphQLError)(refusal) : import_data3.createError.forbidden("You do not have permission to perform this action.");
710
+ throw body?.errors?.length ? withResponseErrors(forbidden, null, body.errors) : forbidden;
472
711
  }
473
712
  if (status === 404) {
474
- throw import_data2.createError.notFound("The requested endpoint does not exist.");
713
+ throw import_data3.createError.notFound("The requested endpoint does not exist.");
475
714
  }
476
715
  try {
477
716
  const body = await response.json();
478
717
  if (body.errors?.length) {
479
- throw import_data2.createError.graphql(body.errors[0].message || `Request failed: ${status}`, body.errors[0].extensions?.code);
718
+ throw withResponseErrors(
719
+ import_data3.createError.graphql(body.errors[0].message || `Request failed: ${status}`, body.errors[0].extensions?.code),
720
+ null,
721
+ body.errors
722
+ );
480
723
  }
481
724
  } catch (e) {
482
- if (e instanceof import_data2.ConstructiveError) throw e;
725
+ if (e instanceof import_data3.ConstructiveError) throw e;
483
726
  }
484
- throw import_data2.createError.badRequest(`Request failed: ${status} ${statusText}`);
727
+ throw import_data3.createError.badRequest(`Request failed: ${status} ${statusText}`);
485
728
  }
486
729
  const result = await response.json();
487
730
  const graphqlError = parseGraphQLResponse(result, config.onAuthError);
488
731
  if (graphqlError) {
489
- throw graphqlError;
732
+ const keepsData = !["UNAUTHENTICATED", "ACCESS_SUSPENDED"].includes(graphqlError.code);
733
+ throw withResponseErrors(graphqlError, keepsData ? result.data : null, result.errors ?? []);
490
734
  }
491
735
  return result.data;
492
736
  };
493
737
  }
494
- function createSheetsUpload(config, getToken) {
495
- const execute = config.execute ?? createSheetsExecute(config, getToken);
496
- return async (file, _path, options) => {
497
- if (!config.endpoint) {
498
- throw import_data2.createError.badRequest("No GraphQL endpoint configured.");
499
- }
500
- const bucketKey = config.upload?.bucketKey ?? "public";
501
- const contentType = file.type || "application/octet-stream";
502
- const buffer = await file.arrayBuffer();
503
- const contentHash = await sha256HexFromBuffer(buffer);
504
- const cap = await discoverUploadCapability(config.endpoint, execute);
505
- const payload = await callUploadOp(execute, cap, {
506
- bucketKey,
507
- contentHash,
508
- contentType,
509
- size: file.size,
510
- filename: file.name
511
- });
512
- if (!payload.deduplicated) {
513
- if (!payload.uploadUrl) {
514
- throw import_data2.createError.badRequest("Upload failed: server returned no uploadUrl for a non-deduplicated file.");
515
- }
516
- try {
517
- await presignedPut(payload.uploadUrl, buffer, contentType, options?.onProgress);
518
- } catch (error) {
519
- await deleteUploadedFileRow(execute, cap, payload.fileId);
520
- throw error;
521
- }
522
- } else {
523
- options?.onProgress?.({ loaded: file.size, total: file.size, percentage: 100 });
524
- }
525
- const url = await fetchDownloadUrl(execute, cap, payload.fileId);
526
- return {
527
- url,
528
- filename: file.name,
529
- mime: file.type,
530
- size: file.size,
531
- key: payload.key,
532
- fileId: payload.fileId
533
- };
738
+ function resolveStorageTransport(config, getToken) {
739
+ const endpoint = config.storage?.endpoint;
740
+ if (!endpoint) return void 0;
741
+ return {
742
+ endpoint,
743
+ execute: config.storage?.execute ?? createSheetsExecute({ ...config, endpoint }, getToken)
534
744
  };
535
745
  }
536
746
 
@@ -556,7 +766,7 @@ function createDraftRowsSlice(set) {
556
766
  const effectiveColumnOrder = ensureColumnOrder(columnOrder, fieldMetaByKey, relationInfoByKey);
557
767
  const template = buildTemplate(effectiveColumnOrder, relationInfoByKey);
558
768
  const draftRowId = `draft:${generateDraftSuffix()}`;
559
- const values = initializeValuesFromTemplate(template, draftRowId);
769
+ const values = initializeValuesFromTemplate(template);
560
770
  set((state) => {
561
771
  const existing = state.draftRowsByTable[tableKey];
562
772
  const nextOrder = existing ? [...existing.order, draftRowId] : [draftRowId];
@@ -697,7 +907,7 @@ function createDraftRowsSlice(set) {
697
907
  for (const draftId of tableState.order) {
698
908
  const row = tableState.map[draftId];
699
909
  if (!row) continue;
700
- const mergedValues = initializeValuesFromTemplate(template, draftId);
910
+ const mergedValues = initializeValuesFromTemplate(template);
701
911
  for (const key of Object.keys(row.values)) {
702
912
  if (Object.prototype.hasOwnProperty.call(template, key)) {
703
913
  mergedValues[key] = deepClone(row.values[key]);
@@ -768,7 +978,7 @@ function buildTemplate(columnOrder, relationInfoByKey) {
768
978
  if (relationInfo && (relationInfo.kind === "hasMany" || relationInfo.kind === "manyToMany")) {
769
979
  template[column] = [];
770
980
  } else {
771
- template[column] = null;
981
+ template[column] = void 0;
772
982
  }
773
983
  }
774
984
  return template;
@@ -782,12 +992,11 @@ function generateDraftSuffix() {
782
992
  }
783
993
  return Math.random().toString(36).slice(2, 10);
784
994
  }
785
- function initializeValuesFromTemplate(template, draftRowId) {
995
+ function initializeValuesFromTemplate(template) {
786
996
  const result = {};
787
997
  for (const [key, value] of Object.entries(template)) {
788
998
  result[key] = deepClone(value);
789
999
  }
790
- if (!result.id) result.id = draftRowId;
791
1000
  return result;
792
1001
  }
793
1002
  function deepClone(value) {
@@ -843,242 +1052,11 @@ function shallowEqualArrays(a, b) {
843
1052
  return true;
844
1053
  }
845
1054
 
846
- // src/store/relation-info-slice.ts
847
- var import_inflekt2 = require("inflekt");
848
- var import_data5 = require("@constructive-io/data");
849
-
850
- // src/utils/relation-utils.ts
851
- var import_inflekt = require("inflekt");
852
- var import_data4 = require("@constructive-io/data");
853
- function isJunctionTablePure(junctionTableName, leftFkField, rightFkField, metaTables) {
854
- if (!leftFkField || !rightFkField) return true;
855
- const junctionMeta = metaTables.find((t) => t?.name === junctionTableName);
856
- if (!junctionMeta?.fields) return true;
857
- const exemptFields = /* @__PURE__ */ new Set(["id", leftFkField, rightFkField]);
858
- for (const field of junctionMeta.fields) {
859
- if (!field?.name) continue;
860
- const camelName = (0, import_data4.pgFieldToCamelCase)(field.name);
861
- if (exemptFields.has(camelName)) continue;
862
- if (field.isNotNull && !field.hasDefault) return false;
863
- }
864
- return true;
865
- }
866
- function getJunctionTableNames(relations, metaTables) {
867
- const names = /* @__PURE__ */ new Set();
868
- for (const rel of relations.manyToMany) {
869
- if (!rel.junctionTable) continue;
870
- if (metaTables) {
871
- const leftFk = rel.junctionLeftKeyFields?.[0];
872
- const rightFk = rel.junctionRightKeyFields?.[0];
873
- if (!isJunctionTablePure(rel.junctionTable, leftFk, rightFk, metaTables)) continue;
874
- }
875
- names.add(rel.junctionTable);
876
- }
877
- return names;
878
- }
879
-
880
- // src/store/relation-info-slice.ts
881
- function toRelationInfoMap(info) {
882
- return new Map(Object.entries(info));
883
- }
884
- function setTableRelationInfo(set, tableName, info) {
885
- set((state) => ({
886
- relationInfoCache: { ...state.relationInfoCache, [tableName]: info },
887
- relationInfoMapCache: { ...state.relationInfoMapCache, [tableName]: toRelationInfoMap(info) }
888
- }));
889
- }
890
- function createRelationInfoSlice(set, get) {
891
- return {
892
- relationInfoCache: {},
893
- relationInfoMapCache: {},
894
- setRelationInfoForTable: (tableName, info) => setTableRelationInfo(set, tableName, info),
895
- getRelationInfoForTable: (tableName) => get().relationInfoCache[tableName],
896
- getRelationInfoMapForTable: (tableName) => get().relationInfoMapCache[tableName],
897
- clearRelationInfoCache: () => set({ relationInfoCache: {}, relationInfoMapCache: {} }),
898
- rebuildRelationInfo: (tableName, meta) => {
899
- try {
900
- const info = buildRelationInfoFromMeta(tableName, meta);
901
- if (!info) return;
902
- setTableRelationInfo(set, tableName, info);
903
- } catch {
904
- }
905
- },
906
- ensureRelationInfo: (tableName, meta) => {
907
- const existing = get().relationInfoCache[tableName];
908
- if (existing) return existing;
909
- const info = buildRelationInfoFromMeta(tableName, meta) || {};
910
- if (Object.keys(info).length) {
911
- setTableRelationInfo(set, tableName, info);
912
- }
913
- return info;
914
- }
915
- };
916
- }
917
- function toCleanTables(meta) {
918
- const tables = meta?._meta?.tables ?? [];
919
- return tables.filter((table) => table != null).map((table) => (0, import_data5.cleanTable)(table));
920
- }
921
- function firstFieldName(fields2) {
922
- return fields2[0]?.name;
923
- }
924
- function findForeignKeyInRelatedTable(currentTableName, relatedTableName, allTables, rawMetaTables) {
925
- const relatedTable = allTables.find((t) => t.name === relatedTableName);
926
- if (relatedTable) {
927
- const belongsTo = relatedTable.relations.belongsTo.find(
928
- (rel) => rel.referencesTable === currentTableName
929
- );
930
- if (belongsTo?.keys?.[0]?.name) return belongsTo.keys[0].name;
931
- }
932
- const rawRelated = rawMetaTables.find((t) => t.name === relatedTableName);
933
- if (rawRelated) {
934
- const v5Fks = Array.isArray(rawRelated.constraints) ? [] : rawRelated.constraints?.foreignKey;
935
- const fks = v5Fks ?? rawRelated.foreignKeyConstraints ?? [];
936
- for (const fk of fks) {
937
- if (!fk) continue;
938
- const refName = fk.refTable?.name;
939
- if (refName && refName.toLowerCase() === currentTableName.toLowerCase()) {
940
- const fieldName = fk.fields?.[0]?.name;
941
- if (fieldName) return (0, import_data5.pgFieldToCamelCase)(fieldName);
942
- }
943
- }
944
- }
945
- return void 0;
946
- }
947
- function buildRelationInfoFromMeta(tableName, meta) {
948
- const tables = toCleanTables(meta);
949
- const table = tables.find((candidate) => candidate.name === tableName);
950
- if (!table) return null;
951
- const rawMetaTables = (meta?._meta?.tables ?? []).filter(
952
- (t) => t != null
953
- );
954
- const PRIORITY_FIELDS = [
955
- "displayName",
956
- "fullName",
957
- "preferredName",
958
- "nickname",
959
- "firstName",
960
- "lastName",
961
- "givenName",
962
- "familyName",
963
- "username",
964
- "handle",
965
- "email",
966
- "phone",
967
- "title",
968
- "label",
969
- "slug",
970
- "code",
971
- "name"
972
- ];
973
- const NAME_PATTERN = /name/i;
974
- const computeCandidates = (relatedTableName) => {
975
- if (!relatedTableName) return [];
976
- const related = tables.find((candidate) => candidate.name === relatedTableName);
977
- if (!related) return [];
978
- const fieldNamesSet = new Set(related.fields.map((field) => field.name));
979
- const explicit = PRIORITY_FIELDS.filter((k) => fieldNamesSet.has(k));
980
- const explicitSet = new Set(explicit);
981
- const nameLike = [];
982
- for (const name of fieldNamesSet) {
983
- if (NAME_PATTERN.test(name) && !explicitSet.has(name)) {
984
- nameLike.push(name);
985
- }
986
- }
987
- nameLike.sort((a, b) => a.length - b.length);
988
- return Array.from(/* @__PURE__ */ new Set([...explicit, ...nameLike]));
989
- };
990
- const info = {};
991
- table.relations.belongsTo.forEach((relation) => {
992
- const displayCandidates = computeCandidates(relation.referencesTable);
993
- const foreignKeys = relation.keys.map((key) => key.name).filter(Boolean);
994
- const primaryForeignKey = foreignKeys[0];
995
- if (relation.fieldName) {
996
- info[relation.fieldName] = {
997
- kind: "belongsTo",
998
- relatedTable: relation.referencesTable,
999
- displayCandidates,
1000
- relationField: relation.fieldName,
1001
- foreignKeyField: primaryForeignKey
1002
- };
1003
- }
1004
- foreignKeys.forEach((fk) => {
1005
- if (!fk) return;
1006
- info[fk] = {
1007
- kind: "belongsTo",
1008
- relatedTable: relation.referencesTable,
1009
- displayCandidates,
1010
- relationField: relation.fieldName ?? void 0,
1011
- foreignKeyField: fk
1012
- };
1013
- });
1014
- });
1015
- table.relations.hasOne.forEach((relation) => {
1016
- if (relation.fieldName) {
1017
- const fkInRelated = findForeignKeyInRelatedTable(tableName, relation.referencedByTable, tables, rawMetaTables);
1018
- info[relation.fieldName] = {
1019
- kind: "hasOne",
1020
- relatedTable: relation.referencedByTable,
1021
- displayCandidates: computeCandidates(relation.referencedByTable),
1022
- relationField: relation.fieldName,
1023
- foreignKeyField: fkInRelated
1024
- };
1025
- }
1026
- });
1027
- const junctionTableNames = getJunctionTableNames(table.relations, rawMetaTables);
1028
- table.relations.hasMany.forEach((relation) => {
1029
- if (!relation.fieldName) return;
1030
- if (junctionTableNames.has(relation.referencedByTable)) return;
1031
- const fkInRelated = findForeignKeyInRelatedTable(tableName, relation.referencedByTable, tables, rawMetaTables);
1032
- info[relation.fieldName] = {
1033
- kind: "hasMany",
1034
- relatedTable: relation.referencedByTable,
1035
- displayCandidates: computeCandidates(relation.referencedByTable),
1036
- relationField: relation.fieldName,
1037
- foreignKeyField: fkInRelated
1038
- };
1039
- });
1040
- table.relations.manyToMany.forEach((relation) => {
1041
- if (relation.fieldName) {
1042
- let junctionLeftKeyField = relation.junctionLeftKeyFields?.[0];
1043
- let junctionRightKeyField = relation.junctionRightKeyFields?.[0];
1044
- if (!junctionLeftKeyField || !junctionRightKeyField) {
1045
- const junctionTableName = relation.junctionTable;
1046
- const junctionTable = junctionTableName ? tables.find((candidate) => candidate.name === junctionTableName) : void 0;
1047
- const junctionBelongsTo = junctionTable?.relations.belongsTo ?? [];
1048
- if (!junctionLeftKeyField) {
1049
- const leftRelation = junctionBelongsTo.find((entry) => entry.referencesTable === tableName);
1050
- junctionLeftKeyField = firstFieldName(leftRelation?.keys ?? []);
1051
- }
1052
- if (!junctionRightKeyField) {
1053
- const rightRelation = junctionBelongsTo.find((entry) => entry.referencesTable === relation.rightTable);
1054
- junctionRightKeyField = firstFieldName(rightRelation?.keys ?? []);
1055
- }
1056
- }
1057
- if (!isJunctionTablePure(relation.junctionTable, junctionLeftKeyField, junctionRightKeyField, rawMetaTables)) {
1058
- return;
1059
- }
1060
- info[relation.fieldName] = {
1061
- kind: "manyToMany",
1062
- relatedTable: relation.rightTable,
1063
- displayCandidates: computeCandidates(relation.rightTable),
1064
- relationField: relation.fieldName,
1065
- junctionTable: relation.junctionTable,
1066
- junctionLeftKeyField,
1067
- junctionRightKeyField,
1068
- displayName: (0, import_inflekt2.pluralize)(relation.rightTable)
1069
- };
1070
- }
1071
- });
1072
- return info;
1073
- }
1074
-
1075
1055
  // src/store/sheets-store.ts
1076
1056
  function createSheetsStore() {
1077
- return (0, import_zustand.createStore)((set, get) => ({
1057
+ return (0, import_zustand.createStore)((set) => ({
1078
1058
  // Draft rows
1079
1059
  ...createDraftRowsSlice(set),
1080
- // Relation info cache
1081
- ...createRelationInfoSlice(set, get),
1082
1060
  // Auth state (standalone mode)
1083
1061
  isAuthenticated: false,
1084
1062
  accessToken: null,
@@ -1137,25 +1115,33 @@ function setSheetsLocale(locale) {
1137
1115
  }
1138
1116
 
1139
1117
  // src/hooks/query-keys.ts
1118
+ function tableKeySegments(tableRef) {
1119
+ const dot = tableRef.lastIndexOf(".");
1120
+ return dot === -1 ? [tableRef] : [tableRef.slice(dot + 1), tableRef.slice(0, dot)];
1121
+ }
1140
1122
  var sheetsQueryKeys = {
1141
1123
  root: ["sheets"],
1142
1124
  scope: (scope) => ["sheets", scope],
1143
1125
  meta: (scope) => [...sheetsQueryKeys.scope(scope), "meta"],
1144
- typeFields: (scope, typeName) => [...sheetsQueryKeys.scope(scope), "type-fields", typeName],
1145
- enumValues: (scope, typeName) => [...sheetsQueryKeys.scope(scope), "enum-values", typeName],
1146
- relations: (scope, tableName) => [...sheetsQueryKeys.scope(scope), "relations", tableName],
1147
- table: (scope, tableName) => [...sheetsQueryKeys.scope(scope), "table", tableName],
1148
- tableRows: (scope, tableName, options) => [...sheetsQueryKeys.table(scope, tableName), "rows", options],
1149
- tableRow: (scope, tableName, id) => [...sheetsQueryKeys.table(scope, tableName), "row", id],
1150
- tableCount: (scope, tableName, where) => [...sheetsQueryKeys.table(scope, tableName), "count", where],
1151
- infiniteTable: (scope, tableName) => [...sheetsQueryKeys.scope(scope), "infinite-table", tableName],
1152
- infiniteTablePage: (scope, tableName, pageIndex, options) => [...sheetsQueryKeys.infiniteTable(scope, tableName), "page", pageIndex, options],
1153
- infiniteTableTotalCount: (scope, tableName, where) => [...sheetsQueryKeys.infiniteTable(scope, tableName), "totalCount", where],
1154
- cursorTable: (scope, tableName, options) => [...sheetsQueryKeys.scope(scope), "cursor-table", tableName, options]
1126
+ /** One table model, per `_meta` version and display override. */
1127
+ tableModel: (scope, tableKey, metaVersion, displayKey) => [...sheetsQueryKeys.scope(scope), "table-model", ...tableKeySegments(tableKey), metaVersion, displayKey],
1128
+ mediaUrl: (scope, endpoint, id) => [...sheetsQueryKeys.scope(scope), "media-url", endpoint, id],
1129
+ relations: (scope, tableName) => [...sheetsQueryKeys.scope(scope), "relations", ...tableKeySegments(tableName)],
1130
+ table: (scope, tableRef) => [...sheetsQueryKeys.scope(scope), "table", ...tableKeySegments(tableRef)],
1131
+ tableRows: (scope, tableRef, options) => [...sheetsQueryKeys.table(scope, tableRef), "rows", options],
1132
+ tableRow: (scope, tableRef, id) => [...sheetsQueryKeys.table(scope, tableRef), "row", id],
1133
+ tableCount: (scope, tableRef, where) => [...sheetsQueryKeys.table(scope, tableRef), "count", where],
1134
+ infiniteTable: (scope, tableRef) => [...sheetsQueryKeys.scope(scope), "infinite-table", ...tableKeySegments(tableRef)],
1135
+ infiniteTablePage: (scope, tableRef, pageIndex, options) => [...sheetsQueryKeys.infiniteTable(scope, tableRef), "page", pageIndex, options],
1136
+ infiniteTableTotalCount: (scope, tableRef, where) => [...sheetsQueryKeys.infiniteTable(scope, tableRef), "totalCount", where],
1137
+ cursorTable: (scope, tableRef, options) => [...sheetsQueryKeys.scope(scope), "cursor-table", ...tableKeySegments(tableRef), options]
1155
1138
  };
1156
1139
 
1157
1140
  // src/context/sheets-provider.tsx
1158
1141
  var import_jsx_runtime = require("react/jsx-runtime");
1142
+ var unavailableUpload = async () => {
1143
+ throw new Error("Uploads need a storage endpoint");
1144
+ };
1159
1145
  function SheetsProvider({ config, children }) {
1160
1146
  const providerInstanceId = (0, import_react3.useId)();
1161
1147
  const storeRef = (0, import_react3.useRef)(null);
@@ -1214,10 +1200,13 @@ function SheetsProvider({ config, children }) {
1214
1200
  if (config.execute) return config.execute;
1215
1201
  return createSheetsExecute(config, getToken);
1216
1202
  }, [config, getToken]);
1203
+ const storage = (0, import_react3.useMemo)(() => resolveStorageTransport(config, getToken), [config, getToken]);
1204
+ const bucketKey = config.upload?.bucketKey;
1217
1205
  const executeUpload = (0, import_react3.useMemo)(() => {
1218
1206
  if (config.executeUpload) return config.executeUpload;
1219
- return createSheetsUpload(config, getToken);
1220
- }, [config, getToken]);
1207
+ return storage ? createPresignedSheetsUpload(storage, bucketKey) : unavailableUpload;
1208
+ }, [config.executeUpload, storage, bucketKey]);
1209
+ const canUpload = Boolean(config.executeUpload || storage);
1221
1210
  const configuredIdentityKey = config.auth.mode === "embedded" ? config.auth.getIdentityKey?.() ?? null : standaloneIdentityKey;
1222
1211
  const activeToken = config.auth.mode === "embedded" ? config.auth.getToken() : standaloneAccessToken;
1223
1212
  const authGenerationRef = (0, import_react3.useRef)({ mode: config.auth.mode, token: activeToken, generation: 0 });
@@ -1243,12 +1232,137 @@ function SheetsProvider({ config, children }) {
1243
1232
  };
1244
1233
  }, [queryClient, scopeKey]);
1245
1234
  const contextValue = (0, import_react3.useMemo)(
1246
- () => ({ config, execute, executeUpload, scopeKey }),
1247
- [config, execute, executeUpload, scopeKey]
1235
+ () => ({ config, execute, executeUpload, storage, canUpload, scopeKey }),
1236
+ [config, execute, executeUpload, storage, canUpload, scopeKey]
1248
1237
  );
1249
1238
  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 }) }) });
1250
1239
  }
1251
1240
 
1241
+ // src/testing/meta-schema.ts
1242
+ var import_data5 = require("@constructive-io/data");
1243
+ var BUILT_IN_SCALARS = /* @__PURE__ */ new Set(["String", "Int", "Float", "Boolean", "ID"]);
1244
+ var ORDERED_SCALARS = /* @__PURE__ */ new Set(["Int", "Float", "BigInt", "BigFloat", "Date", "Datetime", "Time", "String", "UUID"]);
1245
+ function constantCase(name) {
1246
+ return name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/[^A-Za-z0-9]+/g, "_").toUpperCase();
1247
+ }
1248
+ function fieldsOf(table) {
1249
+ return (table.fields ?? []).filter((field) => Boolean(field?.name));
1250
+ }
1251
+ function typeRef(field) {
1252
+ return field.type.isArray ? `[${field.type.gqlType}]` : field.type.gqlType;
1253
+ }
1254
+ function operatorType(field) {
1255
+ return field.type.isArray ? `${field.type.gqlType}ListFilter` : `${field.type.gqlType}Filter`;
1256
+ }
1257
+ function scalarFilter(scalar) {
1258
+ const ordered = ORDERED_SCALARS.has(scalar) ? `lessThan: ${scalar} lessThanOrEqualTo: ${scalar} greaterThan: ${scalar} greaterThanOrEqualTo: ${scalar}` : "";
1259
+ const text = scalar === "String" ? "includes: String notIncludes: String includesInsensitive: String notIncludesInsensitive: String startsWith: String startsWithInsensitive: String endsWith: String endsWithInsensitive: String equalToInsensitive: String" : "";
1260
+ return `input ${scalar}Filter { isNull: Boolean equalTo: ${scalar} notEqualTo: ${scalar} distinctFrom: ${scalar} notDistinctFrom: ${scalar} in: [${scalar}!] notIn: [${scalar}!] ${ordered} ${text} }`;
1261
+ }
1262
+ function listFilter(scalar) {
1263
+ return `input ${scalar}ListFilter { isNull: Boolean equalTo: [${scalar}] notEqualTo: [${scalar}] contains: [${scalar}] anyEqualTo: ${scalar} }`;
1264
+ }
1265
+ function relationFields(table, names) {
1266
+ const relations = table.relations;
1267
+ const columns = new Set(fieldsOf(table).map((field) => field.name));
1268
+ const fields2 = [];
1269
+ const add = (fieldName, definition) => {
1270
+ if (!columns.has(fieldName)) fields2.push(definition);
1271
+ };
1272
+ for (const relation of relations?.belongsTo ?? []) {
1273
+ if (relation?.fieldName && names.has(relation.references.name)) add(relation.fieldName, `${relation.fieldName}: ${relation.references.name}`);
1274
+ }
1275
+ for (const relation of relations?.hasOne ?? []) {
1276
+ if (relation?.fieldName && names.has(relation.referencedBy.name)) add(relation.fieldName, `${relation.fieldName}: ${relation.referencedBy.name}`);
1277
+ }
1278
+ for (const relation of relations?.hasMany ?? []) {
1279
+ if (relation?.fieldName && names.has(relation.referencedBy.name)) {
1280
+ add(relation.fieldName, `${relation.fieldName}(first: Int): ${relation.referencedBy.name}Connection!`);
1281
+ }
1282
+ }
1283
+ for (const relation of relations?.manyToMany ?? []) {
1284
+ if (relation?.fieldName && names.has(relation.rightTable.name)) {
1285
+ add(relation.fieldName, `${relation.fieldName}(first: Int): ${relation.rightTable.name}Connection!`);
1286
+ }
1287
+ }
1288
+ return fields2;
1289
+ }
1290
+ function tableTypes(table, names) {
1291
+ const name = table.name;
1292
+ const fields2 = fieldsOf(table);
1293
+ const identity = (0, import_data5.getRowIdentityDefinition)(table);
1294
+ const primaryKey = identity.status === "keyed" ? identity.fields.map((field) => field.fieldName) : [];
1295
+ const record = (0, import_data5.toCamelCaseSingular)(name);
1296
+ const requiredOnCreate = (field) => !primaryKey.includes(field.name) && Boolean(field.isNotNull) && !field.hasDefault;
1297
+ const columns = fields2.map((field) => `${field.name}: ${typeRef(field)}`).join(" ");
1298
+ const keyFields = primaryKey.map((key) => fields2.find((field) => field.name === key)).filter((field) => Boolean(field)).map((field) => `${field.name}: ${typeRef(field)}!`).join(" ");
1299
+ const sdl = [
1300
+ `type ${name} { ${[columns, ...relationFields(table, names)].join(" ")} }`,
1301
+ `type ${name}Connection { nodes: [${name}]! totalCount: Int! pageInfo: PageInfo! }`,
1302
+ `input ${name}Filter { ${fields2.map((field) => `${field.name}: ${operatorType(field)}`).join(" ")} and: [${name}Filter!] or: [${name}Filter!] not: ${name}Filter }`,
1303
+ `enum ${name}OrderBy { NATURAL ${primaryKey.length > 0 ? "PRIMARY_KEY_ASC PRIMARY_KEY_DESC" : ""} ${fields2.map((field) => `${constantCase(field.name)}_ASC ${constantCase(field.name)}_DESC`).join(" ")} }`
1304
+ ];
1305
+ if (table.query?.create) {
1306
+ sdl.push(
1307
+ `input ${name}Input { ${fields2.map((field) => `${field.name}: ${typeRef(field)}${requiredOnCreate(field) ? "!" : ""}`).join(" ")} }`,
1308
+ `input Create${name}Input { clientMutationId: String ${record}: ${name}Input! }`,
1309
+ `type Create${name}Payload { clientMutationId: String ${record}: ${name} }`
1310
+ );
1311
+ }
1312
+ if (table.query?.update && keyFields) {
1313
+ sdl.push(
1314
+ `input ${name}Patch { ${columns} }`,
1315
+ `input Update${name}Input { clientMutationId: String ${keyFields} ${record}Patch: ${name}Patch! }`,
1316
+ `type Update${name}Payload { clientMutationId: String ${record}: ${name} }`
1317
+ );
1318
+ }
1319
+ if (table.query?.delete && keyFields) {
1320
+ sdl.push(
1321
+ `input Delete${name}Input { clientMutationId: String ${keyFields} }`,
1322
+ `type Delete${name}Payload { clientMutationId: String ${record}: ${name} }`
1323
+ );
1324
+ }
1325
+ return sdl;
1326
+ }
1327
+ function rootFields(tables) {
1328
+ const query = [];
1329
+ const mutation = [];
1330
+ for (const table of tables) {
1331
+ const name = table.name;
1332
+ const ops = table.query;
1333
+ if (ops?.all) {
1334
+ query.push(`${ops.all}(first: Int, offset: Int, after: Cursor, where: ${name}Filter, orderBy: [${name}OrderBy!]): ${name}Connection`);
1335
+ }
1336
+ const keyed = (0, import_data5.getRowIdentityDefinition)(table).status === "keyed";
1337
+ if (ops?.create) mutation.push(`${ops.create}(input: Create${name}Input!): Create${name}Payload`);
1338
+ if (ops?.update && keyed) mutation.push(`${ops.update}(input: Update${name}Input!): Update${name}Payload`);
1339
+ if (ops?.delete && keyed) mutation.push(`${ops.delete}(input: Delete${name}Input!): Delete${name}Payload`);
1340
+ }
1341
+ return { query, mutation };
1342
+ }
1343
+ function buildMetaSchemaSdl(tables) {
1344
+ const names = new Set(tables.map((table) => table.name));
1345
+ const fields2 = tables.flatMap(fieldsOf);
1346
+ const scalars = new Set(fields2.map((field) => field.type.gqlType));
1347
+ const listScalars = new Set(fields2.filter((field) => field.type.isArray).map((field) => field.type.gqlType));
1348
+ const { query, mutation } = rootFields(tables);
1349
+ return [
1350
+ "scalar Cursor",
1351
+ ...[...scalars].filter((scalar) => !BUILT_IN_SCALARS.has(scalar) && scalar !== "Cursor").map((scalar) => `scalar ${scalar}`),
1352
+ "type PageInfo { hasNextPage: Boolean! hasPreviousPage: Boolean! startCursor: Cursor endCursor: Cursor }",
1353
+ "input BooleanFilter { isNull: Boolean equalTo: Boolean notEqualTo: Boolean }",
1354
+ ...[...scalars].filter((scalar) => scalar !== "Boolean").map(scalarFilter),
1355
+ ...[...listScalars].map(listFilter),
1356
+ ...tables.flatMap((table) => tableTypes(table, names)),
1357
+ `type Query { ${query.join(" ") || "noop: Boolean"} }`,
1358
+ mutation.length > 0 ? `type Mutation { ${mutation.join(" ")} }` : ""
1359
+ ].filter(Boolean).join("\n");
1360
+ }
1361
+
1362
+ // src/testing/model-backend.ts
1363
+ var import_graphql4 = require("graphql");
1364
+ var import_data7 = require("@constructive-io/data");
1365
+
1252
1366
  // src/testing/meta-contract-fixture.ts
1253
1367
  var import_data6 = require("@constructive-io/data");
1254
1368
  var fields = (names) => names.map((name) => ({ name }));
@@ -1261,29 +1375,619 @@ function createMetaContractFixture() {
1261
1375
  );
1262
1376
  }
1263
1377
 
1264
- // src/testing/mock-sheets-provider.tsx
1265
- var import_jsx_runtime2 = require("react/jsx-runtime");
1266
- function documentToString2(document) {
1378
+ // src/testing/model-backend-uploads.ts
1379
+ var import_graphql3 = require("graphql");
1380
+ var LIVE_STATUSES = /* @__PURE__ */ new Set(["uploaded", "processed"]);
1381
+ var UPLOAD_URL_LIFETIME_MS = 15 * 60 * 1e3;
1382
+ function fail(message, code, extensions = {}) {
1383
+ return new import_graphql3.GraphQLError(message, { extensions: { code, ...extensions } });
1384
+ }
1385
+ function hexToBase64(hex2) {
1386
+ let binary = "";
1387
+ for (let index = 0; index < hex2.length; index += 2) binary += String.fromCharCode(Number.parseInt(hex2.slice(index, index + 2), 16));
1388
+ return btoa(binary);
1389
+ }
1390
+ function mimeAllowed(allowed, contentType) {
1391
+ if (!Array.isArray(allowed) || allowed.length === 0) return true;
1392
+ return allowed.some((pattern) => {
1393
+ if (typeof pattern !== "string") return false;
1394
+ if (pattern === "*/*") return true;
1395
+ if (pattern.endsWith("/*")) return contentType.startsWith(pattern.slice(0, -1));
1396
+ return contentType === pattern;
1397
+ });
1398
+ }
1399
+ var fileIds = 0;
1400
+ function nextFileId() {
1401
+ fileIds += 1;
1402
+ return `00000000-0000-4000-9000-${String(fileIds).padStart(12, "0")}`;
1403
+ }
1404
+ function surfacesOf(models) {
1405
+ return models.flatMap((files) => {
1406
+ const storage = files.storage;
1407
+ if (storage?.role !== "files" || !storage.upload?.mutation) return [];
1408
+ const buckets = models.find((candidate) => candidate.name === storage.bucketsType) ?? null;
1409
+ const link = files.relations.find(
1410
+ (relation) => relation.kind === "belongsTo" && relation.targetName === storage.bucketsType && relation.keys.length === 1
1411
+ );
1412
+ return [{
1413
+ files,
1414
+ buckets,
1415
+ bucketLink: link?.keys[0] ?? null,
1416
+ mutation: storage.upload.mutation,
1417
+ bulkMutation: storage.upload.bulkMutation,
1418
+ downloadUrlField: storage.downloadUrlField
1419
+ }];
1420
+ });
1421
+ }
1422
+ function createUploadService(models, tableRows, options = {}, uploads = []) {
1423
+ const surfaces = surfacesOf(models);
1424
+ const refusalsLeft = /* @__PURE__ */ new Map();
1425
+ const publicUrlPrefix = (options.publicUrlPrefix ?? "https://cdn.mock").replace(/\/$/, "");
1426
+ const uploadUrlPrefix = (options.uploadUrlPrefix ?? "https://storage.mock/upload").replace(/\/$/, "");
1427
+ const fileRow = (fileId) => {
1428
+ for (const surface of surfaces) {
1429
+ const row = tableRows(surface.files).find((candidate) => candidate.id === fileId);
1430
+ if (row) return { surface, row };
1431
+ }
1432
+ return null;
1433
+ };
1434
+ const assign = (surface, row, field, value) => {
1435
+ if (surface.files.columns.some((column) => column.name === field)) row[field] = value;
1436
+ };
1437
+ function resolveBucket(surface, input) {
1438
+ const buckets = surface.buckets ? tableRows(surface.buckets) : [];
1439
+ const bucket = typeof input.bucketKey === "string" ? buckets.find((candidate) => candidate.key === input.bucketKey) : buckets.find((candidate) => candidate.isPublic === true === (input.isPublic === true));
1440
+ if (!bucket) throw fail("BUCKET_NOT_FOUND", "BUCKET_NOT_FOUND");
1441
+ return bucket;
1442
+ }
1443
+ function projection(fileId, key, bucket, input) {
1444
+ return {
1445
+ id: fileId,
1446
+ key,
1447
+ bucket_id: bucket.id,
1448
+ mime: input.contentType,
1449
+ size: input.size,
1450
+ ...typeof input.filename === "string" && input.filename ? { filename: input.filename } : {},
1451
+ ...bucket.isPublic === true ? { url: `${publicUrlPrefix}/${key}` } : {}
1452
+ };
1453
+ }
1454
+ function uploadOne(surface, mutation, input) {
1455
+ const entry = {
1456
+ mutation,
1457
+ filesTable: surface.files.name,
1458
+ input,
1459
+ outcome: "failed",
1460
+ fileId: null,
1461
+ error: null,
1462
+ at: Date.now()
1463
+ };
1464
+ uploads.push(entry);
1465
+ try {
1466
+ const refused = options.failure?.(input);
1467
+ if (refused) throw fail(refused.message, refused.code ?? "UPLOAD_FAILED");
1468
+ const contentHash = String(input.contentHash ?? "");
1469
+ const contentType = String(input.contentType ?? "");
1470
+ if (!/^[0-9a-f]{64}$/i.test(contentHash)) {
1471
+ throw fail("INVALID_CONTENT_HASH_FORMAT: must be a 64-char lowercase hex SHA-256", "INVALID_CONTENT_HASH_FORMAT");
1472
+ }
1473
+ const bucket = resolveBucket(surface, input);
1474
+ if (!mimeAllowed(bucket.allowedMimeTypes, contentType)) {
1475
+ throw fail(`CONTENT_TYPE_NOT_ALLOWED: ${contentType} not in bucket allowed types`, "CONTENT_TYPE_NOT_ALLOWED");
1476
+ }
1477
+ const maxFileSize = bucket.maxFileSize == null ? null : Number(bucket.maxFileSize);
1478
+ if (maxFileSize && Number(input.size) > maxFileSize) {
1479
+ throw fail(`FILE_TOO_LARGE: exceeds bucket max of ${maxFileSize} bytes`, "FILE_TOO_LARGE");
1480
+ }
1481
+ const key = typeof input.key === "string" && input.key ? input.key : contentHash;
1482
+ const rows = tableRows(surface.files);
1483
+ const link = surface.bucketLink;
1484
+ const inBucket = (row) => !link || row[link.local] === bucket[link.remote];
1485
+ const existing = rows.find((row) => row.key === key && inBucket(row));
1486
+ const live = existing && LIVE_STATUSES.has(String(existing.status));
1487
+ if (live || options.deduplicated) {
1488
+ const fileId2 = existing && live ? String(existing.id) : createRow(surface, bucket, key, input, "uploaded");
1489
+ Object.assign(entry, { outcome: "deduplicated", fileId: fileId2 });
1490
+ return {
1491
+ uploadUrl: null,
1492
+ uploadHeaders: null,
1493
+ fileId: fileId2,
1494
+ key,
1495
+ deduplicated: true,
1496
+ expiresAt: null,
1497
+ file: projection(fileId2, key, bucket, input)
1498
+ };
1499
+ }
1500
+ if (existing) rows.splice(rows.indexOf(existing), 1);
1501
+ const rejected = options.rejectUpload?.(input) ?? false;
1502
+ const refusals = rejected ? 0 : options.notLiveForWrites ?? 0;
1503
+ const fileId = createRow(surface, bucket, key, input, rejected ? "rejected" : refusals > 0 ? "requested" : "uploaded");
1504
+ if (refusals > 0) refusalsLeft.set(fileId, refusals);
1505
+ Object.assign(entry, { outcome: "requested", fileId });
1506
+ return {
1507
+ uploadUrl: `${uploadUrlPrefix}/${fileId}`,
1508
+ uploadHeaders: {
1509
+ "Content-Type": contentType,
1510
+ "x-amz-checksum-sha256": hexToBase64(contentHash),
1511
+ "x-amz-meta-upload-id": fileId
1512
+ },
1513
+ fileId,
1514
+ key,
1515
+ deduplicated: false,
1516
+ expiresAt: new Date(Date.now() + UPLOAD_URL_LIFETIME_MS).toISOString(),
1517
+ file: projection(fileId, key, bucket, input)
1518
+ };
1519
+ } catch (error) {
1520
+ entry.error = error instanceof Error ? error.message : String(error);
1521
+ throw error;
1522
+ }
1523
+ }
1524
+ function createRow(surface, bucket, key, input, status) {
1525
+ const fileId = nextFileId();
1526
+ const now = (/* @__PURE__ */ new Date()).toISOString();
1527
+ const row = {};
1528
+ for (const column of surface.files.columns) row[column.name] = null;
1529
+ assign(surface, row, "id", fileId);
1530
+ if (surface.bucketLink) row[surface.bucketLink.local] = bucket[surface.bucketLink.remote];
1531
+ assign(surface, row, "key", key);
1532
+ assign(surface, row, "contentHash", input.contentHash);
1533
+ assign(surface, row, "mimeType", input.contentType);
1534
+ assign(surface, row, "size", String(input.size));
1535
+ assign(surface, row, "filename", input.filename ?? null);
1536
+ assign(surface, row, "isPublic", bucket.isPublic === true);
1537
+ assign(surface, row, "status", status);
1538
+ assign(surface, row, "createdAt", now);
1539
+ assign(surface, row, "updatedAt", now);
1540
+ tableRows(surface.files).push(row);
1541
+ return fileId;
1542
+ }
1543
+ return {
1544
+ uploads,
1545
+ rootResolvers(onRequest) {
1546
+ const root = {};
1547
+ for (const surface of surfaces) {
1548
+ root[surface.mutation] = (args) => {
1549
+ onRequest(surface.files);
1550
+ return uploadOne(surface, surface.mutation, args.input ?? {});
1551
+ };
1552
+ if (surface.bulkMutation) {
1553
+ const bulk = surface.bulkMutation;
1554
+ root[bulk] = (args) => {
1555
+ onRequest(surface.files);
1556
+ const { files = [], ...shared } = args.input ?? {};
1557
+ return { files: files.map((file) => uploadOne(surface, bulk, { ...shared, ...file })) };
1558
+ };
1559
+ }
1560
+ }
1561
+ return root;
1562
+ },
1563
+ assertFileRefsLive(model, values) {
1564
+ for (const column of model.columns) {
1565
+ if (!column.value.file || column.value.file.kind === "attachment") continue;
1566
+ const value = values[column.name];
1567
+ const references = (Array.isArray(value) ? value : [value]).filter(
1568
+ (entry) => Boolean(entry) && typeof entry.id === "string"
1569
+ );
1570
+ for (const { id } of references) {
1571
+ const found = fileRow(id);
1572
+ if (!found || LIVE_STATUSES.has(String(found.row.status))) continue;
1573
+ const status = String(found.row.status);
1574
+ const left = refusalsLeft.get(id) ?? 0;
1575
+ if (left > 0) {
1576
+ refusalsLeft.set(id, left - 1);
1577
+ if (left === 1) found.row.status = "uploaded";
1578
+ }
1579
+ throw fail("FILE_REF_FILE_NOT_LIVE", "FILE_REF_FILE_NOT_LIVE", {
1580
+ class: "public",
1581
+ context: { field: column.name, file_id: id, status }
1582
+ });
1583
+ }
1584
+ }
1585
+ },
1586
+ resolveField(model, row, fieldName) {
1587
+ const surface = surfaces.find((candidate) => candidate.files.key === model.key);
1588
+ if (!surface || fieldName !== surface.downloadUrlField) return null;
1589
+ return { value: LIVE_STATUSES.has(String(row.status)) ? `https://storage.mock/download/${String(row.key)}` : null };
1590
+ },
1591
+ confirm(fileId) {
1592
+ const found = fileRow(fileId);
1593
+ if (found && found.row.status !== "rejected") found.row.status = "uploaded";
1594
+ refusalsLeft.delete(fileId);
1595
+ }
1596
+ };
1597
+ }
1598
+
1599
+ // src/testing/model-backend.ts
1600
+ var ROW_MODEL = /* @__PURE__ */ Symbol("row-model");
1601
+ function documentSource(document) {
1267
1602
  if (typeof document === "string") return document;
1268
1603
  if (document instanceof String) return document.toString();
1269
- if (document && typeof document === "object" && "kind" in document) {
1270
- return (0, import_graphql3.print)(document);
1271
- }
1604
+ if (document && typeof document === "object" && "kind" in document) return (0, import_graphql4.print)(document);
1272
1605
  return String(document ?? "");
1273
1606
  }
1607
+ function sameValue(left, right) {
1608
+ if (left === right) return true;
1609
+ if (left == null || right == null) return false;
1610
+ return JSON.stringify(left) === JSON.stringify(right);
1611
+ }
1612
+ function compare(left, right) {
1613
+ if (left == null && right == null) return 0;
1614
+ if (left == null) return -1;
1615
+ if (right == null) return 1;
1616
+ const leftNumber = typeof left === "number" ? left : Number(left);
1617
+ const rightNumber = typeof right === "number" ? right : Number(right);
1618
+ if (typeof left !== "boolean" && Number.isFinite(leftNumber) && Number.isFinite(rightNumber) && String(left).trim() !== "" && String(right).trim() !== "") {
1619
+ return leftNumber - rightNumber;
1620
+ }
1621
+ return String(left).localeCompare(String(right));
1622
+ }
1623
+ function matchesOperator(value, operator, operand) {
1624
+ const text = (input) => String(input ?? "").toLowerCase();
1625
+ switch (operator) {
1626
+ case "isNull":
1627
+ return operand ? value == null : value != null;
1628
+ case "equalTo":
1629
+ return sameValue(value, operand);
1630
+ case "notEqualTo":
1631
+ return !sameValue(value, operand);
1632
+ case "distinctFrom":
1633
+ return !sameValue(value, operand);
1634
+ case "notDistinctFrom":
1635
+ return sameValue(value, operand);
1636
+ case "in":
1637
+ return Array.isArray(operand) && operand.some((item) => sameValue(value, item));
1638
+ case "notIn":
1639
+ return Array.isArray(operand) && !operand.some((item) => sameValue(value, item));
1640
+ case "lessThan":
1641
+ return value != null && compare(value, operand) < 0;
1642
+ case "lessThanOrEqualTo":
1643
+ return value != null && compare(value, operand) <= 0;
1644
+ case "greaterThan":
1645
+ return value != null && compare(value, operand) > 0;
1646
+ case "greaterThanOrEqualTo":
1647
+ return value != null && compare(value, operand) >= 0;
1648
+ case "includes":
1649
+ return String(value ?? "").includes(String(operand));
1650
+ case "notIncludes":
1651
+ return !String(value ?? "").includes(String(operand));
1652
+ case "includesInsensitive":
1653
+ return text(value).includes(text(operand));
1654
+ case "notIncludesInsensitive":
1655
+ return !text(value).includes(text(operand));
1656
+ case "startsWith":
1657
+ return String(value ?? "").startsWith(String(operand));
1658
+ case "notStartsWith":
1659
+ return !String(value ?? "").startsWith(String(operand));
1660
+ case "startsWithInsensitive":
1661
+ return text(value).startsWith(text(operand));
1662
+ case "notStartsWithInsensitive":
1663
+ return !text(value).startsWith(text(operand));
1664
+ case "endsWith":
1665
+ return String(value ?? "").endsWith(String(operand));
1666
+ case "notEndsWith":
1667
+ return !String(value ?? "").endsWith(String(operand));
1668
+ case "endsWithInsensitive":
1669
+ return text(value).endsWith(text(operand));
1670
+ case "notEndsWithInsensitive":
1671
+ return !text(value).endsWith(text(operand));
1672
+ case "equalToInsensitive":
1673
+ return text(value) === text(operand);
1674
+ case "notEqualToInsensitive":
1675
+ return text(value) !== text(operand);
1676
+ case "inInsensitive":
1677
+ return Array.isArray(operand) && operand.some((item) => text(value) === text(item));
1678
+ case "notInInsensitive":
1679
+ return Array.isArray(operand) && !operand.some((item) => text(value) === text(item));
1680
+ case "anyEqualTo":
1681
+ return Array.isArray(value) && value.some((item) => sameValue(item, operand));
1682
+ case "anyNotEqualTo":
1683
+ return Array.isArray(value) && value.some((item) => !sameValue(item, operand));
1684
+ case "contains":
1685
+ return Array.isArray(value) && Array.isArray(operand) && operand.every((item) => value.some((entry) => sameValue(entry, item)));
1686
+ case "containedBy":
1687
+ return Array.isArray(value) && Array.isArray(operand) && value.every((entry) => operand.some((item) => sameValue(entry, item)));
1688
+ case "overlaps":
1689
+ return Array.isArray(value) && Array.isArray(operand) && value.some((entry) => operand.some((item) => sameValue(entry, item)));
1690
+ default:
1691
+ throw import_data7.createError.badRequest(`The mock backend does not support the "${operator}" filter.`);
1692
+ }
1693
+ }
1694
+ function matchesFilter(model, row, filter, related) {
1695
+ if (!filter) return true;
1696
+ const matches = (target, candidate, condition) => matchesFilter(target, candidate, condition, related);
1697
+ return Object.entries(filter).every(([key, condition]) => {
1698
+ if (condition === void 0 || condition === null) return true;
1699
+ if (key === "and") return condition.every((part) => matches(model, row, part));
1700
+ if (key === "or") return condition.some((part) => matches(model, row, part));
1701
+ if (key === "not") return !matches(model, row, condition);
1702
+ const column = model.columns.find((candidate) => candidate.filter?.field === key);
1703
+ if (column) {
1704
+ return Object.entries(condition).every(
1705
+ ([operator, operand]) => matchesOperator(row[column.name], operator, operand)
1706
+ );
1707
+ }
1708
+ if (key === model.search?.unifiedSearchField) {
1709
+ const needle = String(condition).toLowerCase();
1710
+ return model.columns.some(
1711
+ (candidate) => candidate.value.kind === "text" && String(row[candidate.name] ?? "").toLowerCase().includes(needle)
1712
+ );
1713
+ }
1714
+ const byExists = model.relations.find((relation2) => relation2.filter?.exists === key);
1715
+ if (byExists) return related(model, row, byExists).rows.length > 0 === Boolean(condition);
1716
+ const relation = model.relations.find((candidate) => candidate.filter?.field === key);
1717
+ const filter2 = relation?.filter;
1718
+ if (!relation || !filter2) throw import_data7.createError.badRequest(`The mock backend does not filter by "${key}".`);
1719
+ const { target, rows } = related(model, row, relation);
1720
+ const nested = condition;
1721
+ if (!filter2.many) {
1722
+ if (Object.keys(nested).length === 0) return true;
1723
+ return Boolean(target && rows[0] && matches(target, rows[0], nested));
1724
+ }
1725
+ const many = filter2.many;
1726
+ return Object.entries(nested).every(([quantifier, inner]) => {
1727
+ const test = (candidate) => Boolean(target) && matches(target, candidate, inner);
1728
+ if (quantifier === many.some) return rows.some(test);
1729
+ if (quantifier === many.every) return rows.every(test);
1730
+ if (quantifier === many.none) return !rows.some(test);
1731
+ throw import_data7.createError.badRequest(`The mock backend does not support the "${quantifier}" relation filter.`);
1732
+ });
1733
+ });
1734
+ }
1735
+ function sortRows(model, rows, orderBy) {
1736
+ const values = Array.isArray(orderBy) ? orderBy : [];
1737
+ const keys = values.flatMap((value) => {
1738
+ if (value === "NATURAL") return [];
1739
+ if (value === "PRIMARY_KEY_ASC" || value === "PRIMARY_KEY_DESC") {
1740
+ return model.primaryKey.map((field) => ({ field, desc: value === "PRIMARY_KEY_DESC" }));
1741
+ }
1742
+ const column = model.columns.find((candidate) => candidate.sort?.asc === value || candidate.sort?.desc === value);
1743
+ if (!column) throw import_data7.createError.badRequest(`The mock backend does not sort by "${value}".`);
1744
+ return [{ field: column.name, desc: column.sort?.desc === value }];
1745
+ });
1746
+ if (keys.length === 0) return rows;
1747
+ return [...rows].sort((left, right) => {
1748
+ for (const { field, desc } of keys) {
1749
+ const order = compare(left[field], right[field]);
1750
+ if (order !== 0) return desc ? -order : order;
1751
+ }
1752
+ return 0;
1753
+ });
1754
+ }
1755
+ function page(rows, args) {
1756
+ const afterIndex = typeof args.after === "string" && args.after !== "" ? Number(args.after) : Number.NaN;
1757
+ const start = Number.isFinite(afterIndex) ? afterIndex : typeof args.offset === "number" ? args.offset : 0;
1758
+ const end = typeof args.first === "number" ? start + args.first : rows.length;
1759
+ const nodes = rows.slice(start, end);
1760
+ return {
1761
+ nodes,
1762
+ totalCount: rows.length,
1763
+ pageInfo: {
1764
+ hasNextPage: end < rows.length,
1765
+ hasPreviousPage: start > 0,
1766
+ startCursor: nodes.length > 0 ? String(start) : null,
1767
+ endCursor: nodes.length > 0 ? String(start + nodes.length) : null
1768
+ }
1769
+ };
1770
+ }
1771
+ function keyMatches(row, key) {
1772
+ return Object.entries(key).every(([field, value]) => sameValue(row[field], value));
1773
+ }
1774
+ var generatedIds = 0;
1775
+ function generatedKey(column) {
1776
+ generatedIds += 1;
1777
+ if (column.value.kind === "uuid") return `00000000-0000-4000-8000-${String(generatedIds).padStart(12, "0")}`;
1778
+ if (column.value.kind === "integer" || column.value.kind === "bigint") {
1779
+ return column.value.kind === "bigint" ? String(1e5 + generatedIds) : 1e5 + generatedIds;
1780
+ }
1781
+ return `mock-${generatedIds}`;
1782
+ }
1783
+ function storedValue(schema, column, written, previous) {
1784
+ if (column.value.kind !== "geometry" || written == null) return written;
1785
+ const prior = previous && typeof previous === "object" ? previous : {};
1786
+ const type = schema.getType(column.value.typeName);
1787
+ const concrete = prior.__typename ?? (type && (0, import_graphql4.isAbstractType)(type) ? schema.getPossibleTypes(type)[0]?.name : void 0);
1788
+ return { ...prior, ...concrete ? { __typename: concrete } : {}, geojson: written, srid: prior.srid ?? 0 };
1789
+ }
1790
+ function createModelBackend(options) {
1791
+ const { schema, meta } = options;
1792
+ const rows = options.rows;
1793
+ const mutations = [];
1794
+ const uploads = [];
1795
+ let uploadService = null;
1796
+ const hasMetaTypes = Boolean(schema.getType("MetaTable"));
1797
+ const introspect = async (document, variables) => {
1798
+ const result = await (0, import_graphql4.graphql)({ schema, source: documentSource(document), variableValues: variables });
1799
+ if (result.errors?.length) throw import_data7.createError.graphql(result.errors[0].message);
1800
+ return result.data;
1801
+ };
1802
+ let modelsPromise = null;
1803
+ const models = () => {
1804
+ modelsPromise ??= (async () => {
1805
+ const resolver = (0, import_data7.createTableModelResolver)(meta);
1806
+ const resolved = [];
1807
+ for (const table of (0, import_data7.metaTablesOf)(meta)) resolved.push(await resolver.resolve(introspect, (0, import_data7.tableKeyOf)(table)));
1808
+ return resolved;
1809
+ })();
1810
+ return modelsPromise;
1811
+ };
1812
+ const tableRows = (model) => rows[model.name] ??= [];
1813
+ const stored = (model, row) => Object.assign({ ...row }, { [ROW_MODEL]: model });
1814
+ const record = (op, model, variables) => {
1815
+ const mutation = { op, tableName: model.name, variables: variables ?? {}, at: Date.now() };
1816
+ mutations.push(mutation);
1817
+ options.onMutation?.(mutation);
1818
+ };
1819
+ function relatedRowsIn(all) {
1820
+ return (_model, row, relation) => {
1821
+ const target = all.find((candidate) => candidate.key === relation.targetKey) ?? null;
1822
+ if (target && relation.junction) {
1823
+ const junction = all.find((candidate) => candidate.key === relation.junction.tableKey);
1824
+ const links = junction ? tableRows(junction).filter((link) => relation.junction.left.every((pair) => sameValue(link[pair.junction], row[pair.local]))) : [];
1825
+ return {
1826
+ target,
1827
+ rows: tableRows(target).filter(
1828
+ (candidate) => links.some((link) => relation.junction.right.every((pair) => sameValue(candidate[pair.remote], link[pair.junction])))
1829
+ )
1830
+ };
1831
+ }
1832
+ if (target && relation.keys.length > 0) {
1833
+ return {
1834
+ target,
1835
+ rows: tableRows(target).filter(
1836
+ (candidate) => relation.keys.every((pair) => sameValue(candidate[pair.remote], row[pair.local]))
1837
+ )
1838
+ };
1839
+ }
1840
+ return { target, rows: [] };
1841
+ };
1842
+ }
1843
+ function relationValue(all, model, row, relation, args) {
1844
+ const { target, rows: related } = relatedRowsIn(all)(model, row, relation);
1845
+ const nodes = related.map((entry) => stored(target, entry));
1846
+ if (relation.shape === "object") return nodes[0] ?? null;
1847
+ const limited = typeof args.first === "number" ? nodes.slice(0, args.first) : nodes;
1848
+ return relation.shape === "list" ? limited : { nodes: limited, totalCount: nodes.length };
1849
+ }
1850
+ function rootResolvers(all, variables, files) {
1851
+ const related = relatedRowsIn(all);
1852
+ const root = {
1853
+ ...files.rootResolvers((filesModel) => record("upload", filesModel, variables))
1854
+ };
1855
+ for (const model of all) {
1856
+ const ops = model.operations;
1857
+ if (ops.list) {
1858
+ const list = ops.list;
1859
+ root[list.field] = (args) => {
1860
+ const filtered = tableRows(model).filter(
1861
+ (row) => matchesFilter(model, row, args[list.filter?.name ?? "where"], related)
1862
+ );
1863
+ const sorted = sortRows(model, filtered, args[list.orderBy?.name ?? "orderBy"]);
1864
+ const result = page(sorted, args);
1865
+ const nodes = result.nodes.map((row) => stored(model, row));
1866
+ return list.shape === "list" ? nodes : { ...result, nodes };
1867
+ };
1868
+ }
1869
+ if (ops.create) {
1870
+ const create = ops.create;
1871
+ root[create.field] = (args) => {
1872
+ record("create", model, variables);
1873
+ const values = args[create.input.name]?.[create.recordField] ?? {};
1874
+ files.assertFileRefsLive(model, values);
1875
+ const row = {};
1876
+ for (const column of model.columns) {
1877
+ if (Object.prototype.hasOwnProperty.call(values, column.name)) {
1878
+ row[column.name] = storedValue(schema, column, values[column.name], void 0);
1879
+ } else if (column.isPrimaryKey) {
1880
+ row[column.name] = generatedKey(column);
1881
+ } else if (!column.hasDefault) {
1882
+ row[column.name] = null;
1883
+ } else {
1884
+ }
1885
+ }
1886
+ tableRows(model).push(row);
1887
+ return { clientMutationId: null, [create.payloadField]: stored(model, row) };
1888
+ };
1889
+ }
1890
+ if (ops.update) {
1891
+ const update = ops.update;
1892
+ root[update.field] = (args) => {
1893
+ record("update", model, variables);
1894
+ const input = args[update.input.name] ?? {};
1895
+ const key = Object.fromEntries(update.keyArgs.map((field) => [field, input[field]]));
1896
+ const row = tableRows(model).find((candidate) => keyMatches(candidate, key));
1897
+ if (!row || options.writeHidden?.(model.name, row)) return { clientMutationId: null, [update.payloadField]: null };
1898
+ const patch = input[update.patchField] ?? {};
1899
+ files.assertFileRefsLive(model, patch);
1900
+ for (const [field, value] of Object.entries(patch)) {
1901
+ const column = model.columns.find((candidate) => candidate.name === field);
1902
+ row[field] = column ? storedValue(schema, column, value, row[field]) : value;
1903
+ }
1904
+ return { clientMutationId: null, [update.payloadField]: stored(model, row) };
1905
+ };
1906
+ }
1907
+ if (ops.delete) {
1908
+ const remove = ops.delete;
1909
+ root[remove.field] = (args) => {
1910
+ record("delete", model, variables);
1911
+ const input = args[remove.input.name] ?? {};
1912
+ const key = Object.fromEntries(remove.keyArgs.map((field) => [field, input[field]]));
1913
+ const list = tableRows(model);
1914
+ const found = list.findIndex((candidate) => keyMatches(candidate, key));
1915
+ const index = found !== -1 && options.writeHidden?.(model.name, list[found]) ? -1 : found;
1916
+ const [row] = index === -1 ? [] : list.splice(index, 1);
1917
+ return { clientMutationId: null, ...remove.payloadField ? { [remove.payloadField]: row ? stored(model, row) : null } : {} };
1918
+ };
1919
+ }
1920
+ }
1921
+ return root;
1922
+ }
1923
+ const execute = async (document, variables) => {
1924
+ const source = documentSource(document);
1925
+ if (source.includes("ConstructiveMetaContract") && !hasMetaTypes) return createMetaContractFixture();
1926
+ if (/query ConstructiveMeta\b/.test(source)) {
1927
+ const errors = hasMetaTypes ? (0, import_graphql4.validate)(schema, (0, import_graphql4.parse)(source)) : [];
1928
+ if (errors.length > 0) throw import_data7.createError.graphql(errors[0].message);
1929
+ return meta;
1930
+ }
1931
+ if (/\b__(schema|type)\b/.test(source)) return introspect(source, variables);
1932
+ const all = await models();
1933
+ const files = uploadService ??= createUploadService(all, tableRows, options.uploads, uploads);
1934
+ const fieldResolver = (parent, args, context, info) => {
1935
+ const model = parent?.[ROW_MODEL];
1936
+ const computed = model ? files.resolveField(model, parent, info.fieldName) : null;
1937
+ if (computed) return computed.value;
1938
+ const relation = model?.relations.find((candidate) => candidate.fieldName === info.fieldName);
1939
+ if (model && relation) return relationValue(all, model, parent, relation, args);
1940
+ return (0, import_graphql4.defaultFieldResolver)(parent, args, context, info);
1941
+ };
1942
+ const result = await (0, import_graphql4.graphql)({
1943
+ schema,
1944
+ source,
1945
+ variableValues: variables,
1946
+ rootValue: rootResolvers(all, variables, files),
1947
+ fieldResolver
1948
+ });
1949
+ if (result.errors?.length) {
1950
+ const first = result.errors[0];
1951
+ const code = first.extensions?.code;
1952
+ throw withResponseErrors(
1953
+ import_data7.createError.graphql(first.message, typeof code === "string" ? code : void 0),
1954
+ result.data,
1955
+ result.errors
1956
+ );
1957
+ }
1958
+ return result.data;
1959
+ };
1960
+ const confirmUpload = (fileId) => {
1961
+ if (uploadService) {
1962
+ uploadService.confirm(fileId);
1963
+ return;
1964
+ }
1965
+ for (const list of Object.values(rows)) {
1966
+ for (const row of list) if (row.id === fileId && "status" in row) row.status = "uploaded";
1967
+ }
1968
+ };
1969
+ return { execute, mutations, uploads, rows, confirmUpload };
1970
+ }
1971
+
1972
+ // src/testing/mock-sheets-provider.tsx
1973
+ var import_jsx_runtime2 = require("react/jsx-runtime");
1274
1974
  function buildMetaField(field, primaryKeyFields) {
1275
1975
  return {
1276
1976
  name: field.name,
1277
1977
  isPrimaryKey: primaryKeyFields.has(field.name),
1978
+ isForeignKey: false,
1278
1979
  isNotNull: false,
1279
1980
  hasDefault: false,
1981
+ description: null,
1982
+ enumValues: null,
1280
1983
  type: {
1281
1984
  gqlType: field.gqlType,
1282
1985
  isArray: field.isArray ?? false,
1283
1986
  pgType: field.pgType ?? "text",
1284
1987
  isNotNull: false,
1285
1988
  hasDefault: false,
1286
- subtype: field.subtype ?? null
1989
+ subtype: field.subtype ?? null,
1990
+ encoding: null
1287
1991
  }
1288
1992
  };
1289
1993
  }
@@ -1291,162 +1995,59 @@ function buildMetaTable(table) {
1291
1995
  const primaryKeyFields = table.primaryKeyFields ?? (table.fields.some((field) => field.name === "id") ? ["id"] : []);
1292
1996
  const primaryKeySet = new Set(primaryKeyFields);
1293
1997
  const primaryKeyMetaFields = table.fields.filter((field) => primaryKeySet.has(field.name)).map((field) => buildMetaField(field, primaryKeySet));
1998
+ const hasKey = primaryKeyMetaFields.length > 0;
1294
1999
  return {
1295
2000
  name: table.name,
1296
2001
  schemaName: "public",
1297
2002
  query: {
1298
- all: (0, import_data7.toCamelCasePlural)(table.name),
1299
- create: (0, import_data7.toCreateMutationName)(table.name),
1300
- delete: (0, import_data7.toDeleteMutationName)(table.name),
1301
- one: (0, import_data7.toCamelCaseSingular)(table.name),
1302
- update: (0, import_data7.toUpdateMutationName)(table.name)
2003
+ all: (0, import_data8.toCamelCasePlural)(table.name),
2004
+ one: null,
2005
+ create: (0, import_data8.toCreateMutationName)(table.name),
2006
+ update: hasKey ? (0, import_data8.toUpdateMutationName)(table.name) : null,
2007
+ delete: hasKey ? (0, import_data8.toDeleteMutationName)(table.name) : null
1303
2008
  },
1304
2009
  fields: table.fields.map((field) => buildMetaField(field, primaryKeySet)),
1305
2010
  inflection: {
1306
- allRows: (0, import_data7.toCamelCasePlural)(table.name),
1307
- connection: (0, import_data7.toCamelCasePlural)(table.name),
1308
- tableType: table.name
2011
+ tableType: table.name,
2012
+ allRows: (0, import_data8.toCamelCasePlural)(table.name),
2013
+ connection: `${table.name}Connection`,
2014
+ filterType: `${table.name}Filter`,
2015
+ orderByType: `${table.name}OrderBy`
1309
2016
  },
1310
2017
  indexes: [],
1311
2018
  constraints: {
1312
- primaryKey: primaryKeyMetaFields.length > 0 ? { name: `${table.name}_pkey`, fields: primaryKeyMetaFields } : null,
2019
+ primaryKey: hasKey ? { name: `${table.name}_pkey`, fields: primaryKeyMetaFields } : null,
1313
2020
  unique: [],
1314
2021
  foreignKey: []
1315
2022
  },
1316
2023
  foreignKeyConstraints: [],
1317
- primaryKeyConstraints: primaryKeyMetaFields.length > 0 ? [{ name: `${table.name}_pkey`, fields: primaryKeyMetaFields }] : [],
2024
+ primaryKeyConstraints: hasKey ? [{ name: `${table.name}_pkey`, fields: primaryKeyMetaFields }] : [],
1318
2025
  uniqueConstraints: [],
1319
- relations: { belongsTo: [], has: [], hasOne: [], hasMany: [], manyToMany: [] }
2026
+ relations: { belongsTo: [], has: [], hasOne: [], hasMany: [], manyToMany: [] },
2027
+ storage: null,
2028
+ search: null,
2029
+ i18n: null,
2030
+ realtime: null,
2031
+ scope: null
1320
2032
  };
1321
2033
  }
1322
2034
  function buildMetaResponse(tables) {
1323
- return {
1324
- _meta: {
1325
- tables: tables.map(buildMetaTable)
1326
- }
1327
- };
1328
- }
1329
- function buildListResponse(table) {
1330
- const field = (0, import_data7.toCamelCasePlural)(table.name);
1331
- return {
1332
- [field]: {
1333
- nodes: table.rows,
1334
- totalCount: table.rows.length,
1335
- pageInfo: {
1336
- hasNextPage: false,
1337
- hasPreviousPage: false,
1338
- endCursor: null,
1339
- startCursor: null
1340
- }
1341
- }
1342
- };
1343
- }
1344
- var mockIdCounter = 0;
1345
- function synthesizeId() {
1346
- mockIdCounter += 1;
1347
- return `mock-${mockIdCounter}`;
1348
- }
1349
- function extractMutationInput(variables) {
1350
- const input = variables?.input;
1351
- return input && typeof input === "object" ? input : {};
1352
- }
1353
- function synthesizeCreatedRow(table, singular, variables) {
1354
- const input = extractMutationInput(variables);
1355
- const data = input[singular] ?? {};
1356
- const row = { id: synthesizeId(), ...data };
1357
- table.rows.push(row);
1358
- return row;
1359
- }
1360
- function synthesizeUpdatedRow(table, variables) {
1361
- const input = extractMutationInput(variables);
1362
- const id = input.id;
1363
- let patch = {};
1364
- for (const [key, value] of Object.entries(input)) {
1365
- if (key === "id") continue;
1366
- if (value && typeof value === "object") {
1367
- patch = value;
1368
- break;
1369
- }
1370
- }
1371
- const existing = table.rows.find((r) => r.id === id);
1372
- const merged = { ...existing ?? { id }, ...patch };
1373
- if (existing) {
1374
- Object.assign(existing, patch);
1375
- } else {
1376
- table.rows.push(merged);
1377
- }
1378
- return merged;
1379
- }
1380
- function isMetaQuery(query) {
1381
- return query.includes("_meta");
1382
- }
1383
- function isMutationDocument(query) {
1384
- return /(^|\s)mutation(\s|\{)/.test(query);
1385
- }
1386
- function findMutationTable(query, tables) {
1387
- let best = null;
1388
- for (const table of tables) {
1389
- const candidates = [
1390
- { op: "create", mutationName: (0, import_data7.toCreateMutationName)(table.name) },
1391
- { op: "update", mutationName: (0, import_data7.toUpdateMutationName)(table.name) },
1392
- { op: "delete", mutationName: (0, import_data7.toDeleteMutationName)(table.name) }
1393
- ];
1394
- for (const c of candidates) {
1395
- if (query.includes(c.mutationName) && (!best || c.mutationName.length > best.mutationName.length)) {
1396
- best = { table, op: c.op, mutationName: c.mutationName, singular: (0, import_data7.toCamelCaseSingular)(table.name) };
1397
- }
1398
- }
1399
- }
1400
- return best;
1401
- }
1402
- function findListTable(query, tables) {
1403
- let best = null;
1404
- let bestLen = 0;
1405
- for (const table of tables) {
1406
- const plural = (0, import_data7.toCamelCasePlural)(table.name);
1407
- if (query.includes(plural) && plural.length > bestLen) {
1408
- best = table;
1409
- bestLen = plural.length;
1410
- }
1411
- }
1412
- return best;
2035
+ return { _meta: { tables: tables.map(buildMetaTable) } };
1413
2036
  }
1414
2037
  function createMockExecute(opts) {
1415
- const mutations = [];
1416
- function record(m) {
1417
- mutations.push(m);
1418
- opts.onMutation?.(m);
1419
- }
1420
- const execute = async (document, variables) => {
1421
- const query = documentToString2(document);
1422
- if (query.includes("ConstructiveMetaContract")) {
1423
- return createMetaContractFixture();
1424
- }
1425
- if (isMetaQuery(query)) {
1426
- return buildMetaResponse(opts.tables);
1427
- }
1428
- const mutationMatch = isMutationDocument(query) ? findMutationTable(query, opts.tables) : null;
1429
- if (mutationMatch) {
1430
- const { table, op, mutationName, singular } = mutationMatch;
1431
- record({ op, tableName: table.name, variables: variables ?? {}, at: Date.now() });
1432
- if (op === "delete") {
1433
- const input = extractMutationInput(variables);
1434
- const id = input.id ?? null;
1435
- table.rows = table.rows.filter((r) => r.id !== id);
1436
- return { [mutationName]: { deletedNodeId: id, clientMutationId: null } };
1437
- }
1438
- const row = op === "create" ? synthesizeCreatedRow(table, singular, variables) : synthesizeUpdatedRow(table, variables);
1439
- return { [mutationName]: { [singular]: row } };
1440
- }
1441
- const listTable = findListTable(query, opts.tables);
1442
- if (listTable) {
1443
- return buildListResponse(listTable);
1444
- }
1445
- return {};
1446
- };
2038
+ const meta = buildMetaResponse(opts.tables);
2039
+ const metaTables = (meta._meta?.tables ?? []).filter((table) => table != null);
2040
+ const backend = createModelBackend({
2041
+ schema: (0, import_graphql5.buildSchema)(buildMetaSchemaSdl(metaTables)),
2042
+ meta,
2043
+ // The row arrays are shared with the caller's MockTables, so tests see writes in place.
2044
+ rows: Object.fromEntries(opts.tables.map((table) => [table.name, table.rows])),
2045
+ onMutation: opts.onMutation
2046
+ });
2047
+ const { mutations } = backend;
1447
2048
  const executeUpload = async (file, path, options) => {
1448
2049
  const name = file?.name ?? "file";
1449
- record({
2050
+ const upload = {
1450
2051
  op: "upload",
1451
2052
  tableName: options?.tableName ?? "",
1452
2053
  variables: {
@@ -1456,13 +2057,27 @@ function createMockExecute(opts) {
1456
2057
  ...options?.recordId !== void 0 && { recordId: options.recordId }
1457
2058
  },
1458
2059
  at: Date.now()
1459
- });
1460
- return { url: "mock://uploaded/" + name };
2060
+ };
2061
+ mutations.push(upload);
2062
+ opts.onMutation?.(upload);
2063
+ const url = "mock://uploaded/" + name;
2064
+ return {
2065
+ file: {
2066
+ id: "mock-file-" + mutations.length,
2067
+ key: name,
2068
+ bucket_id: "mock-bucket",
2069
+ filename: name,
2070
+ mime: file.type || "application/octet-stream",
2071
+ size: file.size,
2072
+ url
2073
+ },
2074
+ url
2075
+ };
1461
2076
  };
1462
2077
  function reset() {
1463
2078
  mutations.length = 0;
1464
2079
  }
1465
- return { execute, executeUpload, mutations, reset };
2080
+ return { execute: backend.execute, executeUpload, mutations, reset };
1466
2081
  }
1467
2082
  function MockSheetsProvider({ options, children }) {
1468
2083
  const { execute, executeUpload } = (0, import_react4.useMemo)(() => createMockExecute(options), []);