@constructive-io/sheets 0.13.1 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +231 -148
- package/dist/advanced.cjs +7220 -4030
- 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-MXVNIKES.js → chunk-J7KK4UWI.js} +6 -6
- package/dist/chunk-MBSHDF55.js +839 -0
- package/dist/chunk-MBSHDF55.js.map +1 -0
- package/dist/{chunk-ZKANUG3F.js → chunk-MOFFS5WQ.js} +20 -15
- 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-H5HR5HUJ.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-YNIVK4hN.d.cts +346 -0
- package/dist/grid-cell-types-YNIVK4hN.d.ts +346 -0
- package/dist/index.cjs +22910 -12084
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1497 -337
- package/dist/index.d.ts +1497 -337
- package/dist/index.js +12833 -6142
- 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 +1253 -638
- 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 +791 -148
- package/dist/testing.js.map +1 -1
- package/package.json +5 -5
- package/dist/chunk-4EZ6A23C.js +0 -44
- package/dist/chunk-4EZ6A23C.js.map +0 -1
- package/dist/chunk-5QPNOKMA.js +0 -4397
- package/dist/chunk-5QPNOKMA.js.map +0 -1
- package/dist/chunk-AYMXT3ME.js +0 -540
- package/dist/chunk-AYMXT3ME.js.map +0 -1
- package/dist/chunk-H5HR5HUJ.js.map +0 -1
- package/dist/chunk-PZL2BCWF.js +0 -168
- package/dist/chunk-PZL2BCWF.js.map +0 -1
- package/dist/chunk-X7DHTSOX.js +0 -21
- package/dist/chunk-X7DHTSOX.js.map +0 -1
- package/dist/chunk-ZKANUG3F.js.map +0 -1
- package/dist/date-editor-ZFNDKYBD.js +0 -358
- package/dist/date-editor-ZFNDKYBD.js.map +0 -1
- package/dist/grid-cell-types-Pbe2m2tE.d.cts +0 -253
- package/dist/grid-cell-types-Pbe2m2tE.d.ts +0 -253
- package/dist/map-picker-ZUGGOIZS.js +0 -290
- package/dist/map-picker-ZUGGOIZS.js.map +0 -1
- package/dist/sheets-context-CY1RmDKL.d.cts +0 -244
- package/dist/sheets-context-Cu3Ec_ca.d.ts +0 -244
- /package/dist/{chunk-MXVNIKES.js.map → chunk-J7KK4UWI.js.map} +0 -0
package/dist/testing.js
CHANGED
|
@@ -1,25 +1,165 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import {
|
|
3
3
|
SheetsProvider
|
|
4
|
-
} from "./chunk-
|
|
5
|
-
import
|
|
6
|
-
|
|
7
|
-
|
|
4
|
+
} from "./chunk-MOFFS5WQ.js";
|
|
5
|
+
import {
|
|
6
|
+
withResponseErrors
|
|
7
|
+
} from "./chunk-MBSHDF55.js";
|
|
8
|
+
import "./chunk-ZOQDSOMO.js";
|
|
9
|
+
import "./chunk-II3MSNRO.js";
|
|
8
10
|
import "./chunk-GGECS2BP.js";
|
|
9
|
-
import "./chunk-X7DHTSOX.js";
|
|
10
11
|
|
|
11
12
|
// src/testing/mock-sheets-provider.tsx
|
|
12
13
|
import { useMemo } from "react";
|
|
13
|
-
import {
|
|
14
|
+
import { buildSchema } from "graphql";
|
|
14
15
|
import { QueryClient } from "@tanstack/react-query";
|
|
15
16
|
import {
|
|
16
17
|
toCamelCasePlural,
|
|
17
|
-
toCamelCaseSingular,
|
|
18
18
|
toCreateMutationName,
|
|
19
19
|
toUpdateMutationName,
|
|
20
20
|
toDeleteMutationName
|
|
21
21
|
} from "@constructive-io/data";
|
|
22
22
|
|
|
23
|
+
// src/testing/meta-schema.ts
|
|
24
|
+
import {
|
|
25
|
+
getRowIdentityDefinition,
|
|
26
|
+
toCamelCaseSingular
|
|
27
|
+
} from "@constructive-io/data";
|
|
28
|
+
var BUILT_IN_SCALARS = /* @__PURE__ */ new Set(["String", "Int", "Float", "Boolean", "ID"]);
|
|
29
|
+
var ORDERED_SCALARS = /* @__PURE__ */ new Set(["Int", "Float", "BigInt", "BigFloat", "Date", "Datetime", "Time", "String", "UUID"]);
|
|
30
|
+
function constantCase(name) {
|
|
31
|
+
return name.replace(/([a-z0-9])([A-Z])/g, "$1_$2").replace(/[^A-Za-z0-9]+/g, "_").toUpperCase();
|
|
32
|
+
}
|
|
33
|
+
function fieldsOf(table) {
|
|
34
|
+
return (table.fields ?? []).filter((field) => Boolean(field?.name));
|
|
35
|
+
}
|
|
36
|
+
function typeRef(field) {
|
|
37
|
+
return field.type.isArray ? `[${field.type.gqlType}]` : field.type.gqlType;
|
|
38
|
+
}
|
|
39
|
+
function operatorType(field) {
|
|
40
|
+
return field.type.isArray ? `${field.type.gqlType}ListFilter` : `${field.type.gqlType}Filter`;
|
|
41
|
+
}
|
|
42
|
+
function scalarFilter(scalar) {
|
|
43
|
+
const ordered = ORDERED_SCALARS.has(scalar) ? `lessThan: ${scalar} lessThanOrEqualTo: ${scalar} greaterThan: ${scalar} greaterThanOrEqualTo: ${scalar}` : "";
|
|
44
|
+
const text = scalar === "String" ? "includes: String notIncludes: String includesInsensitive: String notIncludesInsensitive: String startsWith: String startsWithInsensitive: String endsWith: String endsWithInsensitive: String equalToInsensitive: String" : "";
|
|
45
|
+
return `input ${scalar}Filter { isNull: Boolean equalTo: ${scalar} notEqualTo: ${scalar} distinctFrom: ${scalar} notDistinctFrom: ${scalar} in: [${scalar}!] notIn: [${scalar}!] ${ordered} ${text} }`;
|
|
46
|
+
}
|
|
47
|
+
function listFilter(scalar) {
|
|
48
|
+
return `input ${scalar}ListFilter { isNull: Boolean equalTo: [${scalar}] notEqualTo: [${scalar}] contains: [${scalar}] anyEqualTo: ${scalar} }`;
|
|
49
|
+
}
|
|
50
|
+
function relationFields(table, names) {
|
|
51
|
+
const relations = table.relations;
|
|
52
|
+
const columns = new Set(fieldsOf(table).map((field) => field.name));
|
|
53
|
+
const fields2 = [];
|
|
54
|
+
const add = (fieldName, definition) => {
|
|
55
|
+
if (!columns.has(fieldName)) fields2.push(definition);
|
|
56
|
+
};
|
|
57
|
+
for (const relation of relations?.belongsTo ?? []) {
|
|
58
|
+
if (relation?.fieldName && names.has(relation.references.name)) add(relation.fieldName, `${relation.fieldName}: ${relation.references.name}`);
|
|
59
|
+
}
|
|
60
|
+
for (const relation of relations?.hasOne ?? []) {
|
|
61
|
+
if (relation?.fieldName && names.has(relation.referencedBy.name)) add(relation.fieldName, `${relation.fieldName}: ${relation.referencedBy.name}`);
|
|
62
|
+
}
|
|
63
|
+
for (const relation of relations?.hasMany ?? []) {
|
|
64
|
+
if (relation?.fieldName && names.has(relation.referencedBy.name)) {
|
|
65
|
+
add(relation.fieldName, `${relation.fieldName}(first: Int): ${relation.referencedBy.name}Connection!`);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
for (const relation of relations?.manyToMany ?? []) {
|
|
69
|
+
if (relation?.fieldName && names.has(relation.rightTable.name)) {
|
|
70
|
+
add(relation.fieldName, `${relation.fieldName}(first: Int): ${relation.rightTable.name}Connection!`);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return fields2;
|
|
74
|
+
}
|
|
75
|
+
function tableTypes(table, names) {
|
|
76
|
+
const name = table.name;
|
|
77
|
+
const fields2 = fieldsOf(table);
|
|
78
|
+
const identity = getRowIdentityDefinition(table);
|
|
79
|
+
const primaryKey = identity.status === "keyed" ? identity.fields.map((field) => field.fieldName) : [];
|
|
80
|
+
const record = toCamelCaseSingular(name);
|
|
81
|
+
const requiredOnCreate = (field) => !primaryKey.includes(field.name) && Boolean(field.isNotNull) && !field.hasDefault;
|
|
82
|
+
const columns = fields2.map((field) => `${field.name}: ${typeRef(field)}`).join(" ");
|
|
83
|
+
const keyFields = primaryKey.map((key) => fields2.find((field) => field.name === key)).filter((field) => Boolean(field)).map((field) => `${field.name}: ${typeRef(field)}!`).join(" ");
|
|
84
|
+
const sdl = [
|
|
85
|
+
`type ${name} { ${[columns, ...relationFields(table, names)].join(" ")} }`,
|
|
86
|
+
`type ${name}Connection { nodes: [${name}]! totalCount: Int! pageInfo: PageInfo! }`,
|
|
87
|
+
`input ${name}Filter { ${fields2.map((field) => `${field.name}: ${operatorType(field)}`).join(" ")} and: [${name}Filter!] or: [${name}Filter!] not: ${name}Filter }`,
|
|
88
|
+
`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(" ")} }`
|
|
89
|
+
];
|
|
90
|
+
if (table.query?.create) {
|
|
91
|
+
sdl.push(
|
|
92
|
+
`input ${name}Input { ${fields2.map((field) => `${field.name}: ${typeRef(field)}${requiredOnCreate(field) ? "!" : ""}`).join(" ")} }`,
|
|
93
|
+
`input Create${name}Input { clientMutationId: String ${record}: ${name}Input! }`,
|
|
94
|
+
`type Create${name}Payload { clientMutationId: String ${record}: ${name} }`
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
if (table.query?.update && keyFields) {
|
|
98
|
+
sdl.push(
|
|
99
|
+
`input ${name}Patch { ${columns} }`,
|
|
100
|
+
`input Update${name}Input { clientMutationId: String ${keyFields} ${record}Patch: ${name}Patch! }`,
|
|
101
|
+
`type Update${name}Payload { clientMutationId: String ${record}: ${name} }`
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
if (table.query?.delete && keyFields) {
|
|
105
|
+
sdl.push(
|
|
106
|
+
`input Delete${name}Input { clientMutationId: String ${keyFields} }`,
|
|
107
|
+
`type Delete${name}Payload { clientMutationId: String ${record}: ${name} }`
|
|
108
|
+
);
|
|
109
|
+
}
|
|
110
|
+
return sdl;
|
|
111
|
+
}
|
|
112
|
+
function rootFields(tables) {
|
|
113
|
+
const query = [];
|
|
114
|
+
const mutation = [];
|
|
115
|
+
for (const table of tables) {
|
|
116
|
+
const name = table.name;
|
|
117
|
+
const ops = table.query;
|
|
118
|
+
if (ops?.all) {
|
|
119
|
+
query.push(`${ops.all}(first: Int, offset: Int, after: Cursor, where: ${name}Filter, orderBy: [${name}OrderBy!]): ${name}Connection`);
|
|
120
|
+
}
|
|
121
|
+
const keyed = getRowIdentityDefinition(table).status === "keyed";
|
|
122
|
+
if (ops?.create) mutation.push(`${ops.create}(input: Create${name}Input!): Create${name}Payload`);
|
|
123
|
+
if (ops?.update && keyed) mutation.push(`${ops.update}(input: Update${name}Input!): Update${name}Payload`);
|
|
124
|
+
if (ops?.delete && keyed) mutation.push(`${ops.delete}(input: Delete${name}Input!): Delete${name}Payload`);
|
|
125
|
+
}
|
|
126
|
+
return { query, mutation };
|
|
127
|
+
}
|
|
128
|
+
function buildMetaSchemaSdl(tables) {
|
|
129
|
+
const names = new Set(tables.map((table) => table.name));
|
|
130
|
+
const fields2 = tables.flatMap(fieldsOf);
|
|
131
|
+
const scalars = new Set(fields2.map((field) => field.type.gqlType));
|
|
132
|
+
const listScalars = new Set(fields2.filter((field) => field.type.isArray).map((field) => field.type.gqlType));
|
|
133
|
+
const { query, mutation } = rootFields(tables);
|
|
134
|
+
return [
|
|
135
|
+
"scalar Cursor",
|
|
136
|
+
...[...scalars].filter((scalar) => !BUILT_IN_SCALARS.has(scalar) && scalar !== "Cursor").map((scalar) => `scalar ${scalar}`),
|
|
137
|
+
"type PageInfo { hasNextPage: Boolean! hasPreviousPage: Boolean! startCursor: Cursor endCursor: Cursor }",
|
|
138
|
+
"input BooleanFilter { isNull: Boolean equalTo: Boolean notEqualTo: Boolean }",
|
|
139
|
+
...[...scalars].filter((scalar) => scalar !== "Boolean").map(scalarFilter),
|
|
140
|
+
...[...listScalars].map(listFilter),
|
|
141
|
+
...tables.flatMap((table) => tableTypes(table, names)),
|
|
142
|
+
`type Query { ${query.join(" ") || "noop: Boolean"} }`,
|
|
143
|
+
mutation.length > 0 ? `type Mutation { ${mutation.join(" ")} }` : ""
|
|
144
|
+
].filter(Boolean).join("\n");
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// src/testing/model-backend.ts
|
|
148
|
+
import {
|
|
149
|
+
defaultFieldResolver,
|
|
150
|
+
graphql,
|
|
151
|
+
isAbstractType,
|
|
152
|
+
parse,
|
|
153
|
+
print,
|
|
154
|
+
validate
|
|
155
|
+
} from "graphql";
|
|
156
|
+
import {
|
|
157
|
+
createError,
|
|
158
|
+
createTableModelResolver,
|
|
159
|
+
metaTablesOf,
|
|
160
|
+
tableKeyOf
|
|
161
|
+
} from "@constructive-io/data";
|
|
162
|
+
|
|
23
163
|
// src/testing/meta-contract-fixture.ts
|
|
24
164
|
import { META_CONTRACT_REQUIREMENTS } from "@constructive-io/data";
|
|
25
165
|
var fields = (names) => names.map((name) => ({ name }));
|
|
@@ -32,29 +172,619 @@ function createMetaContractFixture() {
|
|
|
32
172
|
);
|
|
33
173
|
}
|
|
34
174
|
|
|
35
|
-
// src/testing/
|
|
36
|
-
import {
|
|
37
|
-
|
|
175
|
+
// src/testing/model-backend-uploads.ts
|
|
176
|
+
import { GraphQLError } from "graphql";
|
|
177
|
+
var LIVE_STATUSES = /* @__PURE__ */ new Set(["uploaded", "processed"]);
|
|
178
|
+
var UPLOAD_URL_LIFETIME_MS = 15 * 60 * 1e3;
|
|
179
|
+
function fail(message, code, extensions = {}) {
|
|
180
|
+
return new GraphQLError(message, { extensions: { code, ...extensions } });
|
|
181
|
+
}
|
|
182
|
+
function hexToBase64(hex) {
|
|
183
|
+
let binary = "";
|
|
184
|
+
for (let index = 0; index < hex.length; index += 2) binary += String.fromCharCode(Number.parseInt(hex.slice(index, index + 2), 16));
|
|
185
|
+
return btoa(binary);
|
|
186
|
+
}
|
|
187
|
+
function mimeAllowed(allowed, contentType) {
|
|
188
|
+
if (!Array.isArray(allowed) || allowed.length === 0) return true;
|
|
189
|
+
return allowed.some((pattern) => {
|
|
190
|
+
if (typeof pattern !== "string") return false;
|
|
191
|
+
if (pattern === "*/*") return true;
|
|
192
|
+
if (pattern.endsWith("/*")) return contentType.startsWith(pattern.slice(0, -1));
|
|
193
|
+
return contentType === pattern;
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
var fileIds = 0;
|
|
197
|
+
function nextFileId() {
|
|
198
|
+
fileIds += 1;
|
|
199
|
+
return `00000000-0000-4000-9000-${String(fileIds).padStart(12, "0")}`;
|
|
200
|
+
}
|
|
201
|
+
function surfacesOf(models) {
|
|
202
|
+
return models.flatMap((files) => {
|
|
203
|
+
const storage = files.storage;
|
|
204
|
+
if (storage?.role !== "files" || !storage.upload?.mutation) return [];
|
|
205
|
+
const buckets = models.find((candidate) => candidate.name === storage.bucketsType) ?? null;
|
|
206
|
+
const link = files.relations.find(
|
|
207
|
+
(relation) => relation.kind === "belongsTo" && relation.targetName === storage.bucketsType && relation.keys.length === 1
|
|
208
|
+
);
|
|
209
|
+
return [{
|
|
210
|
+
files,
|
|
211
|
+
buckets,
|
|
212
|
+
bucketLink: link?.keys[0] ?? null,
|
|
213
|
+
mutation: storage.upload.mutation,
|
|
214
|
+
bulkMutation: storage.upload.bulkMutation,
|
|
215
|
+
downloadUrlField: storage.downloadUrlField
|
|
216
|
+
}];
|
|
217
|
+
});
|
|
218
|
+
}
|
|
219
|
+
function createUploadService(models, tableRows, options = {}, uploads = []) {
|
|
220
|
+
const surfaces = surfacesOf(models);
|
|
221
|
+
const refusalsLeft = /* @__PURE__ */ new Map();
|
|
222
|
+
const publicUrlPrefix = (options.publicUrlPrefix ?? "https://cdn.mock").replace(/\/$/, "");
|
|
223
|
+
const uploadUrlPrefix = (options.uploadUrlPrefix ?? "https://storage.mock/upload").replace(/\/$/, "");
|
|
224
|
+
const fileRow = (fileId) => {
|
|
225
|
+
for (const surface of surfaces) {
|
|
226
|
+
const row = tableRows(surface.files).find((candidate) => candidate.id === fileId);
|
|
227
|
+
if (row) return { surface, row };
|
|
228
|
+
}
|
|
229
|
+
return null;
|
|
230
|
+
};
|
|
231
|
+
const assign = (surface, row, field, value) => {
|
|
232
|
+
if (surface.files.columns.some((column) => column.name === field)) row[field] = value;
|
|
233
|
+
};
|
|
234
|
+
function resolveBucket(surface, input) {
|
|
235
|
+
const buckets = surface.buckets ? tableRows(surface.buckets) : [];
|
|
236
|
+
const bucket = typeof input.bucketKey === "string" ? buckets.find((candidate) => candidate.key === input.bucketKey) : buckets.find((candidate) => candidate.isPublic === true === (input.isPublic === true));
|
|
237
|
+
if (!bucket) throw fail("BUCKET_NOT_FOUND", "BUCKET_NOT_FOUND");
|
|
238
|
+
return bucket;
|
|
239
|
+
}
|
|
240
|
+
function projection(fileId, key, bucket, input) {
|
|
241
|
+
return {
|
|
242
|
+
id: fileId,
|
|
243
|
+
key,
|
|
244
|
+
bucket_id: bucket.id,
|
|
245
|
+
mime: input.contentType,
|
|
246
|
+
size: input.size,
|
|
247
|
+
...typeof input.filename === "string" && input.filename ? { filename: input.filename } : {},
|
|
248
|
+
...bucket.isPublic === true ? { url: `${publicUrlPrefix}/${key}` } : {}
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
function uploadOne(surface, mutation, input) {
|
|
252
|
+
const entry = {
|
|
253
|
+
mutation,
|
|
254
|
+
filesTable: surface.files.name,
|
|
255
|
+
input,
|
|
256
|
+
outcome: "failed",
|
|
257
|
+
fileId: null,
|
|
258
|
+
error: null,
|
|
259
|
+
at: Date.now()
|
|
260
|
+
};
|
|
261
|
+
uploads.push(entry);
|
|
262
|
+
try {
|
|
263
|
+
const refused = options.failure?.(input);
|
|
264
|
+
if (refused) throw fail(refused.message, refused.code ?? "UPLOAD_FAILED");
|
|
265
|
+
const contentHash = String(input.contentHash ?? "");
|
|
266
|
+
const contentType = String(input.contentType ?? "");
|
|
267
|
+
if (!/^[0-9a-f]{64}$/i.test(contentHash)) {
|
|
268
|
+
throw fail("INVALID_CONTENT_HASH_FORMAT: must be a 64-char lowercase hex SHA-256", "INVALID_CONTENT_HASH_FORMAT");
|
|
269
|
+
}
|
|
270
|
+
const bucket = resolveBucket(surface, input);
|
|
271
|
+
if (!mimeAllowed(bucket.allowedMimeTypes, contentType)) {
|
|
272
|
+
throw fail(`CONTENT_TYPE_NOT_ALLOWED: ${contentType} not in bucket allowed types`, "CONTENT_TYPE_NOT_ALLOWED");
|
|
273
|
+
}
|
|
274
|
+
const maxFileSize = bucket.maxFileSize == null ? null : Number(bucket.maxFileSize);
|
|
275
|
+
if (maxFileSize && Number(input.size) > maxFileSize) {
|
|
276
|
+
throw fail(`FILE_TOO_LARGE: exceeds bucket max of ${maxFileSize} bytes`, "FILE_TOO_LARGE");
|
|
277
|
+
}
|
|
278
|
+
const key = typeof input.key === "string" && input.key ? input.key : contentHash;
|
|
279
|
+
const rows = tableRows(surface.files);
|
|
280
|
+
const link = surface.bucketLink;
|
|
281
|
+
const inBucket = (row) => !link || row[link.local] === bucket[link.remote];
|
|
282
|
+
const existing = rows.find((row) => row.key === key && inBucket(row));
|
|
283
|
+
const live = existing && LIVE_STATUSES.has(String(existing.status));
|
|
284
|
+
if (live || options.deduplicated) {
|
|
285
|
+
const fileId2 = existing && live ? String(existing.id) : createRow(surface, bucket, key, input, "uploaded");
|
|
286
|
+
Object.assign(entry, { outcome: "deduplicated", fileId: fileId2 });
|
|
287
|
+
return {
|
|
288
|
+
uploadUrl: null,
|
|
289
|
+
uploadHeaders: null,
|
|
290
|
+
fileId: fileId2,
|
|
291
|
+
key,
|
|
292
|
+
deduplicated: true,
|
|
293
|
+
expiresAt: null,
|
|
294
|
+
file: projection(fileId2, key, bucket, input)
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
if (existing) rows.splice(rows.indexOf(existing), 1);
|
|
298
|
+
const rejected = options.rejectUpload?.(input) ?? false;
|
|
299
|
+
const refusals = rejected ? 0 : options.notLiveForWrites ?? 0;
|
|
300
|
+
const fileId = createRow(surface, bucket, key, input, rejected ? "rejected" : refusals > 0 ? "requested" : "uploaded");
|
|
301
|
+
if (refusals > 0) refusalsLeft.set(fileId, refusals);
|
|
302
|
+
Object.assign(entry, { outcome: "requested", fileId });
|
|
303
|
+
return {
|
|
304
|
+
uploadUrl: `${uploadUrlPrefix}/${fileId}`,
|
|
305
|
+
uploadHeaders: {
|
|
306
|
+
"Content-Type": contentType,
|
|
307
|
+
"x-amz-checksum-sha256": hexToBase64(contentHash),
|
|
308
|
+
"x-amz-meta-upload-id": fileId
|
|
309
|
+
},
|
|
310
|
+
fileId,
|
|
311
|
+
key,
|
|
312
|
+
deduplicated: false,
|
|
313
|
+
expiresAt: new Date(Date.now() + UPLOAD_URL_LIFETIME_MS).toISOString(),
|
|
314
|
+
file: projection(fileId, key, bucket, input)
|
|
315
|
+
};
|
|
316
|
+
} catch (error) {
|
|
317
|
+
entry.error = error instanceof Error ? error.message : String(error);
|
|
318
|
+
throw error;
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
function createRow(surface, bucket, key, input, status) {
|
|
322
|
+
const fileId = nextFileId();
|
|
323
|
+
const now = (/* @__PURE__ */ new Date()).toISOString();
|
|
324
|
+
const row = {};
|
|
325
|
+
for (const column of surface.files.columns) row[column.name] = null;
|
|
326
|
+
assign(surface, row, "id", fileId);
|
|
327
|
+
if (surface.bucketLink) row[surface.bucketLink.local] = bucket[surface.bucketLink.remote];
|
|
328
|
+
assign(surface, row, "key", key);
|
|
329
|
+
assign(surface, row, "contentHash", input.contentHash);
|
|
330
|
+
assign(surface, row, "mimeType", input.contentType);
|
|
331
|
+
assign(surface, row, "size", String(input.size));
|
|
332
|
+
assign(surface, row, "filename", input.filename ?? null);
|
|
333
|
+
assign(surface, row, "isPublic", bucket.isPublic === true);
|
|
334
|
+
assign(surface, row, "status", status);
|
|
335
|
+
assign(surface, row, "createdAt", now);
|
|
336
|
+
assign(surface, row, "updatedAt", now);
|
|
337
|
+
tableRows(surface.files).push(row);
|
|
338
|
+
return fileId;
|
|
339
|
+
}
|
|
340
|
+
return {
|
|
341
|
+
uploads,
|
|
342
|
+
rootResolvers(onRequest) {
|
|
343
|
+
const root = {};
|
|
344
|
+
for (const surface of surfaces) {
|
|
345
|
+
root[surface.mutation] = (args) => {
|
|
346
|
+
onRequest(surface.files);
|
|
347
|
+
return uploadOne(surface, surface.mutation, args.input ?? {});
|
|
348
|
+
};
|
|
349
|
+
if (surface.bulkMutation) {
|
|
350
|
+
const bulk = surface.bulkMutation;
|
|
351
|
+
root[bulk] = (args) => {
|
|
352
|
+
onRequest(surface.files);
|
|
353
|
+
const { files = [], ...shared } = args.input ?? {};
|
|
354
|
+
return { files: files.map((file) => uploadOne(surface, bulk, { ...shared, ...file })) };
|
|
355
|
+
};
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
return root;
|
|
359
|
+
},
|
|
360
|
+
assertFileRefsLive(model, values) {
|
|
361
|
+
for (const column of model.columns) {
|
|
362
|
+
if (!column.value.file || column.value.file.kind === "attachment") continue;
|
|
363
|
+
const value = values[column.name];
|
|
364
|
+
const references = (Array.isArray(value) ? value : [value]).filter(
|
|
365
|
+
(entry) => Boolean(entry) && typeof entry.id === "string"
|
|
366
|
+
);
|
|
367
|
+
for (const { id } of references) {
|
|
368
|
+
const found = fileRow(id);
|
|
369
|
+
if (!found || LIVE_STATUSES.has(String(found.row.status))) continue;
|
|
370
|
+
const status = String(found.row.status);
|
|
371
|
+
const left = refusalsLeft.get(id) ?? 0;
|
|
372
|
+
if (left > 0) {
|
|
373
|
+
refusalsLeft.set(id, left - 1);
|
|
374
|
+
if (left === 1) found.row.status = "uploaded";
|
|
375
|
+
}
|
|
376
|
+
throw fail("FILE_REF_FILE_NOT_LIVE", "FILE_REF_FILE_NOT_LIVE", {
|
|
377
|
+
class: "public",
|
|
378
|
+
context: { field: column.name, file_id: id, status }
|
|
379
|
+
});
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
},
|
|
383
|
+
resolveField(model, row, fieldName) {
|
|
384
|
+
const surface = surfaces.find((candidate) => candidate.files.key === model.key);
|
|
385
|
+
if (!surface || fieldName !== surface.downloadUrlField) return null;
|
|
386
|
+
return { value: LIVE_STATUSES.has(String(row.status)) ? `https://storage.mock/download/${String(row.key)}` : null };
|
|
387
|
+
},
|
|
388
|
+
confirm(fileId) {
|
|
389
|
+
const found = fileRow(fileId);
|
|
390
|
+
if (found && found.row.status !== "rejected") found.row.status = "uploaded";
|
|
391
|
+
refusalsLeft.delete(fileId);
|
|
392
|
+
}
|
|
393
|
+
};
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
// src/testing/model-backend.ts
|
|
397
|
+
var ROW_MODEL = /* @__PURE__ */ Symbol("row-model");
|
|
398
|
+
function documentSource(document) {
|
|
38
399
|
if (typeof document === "string") return document;
|
|
39
400
|
if (document instanceof String) return document.toString();
|
|
40
|
-
if (document && typeof document === "object" && "kind" in document)
|
|
41
|
-
return print(document);
|
|
42
|
-
}
|
|
401
|
+
if (document && typeof document === "object" && "kind" in document) return print(document);
|
|
43
402
|
return String(document ?? "");
|
|
44
403
|
}
|
|
404
|
+
function sameValue(left, right) {
|
|
405
|
+
if (left === right) return true;
|
|
406
|
+
if (left == null || right == null) return false;
|
|
407
|
+
return JSON.stringify(left) === JSON.stringify(right);
|
|
408
|
+
}
|
|
409
|
+
function compare(left, right) {
|
|
410
|
+
if (left == null && right == null) return 0;
|
|
411
|
+
if (left == null) return -1;
|
|
412
|
+
if (right == null) return 1;
|
|
413
|
+
const leftNumber = typeof left === "number" ? left : Number(left);
|
|
414
|
+
const rightNumber = typeof right === "number" ? right : Number(right);
|
|
415
|
+
if (typeof left !== "boolean" && Number.isFinite(leftNumber) && Number.isFinite(rightNumber) && String(left).trim() !== "" && String(right).trim() !== "") {
|
|
416
|
+
return leftNumber - rightNumber;
|
|
417
|
+
}
|
|
418
|
+
return String(left).localeCompare(String(right));
|
|
419
|
+
}
|
|
420
|
+
function matchesOperator(value, operator, operand) {
|
|
421
|
+
const text = (input) => String(input ?? "").toLowerCase();
|
|
422
|
+
switch (operator) {
|
|
423
|
+
case "isNull":
|
|
424
|
+
return operand ? value == null : value != null;
|
|
425
|
+
case "equalTo":
|
|
426
|
+
return sameValue(value, operand);
|
|
427
|
+
case "notEqualTo":
|
|
428
|
+
return !sameValue(value, operand);
|
|
429
|
+
case "distinctFrom":
|
|
430
|
+
return !sameValue(value, operand);
|
|
431
|
+
case "notDistinctFrom":
|
|
432
|
+
return sameValue(value, operand);
|
|
433
|
+
case "in":
|
|
434
|
+
return Array.isArray(operand) && operand.some((item) => sameValue(value, item));
|
|
435
|
+
case "notIn":
|
|
436
|
+
return Array.isArray(operand) && !operand.some((item) => sameValue(value, item));
|
|
437
|
+
case "lessThan":
|
|
438
|
+
return value != null && compare(value, operand) < 0;
|
|
439
|
+
case "lessThanOrEqualTo":
|
|
440
|
+
return value != null && compare(value, operand) <= 0;
|
|
441
|
+
case "greaterThan":
|
|
442
|
+
return value != null && compare(value, operand) > 0;
|
|
443
|
+
case "greaterThanOrEqualTo":
|
|
444
|
+
return value != null && compare(value, operand) >= 0;
|
|
445
|
+
case "includes":
|
|
446
|
+
return String(value ?? "").includes(String(operand));
|
|
447
|
+
case "notIncludes":
|
|
448
|
+
return !String(value ?? "").includes(String(operand));
|
|
449
|
+
case "includesInsensitive":
|
|
450
|
+
return text(value).includes(text(operand));
|
|
451
|
+
case "notIncludesInsensitive":
|
|
452
|
+
return !text(value).includes(text(operand));
|
|
453
|
+
case "startsWith":
|
|
454
|
+
return String(value ?? "").startsWith(String(operand));
|
|
455
|
+
case "notStartsWith":
|
|
456
|
+
return !String(value ?? "").startsWith(String(operand));
|
|
457
|
+
case "startsWithInsensitive":
|
|
458
|
+
return text(value).startsWith(text(operand));
|
|
459
|
+
case "notStartsWithInsensitive":
|
|
460
|
+
return !text(value).startsWith(text(operand));
|
|
461
|
+
case "endsWith":
|
|
462
|
+
return String(value ?? "").endsWith(String(operand));
|
|
463
|
+
case "notEndsWith":
|
|
464
|
+
return !String(value ?? "").endsWith(String(operand));
|
|
465
|
+
case "endsWithInsensitive":
|
|
466
|
+
return text(value).endsWith(text(operand));
|
|
467
|
+
case "notEndsWithInsensitive":
|
|
468
|
+
return !text(value).endsWith(text(operand));
|
|
469
|
+
case "equalToInsensitive":
|
|
470
|
+
return text(value) === text(operand);
|
|
471
|
+
case "notEqualToInsensitive":
|
|
472
|
+
return text(value) !== text(operand);
|
|
473
|
+
case "inInsensitive":
|
|
474
|
+
return Array.isArray(operand) && operand.some((item) => text(value) === text(item));
|
|
475
|
+
case "notInInsensitive":
|
|
476
|
+
return Array.isArray(operand) && !operand.some((item) => text(value) === text(item));
|
|
477
|
+
case "anyEqualTo":
|
|
478
|
+
return Array.isArray(value) && value.some((item) => sameValue(item, operand));
|
|
479
|
+
case "anyNotEqualTo":
|
|
480
|
+
return Array.isArray(value) && value.some((item) => !sameValue(item, operand));
|
|
481
|
+
case "contains":
|
|
482
|
+
return Array.isArray(value) && Array.isArray(operand) && operand.every((item) => value.some((entry) => sameValue(entry, item)));
|
|
483
|
+
case "containedBy":
|
|
484
|
+
return Array.isArray(value) && Array.isArray(operand) && value.every((entry) => operand.some((item) => sameValue(entry, item)));
|
|
485
|
+
case "overlaps":
|
|
486
|
+
return Array.isArray(value) && Array.isArray(operand) && value.some((entry) => operand.some((item) => sameValue(entry, item)));
|
|
487
|
+
default:
|
|
488
|
+
throw createError.badRequest(`The mock backend does not support the "${operator}" filter.`);
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
function matchesFilter(model, row, filter, related) {
|
|
492
|
+
if (!filter) return true;
|
|
493
|
+
const matches = (target, candidate, condition) => matchesFilter(target, candidate, condition, related);
|
|
494
|
+
return Object.entries(filter).every(([key, condition]) => {
|
|
495
|
+
if (condition === void 0 || condition === null) return true;
|
|
496
|
+
if (key === "and") return condition.every((part) => matches(model, row, part));
|
|
497
|
+
if (key === "or") return condition.some((part) => matches(model, row, part));
|
|
498
|
+
if (key === "not") return !matches(model, row, condition);
|
|
499
|
+
const column = model.columns.find((candidate) => candidate.filter?.field === key);
|
|
500
|
+
if (column) {
|
|
501
|
+
return Object.entries(condition).every(
|
|
502
|
+
([operator, operand]) => matchesOperator(row[column.name], operator, operand)
|
|
503
|
+
);
|
|
504
|
+
}
|
|
505
|
+
if (key === model.search?.unifiedSearchField) {
|
|
506
|
+
const needle = String(condition).toLowerCase();
|
|
507
|
+
return model.columns.some(
|
|
508
|
+
(candidate) => candidate.value.kind === "text" && String(row[candidate.name] ?? "").toLowerCase().includes(needle)
|
|
509
|
+
);
|
|
510
|
+
}
|
|
511
|
+
const byExists = model.relations.find((relation2) => relation2.filter?.exists === key);
|
|
512
|
+
if (byExists) return related(model, row, byExists).rows.length > 0 === Boolean(condition);
|
|
513
|
+
const relation = model.relations.find((candidate) => candidate.filter?.field === key);
|
|
514
|
+
const filter2 = relation?.filter;
|
|
515
|
+
if (!relation || !filter2) throw createError.badRequest(`The mock backend does not filter by "${key}".`);
|
|
516
|
+
const { target, rows } = related(model, row, relation);
|
|
517
|
+
const nested = condition;
|
|
518
|
+
if (!filter2.many) {
|
|
519
|
+
if (Object.keys(nested).length === 0) return true;
|
|
520
|
+
return Boolean(target && rows[0] && matches(target, rows[0], nested));
|
|
521
|
+
}
|
|
522
|
+
const many = filter2.many;
|
|
523
|
+
return Object.entries(nested).every(([quantifier, inner]) => {
|
|
524
|
+
const test = (candidate) => Boolean(target) && matches(target, candidate, inner);
|
|
525
|
+
if (quantifier === many.some) return rows.some(test);
|
|
526
|
+
if (quantifier === many.every) return rows.every(test);
|
|
527
|
+
if (quantifier === many.none) return !rows.some(test);
|
|
528
|
+
throw createError.badRequest(`The mock backend does not support the "${quantifier}" relation filter.`);
|
|
529
|
+
});
|
|
530
|
+
});
|
|
531
|
+
}
|
|
532
|
+
function sortRows(model, rows, orderBy) {
|
|
533
|
+
const values = Array.isArray(orderBy) ? orderBy : [];
|
|
534
|
+
const keys = values.flatMap((value) => {
|
|
535
|
+
if (value === "NATURAL") return [];
|
|
536
|
+
if (value === "PRIMARY_KEY_ASC" || value === "PRIMARY_KEY_DESC") {
|
|
537
|
+
return model.primaryKey.map((field) => ({ field, desc: value === "PRIMARY_KEY_DESC" }));
|
|
538
|
+
}
|
|
539
|
+
const column = model.columns.find((candidate) => candidate.sort?.asc === value || candidate.sort?.desc === value);
|
|
540
|
+
if (!column) throw createError.badRequest(`The mock backend does not sort by "${value}".`);
|
|
541
|
+
return [{ field: column.name, desc: column.sort?.desc === value }];
|
|
542
|
+
});
|
|
543
|
+
if (keys.length === 0) return rows;
|
|
544
|
+
return [...rows].sort((left, right) => {
|
|
545
|
+
for (const { field, desc } of keys) {
|
|
546
|
+
const order = compare(left[field], right[field]);
|
|
547
|
+
if (order !== 0) return desc ? -order : order;
|
|
548
|
+
}
|
|
549
|
+
return 0;
|
|
550
|
+
});
|
|
551
|
+
}
|
|
552
|
+
function page(rows, args) {
|
|
553
|
+
const afterIndex = typeof args.after === "string" && args.after !== "" ? Number(args.after) : Number.NaN;
|
|
554
|
+
const start = Number.isFinite(afterIndex) ? afterIndex : typeof args.offset === "number" ? args.offset : 0;
|
|
555
|
+
const end = typeof args.first === "number" ? start + args.first : rows.length;
|
|
556
|
+
const nodes = rows.slice(start, end);
|
|
557
|
+
return {
|
|
558
|
+
nodes,
|
|
559
|
+
totalCount: rows.length,
|
|
560
|
+
pageInfo: {
|
|
561
|
+
hasNextPage: end < rows.length,
|
|
562
|
+
hasPreviousPage: start > 0,
|
|
563
|
+
startCursor: nodes.length > 0 ? String(start) : null,
|
|
564
|
+
endCursor: nodes.length > 0 ? String(start + nodes.length) : null
|
|
565
|
+
}
|
|
566
|
+
};
|
|
567
|
+
}
|
|
568
|
+
function keyMatches(row, key) {
|
|
569
|
+
return Object.entries(key).every(([field, value]) => sameValue(row[field], value));
|
|
570
|
+
}
|
|
571
|
+
var generatedIds = 0;
|
|
572
|
+
function generatedKey(column) {
|
|
573
|
+
generatedIds += 1;
|
|
574
|
+
if (column.value.kind === "uuid") return `00000000-0000-4000-8000-${String(generatedIds).padStart(12, "0")}`;
|
|
575
|
+
if (column.value.kind === "integer" || column.value.kind === "bigint") {
|
|
576
|
+
return column.value.kind === "bigint" ? String(1e5 + generatedIds) : 1e5 + generatedIds;
|
|
577
|
+
}
|
|
578
|
+
return `mock-${generatedIds}`;
|
|
579
|
+
}
|
|
580
|
+
function storedValue(schema, column, written, previous) {
|
|
581
|
+
if (column.value.kind !== "geometry" || written == null) return written;
|
|
582
|
+
const prior = previous && typeof previous === "object" ? previous : {};
|
|
583
|
+
const type = schema.getType(column.value.typeName);
|
|
584
|
+
const concrete = prior.__typename ?? (type && isAbstractType(type) ? schema.getPossibleTypes(type)[0]?.name : void 0);
|
|
585
|
+
return { ...prior, ...concrete ? { __typename: concrete } : {}, geojson: written, srid: prior.srid ?? 0 };
|
|
586
|
+
}
|
|
587
|
+
function createModelBackend(options) {
|
|
588
|
+
const { schema, meta } = options;
|
|
589
|
+
const rows = options.rows;
|
|
590
|
+
const mutations = [];
|
|
591
|
+
const uploads = [];
|
|
592
|
+
let uploadService = null;
|
|
593
|
+
const hasMetaTypes = Boolean(schema.getType("MetaTable"));
|
|
594
|
+
const introspect = async (document, variables) => {
|
|
595
|
+
const result = await graphql({ schema, source: documentSource(document), variableValues: variables });
|
|
596
|
+
if (result.errors?.length) throw createError.graphql(result.errors[0].message);
|
|
597
|
+
return result.data;
|
|
598
|
+
};
|
|
599
|
+
let modelsPromise = null;
|
|
600
|
+
const models = () => {
|
|
601
|
+
modelsPromise ??= (async () => {
|
|
602
|
+
const resolver = createTableModelResolver(meta);
|
|
603
|
+
const resolved = [];
|
|
604
|
+
for (const table of metaTablesOf(meta)) resolved.push(await resolver.resolve(introspect, tableKeyOf(table)));
|
|
605
|
+
return resolved;
|
|
606
|
+
})();
|
|
607
|
+
return modelsPromise;
|
|
608
|
+
};
|
|
609
|
+
const tableRows = (model) => rows[model.name] ??= [];
|
|
610
|
+
const stored = (model, row) => Object.assign({ ...row }, { [ROW_MODEL]: model });
|
|
611
|
+
const record = (op, model, variables) => {
|
|
612
|
+
const mutation = { op, tableName: model.name, variables: variables ?? {}, at: Date.now() };
|
|
613
|
+
mutations.push(mutation);
|
|
614
|
+
options.onMutation?.(mutation);
|
|
615
|
+
};
|
|
616
|
+
function relatedRowsIn(all) {
|
|
617
|
+
return (_model, row, relation) => {
|
|
618
|
+
const target = all.find((candidate) => candidate.key === relation.targetKey) ?? null;
|
|
619
|
+
if (target && relation.junction) {
|
|
620
|
+
const junction = all.find((candidate) => candidate.key === relation.junction.tableKey);
|
|
621
|
+
const links = junction ? tableRows(junction).filter((link) => relation.junction.left.every((pair) => sameValue(link[pair.junction], row[pair.local]))) : [];
|
|
622
|
+
return {
|
|
623
|
+
target,
|
|
624
|
+
rows: tableRows(target).filter(
|
|
625
|
+
(candidate) => links.some((link) => relation.junction.right.every((pair) => sameValue(candidate[pair.remote], link[pair.junction])))
|
|
626
|
+
)
|
|
627
|
+
};
|
|
628
|
+
}
|
|
629
|
+
if (target && relation.keys.length > 0) {
|
|
630
|
+
return {
|
|
631
|
+
target,
|
|
632
|
+
rows: tableRows(target).filter(
|
|
633
|
+
(candidate) => relation.keys.every((pair) => sameValue(candidate[pair.remote], row[pair.local]))
|
|
634
|
+
)
|
|
635
|
+
};
|
|
636
|
+
}
|
|
637
|
+
return { target, rows: [] };
|
|
638
|
+
};
|
|
639
|
+
}
|
|
640
|
+
function relationValue(all, model, row, relation, args) {
|
|
641
|
+
const { target, rows: related } = relatedRowsIn(all)(model, row, relation);
|
|
642
|
+
const nodes = related.map((entry) => stored(target, entry));
|
|
643
|
+
if (relation.shape === "object") return nodes[0] ?? null;
|
|
644
|
+
const limited = typeof args.first === "number" ? nodes.slice(0, args.first) : nodes;
|
|
645
|
+
return relation.shape === "list" ? limited : { nodes: limited, totalCount: nodes.length };
|
|
646
|
+
}
|
|
647
|
+
function rootResolvers(all, variables, files) {
|
|
648
|
+
const related = relatedRowsIn(all);
|
|
649
|
+
const root = {
|
|
650
|
+
...files.rootResolvers((filesModel) => record("upload", filesModel, variables))
|
|
651
|
+
};
|
|
652
|
+
for (const model of all) {
|
|
653
|
+
const ops = model.operations;
|
|
654
|
+
if (ops.list) {
|
|
655
|
+
const list = ops.list;
|
|
656
|
+
root[list.field] = (args) => {
|
|
657
|
+
const filtered = tableRows(model).filter(
|
|
658
|
+
(row) => matchesFilter(model, row, args[list.filter?.name ?? "where"], related)
|
|
659
|
+
);
|
|
660
|
+
const sorted = sortRows(model, filtered, args[list.orderBy?.name ?? "orderBy"]);
|
|
661
|
+
const result = page(sorted, args);
|
|
662
|
+
const nodes = result.nodes.map((row) => stored(model, row));
|
|
663
|
+
return list.shape === "list" ? nodes : { ...result, nodes };
|
|
664
|
+
};
|
|
665
|
+
}
|
|
666
|
+
if (ops.create) {
|
|
667
|
+
const create = ops.create;
|
|
668
|
+
root[create.field] = (args) => {
|
|
669
|
+
record("create", model, variables);
|
|
670
|
+
const values = args[create.input.name]?.[create.recordField] ?? {};
|
|
671
|
+
files.assertFileRefsLive(model, values);
|
|
672
|
+
const row = {};
|
|
673
|
+
for (const column of model.columns) {
|
|
674
|
+
if (Object.prototype.hasOwnProperty.call(values, column.name)) {
|
|
675
|
+
row[column.name] = storedValue(schema, column, values[column.name], void 0);
|
|
676
|
+
} else if (column.isPrimaryKey) {
|
|
677
|
+
row[column.name] = generatedKey(column);
|
|
678
|
+
} else if (!column.hasDefault) {
|
|
679
|
+
row[column.name] = null;
|
|
680
|
+
} else {
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
tableRows(model).push(row);
|
|
684
|
+
return { clientMutationId: null, [create.payloadField]: stored(model, row) };
|
|
685
|
+
};
|
|
686
|
+
}
|
|
687
|
+
if (ops.update) {
|
|
688
|
+
const update = ops.update;
|
|
689
|
+
root[update.field] = (args) => {
|
|
690
|
+
record("update", model, variables);
|
|
691
|
+
const input = args[update.input.name] ?? {};
|
|
692
|
+
const key = Object.fromEntries(update.keyArgs.map((field) => [field, input[field]]));
|
|
693
|
+
const row = tableRows(model).find((candidate) => keyMatches(candidate, key));
|
|
694
|
+
if (!row || options.writeHidden?.(model.name, row)) return { clientMutationId: null, [update.payloadField]: null };
|
|
695
|
+
const patch = input[update.patchField] ?? {};
|
|
696
|
+
files.assertFileRefsLive(model, patch);
|
|
697
|
+
for (const [field, value] of Object.entries(patch)) {
|
|
698
|
+
const column = model.columns.find((candidate) => candidate.name === field);
|
|
699
|
+
row[field] = column ? storedValue(schema, column, value, row[field]) : value;
|
|
700
|
+
}
|
|
701
|
+
return { clientMutationId: null, [update.payloadField]: stored(model, row) };
|
|
702
|
+
};
|
|
703
|
+
}
|
|
704
|
+
if (ops.delete) {
|
|
705
|
+
const remove = ops.delete;
|
|
706
|
+
root[remove.field] = (args) => {
|
|
707
|
+
record("delete", model, variables);
|
|
708
|
+
const input = args[remove.input.name] ?? {};
|
|
709
|
+
const key = Object.fromEntries(remove.keyArgs.map((field) => [field, input[field]]));
|
|
710
|
+
const list = tableRows(model);
|
|
711
|
+
const found = list.findIndex((candidate) => keyMatches(candidate, key));
|
|
712
|
+
const index = found !== -1 && options.writeHidden?.(model.name, list[found]) ? -1 : found;
|
|
713
|
+
const [row] = index === -1 ? [] : list.splice(index, 1);
|
|
714
|
+
return { clientMutationId: null, ...remove.payloadField ? { [remove.payloadField]: row ? stored(model, row) : null } : {} };
|
|
715
|
+
};
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
return root;
|
|
719
|
+
}
|
|
720
|
+
const execute = async (document, variables) => {
|
|
721
|
+
const source = documentSource(document);
|
|
722
|
+
if (source.includes("ConstructiveMetaContract") && !hasMetaTypes) return createMetaContractFixture();
|
|
723
|
+
if (/query ConstructiveMeta\b/.test(source)) {
|
|
724
|
+
const errors = hasMetaTypes ? validate(schema, parse(source)) : [];
|
|
725
|
+
if (errors.length > 0) throw createError.graphql(errors[0].message);
|
|
726
|
+
return meta;
|
|
727
|
+
}
|
|
728
|
+
if (/\b__(schema|type)\b/.test(source)) return introspect(source, variables);
|
|
729
|
+
const all = await models();
|
|
730
|
+
const files = uploadService ??= createUploadService(all, tableRows, options.uploads, uploads);
|
|
731
|
+
const fieldResolver = (parent, args, context, info) => {
|
|
732
|
+
const model = parent?.[ROW_MODEL];
|
|
733
|
+
const computed = model ? files.resolveField(model, parent, info.fieldName) : null;
|
|
734
|
+
if (computed) return computed.value;
|
|
735
|
+
const relation = model?.relations.find((candidate) => candidate.fieldName === info.fieldName);
|
|
736
|
+
if (model && relation) return relationValue(all, model, parent, relation, args);
|
|
737
|
+
return defaultFieldResolver(parent, args, context, info);
|
|
738
|
+
};
|
|
739
|
+
const result = await graphql({
|
|
740
|
+
schema,
|
|
741
|
+
source,
|
|
742
|
+
variableValues: variables,
|
|
743
|
+
rootValue: rootResolvers(all, variables, files),
|
|
744
|
+
fieldResolver
|
|
745
|
+
});
|
|
746
|
+
if (result.errors?.length) {
|
|
747
|
+
const first = result.errors[0];
|
|
748
|
+
const code = first.extensions?.code;
|
|
749
|
+
throw withResponseErrors(
|
|
750
|
+
createError.graphql(first.message, typeof code === "string" ? code : void 0),
|
|
751
|
+
result.data,
|
|
752
|
+
result.errors
|
|
753
|
+
);
|
|
754
|
+
}
|
|
755
|
+
return result.data;
|
|
756
|
+
};
|
|
757
|
+
const confirmUpload = (fileId) => {
|
|
758
|
+
if (uploadService) {
|
|
759
|
+
uploadService.confirm(fileId);
|
|
760
|
+
return;
|
|
761
|
+
}
|
|
762
|
+
for (const list of Object.values(rows)) {
|
|
763
|
+
for (const row of list) if (row.id === fileId && "status" in row) row.status = "uploaded";
|
|
764
|
+
}
|
|
765
|
+
};
|
|
766
|
+
return { execute, mutations, uploads, rows, confirmUpload };
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
// src/testing/mock-sheets-provider.tsx
|
|
770
|
+
import { jsx } from "react/jsx-runtime";
|
|
45
771
|
function buildMetaField(field, primaryKeyFields) {
|
|
46
772
|
return {
|
|
47
773
|
name: field.name,
|
|
48
774
|
isPrimaryKey: primaryKeyFields.has(field.name),
|
|
775
|
+
isForeignKey: false,
|
|
49
776
|
isNotNull: false,
|
|
50
777
|
hasDefault: false,
|
|
778
|
+
description: null,
|
|
779
|
+
enumValues: null,
|
|
51
780
|
type: {
|
|
52
781
|
gqlType: field.gqlType,
|
|
53
782
|
isArray: field.isArray ?? false,
|
|
54
783
|
pgType: field.pgType ?? "text",
|
|
55
784
|
isNotNull: false,
|
|
56
785
|
hasDefault: false,
|
|
57
|
-
subtype: field.subtype ?? null
|
|
786
|
+
subtype: field.subtype ?? null,
|
|
787
|
+
encoding: null
|
|
58
788
|
}
|
|
59
789
|
};
|
|
60
790
|
}
|
|
@@ -62,162 +792,59 @@ function buildMetaTable(table) {
|
|
|
62
792
|
const primaryKeyFields = table.primaryKeyFields ?? (table.fields.some((field) => field.name === "id") ? ["id"] : []);
|
|
63
793
|
const primaryKeySet = new Set(primaryKeyFields);
|
|
64
794
|
const primaryKeyMetaFields = table.fields.filter((field) => primaryKeySet.has(field.name)).map((field) => buildMetaField(field, primaryKeySet));
|
|
795
|
+
const hasKey = primaryKeyMetaFields.length > 0;
|
|
65
796
|
return {
|
|
66
797
|
name: table.name,
|
|
67
798
|
schemaName: "public",
|
|
68
799
|
query: {
|
|
69
800
|
all: toCamelCasePlural(table.name),
|
|
801
|
+
one: null,
|
|
70
802
|
create: toCreateMutationName(table.name),
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
update: toUpdateMutationName(table.name)
|
|
803
|
+
update: hasKey ? toUpdateMutationName(table.name) : null,
|
|
804
|
+
delete: hasKey ? toDeleteMutationName(table.name) : null
|
|
74
805
|
},
|
|
75
806
|
fields: table.fields.map((field) => buildMetaField(field, primaryKeySet)),
|
|
76
807
|
inflection: {
|
|
808
|
+
tableType: table.name,
|
|
77
809
|
allRows: toCamelCasePlural(table.name),
|
|
78
|
-
connection:
|
|
79
|
-
|
|
810
|
+
connection: `${table.name}Connection`,
|
|
811
|
+
filterType: `${table.name}Filter`,
|
|
812
|
+
orderByType: `${table.name}OrderBy`
|
|
80
813
|
},
|
|
81
814
|
indexes: [],
|
|
82
815
|
constraints: {
|
|
83
|
-
primaryKey:
|
|
816
|
+
primaryKey: hasKey ? { name: `${table.name}_pkey`, fields: primaryKeyMetaFields } : null,
|
|
84
817
|
unique: [],
|
|
85
818
|
foreignKey: []
|
|
86
819
|
},
|
|
87
820
|
foreignKeyConstraints: [],
|
|
88
|
-
primaryKeyConstraints:
|
|
821
|
+
primaryKeyConstraints: hasKey ? [{ name: `${table.name}_pkey`, fields: primaryKeyMetaFields }] : [],
|
|
89
822
|
uniqueConstraints: [],
|
|
90
|
-
relations: { belongsTo: [], has: [], hasOne: [], hasMany: [], manyToMany: [] }
|
|
823
|
+
relations: { belongsTo: [], has: [], hasOne: [], hasMany: [], manyToMany: [] },
|
|
824
|
+
storage: null,
|
|
825
|
+
search: null,
|
|
826
|
+
i18n: null,
|
|
827
|
+
realtime: null,
|
|
828
|
+
scope: null
|
|
91
829
|
};
|
|
92
830
|
}
|
|
93
831
|
function buildMetaResponse(tables) {
|
|
94
|
-
return {
|
|
95
|
-
_meta: {
|
|
96
|
-
tables: tables.map(buildMetaTable)
|
|
97
|
-
}
|
|
98
|
-
};
|
|
99
|
-
}
|
|
100
|
-
function buildListResponse(table) {
|
|
101
|
-
const field = toCamelCasePlural(table.name);
|
|
102
|
-
return {
|
|
103
|
-
[field]: {
|
|
104
|
-
nodes: table.rows,
|
|
105
|
-
totalCount: table.rows.length,
|
|
106
|
-
pageInfo: {
|
|
107
|
-
hasNextPage: false,
|
|
108
|
-
hasPreviousPage: false,
|
|
109
|
-
endCursor: null,
|
|
110
|
-
startCursor: null
|
|
111
|
-
}
|
|
112
|
-
}
|
|
113
|
-
};
|
|
114
|
-
}
|
|
115
|
-
var mockIdCounter = 0;
|
|
116
|
-
function synthesizeId() {
|
|
117
|
-
mockIdCounter += 1;
|
|
118
|
-
return `mock-${mockIdCounter}`;
|
|
119
|
-
}
|
|
120
|
-
function extractMutationInput(variables) {
|
|
121
|
-
const input = variables?.input;
|
|
122
|
-
return input && typeof input === "object" ? input : {};
|
|
123
|
-
}
|
|
124
|
-
function synthesizeCreatedRow(table, singular, variables) {
|
|
125
|
-
const input = extractMutationInput(variables);
|
|
126
|
-
const data = input[singular] ?? {};
|
|
127
|
-
const row = { id: synthesizeId(), ...data };
|
|
128
|
-
table.rows.push(row);
|
|
129
|
-
return row;
|
|
130
|
-
}
|
|
131
|
-
function synthesizeUpdatedRow(table, variables) {
|
|
132
|
-
const input = extractMutationInput(variables);
|
|
133
|
-
const id = input.id;
|
|
134
|
-
let patch = {};
|
|
135
|
-
for (const [key, value] of Object.entries(input)) {
|
|
136
|
-
if (key === "id") continue;
|
|
137
|
-
if (value && typeof value === "object") {
|
|
138
|
-
patch = value;
|
|
139
|
-
break;
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
const existing = table.rows.find((r) => r.id === id);
|
|
143
|
-
const merged = { ...existing ?? { id }, ...patch };
|
|
144
|
-
if (existing) {
|
|
145
|
-
Object.assign(existing, patch);
|
|
146
|
-
} else {
|
|
147
|
-
table.rows.push(merged);
|
|
148
|
-
}
|
|
149
|
-
return merged;
|
|
150
|
-
}
|
|
151
|
-
function isMetaQuery(query) {
|
|
152
|
-
return query.includes("_meta");
|
|
153
|
-
}
|
|
154
|
-
function isMutationDocument(query) {
|
|
155
|
-
return /(^|\s)mutation(\s|\{)/.test(query);
|
|
156
|
-
}
|
|
157
|
-
function findMutationTable(query, tables) {
|
|
158
|
-
let best = null;
|
|
159
|
-
for (const table of tables) {
|
|
160
|
-
const candidates = [
|
|
161
|
-
{ op: "create", mutationName: toCreateMutationName(table.name) },
|
|
162
|
-
{ op: "update", mutationName: toUpdateMutationName(table.name) },
|
|
163
|
-
{ op: "delete", mutationName: toDeleteMutationName(table.name) }
|
|
164
|
-
];
|
|
165
|
-
for (const c of candidates) {
|
|
166
|
-
if (query.includes(c.mutationName) && (!best || c.mutationName.length > best.mutationName.length)) {
|
|
167
|
-
best = { table, op: c.op, mutationName: c.mutationName, singular: toCamelCaseSingular(table.name) };
|
|
168
|
-
}
|
|
169
|
-
}
|
|
170
|
-
}
|
|
171
|
-
return best;
|
|
172
|
-
}
|
|
173
|
-
function findListTable(query, tables) {
|
|
174
|
-
let best = null;
|
|
175
|
-
let bestLen = 0;
|
|
176
|
-
for (const table of tables) {
|
|
177
|
-
const plural = toCamelCasePlural(table.name);
|
|
178
|
-
if (query.includes(plural) && plural.length > bestLen) {
|
|
179
|
-
best = table;
|
|
180
|
-
bestLen = plural.length;
|
|
181
|
-
}
|
|
182
|
-
}
|
|
183
|
-
return best;
|
|
832
|
+
return { _meta: { tables: tables.map(buildMetaTable) } };
|
|
184
833
|
}
|
|
185
834
|
function createMockExecute(opts) {
|
|
186
|
-
const
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
if (isMetaQuery(query)) {
|
|
197
|
-
return buildMetaResponse(opts.tables);
|
|
198
|
-
}
|
|
199
|
-
const mutationMatch = isMutationDocument(query) ? findMutationTable(query, opts.tables) : null;
|
|
200
|
-
if (mutationMatch) {
|
|
201
|
-
const { table, op, mutationName, singular } = mutationMatch;
|
|
202
|
-
record({ op, tableName: table.name, variables: variables ?? {}, at: Date.now() });
|
|
203
|
-
if (op === "delete") {
|
|
204
|
-
const input = extractMutationInput(variables);
|
|
205
|
-
const id = input.id ?? null;
|
|
206
|
-
table.rows = table.rows.filter((r) => r.id !== id);
|
|
207
|
-
return { [mutationName]: { deletedNodeId: id, clientMutationId: null } };
|
|
208
|
-
}
|
|
209
|
-
const row = op === "create" ? synthesizeCreatedRow(table, singular, variables) : synthesizeUpdatedRow(table, variables);
|
|
210
|
-
return { [mutationName]: { [singular]: row } };
|
|
211
|
-
}
|
|
212
|
-
const listTable = findListTable(query, opts.tables);
|
|
213
|
-
if (listTable) {
|
|
214
|
-
return buildListResponse(listTable);
|
|
215
|
-
}
|
|
216
|
-
return {};
|
|
217
|
-
};
|
|
835
|
+
const meta = buildMetaResponse(opts.tables);
|
|
836
|
+
const metaTables = (meta._meta?.tables ?? []).filter((table) => table != null);
|
|
837
|
+
const backend = createModelBackend({
|
|
838
|
+
schema: buildSchema(buildMetaSchemaSdl(metaTables)),
|
|
839
|
+
meta,
|
|
840
|
+
// The row arrays are shared with the caller's MockTables, so tests see writes in place.
|
|
841
|
+
rows: Object.fromEntries(opts.tables.map((table) => [table.name, table.rows])),
|
|
842
|
+
onMutation: opts.onMutation
|
|
843
|
+
});
|
|
844
|
+
const { mutations } = backend;
|
|
218
845
|
const executeUpload = async (file, path, options) => {
|
|
219
846
|
const name = file?.name ?? "file";
|
|
220
|
-
|
|
847
|
+
const upload = {
|
|
221
848
|
op: "upload",
|
|
222
849
|
tableName: options?.tableName ?? "",
|
|
223
850
|
variables: {
|
|
@@ -227,13 +854,27 @@ function createMockExecute(opts) {
|
|
|
227
854
|
...options?.recordId !== void 0 && { recordId: options.recordId }
|
|
228
855
|
},
|
|
229
856
|
at: Date.now()
|
|
230
|
-
}
|
|
231
|
-
|
|
857
|
+
};
|
|
858
|
+
mutations.push(upload);
|
|
859
|
+
opts.onMutation?.(upload);
|
|
860
|
+
const url = "mock://uploaded/" + name;
|
|
861
|
+
return {
|
|
862
|
+
file: {
|
|
863
|
+
id: "mock-file-" + mutations.length,
|
|
864
|
+
key: name,
|
|
865
|
+
bucket_id: "mock-bucket",
|
|
866
|
+
filename: name,
|
|
867
|
+
mime: file.type || "application/octet-stream",
|
|
868
|
+
size: file.size,
|
|
869
|
+
url
|
|
870
|
+
},
|
|
871
|
+
url
|
|
872
|
+
};
|
|
232
873
|
};
|
|
233
874
|
function reset() {
|
|
234
875
|
mutations.length = 0;
|
|
235
876
|
}
|
|
236
|
-
return { execute, executeUpload, mutations, reset };
|
|
877
|
+
return { execute: backend.execute, executeUpload, mutations, reset };
|
|
237
878
|
}
|
|
238
879
|
function MockSheetsProvider({ options, children }) {
|
|
239
880
|
const { execute, executeUpload } = useMemo(() => createMockExecute(options), []);
|
|
@@ -288,8 +929,10 @@ var usersFixture = {
|
|
|
288
929
|
};
|
|
289
930
|
export {
|
|
290
931
|
MockSheetsProvider,
|
|
932
|
+
buildMetaSchemaSdl,
|
|
291
933
|
createMetaContractFixture,
|
|
292
934
|
createMockExecute,
|
|
935
|
+
createModelBackend,
|
|
293
936
|
usersFixture
|
|
294
937
|
};
|
|
295
938
|
//# sourceMappingURL=testing.js.map
|