@constructive-io/sheets 0.3.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/LICENSE +21 -0
- package/README.md +188 -0
- package/dist/advanced.cjs +5477 -0
- package/dist/advanced.cjs.map +1 -0
- package/dist/advanced.d.cts +83 -0
- package/dist/advanced.d.ts +83 -0
- package/dist/advanced.js +34 -0
- package/dist/advanced.js.map +1 -0
- package/dist/auth.cjs +1396 -0
- package/dist/auth.cjs.map +1 -0
- package/dist/auth.d.cts +60 -0
- package/dist/auth.d.ts +60 -0
- package/dist/auth.js +19 -0
- package/dist/auth.js.map +1 -0
- package/dist/chunk-4PGPVMZB.js +670 -0
- package/dist/chunk-4PGPVMZB.js.map +1 -0
- package/dist/chunk-FNVHSOQQ.js +1314 -0
- package/dist/chunk-FNVHSOQQ.js.map +1 -0
- package/dist/chunk-GGECS2BP.js +17 -0
- package/dist/chunk-GGECS2BP.js.map +1 -0
- package/dist/chunk-GLVZSPV2.js +43 -0
- package/dist/chunk-GLVZSPV2.js.map +1 -0
- package/dist/chunk-H4JJTMP5.js +160 -0
- package/dist/chunk-H4JJTMP5.js.map +1 -0
- package/dist/chunk-ODUBS2NL.js +100 -0
- package/dist/chunk-ODUBS2NL.js.map +1 -0
- package/dist/chunk-PZL2BCWF.js +168 -0
- package/dist/chunk-PZL2BCWF.js.map +1 -0
- package/dist/chunk-TU7ATZ4X.js +4494 -0
- package/dist/chunk-TU7ATZ4X.js.map +1 -0
- package/dist/chunk-X7DHTSOX.js +21 -0
- package/dist/chunk-X7DHTSOX.js.map +1 -0
- package/dist/chunk-YDQQA46V.js +13 -0
- package/dist/chunk-YDQQA46V.js.map +1 -0
- package/dist/date-editor-CXKKGNL6.js +361 -0
- package/dist/date-editor-CXKKGNL6.js.map +1 -0
- package/dist/editor-props-M6Dh0P9f.d.cts +245 -0
- package/dist/editor-props-M6Dh0P9f.d.ts +245 -0
- package/dist/index.cjs +15861 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +1650 -0
- package/dist/index.d.ts +1650 -0
- package/dist/index.js +8470 -0
- package/dist/index.js.map +1 -0
- package/dist/map-picker-VTKDS6CM.js +290 -0
- package/dist/map-picker-VTKDS6CM.js.map +1 -0
- package/dist/sheets-context-CojEFlaY.d.cts +214 -0
- package/dist/sheets-context-Da55TTR9.d.ts +214 -0
- package/dist/testing.cjs +1113 -0
- package/dist/testing.cjs.map +1 -0
- package/dist/testing.d.cts +45 -0
- package/dist/testing.d.ts +45 -0
- package/dist/testing.js +269 -0
- package/dist/testing.js.map +1 -0
- package/package.json +144 -0
package/dist/testing.cjs
ADDED
|
@@ -0,0 +1,1113 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
"use strict";
|
|
3
|
+
var __defProp = Object.defineProperty;
|
|
4
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
5
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
7
|
+
var __export = (target, all) => {
|
|
8
|
+
for (var name in all)
|
|
9
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
10
|
+
};
|
|
11
|
+
var __copyProps = (to, from, except, desc) => {
|
|
12
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
13
|
+
for (let key of __getOwnPropNames(from))
|
|
14
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
15
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
16
|
+
}
|
|
17
|
+
return to;
|
|
18
|
+
};
|
|
19
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
20
|
+
|
|
21
|
+
// src/testing/index.ts
|
|
22
|
+
var testing_exports = {};
|
|
23
|
+
__export(testing_exports, {
|
|
24
|
+
MockSheetsProvider: () => MockSheetsProvider,
|
|
25
|
+
createMockExecute: () => createMockExecute,
|
|
26
|
+
usersFixture: () => usersFixture
|
|
27
|
+
});
|
|
28
|
+
module.exports = __toCommonJS(testing_exports);
|
|
29
|
+
|
|
30
|
+
// src/testing/mock-sheets-provider.tsx
|
|
31
|
+
var import_react4 = require("react");
|
|
32
|
+
var import_graphql2 = require("graphql");
|
|
33
|
+
var import_react_query2 = require("@tanstack/react-query");
|
|
34
|
+
var import_data5 = require("@constructive-io/data");
|
|
35
|
+
|
|
36
|
+
// src/context/sheets-provider.tsx
|
|
37
|
+
var import_react3 = require("react");
|
|
38
|
+
var import_react_query = require("@tanstack/react-query");
|
|
39
|
+
|
|
40
|
+
// src/context/sheets-context.ts
|
|
41
|
+
var import_react = require("react");
|
|
42
|
+
var SheetsContext = (0, import_react.createContext)(null);
|
|
43
|
+
|
|
44
|
+
// src/context/sheets-execute.ts
|
|
45
|
+
var import_graphql = require("graphql");
|
|
46
|
+
var import_data = require("@constructive-io/data");
|
|
47
|
+
var import_data2 = require("@constructive-io/data");
|
|
48
|
+
function documentToString(document) {
|
|
49
|
+
if (typeof document === "string") return document;
|
|
50
|
+
if (document instanceof String) return document.toString();
|
|
51
|
+
if (document && typeof document === "object" && "kind" in document) {
|
|
52
|
+
return (0, import_graphql.print)(document);
|
|
53
|
+
}
|
|
54
|
+
if (document === null || document === void 0) {
|
|
55
|
+
throw import_data.createError.badRequest("Invalid GraphQL document: null or undefined");
|
|
56
|
+
}
|
|
57
|
+
return String(document);
|
|
58
|
+
}
|
|
59
|
+
function hasAuthMessage(message) {
|
|
60
|
+
const normalized = String(message ?? "").toLowerCase();
|
|
61
|
+
return normalized.includes("unauthenticated") || normalized.includes("unauthorized") || normalized.includes("authentication");
|
|
62
|
+
}
|
|
63
|
+
function parseGraphQLResponse(response, onAuthError) {
|
|
64
|
+
if (!response.errors?.length) return null;
|
|
65
|
+
const error = response.errors[0];
|
|
66
|
+
const code = error.extensions?.code;
|
|
67
|
+
const message = error.message || "GraphQL query failed";
|
|
68
|
+
if (code === "UNAUTHENTICATED" || hasAuthMessage(message)) {
|
|
69
|
+
onAuthError?.();
|
|
70
|
+
return import_data.createError.unauthorized("Authentication required. Please log in again.");
|
|
71
|
+
}
|
|
72
|
+
if (code === "FORBIDDEN") {
|
|
73
|
+
return import_data.createError.forbidden("You do not have permission to perform this action.");
|
|
74
|
+
}
|
|
75
|
+
return import_data.createError.graphql(message, code);
|
|
76
|
+
}
|
|
77
|
+
function createSheetsExecute(config, getToken) {
|
|
78
|
+
return async (document, variables) => {
|
|
79
|
+
const url = config.endpoint;
|
|
80
|
+
if (!url) {
|
|
81
|
+
throw import_data.createError.badRequest("No GraphQL endpoint configured.");
|
|
82
|
+
}
|
|
83
|
+
const token = getToken();
|
|
84
|
+
const headers = {
|
|
85
|
+
"Content-Type": "application/json",
|
|
86
|
+
Accept: "application/graphql-response+json"
|
|
87
|
+
};
|
|
88
|
+
if (token) {
|
|
89
|
+
headers["Authorization"] = `Bearer ${token}`;
|
|
90
|
+
}
|
|
91
|
+
let response;
|
|
92
|
+
try {
|
|
93
|
+
response = await fetch(url, {
|
|
94
|
+
method: "POST",
|
|
95
|
+
headers,
|
|
96
|
+
body: JSON.stringify({
|
|
97
|
+
query: documentToString(document),
|
|
98
|
+
...variables !== void 0 && { variables }
|
|
99
|
+
})
|
|
100
|
+
});
|
|
101
|
+
} catch (error) {
|
|
102
|
+
throw import_data.createError.network(error instanceof Error ? error : void 0);
|
|
103
|
+
}
|
|
104
|
+
if (!response.ok) {
|
|
105
|
+
const { status, statusText } = response;
|
|
106
|
+
if (status === 401) {
|
|
107
|
+
config.onAuthError?.();
|
|
108
|
+
throw import_data.createError.unauthorized("Authentication required. Please log in again.");
|
|
109
|
+
}
|
|
110
|
+
if (status === 403) {
|
|
111
|
+
throw import_data.createError.forbidden("You do not have permission to perform this action.");
|
|
112
|
+
}
|
|
113
|
+
if (status === 404) {
|
|
114
|
+
throw import_data.createError.notFound("The requested endpoint does not exist.");
|
|
115
|
+
}
|
|
116
|
+
try {
|
|
117
|
+
const body = await response.json();
|
|
118
|
+
if (body.errors?.length) {
|
|
119
|
+
throw import_data.createError.graphql(body.errors[0].message || `Request failed: ${status}`, body.errors[0].extensions?.code);
|
|
120
|
+
}
|
|
121
|
+
} catch (e) {
|
|
122
|
+
if (e instanceof import_data.DataError) throw e;
|
|
123
|
+
}
|
|
124
|
+
throw import_data.createError.badRequest(`Request failed: ${status} ${statusText}`);
|
|
125
|
+
}
|
|
126
|
+
const result = await response.json();
|
|
127
|
+
const graphqlError = parseGraphQLResponse(result, config.onAuthError);
|
|
128
|
+
if (graphqlError) {
|
|
129
|
+
throw graphqlError;
|
|
130
|
+
}
|
|
131
|
+
return result.data;
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
function createSheetsUpload(config, getToken) {
|
|
135
|
+
return async (file, path) => {
|
|
136
|
+
if (!config.endpoint) {
|
|
137
|
+
throw import_data.createError.badRequest("No GraphQL endpoint configured.");
|
|
138
|
+
}
|
|
139
|
+
const url = config.endpoint.replace(/\/graphql\/?$/, "/upload");
|
|
140
|
+
const token = getToken();
|
|
141
|
+
const formData = new FormData();
|
|
142
|
+
formData.append("file", file);
|
|
143
|
+
if (path) formData.append("path", path);
|
|
144
|
+
const headers = {};
|
|
145
|
+
if (token) {
|
|
146
|
+
headers["Authorization"] = `Bearer ${token}`;
|
|
147
|
+
}
|
|
148
|
+
let response;
|
|
149
|
+
try {
|
|
150
|
+
response = await fetch(url, {
|
|
151
|
+
method: "POST",
|
|
152
|
+
headers,
|
|
153
|
+
body: formData
|
|
154
|
+
});
|
|
155
|
+
} catch (error) {
|
|
156
|
+
throw import_data.createError.network(error instanceof Error ? error : void 0);
|
|
157
|
+
}
|
|
158
|
+
if (!response.ok) {
|
|
159
|
+
if (response.status === 401) {
|
|
160
|
+
config.onAuthError?.();
|
|
161
|
+
throw import_data.createError.unauthorized("Authentication required. Please log in again.");
|
|
162
|
+
}
|
|
163
|
+
if (response.status === 403) {
|
|
164
|
+
throw import_data.createError.forbidden("You do not have permission to perform this action.");
|
|
165
|
+
}
|
|
166
|
+
try {
|
|
167
|
+
const body = await response.json();
|
|
168
|
+
const graphqlError = parseGraphQLResponse(body, config.onAuthError);
|
|
169
|
+
if (graphqlError) {
|
|
170
|
+
throw graphqlError;
|
|
171
|
+
}
|
|
172
|
+
if (body.errors?.length) {
|
|
173
|
+
const firstError = body.errors[0];
|
|
174
|
+
throw import_data.createError.graphql(firstError.message || "Upload failed", firstError.extensions?.code);
|
|
175
|
+
}
|
|
176
|
+
} catch (error) {
|
|
177
|
+
if (error instanceof import_data.DataError) throw error;
|
|
178
|
+
}
|
|
179
|
+
if (response.status === 400) throw import_data.createError.badRequest("No file provided for upload.");
|
|
180
|
+
if (response.status === 413) throw import_data.createError.badRequest("File is too large. Maximum size is 10 MB.");
|
|
181
|
+
throw import_data.createError.badRequest(`Upload failed: ${response.status} ${response.statusText}`);
|
|
182
|
+
}
|
|
183
|
+
const result = await response.json();
|
|
184
|
+
if (result.errors?.length) {
|
|
185
|
+
const graphqlError = parseGraphQLResponse(result, config.onAuthError);
|
|
186
|
+
if (graphqlError) {
|
|
187
|
+
throw graphqlError;
|
|
188
|
+
}
|
|
189
|
+
const firstError = result.errors[0];
|
|
190
|
+
throw import_data.createError.graphql(firstError.message || "Upload failed", firstError.extensions?.code);
|
|
191
|
+
}
|
|
192
|
+
return result;
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// src/store/sheets-store.ts
|
|
197
|
+
var import_react2 = require("react");
|
|
198
|
+
var import_zustand = require("zustand");
|
|
199
|
+
|
|
200
|
+
// src/store/draft-rows-slice.ts
|
|
201
|
+
function parseDraftTableKey(tableKey) {
|
|
202
|
+
const parts = tableKey.split("::");
|
|
203
|
+
if (parts.length === 2) {
|
|
204
|
+
const [databaseId, tableName] = parts;
|
|
205
|
+
if (!databaseId || !tableName) return null;
|
|
206
|
+
return { databaseId, tableName };
|
|
207
|
+
}
|
|
208
|
+
return null;
|
|
209
|
+
}
|
|
210
|
+
function createDraftRowsSlice(set) {
|
|
211
|
+
return {
|
|
212
|
+
draftRowsByTable: {},
|
|
213
|
+
createDraftRow: (args) => {
|
|
214
|
+
const { tableKey, columnOrder, fieldMetaByKey, relationInfoByKey, metaVersion } = args;
|
|
215
|
+
const effectiveColumnOrder = ensureColumnOrder(columnOrder, fieldMetaByKey, relationInfoByKey);
|
|
216
|
+
const template = buildTemplate(effectiveColumnOrder, relationInfoByKey);
|
|
217
|
+
const draftRowId = `draft:${generateDraftSuffix()}`;
|
|
218
|
+
const values = initializeValuesFromTemplate(template, draftRowId);
|
|
219
|
+
set((state) => {
|
|
220
|
+
const existing = state.draftRowsByTable[tableKey];
|
|
221
|
+
const nextOrder = existing ? [...existing.order, draftRowId] : [draftRowId];
|
|
222
|
+
const nextMap = {
|
|
223
|
+
...existing?.map ?? {},
|
|
224
|
+
[draftRowId]: {
|
|
225
|
+
id: draftRowId,
|
|
226
|
+
values,
|
|
227
|
+
status: "idle",
|
|
228
|
+
errors: null,
|
|
229
|
+
createdAt: Date.now(),
|
|
230
|
+
metaVersion
|
|
231
|
+
}
|
|
232
|
+
};
|
|
233
|
+
return {
|
|
234
|
+
draftRowsByTable: {
|
|
235
|
+
...state.draftRowsByTable,
|
|
236
|
+
[tableKey]: {
|
|
237
|
+
order: nextOrder,
|
|
238
|
+
map: nextMap,
|
|
239
|
+
template,
|
|
240
|
+
metaVersion,
|
|
241
|
+
columnOrder: [...effectiveColumnOrder]
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
};
|
|
245
|
+
});
|
|
246
|
+
return draftRowId;
|
|
247
|
+
},
|
|
248
|
+
updateDraftCell: ({ tableKey, draftRowId, columnKey, value, extraValues }) => {
|
|
249
|
+
set((state) => {
|
|
250
|
+
const tableState = state.draftRowsByTable[tableKey];
|
|
251
|
+
if (!tableState) return state;
|
|
252
|
+
const existingRow = tableState.map[draftRowId];
|
|
253
|
+
if (!existingRow) return state;
|
|
254
|
+
let hasValueChanges = !deepEqual(existingRow.values[columnKey], value);
|
|
255
|
+
if (!hasValueChanges && extraValues) {
|
|
256
|
+
for (const [key, extraValue] of Object.entries(extraValues)) {
|
|
257
|
+
if (!deepEqual(existingRow.values[key], extraValue)) {
|
|
258
|
+
hasValueChanges = true;
|
|
259
|
+
break;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
const shouldResetErrors = existingRow.status === "error" || existingRow.errors !== null;
|
|
264
|
+
if (!hasValueChanges && !shouldResetErrors) return state;
|
|
265
|
+
const updatedValues = hasValueChanges ? { ...existingRow.values, [columnKey]: deepClone(value) } : existingRow.values;
|
|
266
|
+
if (hasValueChanges && extraValues) {
|
|
267
|
+
for (const [key, extraValue] of Object.entries(extraValues)) {
|
|
268
|
+
updatedValues[key] = deepClone(extraValue);
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
const nextMap = {
|
|
272
|
+
...tableState.map,
|
|
273
|
+
[draftRowId]: {
|
|
274
|
+
...existingRow,
|
|
275
|
+
values: updatedValues,
|
|
276
|
+
status: existingRow.status === "error" ? "idle" : existingRow.status,
|
|
277
|
+
errors: null
|
|
278
|
+
}
|
|
279
|
+
};
|
|
280
|
+
return {
|
|
281
|
+
draftRowsByTable: {
|
|
282
|
+
...state.draftRowsByTable,
|
|
283
|
+
[tableKey]: {
|
|
284
|
+
...tableState,
|
|
285
|
+
map: nextMap
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
};
|
|
289
|
+
});
|
|
290
|
+
},
|
|
291
|
+
removeDraftRow: (tableKey, draftRowId) => {
|
|
292
|
+
set((state) => {
|
|
293
|
+
const tableState = state.draftRowsByTable[tableKey];
|
|
294
|
+
if (!tableState) return state;
|
|
295
|
+
if (!tableState.map[draftRowId]) return state;
|
|
296
|
+
const nextOrder = tableState.order.filter((id) => id !== draftRowId);
|
|
297
|
+
const nextMap = { ...tableState.map };
|
|
298
|
+
delete nextMap[draftRowId];
|
|
299
|
+
const nextTableState = nextOrder.length ? { ...tableState, order: nextOrder, map: nextMap } : void 0;
|
|
300
|
+
const nextByTable = { ...state.draftRowsByTable };
|
|
301
|
+
if (nextTableState) {
|
|
302
|
+
nextByTable[tableKey] = nextTableState;
|
|
303
|
+
} else {
|
|
304
|
+
delete nextByTable[tableKey];
|
|
305
|
+
}
|
|
306
|
+
return { draftRowsByTable: nextByTable };
|
|
307
|
+
});
|
|
308
|
+
},
|
|
309
|
+
clearDraftRowsForTable: (tableKey) => {
|
|
310
|
+
set((state) => {
|
|
311
|
+
if (!state.draftRowsByTable[tableKey]) return state;
|
|
312
|
+
const nextByTable = { ...state.draftRowsByTable };
|
|
313
|
+
delete nextByTable[tableKey];
|
|
314
|
+
return { draftRowsByTable: nextByTable };
|
|
315
|
+
});
|
|
316
|
+
},
|
|
317
|
+
clearDraftRowsForDatabase: (databaseId) => {
|
|
318
|
+
set((state) => {
|
|
319
|
+
if (!databaseId || !Object.keys(state.draftRowsByTable).length) return state;
|
|
320
|
+
let changed = false;
|
|
321
|
+
const nextByTable = { ...state.draftRowsByTable };
|
|
322
|
+
for (const tableKey of Object.keys(nextByTable)) {
|
|
323
|
+
const parsed = parseDraftTableKey(tableKey);
|
|
324
|
+
const matchesDatabase = parsed ? parsed.databaseId === databaseId : tableKey.includes(`${databaseId}::`);
|
|
325
|
+
if (matchesDatabase) {
|
|
326
|
+
delete nextByTable[tableKey];
|
|
327
|
+
changed = true;
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
return changed ? { draftRowsByTable: nextByTable } : state;
|
|
331
|
+
});
|
|
332
|
+
},
|
|
333
|
+
clearAllDraftRows: () => {
|
|
334
|
+
set((state) => {
|
|
335
|
+
if (!Object.keys(state.draftRowsByTable).length) return state;
|
|
336
|
+
return { draftRowsByTable: {} };
|
|
337
|
+
});
|
|
338
|
+
},
|
|
339
|
+
syncDraftRowsWithMeta: (args) => {
|
|
340
|
+
const { tableKey, columnOrder, fieldMetaByKey, relationInfoByKey, metaVersion } = args;
|
|
341
|
+
set((state) => {
|
|
342
|
+
const tableState = state.draftRowsByTable[tableKey];
|
|
343
|
+
const effectiveColumnOrder = ensureColumnOrder(columnOrder, fieldMetaByKey, relationInfoByKey);
|
|
344
|
+
const template = buildTemplate(effectiveColumnOrder, relationInfoByKey);
|
|
345
|
+
if (!tableState) {
|
|
346
|
+
return state;
|
|
347
|
+
}
|
|
348
|
+
if (tableState.order.length === 0) {
|
|
349
|
+
const nextByTable = { ...state.draftRowsByTable };
|
|
350
|
+
delete nextByTable[tableKey];
|
|
351
|
+
return { draftRowsByTable: nextByTable };
|
|
352
|
+
}
|
|
353
|
+
const isSameMeta = tableState.metaVersion === metaVersion && shallowEqualArrays(tableState.columnOrder, effectiveColumnOrder);
|
|
354
|
+
if (isSameMeta) return state;
|
|
355
|
+
const nextMap = {};
|
|
356
|
+
for (const draftId of tableState.order) {
|
|
357
|
+
const row = tableState.map[draftId];
|
|
358
|
+
if (!row) continue;
|
|
359
|
+
const mergedValues = initializeValuesFromTemplate(template, draftId);
|
|
360
|
+
for (const key of Object.keys(row.values)) {
|
|
361
|
+
if (Object.prototype.hasOwnProperty.call(template, key)) {
|
|
362
|
+
mergedValues[key] = deepClone(row.values[key]);
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
nextMap[draftId] = {
|
|
366
|
+
...row,
|
|
367
|
+
values: mergedValues,
|
|
368
|
+
metaVersion,
|
|
369
|
+
status: row.status === "error" ? "idle" : row.status,
|
|
370
|
+
errors: row.status === "error" ? null : row.errors
|
|
371
|
+
};
|
|
372
|
+
}
|
|
373
|
+
return {
|
|
374
|
+
draftRowsByTable: {
|
|
375
|
+
...state.draftRowsByTable,
|
|
376
|
+
[tableKey]: {
|
|
377
|
+
order: [...tableState.order],
|
|
378
|
+
map: nextMap,
|
|
379
|
+
template,
|
|
380
|
+
metaVersion,
|
|
381
|
+
columnOrder: [...effectiveColumnOrder]
|
|
382
|
+
}
|
|
383
|
+
}
|
|
384
|
+
};
|
|
385
|
+
});
|
|
386
|
+
},
|
|
387
|
+
setDraftRowStatus: ({ tableKey, draftRowId, status, errors }) => {
|
|
388
|
+
set((state) => {
|
|
389
|
+
const tableState = state.draftRowsByTable[tableKey];
|
|
390
|
+
if (!tableState) return state;
|
|
391
|
+
const row = tableState.map[draftRowId];
|
|
392
|
+
if (!row) return state;
|
|
393
|
+
const nextErrors = errors ?? null;
|
|
394
|
+
if (row.status === status && shallowEqualRecords(row.errors, nextErrors)) return state;
|
|
395
|
+
const nextMap = {
|
|
396
|
+
...tableState.map,
|
|
397
|
+
[draftRowId]: { ...row, status, errors: nextErrors }
|
|
398
|
+
};
|
|
399
|
+
return {
|
|
400
|
+
draftRowsByTable: {
|
|
401
|
+
...state.draftRowsByTable,
|
|
402
|
+
[tableKey]: { ...tableState, map: nextMap }
|
|
403
|
+
}
|
|
404
|
+
};
|
|
405
|
+
});
|
|
406
|
+
}
|
|
407
|
+
};
|
|
408
|
+
}
|
|
409
|
+
function ensureColumnOrder(columnOrder, fieldMetaByKey, relationInfoByKey) {
|
|
410
|
+
if (columnOrder.length > 0) return [...columnOrder];
|
|
411
|
+
const keys = /* @__PURE__ */ new Set();
|
|
412
|
+
Object.keys(fieldMetaByKey).forEach((key) => {
|
|
413
|
+
if (key) keys.add(key);
|
|
414
|
+
});
|
|
415
|
+
if (relationInfoByKey) {
|
|
416
|
+
Object.keys(relationInfoByKey).forEach((key) => {
|
|
417
|
+
if (key) keys.add(key);
|
|
418
|
+
});
|
|
419
|
+
}
|
|
420
|
+
return Array.from(keys).sort((a, b) => a.localeCompare(b));
|
|
421
|
+
}
|
|
422
|
+
function buildTemplate(columnOrder, relationInfoByKey) {
|
|
423
|
+
const template = {};
|
|
424
|
+
for (const column of columnOrder) {
|
|
425
|
+
if (!column) continue;
|
|
426
|
+
const relationInfo = relationInfoByKey?.[column];
|
|
427
|
+
if (relationInfo && (relationInfo.kind === "hasMany" || relationInfo.kind === "manyToMany")) {
|
|
428
|
+
template[column] = [];
|
|
429
|
+
} else {
|
|
430
|
+
template[column] = null;
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
return template;
|
|
434
|
+
}
|
|
435
|
+
function generateDraftSuffix() {
|
|
436
|
+
const cryptoObj = typeof globalThis !== "undefined" ? globalThis.crypto : void 0;
|
|
437
|
+
if (cryptoObj && typeof cryptoObj.getRandomValues === "function") {
|
|
438
|
+
const buffer = new Uint32Array(1);
|
|
439
|
+
cryptoObj.getRandomValues(buffer);
|
|
440
|
+
return buffer[0].toString(36).slice(0, 8);
|
|
441
|
+
}
|
|
442
|
+
return Math.random().toString(36).slice(2, 10);
|
|
443
|
+
}
|
|
444
|
+
function initializeValuesFromTemplate(template, draftRowId) {
|
|
445
|
+
const result = {};
|
|
446
|
+
for (const [key, value] of Object.entries(template)) {
|
|
447
|
+
result[key] = deepClone(value);
|
|
448
|
+
}
|
|
449
|
+
if (!result.id) result.id = draftRowId;
|
|
450
|
+
return result;
|
|
451
|
+
}
|
|
452
|
+
function deepClone(value) {
|
|
453
|
+
if (Array.isArray(value)) return value.map((item) => deepClone(item));
|
|
454
|
+
if (value instanceof Date) return new Date(value.getTime());
|
|
455
|
+
if (value && typeof value === "object") {
|
|
456
|
+
const result = {};
|
|
457
|
+
for (const [key, val] of Object.entries(value)) {
|
|
458
|
+
result[key] = deepClone(val);
|
|
459
|
+
}
|
|
460
|
+
return result;
|
|
461
|
+
}
|
|
462
|
+
return value;
|
|
463
|
+
}
|
|
464
|
+
function deepEqual(a, b) {
|
|
465
|
+
if (Object.is(a, b)) return true;
|
|
466
|
+
if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
|
|
467
|
+
if (Array.isArray(a) && Array.isArray(b)) {
|
|
468
|
+
if (a.length !== b.length) return false;
|
|
469
|
+
for (let i = 0; i < a.length; i += 1) {
|
|
470
|
+
if (!deepEqual(a[i], b[i])) return false;
|
|
471
|
+
}
|
|
472
|
+
return true;
|
|
473
|
+
}
|
|
474
|
+
if (a && b && typeof a === "object" && typeof b === "object") {
|
|
475
|
+
const keysA = Object.keys(a);
|
|
476
|
+
const keysB = Object.keys(b);
|
|
477
|
+
if (keysA.length !== keysB.length) return false;
|
|
478
|
+
for (const key of keysA) {
|
|
479
|
+
if (!(key in b)) return false;
|
|
480
|
+
if (!deepEqual(a[key], b[key])) return false;
|
|
481
|
+
}
|
|
482
|
+
return true;
|
|
483
|
+
}
|
|
484
|
+
return false;
|
|
485
|
+
}
|
|
486
|
+
function shallowEqualRecords(a, b) {
|
|
487
|
+
if (a === b) return true;
|
|
488
|
+
if (!a || !b) return false;
|
|
489
|
+
const keysA = Object.keys(a);
|
|
490
|
+
const keysB = Object.keys(b);
|
|
491
|
+
if (keysA.length !== keysB.length) return false;
|
|
492
|
+
for (const key of keysA) {
|
|
493
|
+
if (a[key] !== b[key]) return false;
|
|
494
|
+
}
|
|
495
|
+
return true;
|
|
496
|
+
}
|
|
497
|
+
function shallowEqualArrays(a, b) {
|
|
498
|
+
if (a.length !== b.length) return false;
|
|
499
|
+
for (let i = 0; i < a.length; i += 1) {
|
|
500
|
+
if (a[i] !== b[i]) return false;
|
|
501
|
+
}
|
|
502
|
+
return true;
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
// src/store/relation-info-slice.ts
|
|
506
|
+
var import_inflekt2 = require("inflekt");
|
|
507
|
+
var import_data4 = require("@constructive-io/data");
|
|
508
|
+
|
|
509
|
+
// src/utils/relation-utils.ts
|
|
510
|
+
var import_inflekt = require("inflekt");
|
|
511
|
+
var import_data3 = require("@constructive-io/data");
|
|
512
|
+
function isJunctionTablePure(junctionTableName, leftFkField, rightFkField, metaTables) {
|
|
513
|
+
if (!leftFkField || !rightFkField) return true;
|
|
514
|
+
const junctionMeta = metaTables.find((t) => t?.name === junctionTableName);
|
|
515
|
+
if (!junctionMeta?.fields) return true;
|
|
516
|
+
const exemptFields = /* @__PURE__ */ new Set(["id", leftFkField, rightFkField]);
|
|
517
|
+
for (const field of junctionMeta.fields) {
|
|
518
|
+
if (!field?.name) continue;
|
|
519
|
+
const camelName = (0, import_data3.pgFieldToCamelCase)(field.name);
|
|
520
|
+
if (exemptFields.has(camelName)) continue;
|
|
521
|
+
if (field.isNotNull && !field.hasDefault) return false;
|
|
522
|
+
}
|
|
523
|
+
return true;
|
|
524
|
+
}
|
|
525
|
+
function getJunctionTableNames(relations, metaTables) {
|
|
526
|
+
const names = /* @__PURE__ */ new Set();
|
|
527
|
+
for (const rel of relations.manyToMany) {
|
|
528
|
+
if (!rel.junctionTable) continue;
|
|
529
|
+
if (metaTables) {
|
|
530
|
+
const leftFk = rel.junctionLeftKeyFields?.[0];
|
|
531
|
+
const rightFk = rel.junctionRightKeyFields?.[0];
|
|
532
|
+
if (!isJunctionTablePure(rel.junctionTable, leftFk, rightFk, metaTables)) continue;
|
|
533
|
+
}
|
|
534
|
+
names.add(rel.junctionTable);
|
|
535
|
+
}
|
|
536
|
+
return names;
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
// src/store/relation-info-slice.ts
|
|
540
|
+
function toRelationInfoMap(info) {
|
|
541
|
+
return new Map(Object.entries(info));
|
|
542
|
+
}
|
|
543
|
+
function setTableRelationInfo(set, tableName, info) {
|
|
544
|
+
set((state) => ({
|
|
545
|
+
relationInfoCache: { ...state.relationInfoCache, [tableName]: info },
|
|
546
|
+
relationInfoMapCache: { ...state.relationInfoMapCache, [tableName]: toRelationInfoMap(info) }
|
|
547
|
+
}));
|
|
548
|
+
}
|
|
549
|
+
function createRelationInfoSlice(set, get) {
|
|
550
|
+
return {
|
|
551
|
+
relationInfoCache: {},
|
|
552
|
+
relationInfoMapCache: {},
|
|
553
|
+
setRelationInfoForTable: (tableName, info) => setTableRelationInfo(set, tableName, info),
|
|
554
|
+
getRelationInfoForTable: (tableName) => get().relationInfoCache[tableName],
|
|
555
|
+
getRelationInfoMapForTable: (tableName) => get().relationInfoMapCache[tableName],
|
|
556
|
+
clearRelationInfoCache: () => set({ relationInfoCache: {}, relationInfoMapCache: {} }),
|
|
557
|
+
rebuildRelationInfo: (tableName, meta) => {
|
|
558
|
+
try {
|
|
559
|
+
const info = buildRelationInfoFromMeta(tableName, meta);
|
|
560
|
+
if (!info) return;
|
|
561
|
+
setTableRelationInfo(set, tableName, info);
|
|
562
|
+
} catch {
|
|
563
|
+
}
|
|
564
|
+
},
|
|
565
|
+
ensureRelationInfo: (tableName, meta) => {
|
|
566
|
+
const existing = get().relationInfoCache[tableName];
|
|
567
|
+
if (existing) return existing;
|
|
568
|
+
const info = buildRelationInfoFromMeta(tableName, meta) || {};
|
|
569
|
+
if (Object.keys(info).length) {
|
|
570
|
+
setTableRelationInfo(set, tableName, info);
|
|
571
|
+
}
|
|
572
|
+
return info;
|
|
573
|
+
}
|
|
574
|
+
};
|
|
575
|
+
}
|
|
576
|
+
function toCleanTables(meta) {
|
|
577
|
+
const tables = meta?._meta?.tables ?? [];
|
|
578
|
+
return tables.filter((table) => table != null).map((table) => (0, import_data4.cleanTable)(table));
|
|
579
|
+
}
|
|
580
|
+
function firstFieldName(fields) {
|
|
581
|
+
return fields[0]?.name;
|
|
582
|
+
}
|
|
583
|
+
function findForeignKeyInRelatedTable(currentTableName, relatedTableName, allTables, rawMetaTables) {
|
|
584
|
+
const relatedTable = allTables.find((t) => t.name === relatedTableName);
|
|
585
|
+
if (relatedTable) {
|
|
586
|
+
const belongsTo = relatedTable.relations.belongsTo.find(
|
|
587
|
+
(rel) => rel.referencesTable === currentTableName
|
|
588
|
+
);
|
|
589
|
+
if (belongsTo?.keys?.[0]?.name) return belongsTo.keys[0].name;
|
|
590
|
+
}
|
|
591
|
+
const rawRelated = rawMetaTables.find((t) => t.name === relatedTableName);
|
|
592
|
+
if (rawRelated) {
|
|
593
|
+
const v5Fks = Array.isArray(rawRelated.constraints) ? [] : rawRelated.constraints?.foreignKey;
|
|
594
|
+
const fks = v5Fks ?? rawRelated.foreignKeyConstraints ?? [];
|
|
595
|
+
for (const fk of fks) {
|
|
596
|
+
if (!fk) continue;
|
|
597
|
+
const refName = fk.refTable?.name;
|
|
598
|
+
if (refName && refName.toLowerCase() === currentTableName.toLowerCase()) {
|
|
599
|
+
const fieldName = fk.fields?.[0]?.name;
|
|
600
|
+
if (fieldName) return (0, import_data4.pgFieldToCamelCase)(fieldName);
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
return void 0;
|
|
605
|
+
}
|
|
606
|
+
function buildRelationInfoFromMeta(tableName, meta) {
|
|
607
|
+
const tables = toCleanTables(meta);
|
|
608
|
+
const table = tables.find((candidate) => candidate.name === tableName);
|
|
609
|
+
if (!table) return null;
|
|
610
|
+
const rawMetaTables = (meta?._meta?.tables ?? []).filter(
|
|
611
|
+
(t) => t != null
|
|
612
|
+
);
|
|
613
|
+
const PRIORITY_FIELDS = [
|
|
614
|
+
"displayName",
|
|
615
|
+
"fullName",
|
|
616
|
+
"preferredName",
|
|
617
|
+
"nickname",
|
|
618
|
+
"firstName",
|
|
619
|
+
"lastName",
|
|
620
|
+
"givenName",
|
|
621
|
+
"familyName",
|
|
622
|
+
"username",
|
|
623
|
+
"handle",
|
|
624
|
+
"email",
|
|
625
|
+
"phone",
|
|
626
|
+
"title",
|
|
627
|
+
"label",
|
|
628
|
+
"slug",
|
|
629
|
+
"code",
|
|
630
|
+
"name"
|
|
631
|
+
];
|
|
632
|
+
const NAME_PATTERN = /name/i;
|
|
633
|
+
const computeCandidates = (relatedTableName) => {
|
|
634
|
+
if (!relatedTableName) return [];
|
|
635
|
+
const related = tables.find((candidate) => candidate.name === relatedTableName);
|
|
636
|
+
if (!related) return [];
|
|
637
|
+
const fieldNamesSet = new Set(related.fields.map((field) => field.name));
|
|
638
|
+
const explicit = PRIORITY_FIELDS.filter((k) => fieldNamesSet.has(k));
|
|
639
|
+
const explicitSet = new Set(explicit);
|
|
640
|
+
const nameLike = [];
|
|
641
|
+
for (const name of fieldNamesSet) {
|
|
642
|
+
if (NAME_PATTERN.test(name) && !explicitSet.has(name)) {
|
|
643
|
+
nameLike.push(name);
|
|
644
|
+
}
|
|
645
|
+
}
|
|
646
|
+
nameLike.sort((a, b) => a.length - b.length);
|
|
647
|
+
return Array.from(/* @__PURE__ */ new Set([...explicit, ...nameLike]));
|
|
648
|
+
};
|
|
649
|
+
const info = {};
|
|
650
|
+
table.relations.belongsTo.forEach((relation) => {
|
|
651
|
+
const displayCandidates = computeCandidates(relation.referencesTable);
|
|
652
|
+
const foreignKeys = relation.keys.map((key) => key.name).filter(Boolean);
|
|
653
|
+
const primaryForeignKey = foreignKeys[0];
|
|
654
|
+
if (relation.fieldName) {
|
|
655
|
+
info[relation.fieldName] = {
|
|
656
|
+
kind: "belongsTo",
|
|
657
|
+
relatedTable: relation.referencesTable,
|
|
658
|
+
displayCandidates,
|
|
659
|
+
relationField: relation.fieldName,
|
|
660
|
+
foreignKeyField: primaryForeignKey
|
|
661
|
+
};
|
|
662
|
+
}
|
|
663
|
+
foreignKeys.forEach((fk) => {
|
|
664
|
+
if (!fk) return;
|
|
665
|
+
info[fk] = {
|
|
666
|
+
kind: "belongsTo",
|
|
667
|
+
relatedTable: relation.referencesTable,
|
|
668
|
+
displayCandidates,
|
|
669
|
+
relationField: relation.fieldName ?? void 0,
|
|
670
|
+
foreignKeyField: fk
|
|
671
|
+
};
|
|
672
|
+
});
|
|
673
|
+
});
|
|
674
|
+
table.relations.hasOne.forEach((relation) => {
|
|
675
|
+
if (relation.fieldName) {
|
|
676
|
+
const fkInRelated = findForeignKeyInRelatedTable(tableName, relation.referencedByTable, tables, rawMetaTables);
|
|
677
|
+
info[relation.fieldName] = {
|
|
678
|
+
kind: "hasOne",
|
|
679
|
+
relatedTable: relation.referencedByTable,
|
|
680
|
+
displayCandidates: computeCandidates(relation.referencedByTable),
|
|
681
|
+
relationField: relation.fieldName,
|
|
682
|
+
foreignKeyField: fkInRelated
|
|
683
|
+
};
|
|
684
|
+
}
|
|
685
|
+
});
|
|
686
|
+
const junctionTableNames = getJunctionTableNames(table.relations, rawMetaTables);
|
|
687
|
+
table.relations.hasMany.forEach((relation) => {
|
|
688
|
+
if (!relation.fieldName) return;
|
|
689
|
+
if (junctionTableNames.has(relation.referencedByTable)) return;
|
|
690
|
+
const fkInRelated = findForeignKeyInRelatedTable(tableName, relation.referencedByTable, tables, rawMetaTables);
|
|
691
|
+
info[relation.fieldName] = {
|
|
692
|
+
kind: "hasMany",
|
|
693
|
+
relatedTable: relation.referencedByTable,
|
|
694
|
+
displayCandidates: computeCandidates(relation.referencedByTable),
|
|
695
|
+
relationField: relation.fieldName,
|
|
696
|
+
foreignKeyField: fkInRelated
|
|
697
|
+
};
|
|
698
|
+
});
|
|
699
|
+
table.relations.manyToMany.forEach((relation) => {
|
|
700
|
+
if (relation.fieldName) {
|
|
701
|
+
let junctionLeftKeyField = relation.junctionLeftKeyFields?.[0];
|
|
702
|
+
let junctionRightKeyField = relation.junctionRightKeyFields?.[0];
|
|
703
|
+
if (!junctionLeftKeyField || !junctionRightKeyField) {
|
|
704
|
+
const junctionTableName = relation.junctionTable;
|
|
705
|
+
const junctionTable = junctionTableName ? tables.find((candidate) => candidate.name === junctionTableName) : void 0;
|
|
706
|
+
const junctionBelongsTo = junctionTable?.relations.belongsTo ?? [];
|
|
707
|
+
if (!junctionLeftKeyField) {
|
|
708
|
+
const leftRelation = junctionBelongsTo.find((entry) => entry.referencesTable === tableName);
|
|
709
|
+
junctionLeftKeyField = firstFieldName(leftRelation?.keys ?? []);
|
|
710
|
+
}
|
|
711
|
+
if (!junctionRightKeyField) {
|
|
712
|
+
const rightRelation = junctionBelongsTo.find((entry) => entry.referencesTable === relation.rightTable);
|
|
713
|
+
junctionRightKeyField = firstFieldName(rightRelation?.keys ?? []);
|
|
714
|
+
}
|
|
715
|
+
}
|
|
716
|
+
if (!isJunctionTablePure(relation.junctionTable, junctionLeftKeyField, junctionRightKeyField, rawMetaTables)) {
|
|
717
|
+
return;
|
|
718
|
+
}
|
|
719
|
+
info[relation.fieldName] = {
|
|
720
|
+
kind: "manyToMany",
|
|
721
|
+
relatedTable: relation.rightTable,
|
|
722
|
+
displayCandidates: computeCandidates(relation.rightTable),
|
|
723
|
+
relationField: relation.fieldName,
|
|
724
|
+
junctionTable: relation.junctionTable,
|
|
725
|
+
junctionLeftKeyField,
|
|
726
|
+
junctionRightKeyField,
|
|
727
|
+
displayName: (0, import_inflekt2.pluralize)(relation.rightTable)
|
|
728
|
+
};
|
|
729
|
+
}
|
|
730
|
+
});
|
|
731
|
+
return info;
|
|
732
|
+
}
|
|
733
|
+
|
|
734
|
+
// src/store/sheets-store.ts
|
|
735
|
+
function createSheetsStore() {
|
|
736
|
+
return (0, import_zustand.createStore)((set, get) => ({
|
|
737
|
+
// Draft rows
|
|
738
|
+
...createDraftRowsSlice(set),
|
|
739
|
+
// Relation info cache
|
|
740
|
+
...createRelationInfoSlice(set, get),
|
|
741
|
+
// Auth state (standalone mode)
|
|
742
|
+
isAuthenticated: false,
|
|
743
|
+
accessToken: null,
|
|
744
|
+
expiresAt: null,
|
|
745
|
+
setAuthenticated: (token, expiresAt) => set({ isAuthenticated: true, accessToken: token, expiresAt }),
|
|
746
|
+
setUnauthenticated: () => set({ isAuthenticated: false, accessToken: null, expiresAt: null })
|
|
747
|
+
}));
|
|
748
|
+
}
|
|
749
|
+
var SheetsStoreContext = (0, import_react2.createContext)(null);
|
|
750
|
+
|
|
751
|
+
// src/auth/utils/token-store.ts
|
|
752
|
+
var KEY_PREFIX = "sheets-auth-token";
|
|
753
|
+
function storageKey(databaseId) {
|
|
754
|
+
return `${KEY_PREFIX}:${databaseId}`;
|
|
755
|
+
}
|
|
756
|
+
function getStorage() {
|
|
757
|
+
if (typeof window === "undefined") return null;
|
|
758
|
+
try {
|
|
759
|
+
return window.localStorage;
|
|
760
|
+
} catch {
|
|
761
|
+
return null;
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
function getStoredToken(databaseId) {
|
|
765
|
+
const storage = getStorage();
|
|
766
|
+
if (!storage) return null;
|
|
767
|
+
try {
|
|
768
|
+
const raw = storage.getItem(storageKey(databaseId));
|
|
769
|
+
if (!raw) return null;
|
|
770
|
+
const parsed = JSON.parse(raw);
|
|
771
|
+
if (!parsed.accessToken || !parsed.expiresAt) return null;
|
|
772
|
+
return parsed;
|
|
773
|
+
} catch {
|
|
774
|
+
return null;
|
|
775
|
+
}
|
|
776
|
+
}
|
|
777
|
+
|
|
778
|
+
// src/utils/sheets-logger.ts
|
|
779
|
+
var defaultLogger = {
|
|
780
|
+
warn: (...a) => console.warn(...a),
|
|
781
|
+
error: (...a) => console.error(...a)
|
|
782
|
+
// debug omitted = no-op
|
|
783
|
+
};
|
|
784
|
+
var active = defaultLogger;
|
|
785
|
+
function setSheetsLogger(l) {
|
|
786
|
+
active = l ? { ...defaultLogger, ...l } : defaultLogger;
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
// src/utils/sheets-i18n.ts
|
|
790
|
+
var DEFAULT_LOCALE = "en-US";
|
|
791
|
+
var active2 = DEFAULT_LOCALE;
|
|
792
|
+
function setSheetsLocale(locale) {
|
|
793
|
+
active2 = locale || DEFAULT_LOCALE;
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
// src/context/sheets-provider.tsx
|
|
797
|
+
var import_jsx_runtime = require("react/jsx-runtime");
|
|
798
|
+
function SheetsProvider({ config, children }) {
|
|
799
|
+
const storeRef = (0, import_react3.useRef)(null);
|
|
800
|
+
if (!storeRef.current) {
|
|
801
|
+
storeRef.current = createSheetsStore();
|
|
802
|
+
}
|
|
803
|
+
setSheetsLogger(config.logger);
|
|
804
|
+
setSheetsLocale(config.locale);
|
|
805
|
+
(0, import_react3.useEffect)(() => {
|
|
806
|
+
setSheetsLogger(config.logger);
|
|
807
|
+
setSheetsLocale(config.locale);
|
|
808
|
+
}, [config.logger, config.locale]);
|
|
809
|
+
(0, import_react3.useEffect)(() => {
|
|
810
|
+
const store = storeRef.current?.getState();
|
|
811
|
+
if (!store) return;
|
|
812
|
+
if (config.auth.mode !== "standalone") {
|
|
813
|
+
store.setUnauthenticated();
|
|
814
|
+
return;
|
|
815
|
+
}
|
|
816
|
+
const databaseId = config.databaseId || "default";
|
|
817
|
+
const stored = getStoredToken(databaseId);
|
|
818
|
+
if (!stored) {
|
|
819
|
+
store.setUnauthenticated();
|
|
820
|
+
return;
|
|
821
|
+
}
|
|
822
|
+
const expiresAt = new Date(stored.expiresAt);
|
|
823
|
+
if (expiresAt > /* @__PURE__ */ new Date()) {
|
|
824
|
+
store.setAuthenticated(stored.accessToken, stored.expiresAt);
|
|
825
|
+
return;
|
|
826
|
+
}
|
|
827
|
+
store.setUnauthenticated();
|
|
828
|
+
}, [config.auth.mode, config.databaseId]);
|
|
829
|
+
const internalQueryClient = (0, import_react3.useMemo)(
|
|
830
|
+
() => new import_react_query.QueryClient({
|
|
831
|
+
defaultOptions: {
|
|
832
|
+
queries: {
|
|
833
|
+
staleTime: 5 * 60 * 1e3,
|
|
834
|
+
gcTime: 30 * 60 * 1e3,
|
|
835
|
+
retry: 1
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
}),
|
|
839
|
+
[]
|
|
840
|
+
);
|
|
841
|
+
const queryClient = config.queryClient ?? internalQueryClient;
|
|
842
|
+
const getToken = (0, import_react3.useMemo)(() => {
|
|
843
|
+
if (config.auth.mode === "embedded") {
|
|
844
|
+
return config.auth.getToken;
|
|
845
|
+
}
|
|
846
|
+
return () => storeRef.current?.getState().accessToken ?? null;
|
|
847
|
+
}, [config.auth]);
|
|
848
|
+
const execute = (0, import_react3.useMemo)(() => {
|
|
849
|
+
if (config.execute) return config.execute;
|
|
850
|
+
return createSheetsExecute(config, getToken);
|
|
851
|
+
}, [config, getToken]);
|
|
852
|
+
const executeUpload = (0, import_react3.useMemo)(() => {
|
|
853
|
+
if (config.executeUpload) return config.executeUpload;
|
|
854
|
+
return createSheetsUpload(config, getToken);
|
|
855
|
+
}, [config, getToken]);
|
|
856
|
+
const scopeKey = (0, import_react3.useMemo)(
|
|
857
|
+
() => ({
|
|
858
|
+
databaseId: config.databaseId ?? null,
|
|
859
|
+
endpoint: config.endpoint
|
|
860
|
+
}),
|
|
861
|
+
[config.databaseId, config.endpoint]
|
|
862
|
+
);
|
|
863
|
+
const contextValue = (0, import_react3.useMemo)(
|
|
864
|
+
() => ({ config, execute, executeUpload, scopeKey }),
|
|
865
|
+
[config, execute, executeUpload, scopeKey]
|
|
866
|
+
);
|
|
867
|
+
return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_query.QueryClientProvider, { client: queryClient, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SheetsStoreContext.Provider, { value: storeRef.current, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SheetsContext.Provider, { value: contextValue, children }) }) });
|
|
868
|
+
}
|
|
869
|
+
|
|
870
|
+
// src/testing/mock-sheets-provider.tsx
|
|
871
|
+
var import_jsx_runtime2 = require("react/jsx-runtime");
|
|
872
|
+
function documentToString2(document) {
|
|
873
|
+
if (typeof document === "string") return document;
|
|
874
|
+
if (document instanceof String) return document.toString();
|
|
875
|
+
if (document && typeof document === "object" && "kind" in document) {
|
|
876
|
+
return (0, import_graphql2.print)(document);
|
|
877
|
+
}
|
|
878
|
+
return String(document ?? "");
|
|
879
|
+
}
|
|
880
|
+
function buildMetaField(field) {
|
|
881
|
+
return {
|
|
882
|
+
name: field.name,
|
|
883
|
+
isNotNull: false,
|
|
884
|
+
hasDefault: false,
|
|
885
|
+
type: {
|
|
886
|
+
gqlType: field.gqlType,
|
|
887
|
+
isArray: field.isArray ?? false,
|
|
888
|
+
pgType: field.pgType ?? "text",
|
|
889
|
+
isNotNull: false,
|
|
890
|
+
hasDefault: false,
|
|
891
|
+
subtype: field.subtype ?? null
|
|
892
|
+
}
|
|
893
|
+
};
|
|
894
|
+
}
|
|
895
|
+
function buildMetaTable(table) {
|
|
896
|
+
return {
|
|
897
|
+
name: table.name,
|
|
898
|
+
schemaName: "public",
|
|
899
|
+
query: {
|
|
900
|
+
all: (0, import_data5.toCamelCasePlural)(table.name),
|
|
901
|
+
create: (0, import_data5.toCreateMutationName)(table.name),
|
|
902
|
+
delete: (0, import_data5.toDeleteMutationName)(table.name),
|
|
903
|
+
one: (0, import_data5.toCamelCaseSingular)(table.name),
|
|
904
|
+
update: (0, import_data5.toUpdateMutationName)(table.name)
|
|
905
|
+
},
|
|
906
|
+
fields: table.fields.map(buildMetaField),
|
|
907
|
+
inflection: {
|
|
908
|
+
allRows: (0, import_data5.toCamelCasePlural)(table.name),
|
|
909
|
+
connection: (0, import_data5.toCamelCasePlural)(table.name),
|
|
910
|
+
tableType: table.name
|
|
911
|
+
},
|
|
912
|
+
indexes: [],
|
|
913
|
+
constraints: { primaryKey: null, unique: [], foreignKey: [] },
|
|
914
|
+
foreignKeyConstraints: [],
|
|
915
|
+
primaryKeyConstraints: [],
|
|
916
|
+
uniqueConstraints: [],
|
|
917
|
+
relations: { belongsTo: [], has: [], hasOne: [], hasMany: [], manyToMany: [] }
|
|
918
|
+
};
|
|
919
|
+
}
|
|
920
|
+
function buildMetaResponse(tables) {
|
|
921
|
+
return {
|
|
922
|
+
_meta: {
|
|
923
|
+
tables: tables.map(buildMetaTable)
|
|
924
|
+
}
|
|
925
|
+
};
|
|
926
|
+
}
|
|
927
|
+
function buildListResponse(table) {
|
|
928
|
+
const field = (0, import_data5.toCamelCasePlural)(table.name);
|
|
929
|
+
return {
|
|
930
|
+
[field]: {
|
|
931
|
+
nodes: table.rows,
|
|
932
|
+
totalCount: table.rows.length,
|
|
933
|
+
pageInfo: {
|
|
934
|
+
hasNextPage: false,
|
|
935
|
+
hasPreviousPage: false,
|
|
936
|
+
endCursor: null,
|
|
937
|
+
startCursor: null
|
|
938
|
+
}
|
|
939
|
+
}
|
|
940
|
+
};
|
|
941
|
+
}
|
|
942
|
+
var mockIdCounter = 0;
|
|
943
|
+
function synthesizeId() {
|
|
944
|
+
mockIdCounter += 1;
|
|
945
|
+
return `mock-${mockIdCounter}`;
|
|
946
|
+
}
|
|
947
|
+
function extractMutationInput(variables) {
|
|
948
|
+
const input = variables?.input;
|
|
949
|
+
return input && typeof input === "object" ? input : {};
|
|
950
|
+
}
|
|
951
|
+
function synthesizeCreatedRow(table, singular, variables) {
|
|
952
|
+
const input = extractMutationInput(variables);
|
|
953
|
+
const data = input[singular] ?? {};
|
|
954
|
+
const row = { id: synthesizeId(), ...data };
|
|
955
|
+
table.rows.push(row);
|
|
956
|
+
return row;
|
|
957
|
+
}
|
|
958
|
+
function synthesizeUpdatedRow(table, variables) {
|
|
959
|
+
const input = extractMutationInput(variables);
|
|
960
|
+
const id = input.id;
|
|
961
|
+
let patch = {};
|
|
962
|
+
for (const [key, value] of Object.entries(input)) {
|
|
963
|
+
if (key === "id") continue;
|
|
964
|
+
if (value && typeof value === "object") {
|
|
965
|
+
patch = value;
|
|
966
|
+
break;
|
|
967
|
+
}
|
|
968
|
+
}
|
|
969
|
+
const existing = table.rows.find((r) => r.id === id);
|
|
970
|
+
const merged = { ...existing ?? { id }, ...patch };
|
|
971
|
+
if (existing) {
|
|
972
|
+
Object.assign(existing, patch);
|
|
973
|
+
} else {
|
|
974
|
+
table.rows.push(merged);
|
|
975
|
+
}
|
|
976
|
+
return merged;
|
|
977
|
+
}
|
|
978
|
+
function isMetaQuery(query) {
|
|
979
|
+
return query.includes("_meta");
|
|
980
|
+
}
|
|
981
|
+
function isMutationDocument(query) {
|
|
982
|
+
return /(^|\s)mutation(\s|\{)/.test(query);
|
|
983
|
+
}
|
|
984
|
+
function findMutationTable(query, tables) {
|
|
985
|
+
let best = null;
|
|
986
|
+
for (const table of tables) {
|
|
987
|
+
const candidates = [
|
|
988
|
+
{ op: "create", mutationName: (0, import_data5.toCreateMutationName)(table.name) },
|
|
989
|
+
{ op: "update", mutationName: (0, import_data5.toUpdateMutationName)(table.name) },
|
|
990
|
+
{ op: "delete", mutationName: (0, import_data5.toDeleteMutationName)(table.name) }
|
|
991
|
+
];
|
|
992
|
+
for (const c of candidates) {
|
|
993
|
+
if (query.includes(c.mutationName) && (!best || c.mutationName.length > best.mutationName.length)) {
|
|
994
|
+
best = { table, op: c.op, mutationName: c.mutationName, singular: (0, import_data5.toCamelCaseSingular)(table.name) };
|
|
995
|
+
}
|
|
996
|
+
}
|
|
997
|
+
}
|
|
998
|
+
return best;
|
|
999
|
+
}
|
|
1000
|
+
function findListTable(query, tables) {
|
|
1001
|
+
let best = null;
|
|
1002
|
+
let bestLen = 0;
|
|
1003
|
+
for (const table of tables) {
|
|
1004
|
+
const plural = (0, import_data5.toCamelCasePlural)(table.name);
|
|
1005
|
+
if (query.includes(plural) && plural.length > bestLen) {
|
|
1006
|
+
best = table;
|
|
1007
|
+
bestLen = plural.length;
|
|
1008
|
+
}
|
|
1009
|
+
}
|
|
1010
|
+
return best;
|
|
1011
|
+
}
|
|
1012
|
+
function createMockExecute(opts) {
|
|
1013
|
+
const mutations = [];
|
|
1014
|
+
function record(m) {
|
|
1015
|
+
mutations.push(m);
|
|
1016
|
+
opts.onMutation?.(m);
|
|
1017
|
+
}
|
|
1018
|
+
const execute = async (document, variables) => {
|
|
1019
|
+
const query = documentToString2(document);
|
|
1020
|
+
if (isMetaQuery(query)) {
|
|
1021
|
+
return buildMetaResponse(opts.tables);
|
|
1022
|
+
}
|
|
1023
|
+
const mutationMatch = isMutationDocument(query) ? findMutationTable(query, opts.tables) : null;
|
|
1024
|
+
if (mutationMatch) {
|
|
1025
|
+
const { table, op, mutationName, singular } = mutationMatch;
|
|
1026
|
+
record({ op, tableName: table.name, variables: variables ?? {}, at: Date.now() });
|
|
1027
|
+
if (op === "delete") {
|
|
1028
|
+
const input = extractMutationInput(variables);
|
|
1029
|
+
const id = input.id ?? null;
|
|
1030
|
+
table.rows = table.rows.filter((r) => r.id !== id);
|
|
1031
|
+
return { [mutationName]: { deletedNodeId: id, clientMutationId: null } };
|
|
1032
|
+
}
|
|
1033
|
+
const row = op === "create" ? synthesizeCreatedRow(table, singular, variables) : synthesizeUpdatedRow(table, variables);
|
|
1034
|
+
return { [mutationName]: { [singular]: row } };
|
|
1035
|
+
}
|
|
1036
|
+
const listTable = findListTable(query, opts.tables);
|
|
1037
|
+
if (listTable) {
|
|
1038
|
+
return buildListResponse(listTable);
|
|
1039
|
+
}
|
|
1040
|
+
return {};
|
|
1041
|
+
};
|
|
1042
|
+
const executeUpload = async (file, path, options) => {
|
|
1043
|
+
const name = file?.name ?? "file";
|
|
1044
|
+
record({
|
|
1045
|
+
op: "upload",
|
|
1046
|
+
tableName: options?.tableName ?? "",
|
|
1047
|
+
variables: {
|
|
1048
|
+
name,
|
|
1049
|
+
...path !== void 0 && { path },
|
|
1050
|
+
...options?.fieldName !== void 0 && { fieldName: options.fieldName },
|
|
1051
|
+
...options?.recordId !== void 0 && { recordId: options.recordId }
|
|
1052
|
+
},
|
|
1053
|
+
at: Date.now()
|
|
1054
|
+
});
|
|
1055
|
+
return { url: "mock://uploaded/" + name };
|
|
1056
|
+
};
|
|
1057
|
+
function reset() {
|
|
1058
|
+
mutations.length = 0;
|
|
1059
|
+
}
|
|
1060
|
+
return { execute, executeUpload, mutations, reset };
|
|
1061
|
+
}
|
|
1062
|
+
function MockSheetsProvider({ options, children }) {
|
|
1063
|
+
const { execute, executeUpload } = (0, import_react4.useMemo)(() => createMockExecute(options), []);
|
|
1064
|
+
const queryClient = (0, import_react4.useMemo)(
|
|
1065
|
+
() => new import_react_query2.QueryClient({
|
|
1066
|
+
defaultOptions: {
|
|
1067
|
+
queries: { retry: false, gcTime: 0 },
|
|
1068
|
+
mutations: { retry: false }
|
|
1069
|
+
}
|
|
1070
|
+
}),
|
|
1071
|
+
[]
|
|
1072
|
+
);
|
|
1073
|
+
return /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
|
|
1074
|
+
SheetsProvider,
|
|
1075
|
+
{
|
|
1076
|
+
config: {
|
|
1077
|
+
endpoint: "mock://sheets",
|
|
1078
|
+
auth: { mode: "embedded", getToken: () => "test" },
|
|
1079
|
+
execute,
|
|
1080
|
+
executeUpload,
|
|
1081
|
+
queryClient
|
|
1082
|
+
},
|
|
1083
|
+
children
|
|
1084
|
+
}
|
|
1085
|
+
);
|
|
1086
|
+
}
|
|
1087
|
+
var usersFixture = {
|
|
1088
|
+
name: "users",
|
|
1089
|
+
fields: [
|
|
1090
|
+
{ name: "id", gqlType: "UUID", pgType: "uuid" },
|
|
1091
|
+
{ name: "name", gqlType: "String", pgType: "text" },
|
|
1092
|
+
{ name: "email", gqlType: "String", pgType: "text" },
|
|
1093
|
+
{ name: "isActive", gqlType: "Boolean", pgType: "boolean" },
|
|
1094
|
+
{ name: "createdAt", gqlType: "Datetime", pgType: "timestamptz" }
|
|
1095
|
+
],
|
|
1096
|
+
rows: [
|
|
1097
|
+
{
|
|
1098
|
+
id: "00000000-0000-0000-0000-000000000001",
|
|
1099
|
+
name: "Ada Lovelace",
|
|
1100
|
+
email: "ada@example.com",
|
|
1101
|
+
isActive: true,
|
|
1102
|
+
createdAt: "2024-01-01T00:00:00Z"
|
|
1103
|
+
},
|
|
1104
|
+
{
|
|
1105
|
+
id: "00000000-0000-0000-0000-000000000002",
|
|
1106
|
+
name: "Alan Turing",
|
|
1107
|
+
email: "alan@example.com",
|
|
1108
|
+
isActive: false,
|
|
1109
|
+
createdAt: "2024-01-02T00:00:00Z"
|
|
1110
|
+
}
|
|
1111
|
+
]
|
|
1112
|
+
};
|
|
1113
|
+
//# sourceMappingURL=testing.cjs.map
|