@constructive-io/sheets 0.13.1 → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +10 -1
  2. package/dist/advanced.cjs +554 -716
  3. package/dist/advanced.cjs.map +1 -1
  4. package/dist/advanced.d.cts +2 -2
  5. package/dist/advanced.d.ts +2 -2
  6. package/dist/advanced.js +4 -4
  7. package/dist/auth.cjs.map +1 -1
  8. package/dist/auth.js +2 -2
  9. package/dist/{chunk-PZL2BCWF.js → chunk-6Y7CZ5VS.js} +2 -2
  10. package/dist/chunk-6Y7CZ5VS.js.map +1 -0
  11. package/dist/{chunk-AYMXT3ME.js → chunk-BGL6EBTE.js} +108 -202
  12. package/dist/chunk-BGL6EBTE.js.map +1 -0
  13. package/dist/{chunk-MXVNIKES.js → chunk-BYAYBXVB.js} +2 -2
  14. package/dist/{chunk-5QPNOKMA.js → chunk-ER3FIDK7.js} +444 -458
  15. package/dist/chunk-ER3FIDK7.js.map +1 -0
  16. package/dist/chunk-GZM2CSTR.js +279 -0
  17. package/dist/chunk-GZM2CSTR.js.map +1 -0
  18. package/dist/{chunk-H5HR5HUJ.js → chunk-YJZFHL2D.js} +1 -1
  19. package/dist/chunk-YJZFHL2D.js.map +1 -0
  20. package/dist/{date-editor-ZFNDKYBD.js → date-editor-G26WKILO.js} +2 -2
  21. package/dist/{grid-cell-types-Pbe2m2tE.d.ts → grid-cell-types-C2-ocDS7.d.cts} +45 -5
  22. package/dist/{grid-cell-types-Pbe2m2tE.d.cts → grid-cell-types-C2-ocDS7.d.ts} +45 -5
  23. package/dist/index.cjs +782 -637
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.d.cts +106 -112
  26. package/dist/index.d.ts +106 -112
  27. package/dist/index.js +234 -134
  28. package/dist/index.js.map +1 -1
  29. package/dist/{sheets-context-Cu3Ec_ca.d.ts → sheets-context-CHUVJCff.d.ts} +32 -31
  30. package/dist/{sheets-context-CY1RmDKL.d.cts → sheets-context-C_MkTxXm.d.cts} +32 -31
  31. package/dist/testing.cjs +121 -87
  32. package/dist/testing.cjs.map +1 -1
  33. package/dist/testing.d.cts +2 -2
  34. package/dist/testing.d.ts +2 -2
  35. package/dist/testing.js +16 -4
  36. package/dist/testing.js.map +1 -1
  37. package/package.json +5 -4
  38. package/dist/chunk-5QPNOKMA.js.map +0 -1
  39. package/dist/chunk-AYMXT3ME.js.map +0 -1
  40. package/dist/chunk-H5HR5HUJ.js.map +0 -1
  41. package/dist/chunk-PZL2BCWF.js.map +0 -1
  42. package/dist/chunk-ZKANUG3F.js +0 -123
  43. package/dist/chunk-ZKANUG3F.js.map +0 -1
  44. /package/dist/{chunk-MXVNIKES.js.map → chunk-BYAYBXVB.js.map} +0 -0
  45. /package/dist/{date-editor-ZFNDKYBD.js.map → date-editor-G26WKILO.js.map} +0 -0
package/dist/advanced.cjs CHANGED
@@ -166,7 +166,7 @@ var init_cell_type_groups = __esm({
166
166
  "date-array",
167
167
  "tags"
168
168
  ]);
169
- MEDIA_TYPES = /* @__PURE__ */ new Set(["image", "file", "video", "audio", "upload"]);
169
+ MEDIA_TYPES = /* @__PURE__ */ new Set(["image", "file", "video", "audio", "upload", "attachment"]);
170
170
  }
171
171
  });
172
172
 
@@ -1579,14 +1579,29 @@ function GeometryEditorDom({ value, fieldMeta, onCommit, onCancel }) {
1579
1579
  }
1580
1580
 
1581
1581
  // src/grid-dom/editors/image-editor.tsx
1582
- var import_react17 = require("react");
1582
+ var import_react16 = require("react");
1583
1583
 
1584
1584
  // src/grid/editors/image-editor.tsx
1585
- var import_react15 = require("react");
1585
+ var import_react14 = require("react");
1586
1586
  var import_lucide_react4 = require("lucide-react");
1587
- var import_react16 = require("motion/react");
1587
+ var import_react15 = require("motion/react");
1588
1588
  var import_toast = require("@constructive-io/ui/toast");
1589
1589
 
1590
+ // src/hooks/use-sheets-upload.ts
1591
+ var import_react_query3 = require("@tanstack/react-query");
1592
+ var import_data8 = require("@constructive-io/data");
1593
+
1594
+ // src/adapter/postgraphile-adapter.ts
1595
+ var import_graphql = require("graphql");
1596
+ var import_data7 = require("@constructive-io/data");
1597
+
1598
+ // src/hooks/use-sheets-table.ts
1599
+ var import_react10 = require("react");
1600
+ var import_react_query2 = require("@tanstack/react-query");
1601
+
1602
+ // src/hooks/use-sheets-meta.ts
1603
+ var import_react_query = require("@tanstack/react-query");
1604
+
1590
1605
  // src/context/sheets-context.ts
1591
1606
  var import_react9 = require("react");
1592
1607
  var SheetsContext = (0, import_react9.createContext)(null);
@@ -1598,43 +1613,6 @@ function useSheetsContext() {
1598
1613
  return ctx;
1599
1614
  }
1600
1615
 
1601
- // src/store/sheets-store.ts
1602
- var import_react10 = require("react");
1603
- var import_zustand = require("zustand");
1604
- var SheetsStoreContext = (0, import_react10.createContext)(null);
1605
- function useSheetsStore(selector) {
1606
- const store = (0, import_react10.useContext)(SheetsStoreContext);
1607
- if (!store) {
1608
- throw new Error("useSheetsStore must be used within a <SheetsProvider>");
1609
- }
1610
- return (0, import_zustand.useStore)(store, selector);
1611
- }
1612
- function useSheetsStoreApi() {
1613
- const store = (0, import_react10.useContext)(SheetsStoreContext);
1614
- if (!store) {
1615
- throw new Error("useSheetsStoreApi must be used within a <SheetsProvider>");
1616
- }
1617
- return store;
1618
- }
1619
-
1620
- // src/hooks/use-sheets-upload.ts
1621
- var import_react12 = require("react");
1622
- var import_react_query3 = require("@tanstack/react-query");
1623
- var import_data11 = require("@constructive-io/data");
1624
-
1625
- // src/hooks/use-sheets-meta.ts
1626
- var import_react_query2 = require("@tanstack/react-query");
1627
-
1628
- // src/adapter/postgraphile-adapter.ts
1629
- var import_data7 = require("@constructive-io/data");
1630
-
1631
- // src/hooks/use-sheets-table.ts
1632
- var import_react11 = require("react");
1633
- var import_react_query = require("@tanstack/react-query");
1634
- var import_data4 = require("@constructive-io/data");
1635
- var import_data5 = require("@constructive-io/data");
1636
- var import_data6 = require("@constructive-io/data");
1637
-
1638
1616
  // src/hooks/query-keys.ts
