@constructive-io/sheets 0.14.1 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +231 -157
- package/dist/advanced.cjs +7192 -3840
- package/dist/advanced.cjs.map +1 -1
- package/dist/advanced.d.cts +2 -2
- package/dist/advanced.d.ts +2 -2
- package/dist/advanced.js +5 -5
- package/dist/auth.cjs.map +1 -1
- package/dist/auth.js +3 -3
- package/dist/chunk-CJ4PRA64.js +312 -0
- package/dist/chunk-CJ4PRA64.js.map +1 -0
- package/dist/chunk-II3MSNRO.js +18 -0
- package/dist/chunk-II3MSNRO.js.map +1 -0
- package/dist/{chunk-BYAYBXVB.js → chunk-J7KK4UWI.js} +6 -6
- package/dist/chunk-MBSHDF55.js +839 -0
- package/dist/chunk-MBSHDF55.js.map +1 -0
- package/dist/chunk-MOFFS5WQ.js +128 -0
- package/dist/chunk-MOFFS5WQ.js.map +1 -0
- package/dist/chunk-VCBY2AMT.js +8920 -0
- package/dist/chunk-VCBY2AMT.js.map +1 -0
- package/dist/{chunk-YJZFHL2D.js → chunk-ZOQDSOMO.js} +50 -312
- package/dist/chunk-ZOQDSOMO.js.map +1 -0
- package/dist/date-editor-ORCB43ZM.js +346 -0
- package/dist/date-editor-ORCB43ZM.js.map +1 -0
- package/dist/{grid-cell-types-C2-ocDS7.d.cts → grid-cell-types-YNIVK4hN.d.cts} +71 -18
- package/dist/{grid-cell-types-C2-ocDS7.d.ts → grid-cell-types-YNIVK4hN.d.ts} +71 -18
- package/dist/index.cjs +22733 -12052
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1432 -266
- package/dist/index.d.ts +1432 -266
- package/dist/index.js +12688 -6097
- package/dist/index.js.map +1 -1
- package/dist/sheets-context-Bb7ZoNBg.d.cts +436 -0
- package/dist/sheets-context-CPuf31LS.d.ts +436 -0
- package/dist/testing.cjs +1170 -589
- package/dist/testing.cjs.map +1 -1
- package/dist/testing.d.cts +80 -11
- package/dist/testing.d.ts +80 -11
- package/dist/testing.js +778 -147
- package/dist/testing.js.map +1 -1
- package/package.json +4 -5
- package/dist/chunk-4EZ6A23C.js +0 -44
- package/dist/chunk-4EZ6A23C.js.map +0 -1
- package/dist/chunk-6Y7CZ5VS.js +0 -168
- package/dist/chunk-6Y7CZ5VS.js.map +0 -1
- package/dist/chunk-BGL6EBTE.js +0 -446
- package/dist/chunk-BGL6EBTE.js.map +0 -1
- package/dist/chunk-ER3FIDK7.js +0 -4383
- package/dist/chunk-ER3FIDK7.js.map +0 -1
- package/dist/chunk-GZM2CSTR.js +0 -279
- package/dist/chunk-GZM2CSTR.js.map +0 -1
- package/dist/chunk-X7DHTSOX.js +0 -21
- package/dist/chunk-X7DHTSOX.js.map +0 -1
- package/dist/chunk-YJZFHL2D.js.map +0 -1
- package/dist/date-editor-G26WKILO.js +0 -358
- package/dist/date-editor-G26WKILO.js.map +0 -1
- package/dist/map-picker-ZUGGOIZS.js +0 -290
- package/dist/map-picker-ZUGGOIZS.js.map +0 -1
- package/dist/sheets-context-CHUVJCff.d.ts +0 -245
- package/dist/sheets-context-C_MkTxXm.d.cts +0 -245
- /package/dist/{chunk-BYAYBXVB.js.map → chunk-J7KK4UWI.js.map} +0 -0
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
|
|
35
|
+
var import_graphql5 = require("graphql");
|
|
34
36
|
var import_react_query2 = require("@tanstack/react-query");
|
|
35
|
-
var
|
|
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,23 +47,14 @@ 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
|
|
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.");
|
|
56
|
-
}
|
|
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
58
|
var capabilityCache = /* @__PURE__ */ new WeakMap();
|
|
66
59
|
async function discoverStorageCapabilities(endpoint, execute) {
|
|
67
60
|
let endpoints = capabilityCache.get(execute);
|
|
@@ -74,17 +67,20 @@ async function discoverStorageCapabilities(endpoint, execute) {
|
|
|
74
67
|
const promise = (async () => {
|
|
75
68
|
const data = await execute((0, import_graphql.getIntrospectionQuery)());
|
|
76
69
|
const schema = data?.__schema;
|
|
77
|
-
if (!schema)
|
|
78
|
-
throw import_data.createError.badRequest("Uploads are not enabled for this endpoint.");
|
|
79
|
-
}
|
|
70
|
+
if (!schema) throw import_data.createError.badRequest("Uploads are not enabled for this endpoint.");
|
|
80
71
|
return resolveStorageCapabilities(schema);
|
|
81
72
|
})();
|
|
82
73
|
promise.catch(() => endpoints.delete(endpoint));
|
|
83
74
|
endpoints.set(endpoint, promise);
|
|
84
75
|
return promise;
|
|
85
76
|
}
|
|
86
|
-
async function discoverUploadCapability(endpoint, execute) {
|
|
87
|
-
const { upload } = await discoverStorageCapabilities(endpoint, execute);
|
|
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
|
+
}
|
|
88
84
|
if (!upload) capabilityCache.get(execute)?.delete(endpoint);
|
|
89
85
|
return requireUploadCapability(upload);
|
|
90
86
|
}
|
|
@@ -94,16 +90,12 @@ function requireUploadCapability(upload) {
|
|
|
94
90
|
}
|
|
95
91
|
function namedTypeName(ref) {
|
|
96
92
|
let cur = ref;
|
|
97
|
-
while (cur && (cur.kind === "NON_NULL" || cur.kind === "LIST"))
|
|
98
|
-
cur = cur.ofType ?? null;
|
|
99
|
-
}
|
|
93
|
+
while (cur && (cur.kind === "NON_NULL" || cur.kind === "LIST")) cur = cur.ofType ?? null;
|
|
100
94
|
return cur?.name ?? null;
|
|
101
95
|
}
|
|
102
96
|
function isListTypeRef(ref) {
|
|
103
97
|
let cur = ref;
|
|
104
|
-
while (cur && cur.kind === "NON_NULL")
|
|
105
|
-
cur = cur.ofType ?? null;
|
|
106
|
-
}
|
|
98
|
+
while (cur && cur.kind === "NON_NULL") cur = cur.ofType ?? null;
|
|
107
99
|
return cur?.kind === "LIST";
|
|
108
100
|
}
|
|
109
101
|
var PK_FIELD_NAME = "id";
|
|
@@ -113,50 +105,49 @@ function resolveStorageCapabilities(schema) {
|
|
|
113
105
|
if (t.name) typeByName.set(t.name, t);
|
|
114
106
|
}
|
|
115
107
|
const objectHasFields = (typeName, names) => {
|
|
116
|
-
|
|
117
|
-
const t = typeByName.get(typeName);
|
|
108
|
+
const t = typeName ? typeByName.get(typeName) : void 0;
|
|
118
109
|
if (!t?.fields) return false;
|
|
119
110
|
const present = new Set(t.fields.map((f) => f.name));
|
|
120
111
|
return names.every((n) => present.has(n));
|
|
121
112
|
};
|
|
122
113
|
const inputHasFields = (typeName, names) => {
|
|
123
|
-
|
|
124
|
-
const t = typeByName.get(typeName);
|
|
114
|
+
const t = typeName ? typeByName.get(typeName) : void 0;
|
|
125
115
|
if (!t?.inputFields) return false;
|
|
126
116
|
const present = new Set(t.inputFields.map((f) => f.name));
|
|
127
117
|
return names.every((n) => present.has(n));
|
|
128
118
|
};
|
|
129
119
|
const PAYLOAD_FIELDS = ["uploadUrl", "fileId", "key", "deduplicated"];
|
|
130
|
-
const INPUT_FIELDS = ["contentHash", "
|
|
120
|
+
const INPUT_FIELDS = ["contentHash", "contentType", "size"];
|
|
121
|
+
const LEGACY_INPUT_FIELDS = [...INPUT_FIELDS, "bucketKey"];
|
|
131
122
|
const mutationType = schema.mutationType ? typeByName.get(schema.mutationType.name) : null;
|
|
132
123
|
const queryType = schema.queryType ? typeByName.get(schema.queryType.name) : null;
|
|
133
124
|
let upload = null;
|
|
125
|
+
const uploads = [];
|
|
134
126
|
for (const field of mutationType?.fields ?? []) {
|
|
135
127
|
const inputArg = field.args.find((a) => a.name === "input");
|
|
136
128
|
if (!inputArg) continue;
|
|
137
129
|
const inputTypeName = namedTypeName(inputArg.type);
|
|
138
130
|
const payloadTypeName = namedTypeName(field.type);
|
|
139
131
|
if (inputTypeName && inputHasFields(inputTypeName, INPUT_FIELDS) && objectHasFields(payloadTypeName, PAYLOAD_FIELDS)) {
|
|
140
|
-
const payloadFields = typeByName.get(payloadTypeName ?? "")?.fields;
|
|
132
|
+
const payloadFields = typeByName.get(payloadTypeName ?? "")?.fields ?? [];
|
|
141
133
|
const candidate = {
|
|
142
134
|
uploadFieldName: field.name,
|
|
143
135
|
inputTypeName,
|
|
144
|
-
hasFileProjection: payloadFields
|
|
136
|
+
hasFileProjection: payloadFields.some(
|
|
145
137
|
(f) => f.name === "file" && !isListTypeRef(f.type) && namedTypeName(f.type) === "JSON"
|
|
146
|
-
)
|
|
138
|
+
),
|
|
139
|
+
payloadFieldNames: payloadFields.map((f) => f.name),
|
|
140
|
+
inputFieldNames: (typeByName.get(inputTypeName)?.inputFields ?? []).map((f) => f.name)
|
|
147
141
|
};
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
upload ??= candidate;
|
|
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;
|
|
153
146
|
}
|
|
154
147
|
}
|
|
155
148
|
const fileTypes = /* @__PURE__ */ new Set();
|
|
156
149
|
for (const t of schema.types) {
|
|
157
|
-
if (t.kind === "OBJECT" && t.name && t.fields?.some((f) => f.name === "downloadUrl"))
|
|
158
|
-
fileTypes.add(t.name);
|
|
159
|
-
}
|
|
150
|
+
if (t.kind === "OBJECT" && t.name && t.fields?.some((f) => f.name === "downloadUrl")) fileTypes.add(t.name);
|
|
160
151
|
}
|
|
161
152
|
const uploadType = upload?.uploadFieldName.replace(/^upload/, "") ?? "AppFile";
|
|
162
153
|
const uploadDownload = resolveDownloadByIdField(typeByName, queryType, fileTypes, uploadType);
|
|
@@ -164,8 +155,15 @@ function resolveStorageCapabilities(schema) {
|
|
|
164
155
|
const previewType = fileTypes.has(preferredPreviewType) ? preferredPreviewType : uploadDownload?.fileTypeName ?? preferredPreviewType;
|
|
165
156
|
const download = previewType === uploadType ? uploadDownload : resolveDownloadByIdField(typeByName, queryType, fileTypes, previewType);
|
|
166
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;
|
|
167
163
|
return {
|
|
168
164
|
upload: upload ? { ...upload, download: uploadDownload } : null,
|
|
165
|
+
uploads,
|
|
166
|
+
sole,
|
|
169
167
|
download,
|
|
170
168
|
batch
|
|
171
169
|
};
|
|
@@ -189,9 +187,7 @@ function resolveDownloadByIdField(typeByName, queryType, fileTypesWithDownloadUr
|
|
|
189
187
|
const connection = resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, preferred);
|
|
190
188
|
if (connection?.fileTypeName === preferred) return connection;
|
|
191
189
|
if (singular || connection) return singular ?? connection;
|
|
192
|
-
const nodeField = queryType?.fields?.find(
|
|
193
|
-
(f) => f.name === "node" && f.args.some((a) => a.name === "nodeId")
|
|
194
|
-
);
|
|
190
|
+
const nodeField = queryType?.fields?.find((f) => f.name === "node" && f.args.some((a) => a.name === "nodeId"));
|
|
195
191
|
if (nodeField && fileTypesWithDownloadUrl.size > 0) {
|
|
196
192
|
const fileTypeName = fileTypesWithDownloadUrl.has(preferred) ? preferred : [...fileTypesWithDownloadUrl][0];
|
|
197
193
|
return { fileByIdField: "node", fileByIdArgName: "nodeId", fileTypeName };
|
|
@@ -213,7 +209,7 @@ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDown
|
|
|
213
209
|
});
|
|
214
210
|
if (!nodesField) continue;
|
|
215
211
|
const fileTypeName = namedTypeName(nodesField.type);
|
|
216
|
-
if (batch && (fileTypeName !== preferred || !typeByName.get(fileTypeName)?.fields?.some((
|
|
212
|
+
if (batch && (fileTypeName !== preferred || !typeByName.get(fileTypeName)?.fields?.some((candidate) => candidate.name === PK_FIELD_NAME))) continue;
|
|
217
213
|
const connectionHasFirst = field.args.some((arg) => arg.name === "first");
|
|
218
214
|
for (const arg of field.args) {
|
|
219
215
|
const filterTypeName = namedTypeName(arg.type);
|
|
@@ -224,9 +220,8 @@ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDown
|
|
|
224
220
|
const idFieldTypeName = namedTypeName(idField.type);
|
|
225
221
|
const idFieldType = idFieldTypeName ? typeByName.get(idFieldTypeName) : null;
|
|
226
222
|
if (idFieldType?.kind === "INPUT_OBJECT" && idFieldType.inputFields) {
|
|
227
|
-
const
|
|
228
|
-
|
|
229
|
-
).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);
|
|
230
225
|
if (opField) {
|
|
231
226
|
candidates.push({
|
|
232
227
|
fileByIdField: field.name,
|
|
@@ -261,88 +256,70 @@ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDown
|
|
|
261
256
|
if (candidates.length === 0) return null;
|
|
262
257
|
return candidates.find((c) => c.fileTypeName === preferred) ?? candidates[0];
|
|
263
258
|
}
|
|
264
|
-
|
|
265
|
-
const
|
|
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 `
|
|
266
274
|
mutation SheetsUpload($input: ${cap.inputTypeName}!) {
|
|
267
275
|
${cap.uploadFieldName}(input: $input) {
|
|
268
|
-
|
|
269
|
-
fileId
|
|
270
|
-
key
|
|
271
|
-
deduplicated
|
|
272
|
-
file
|
|
276
|
+
${payloadFields.join("\n ")}
|
|
273
277
|
}
|
|
274
278
|
}
|
|
275
279
|
`.trim();
|
|
276
|
-
const data = await execute(mutation, {
|
|
277
|
-
input: {
|
|
278
|
-
...input.bucketKey === void 0 ? { isPublic: true } : { bucketKey: input.bucketKey },
|
|
279
|
-
contentHash: input.contentHash,
|
|
280
|
-
contentType: input.contentType,
|
|
281
|
-
size: input.size,
|
|
282
|
-
filename: input.filename
|
|
283
|
-
}
|
|
284
|
-
});
|
|
285
|
-
const payload = data?.[cap.uploadFieldName];
|
|
286
|
-
if (!payload) {
|
|
287
|
-
throw import_data.createError.badRequest("Upload failed: no payload returned from upload mutation.");
|
|
288
|
-
}
|
|
289
|
-
const file = payload.file;
|
|
290
|
-
if (!file || typeof file.id !== "string" || typeof file.key !== "string" || typeof file.bucket_id !== "string" || typeof file.mime !== "string" || typeof file.size !== "number") {
|
|
291
|
-
throw import_data.createError.badRequest("Upload failed: server returned an invalid file projection.");
|
|
292
|
-
}
|
|
293
|
-
return payload;
|
|
294
280
|
}
|
|
295
|
-
var
|
|
296
|
-
function
|
|
297
|
-
|
|
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]);
|
|
298
286
|
}
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
response = await fetch(url, {
|
|
308
|
-
method: "PUT",
|
|
309
|
-
headers: { "Content-Type": contentType },
|
|
310
|
-
body: buffer
|
|
311
|
-
});
|
|
312
|
-
} catch {
|
|
313
|
-
throw storageUnreachableError();
|
|
314
|
-
}
|
|
315
|
-
if (!response.ok) {
|
|
316
|
-
const body = await response.text().catch(() => "");
|
|
317
|
-
throw import_data.createError.badRequest(`Upload failed: ${response.status} ${response.statusText}${body ? ` \u2014 ${body}` : ""}`);
|
|
318
|
-
}
|
|
319
|
-
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
|
+
};
|
|
320
295
|
}
|
|
321
|
-
function
|
|
322
|
-
return
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
})
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
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
|
+
};
|
|
346
323
|
}
|
|
347
324
|
function toGlobalId(typeName, id) {
|
|
348
325
|
if (typeof btoa !== "function") {
|
|
@@ -351,6 +328,7 @@ function toGlobalId(typeName, id) {
|
|
|
351
328
|
return btoa(JSON.stringify([typeName, id]));
|
|
352
329
|
}
|
|
353
330
|
async function fetchDownloadUrl(execute, cap, fileId) {
|
|
331
|
+
const missing = () => import_data.createError.badRequest("Upload succeeded but no downloadUrl was returned for the file.");
|
|
354
332
|
if (cap.fileByIdArgName === "nodeId") {
|
|
355
333
|
const nodeId = toGlobalId(cap.fileTypeName, fileId);
|
|
356
334
|
const query2 = `
|
|
@@ -363,11 +341,8 @@ async function fetchDownloadUrl(execute, cap, fileId) {
|
|
|
363
341
|
}
|
|
364
342
|
`.trim();
|
|
365
343
|
const data2 = await execute(query2, { nodeId });
|
|
366
|
-
const
|
|
367
|
-
|
|
368
|
-
if (!url2) {
|
|
369
|
-
throw import_data.createError.badRequest("Upload succeeded but no downloadUrl was returned for the file.");
|
|
370
|
-
}
|
|
344
|
+
const url2 = data2?.[cap.fileByIdField]?.downloadUrl;
|
|
345
|
+
if (!url2) throw missing();
|
|
371
346
|
return url2;
|
|
372
347
|
}
|
|
373
348
|
if (cap.fileByIdArgName === "connection") {
|
|
@@ -389,11 +364,8 @@ async function fetchDownloadUrl(execute, cap, fileId) {
|
|
|
389
364
|
query2,
|
|
390
365
|
{ id: fileId }
|
|
391
366
|
);
|
|
392
|
-
const
|
|
393
|
-
|
|
394
|
-
if (!url2) {
|
|
395
|
-
throw import_data.createError.badRequest("Upload succeeded but no downloadUrl was returned for the file.");
|
|
396
|
-
}
|
|
367
|
+
const url2 = data2?.[cap.fileByIdField]?.[nodesField]?.[0]?.downloadUrl;
|
|
368
|
+
if (!url2) throw missing();
|
|
397
369
|
return url2;
|
|
398
370
|
}
|
|
399
371
|
const idScalar = cap.idScalarName ?? "ID";
|
|
@@ -406,16 +378,258 @@ async function fetchDownloadUrl(execute, cap, fileId) {
|
|
|
406
378
|
}
|
|
407
379
|
`.trim();
|
|
408
380
|
const data = await execute(query, { id: fileId });
|
|
409
|
-
const
|
|
410
|
-
|
|
411
|
-
if (!url) {
|
|
412
|
-
throw import_data.createError.badRequest("Upload succeeded but no downloadUrl was returned for the file.");
|
|
413
|
-
}
|
|
381
|
+
const url = data?.[cap.fileByIdField]?.downloadUrl;
|
|
382
|
+
if (!url) throw missing();
|
|
414
383
|
return url;
|
|
415
384
|
}
|
|
416
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
|
+
|
|
417
631
|
// src/context/sheets-execute.ts
|
|
418
|
-
var
|
|
632
|
+
var import_data4 = require("@constructive-io/data");
|
|
419
633
|
function documentToString(document) {
|
|
420
634
|
if (typeof document === "string") return document;
|
|
421
635
|
if (document instanceof String) return document.toString();
|
|
@@ -423,33 +637,43 @@ function documentToString(document) {
|
|
|
423
637
|
return (0, import_graphql2.print)(document);
|
|
424
638
|
}
|
|
425
639
|
if (document === null || document === void 0) {
|
|
426
|
-
throw
|
|
640
|
+
throw import_data3.createError.badRequest("Invalid GraphQL document: null or undefined");
|
|
427
641
|
}
|
|
428
642
|
return String(document);
|
|
429
643
|
}
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
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;
|
|
433
656
|
}
|
|
434
657
|
function parseGraphQLResponse(response, onAuthError) {
|
|
435
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
|
+
}
|
|
436
663
|
const error = response.errors[0];
|
|
437
664
|
const code = error.extensions?.code;
|
|
438
665
|
const message = error.message || "GraphQL query failed";
|
|
439
|
-
if (code === "
|
|
440
|
-
onAuthError?.();
|
|
441
|
-
return import_data2.createError.unauthorized("Authentication required. Please log in again.");
|
|
442
|
-
}
|
|
666
|
+
if (code === "ACCESS_SUSPENDED") return (0, import_data3.parseGraphQLError)(error);
|
|
443
667
|
if (code === "FORBIDDEN") {
|
|
444
|
-
return
|
|
668
|
+
return import_data3.createError.forbidden("You do not have permission to perform this action.");
|
|
445
669
|
}
|
|
446
|
-
return
|
|
670
|
+
return import_data3.createError.graphql(message, code);
|
|
447
671
|
}
|
|
448
672
|
function createSheetsExecute(config, getToken) {
|
|
449
|
-
return async (document, variables) => {
|
|
673
|
+
return async (document, variables, options) => {
|
|
450
674
|
const url = config.endpoint;
|
|
451
675
|
if (!url) {
|
|
452
|
-
throw
|
|
676
|
+
throw import_data3.createError.badRequest("No GraphQL endpoint configured.");
|
|
453
677
|
}
|
|
454
678
|
const token = getToken();
|
|
455
679
|
const headers = {
|
|
@@ -467,37 +691,46 @@ function createSheetsExecute(config, getToken) {
|
|
|
467
691
|
body: JSON.stringify({
|
|
468
692
|
query: documentToString(document),
|
|
469
693
|
...variables !== void 0 && { variables }
|
|
470
|
-
})
|
|
694
|
+
}),
|
|
695
|
+
...options?.signal ? { signal: options.signal } : {}
|
|
471
696
|
});
|
|
472
697
|
} catch (error) {
|
|
473
|
-
throw
|
|
698
|
+
throw import_data3.createError.network(error instanceof Error ? error : void 0);
|
|
474
699
|
}
|
|
475
700
|
if (!response.ok) {
|
|
476
701
|
const { status, statusText } = response;
|
|
477
702
|
if (status === 401) {
|
|
478
703
|
config.onAuthError?.();
|
|
479
|
-
throw
|
|
704
|
+
throw import_data3.createError.unauthorized("Authentication required. Please log in again.");
|
|
480
705
|
}
|
|
481
706
|
if (status === 403) {
|
|
482
|
-
|
|
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;
|
|
483
711
|
}
|
|
484
712
|
if (status === 404) {
|
|
485
|
-
throw
|
|
713
|
+
throw import_data3.createError.notFound("The requested endpoint does not exist.");
|
|
486
714
|
}
|
|
487
715
|
try {
|
|
488
716
|
const body = await response.json();
|
|
489
717
|
if (body.errors?.length) {
|
|
490
|
-
throw
|
|
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
|
+
);
|
|
491
723
|
}
|
|
492
724
|
} catch (e) {
|
|
493
|
-
if (e instanceof
|
|
725
|
+
if (e instanceof import_data3.ConstructiveError) throw e;
|
|
494
726
|
}
|
|
495
|
-
throw
|
|
727
|
+
throw import_data3.createError.badRequest(`Request failed: ${status} ${statusText}`);
|
|
496
728
|
}
|
|
497
729
|
const result = await response.json();
|
|
498
730
|
const graphqlError = parseGraphQLResponse(result, config.onAuthError);
|
|
499
731
|
if (graphqlError) {
|
|
500
|
-
|
|
732
|
+
const keepsData = !["UNAUTHENTICATED", "ACCESS_SUSPENDED"].includes(graphqlError.code);
|
|
733
|
+
throw withResponseErrors(graphqlError, keepsData ? result.data : null, result.errors ?? []);
|
|
501
734
|
}
|
|
502
735
|
return result.data;
|
|
503
736
|
};
|
|
@@ -510,44 +743,6 @@ function resolveStorageTransport(config, getToken) {
|
|
|
510
743
|
execute: config.storage?.execute ?? createSheetsExecute({ ...config, endpoint }, getToken)
|
|
511
744
|
};
|
|
512
745
|
}
|
|
513
|
-
function createPresignedSheetsUpload({ endpoint, execute }, bucketKey) {
|
|
514
|
-
return async (file, _path, options) => {
|
|
515
|
-
if (!endpoint) {
|
|
516
|
-
throw import_data2.createError.badRequest("No GraphQL endpoint configured.");
|
|
517
|
-
}
|
|
518
|
-
const cap = await discoverUploadCapability(endpoint, execute);
|
|
519
|
-
if (!cap.hasFileProjection) {
|
|
520
|
-
throw import_data2.createError.badRequest("Uploads require a storage mutation that returns a file projection.");
|
|
521
|
-
}
|
|
522
|
-
const contentType = file.type || "application/octet-stream";
|
|
523
|
-
const buffer = await file.arrayBuffer();
|
|
524
|
-
const contentHash = await sha256HexFromBuffer(buffer);
|
|
525
|
-
const payload = await callUploadOp(execute, cap, {
|
|
526
|
-
bucketKey,
|
|
527
|
-
contentHash,
|
|
528
|
-
contentType,
|
|
529
|
-
size: file.size,
|
|
530
|
-
filename: file.name
|
|
531
|
-
});
|
|
532
|
-
if (!payload.deduplicated) {
|
|
533
|
-
if (!payload.uploadUrl) {
|
|
534
|
-
throw import_data2.createError.badRequest("Upload failed: server returned no uploadUrl for a non-deduplicated file.");
|
|
535
|
-
}
|
|
536
|
-
await presignedPut(payload.uploadUrl, buffer, contentType, options?.onProgress);
|
|
537
|
-
} else {
|
|
538
|
-
options?.onProgress?.({ loaded: file.size, total: file.size, percentage: 100 });
|
|
539
|
-
}
|
|
540
|
-
const result = {
|
|
541
|
-
file: { ...payload.file, filename: payload.file.filename ?? file.name }
|
|
542
|
-
};
|
|
543
|
-
if (!cap.download) return result;
|
|
544
|
-
try {
|
|
545
|
-
return { ...result, url: await fetchDownloadUrl(execute, cap.download, payload.fileId) };
|
|
546
|
-
} catch {
|
|
547
|
-
return result;
|
|
548
|
-
}
|
|
549
|
-
};
|
|
550
|
-
}
|
|
551
746
|
|
|
552
747
|
// src/store/sheets-store.ts
|
|
553
748
|
var import_react2 = require("react");
|
|
@@ -571,7 +766,7 @@ function createDraftRowsSlice(set) {
|
|
|
571
766
|
const effectiveColumnOrder = ensureColumnOrder(columnOrder, fieldMetaByKey, relationInfoByKey);
|
|
572
767
|
const template = buildTemplate(effectiveColumnOrder, relationInfoByKey);
|
|
573
768
|
const draftRowId = `draft:${generateDraftSuffix()}`;
|
|
574
|
-
const values = initializeValuesFromTemplate(template
|
|
769
|
+
const values = initializeValuesFromTemplate(template);
|
|
575
770
|
set((state) => {
|
|
576
771
|
const existing = state.draftRowsByTable[tableKey];
|
|
577
772
|
const nextOrder = existing ? [...existing.order, draftRowId] : [draftRowId];
|
|
@@ -712,7 +907,7 @@ function createDraftRowsSlice(set) {
|
|
|
712
907
|
for (const draftId of tableState.order) {
|
|
713
908
|
const row = tableState.map[draftId];
|
|
714
909
|
if (!row) continue;
|
|
715
|
-
const mergedValues = initializeValuesFromTemplate(template
|
|
910
|
+
const mergedValues = initializeValuesFromTemplate(template);
|
|
716
911
|
for (const key of Object.keys(row.values)) {
|
|
717
912
|
if (Object.prototype.hasOwnProperty.call(template, key)) {
|
|
718
913
|
mergedValues[key] = deepClone(row.values[key]);
|
|
@@ -783,7 +978,7 @@ function buildTemplate(columnOrder, relationInfoByKey) {
|
|
|
783
978
|
if (relationInfo && (relationInfo.kind === "hasMany" || relationInfo.kind === "manyToMany")) {
|
|
784
979
|
template[column] = [];
|
|
785
980
|
} else {
|
|
786
|
-
template[column] =
|
|
981
|
+
template[column] = void 0;
|
|
787
982
|
}
|
|
788
983
|
}
|
|
789
984
|
return template;
|
|
@@ -797,12 +992,11 @@ function generateDraftSuffix() {
|
|
|
797
992
|
}
|
|
798
993
|
return Math.random().toString(36).slice(2, 10);
|
|
799
994
|
}
|
|
800
|
-
function initializeValuesFromTemplate(template
|
|
995
|
+
function initializeValuesFromTemplate(template) {
|
|
801
996
|
const result = {};
|
|
802
997
|
for (const [key, value] of Object.entries(template)) {
|
|
803
998
|
result[key] = deepClone(value);
|
|
804
999
|
}
|
|
805
|
-
if (!result.id) result.id = draftRowId;
|
|
806
1000
|
return result;
|
|
807
1001
|
}
|
|
808
1002
|
function deepClone(value) {
|
|
@@ -858,242 +1052,11 @@ function shallowEqualArrays(a, b) {
|
|
|
858
1052
|
return true;
|
|
859
1053
|
}
|
|
860
1054
|
|
|
861
|
-
// src/store/relation-info-slice.ts
|
|
862
|
-
var import_inflekt2 = require("inflekt");
|
|
863
|
-
var import_data5 = require("@constructive-io/data");
|
|
864
|
-
|
|
865
|
-
// src/utils/relation-utils.ts
|
|
866
|
-
var import_inflekt = require("inflekt");
|
|
867
|
-
var import_data4 = require("@constructive-io/data");
|
|
868
|
-
function isJunctionTablePure(junctionTableName, leftFkField, rightFkField, metaTables) {
|
|
869
|
-
if (!leftFkField || !rightFkField) return true;
|
|
870
|
-
const junctionMeta = metaTables.find((t) => t?.name === junctionTableName);
|
|
871
|
-
if (!junctionMeta?.fields) return true;
|
|
872
|
-
const exemptFields = /* @__PURE__ */ new Set(["id", leftFkField, rightFkField]);
|
|
873
|
-
for (const field of junctionMeta.fields) {
|
|
874
|
-
if (!field?.name) continue;
|
|
875
|
-
const camelName = (0, import_data4.pgFieldToCamelCase)(field.name);
|
|
876
|
-
if (exemptFields.has(camelName)) continue;
|
|
877
|
-
if (field.isNotNull && !field.hasDefault) return false;
|
|
878
|
-
}
|
|
879
|
-
return true;
|
|
880
|
-
}
|
|
881
|
-
function getJunctionTableNames(relations, metaTables) {
|
|
882
|
-
const names = /* @__PURE__ */ new Set();
|
|
883
|
-
for (const rel of relations.manyToMany) {
|
|
884
|
-
if (!rel.junctionTable) continue;
|
|
885
|
-
if (metaTables) {
|
|
886
|
-
const leftFk = rel.junctionLeftKeyFields?.[0];
|
|
887
|
-
const rightFk = rel.junctionRightKeyFields?.[0];
|
|
888
|
-
if (!isJunctionTablePure(rel.junctionTable, leftFk, rightFk, metaTables)) continue;
|
|
889
|
-
}
|
|
890
|
-
names.add(rel.junctionTable);
|
|
891
|
-
}
|
|
892
|
-
return names;
|
|
893
|
-
}
|
|
894
|
-
|
|
895
|
-
// src/store/relation-info-slice.ts
|
|
896
|
-
function toRelationInfoMap(info) {
|
|
897
|
-
return new Map(Object.entries(info));
|
|
898
|
-
}
|
|
899
|
-
function setTableRelationInfo(set, tableName, info) {
|
|
900
|
-
set((state) => ({
|
|
901
|
-
relationInfoCache: { ...state.relationInfoCache, [tableName]: info },
|
|
902
|
-
relationInfoMapCache: { ...state.relationInfoMapCache, [tableName]: toRelationInfoMap(info) }
|
|
903
|
-
}));
|
|
904
|
-
}
|
|
905
|
-
function createRelationInfoSlice(set, get) {
|
|
906
|
-
return {
|
|
907
|
-
relationInfoCache: {},
|
|
908
|
-
relationInfoMapCache: {},
|
|
909
|
-
setRelationInfoForTable: (tableName, info) => setTableRelationInfo(set, tableName, info),
|
|
910
|
-
getRelationInfoForTable: (tableName) => get().relationInfoCache[tableName],
|
|
911
|
-
getRelationInfoMapForTable: (tableName) => get().relationInfoMapCache[tableName],
|
|
912
|
-
clearRelationInfoCache: () => set({ relationInfoCache: {}, relationInfoMapCache: {} }),
|
|
913
|
-
rebuildRelationInfo: (tableName, meta) => {
|
|
914
|
-
try {
|
|
915
|
-
const info = buildRelationInfoFromMeta(tableName, meta);
|
|
916
|
-
if (!info) return;
|
|
917
|
-
setTableRelationInfo(set, tableName, info);
|
|
918
|
-
} catch {
|
|
919
|
-
}
|
|
920
|
-
},
|
|
921
|
-
ensureRelationInfo: (tableName, meta) => {
|
|
922
|
-
const existing = get().relationInfoCache[tableName];
|
|
923
|
-
if (existing) return existing;
|
|
924
|
-
const info = buildRelationInfoFromMeta(tableName, meta) || {};
|
|
925
|
-
if (Object.keys(info).length) {
|
|
926
|
-
setTableRelationInfo(set, tableName, info);
|
|
927
|
-
}
|
|
928
|
-
return info;
|
|
929
|
-
}
|
|
930
|
-
};
|
|
931
|
-
}
|
|
932
|
-
function toCleanTables(meta) {
|
|
933
|
-
const tables = meta?._meta?.tables ?? [];
|
|
934
|
-
return tables.filter((table) => table != null).map((table) => (0, import_data5.cleanTable)(table));
|
|
935
|
-
}
|
|
936
|
-
function firstFieldName(fields2) {
|
|
937
|
-
return fields2[0]?.name;
|
|
938
|
-
}
|
|
939
|
-
function findForeignKeyInRelatedTable(currentTableName, relatedTableName, allTables, rawMetaTables) {
|
|
940
|
-
const relatedTable = allTables.find((t) => t.name === relatedTableName);
|
|
941
|
-
if (relatedTable) {
|
|
942
|
-
const belongsTo = relatedTable.relations.belongsTo.find(
|
|
943
|
-
(rel) => rel.referencesTable === currentTableName
|
|
944
|
-
);
|
|
945
|
-
if (belongsTo?.keys?.[0]?.name) return belongsTo.keys[0].name;
|
|
946
|
-
}
|
|
947
|
-
const rawRelated = rawMetaTables.find((t) => t.name === relatedTableName);
|
|
948
|
-
if (rawRelated) {
|
|
949
|
-
const v5Fks = Array.isArray(rawRelated.constraints) ? [] : rawRelated.constraints?.foreignKey;
|
|
950
|
-
const fks = v5Fks ?? rawRelated.foreignKeyConstraints ?? [];
|
|
951
|
-
for (const fk of fks) {
|
|
952
|
-
if (!fk) continue;
|
|
953
|
-
const refName = fk.refTable?.name;
|
|
954
|
-
if (refName && refName.toLowerCase() === currentTableName.toLowerCase()) {
|
|
955
|
-
const fieldName = fk.fields?.[0]?.name;
|
|
956
|
-
if (fieldName) return (0, import_data5.pgFieldToCamelCase)(fieldName);
|
|
957
|
-
}
|
|
958
|
-
}
|
|
959
|
-
}
|
|
960
|
-
return void 0;
|
|
961
|
-
}
|
|
962
|
-
function buildRelationInfoFromMeta(tableName, meta) {
|
|
963
|
-
const tables = toCleanTables(meta);
|
|
964
|
-
const table = tables.find((candidate) => candidate.name === tableName);
|
|
965
|
-
if (!table) return null;
|
|
966
|
-
const rawMetaTables = (meta?._meta?.tables ?? []).filter(
|
|
967
|
-
(t) => t != null
|
|
968
|
-
);
|
|
969
|
-
const PRIORITY_FIELDS = [
|
|
970
|
-
"displayName",
|
|
971
|
-
"fullName",
|
|
972
|
-
"preferredName",
|
|
973
|
-
"nickname",
|
|
974
|
-
"firstName",
|
|
975
|
-
"lastName",
|
|
976
|
-
"givenName",
|
|
977
|
-
"familyName",
|
|
978
|
-
"username",
|
|
979
|
-
"handle",
|
|
980
|
-
"email",
|
|
981
|
-
"phone",
|
|
982
|
-
"title",
|
|
983
|
-
"label",
|
|
984
|
-
"slug",
|
|
985
|
-
"code",
|
|
986
|
-
"name"
|
|
987
|
-
];
|
|
988
|
-
const NAME_PATTERN = /name/i;
|
|
989
|
-
const computeCandidates = (relatedTableName) => {
|
|
990
|
-
if (!relatedTableName) return [];
|
|
991
|
-
const related = tables.find((candidate) => candidate.name === relatedTableName);
|
|
992
|
-
if (!related) return [];
|
|
993
|
-
const fieldNamesSet = new Set(related.fields.map((field) => field.name));
|
|
994
|
-
const explicit = PRIORITY_FIELDS.filter((k) => fieldNamesSet.has(k));
|
|
995
|
-
const explicitSet = new Set(explicit);
|
|
996
|
-
const nameLike = [];
|
|
997
|
-
for (const name of fieldNamesSet) {
|
|
998
|
-
if (NAME_PATTERN.test(name) && !explicitSet.has(name)) {
|
|
999
|
-
nameLike.push(name);
|
|
1000
|
-
}
|
|
1001
|
-
}
|
|
1002
|
-
nameLike.sort((a, b) => a.length - b.length);
|
|
1003
|
-
return Array.from(/* @__PURE__ */ new Set([...explicit, ...nameLike]));
|
|
1004
|
-
};
|
|
1005
|
-
const info = {};
|
|
1006
|
-
table.relations.belongsTo.forEach((relation) => {
|
|
1007
|
-
const displayCandidates = computeCandidates(relation.referencesTable);
|
|
1008
|
-
const foreignKeys = relation.keys.map((key) => key.name).filter(Boolean);
|
|
1009
|
-
const primaryForeignKey = foreignKeys[0];
|
|
1010
|
-
if (relation.fieldName) {
|
|
1011
|
-
info[relation.fieldName] = {
|
|
1012
|
-
kind: "belongsTo",
|
|
1013
|
-
relatedTable: relation.referencesTable,
|
|
1014
|
-
displayCandidates,
|
|
1015
|
-
relationField: relation.fieldName,
|
|
1016
|
-
foreignKeyField: primaryForeignKey
|
|
1017
|
-
};
|
|
1018
|
-
}
|
|
1019
|
-
foreignKeys.forEach((fk) => {
|
|
1020
|
-
if (!fk) return;
|
|
1021
|
-
info[fk] = {
|
|
1022
|
-
kind: "belongsTo",
|
|
1023
|
-
relatedTable: relation.referencesTable,
|
|
1024
|
-
displayCandidates,
|
|
1025
|
-
relationField: relation.fieldName ?? void 0,
|
|
1026
|
-
foreignKeyField: fk
|
|
1027
|
-
};
|
|
1028
|
-
});
|
|
1029
|
-
});
|
|
1030
|
-
table.relations.hasOne.forEach((relation) => {
|
|
1031
|
-
if (relation.fieldName) {
|
|
1032
|
-
const fkInRelated = findForeignKeyInRelatedTable(tableName, relation.referencedByTable, tables, rawMetaTables);
|
|
1033
|
-
info[relation.fieldName] = {
|
|
1034
|
-
kind: "hasOne",
|
|
1035
|
-
relatedTable: relation.referencedByTable,
|
|
1036
|
-
displayCandidates: computeCandidates(relation.referencedByTable),
|
|
1037
|
-
relationField: relation.fieldName,
|
|
1038
|
-
foreignKeyField: fkInRelated
|
|
1039
|
-
};
|
|
1040
|
-
}
|
|
1041
|
-
});
|
|
1042
|
-
const junctionTableNames = getJunctionTableNames(table.relations, rawMetaTables);
|
|
1043
|
-
table.relations.hasMany.forEach((relation) => {
|
|
1044
|
-
if (!relation.fieldName) return;
|
|
1045
|
-
if (junctionTableNames.has(relation.referencedByTable)) return;
|
|
1046
|
-
const fkInRelated = findForeignKeyInRelatedTable(tableName, relation.referencedByTable, tables, rawMetaTables);
|
|
1047
|
-
info[relation.fieldName] = {
|
|
1048
|
-
kind: "hasMany",
|
|
1049
|
-
relatedTable: relation.referencedByTable,
|
|
1050
|
-
displayCandidates: computeCandidates(relation.referencedByTable),
|
|
1051
|
-
relationField: relation.fieldName,
|
|
1052
|
-
foreignKeyField: fkInRelated
|
|
1053
|
-
};
|
|
1054
|
-
});
|
|
1055
|
-
table.relations.manyToMany.forEach((relation) => {
|
|
1056
|
-
if (relation.fieldName) {
|
|
1057
|
-
let junctionLeftKeyField = relation.junctionLeftKeyFields?.[0];
|
|
1058
|
-
let junctionRightKeyField = relation.junctionRightKeyFields?.[0];
|
|
1059
|
-
if (!junctionLeftKeyField || !junctionRightKeyField) {
|
|
1060
|
-
const junctionTableName = relation.junctionTable;
|
|
1061
|
-
const junctionTable = junctionTableName ? tables.find((candidate) => candidate.name === junctionTableName) : void 0;
|
|
1062
|
-
const junctionBelongsTo = junctionTable?.relations.belongsTo ?? [];
|
|
1063
|
-
if (!junctionLeftKeyField) {
|
|
1064
|
-
const leftRelation = junctionBelongsTo.find((entry) => entry.referencesTable === tableName);
|
|
1065
|
-
junctionLeftKeyField = firstFieldName(leftRelation?.keys ?? []);
|
|
1066
|
-
}
|
|
1067
|
-
if (!junctionRightKeyField) {
|
|
1068
|
-
const rightRelation = junctionBelongsTo.find((entry) => entry.referencesTable === relation.rightTable);
|
|
1069
|
-
junctionRightKeyField = firstFieldName(rightRelation?.keys ?? []);
|
|
1070
|
-
}
|
|
1071
|
-
}
|
|
1072
|
-
if (!isJunctionTablePure(relation.junctionTable, junctionLeftKeyField, junctionRightKeyField, rawMetaTables)) {
|
|
1073
|
-
return;
|
|
1074
|
-
}
|
|
1075
|
-
info[relation.fieldName] = {
|
|
1076
|
-
kind: "manyToMany",
|
|
1077
|
-
relatedTable: relation.rightTable,
|
|
1078
|
-
displayCandidates: computeCandidates(relation.rightTable),
|
|
1079
|
-
relationField: relation.fieldName,
|
|
1080
|
-
junctionTable: relation.junctionTable,
|
|
1081
|
-
junctionLeftKeyField,
|
|
1082
|
-
junctionRightKeyField,
|
|
1083
|
-
displayName: (0, import_inflekt2.pluralize)(relation.rightTable)
|
|
1084
|
-
};
|
|
1085
|
-
}
|
|
1086
|
-
});
|
|
1087
|
-
return info;
|
|
1088
|
-
}
|
|
1089
|
-
|
|
1090
1055
|
// src/store/sheets-store.ts
|
|
1091
1056
|
function createSheetsStore() {
|
|
1092
|
-
return (0, import_zustand.createStore)((set
|
|
1057
|
+
return (0, import_zustand.createStore)((set) => ({
|
|
1093
1058
|
// Draft rows
|
|
1094
1059
|
...createDraftRowsSlice(set),
|
|
1095
|
-
// Relation info cache
|
|
1096
|
-
...createRelationInfoSlice(set, get),
|
|
1097
1060
|
// Auth state (standalone mode)
|
|
1098
1061
|
isAuthenticated: false,
|
|
1099
1062
|
accessToken: null,
|
|
@@ -1152,22 +1115,26 @@ function setSheetsLocale(locale) {
|
|
|
1152
1115
|
}
|
|
1153
1116
|
|
|
1154
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
|
+
}
|
|
1155
1122
|
var sheetsQueryKeys = {
|
|
1156
1123
|
root: ["sheets"],
|
|
1157
1124
|
scope: (scope) => ["sheets", scope],
|
|
1158
1125
|
meta: (scope) => [...sheetsQueryKeys.scope(scope), "meta"],
|
|
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],
|
|
1159
1128
|
mediaUrl: (scope, endpoint, id) => [...sheetsQueryKeys.scope(scope), "media-url", endpoint, id],
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
infiniteTableTotalCount: (scope, tableName, where) => [...sheetsQueryKeys.infiniteTable(scope, tableName), "totalCount", where],
|
|
1170
|
-
cursorTable: (scope, tableName, options) => [...sheetsQueryKeys.scope(scope), "cursor-table", tableName, options]
|
|
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]
|
|
1171
1138
|
};
|
|
1172
1139
|
|
|
1173
1140
|
// src/context/sheets-provider.tsx
|
|
@@ -1271,6 +1238,131 @@ function SheetsProvider({ config, children }) {
|
|
|
1271
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 }) }) });
|
|
1272
1239
|
}
|
|
1273
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
|
+
|
|
1274
1366
|
// src/testing/meta-contract-fixture.ts
|
|
1275
1367
|
var import_data6 = require("@constructive-io/data");
|
|
1276
1368
|
var fields = (names) => names.map((name) => ({ name }));
|
|
@@ -1283,29 +1375,619 @@ function createMetaContractFixture() {
|
|
|
1283
1375
|
);
|
|
1284
1376
|
}
|
|
1285
1377
|
|
|
1286
|
-
// src/testing/
|
|
1287
|
-
var
|
|
1288
|
-
|
|
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) {
|
|
1289
1602
|
if (typeof document === "string") return document;
|
|
1290
1603
|
if (document instanceof String) return document.toString();
|
|
1291
|
-
if (document && typeof document === "object" && "kind" in document)
|
|
1292
|
-
return (0, import_graphql3.print)(document);
|
|
1293
|
-
}
|
|
1604
|
+
if (document && typeof document === "object" && "kind" in document) return (0, import_graphql4.print)(document);
|
|
1294
1605
|
return String(document ?? "");
|
|
1295
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");
|
|
1296
1974
|
function buildMetaField(field, primaryKeyFields) {
|
|
1297
1975
|
return {
|
|
1298
1976
|
name: field.name,
|
|
1299
1977
|
isPrimaryKey: primaryKeyFields.has(field.name),
|
|
1978
|
+
isForeignKey: false,
|
|
1300
1979
|
isNotNull: false,
|
|
1301
1980
|
hasDefault: false,
|
|
1981
|
+
description: null,
|
|
1982
|
+
enumValues: null,
|
|
1302
1983
|
type: {
|
|
1303
1984
|
gqlType: field.gqlType,
|
|
1304
1985
|
isArray: field.isArray ?? false,
|
|
1305
1986
|
pgType: field.pgType ?? "text",
|
|
1306
1987
|
isNotNull: false,
|
|
1307
1988
|
hasDefault: false,
|
|
1308
|
-
subtype: field.subtype ?? null
|
|
1989
|
+
subtype: field.subtype ?? null,
|
|
1990
|
+
encoding: null
|
|
1309
1991
|
}
|
|
1310
1992
|
};
|
|
1311
1993
|
}
|
|
@@ -1313,162 +1995,59 @@ function buildMetaTable(table) {
|
|
|
1313
1995
|
const primaryKeyFields = table.primaryKeyFields ?? (table.fields.some((field) => field.name === "id") ? ["id"] : []);
|
|
1314
1996
|
const primaryKeySet = new Set(primaryKeyFields);
|
|
1315
1997
|
const primaryKeyMetaFields = table.fields.filter((field) => primaryKeySet.has(field.name)).map((field) => buildMetaField(field, primaryKeySet));
|
|
1998
|
+
const hasKey = primaryKeyMetaFields.length > 0;
|
|
1316
1999
|
return {
|
|
1317
2000
|
name: table.name,
|
|
1318
2001
|
schemaName: "public",
|
|
1319
2002
|
query: {
|
|
1320
|
-
all: (0,
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
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
|
|
1325
2008
|
},
|
|
1326
2009
|
fields: table.fields.map((field) => buildMetaField(field, primaryKeySet)),
|
|
1327
2010
|
inflection: {
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
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`
|
|
1331
2016
|
},
|
|
1332
2017
|
indexes: [],
|
|
1333
2018
|
constraints: {
|
|
1334
|
-
primaryKey:
|
|
2019
|
+
primaryKey: hasKey ? { name: `${table.name}_pkey`, fields: primaryKeyMetaFields } : null,
|
|
1335
2020
|
unique: [],
|
|
1336
2021
|
foreignKey: []
|
|
1337
2022
|
},
|
|
1338
2023
|
foreignKeyConstraints: [],
|
|
1339
|
-
primaryKeyConstraints:
|
|
2024
|
+
primaryKeyConstraints: hasKey ? [{ name: `${table.name}_pkey`, fields: primaryKeyMetaFields }] : [],
|
|
1340
2025
|
uniqueConstraints: [],
|
|
1341
|
-
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
|
|
1342
2032
|
};
|
|
1343
2033
|
}
|
|
1344
2034
|
function buildMetaResponse(tables) {
|
|
1345
|
-
return {
|
|
1346
|
-
_meta: {
|
|
1347
|
-
tables: tables.map(buildMetaTable)
|
|
1348
|
-
}
|
|
1349
|
-
};
|
|
1350
|
-
}
|
|
1351
|
-
function buildListResponse(table) {
|
|
1352
|
-
const field = (0, import_data7.toCamelCasePlural)(table.name);
|
|
1353
|
-
return {
|
|
1354
|
-
[field]: {
|
|
1355
|
-
nodes: table.rows,
|
|
1356
|
-
totalCount: table.rows.length,
|
|
1357
|
-
pageInfo: {
|
|
1358
|
-
hasNextPage: false,
|
|
1359
|
-
hasPreviousPage: false,
|
|
1360
|
-
endCursor: null,
|
|
1361
|
-
startCursor: null
|
|
1362
|
-
}
|
|
1363
|
-
}
|
|
1364
|
-
};
|
|
1365
|
-
}
|
|
1366
|
-
var mockIdCounter = 0;
|
|
1367
|
-
function synthesizeId() {
|
|
1368
|
-
mockIdCounter += 1;
|
|
1369
|
-
return `mock-${mockIdCounter}`;
|
|
1370
|
-
}
|
|
1371
|
-
function extractMutationInput(variables) {
|
|
1372
|
-
const input = variables?.input;
|
|
1373
|
-
return input && typeof input === "object" ? input : {};
|
|
1374
|
-
}
|
|
1375
|
-
function synthesizeCreatedRow(table, singular, variables) {
|
|
1376
|
-
const input = extractMutationInput(variables);
|
|
1377
|
-
const data = input[singular] ?? {};
|
|
1378
|
-
const row = { id: synthesizeId(), ...data };
|
|
1379
|
-
table.rows.push(row);
|
|
1380
|
-
return row;
|
|
1381
|
-
}
|
|
1382
|
-
function synthesizeUpdatedRow(table, variables) {
|
|
1383
|
-
const input = extractMutationInput(variables);
|
|
1384
|
-
const id = input.id;
|
|
1385
|
-
let patch = {};
|
|
1386
|
-
for (const [key, value] of Object.entries(input)) {
|
|
1387
|
-
if (key === "id") continue;
|
|
1388
|
-
if (value && typeof value === "object") {
|
|
1389
|
-
patch = value;
|
|
1390
|
-
break;
|
|
1391
|
-
}
|
|
1392
|
-
}
|
|
1393
|
-
const existing = table.rows.find((r) => r.id === id);
|
|
1394
|
-
const merged = { ...existing ?? { id }, ...patch };
|
|
1395
|
-
if (existing) {
|
|
1396
|
-
Object.assign(existing, patch);
|
|
1397
|
-
} else {
|
|
1398
|
-
table.rows.push(merged);
|
|
1399
|
-
}
|
|
1400
|
-
return merged;
|
|
1401
|
-
}
|
|
1402
|
-
function isMetaQuery(query) {
|
|
1403
|
-
return query.includes("_meta");
|
|
1404
|
-
}
|
|
1405
|
-
function isMutationDocument(query) {
|
|
1406
|
-
return /(^|\s)mutation(\s|\{)/.test(query);
|
|
1407
|
-
}
|
|
1408
|
-
function findMutationTable(query, tables) {
|
|
1409
|
-
let best = null;
|
|
1410
|
-
for (const table of tables) {
|
|
1411
|
-
const candidates = [
|
|
1412
|
-
{ op: "create", mutationName: (0, import_data7.toCreateMutationName)(table.name) },
|
|
1413
|
-
{ op: "update", mutationName: (0, import_data7.toUpdateMutationName)(table.name) },
|
|
1414
|
-
{ op: "delete", mutationName: (0, import_data7.toDeleteMutationName)(table.name) }
|
|
1415
|
-
];
|
|
1416
|
-
for (const c of candidates) {
|
|
1417
|
-
if (query.includes(c.mutationName) && (!best || c.mutationName.length > best.mutationName.length)) {
|
|
1418
|
-
best = { table, op: c.op, mutationName: c.mutationName, singular: (0, import_data7.toCamelCaseSingular)(table.name) };
|
|
1419
|
-
}
|
|
1420
|
-
}
|
|
1421
|
-
}
|
|
1422
|
-
return best;
|
|
1423
|
-
}
|
|
1424
|
-
function findListTable(query, tables) {
|
|
1425
|
-
let best = null;
|
|
1426
|
-
let bestLen = 0;
|
|
1427
|
-
for (const table of tables) {
|
|
1428
|
-
const plural = (0, import_data7.toCamelCasePlural)(table.name);
|
|
1429
|
-
if (query.includes(plural) && plural.length > bestLen) {
|
|
1430
|
-
best = table;
|
|
1431
|
-
bestLen = plural.length;
|
|
1432
|
-
}
|
|
1433
|
-
}
|
|
1434
|
-
return best;
|
|
2035
|
+
return { _meta: { tables: tables.map(buildMetaTable) } };
|
|
1435
2036
|
}
|
|
1436
2037
|
function createMockExecute(opts) {
|
|
1437
|
-
const
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
if (isMetaQuery(query)) {
|
|
1448
|
-
return buildMetaResponse(opts.tables);
|
|
1449
|
-
}
|
|
1450
|
-
const mutationMatch = isMutationDocument(query) ? findMutationTable(query, opts.tables) : null;
|
|
1451
|
-
if (mutationMatch) {
|
|
1452
|
-
const { table, op, mutationName, singular } = mutationMatch;
|
|
1453
|
-
record({ op, tableName: table.name, variables: variables ?? {}, at: Date.now() });
|
|
1454
|
-
if (op === "delete") {
|
|
1455
|
-
const input = extractMutationInput(variables);
|
|
1456
|
-
const id = input.id ?? null;
|
|
1457
|
-
table.rows = table.rows.filter((r) => r.id !== id);
|
|
1458
|
-
return { [mutationName]: { deletedNodeId: id, clientMutationId: null } };
|
|
1459
|
-
}
|
|
1460
|
-
const row = op === "create" ? synthesizeCreatedRow(table, singular, variables) : synthesizeUpdatedRow(table, variables);
|
|
1461
|
-
return { [mutationName]: { [singular]: row } };
|
|
1462
|
-
}
|
|
1463
|
-
const listTable = findListTable(query, opts.tables);
|
|
1464
|
-
if (listTable) {
|
|
1465
|
-
return buildListResponse(listTable);
|
|
1466
|
-
}
|
|
1467
|
-
return {};
|
|
1468
|
-
};
|
|
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;
|
|
1469
2048
|
const executeUpload = async (file, path, options) => {
|
|
1470
2049
|
const name = file?.name ?? "file";
|
|
1471
|
-
|
|
2050
|
+
const upload = {
|
|
1472
2051
|
op: "upload",
|
|
1473
2052
|
tableName: options?.tableName ?? "",
|
|
1474
2053
|
variables: {
|
|
@@ -1478,7 +2057,9 @@ function createMockExecute(opts) {
|
|
|
1478
2057
|
...options?.recordId !== void 0 && { recordId: options.recordId }
|
|
1479
2058
|
},
|
|
1480
2059
|
at: Date.now()
|
|
1481
|
-
}
|
|
2060
|
+
};
|
|
2061
|
+
mutations.push(upload);
|
|
2062
|
+
opts.onMutation?.(upload);
|
|
1482
2063
|
const url = "mock://uploaded/" + name;
|
|
1483
2064
|
return {
|
|
1484
2065
|
file: {
|
|
@@ -1496,7 +2077,7 @@ function createMockExecute(opts) {
|
|
|
1496
2077
|
function reset() {
|
|
1497
2078
|
mutations.length = 0;
|
|
1498
2079
|
}
|
|
1499
|
-
return { execute, executeUpload, mutations, reset };
|
|
2080
|
+
return { execute: backend.execute, executeUpload, mutations, reset };
|
|
1500
2081
|
}
|
|
1501
2082
|
function MockSheetsProvider({ options, children }) {
|
|
1502
2083
|
const { execute, executeUpload } = (0, import_react4.useMemo)(() => createMockExecute(options), []);
|