1639
1617
  function isSheetsScopeKey(value) {
1640
1618
  if (!value || typeof value !== "object") return false;
@@ -1653,6 +1631,7 @@ var sheetsQueryKeys = {
1653
1631
  root: ["sheets"],
1654
1632
  scope: (scope) => ["sheets", scope],
1655
1633
  meta: (scope) => [...sheetsQueryKeys.scope(scope), "meta"],
1634
+ mediaUrl: (scope, endpoint, id) => [...sheetsQueryKeys.scope(scope), "media-url", endpoint, id],
1656
1635
  typeFields: (scope, typeName) => [...sheetsQueryKeys.scope(scope), "type-fields", typeName],
1657
1636
  enumValues: (scope, typeName) => [...sheetsQueryKeys.scope(scope), "enum-values", typeName],
1658
1637
  relations: (scope, tableName) => [...sheetsQueryKeys.scope(scope), "relations", tableName],
@@ -1666,6 +1645,30 @@ var sheetsQueryKeys = {
1666
1645
  cursorTable: (scope, tableName, options) => [...sheetsQueryKeys.scope(scope), "cursor-table", tableName, options]
1667
1646
  };
1668
1647
 
1648
+ // src/hooks/use-sheets-meta.ts
1649
+ var metaKey = (scope) => sheetsQueryKeys.meta(scope);
1650
+ function useSheetsMeta(options = {}) {
1651
+ const { enabled = true } = options;
1652
+ const { execute, scopeKey } = useSheetsContext();
1653
+ const adapter = useSheetsAdapter();
1654
+ return (0, import_react_query.useQuery)({
1655
+ queryKey: metaKey(scopeKey),
1656
+ queryFn: () => adapter.fetchMeta(execute),
1657
+ staleTime: 5 * 60 * 1e3,
1658
+ // 5 min - finite so invalidation + remount triggers refetch
1659
+ gcTime: 30 * 60 * 1e3,
1660
+ // 30 min - survive long schema-editing sessions
1661
+ refetchOnMount: true,
1662
+ // Respect staleTime and refetch stale metadata on mount
1663
+ enabled
1664
+ });
1665
+ }
1666
+
1667
+ // src/hooks/use-sheets-table.ts
1668
+ var import_data4 = require("@constructive-io/data");
1669
+ var import_data5 = require("@constructive-io/data");
1670
+ var import_data6 = require("@constructive-io/data");
1671
+
1669
1672
  // src/hooks/relation-field-resolution.ts
1670
1673
  var import_inflekt = require("inflekt");
1671
1674
  var import_data = require("@constructive-io/data");
@@ -1981,20 +1984,20 @@ function transformToPostGraphileVariables(table, options = {}) {
1981
1984
  return variables;
1982
1985
  }
1983
1986
  function useSheetsTable(tableName, options = {}) {
1984
- const queryClient = (0, import_react_query.useQueryClient)();
1987
+ const queryClient = (0, import_react_query2.useQueryClient)();
1985
1988
  const { execute, scopeKey } = useSheetsContext();
1986
1989
  const { data: meta } = useSheetsMeta();
1987
1990
  const adapter = useSheetsAdapter();
1988
- const metaTables = (0, import_react11.useMemo)(() => {
1991
+ const metaTables = (0, import_react10.useMemo)(() => {
1989
1992
  if (!meta?._meta?.tables) return [];
1990
1993
  return meta._meta.tables.filter((candidate) => candidate != null);
1991
1994
  }, [meta]);
1992
- const tables = (0, import_react11.useMemo)(() => metaTables.map(import_data4.cleanTable), [metaTables]);
1993
- const table = (0, import_react11.useMemo)(
1995
+ const tables = (0, import_react10.useMemo)(() => metaTables.map(import_data4.cleanTable), [metaTables]);
1996
+ const table = (0, import_react10.useMemo)(
1994
1997
  () => tables.find((candidate) => candidate.name === tableName) ?? null,
1995
1998
  [tables, tableName]
1996
1999
  );
1997
- const tableMeta = (0, import_react11.useMemo)(
2000
+ const tableMeta = (0, import_react10.useMemo)(
1998
2001
  () => metaTables.find((candidate) => candidate.name === tableName) ?? null,
1999
2002
  [metaTables, tableName]
2000
2003
  );
@@ -2022,7 +2025,7 @@ function useSheetsTable(tableName, options = {}) {
2022
2025
  isLoading,
2023
2026
  error,
2024
2027
  refetch
2025
- } = (0, import_react_query.useQuery)({
2028
+ } = (0, import_react_query2.useQuery)({
2026
2029
  queryKey: sheetsTableQueryKeys.tableRows(scopeKey, tableName, finalQueryOptions),
2027
2030
  queryFn: async () => {
2028
2031
  if (!table) {
@@ -2065,7 +2068,7 @@ function useSheetsTable(tableName, options = {}) {
2065
2068
  });
2066
2069
  const rowsData = data?.rows ?? [];
2067
2070
  const totalCount = data?.totalCount ?? 0;
2068
- const createMutation = (0, import_react_query.useMutation)({
2071
+ const createMutation = (0, import_react_query2.useMutation)({
2069
2072
  mutationKey: sheetsTableMutationKeys.create(scopeKey, tableName),
2070
2073
  mutationFn: async (data2) => {
2071
2074
  if (!table || !tableMeta) {
@@ -2088,7 +2091,7 @@ function useSheetsTable(tableName, options = {}) {
2088
2091
  }
2089
2092
  }
2090
2093
  });
2091
- const updateMutation = (0, import_react_query.useMutation)({
2094
+ const updateMutation = (0, import_react_query2.useMutation)({
2092
2095
  mutationKey: sheetsTableMutationKeys.update(scopeKey, tableName),
2093
2096
  mutationFn: async ({ id, patch }) => {
2094
2097
  if (!table || !tableMeta) {
@@ -2142,7 +2145,7 @@ function useSheetsTable(tableName, options = {}) {
2142
2145
  }
2143
2146
  }
2144
2147
  });
2145
- const deleteMutation = (0, import_react_query.useMutation)({
2148
+ const deleteMutation = (0, import_react_query2.useMutation)({
2146
2149
  mutationKey: sheetsTableMutationKeys.delete(scopeKey, tableName),
2147
2150
  mutationFn: async (idOrPk) => {
2148
2151
  if (!table || !tableMeta) {
@@ -2344,11 +2347,17 @@ function createPostGraphileAdapter() {
2344
2347
  },
2345
2348
  async updateRow(ctx, id, patch, execute, options = {}) {
2346
2349
  const { table, allTables, tableName } = ctx;
2347
- const doc = (0, import_data7.buildPostGraphileUpdate)(table, allTables, {
2350
+ const mutationName = (0, import_data7.toUpdateMutationName)(tableName, table);
2351
+ const returning = options.returning && table.fields.filter((field) => options.returning?.includes(field.name)).map((field) => (0, import_graphql.print)((0, import_data7.getCustomAstForCleanField)(field))).join(" ");
2352
+ const payloadTable = returning && table.query ? { ...table, query: { ...table.query, one: null } } : table;
2353
+ const singularName = (0, import_data7.toCamelCaseSingular)(tableName, payloadTable);
2354
+ const patchFieldName = (0, import_data7.toPatchFieldName)(tableName, payloadTable);
2355
+ const doc = returning ? `mutation SheetsUpdateFields($input: ${mutationName[0].toUpperCase()}${mutationName.slice(1)}Input!) {
2356
+ ${mutationName}(input: $input) { ${singularName} { ${returning} } }
2357
+ }` : (0, import_data7.buildPostGraphileUpdate)(table, allTables, {
2348
2358
  ...options,
2349
2359
  fieldSelection: options.fieldSelection || "display"
2350
2360
  });
2351
- const patchFieldName = (0, import_data7.toPatchFieldName)(tableName, table);
2352
2361
  const sanitizedPatch = (0, import_data7.prepareUpdateInput)(patch);
2353
2362
  if (Object.keys(sanitizedPatch).length === 0) return null;
2354
2363
  const normalizedPatch = normalizeMutationEnums(ctx, sanitizedPatch, execute);
@@ -2359,8 +2368,6 @@ function createPostGraphileAdapter() {
2359
2368
  }
2360
2369
  };
2361
2370
  const result = await execute(doc, variables);
2362
- const mutationName = (0, import_data7.toUpdateMutationName)(tableName, table);
2363
- const singularName = (0, import_data7.toCamelCaseSingular)(tableName, table);
2364
2371
  const updatedRow = result[mutationName]?.[singularName] ?? null;
2365
2372
  return updatedRow;
2366
2373
  },
@@ -2382,61 +2389,125 @@ function useSheetsAdapter() {
2382
2389
  return config.adapter ?? defaultAdapter;
2383
2390
  }
2384
2391
 
2385
- // src/hooks/use-sheets-meta.ts
2386
- var metaKey = (scope) => sheetsQueryKeys.meta(scope);
2387
- function useSheetsMeta(options = {}) {
2388
- const { enabled = true } = options;
2389
- const { execute, scopeKey } = useSheetsContext();
2392
+ // src/hooks/use-sheets-upload.ts
2393
+ async function executeFieldUpload({ table: meta, allTables, fieldName, recordId }, file, { execute, executeUpload, adapter, onProgress }) {
2394
+ assertSheetsMutationAllowed(meta, "update");
2395
+ const identity = resolveSheetsIdentifier(meta, recordId);
2396
+ if (identity.status !== "identified") {
2397
+ throw new Error(`Cannot resolve a primary-key identity for table '${meta.name}'.`);
2398
+ }
2399
+ const table = (0, import_data8.cleanTable)(meta);
2400
+ const field = table.fields.find(({ name }) => name === fieldName);
2401
+ if (!field) throw new Error(`Field '${fieldName}' not found in table '${meta.name}'.`);
2402
+ const isAttachment = field.type.pgAlias?.toLowerCase() === "attachment" || field.type.pgType?.toLowerCase() === "attachment";
2403
+ let value = null;
2404
+ if (file) {
2405
+ const { file: projection } = await executeUpload(file, void 0, {
2406
+ tableName: meta.name,
2407
+ fieldName,
2408
+ recordId: typeof identity.identifier === "object" ? void 0 : identity.identifier,
2409
+ onProgress
2410
+ });
2411
+ if (isAttachment) {
2412
+ if (!projection.url) throw new Error("attachment columns need a public bucket with a public URL prefix");
2413
+ value = projection.url;
2414
+ } else {
2415
+ value = {
2416
+ ...projection,
2417
+ filename: projection.filename ?? file.name,
2418
+ mime: projection.mime ?? (file.type || "application/octet-stream")
2419
+ };
2420
+ }
2421
+ }
2422
+ const updatedRow = await adapter.updateRow(
2423
+ { table, tableName: meta.name, allTables: allTables?.map(import_data8.cleanTable) ?? [table] },
2424
+ identity.identifier,
2425
+ { [fieldName]: value },
2426
+ execute,
2427
+ { returning: [fieldName] }
2428
+ );
2429
+ if (!updatedRow || !Object.hasOwn(updatedRow, fieldName)) {
2430
+ throw new Error(`Update did not return '${fieldName}'.`);
2431
+ }
2432
+ const saved = updatedRow[fieldName];
2433
+ if (value === null) {
2434
+ if (saved === null) return null;
2435
+ } else if (isAttachment) {
2436
+ if (typeof saved === "string" && saved) return saved;
2437
+ } else if (saved && typeof saved === "object" && !Array.isArray(saved)) {
2438
+ return saved;
2439
+ }
2440
+ throw new Error(`Update returned an unexpected value for '${fieldName}'.`);
2441
+ }
2442
+ function useSheetsFieldUpload(tableName, fieldName, recordId, options = {}) {
2443
+ const queryClient = (0, import_react_query3.useQueryClient)();
2444
+ const { execute, executeUpload, scopeKey } = useSheetsContext();
2445
+ const { data: meta } = useSheetsMeta();
2390
2446
  const adapter = useSheetsAdapter();
2391
- return (0, import_react_query2.useQuery)({
2392
- queryKey: metaKey(scopeKey),
2393
- queryFn: () => adapter.fetchMeta(execute),
2394
- staleTime: 5 * 60 * 1e3,
2395
- // 5 min - finite so invalidation + remount triggers refetch
2396
- gcTime: 30 * 60 * 1e3,
2397
- // 30 min - survive long schema-editing sessions
2398
- refetchOnMount: true,
2399
- // Respect staleTime and refetch stale metadata on mount
2400
- enabled
2447
+ const allTables = meta?._meta?.tables?.filter((entry) => entry != null);
2448
+ const table = allTables?.find(({ name }) => name === tableName);
2449
+ function resolveRowIdentifier(row) {
2450
+ if (!table) return null;
2451
+ const identity = resolveSheetsRowIdentity(table, row);
2452
+ return identity.status === "identified" ? identity.identifier : null;
2453
+ }
2454
+ async function persist(id, file) {
2455
+ if (!table) throw new Error(`Table '${tableName}' not found.`);
2456
+ return executeFieldUpload(
2457
+ { table, allTables, fieldName, recordId: id },
2458
+ file,
2459
+ { execute, executeUpload, adapter, onProgress: options.onProgress }
2460
+ );
2461
+ }
2462
+ function invalidate() {
2463
+ void queryClient.invalidateQueries({ queryKey: sheetsQueryKeys.table(scopeKey, tableName) });
2464
+ }
2465
+ async function write(id, file) {
2466
+ const value = await persist(id, file);
2467
+ invalidate();
2468
+ return value;
2469
+ }
2470
+ const mutation = (0, import_react_query3.useMutation)({
2471
+ mutationKey: [...sheetsQueryKeys.table(scopeKey, tableName), "field-upload", fieldName, recordId],
2472
+ mutationFn: (file) => {
2473
+ if (recordId == null) throw new Error("Missing record context for upload");
2474
+ return persist(recordId, file);
2475
+ },
2476
+ onSuccess: (value) => {
2477
+ options.onSuccess?.(value);
2478
+ invalidate();
2479
+ },
2480
+ onError: options.onError
2401
2481
  });
2482
+ return { ...mutation, write, resolveRowIdentifier };
2402
2483
  }
2403
2484
 
2404
- // src/hooks/use-sheets-upload.ts
2405
- var import_data12 = require("@constructive-io/data");
2485
+ // src/hooks/use-sheets-media-url.ts
2486
+ var import_react11 = require("react");
2487
+ var import_react_query4 = require("@tanstack/react-query");
2406
2488
 
2407
- // src/context/sheets-execute.ts
2489
+ // src/context/sheets-upload-presigned.ts
2408
2490
  var import_graphql2 = require("graphql");
2409
2491
  var import_data9 = require("@constructive-io/data");
2410
-
2411
- // src/context/sheets-upload-presigned.ts
2412
- var import_graphql = require("graphql");
2413
- var import_data8 = require("@constructive-io/data");
2414
- async function sha256HexFromBuffer(buffer) {
2415
- if (!globalThis.crypto?.subtle) {
2416
- throw import_data8.createError.badRequest("Web Crypto (crypto.subtle) is unavailable; cannot hash file for upload.");
2417
- }
2418
- const digest = await crypto.subtle.digest("SHA-256", buffer);
2419
- const bytes = new Uint8Array(digest);
2420
- let hex = "";
2421
- for (let i = 0; i < bytes.length; i++) {
2422
- hex += bytes[i].toString(16).padStart(2, "0");
2423
- }
2424
- return hex;
2425
- }
2426
- var capabilityCache = /* @__PURE__ */ new Map();
2427
- function discoverUploadCapability(endpoint, execute) {
2428
- const cached = capabilityCache.get(endpoint);
2492
+ var capabilityCache = /* @__PURE__ */ new WeakMap();
2493
+ async function discoverStorageCapabilities(endpoint, execute) {
2494
+ let endpoints = capabilityCache.get(execute);
2495
+ if (!endpoints) {
2496
+ endpoints = /* @__PURE__ */ new Map();
2497
+ capabilityCache.set(execute, endpoints);
2498
+ }
2499
+ const cached = endpoints.get(endpoint);
2429
2500
  if (cached) return cached;
2430
2501
  const promise = (async () => {
2431
- const data = await execute((0, import_graphql.getIntrospectionQuery)());
2502
+ const data = await execute((0, import_graphql2.getIntrospectionQuery)());
2432
2503
  const schema = data?.__schema;
2433
2504
  if (!schema) {
2434
- throw import_data8.createError.badRequest("Uploads are not enabled for this endpoint.");
2505
+ throw import_data9.createError.badRequest("Uploads are not enabled for this endpoint.");
2435
2506
  }
2436
- return resolveUploadCapability(schema);
2507
+ return resolveStorageCapabilities(schema);
2437
2508
  })();
2438
- promise.catch(() => capabilityCache.delete(endpoint));
2439
- capabilityCache.set(endpoint, promise);
2509
+ promise.catch(() => endpoints.delete(endpoint));
2510
+ endpoints.set(endpoint, promise);
2440
2511
  return promise;
2441
2512
  }
2442
2513
  function namedTypeName(ref) {
@@ -2454,7 +2525,7 @@ function isListTypeRef(ref) {
2454
2525
  return cur?.kind === "LIST";
2455
2526
  }
2456
2527
  var PK_FIELD_NAME = "id";
2457
- function resolveUploadCapability(schema) {
2528
+ function resolveStorageCapabilities(schema) {
2458
2529
  const typeByName = /* @__PURE__ */ new Map();
2459
2530
  for (const t of schema.types) {
2460
2531
  if (t.name) typeByName.set(t.name, t);
@@ -2473,7 +2544,7 @@ function resolveUploadCapability(schema) {
2473
2544
  const present = new Set(t.inputFields.map((f) => f.name));
2474
2545
  return names.every((n) => present.has(n));
2475
2546
  };
2476
- const PAYLOAD_FIELDS = ["uploadUrl", "fileId", "deduplicated"];
2547
+ const PAYLOAD_FIELDS = ["uploadUrl", "fileId", "key", "deduplicated"];
2477
2548
  const INPUT_FIELDS = ["contentHash", "bucketKey", "contentType", "size"];
2478
2549
  const mutationType = schema.mutationType ? typeByName.get(schema.mutationType.name) : null;
2479
2550
  const queryType = schema.queryType ? typeByName.get(schema.queryType.name) : null;
@@ -2483,80 +2554,69 @@ function resolveUploadCapability(schema) {
2483
2554
  if (!inputArg) continue;
2484
2555
  const inputTypeName = namedTypeName(inputArg.type);
2485
2556
  const payloadTypeName = namedTypeName(field.type);
2486
- if (inputHasFields(inputTypeName, INPUT_FIELDS) && objectHasFields(payloadTypeName, PAYLOAD_FIELDS)) {
2487
- upload = { uploadFieldName: field.name, inputTypeName };
2488
- break;
2557
+ if (inputTypeName && inputHasFields(inputTypeName, INPUT_FIELDS) && objectHasFields(payloadTypeName, PAYLOAD_FIELDS)) {
2558
+ const payloadFields = typeByName.get(payloadTypeName ?? "")?.fields;
2559
+ const candidate = {
2560
+ uploadFieldName: field.name,
2561
+ inputTypeName,
2562
+ hasFileProjection: payloadFields?.some(
2563
+ (f) => f.name === "file" && !isListTypeRef(f.type) && namedTypeName(f.type) === "JSON"
2564
+ ) ?? false
2565
+ };
2566
+ if (field.name === "uploadAppFile") {
2567
+ upload = candidate;
2568
+ break;
2569
+ }
2570
+ upload ??= candidate;
2489
2571
  }
2490
2572
  }
2491
- if (!upload) {
2492
- throw import_data8.createError.badRequest("Uploads are not enabled for this endpoint.");
2493
- }
2494
- const downloadById = resolveDownloadByIdField(schema, typeByName, queryType, upload.uploadFieldName);
2495
- const uploadedTypeName = upload.uploadFieldName.replace(/^upload/, "");
2496
- const fileTypeName = typeByName.has(uploadedTypeName) ? uploadedTypeName : downloadById.fileTypeName;
2497
- let remove = {};
2498
- for (const field of mutationType?.fields ?? []) {
2499
- const inputArg = field.args.find((a) => a.name === "input");
2500
- const inputTypeName = namedTypeName(inputArg?.type);
2501
- const inputFields = inputTypeName ? typeByName.get(inputTypeName)?.inputFields : null;
2502
- if (!inputTypeName || !inputFields?.some((f) => f.name === PK_FIELD_NAME)) continue;
2503
- if (!inputFields.every((f) => f.name === PK_FIELD_NAME || f.name === "clientMutationId")) continue;
2504
- const payload = typeByName.get(namedTypeName(field.type) ?? "");
2505
- if (payload?.fields?.some((f) => namedTypeName(f.type) === fileTypeName)) {
2506
- remove = { deleteFieldName: field.name, deleteInputTypeName: inputTypeName };
2507
- break;
2573
+ const fileTypes = /* @__PURE__ */ new Set();
2574
+ for (const t of schema.types) {
2575
+ if (t.kind === "OBJECT" && t.name && t.fields?.some((f) => f.name === "downloadUrl")) {
2576
+ fileTypes.add(t.name);
2508
2577
  }
2509
2578
  }
2579
+ const uploadType = upload?.uploadFieldName.replace(/^upload/, "") ?? "AppFile";
2580
+ const uploadDownload = resolveDownloadByIdField(typeByName, queryType, fileTypes, uploadType);
2581
+ const preferredPreviewType = fileTypes.has("AppFile") ? "AppFile" : uploadType;
2582
+ const previewType = fileTypes.has(preferredPreviewType) ? preferredPreviewType : uploadDownload?.fileTypeName ?? preferredPreviewType;
2583
+ const download = previewType === uploadType ? uploadDownload : resolveDownloadByIdField(typeByName, queryType, fileTypes, previewType);
2584
+ const batch = resolveConnectionDownloadField(typeByName, queryType, fileTypes, previewType, true);
2510
2585
  return {
2511
- ...upload,
2512
- ...downloadById,
2513
- ...remove
2586
+ upload: upload ? { ...upload, download: uploadDownload } : null,
2587
+ download,
2588
+ batch
2514
2589
  };
2515
2590
  }
2516
- async function deleteUploadedFileRow(execute, cap, fileId) {
2517
- if (!cap.deleteFieldName || !cap.deleteInputTypeName) return;
2518
- const mutation = `
2519
- mutation SheetsUploadCleanup($input: ${cap.deleteInputTypeName}!) {
2520
- ${cap.deleteFieldName}(input: $input) { __typename }
2521
- }
2522
- `.trim();
2523
- try {
2524
- await execute(mutation, { input: { [PK_FIELD_NAME]: fileId } });
2525
- } catch {
2526
- }
2527
- }
2528
- function resolveDownloadByIdField(schema, typeByName, queryType, uploadFieldName) {
2529
- const fileTypesWithDownloadUrl = /* @__PURE__ */ new Set();
2530
- for (const t of schema.types) {
2531
- if (t.kind === "OBJECT" && t.name && t.fields?.some((f) => f.name === "downloadUrl")) {
2532
- fileTypesWithDownloadUrl.add(t.name);
2533
- }
2534
- }
2591
+ function resolveDownloadByIdField(typeByName, queryType, fileTypesWithDownloadUrl, preferred) {
2592
+ let singular = null;
2535
2593
  for (const field of queryType?.fields ?? []) {
2536
2594
  const returnTypeName = namedTypeName(field.type);
2537
2595
  if (!returnTypeName || !fileTypesWithDownloadUrl.has(returnTypeName)) continue;
2538
2596
  if (field.args.length === 1 && field.args[0].name === PK_FIELD_NAME) {
2539
- return {
2597
+ const candidate = {
2540
2598
  fileByIdField: field.name,
2541
2599
  fileByIdArgName: "id",
2542
2600
  fileTypeName: returnTypeName,
2543
2601
  idScalarName: namedTypeName(field.args[0].type) ?? void 0
2544
2602
  };
2603
+ if (returnTypeName === preferred) return candidate;
2604
+ singular ??= candidate;
2545
2605
  }
2546
2606
  }
2547
- const connection = resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, uploadFieldName);
2548
- if (connection) return connection;
2607
+ const connection = resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, preferred);
2608
+ if (connection?.fileTypeName === preferred) return connection;
2609
+ if (singular || connection) return singular ?? connection;
2549
2610
  const nodeField = queryType?.fields?.find(
2550
2611
  (f) => f.name === "node" && f.args.some((a) => a.name === "nodeId")
2551
2612
  );
2552
2613
  if (nodeField && fileTypesWithDownloadUrl.size > 0) {
2553
- const preferred = uploadFieldName.replace(/^upload/, "");
2554
2614
  const fileTypeName = fileTypesWithDownloadUrl.has(preferred) ? preferred : [...fileTypesWithDownloadUrl][0];
2555
2615
  return { fileByIdField: "node", fileByIdArgName: "nodeId", fileTypeName };
2556
2616
  }
2557
- throw import_data8.createError.badRequest("Uploads are not enabled for this endpoint.");
2617
+ return null;
2558
2618
  }
2559
- function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, uploadFieldName) {
2619
+ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, preferred, batch = false) {
2560
2620
  const EQUALITY_OPERATORS = ["equalTo", "eq"];
2561
2621
  const candidates = [];
2562
2622
  for (const field of queryType?.fields ?? []) {
@@ -2571,6 +2631,8 @@ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDown
2571
2631
  });
2572
2632
  if (!nodesField) continue;
2573
2633
  const fileTypeName = namedTypeName(nodesField.type);
2634
+ if (batch && (fileTypeName !== preferred || !typeByName.get(fileTypeName)?.fields?.some((field2) => field2.name === PK_FIELD_NAME))) continue;
2635
+ const connectionHasFirst = field.args.some((arg) => arg.name === "first");
2574
2636
  for (const arg of field.args) {
2575
2637
  const filterTypeName = namedTypeName(arg.type);
2576
2638
  const filterType = filterTypeName ? typeByName.get(filterTypeName) : null;
@@ -2580,7 +2642,7 @@ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDown
2580
2642
  const idFieldTypeName = namedTypeName(idField.type);
2581
2643
  const idFieldType = idFieldTypeName ? typeByName.get(idFieldTypeName) : null;
2582
2644
  if (idFieldType?.kind === "INPUT_OBJECT" && idFieldType.inputFields) {
2583
- const opField = EQUALITY_OPERATORS.map(
2645
+ const opField = batch ? idFieldType.inputFields.find((f) => f.name === "in" && isListTypeRef(f.type)) : EQUALITY_OPERATORS.map(
2584
2646
  (op) => idFieldType.inputFields.find((f) => f.name === op)
2585
2647
  ).find((f) => f != null);
2586
2648
  if (opField) {
@@ -2592,13 +2654,14 @@ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDown
2592
2654
  connectionFilterArgName: arg.name,
2593
2655
  connectionIdField: idField.name,
2594
2656
  connectionIdOperator: opField.name,
2595
- connectionNodesField: nodesField.name
2657
+ connectionNodesField: nodesField.name,
2658
+ connectionHasFirst
2596
2659
  });
2597
2660
  break;
2598
2661
  }
2599
2662
  continue;
2600
2663
  }
2601
- if (idFieldType?.kind === "SCALAR" || !idFieldType && idFieldTypeName) {
2664
+ if (!batch && (idFieldType?.kind === "SCALAR" || !idFieldType && idFieldTypeName)) {
2602
2665
  candidates.push({
2603
2666
  fileByIdField: field.name,
2604
2667
  fileByIdArgName: "connection",
@@ -2606,97 +2669,19 @@ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDown
2606
2669
  idScalarName: idFieldTypeName ?? void 0,
2607
2670
  connectionFilterArgName: arg.name,
2608
2671
  connectionIdField: idField.name,
2609
- connectionNodesField: nodesField.name
2672
+ connectionNodesField: nodesField.name,
2673
+ connectionHasFirst
2610
2674
  });
2611
2675
  break;
2612
2676
  }
2613
2677
  }
2614
2678
  }
2615
2679
  if (candidates.length === 0) return null;
2616
- const preferred = uploadFieldName.replace(/^upload/, "");
2617
2680
  return candidates.find((c) => c.fileTypeName === preferred) ?? candidates[0];
2618
2681
  }
2619
- async function callUploadOp(execute, cap, input) {
2620
- const mutation = `
2621
- mutation SheetsUpload($input: ${cap.inputTypeName}!) {
2622
- ${cap.uploadFieldName}(input: $input) {
2623
- uploadUrl
2624
- fileId
2625
- key
2626
- deduplicated
2627
- }
2628
- }
2629
- `.trim();
2630
- const data = await execute(mutation, {
2631
- input: {
2632
- bucketKey: input.bucketKey,
2633
- contentHash: input.contentHash,
2634
- contentType: input.contentType,
2635
- size: input.size,
2636
- filename: input.filename
2637
- }
2638
- });
2639
- const payload = data?.[cap.uploadFieldName];
2640
- if (!payload) {
2641
- throw import_data8.createError.badRequest("Upload failed: no payload returned from upload mutation.");
2642
- }
2643
- return payload;
2644
- }
2645
- var STORAGE_UPLOAD_BLOCKED_MESSAGE = "Upload failed: the storage server didn't accept the upload from this site. Check the bucket's allowed origins (CORS) and your connection.";
2646
- function storageUnreachableError() {
2647
- return import_data8.createError.graphql(STORAGE_UPLOAD_BLOCKED_MESSAGE, "STORAGE_UPLOAD_BLOCKED");
2648
- }
2649
- async function presignedPut(url, buffer, contentType, onProgress) {
2650
- const total = buffer.byteLength;
2651
- if (onProgress && typeof XMLHttpRequest !== "undefined") {
2652
- await putWithXHR(url, buffer, contentType, total, onProgress);
2653
- return;
2654
- }
2655
- let response;
2656
- try {
2657
- response = await fetch(url, {
2658
- method: "PUT",
2659
- headers: { "Content-Type": contentType },
2660
- body: buffer
2661
- });
2662
- } catch {
2663
- throw storageUnreachableError();
2664
- }
2665
- if (!response.ok) {
2666
- const body = await response.text().catch(() => "");
2667
- throw import_data8.createError.badRequest(`Upload failed: ${response.status} ${response.statusText}${body ? ` \u2014 ${body}` : ""}`);
2668
- }
2669
- onProgress?.({ loaded: total, total, percentage: 100 });
2670
- }
2671
- function putWithXHR(url, buffer, contentType, total, onProgress) {
2672
- return new Promise((resolve, reject) => {
2673
- const xhr = new XMLHttpRequest();
2674
- xhr.open("PUT", url);
2675
- xhr.setRequestHeader("Content-Type", contentType);
2676
- xhr.upload.addEventListener("progress", (event) => {
2677
- if (event.lengthComputable) {
2678
- onProgress({
2679
- loaded: event.loaded,
2680
- total: event.total,
2681
- percentage: Math.round(event.loaded / event.total * 100)
2682
- });
2683
- }
2684
- });
2685
- xhr.addEventListener("load", () => {
2686
- if (xhr.status >= 200 && xhr.status < 300) {
2687
- onProgress({ loaded: total, total, percentage: 100 });
2688
- resolve();
2689
- } else {
2690
- reject(import_data8.createError.badRequest(`Upload failed: ${xhr.status} ${xhr.statusText}${xhr.responseText ? ` \u2014 ${xhr.responseText}` : ""}`));
2691
- }
2692
- });
2693
- xhr.addEventListener("error", () => reject(storageUnreachableError()));
2694
- xhr.send(buffer);
2695
- });
2696
- }
2697
2682
  function toGlobalId(typeName, id) {
2698
2683
  if (typeof btoa !== "function") {
2699
- throw import_data8.createError.badRequest("Cannot encode the file node id: btoa is unavailable in this environment.");
2684
+ throw import_data9.createError.badRequest("Cannot encode the file node id: btoa is unavailable in this environment.");
2700
2685
  }
2701
2686
  return btoa(JSON.stringify([typeName, id]));
2702
2687
  }
@@ -2716,7 +2701,7 @@ async function fetchDownloadUrl(execute, cap, fileId) {
2716
2701
  const node = data2?.[cap.fileByIdField];
2717
2702
  const url2 = node?.downloadUrl;
2718
2703
  if (!url2) {
2719
- throw import_data8.createError.badRequest("Upload succeeded but no downloadUrl was returned for the file.");
2704
+ throw import_data9.createError.badRequest("Upload succeeded but no downloadUrl was returned for the file.");
2720
2705
  }
2721
2706
  return url2;
2722
2707
  }
@@ -2728,7 +2713,7 @@ async function fetchDownloadUrl(execute, cap, fileId) {
2728
2713
  const filterLiteral = cap.connectionIdOperator ? `{ ${idField}: { ${cap.connectionIdOperator}: $id } }` : `{ ${idField}: $id }`;
2729
2714
  const query2 = `
2730
2715
  query SheetsDownloadUrl($id: ${idScalar2}!) {
2731
- ${cap.fileByIdField}(${filterArg}: ${filterLiteral}, first: 1) {
2716
+ ${cap.fileByIdField}(${filterArg}: ${filterLiteral}${cap.connectionHasFirst ? ", first: 1" : ""}) {
2732
2717
  ${nodesField} {
2733
2718
  downloadUrl
2734
2719
  }
@@ -2742,7 +2727,7 @@ async function fetchDownloadUrl(execute, cap, fileId) {
2742
2727
  const conn = data2?.[cap.fileByIdField];
2743
2728
  const url2 = conn?.[nodesField]?.[0]?.downloadUrl;
2744
2729
  if (!url2) {
2745
- throw import_data8.createError.badRequest("Upload succeeded but no downloadUrl was returned for the file.");
2730
+ throw import_data9.createError.badRequest("Upload succeeded but no downloadUrl was returned for the file.");
2746
2731
  }
2747
2732
  return url2;
2748
2733
  }
@@ -2759,265 +2744,33 @@ async function fetchDownloadUrl(execute, cap, fileId) {
2759
2744
  const file = data?.[cap.fileByIdField];
2760
2745
  const url = file?.downloadUrl;
2761
2746
  if (!url) {
2762
- throw import_data8.createError.badRequest("Upload succeeded but no downloadUrl was returned for the file.");
2747
+ throw import_data9.createError.badRequest("Upload succeeded but no downloadUrl was returned for the file.");
2763
2748
  }
2764
2749
  return url;
2765
2750
  }
2766
-
2767
- // src/context/sheets-execute.ts
2768
- var import_data10 = require("@constructive-io/data");
2769
- function documentToString(document2) {
2770
- if (typeof document2 === "string") return document2;
2771
- if (document2 instanceof String) return document2.toString();
2772
- if (document2 && typeof document2 === "object" && "kind" in document2) {
2773
- return (0, import_graphql2.print)(document2);
2774
- }
2775
- if (document2 === null || document2 === void 0) {
2776
- throw import_data9.createError.badRequest("Invalid GraphQL document: null or undefined");
2777
- }
2778
- return String(document2);
2779
- }
2780
- function hasAuthMessage(message) {
2781
- const normalized = String(message ?? "").toLowerCase();
2782
- return normalized.includes("unauthenticated") || normalized.includes("unauthorized") || normalized.includes("authentication");
2783
- }
2784
- function parseGraphQLResponse(response, onAuthError) {
2785
- if (!response.errors?.length) return null;
2786
- const error = response.errors[0];
2787
- const code = error.extensions?.code;
2788
- const message = error.message || "GraphQL query failed";
2789
- if (code === "UNAUTHENTICATED" || hasAuthMessage(message)) {
2790
- onAuthError?.();
2791
- return import_data9.createError.unauthorized("Authentication required. Please log in again.");
2792
- }
2793
- if (code === "FORBIDDEN") {
2794
- return import_data9.createError.forbidden("You do not have permission to perform this action.");
2795
- }
2796
- return import_data9.createError.graphql(message, code);
2797
- }
2798
- function createSheetsExecute(config, getToken) {
2799
- return async (document2, variables) => {
2800
- const url = config.endpoint;
2801
- if (!url) {
2802
- throw import_data9.createError.badRequest("No GraphQL endpoint configured.");
2803
- }
2804
- const token = getToken();
2805
- const headers = {
2806
- "Content-Type": "application/json",
2807
- Accept: "application/graphql-response+json"
2808
- };
2809
- if (token) {
2810
- headers["Authorization"] = `Bearer ${token}`;
2811
- }
2812
- let response;
2813
- try {
2814
- response = await fetch(url, {
2815
- method: "POST",
2816
- headers,
2817
- body: JSON.stringify({
2818
- query: documentToString(document2),
2819
- ...variables !== void 0 && { variables }
2820
- })
2821
- });
2822
- } catch (error) {
2823
- throw import_data9.createError.network(error instanceof Error ? error : void 0);
2824
- }
2825
- if (!response.ok) {
2826
- const { status, statusText } = response;
2827
- if (status === 401) {
2828
- config.onAuthError?.();
2829
- throw import_data9.createError.unauthorized("Authentication required. Please log in again.");
2830
- }
2831
- if (status === 403) {
2832
- throw import_data9.createError.forbidden("You do not have permission to perform this action.");
2833
- }
2834
- if (status === 404) {
2835
- throw import_data9.createError.notFound("The requested endpoint does not exist.");
2836
- }
2837
- try {
2838
- const body = await response.json();
2839
- if (body.errors?.length) {
2840
- throw import_data9.createError.graphql(body.errors[0].message || `Request failed: ${status}`, body.errors[0].extensions?.code);
2841
- }
2842
- } catch (e) {
2843
- if (e instanceof import_data9.ConstructiveError) throw e;
2844
- }
2845
- throw import_data9.createError.badRequest(`Request failed: ${status} ${statusText}`);
2846
- }
2847
- const result = await response.json();
2848
- const graphqlError = parseGraphQLResponse(result, config.onAuthError);
2849
- if (graphqlError) {
2850
- throw graphqlError;
2851
- }
2852
- return result.data;
2853
- };
2854
- }
2855
- function createSheetsUpload(config, getToken) {
2856
- const execute = config.execute ?? createSheetsExecute(config, getToken);
2857
- return async (file, _path, options) => {
2858
- if (!config.endpoint) {
2859
- throw import_data9.createError.badRequest("No GraphQL endpoint configured.");
2751
+ async function fetchMediaDownloadUrls({ endpoint, execute }, getActiveIds) {
2752
+ const { batch, download } = await discoverStorageCapabilities(endpoint, execute);
2753
+ const ids = getActiveIds();
2754
+ const urls = /* @__PURE__ */ new Map();
2755
+ if (ids.length === 0) return urls;
2756
+ if (batch) {
2757
+ const first = batch.connectionHasFirst ? `, first: ${ids.length}` : "";
2758
+ const query = `query SheetsMediaDownloadUrls($ids: [${batch.idScalarName ?? "ID"}!]!) {
2759
+ ${batch.fileByIdField}(${batch.connectionFilterArgName}: {
2760
+ ${batch.connectionIdField}: { in: $ids }
2761
+ }${first}) { ${batch.connectionNodesField} { id downloadUrl } }
2762
+ }`;
2763
+ const data = await execute(query, { ids });
2764
+ for (const row of data?.[batch.fileByIdField]?.[batch.connectionNodesField] ?? []) {
2765
+ if (row?.downloadUrl) urls.set(row.id, row.downloadUrl);
2860
2766
  }
2861
- const bucketKey = config.upload?.bucketKey ?? "public";
2862
- const contentType = file.type || "application/octet-stream";
2863
- const buffer = await file.arrayBuffer();
2864
- const contentHash = await sha256HexFromBuffer(buffer);
2865
- const cap = await discoverUploadCapability(config.endpoint, execute);
2866
- const payload = await callUploadOp(execute, cap, {
2867
- bucketKey,
2868
- contentHash,
2869
- contentType,
2870
- size: file.size,
2871
- filename: file.name
2767
+ } else if (download) {
2768
+ const results = await Promise.allSettled(ids.map((id) => fetchDownloadUrl(execute, download, id)));
2769
+ results.forEach((result, index) => {
2770
+ if (result.status === "fulfilled") urls.set(ids[index], result.value);
2872
2771
  });
2873
- if (!payload.deduplicated) {
2874
- if (!payload.uploadUrl) {
2875
- throw import_data9.createError.badRequest("Upload failed: server returned no uploadUrl for a non-deduplicated file.");
2876
- }
2877
- try {
2878
- await presignedPut(payload.uploadUrl, buffer, contentType, options?.onProgress);
2879
- } catch (error) {
2880
- await deleteUploadedFileRow(execute, cap, payload.fileId);
2881
- throw error;
2882
- }
2883
- } else {
2884
- options?.onProgress?.({ loaded: file.size, total: file.size, percentage: 100 });
2885
- }
2886
- const url = await fetchDownloadUrl(execute, cap, payload.fileId);
2887
- return {
2888
- url,
2889
- filename: file.name,
2890
- mime: file.type,
2891
- size: file.size,
2892
- key: payload.key,
2893
- fileId: payload.fileId
2894
- };
2895
- };
2896
- }
2897
-
2898
- // src/hooks/use-sheets-upload.ts
2899
- function resolveUploadNaming(tableName, table) {
2900
- return {
2901
- mutationName: (0, import_data12.toUpdateMutationName)(tableName, table),
2902
- singularName: (0, import_data12.toCamelCaseSingular)(tableName, table),
2903
- patchFieldName: (0, import_data12.toPatchFieldName)(tableName, table),
2904
- updateInputTypeName: (0, import_data12.toUpdateInputTypeName)(tableName)
2905
- };
2906
- }
2907
- function resolveTransport(endpoint, getToken, options) {
2908
- if (options?.execute && options?.executeUpload) {
2909
- return { execute: options.execute, executeUpload: options.executeUpload };
2910
- }
2911
- const config = {
2912
- endpoint,
2913
- auth: { mode: "standalone" },
2914
- onAuthError: options?.onAuthError
2915
- };
2916
- return {
2917
- execute: createSheetsExecute(config, getToken),
2918
- executeUpload: createSheetsUpload(config, getToken)
2919
- };
2920
- }
2921
- async function executeFieldUpload(tableName, fieldName, recordId, file, endpoint, getToken, naming, options) {
2922
- if (!endpoint && !(options?.execute && options?.executeUpload)) {
2923
- throw new Error("No endpoint configured. Select a database API or use Direct Connect.");
2924
- }
2925
- const { execute, executeUpload } = resolveTransport(endpoint, getToken, options);
2926
- const uploadResult = await executeUpload(file, void 0, {
2927
- tableName,
2928
- fieldName,
2929
- recordId,
2930
- onProgress: options?.onProgress
2931
- });
2932
- const resolvedNaming = naming ?? resolveUploadNaming(tableName);
2933
- const patchValue = {
2934
- ...uploadResult.url != null && { url: uploadResult.url },
2935
- ...uploadResult.filename != null && { filename: uploadResult.filename },
2936
- ...uploadResult.mime != null && { mime: uploadResult.mime },
2937
- ...uploadResult.size != null && { size: uploadResult.size }
2938
- };
2939
- const mutationString = `
2940
- mutation ${resolvedNaming.mutationName}Mutation($input: ${resolvedNaming.updateInputTypeName}!) {
2941
- ${resolvedNaming.mutationName}(input: $input) {
2942
- ${resolvedNaming.singularName} {
2943
- id
2944
- ${fieldName}
2945
- }
2946
- }
2947
- }
2948
- `.trim();
2949
- const result = await execute(mutationString, {
2950
- input: {
2951
- id: recordId,
2952
- [resolvedNaming.patchFieldName]: {
2953
- [fieldName]: patchValue
2954
- }
2955
- }
2956
- });
2957
- const updatedRecord = result?.[resolvedNaming.mutationName]?.[resolvedNaming.singularName];
2958
- if (!updatedRecord) {
2959
- throw new Error("Upload succeeded but no data returned from patch");
2960
2772
  }
2961
- const uploadedFileData = updatedRecord[fieldName];
2962
- if (!uploadedFileData) {
2963
- throw new Error(`Upload succeeded but ${fieldName} field not found in response`);
2964
- }
2965
- const fileObject = typeof uploadedFileData === "object" ? uploadedFileData : null;
2966
- return {
2967
- url: fileObject?.url || uploadedFileData,
2968
- filename: fileObject?.filename || file.name,
2969
- mime: fileObject?.mime || file.type,
2970
- size: fileObject?.size || file.size
2971
- };
2972
- }
2973
- function useSheetsFieldUpload(tableName, fieldName, recordId, options = {}) {
2974
- const queryClient = (0, import_react_query3.useQueryClient)();
2975
- const { scopeKey, config, execute, executeUpload } = useSheetsContext();
2976
- const storeApi = useSheetsStoreApi();
2977
- const { data: meta } = useSheetsMeta();
2978
- const table = (0, import_react12.useMemo)(() => {
2979
- if (!meta?._meta?.tables) return null;
2980
- const candidate = meta._meta.tables.find((item) => item?.name === tableName);
2981
- return candidate ? (0, import_data11.cleanTable)(candidate) : null;
2982
- }, [meta, tableName]);
2983
- const resolvedNaming = (0, import_react12.useMemo)(() => resolveUploadNaming(tableName, table), [tableName, table]);
2984
- const getToken = (0, import_react12.useMemo)(() => {
2985
- if (config.auth.mode === "embedded") {
2986
- return config.auth.getToken;
2987
- }
2988
- return () => storeApi.getState().accessToken;
2989
- }, [config.auth, storeApi]);
2990
- const tableRef = (0, import_react12.useRef)(tableName);
2991
- const fieldRef = (0, import_react12.useRef)(fieldName);
2992
- const idRef = (0, import_react12.useRef)(recordId);
2993
- (0, import_react12.useEffect)(() => {
2994
- tableRef.current = tableName;
2995
- fieldRef.current = fieldName;
2996
- idRef.current = recordId;
2997
- }, [tableName, fieldName, recordId]);
2998
- return (0, import_react_query3.useMutation)({
2999
- mutationKey: ["sheets", scopeKey, "field-upload", tableName, fieldName, recordId],
3000
- mutationFn: async (file) => {
3001
- return executeFieldUpload(
3002
- tableRef.current,
3003
- fieldRef.current,
3004
- idRef.current,
3005
- file,
3006
- config.endpoint,
3007
- getToken,
3008
- resolvedNaming,
3009
- { onAuthError: config.onAuthError, execute, executeUpload, onProgress: options.onProgress }
3010
- );
3011
- },
3012
- onSuccess: (data) => {
3013
- options.onSuccess?.(data);
3014
- queryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.table(scopeKey, tableRef.current) });
3015
- queryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.tableRow(scopeKey, tableRef.current, idRef.current) });
3016
- },
3017
- onError: (error) => {
3018
- options.onError?.(error);
3019
- }
3020
- });
2773
+ return urls;
3021
2774
  }
3022
2775
 
3023
2776
  // src/utils/file.utils.ts
@@ -3037,14 +2790,18 @@ var getImageUrl = (imageValue) => {
3037
2790
  }
3038
2791
  return null;
3039
2792
  };
2793
+ function getMediaFileId(value) {
2794
+ if (!value || typeof value !== "object") return null;
2795
+ const { id } = value;
2796
+ return typeof id === "string" && id ? id : null;
2797
+ }
3040
2798
  var getImageMetadata = (imageValue) => {
3041
2799
  if (!imageValue || typeof imageValue !== "object") return null;
3042
2800
  const obj = imageValue;
3043
2801
  return {
3044
2802
  filename: obj.filename || obj.name || "Unknown",
3045
- size: obj.size || obj.fileSize || 0,
3046
- mime: obj.mime || obj.type || obj.contentType || "unknown",
3047
- url: getImageUrl(imageValue) || ""
2803
+ size: typeof obj.size === "number" ? obj.size : typeof obj.fileSize === "number" ? obj.fileSize : void 0,
2804
+ mime: obj.mime || obj.type || obj.contentType || "unknown"
3048
2805
  };
3049
2806
  };
3050
2807
  var formatFileSize = (bytes) => {
@@ -3055,28 +2812,106 @@ var formatFileSize = (bytes) => {
3055
2812
  return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + " " + sizes[i];
3056
2813
  };
3057
2814
 
2815
+ // src/hooks/use-sheets-media-url.ts
2816
+ var MAX_BATCH_SIZE = 100;
2817
+ var REFRESH_INTERVAL = 50 * 60 * 1e3;
2818
+ var UNRESOLVED_STALE_TIME = 60 * 1e3;
2819
+ var loaders = /* @__PURE__ */ new WeakMap();
2820
+ function createMediaLoader(storage) {
2821
+ let pending = [];
2822
+ async function fetchBatch(requests) {
2823
+ const getActiveIds = () => [...new Set(requests.filter(({ signal }) => !signal.aborted).map(({ id }) => id))];
2824
+ try {
2825
+ const urls = getActiveIds().length ? await fetchMediaDownloadUrls(storage, getActiveIds) : null;
2826
+ for (const request of requests) {
2827
+ request.resolve(request.signal.aborted ? null : urls?.get(request.id) ?? null);
2828
+ }
2829
+ } catch (error) {
2830
+ for (const request of requests) request.reject(error);
2831
+ }
2832
+ }
2833
+ function flush() {
2834
+ const requests = pending;
2835
+ pending = [];
2836
+ for (let start = 0; start < requests.length; start += MAX_BATCH_SIZE) {
2837
+ void fetchBatch(requests.slice(start, start + MAX_BATCH_SIZE));
2838
+ }
2839
+ }
2840
+ return (id, signal) => new Promise((resolve, reject) => {
2841
+ if (pending.length === 0) queueMicrotask(flush);
2842
+ pending.push({ id, signal, resolve, reject });
2843
+ });
2844
+ }
2845
+ function getMediaLoader(storage, scopeKey) {
2846
+ let scopes = loaders.get(storage);
2847
+ if (!scopes) {
2848
+ scopes = /* @__PURE__ */ new WeakMap();
2849
+ loaders.set(storage, scopes);
2850
+ }
2851
+ let load = scopes.get(scopeKey);
2852
+ if (!load) {
2853
+ load = createMediaLoader(storage);
2854
+ scopes.set(scopeKey, load);
2855
+ }
2856
+ return load;
2857
+ }
2858
+ function useSheetsMediaUrl(value, previewImage = true) {
2859
+ const { storage, scopeKey } = useSheetsContext();
2860
+ const durableUrl = getImageUrl(value);
2861
+ const id = getMediaFileId(value);
2862
+ const endpoint = storage?.endpoint;
2863
+ const resource = (0, import_react11.useMemo)(() => ({ scopeKey, endpoint, id }), [scopeKey, endpoint, id]);
2864
+ const query = (0, import_react_query4.useQuery)({
2865
+ queryKey: sheetsQueryKeys.mediaUrl(scopeKey, endpoint, id),
2866
+ queryFn: storage && id && previewImage && !durableUrl ? ({ signal }) => getMediaLoader(storage, scopeKey)(id, signal) : import_react_query4.skipToken,
2867
+ staleTime: (query2) => query2.state.data ? REFRESH_INTERVAL : UNRESOLVED_STALE_TIME,
2868
+ gcTime: REFRESH_INTERVAL,
2869
+ refetchInterval: (query2) => query2.state.data && query2.state.status === "success" ? REFRESH_INTERVAL : false,
2870
+ refetchOnWindowFocus: true,
2871
+ retry: false
2872
+ });
2873
+ const signedUrl = previewImage && !durableUrl && !query.isPlaceholderData ? query.data ?? null : null;
2874
+ const [failed, setFailed] = (0, import_react11.useState)(null);
2875
+ const retried = (0, import_react11.useRef)(null);
2876
+ const { refetch } = query;
2877
+ const onImageError = (0, import_react11.useCallback)(() => {
2878
+ if (!signedUrl) return;
2879
+ setFailed({ resource, url: signedUrl });
2880
+ if (retried.current === resource) return;
2881
+ retried.current = resource;
2882
+ void refetch({ cancelRefetch: false });
2883
+ }, [refetch, resource, signedUrl]);
2884
+ const onImageLoad = (0, import_react11.useCallback)(() => {
2885
+ if (retried.current !== resource) return;
2886
+ retried.current = null;
2887
+ setFailed(null);
2888
+ }, [resource]);
2889
+ const url = durableUrl ?? (failed?.resource === resource && failed.url === signedUrl ? null : signedUrl);
2890
+ return { url, durableUrl, id, isLoading: query.isFetching && !url, onImageError, onImageLoad };
2891
+ }
2892
+
3058
2893
  // src/grid/editors/image-editor.tsx
3059
2894
  init_sheets_logger();
3060
2895
 
3061
2896
  // src/utils/use-image-status.ts
3062
- var import_react13 = require("react");
2897
+ var import_react12 = require("react");
3063
2898
  function useImageStatus(src) {
3064
- const [status, setStatus] = (0, import_react13.useState)("idle");
3065
- (0, import_react13.useEffect)(() => {
3066
- if (!src) return setStatus("idle");
3067
- setStatus("loading");
2899
+ const [result, setResult] = (0, import_react12.useState)();
2900
+ (0, import_react12.useEffect)(() => {
2901
+ if (!src) return;
3068
2902
  const img = new Image();
3069
- img.src = src;
3070
- const onLoad = () => setStatus("loaded");
3071
- const onError = () => setStatus("error");
2903
+ const onLoad = () => setResult({ src, status: "loaded" });
2904
+ const onError = () => setResult({ src, status: "error" });
3072
2905
  img.addEventListener("load", onLoad);
3073
2906
  img.addEventListener("error", onError);
2907
+ img.src = src;
3074
2908
  return () => {
3075
2909
  img.removeEventListener("load", onLoad);
3076
2910
  img.removeEventListener("error", onError);
3077
2911
  };
3078
2912
  }, [src]);
3079
- return status;
2913
+ if (!src) return "idle";
2914
+ return result?.src === src ? result.status : "loading";
3080
2915
  }
3081
2916
 
3082
2917
  // src/grid/editors/image-editor.tsx
@@ -3084,7 +2919,7 @@ var import_button5 = require("@constructive-io/ui/button");
3084
2919
  var import_skeleton = require("@constructive-io/ui/skeleton");
3085
2920
 
3086
2921
  // src/utils/image-with-fallback.tsx
3087
- var import_react14 = require("react");
2922
+ var import_react13 = require("react");
3088
2923
  init_cn();
3089
2924
  var import_jsx_runtime10 = require("react/jsx-runtime");
3090
2925
  function ImageWithFallback({
@@ -3097,14 +2932,14 @@ function ImageWithFallback({
3097
2932
  className,
3098
2933
  ...imgProps
3099
2934
  }) {
3100
- const fallbacks = (0, import_react14.useMemo)(() => {
2935
+ const fallbacks = (0, import_react13.useMemo)(() => {
3101
2936
  const legacyFallbacks = [];
3102
2937
  if (loadingElement) legacyFallbacks.push(loadingElement);
3103
2938
  if (fallbackElement) legacyFallbacks.push(fallbackElement);
3104
2939
  const primaryFallbacks = fallback === void 0 ? [] : Array.isArray(fallback) ? fallback : [fallback];
3105
2940
  return [...primaryFallbacks, ...legacyFallbacks];
3106
2941
  }, [fallback, fallbackElement, loadingElement]);
3107
- const [currentSrcIndex, setCurrentSrcIndex] = (0, import_react14.useState)(0);
2942
+ const [currentSrcIndex, setCurrentSrcIndex] = (0, import_react13.useState)(0);
3108
2943
  const currentSrc = currentSrcIndex === 0 ? src : fallbacks[currentSrcIndex - 1];
3109
2944
  const status = useImageStatus(typeof currentSrc === "string" ? currentSrc : void 0);
3110
2945
  if (status === "error" && currentSrcIndex < fallbacks.length) {
@@ -3146,9 +2981,6 @@ function ImageWithFallback({
3146
2981
  init_editor_focus_trap();
3147
2982
  init_overlay_presets();
3148
2983
  var import_jsx_runtime11 = require("react/jsx-runtime");
3149
- function normalizeUploadResponse(data) {
3150
- return { url: data.url, filename: data.filename, size: data.size, mime: data.mime };
3151
- }
3152
2984
  var dropzoneTransition = { duration: 0.15, ease: [0.2, 0, 0, 1] };
3153
2985
  function RemoveButton({ onClick, label }) {
3154
2986
  return /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("div", { className: "absolute top-2 right-2", children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
@@ -3167,13 +2999,14 @@ function RemoveButton({ onClick, label }) {
3167
2999
  }
3168
3000
  function FilePreview({ name, size, mime }) {
3169
3001
  const hasMime = !!mime && mime !== "unknown";
3002
+ const hasSize = size !== void 0;
3170
3003
  return /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { className: "flex size-full flex-col items-center justify-center gap-2 p-4 text-center", children: [
3171
3004
  /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("div", { className: "bg-muted/60 flex size-12 shrink-0 items-center justify-center rounded-lg", "aria-hidden": "true", children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_lucide_react4.FileIcon, { className: "text-muted-foreground size-6" }) }),
3172
3005
  /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { className: "min-w-0 max-w-full", children: [
3173
3006
  /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("p", { className: "truncate text-sm font-medium", title: name, children: name || "File" }),
3174
- (size || hasMime) && /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("p", { className: "text-muted-foreground mt-0.5 text-xs", children: [
3175
- size ? formatFileSize(size) : null,
3176
- size && hasMime ? " \u2022 " : null,
3007
+ (hasSize || hasMime) && /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("p", { className: "text-muted-foreground mt-0.5 text-xs", children: [
3008
+ hasSize ? formatFileSize(size) : null,
3009
+ hasSize && hasMime ? " \u2022 " : null,
3177
3010
  hasMime ? /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("span", { className: "uppercase", children: mime }) : null
3178
3011
  ] })
3179
3012
  ] })
@@ -3193,72 +3026,79 @@ var ImageEditor = ({
3193
3026
  }) => {
3194
3027
  const noun = acceptAnyFile ? "file" : "image";
3195
3028
  const Noun = acceptAnyFile ? "File" : "Image";
3196
- const [uploadState, setUploadState] = (0, import_react15.useState)("idle");
3197
- const { config } = useSheetsContext();
3198
- const storeApi = useSheetsStoreApi();
3199
- const { maxHeight: overlayMaxHeight } = (0, import_react15.useContext)(OverlayMeasureContext);
3200
- const getToken = (0, import_react15.useMemo)(() => {
3201
- if (config.auth.mode === "embedded") return config.auth.getToken;
3202
- return () => storeApi.getState().accessToken;
3203
- }, [config.auth, storeApi]);
3204
- const fileInputRef = (0, import_react15.useRef)(null);
3205
- const previewUrlRef = (0, import_react15.useRef)(null);
3206
- const committedRecordIdRef = (0, import_react15.useRef)(null);
3029
+ const [uploadState, setUploadState] = (0, import_react14.useState)("idle");
3030
+ const { maxHeight: overlayMaxHeight } = (0, import_react14.useContext)(OverlayMeasureContext);
3031
+ const fileInputRef = (0, import_react14.useRef)(null);
3032
+ const previewUrlRef = (0, import_react14.useRef)(null);
3033
+ const committedRecordIdRef = (0, import_react14.useRef)(null);
3207
3034
  const currentImageData = value ?? null;
3208
- const [imageValue, setImageValue] = (0, import_react15.useState)(currentImageData);
3209
- const [selectedFile, setSelectedFile] = (0, import_react15.useState)(null);
3210
- const [previewUrl, setPreviewUrl] = (0, import_react15.useState)(null);
3211
- const [uploadProgress, setUploadProgress] = (0, import_react15.useState)(null);
3212
- const [isDragging, setIsDragging] = (0, import_react15.useState)(false);
3213
- const [dragErrors, setDragErrors] = (0, import_react15.useState)([]);
3035
+ const [imageValue, setImageValue] = (0, import_react14.useState)(currentImageData);
3036
+ const [selectedFile, setSelectedFile] = (0, import_react14.useState)(null);
3037
+ const [previewUrl, setPreviewUrl] = (0, import_react14.useState)(null);
3038
+ const [uploadProgress, setUploadProgress] = (0, import_react14.useState)(null);
3039
+ const [isDragging, setIsDragging] = (0, import_react14.useState)(false);
3040
+ const [dragErrors, setDragErrors] = (0, import_react14.useState)([]);
3214
3041
  const isSubmittingDraft = uploadState === "submitting-draft";
3215
3042
  const isUploading = uploadState === "uploading";
3043
+ const isClearing = uploadState === "clearing";
3216
3044
  const isBusy = uploadState !== "idle";
3217
- const imageUrl = (0, import_react15.useMemo)(() => getImageUrl(imageValue), [imageValue]);
3218
- const imageMetadata = (0, import_react15.useMemo)(() => getImageMetadata(imageValue), [imageValue]);
3045
+ const imageMetadata = (0, import_react14.useMemo)(() => getImageMetadata(imageValue), [imageValue]);
3219
3046
  const storedMime = imageMetadata?.mime;
3220
3047
  const storedIsImage = !acceptAnyFile || !!storedMime && storedMime.startsWith("image/");
3048
+ const { url: imageUrl, durableUrl, id: storedFileId, isLoading: isResolvingImage, onImageError, onImageLoad } = useSheetsMediaUrl(imageValue, storedIsImage);
3221
3049
  const imageStatus = useImageStatus(storedIsImage ? imageUrl || void 0 : void 0);
3222
- const imageLoadFailed = storedIsImage && imageUrl != null && imageStatus === "error";
3223
- const hasImage = imageUrl != null && !imageLoadFailed && storedIsImage;
3224
- const revokePreviewUrl = (0, import_react15.useCallback)(() => {
3050
+ (0, import_react14.useEffect)(() => {
3051
+ if (imageStatus === "error") onImageError();
3052
+ if (imageStatus === "loaded") onImageLoad();
3053
+ }, [imageStatus, onImageError, onImageLoad]);
3054
+ const imageLoadFailed = storedIsImage && durableUrl != null && imageStatus === "error";
3055
+ const hasImage = (imageUrl != null || isResolvingImage) && !imageLoadFailed && storedIsImage;
3056
+ const hasStoredMedia = Boolean(storedFileId || durableUrl);
3057
+ const clearPending = value != null && imageValue == null;
3058
+ const needsDraftCreation = isDraftRow && committedRecordIdRef.current == null;
3059
+ const selectedIsImage = !acceptAnyFile || (selectedFile?.type.startsWith("image/") ?? false);
3060
+ const revokePreviewUrl = (0, import_react14.useCallback)(() => {
3225
3061
  if (previewUrlRef.current) {
3226
3062
  URL.revokeObjectURL(previewUrlRef.current);
3227
3063
  previewUrlRef.current = null;
3228
3064
  }
3229
3065
  }, []);
3230
- const resetFileState = (0, import_react15.useCallback)(() => {
3066
+ const resetFileState = (0, import_react14.useCallback)(() => {
3231
3067
  revokePreviewUrl();
3232
3068
  setUploadProgress(null);
3233
3069
  setSelectedFile(null);
3234
3070
  setPreviewUrl(null);
3235
3071
  setUploadState("idle");
3236
3072
  }, [revokePreviewUrl]);
3237
- const handleUploadSuccess = (0, import_react15.useCallback)((data) => {
3238
- const normalized = normalizeUploadResponse(data);
3073
+ const finishSave = (0, import_react14.useCallback)((data, message) => {
3239
3074
  resetFileState();
3240
- setImageValue(normalized);
3241
- onSaveComplete?.({ imageData: normalized });
3075
+ setImageValue(data);
3076
+ if (committedRecordIdRef.current == null) {
3077
+ onSaveComplete?.({ imageData: data });
3078
+ } else {
3079
+ onDraftUploadComplete?.();
3080
+ }
3242
3081
  onFinishedEditing();
3243
- import_toast.toast.success({ message: `${Noun} uploaded successfully` });
3244
- }, [resetFileState, onSaveComplete, onFinishedEditing, Noun]);
3245
- const handleUploadError = (0, import_react15.useCallback)((error) => {
3082
+ import_toast.toast.success({ message });
3083
+ }, [resetFileState, onSaveComplete, onDraftUploadComplete, onFinishedEditing]);
3084
+ const handleWriteError = (0, import_react14.useCallback)((error) => {
3246
3085
  setUploadState("idle");
3247
- sheetsLogger().error("[image-editor] upload failed:", error);
3248
- import_toast.toast.error({ message: error.message || "Upload failed" });
3086
+ setUploadProgress(null);
3087
+ sheetsLogger().error("[image-editor] media update failed:", error);
3088
+ import_toast.toast.error({ message: error.message || "Could not save the file" });
3249
3089
  }, []);
3250
- const uploadMutation = useSheetsFieldUpload(tableName || "", fieldName || "", recordId || "", {
3090
+ const uploadMutation = useSheetsFieldUpload(tableName || "", fieldName || "", recordId ?? null, {
3251
3091
  onProgress: setUploadProgress,
3252
- onSuccess: handleUploadSuccess,
3253
- onError: handleUploadError,
3092
+ onSuccess: (data) => finishSave(data, data === null ? `${Noun} cleared` : `${Noun} uploaded successfully`),
3093
+ onError: handleWriteError,
3254
3094
  showToast: false
3255
3095
  });
3256
- const handleRemoveImage = (0, import_react15.useCallback)(() => {
3096
+ const handleRemoveImage = (0, import_react14.useCallback)(() => {
3257
3097
  setImageValue(null);
3258
3098
  setSelectedFile(null);
3259
3099
  setPreviewUrl(null);
3260
3100
  }, []);
3261
- const handleFileSelection = (0, import_react15.useCallback)((acceptedFiles) => {
3101
+ const handleFileSelection = (0, import_react14.useCallback)((acceptedFiles) => {
3262
3102
  if (acceptedFiles.length === 0) return;
3263
3103
  const file = acceptedFiles[0];
3264
3104
  if (!acceptAnyFile) {
@@ -3277,21 +3117,21 @@ var ImageEditor = ({
3277
3117
  previewUrlRef.current = url;
3278
3118
  setPreviewUrl(url);
3279
3119
  }, [revokePreviewUrl, acceptAnyFile]);
3280
- const handleDragEnter = (0, import_react15.useCallback)((e) => {
3120
+ const handleDragEnter = (0, import_react14.useCallback)((e) => {
3281
3121
  e.preventDefault();
3282
3122
  e.stopPropagation();
3283
3123
  setIsDragging(true);
3284
3124
  }, []);
3285
- const handleDragLeave = (0, import_react15.useCallback)((e) => {
3125
+ const handleDragLeave = (0, import_react14.useCallback)((e) => {
3286
3126
  e.preventDefault();
3287
3127
  e.stopPropagation();
3288
3128
  setIsDragging(false);
3289
3129
  }, []);
3290
- const handleDragOver = (0, import_react15.useCallback)((e) => {
3130
+ const handleDragOver = (0, import_react14.useCallback)((e) => {
3291
3131
  e.preventDefault();
3292
3132
  e.stopPropagation();
3293
3133
  }, []);
3294
- const handleDrop = (0, import_react15.useCallback)((e) => {
3134
+ const handleDrop = (0, import_react14.useCallback)((e) => {
3295
3135
  e.preventDefault();
3296
3136
  e.stopPropagation();
3297
3137
  setIsDragging(false);
@@ -3299,129 +3139,126 @@ var ImageEditor = ({
3299
3139
  const files = Array.from(e.dataTransfer.files);
3300
3140
  if (files.length > 0) handleFileSelection(files);
3301
3141
  }, [handleFileSelection]);
3302
- const openFileDialog = (0, import_react15.useCallback)(() => fileInputRef.current?.click(), []);
3303
- const removeFile = (0, import_react15.useCallback)(() => {
3142
+ const openFileDialog = (0, import_react14.useCallback)(() => fileInputRef.current?.click(), []);
3143
+ const removeFile = (0, import_react14.useCallback)(() => {
3304
3144
  revokePreviewUrl();
3305
3145
  setSelectedFile(null);
3306
3146
  setPreviewUrl(null);
3307
3147
  setDragErrors([]);
3308
3148
  }, [revokePreviewUrl]);
3309
- const handleConfirmUpload = (0, import_react15.useCallback)(async () => {
3310
- if (!tableName || !fieldName || !selectedFile) return;
3311
- const committedId = committedRecordIdRef.current ?? recordId;
3312
- if (committedRecordIdRef.current != null) {
3313
- try {
3314
- import_toast.toast.info({ message: `Uploading ${noun}...` });
3315
- setUploadState("uploading");
3316
- const uploadResult = await executeFieldUpload(
3317
- tableName,
3318
- fieldName,
3319
- committedRecordIdRef.current,
3320
- selectedFile,
3321
- config.endpoint,
3322
- getToken,
3323
- void 0,
3324
- { onAuthError: config.onAuthError }
3325
- );
3326
- const normalized = normalizeUploadResponse(uploadResult);
3327
- resetFileState();
3328
- setImageValue(normalized);
3329
- onDraftUploadComplete?.();
3330
- import_toast.toast.success({ message: `${Noun} uploaded successfully` });
3331
- onFinishedEditing();
3332
- } catch (error) {
3333
- onDraftUploadComplete?.();
3334
- setUploadState("idle");
3335
- import_toast.toast.error({ message: error instanceof Error ? error.message : "Upload failed" });
3149
+ const handleConfirmUpload = (0, import_react14.useCallback)(async () => {
3150
+ if (isBusy || !tableName || !fieldName || !selectedFile) return;
3151
+ if (!isDraftRow) {
3152
+ if (recordId == null) {
3153
+ import_toast.toast.error({ message: "Missing record context for upload" });
3154
+ return;
3336
3155
  }
3156
+ setUploadState("uploading");
3157
+ uploadMutation.mutate(selectedFile);
3337
3158
  return;
3338
3159
  }
3339
- if (isDraftRow) {
3340
- if (!onSubmitDraft) {
3341
- import_toast.toast.error({ message: "Cannot upload to draft row - save the row first" });
3342
- return;
3343
- }
3344
- try {
3160
+ let rowPersisted = committedRecordIdRef.current != null;
3161
+ try {
3162
+ const createRow = committedRecordIdRef.current == null;
3163
+ if (createRow) {
3164
+ if (!onSubmitDraft) throw new Error("Cannot upload to draft row - save the row first");
3345
3165
  import_toast.toast.info({ message: "Creating row..." });
3346
3166
  setUploadState("submitting-draft");
3347
- const result = await onSubmitDraft();
3348
- const createdId = result.createdRow?.id;
3349
- if (typeof createdId !== "string" && typeof createdId !== "number") {
3350
- throw new Error("Image uploads require a scalar id primary key.");
3351
- }
3352
- committedRecordIdRef.current = createdId;
3353
- import_toast.toast.info({ message: `Uploading ${noun}...` });
3354
- setUploadState("uploading");
3355
- const uploadResult = await executeFieldUpload(
3356
- tableName,
3357
- fieldName,
3358
- createdId,
3359
- selectedFile,
3360
- config.endpoint,
3361
- getToken,
3362
- void 0,
3363
- { onAuthError: config.onAuthError }
3364
- );
3365
- const normalized = normalizeUploadResponse(uploadResult);
3366
- resetFileState();
3367
- setImageValue(normalized);
3368
- onDraftUploadComplete?.();
3369
- import_toast.toast.success({ message: `Row created and ${noun} uploaded` });
3370
- onFinishedEditing();
3371
- } catch (error) {
3372
- onDraftUploadComplete?.();
3373
- setUploadState("idle");
3374
- import_toast.toast.error({ message: error instanceof Error ? error.message : "Upload failed" });
3167
+ const { createdRow } = await onSubmitDraft();
3168
+ rowPersisted = true;
3169
+ committedRecordIdRef.current = createdRow ? uploadMutation.resolveRowIdentifier(createdRow) : null;
3375
3170
  }
3376
- return;
3171
+ const committedId = committedRecordIdRef.current;
3172
+ if (committedId == null) throw new Error("Uploads require a primary-key identity for the created row.");
3173
+ import_toast.toast.info({ message: `Uploading ${noun}...` });
3174
+ setUploadState("uploading");
3175
+ const saved = await uploadMutation.write(committedId, selectedFile);
3176
+ finishSave(saved, createRow ? `Row created and ${noun} uploaded` : `${Noun} uploaded successfully`);
3177
+ } catch (error) {
3178
+ if (rowPersisted) onDraftUploadComplete?.();
3179
+ handleWriteError(error instanceof Error ? error : new Error("Upload failed"));
3377
3180
  }
3378
- if (!committedId) {
3379
- import_toast.toast.error({ message: "Missing record context for upload" });
3181
+ }, [
3182
+ isBusy,
3183
+ tableName,
3184
+ fieldName,
3185
+ selectedFile,
3186
+ isDraftRow,
3187
+ recordId,
3188
+ uploadMutation,
3189
+ onSubmitDraft,
3190
+ noun,
3191
+ Noun,
3192
+ finishSave,
3193
+ onDraftUploadComplete,
3194
+ handleWriteError
3195
+ ]);
3196
+ const handleSave = (0, import_react14.useCallback)(async () => {
3197
+ if (isBusy) return;
3198
+ if (!clearPending) {
3199
+ onFinishedEditing();
3380
3200
  return;
3381
3201
  }
3382
- setUploadState("uploading");
3383
- uploadMutation.mutate(selectedFile);
3384
- }, [selectedFile, uploadMutation, tableName, fieldName, recordId, isDraftRow, onSubmitDraft, config.endpoint, config.onAuthError, getToken, resetFileState, onDraftUploadComplete, onFinishedEditing, noun, Noun]);
3385
- const handleSave = (0, import_react15.useCallback)(() => {
3386
- if (!imageValue) {
3387
- onFinishedEditing(null);
3202
+ const targetId = committedRecordIdRef.current ?? recordId;
3203
+ if (targetId == null) {
3204
+ if (isDraftRow) {
3205
+ finishSave(null, `${Noun} cleared`);
3206
+ } else {
3207
+ handleWriteError(new Error("Missing record context for clear"));
3208
+ }
3388
3209
  return;
3389
3210
  }
3390
- const url = getImageUrl(imageValue);
3391
- const originalUrl = getImageUrl(value);
3392
- if (url && originalUrl === url) {
3393
- onFinishedEditing();
3211
+ setUploadState("clearing");
3212
+ if (committedRecordIdRef.current == null) {
3213
+ uploadMutation.mutate(null);
3394
3214
  return;
3395
3215
  }
3396
- onFinishedEditing(url ?? value);
3397
- }, [imageValue, value, onFinishedEditing]);
3398
- const handleCancel = (0, import_react15.useCallback)(() => {
3216
+ try {
3217
+ const saved = await uploadMutation.write(targetId, null);
3218
+ finishSave(saved, `${Noun} cleared`);
3219
+ } catch (error) {
3220
+ handleWriteError(error instanceof Error ? error : new Error("Clear failed"));
3221
+ }
3222
+ }, [isBusy, clearPending, onFinishedEditing, recordId, isDraftRow, finishSave, Noun, handleWriteError, uploadMutation]);
3223
+ const handleCancel = (0, import_react14.useCallback)(() => {
3399
3224
  revokePreviewUrl();
3400
3225
  onFinishedEditing();
3401
3226
  }, [revokePreviewUrl, onFinishedEditing]);
3402
- (0, import_react15.useEffect)(() => () => revokePreviewUrl(), [revokePreviewUrl]);
3403
- const handleEditorKeyDown = (0, import_react15.useCallback)((e) => {
3227
+ (0, import_react14.useEffect)(() => () => revokePreviewUrl(), [revokePreviewUrl]);
3228
+ const handleEditorKeyDown = (0, import_react14.useCallback)((e) => {
3404
3229
  if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
3405
3230
  e.preventDefault();
3406
- handleSave();
3231
+ if (selectedFile) void handleConfirmUpload();
3232
+ else void handleSave();
3407
3233
  }
3408
- }, [handleSave]);
3409
- const hasStoredFile = acceptAnyFile && !!imageUrl && !storedIsImage;
3234
+ }, [handleConfirmUpload, handleSave, selectedFile]);
3235
+ const hasStoredFile = hasStoredMedia && !hasImage && !imageLoadFailed;
3410
3236
  const dropzoneKey = isBusy ? "busy" : previewUrl ? "preview" : hasImage ? "loaded" : hasStoredFile ? "file" : imageLoadFailed ? "broken" : "empty";
3411
3237
  const renderDropzoneContent = () => {
3412
3238
  if (isBusy) {
3413
3239
  return /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { "data-state": uploadState, className: "text-muted-foreground flex w-full flex-col items-center justify-center p-6", children: [
3414
3240
  /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_lucide_react4.Loader2, { className: "mb-2 size-6 animate-spin" }),
3415
- /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("p", { className: "text-sm", children: isSubmittingDraft ? "Creating row..." : `Uploading ${noun}...` }),
3241
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("p", { role: "status", className: "text-sm", children: isSubmittingDraft ? "Creating row..." : isClearing ? `Clearing ${noun}...` : `Uploading ${noun}...` }),
3416
3242
  isUploading && uploadProgress && /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { className: "mt-3 w-full max-w-xs", children: [
3417
- /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("div", { className: "bg-muted h-1.5 overflow-hidden rounded-full", children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
3243
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
3418
3244
  "div",
3419
3245
  {
3420
- className: "bg-primary h-1.5 rounded-full transition-[width] duration-(--duration-slow)",
3421
- style: { width: `${uploadProgress.percentage}%` }
3246
+ role: "progressbar",
3247
+ "aria-label": `Uploading ${noun}`,
3248
+ "aria-valuemin": 0,
3249
+ "aria-valuemax": 100,
3250
+ "aria-valuenow": Math.round(uploadProgress.percentage),
3251
+ className: "bg-muted h-1.5 overflow-hidden rounded-full",
3252
+ children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
3253
+ "div",
3254
+ {
3255
+ className: "bg-primary h-1.5 rounded-full transition-[width] duration-(--duration-slow)",
3256
+ style: { width: `${uploadProgress.percentage}%` }
3257
+ }
3258
+ )
3422
3259
  }
3423
- ) }),
3424
- /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("p", { className: "text-muted-foreground mt-1.5 text-center text-xs", children: [
3260
+ ),
3261
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("p", { "aria-hidden": "true", className: "text-muted-foreground mt-1.5 text-center text-xs tabular-nums", children: [
3425
3262
  Math.round(uploadProgress.percentage),
3426
3263
  "%"
3427
3264
  ] })
@@ -3429,7 +3266,6 @@ var ImageEditor = ({
3429
3266
  ] });
3430
3267
  }
3431
3268
  if (previewUrl) {
3432
- const selectedIsImage = !acceptAnyFile || (selectedFile?.type.startsWith("image/") ?? false);
3433
3269
  return /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { className: "relative w-full", style: { height: "13rem" }, children: [
3434
3270
  selectedIsImage ? /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("img", { src: previewUrl, alt: selectedFile?.name || "Selected file", className: "size-full object-contain p-2" }) : /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(FilePreview, { name: selectedFile?.name, size: selectedFile?.size, mime: selectedFile?.type }),
3435
3271
  /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(RemoveButton, { onClick: removeFile, label: "Remove selected file" })
@@ -3452,7 +3288,7 @@ var ImageEditor = ({
3452
3288
  }
3453
3289
  if (hasStoredFile) {
3454
3290
  return /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { className: "relative w-full", style: { height: "13rem" }, children: [
3455
- /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(FilePreview, { name: imageMetadata?.filename, size: imageMetadata?.size, mime: imageMetadata?.mime }),
3291
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(FilePreview, { name: imageMetadata?.filename ?? durableUrl ?? void 0, size: imageMetadata?.size, mime: imageMetadata?.mime }),
3456
3292
  /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(RemoveButton, { onClick: handleRemoveImage, label: "Remove file" })
3457
3293
  ] });
3458
3294
  }
@@ -3467,12 +3303,12 @@ var ImageEditor = ({
3467
3303
  }
3468
3304
  ),
3469
3305
  /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("p", { className: "text-sm font-medium", children: "Image unavailable" }),
3470
- imageUrl && /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
3306
+ durableUrl && /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
3471
3307
  "p",
3472
3308
  {
3473
3309
  className: "text-muted-foreground mt-1 max-w-full truncate font-mono text-[11px] opacity-50",
3474
- title: imageUrl,
3475
- children: imageUrl
3310
+ title: durableUrl,
3311
+ children: durableUrl
3476
3312
  }
3477
3313
  ),
3478
3314
  /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { className: "mt-3 flex items-center gap-2", children: [
@@ -3535,7 +3371,7 @@ var ImageEditor = ({
3535
3371
  )
3536
3372
  ] });
3537
3373
  };
3538
- const saveLabel = isSubmittingDraft ? "Creating..." : isUploading ? "Uploading..." : imageUrl ? "Save" : "Done";
3374
+ const saveLabel = isSubmittingDraft ? "Creating..." : isClearing ? "Clearing..." : isUploading ? "Uploading..." : hasStoredMedia || clearPending ? "Save" : "Done";
3539
3375
  return /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
3540
3376
  EditorFocusTrap,
3541
3377
  {
@@ -3545,7 +3381,7 @@ var ImageEditor = ({
3545
3381
  children: /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { onKeyDown: handleEditorKeyDown, className: "flex min-h-0 flex-1 flex-col", children: [
3546
3382
  /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { className: "flex shrink-0 items-center gap-2 border-b px-6 py-3", children: [
3547
3383
  acceptAnyFile ? /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_lucide_react4.FileIcon, { className: "text-muted-foreground size-4" }) : /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_lucide_react4.ImageIcon, { className: "text-muted-foreground size-4" }),
3548
- /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("h3", { className: "text-sm font-medium", children: imageUrl ? `Edit ${Noun}` : `Add ${Noun}` })
3384
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("h3", { className: "text-sm font-medium", children: hasStoredMedia ? `Edit ${Noun}` : `Add ${Noun}` })
3549
3385
  ] }),
3550
3386
  /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
3551
3387
  "input",
@@ -3575,8 +3411,8 @@ var ImageEditor = ({
3575
3411
  className: "bg-muted/20 hover:bg-muted/30 data-[dragging=true]:bg-accent/50 data-[dragging=true]:border-primary/40\n relative flex cursor-pointer flex-col items-center justify-center overflow-hidden rounded-lg\n border border-dashed border-border/60 transition-colors",
3576
3412
  style: { height: "13rem" },
3577
3413
  onClick: isBusy ? void 0 : openFileDialog,
3578
- children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_react16.AnimatePresence, { mode: "wait", initial: false, children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
3579
- import_react16.motion.div,
3414
+ children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_react15.AnimatePresence, { mode: "wait", initial: false, children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
3415
+ import_react15.motion.div,
3580
3416
  {
3581
3417
  initial: { opacity: 0 },
3582
3418
  animate: { opacity: 1 },
@@ -3593,7 +3429,7 @@ var ImageEditor = ({
3593
3429
  /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_lucide_react4.AlertCircleIcon, { className: "size-3 shrink-0" }),
3594
3430
  /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("span", { children: dragErrors[0] })
3595
3431
  ] }),
3596
- !isBusy && (selectedFile || imageMetadata && hasImage) && /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("div", { className: "text-muted-foreground mt-2 text-center text-xs", children: selectedFile ? /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(import_jsx_runtime11.Fragment, { children: [
3432
+ !isBusy && (selectedFile ? selectedIsImage : imageMetadata && hasImage) && /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("div", { className: "text-muted-foreground mt-2 text-center text-xs", children: selectedFile ? /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(import_jsx_runtime11.Fragment, { children: [
3597
3433
  /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("span", { className: "font-medium", children: selectedFile.name }),
3598
3434
  " \u2022 ",
3599
3435
  /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("span", { children: formatFileSize(selectedFile.size) }),
@@ -3613,7 +3449,7 @@ var ImageEditor = ({
3613
3449
  ] }) }),
3614
3450
  /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { className: "flex shrink-0 justify-end gap-2 border-t px-6 py-3", children: [
3615
3451
  /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_button5.Button, { type: "button", variant: "outline", size: "sm", onClick: handleCancel, disabled: isBusy, children: "Cancel" }),
3616
- selectedFile && !isBusy ? /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_button5.Button, { type: "button", size: "sm", onClick: handleConfirmUpload, children: isDraftRow ? "Create Row & Upload" : "Upload & Save" }) : /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(import_button5.Button, { type: "button", size: "sm", onClick: handleSave, disabled: isBusy, children: [
3452
+ selectedFile && !isBusy ? /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_button5.Button, { type: "button", size: "sm", onClick: handleConfirmUpload, children: needsDraftCreation ? "Create Row & Upload" : "Upload & Save" }) : /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(import_button5.Button, { type: "button", size: "sm", onClick: handleSave, disabled: isBusy, children: [
3617
3453
  isBusy && /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_lucide_react4.Loader2, { className: "size-3.5 animate-spin" }),
3618
3454
  saveLabel
3619
3455
  ] })
@@ -3631,21 +3467,19 @@ function ImageEditorDom({
3631
3467
  cell,
3632
3468
  colKey,
3633
3469
  rowId,
3470
+ rowIdentifier,
3634
3471
  tableName,
3635
3472
  onCommitPatch,
3636
3473
  onCancel,
3637
3474
  onSubmitDraftRow,
3638
3475
  onInvalidateData
3639
3476
  }) {
3640
- const isDraftRow = rowId.startsWith(DRAFT_PREFIX);
3477
+ const isDraftRow = rowIdentifier == null && rowId.startsWith(DRAFT_PREFIX);
3641
3478
  const cellType = cell.meta?.cellType;
3642
3479
  const acceptAnyFile = cellType != null && cellType !== "image";
3643
3480
  const handleSaveComplete = onCommitPatch ? (saveData) => onCommitPatch({ [colKey]: saveData.imageData }) : void 0;
3644
- const handleSubmitDraft = isDraftRow && onSubmitDraftRow ? async () => {
3645
- const createdRow = await onSubmitDraftRow(rowId);
3646
- return { createdRow };
3647
- } : void 0;
3648
- return /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("div", { "data-slot": "image-editor", children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(import_react17.Suspense, { fallback: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("div", { className: "h-64 w-full min-w-[480px] animate-pulse rounded-lg bg-muted" }), children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
3481
+ const handleSubmitDraft = isDraftRow && onSubmitDraftRow ? () => onSubmitDraftRow(rowId) : void 0;
3482
+ return /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("div", { "data-slot": "image-editor", children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(import_react16.Suspense, { fallback: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)("div", { className: "h-64 w-full min-w-[480px] animate-pulse rounded-lg bg-muted" }), children: /* @__PURE__ */ (0, import_jsx_runtime12.jsx)(
3649
3483
  ImageEditor,
3650
3484
  {
3651
3485
  value,
@@ -3653,7 +3487,7 @@ function ImageEditorDom({
3653
3487
  onFinishedEditing: () => onCancel(),
3654
3488
  tableName,
3655
3489
  fieldName: colKey,
3656
- recordId: rowId,
3490
+ recordId: rowIdentifier ?? null,
3657
3491
  onSaveComplete: handleSaveComplete,
3658
3492
  isDraftRow,
3659
3493
  onSubmitDraft: handleSubmitDraft,
@@ -3663,7 +3497,7 @@ function ImageEditorDom({
3663
3497
  }
3664
3498
 
3665
3499
  // src/grid/editors/inet-editor.tsx
3666
- var import_react18 = require("react");
3500
+ var import_react17 = require("react");
3667
3501
  var import_button6 = require("@constructive-io/ui/button");
3668
3502
  init_editor_focus_trap();
3669
3503
  init_overlay_presets();
@@ -3713,26 +3547,26 @@ function getInetType(value) {
3713
3547
  }
3714
3548
  var InetEditor = ({ value, onFinishedEditing }) => {
3715
3549
  const currentInetData = typeof value === "string" ? value : "";
3716
- const [editingValue, setEditingValue] = (0, import_react18.useState)(currentInetData);
3717
- const [validationError, setValidationError] = (0, import_react18.useState)("");
3718
- const keyContainerRef = (0, import_react18.useRef)(null);
3719
- const handleSave = (0, import_react18.useCallback)(() => {
3550
+ const [editingValue, setEditingValue] = (0, import_react17.useState)(currentInetData);
3551
+ const [validationError, setValidationError] = (0, import_react17.useState)("");
3552
+ const keyContainerRef = (0, import_react17.useRef)(null);
3553
+ const handleSave = (0, import_react17.useCallback)(() => {
3720
3554
  if (editingValue.trim() && !isValidInet(editingValue.trim())) {
3721
3555
  setValidationError("Invalid IP address or CIDR");
3722
3556
  return;
3723
3557
  }
3724
3558
  onFinishedEditing(editingValue.trim());
3725
3559
  }, [editingValue, onFinishedEditing]);
3726
- const handleCancel = (0, import_react18.useCallback)(() => {
3560
+ const handleCancel = (0, import_react17.useCallback)(() => {
3727
3561
  onFinishedEditing();
3728
3562
  }, [onFinishedEditing]);
3729
- const handleInputChange = (0, import_react18.useCallback)((e) => {
3563
+ const handleInputChange = (0, import_react17.useCallback)((e) => {
3730
3564
  setEditingValue(e.target.value);
3731
3565
  setValidationError("");
3732
3566
  }, []);
3733
- const actionsRef = (0, import_react18.useRef)({ handleSave, handleCancel });
3567
+ const actionsRef = (0, import_react17.useRef)({ handleSave, handleCancel });
3734
3568
  actionsRef.current = { handleSave, handleCancel };
3735
- (0, import_react18.useEffect)(() => {
3569
+ (0, import_react17.useEffect)(() => {
3736
3570
  const el = keyContainerRef.current;
3737
3571
  if (!el) return;
3738
3572
  const handler = (e) => {
@@ -3818,7 +3652,7 @@ function InetEditorDom({ value, onCommit, onCancel }) {
3818
3652
  }
3819
3653
 
3820
3654
  // src/grid/editors/interval-editor.tsx
3821
- var import_react19 = require("react");
3655
+ var import_react18 = require("react");
3822
3656
  var import_lucide_react5 = require("lucide-react");
3823
3657
  var import_button7 = require("@constructive-io/ui/button");
3824
3658
  var import_input = require("@constructive-io/ui/input");
@@ -3868,14 +3702,14 @@ function formatIntervalValue(interval) {
3868
3702
  }
3869
3703
  var IntervalEditor = ({ value, onFinishedEditing }) => {
3870
3704
  const currentIntervalData = typeof value === "string" ? value : "";
3871
- const [editingValue, setEditingValue] = (0, import_react19.useState)(() => parseIntervalValue(currentIntervalData));
3872
- const handleSave = (0, import_react19.useCallback)(() => {
3705
+ const [editingValue, setEditingValue] = (0, import_react18.useState)(() => parseIntervalValue(currentIntervalData));
3706
+ const handleSave = (0, import_react18.useCallback)(() => {
3873
3707
  onFinishedEditing(JSON.stringify(editingValue));
3874
3708
  }, [editingValue, onFinishedEditing]);
3875
- const handleCancel = (0, import_react19.useCallback)(() => {
3709
+ const handleCancel = (0, import_react18.useCallback)(() => {
3876
3710
  onFinishedEditing();
3877
3711
  }, [onFinishedEditing]);
3878
- const handleInputChange = (0, import_react19.useCallback)((field, newValue) => {
3712
+ const handleInputChange = (0, import_react18.useCallback)((field, newValue) => {
3879
3713
  const numValue = parseInt(newValue) || 0;
3880
3714
  setEditingValue((prev) => ({
3881
3715
  ...prev,
@@ -3883,7 +3717,7 @@ var IntervalEditor = ({ value, onFinishedEditing }) => {
3883
3717
  // Ensure non-negative values
3884
3718
  }));
3885
3719
  }, []);
3886
- const handleEditorKeyDown = (0, import_react19.useCallback)(
3720
+ const handleEditorKeyDown = (0, import_react18.useCallback)(
3887
3721
  (e) => {
3888
3722
  if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
3889
3723
  e.preventDefault();
@@ -3993,7 +3827,7 @@ function IntervalEditorDom({ value, onCommit, onCancel }) {
3993
3827
  }
3994
3828
 
3995
3829
  // src/grid/editors/json-editor.tsx
3996
- var import_react20 = require("react");
3830
+ var import_react19 = require("react");
3997
3831
  var import_button8 = require("@constructive-io/ui/button");
3998
3832
  init_editor_focus_trap();
3999
3833
  init_overlay_presets();
@@ -4027,18 +3861,18 @@ function highlightJson(json) {
4027
3861
  );
4028
3862
  }
4029
3863
  function JsonEditor({ value, onChange, onFinished }) {
4030
- const [text, setText] = (0, import_react20.useState)(() => typeof value === "string" ? value : JSON.stringify(value, null, 2));
4031
- const textareaRef = (0, import_react20.useRef)(null);
4032
- const preRef = (0, import_react20.useRef)(null);
4033
- const keyContainerRef = (0, import_react20.useRef)(null);
4034
- const { parsed, valid } = (0, import_react20.useMemo)(() => {
3864
+ const [text, setText] = (0, import_react19.useState)(() => typeof value === "string" ? value : JSON.stringify(value, null, 2));
3865
+ const textareaRef = (0, import_react19.useRef)(null);
3866
+ const preRef = (0, import_react19.useRef)(null);
3867
+ const keyContainerRef = (0, import_react19.useRef)(null);
3868
+ const { parsed, valid } = (0, import_react19.useMemo)(() => {
4035
3869
  try {
4036
3870
  return { parsed: JSON.parse(text), valid: true };
4037
3871
  } catch {
4038
3872
  return { parsed: text, valid: false };
4039
3873
  }
4040
3874
  }, [text]);
4041
- const handleChange = (0, import_react20.useCallback)(
3875
+ const handleChange = (0, import_react19.useCallback)(
4042
3876
  (e) => {
4043
3877
  const next = e.target.value;
4044
3878
  setText(next);
@@ -4049,11 +3883,11 @@ function JsonEditor({ value, onChange, onFinished }) {
4049
3883
  },
4050
3884
  [onChange]
4051
3885
  );
4052
- const handleCancel = (0, import_react20.useCallback)(() => onFinished(void 0), [onFinished]);
4053
- const handleSave = (0, import_react20.useCallback)(() => {
3886
+ const handleCancel = (0, import_react19.useCallback)(() => onFinished(void 0), [onFinished]);
3887
+ const handleSave = (0, import_react19.useCallback)(() => {
4054
3888
  if (valid) onFinished(parsed);
4055
3889
  }, [onFinished, parsed, valid]);
4056
- const handleScroll = (0, import_react20.useCallback)(() => {
3890
+ const handleScroll = (0, import_react19.useCallback)(() => {
4057
3891
  const ta = textareaRef.current;
4058
3892
  const pre = preRef.current;
4059
3893
  if (ta && pre) {
@@ -4061,9 +3895,9 @@ function JsonEditor({ value, onChange, onFinished }) {
4061
3895
  pre.scrollLeft = ta.scrollLeft;
4062
3896
  }
4063
3897
  }, []);
4064
- const actionsRef = (0, import_react20.useRef)({ handleSave, handleCancel });
3898
+ const actionsRef = (0, import_react19.useRef)({ handleSave, handleCancel });
4065
3899
  actionsRef.current = { handleSave, handleCancel };
4066
- (0, import_react20.useEffect)(() => {
3900
+ (0, import_react19.useEffect)(() => {
4067
3901
  const el = keyContainerRef.current;
4068
3902
  if (!el) return;
4069
3903
  const handler = (e) => {
@@ -4098,7 +3932,7 @@ function JsonEditor({ value, onChange, onFinished }) {
4098
3932
  el.addEventListener("keydown", handler);
4099
3933
  return () => el.removeEventListener("keydown", handler);
4100
3934
  }, []);
4101
- const highlighted = (0, import_react20.useMemo)(() => highlightJson(text), [text]);
3935
+ const highlighted = (0, import_react19.useMemo)(() => highlightJson(text), [text]);
4102
3936
  const isMac = typeof navigator !== "undefined" && MAC_UA_RE4.test(navigator.userAgent);
4103
3937
  const modKey = isMac ? "\u2318" : "Ctrl";
4104
3938
  return /* @__PURE__ */ (0, import_jsx_runtime17.jsx)(EditorFocusTrap, { onEscape: handleCancel, className: `bg-popover ${OVERLAY.lg} rounded-lg border p-2.5 shadow-lg`, children: /* @__PURE__ */ (0, import_jsx_runtime17.jsxs)("div", { ref: keyContainerRef, children: [
@@ -4169,7 +4003,7 @@ function JsonEditorDom({ value, onCommit, onCancel }) {
4169
4003
  }
4170
4004
 
4171
4005
  // src/grid-dom/editors/number-editor.tsx
4172
- var import_react21 = require("react");
4006
+ var import_react20 = require("react");
4173
4007
  var import_button9 = require("@constructive-io/ui/button");
4174
4008
  init_overlay_presets();
4175
4009
  init_cn();
@@ -4185,8 +4019,8 @@ function parseValue(text) {
4185
4019
  return Number(trimmed);
4186
4020
  }
4187
4021
  function NumberEditorDom({ value, initialText, colKey, fieldMeta, onCommit, onCancel }) {
4188
- const [text, setText] = (0, import_react21.useState)(() => initialText != null ? initialText : seedText(value));
4189
- const escapedRef = (0, import_react21.useRef)(false);
4022
+ const [text, setText] = (0, import_react20.useState)(() => initialText != null ? initialText : seedText(value));
4023
+ const escapedRef = (0, import_react20.useRef)(false);
4190
4024
  const parsed = parseValue(text);
4191
4025
  const canSave = parsed === null || Number.isFinite(parsed);
4192
4026
  function commit() {
@@ -4242,33 +4076,33 @@ NumberEditorDom.commitsOnBlur = true;
4242
4076
  // src/grid/editors/relation-editor.tsx
4243
4077
  var import_react25 = require("react");
4244
4078
  var import_lucide_react6 = require("lucide-react");
4245
- var import_react_query5 = require("@tanstack/react-query");
4079
+ var import_react_query6 = require("@tanstack/react-query");
4246
4080
 
4247
4081
  // src/hooks/use-sheets-table-cursor.ts
4248
- var import_react22 = require("react");
4249
- var import_react_query4 = require("@tanstack/react-query");
4250
- var import_data13 = require("@constructive-io/data");
4251
- var import_data14 = require("@constructive-io/data");
4252
- var import_data15 = require("@constructive-io/data");
4082
+ var import_react21 = require("react");
4083
+ var import_react_query5 = require("@tanstack/react-query");
4084
+ var import_data10 = require("@constructive-io/data");
4085
+ var import_data11 = require("@constructive-io/data");
4086
+ var import_data12 = require("@constructive-io/data");
4253
4087
  function useSheetsTableCursor(tableName, options = {}) {
4254
- const queryClient = (0, import_react_query4.useQueryClient)();
4088
+ const queryClient = (0, import_react_query5.useQueryClient)();
4255
4089
  const { execute, scopeKey } = useSheetsContext();
4256
4090
  const { data: meta } = useSheetsMeta();
4257
4091
  const adapter = useSheetsAdapter();
4258
- const tables = (0, import_react22.useMemo)(() => {
4092
+ const tables = (0, import_react21.useMemo)(() => {
4259
4093
  if (!meta?._meta?.tables) return [];
4260
- return meta._meta.tables.filter((candidate) => candidate != null).map((metaTable) => (0, import_data13.cleanTable)(metaTable));
4094
+ return meta._meta.tables.filter((candidate) => candidate != null).map((metaTable) => (0, import_data10.cleanTable)(metaTable));
4261
4095
  }, [meta]);
4262
- const table = (0, import_react22.useMemo)(
4096
+ const table = (0, import_react21.useMemo)(
4263
4097
  () => tables.find((candidate) => candidate.name === tableName) ?? null,
4264
4098
  [tables, tableName]
4265
4099
  );
4266
4100
  const { enabled = true, select: fieldSelection, pageSize = 20, where, orderBy } = options;
4267
- const stableOptions = (0, import_react22.useMemo)(
4101
+ const stableOptions = (0, import_react21.useMemo)(
4268
4102
  () => ({ fieldSelection, where, orderBy }),
4269
4103
  [fieldSelection, where, orderBy]
4270
4104
  );
4271
- const queryOptions = (0, import_react22.useMemo)(
4105
+ const queryOptions = (0, import_react21.useMemo)(
4272
4106
  () => ({
4273
4107
  fieldSelection,
4274
4108
  where,
@@ -4285,11 +4119,11 @@ function useSheetsTableCursor(tableName, options = {}) {
4285
4119
  hasNextPage,
4286
4120
  fetchNextPage,
4287
4121
  error
4288
- } = (0, import_react_query4.useInfiniteQuery)({
4122
+ } = (0, import_react_query5.useInfiniteQuery)({
4289
4123
  queryKey: sheetsQueryKeys.cursorTable(scopeKey, tableName, stableOptions),
4290
4124
  queryFn: async ({ pageParam }) => {
4291
4125
  if (!table) {
4292
- throw import_data14.createError.notFound(`Table '${tableName}' not found`);
4126
+ throw import_data11.createError.notFound(`Table '${tableName}' not found`);
4293
4127
  }
4294
4128
  const cursor = pageParam;
4295
4129
  const variableOptions = {
@@ -4312,7 +4146,7 @@ function useSheetsTableCursor(tableName, options = {}) {
4312
4146
  const validatedOrderByEnum = new Set(variables.orderBy ?? []);
4313
4147
  const availableOrderByFields = new Set(table.fields.map((field) => field.name));
4314
4148
  const validatedOrderBy = orderBy?.filter(
4315
- ({ field, direction }) => availableOrderByFields.has(field) && validatedOrderByEnum.has((0, import_data15.toOrderByEnumValue)(field, direction))
4149
+ ({ field, direction }) => availableOrderByFields.has(field) && validatedOrderByEnum.has((0, import_data12.toOrderByEnumValue)(field, direction))
4316
4150
  );
4317
4151
  const res = await adapter.listRows(
4318
4152
  { table, allTables: tables, tableName },
@@ -4342,11 +4176,11 @@ function useSheetsTableCursor(tableName, options = {}) {
4342
4176
  enabled: enabled && !!table,
4343
4177
  staleTime: 5 * 60 * 1e3
4344
4178
  });
4345
- const flatData = (0, import_react22.useMemo)(
4179
+ const flatData = (0, import_react21.useMemo)(
4346
4180
  () => data?.pages.flatMap((page) => page.rows) ?? [],
4347
4181
  [data]
4348
4182
  );
4349
- const totalCount = (0, import_react22.useMemo)(
4183
+ const totalCount = (0, import_react21.useMemo)(
4350
4184
  () => data?.pages[data.pages.length - 1]?.totalCount ?? 0,
4351
4185
  [data]
4352
4186
  );
@@ -4361,6 +4195,18 @@ function useSheetsTableCursor(tableName, options = {}) {
4361
4195
  };
4362
4196
  }
4363
4197
 
4198
+ // src/store/sheets-store.ts
4199
+ var import_react22 = require("react");
4200
+ var import_zustand = require("zustand");
4201
+ var SheetsStoreContext = (0, import_react22.createContext)(null);
4202
+ function useSheetsStore(selector) {
4203
+ const store = (0, import_react22.useContext)(SheetsStoreContext);
4204
+ if (!store) {
4205
+ throw new Error("useSheetsStore must be used within a <SheetsProvider>");
4206
+ }
4207
+ return (0, import_zustand.useStore)(store, selector);
4208
+ }
4209
+
4364
4210
  // src/grid/editors/relation-editor.tsx
4365
4211
  init_cn();
4366
4212
  var import_badge2 = require("@constructive-io/ui/badge");
@@ -4499,7 +4345,7 @@ var RelationEditor = ({
4499
4345
  }) => {
4500
4346
  const { data: meta } = useSheetsMeta();
4501
4347
  const { scopeKey } = useSheetsContext();
4502
- const queryClient = (0, import_react_query5.useQueryClient)();
4348
+ const queryClient = (0, import_react_query6.useQueryClient)();
4503
4349
  const ensureRelationInfo = useSheetsStore((s) => s.ensureRelationInfo);
4504
4350
  const relationInfoForTable = useSheetsStore((s) => tableName ? s.relationInfoCache[tableName] : void 0);
4505
4351
  const relationEntry = relationInfoForTable?.[fieldName];
@@ -5265,6 +5111,7 @@ var DOM_EDITOR_REGISTRY = {
5265
5111
  video: ImageEditorDom,
5266
5112
  audio: ImageEditorDom,
5267
5113
  upload: ImageEditorDom,
5114
+ attachment: ImageEditorDom,
5268
5115
  // Date/time types
5269
5116
  date: DateEditorDom,
5270
5117
  datetime: DateEditorDom,
@@ -5427,21 +5274,12 @@ var geometrySheetsCellFactory = { canHandle: canHandle3, create: create3 };
5427
5274
 
5428
5275
  // src/cell-model/factories/image.ts
5429
5276
  init_cell_type_groups();
5430
- function resolveMediaUrl(value) {
5431
- if (typeof value === "string") return value;
5432
- if (typeof value === "object" && value) {
5433
- const obj = value;
5434
- return obj.url || obj.src || obj.href || obj.path || "";
5435
- }
5436
- return "";
5437
- }
5438
5277
  var imageSheetsCellFactory = {
5439
5278
  canHandle(cellType) {
5440
- return MEDIA_TYPES.has(cellType);
5279
+ return cellType !== "attachment" && MEDIA_TYPES.has(cellType);
5441
5280
  },
5442
5281
  create(value, metadata) {
5443
- const url = value === null || value === void 0 || value === "" ? "" : resolveMediaUrl(value);
5444
- const data = [url];
5282
+ const data = [getImageUrl(value) ?? ""];
5445
5283
  return {
5446
5284
  kind: "image",
5447
5285
  data,