@constructive-io/sheets 0.4.1 → 0.6.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 (50) hide show
  1. package/README.md +19 -24
  2. package/dist/advanced.cjs +250 -405
  3. package/dist/advanced.cjs.map +1 -1
  4. package/dist/advanced.d.cts +9 -10
  5. package/dist/advanced.d.ts +9 -10
  6. package/dist/advanced.js +3 -3
  7. package/dist/auth.cjs +10 -10
  8. package/dist/auth.cjs.map +1 -1
  9. package/dist/auth.d.cts +5 -4
  10. package/dist/auth.d.ts +5 -4
  11. package/dist/auth.js +3 -3
  12. package/dist/{chunk-GLVZSPV2.js → chunk-4EZ6A23C.js} +4 -3
  13. package/dist/chunk-4EZ6A23C.js.map +1 -0
  14. package/dist/{chunk-3BNOZQIJ.js → chunk-KKAWMVEG.js} +11 -11
  15. package/dist/chunk-KKAWMVEG.js.map +1 -0
  16. package/dist/{chunk-FG2LRZP5.js → chunk-KOZAW264.js} +4 -3
  17. package/dist/chunk-KOZAW264.js.map +1 -0
  18. package/dist/{chunk-BWJVRYJT.js → chunk-KVPVEXWB.js} +40 -17
  19. package/dist/chunk-KVPVEXWB.js.map +1 -0
  20. package/dist/{chunk-BWKB52JB.js → chunk-LR64FLWO.js} +231 -379
  21. package/dist/chunk-LR64FLWO.js.map +1 -0
  22. package/dist/{chunk-SDKHWE7G.js → chunk-ZETPUEXH.js} +27 -2
  23. package/dist/chunk-ZETPUEXH.js.map +1 -0
  24. package/dist/{date-editor-CXKKGNL6.js → date-editor-QT47WY5T.js} +5 -3
  25. package/dist/date-editor-QT47WY5T.js.map +1 -0
  26. package/dist/{editor-props-M6Dh0P9f.d.ts → grid-cell-types-C3ARj148.d.cts} +70 -62
  27. package/dist/{editor-props-M6Dh0P9f.d.cts → grid-cell-types-C3ARj148.d.ts} +70 -62
  28. package/dist/index.cjs +564 -493
  29. package/dist/index.cjs.map +1 -1
  30. package/dist/index.d.cts +86 -35
  31. package/dist/index.d.ts +86 -35
  32. package/dist/index.js +264 -72
  33. package/dist/index.js.map +1 -1
  34. package/dist/{sheets-context-9u9r7Bs0.d.ts → sheets-context-B03WDhZ9.d.cts} +13 -6
  35. package/dist/{sheets-context-BjGIHocT.d.cts → sheets-context-DmVCOgiX.d.ts} +13 -6
  36. package/dist/styles.css +6 -0
  37. package/dist/testing.cjs +99 -33
  38. package/dist/testing.cjs.map +1 -1
  39. package/dist/testing.d.cts +11 -7
  40. package/dist/testing.d.ts +11 -7
  41. package/dist/testing.js +34 -8
  42. package/dist/testing.js.map +1 -1
  43. package/package.json +15 -16
  44. package/dist/chunk-3BNOZQIJ.js.map +0 -1
  45. package/dist/chunk-BWJVRYJT.js.map +0 -1
  46. package/dist/chunk-BWKB52JB.js.map +0 -1
  47. package/dist/chunk-FG2LRZP5.js.map +0 -1
  48. package/dist/chunk-GLVZSPV2.js.map +0 -1
  49. package/dist/chunk-SDKHWE7G.js.map +0 -1
  50. package/dist/date-editor-CXKKGNL6.js.map +0 -1
package/dist/index.cjs CHANGED
@@ -437,8 +437,10 @@ var init_date_editor = __esm({
437
437
  const isDateTimeType = dateType === "datetime" || dateType === "timestamptz";
438
438
  const handleDateSelect = (0, import_react44.useCallback)(
439
439
  (dateValue2) => {
440
- setSelectedDate(dateValue2);
441
- const jsDate = dateValueToDate(dateValue2);
440
+ if (Array.isArray(dateValue2)) return;
441
+ const selectedValue = dateValue2;
442
+ setSelectedDate(selectedValue);
443
+ const jsDate = dateValueToDate(selectedValue);
442
444
  if (jsDate) {
443
445
  if (isDateTimeType && currentDateValue) {
444
446
  const currentDate = new Date(currentDateValue);
@@ -932,6 +934,7 @@ __export(src_exports, {
932
934
  buildRelationInfoFromMeta: () => buildRelationInfoFromMeta,
933
935
  buildScalarFormSpec: () => buildScalarFormSpec,
934
936
  buildZodSchema: () => buildZodSchema,
937
+ canRunSheetsMutation: () => canRunSheetsMutation,
935
938
  clearSheetsSelection: () => clear,
936
939
  computeDraftMetaSignature: () => computeDraftMetaSignature,
937
940
  countConditions: () => countConditions,
@@ -951,6 +954,7 @@ __export(src_exports, {
951
954
  findTableFormSpec: () => findTableFormSpec,
952
955
  getCellsInRange: () => getCellsInRange,
953
956
  getDraftMeta: () => getDraftMeta,
957
+ getSheetsWriteCapability: () => getSheetsWriteCapability,
954
958
  isArrayCellType: () => isArrayCellType,
955
959
  isDraftRow: () => isDraftRow,
956
960
  isImageField: () => isImageField,
@@ -962,10 +966,15 @@ __export(src_exports, {
962
966
  queryKeys: () => sheetsTableQueryKeys,
963
967
  resolveCellType: () => resolveCellType,
964
968
  resolveDownloadUrl: () => resolveDownloadUrl,
969
+ resolveSheetsIdentifier: () => resolveSheetsIdentifier,
970
+ resolveSheetsRowIdentity: () => resolveSheetsRowIdentity,
965
971
  selectCell: () => selectCell,
966
972
  selectRange: () => selectRange,
967
973
  selectRow: () => selectRow,
974
+ sheetsIdentifierCacheKey: () => sheetsIdentifierCacheKey,
975
+ sheetsIdentifierToWhere: () => sheetsIdentifierToWhere,
968
976
  sheetsQueryKeys: () => sheetsQueryKeys,
977
+ sheetsRowKey: () => sheetsRowKey,
969
978
  toTSV: () => toTSV,
970
979
  toggleRow: () => toggleRow,
971
980
  tokensFromCssVars: () => tokensFromCssVars,
@@ -998,6 +1007,7 @@ module.exports = __toCommonJS(src_exports);
998
1007
  // src/context/sheets-provider.tsx
999
1008
  var import_react3 = require("react");
1000
1009
  var import_react_query = require("@tanstack/react-query");
1010
+ var import_zustand2 = require("zustand");
1001
1011
 
1002
1012
  // src/context/sheets-context.ts
1003
1013
  var import_react = require("react");
@@ -2097,8 +2107,9 @@ function createSheetsStore() {
2097
2107
  isAuthenticated: false,
2098
2108
  accessToken: null,
2099
2109
  expiresAt: null,
2100
- setAuthenticated: (token, expiresAt) => set({ isAuthenticated: true, accessToken: token, expiresAt }),
2101
- setUnauthenticated: () => set({ isAuthenticated: false, accessToken: null, expiresAt: null })
2110
+ identityKey: null,
2111
+ setAuthenticated: (token, expiresAt, identityKey = null) => set({ isAuthenticated: true, accessToken: token, expiresAt, identityKey }),
2112
+ setUnauthenticated: () => set({ isAuthenticated: false, accessToken: null, expiresAt: null, identityKey: null })
2102
2113
  }));
2103
2114
  }
2104
2115
  var SheetsStoreContext = (0, import_react2.createContext)(null);
@@ -2138,16 +2149,17 @@ function getStoredToken(databaseId) {
2138
2149
  if (!raw) return null;
2139
2150
  const parsed = JSON.parse(raw);
2140
2151
  if (!parsed.accessToken || !parsed.expiresAt) return null;
2152
+ if (parsed.identityKey != null && typeof parsed.identityKey !== "string") return null;
2141
2153
  return parsed;
2142
2154
  } catch {
2143
2155
  return null;
2144
2156
  }
2145
2157
  }
2146
- function setStoredToken(databaseId, accessToken, expiresAt) {
2158
+ function setStoredToken(databaseId, accessToken, expiresAt, identityKey) {
2147
2159
  const storage = getStorage();
2148
2160
  if (!storage) return;
2149
2161
  try {
2150
- const data = { accessToken, expiresAt };
2162
+ const data = { accessToken, expiresAt, identityKey };
2151
2163
  storage.setItem(storageKey(databaseId), JSON.stringify(data));
2152
2164
  } catch {
2153
2165
  }
@@ -2156,12 +2168,41 @@ function setStoredToken(databaseId, accessToken, expiresAt) {
2156
2168
  // src/context/sheets-provider.tsx
2157
2169
  init_sheets_logger();
2158
2170
  init_sheets_i18n();
2171
+
2172
+ // src/hooks/query-keys.ts
2173
+ function isSheetsScopeKey(value) {
2174
+ if (!value || typeof value !== "object") return false;
2175
+ const candidate = value;
2176
+ return "databaseId" in candidate && "endpoint" in candidate && "identityKey" in candidate;
2177
+ }
2178
+ var sheetsQueryKeys = {
2179
+ root: ["sheets"],
2180
+ scope: (scope) => ["sheets", scope],
2181
+ meta: (scope) => [...sheetsQueryKeys.scope(scope), "meta"],
2182
+ typeFields: (scope, typeName) => [...sheetsQueryKeys.scope(scope), "type-fields", typeName],
2183
+ enumValues: (scope, typeName) => [...sheetsQueryKeys.scope(scope), "enum-values", typeName],
2184
+ relations: (scope, tableName) => [...sheetsQueryKeys.scope(scope), "relations", tableName],
2185
+ table: (scope, tableName) => [...sheetsQueryKeys.scope(scope), "table", tableName],
2186
+ tableRows: (scope, tableName, options) => [...sheetsQueryKeys.table(scope, tableName), "rows", options],
2187
+ tableRow: (scope, tableName, id) => [...sheetsQueryKeys.table(scope, tableName), "row", id],
2188
+ tableCount: (scope, tableName, where) => [...sheetsQueryKeys.table(scope, tableName), "count", where],
2189
+ infiniteTable: (scope, tableName) => [...sheetsQueryKeys.scope(scope), "infinite-table", tableName],
2190
+ infiniteTablePage: (scope, tableName, pageIndex, options) => [...sheetsQueryKeys.infiniteTable(scope, tableName), "page", pageIndex, options],
2191
+ infiniteTableTotalCount: (scope, tableName, where) => [...sheetsQueryKeys.infiniteTable(scope, tableName), "totalCount", where],
2192
+ cursorTable: (scope, tableName, options) => [...sheetsQueryKeys.scope(scope), "cursor-table", tableName, options]
2193
+ };
2194
+
2195
+ // src/context/sheets-provider.tsx
2159
2196
  var import_jsx_runtime = require("react/jsx-runtime");
2160
2197
  function SheetsProvider({ config, children }) {
2198
+ const providerInstanceId = (0, import_react3.useId)();
2161
2199
  const storeRef = (0, import_react3.useRef)(null);
2162
2200
  if (!storeRef.current) {
2163
2201
  storeRef.current = createSheetsStore();
2164
2202
  }
2203
+ const store = storeRef.current;
2204
+ const standaloneIdentityKey = (0, import_zustand2.useStore)(store, (state) => state.identityKey);
2205
+ const standaloneAccessToken = (0, import_zustand2.useStore)(store, (state) => state.accessToken);
2165
2206
  setSheetsLogger(config.logger);
2166
2207
  setSheetsLocale(config.locale);
2167
2208
  (0, import_react3.useEffect)(() => {
@@ -2169,24 +2210,24 @@ function SheetsProvider({ config, children }) {
2169
2210
  setSheetsLocale(config.locale);
2170
2211
  }, [config.logger, config.locale]);
2171
2212
  (0, import_react3.useEffect)(() => {
2172
- const store = storeRef.current?.getState();
2173
- if (!store) return;
2213
+ const store2 = storeRef.current?.getState();
2214
+ if (!store2) return;
2174
2215
  if (config.auth.mode !== "standalone") {
2175
- store.setUnauthenticated();
2216
+ store2.setUnauthenticated();
2176
2217
  return;
2177
2218
  }
2178
2219
  const databaseId = config.databaseId || "default";
2179
2220
  const stored = getStoredToken(databaseId);
2180
2221
  if (!stored) {
2181
- store.setUnauthenticated();
2222
+ store2.setUnauthenticated();
2182
2223
  return;
2183
2224
  }
2184
2225
  const expiresAt = new Date(stored.expiresAt);
2185
2226
  if (expiresAt > /* @__PURE__ */ new Date()) {
2186
- store.setAuthenticated(stored.accessToken, stored.expiresAt);
2227
+ store2.setAuthenticated(stored.accessToken, stored.expiresAt, stored.identityKey ?? null);
2187
2228
  return;
2188
2229
  }
2189
- store.setUnauthenticated();
2230
+ store2.setUnauthenticated();
2190
2231
  }, [config.auth.mode, config.databaseId]);
2191
2232
  const internalQueryClient = (0, import_react3.useMemo)(
2192
2233
  () => new import_react_query.QueryClient({
@@ -2205,8 +2246,8 @@ function SheetsProvider({ config, children }) {
2205
2246
  if (config.auth.mode === "embedded") {
2206
2247
  return config.auth.getToken;
2207
2248
  }
2208
- return () => storeRef.current?.getState().accessToken ?? null;
2209
- }, [config.auth]);
2249
+ return () => store.getState().accessToken ?? null;
2250
+ }, [config.auth, store]);
2210
2251
  const execute = (0, import_react3.useMemo)(() => {
2211
2252
  if (config.execute) return config.execute;
2212
2253
  return createSheetsExecute(config, getToken);
@@ -2215,18 +2256,35 @@ function SheetsProvider({ config, children }) {
2215
2256
  if (config.executeUpload) return config.executeUpload;
2216
2257
  return createSheetsUpload(config, getToken);
2217
2258
  }, [config, getToken]);
2259
+ const configuredIdentityKey = config.auth.mode === "embedded" ? config.auth.getIdentityKey?.() ?? null : standaloneIdentityKey;
2260
+ const activeToken = config.auth.mode === "embedded" ? config.auth.getToken() : standaloneAccessToken;
2261
+ const authGenerationRef = (0, import_react3.useRef)({ mode: config.auth.mode, token: activeToken, generation: 0 });
2262
+ if (authGenerationRef.current.mode !== config.auth.mode || authGenerationRef.current.token !== activeToken) {
2263
+ authGenerationRef.current = {
2264
+ mode: config.auth.mode,
2265
+ token: activeToken,
2266
+ generation: authGenerationRef.current.generation + 1
2267
+ };
2268
+ }
2269
+ const identityKey = configuredIdentityKey ?? `anonymous:${providerInstanceId}:${authGenerationRef.current.generation}`;
2218
2270
  const scopeKey = (0, import_react3.useMemo)(
2219
2271
  () => ({
2220
2272
  databaseId: config.databaseId ?? null,
2221
- endpoint: config.endpoint
2273
+ endpoint: config.endpoint,
2274
+ identityKey
2222
2275
  }),
2223
- [config.databaseId, config.endpoint]
2276
+ [config.databaseId, config.endpoint, identityKey]
2224
2277
  );
2278
+ (0, import_react3.useEffect)(() => {
2279
+ return () => {
2280
+ void queryClient.cancelQueries({ queryKey: sheetsQueryKeys.scope(scopeKey) });
2281
+ };
2282
+ }, [queryClient, scopeKey]);
2225
2283
  const contextValue = (0, import_react3.useMemo)(
2226
2284
  () => ({ config, execute, executeUpload, scopeKey }),
2227
2285
  [config, execute, executeUpload, scopeKey]
2228
2286
  );
2229
- return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_query.QueryClientProvider, { client: queryClient, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SheetsStoreContext.Provider, { value: storeRef.current, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SheetsContext.Provider, { value: contextValue, children }) }) });
2287
+ return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_query.QueryClientProvider, { client: queryClient, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SheetsStoreContext.Provider, { value: store, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SheetsContext.Provider, { value: contextValue, children }) }) });
2230
2288
  }
2231
2289
 
2232
2290
  // src/grid/sheets.tsx
@@ -2631,7 +2689,9 @@ function SheetsControls(props) {
2631
2689
  gridSelection,
2632
2690
  deleteSelected,
2633
2691
  onAddRow,
2634
- onExport
2692
+ onExport,
2693
+ canDelete = true,
2694
+ readOnlyReason
2635
2695
  } = props;
2636
2696
  const filterableColumns = (0, import_react4.useMemo)(() => {
2637
2697
  if (Object.keys(fieldTypeMap).length === 0) return columnKeys;
@@ -2666,7 +2726,16 @@ function SheetsControls(props) {
2666
2726
  "data-part-id": "sheets-controls",
2667
2727
  className: "flex shrink-0 flex-wrap items-center justify-between gap-4 py-4",
2668
2728
  children: [
2669
- /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "flex items-center gap-2", children: [
2729
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "flex min-w-0 flex-wrap items-center gap-2", children: [
2730
+ readOnlyReason && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
2731
+ "span",
2732
+ {
2733
+ className: "border-border bg-muted text-muted-foreground inline-flex h-8 items-center rounded-md border px-2.5 text-xs",
2734
+ role: "status",
2735
+ title: readOnlyReason,
2736
+ children: "Read-only"
2737
+ }
2738
+ ),
2670
2739
  /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_button.Button, { variant: "outline", size: "sm", onClick: () => openSearch?.(), children: [
2671
2740
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_react5.RiSearch2Line, { className: "text-muted-foreground/60 -ms-1.5 size-5", "aria-hidden": "true" }),
2672
2741
  "Search"
@@ -2688,11 +2757,20 @@ function SheetsControls(props) {
2688
2757
  ] }),
2689
2758
  /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)("div", { className: "flex items-center gap-2", children: [
2690
2759
  showSelection && /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_alert_dialog.AlertDialog, { children: [
2691
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_alert_dialog.AlertDialogTrigger, { asChild: true, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_button.Button, { variant: "destructive-outline", size: "sm", disabled: selectedRowCount === 0, children: [
2692
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_react5.RiDeleteBin6Line, { className: "-ms-1.5 size-5", "aria-hidden": "true" }),
2693
- "Delete",
2694
- selectedRowCount > 0 ? ` (${selectedRowCount})` : ""
2695
- ] }) }),
2760
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_alert_dialog.AlertDialogTrigger, { asChild: true, children: /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
2761
+ import_button.Button,
2762
+ {
2763
+ variant: "destructive-outline",
2764
+ size: "sm",
2765
+ disabled: !canDelete || selectedRowCount === 0,
2766
+ title: !canDelete ? readOnlyReason ?? "Delete is unavailable for this table." : void 0,
2767
+ children: [
2768
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_react5.RiDeleteBin6Line, { className: "-ms-1.5 size-5", "aria-hidden": "true" }),
2769
+ "Delete",
2770
+ selectedRowCount > 0 ? ` (${selectedRowCount})` : ""
2771
+ ]
2772
+ }
2773
+ ) }),
2696
2774
  /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_alert_dialog.AlertDialogContent, { children: [
2697
2775
  /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_alert_dialog.AlertDialogHeader, { children: [
2698
2776
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(import_alert_dialog.AlertDialogTitle, { children: "Delete rows?" }),
@@ -2786,7 +2864,9 @@ function buildContextMenuItems({
2786
2864
  isEnabled,
2787
2865
  onAddRow,
2788
2866
  requestDelete,
2789
- selectedRowCount
2867
+ selectedRowCount,
2868
+ canAddRows = true,
2869
+ canDeleteRows = true
2790
2870
  }) {
2791
2871
  const cmd = (key2, commandId, label, icon, shortcut) => ({
2792
2872
  key: key2,
@@ -2806,6 +2886,7 @@ function buildContextMenuItems({
2806
2886
  key: "add-row",
2807
2887
  label: "Add row",
2808
2888
  icon: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_react7.RiAddLine, { className: "size-4", "aria-hidden": "true" }),
2889
+ disabled: !canAddRows,
2809
2890
  run: onAddRow
2810
2891
  },
2811
2892
  {
@@ -2813,7 +2894,7 @@ function buildContextMenuItems({
2813
2894
  label: selectedRowCount > 1 ? `Delete ${selectedRowCount} rows` : "Delete row",
2814
2895
  icon: /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_react7.RiDeleteBin6Line, { className: "size-4", "aria-hidden": "true" }),
2815
2896
  destructive: true,
2816
- disabled: selectedRowCount === 0,
2897
+ disabled: !canDeleteRows || selectedRowCount === 0,
2817
2898
  run: requestDelete
2818
2899
  }
2819
2900
  ];
@@ -2825,7 +2906,9 @@ function SheetsContextMenu({
2825
2906
  isEnabled,
2826
2907
  onAddRow,
2827
2908
  onDeleteRows,
2828
- selectedRowCount
2909
+ selectedRowCount,
2910
+ canAddRows = true,
2911
+ canDeleteRows = true
2829
2912
  }) {
2830
2913
  const [confirmDelete, setConfirmDelete] = (0, import_react6.useState)(false);
2831
2914
  const open = state !== null;
@@ -2834,7 +2917,9 @@ function SheetsContextMenu({
2834
2917
  isEnabled,
2835
2918
  onAddRow,
2836
2919
  requestDelete: () => setConfirmDelete(true),
2837
- selectedRowCount
2920
+ selectedRowCount,
2921
+ canAddRows,
2922
+ canDeleteRows
2838
2923
  });
2839
2924
  return /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(import_jsx_runtime3.Fragment, { children: [
2840
2925
  /* @__PURE__ */ (0, import_jsx_runtime3.jsxs)(import_dropdown_menu.DropdownMenu, { open, onOpenChange: (next) => !next && onClose(), children: [
@@ -3360,12 +3445,12 @@ function SheetsErrorState({ error, onRetry }) {
3360
3445
  onRetry && /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_button3.Button, { variant: "outline", size: "sm", onClick: onRetry, children: "Retry" })
3361
3446
  ] });
3362
3447
  }
3363
- function SheetsEmptyState({ tableName, onAddRow }) {
3448
+ function SheetsEmptyState({ tableName, onAddRow, readOnlyReason }) {
3364
3449
  return /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(SheetsStateShell, { children: [
3365
3450
  /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_react15.RiInboxLine, { className: "text-muted-foreground h-8 w-8" }),
3366
3451
  /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)("div", { className: "space-y-1", children: [
3367
3452
  /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("p", { className: "text-foreground text-sm font-medium", children: "No rows yet" }),
3368
- /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("p", { className: "text-muted-foreground max-w-md text-sm", children: tableName ? `The "${tableName}" table is empty.` : "This table is empty." })
3453
+ /* @__PURE__ */ (0, import_jsx_runtime7.jsx)("p", { className: "text-muted-foreground max-w-md text-sm", children: readOnlyReason ?? (tableName ? `The "${tableName}" table is empty.` : "This table is empty.") })
3369
3454
  ] }),
3370
3455
  onAddRow && /* @__PURE__ */ (0, import_jsx_runtime7.jsxs)(import_button3.Button, { variant: "outline", size: "sm", onClick: onAddRow, children: [
3371
3456
  /* @__PURE__ */ (0, import_jsx_runtime7.jsx)(import_react15.RiAddLine, { className: "h-4 w-4" }),
@@ -3607,6 +3692,8 @@ init_cell_type_groups();
3607
3692
  init_cell_type_groups();
3608
3693
  function mapToFrontendCellType(metadata) {
3609
3694
  const { gqlType, isArray, pgAlias, pgType } = metadata;
3695
+ const encodedType = mapEncodingToCellType(metadata.encoding);
3696
+ if (encodedType) return encodedType;
3610
3697
  if (pgAlias) {
3611
3698
  const aliasType = mapAliasToCellType(pgAlias);
3612
3699
  if (aliasType !== "unknown") return aliasType;
@@ -3622,6 +3709,38 @@ function mapToFrontendCellType(metadata) {
3622
3709
  const fallbackResult = mapGraphQLTypeToCellType(gqlType, isArray, metadata.subtype, null);
3623
3710
  return fallbackResult;
3624
3711
  }
3712
+ function mapEncodingToCellType(encoding) {
3713
+ if (!encoding) return null;
3714
+ switch (encoding.kind) {
3715
+ case "bigint":
3716
+ return "integer";
3717
+ case "datetime":
3718
+ return "datetime";
3719
+ case "date":
3720
+ return "date";
3721
+ case "time":
3722
+ return "time";
3723
+ case "interval":
3724
+ return "interval";
3725
+ case "uuid":
3726
+ return "uuid";
3727
+ case "inet":
3728
+ return "inet";
3729
+ case "point":
3730
+ return "geometry-point";
3731
+ case "geojson":
3732
+ return encoding.geometrySubtype === "Point" ? "geometry-point" : "geometry";
3733
+ case "vector":
3734
+ return "number-array";
3735
+ case "composite":
3736
+ return "json";
3737
+ case "ltree":
3738
+ case "bytea":
3739
+ return "text";
3740
+ default:
3741
+ return null;
3742
+ }
3743
+ }
3625
3744
  function mapAliasToCellType(alias) {
3626
3745
  const aliasMap = {
3627
3746
  // Media types
@@ -3826,9 +3945,9 @@ function isStructuredDataType(cellType) {
3826
3945
  }
3827
3946
  function createColumnSchemaFromMeta(field) {
3828
3947
  const { name, type } = field;
3829
- const { gqlType, isArray, modifier: _modifier, pgAlias: _pgAlias, pgType: _pgType, subtype, typmod } = type;
3948
+ const { gqlType, isArray, subtype } = type;
3830
3949
  const nullable = !gqlType.endsWith("!");
3831
- const cellType = mapGraphQLTypeToCellType(gqlType, isArray, subtype, typmod);
3950
+ const cellType = mapToFrontendCellType(field.type);
3832
3951
  const label = name.replace(/([A-Z])/g, " $1").replace(/^./, (str) => str.toUpperCase()).trim();
3833
3952
  return {
3834
3953
  id: name,
@@ -4193,43 +4312,20 @@ function createHeaderClickHandler(columnKeys, toggleSorting, sortableColumns) {
4193
4312
  var import_react19 = require("react");
4194
4313
  var import_react_query4 = require("@tanstack/react-query");
4195
4314
  var import_inflekt4 = require("inflekt");
4196
- var import_data13 = require("@constructive-io/data");
4315
+ var import_data14 = require("@constructive-io/data");
4197
4316
 
4198
4317
  // src/hooks/use-sheets-meta.ts
4199
4318
  var import_react_query3 = require("@tanstack/react-query");
4200
4319
 
4201
4320
  // src/adapter/postgraphile-adapter.ts
4202
- var import_data12 = require("@constructive-io/data");
4321
+ var import_data13 = require("@constructive-io/data");
4203
4322
 
4204
4323
  // src/hooks/use-sheets-table.ts
4205
4324
  var import_react18 = require("react");
4206
4325
  var import_react_query2 = require("@tanstack/react-query");
4207
- var import_data9 = require("@constructive-io/data");
4208
4326
  var import_data10 = require("@constructive-io/data");
4209
4327
  var import_data11 = require("@constructive-io/data");
4210
-
4211
- // src/hooks/query-keys.ts
4212
- function isSheetsScopeKey(value) {
4213
- if (!value || typeof value !== "object") return false;
4214
- const candidate = value;
4215
- return "databaseId" in candidate && "endpoint" in candidate;
4216
- }
4217
- var sheetsQueryKeys = {
4218
- root: ["sheets"],
4219
- scope: (scope) => ["sheets", scope],
4220
- meta: (scope) => [...sheetsQueryKeys.scope(scope), "meta"],
4221
- typeFields: (scope, typeName) => [...sheetsQueryKeys.scope(scope), "type-fields", typeName],
4222
- enumValues: (scope, typeName) => [...sheetsQueryKeys.scope(scope), "enum-values", typeName],
4223
- relations: (scope, tableName) => [...sheetsQueryKeys.scope(scope), "relations", tableName],
4224
- table: (scope, tableName) => [...sheetsQueryKeys.scope(scope), "table", tableName],
4225
- tableRows: (scope, tableName, options) => [...sheetsQueryKeys.table(scope, tableName), "rows", options],
4226
- tableRow: (scope, tableName, id) => [...sheetsQueryKeys.table(scope, tableName), "row", id],
4227
- tableCount: (scope, tableName, where) => [...sheetsQueryKeys.table(scope, tableName), "count", where],
4228
- infiniteTable: (scope, tableName) => [...sheetsQueryKeys.scope(scope), "infinite-table", tableName],
4229
- infiniteTablePage: (scope, tableName, pageIndex, options) => [...sheetsQueryKeys.infiniteTable(scope, tableName), "page", pageIndex, options],
4230
- infiniteTableTotalCount: (scope, tableName, where) => [...sheetsQueryKeys.infiniteTable(scope, tableName), "totalCount", where],
4231
- cursorTable: (scope, tableName, options) => [...sheetsQueryKeys.scope(scope), "cursor-table", tableName, options]
4232
- };
4328
+ var import_data12 = require("@constructive-io/data");
4233
4329
 
4234
4330
  // src/hooks/relation-field-resolution.ts
4235
4331
  var import_inflekt3 = require("inflekt");
@@ -4437,14 +4533,70 @@ async function validateOrderByVariables(variables, table, scopeKey, queryClient,
4437
4533
  }
4438
4534
  }
4439
4535
 
4440
- // src/hooks/use-sheets-table.ts
4441
- function extractRowId(row) {
4442
- if (!row || typeof row !== "object") {
4443
- return null;
4536
+ // src/row-identity.ts
4537
+ var import_data9 = require("@constructive-io/data");
4538
+ function isLegacyScalarId(primaryKey) {
4539
+ const entries = Object.entries(primaryKey);
4540
+ return entries.length === 1 && entries[0][0] === "id" && (typeof entries[0][1] === "string" || typeof entries[0][1] === "number");
4541
+ }
4542
+ function resolveSheetsRowIdentity(table, row) {
4543
+ const resolution = (0, import_data9.resolveRowIdentity)(table, row);
4544
+ if (resolution.status === "read-only") {
4545
+ return { status: "unavailable", reason: "no-primary-key" };
4546
+ }
4547
+ if (resolution.status === "invalid-row") {
4548
+ return { status: "unavailable", reason: "invalid-row" };
4549
+ }
4550
+ const primaryKey = (0, import_data9.rowIdentityToPrimaryKey)(resolution.identity);
4551
+ return {
4552
+ status: "identified",
4553
+ identifier: isLegacyScalarId(primaryKey) ? primaryKey.id : primaryKey,
4554
+ primaryKey,
4555
+ key: (0, import_data9.serializeRowIdentity)(resolution.identity)
4556
+ };
4557
+ }
4558
+ function resolveSheetsIdentifier(table, identifier) {
4559
+ const row = typeof identifier === "object" && identifier !== null ? identifier : { id: identifier };
4560
+ return resolveSheetsRowIdentity(table, row);
4561
+ }
4562
+ function sheetsIdentifierToWhere(table, identifier) {
4563
+ const resolution = resolveSheetsIdentifier(table, identifier);
4564
+ if (resolution.status !== "identified") return null;
4565
+ return Object.fromEntries(
4566
+ Object.entries(resolution.primaryKey).map(([field, value]) => [field, { equalTo: value }])
4567
+ );
4568
+ }
4569
+ function sheetsIdentifierCacheKey(table, identifier) {
4570
+ const resolution = resolveSheetsIdentifier(table, identifier);
4571
+ if (resolution.status !== "identified") return null;
4572
+ return typeof resolution.identifier === "object" ? resolution.key : resolution.identifier;
4573
+ }
4574
+ function sheetsRowKey(table, row, index) {
4575
+ const resolution = resolveSheetsRowIdentity(table, row);
4576
+ if (resolution.status === "identified") {
4577
+ return typeof resolution.identifier === "object" ? resolution.key : String(resolution.identifier);
4578
+ }
4579
+ return `${table.schemaName ?? ""}:${table.name}:row:${index}`;
4580
+ }
4581
+ function getSheetsWriteCapability(table) {
4582
+ return table ? (0, import_data9.assessTableWriteCapability)(table) : null;
4583
+ }
4584
+ function canRunSheetsMutation(capability, operation) {
4585
+ if (!capability || capability.status !== "mutable") return false;
4586
+ return capability.operations[operation];
4587
+ }
4588
+ function assertSheetsMutationAllowed(table, operation) {
4589
+ const capability = (0, import_data9.assessTableWriteCapability)(table);
4590
+ if (capability.status === "read-only") {
4591
+ throw new Error(`Table '${table.name}' is read-only because it has no primary key.`);
4592
+ }
4593
+ if (!capability.operations[operation]) {
4594
+ const article = operation === "update" ? "an" : "a";
4595
+ throw new Error(`Table '${table.name}' does not expose ${article} ${operation} mutation.`);
4444
4596
  }
4445
- const candidate = row.id;
4446
- return typeof candidate === "string" || typeof candidate === "number" ? candidate : null;
4447
4597
  }
4598
+
4599
+ // src/hooks/use-sheets-table.ts
4448
4600
  function transformRelationData(data, table) {
4449
4601
  if (!data) return [];
4450
4602
  if (!Array.isArray(data)) return data;
@@ -4496,7 +4648,7 @@ function transformToPostGraphileVariables(table, options = {}) {
4496
4648
  }
4497
4649
  if (options.orderBy && options.orderBy.length > 0) {
4498
4650
  const availableFields = new Set(table.fields.map((field) => field.name));
4499
- variables.orderBy = options.orderBy.filter(({ field }) => availableFields.has(field)).map(({ field, direction }) => (0, import_data11.toOrderByEnumValue)(field, direction));
4651
+ variables.orderBy = options.orderBy.filter(({ field }) => availableFields.has(field)).map(({ field, direction }) => (0, import_data12.toOrderByEnumValue)(field, direction));
4500
4652
  }
4501
4653
  if (options.where) {
4502
4654
  variables.where = options.where;
@@ -4508,14 +4660,33 @@ function useSheetsTable(tableName, options = {}) {
4508
4660
  const { execute, scopeKey } = useSheetsContext();
4509
4661
  const { data: meta } = useSheetsMeta();
4510
4662
  const adapter = useSheetsAdapter();
4511
- const tables = (0, import_react18.useMemo)(() => {
4663
+ const metaTables = (0, import_react18.useMemo)(() => {
4512
4664
  if (!meta?._meta?.tables) return [];
4513
- return meta._meta.tables.filter((candidate) => candidate != null).map((metaTable) => (0, import_data9.cleanTable)(metaTable));
4665
+ return meta._meta.tables.filter((candidate) => candidate != null);
4514
4666
  }, [meta]);
4667
+ const tables = (0, import_react18.useMemo)(() => metaTables.map(import_data10.cleanTable), [metaTables]);
4515
4668
  const table = (0, import_react18.useMemo)(
4516
4669
  () => tables.find((candidate) => candidate.name === tableName) ?? null,
4517
4670
  [tables, tableName]
4518
4671
  );
4672
+ const tableMeta = (0, import_react18.useMemo)(
4673
+ () => metaTables.find((candidate) => candidate.name === tableName) ?? null,
4674
+ [metaTables, tableName]
4675
+ );
4676
+ const resolveIdentifier = (identifier) => {
4677
+ if (!tableMeta) throw import_data11.createError.notFound(`Table '${tableName}' not found`);
4678
+ const resolution = resolveSheetsIdentifier(tableMeta, identifier);
4679
+ if (resolution.status !== "identified") {
4680
+ throw import_data11.createError.badRequest(`Cannot resolve a primary-key identity for table '${tableName}'.`);
4681
+ }
4682
+ return resolution.identifier;
4683
+ };
4684
+ const rowCacheKey = (row) => {
4685
+ if (!tableMeta || !row) return null;
4686
+ const resolution = resolveSheetsRowIdentity(tableMeta, row);
4687
+ if (resolution.status !== "identified") return null;
4688
+ return typeof resolution.identifier === "object" ? resolution.key : resolution.identifier;
4689
+ };
4519
4690
  const { enabled = true, select: fieldSelection, mutationOptions = {}, ...queryOptions } = options;
4520
4691
  const finalQueryOptions = {
4521
4692
  ...queryOptions,
@@ -4530,7 +4701,7 @@ function useSheetsTable(tableName, options = {}) {
4530
4701
  queryKey: sheetsTableQueryKeys.tableRows(scopeKey, tableName, finalQueryOptions),
4531
4702
  queryFn: async () => {
4532
4703
  if (!table) {
4533
- throw import_data10.createError.notFound(`Table '${tableName}' not found`);
4704
+ throw import_data11.createError.notFound(`Table '${tableName}' not found`);
4534
4705
  }
4535
4706
  const variables = transformToPostGraphileVariables(table, finalQueryOptions);
4536
4707
  const [relationFieldMap] = await Promise.all([
@@ -4546,7 +4717,7 @@ function useSheetsTable(tableName, options = {}) {
4546
4717
  const validatedOrderByEnum = new Set(variables.orderBy ?? []);
4547
4718
  const availableOrderByFields = new Set(table.fields.map((field) => field.name));
4548
4719
  const validatedOrderBy = finalQueryOptions.orderBy?.filter(
4549
- ({ field, direction }) => availableOrderByFields.has(field) && validatedOrderByEnum.has((0, import_data11.toOrderByEnumValue)(field, direction))
4720
+ ({ field, direction }) => availableOrderByFields.has(field) && validatedOrderByEnum.has((0, import_data12.toOrderByEnumValue)(field, direction))
4550
4721
  );
4551
4722
  const { rows, totalCount: totalCount2 } = await adapter.listRows(
4552
4723
  { table, allTables: tables, tableName },
@@ -4572,10 +4743,11 @@ function useSheetsTable(tableName, options = {}) {
4572
4743
  const createMutation = (0, import_react_query2.useMutation)({
4573
4744
  mutationKey: sheetsTableMutationKeys.create(scopeKey, tableName),
4574
4745
  mutationFn: async (data2) => {
4575
- if (!table) {
4576
- throw import_data10.createError.notFound(`Table '${tableName}' not found`);
4746
+ if (!table || !tableMeta) {
4747
+ throw import_data11.createError.notFound(`Table '${tableName}' not found`);
4577
4748
  }
4578
- const allTables = meta?._meta?.tables ? meta._meta.tables.filter((t) => t != null).map(import_data9.cleanTable) : [];
4749
+ assertSheetsMutationAllowed(tableMeta, "create");
4750
+ const allTables = meta?._meta?.tables ? meta._meta.tables.filter((t) => t != null).map(import_data10.cleanTable) : [];
4579
4751
  const createdRow = await adapter.createRow({ table, allTables, tableName }, data2, execute, {
4580
4752
  ...mutationOptions,
4581
4753
  fieldSelection: mutationOptions.fieldSelection || fieldSelection || "display"
@@ -4585,20 +4757,22 @@ function useSheetsTable(tableName, options = {}) {
4585
4757
  onSuccess: ({ createdRow }) => {
4586
4758
  queryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.table(scopeKey, tableName) });
4587
4759
  queryClient.invalidateQueries({ queryKey: sheetsQueryKeys.infiniteTable(scopeKey, tableName) });
4588
- const createdRowId = extractRowId(createdRow);
4589
- if (createdRowId !== null) {
4590
- queryClient.setQueryData(sheetsTableQueryKeys.tableRow(scopeKey, tableName, createdRowId), createdRow);
4760
+ const createdRowKey = rowCacheKey(createdRow);
4761
+ if (createdRowKey !== null) {
4762
+ queryClient.setQueryData(sheetsTableQueryKeys.tableRow(scopeKey, tableName, createdRowKey), createdRow);
4591
4763
  }
4592
4764
  }
4593
4765
  });
4594
4766
  const updateMutation = (0, import_react_query2.useMutation)({
4595
4767
  mutationKey: sheetsTableMutationKeys.update(scopeKey, tableName),
4596
4768
  mutationFn: async ({ id, patch }) => {
4597
- if (!table) {
4598
- throw import_data10.createError.notFound(`Table '${tableName}' not found`);
4769
+ if (!table || !tableMeta) {
4770
+ throw import_data11.createError.notFound(`Table '${tableName}' not found`);
4599
4771
  }
4600
- const allTables = meta?._meta?.tables ? meta._meta.tables.filter((t) => t != null).map(import_data9.cleanTable) : [];
4601
- const updatedRow = await adapter.updateRow({ table, allTables, tableName }, id, patch, execute, {
4772
+ assertSheetsMutationAllowed(tableMeta, "update");
4773
+ const mutationIdentifier = resolveIdentifier(id);
4774
+ const allTables = meta?._meta?.tables ? meta._meta.tables.filter((t) => t != null).map(import_data10.cleanTable) : [];
4775
+ const updatedRow = await adapter.updateRow({ table, allTables, tableName }, mutationIdentifier, patch, execute, {
4602
4776
  ...mutationOptions,
4603
4777
  fieldSelection: mutationOptions.fieldSelection || fieldSelection || "display"
4604
4778
  });
@@ -4613,6 +4787,7 @@ function useSheetsTable(tableName, options = {}) {
4613
4787
  onMutate: async ({ id, patch }) => {
4614
4788
  const tablePrefix = sheetsTableQueryKeys.table(scopeKey, tableName);
4615
4789
  await queryClient.cancelQueries({ queryKey: tablePrefix });
4790
+ const targetKey = tableMeta ? sheetsIdentifierCacheKey(tableMeta, id) : null;
4616
4791
  const isRowsKey = (key2) => key2[key2.length - 2] === "rows";
4617
4792
  const previousRows = queryClient.getQueriesData({ queryKey: tablePrefix }).filter(([key2]) => isRowsKey(key2));
4618
4793
  for (const [key2] of previousRows) {
@@ -4620,7 +4795,7 @@ function useSheetsTable(tableName, options = {}) {
4620
4795
  if (!old) return old;
4621
4796
  let changed = false;
4622
4797
  const rows = old.rows.map((row) => {
4623
- if (extractRowId(row) === id) {
4798
+ if (targetKey !== null && rowCacheKey(row) === targetKey) {
4624
4799
  changed = true;
4625
4800
  return { ...row, ...patch };
4626
4801
  }
@@ -4636,51 +4811,58 @@ function useSheetsTable(tableName, options = {}) {
4636
4811
  },
4637
4812
  onSuccess: ({ updatedRow }) => {
4638
4813
  queryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.table(scopeKey, tableName) });
4639
- const updatedRowId = extractRowId(updatedRow);
4640
- if (updatedRowId !== null) {
4641
- queryClient.setQueryData(sheetsTableQueryKeys.tableRow(scopeKey, tableName, updatedRowId), updatedRow);
4814
+ const updatedRowKey = rowCacheKey(updatedRow);
4815
+ if (updatedRowKey !== null) {
4816
+ queryClient.setQueryData(sheetsTableQueryKeys.tableRow(scopeKey, tableName, updatedRowKey), updatedRow);
4642
4817
  }
4643
4818
  }
4644
4819
  });
4645
4820
  const deleteMutation = (0, import_react_query2.useMutation)({
4646
4821
  mutationKey: sheetsTableMutationKeys.delete(scopeKey, tableName),
4647
4822
  mutationFn: async (idOrPk) => {
4648
- if (!table) {
4649
- throw import_data10.createError.notFound(`Table '${tableName}' not found`);
4823
+ if (!table || !tableMeta) {
4824
+ throw import_data11.createError.notFound(`Table '${tableName}' not found`);
4650
4825
  }
4651
- const allTables = meta?._meta?.tables ? meta._meta.tables.filter((t) => t != null).map(import_data9.cleanTable) : [];
4652
- await adapter.deleteRow({ table, allTables, tableName }, idOrPk, execute, mutationOptions);
4826
+ assertSheetsMutationAllowed(tableMeta, "delete");
4827
+ const mutationIdentifier = resolveIdentifier(idOrPk);
4828
+ const allTables = meta?._meta?.tables ? meta._meta.tables.filter((t) => t != null).map(import_data10.cleanTable) : [];
4829
+ await adapter.deleteRow({ table, allTables, tableName }, mutationIdentifier, execute, mutationOptions);
4653
4830
  return { deletedId: idOrPk, __rawResult: {} };
4654
4831
  },
4655
4832
  onSuccess: ({ deletedId }) => {
4656
4833
  queryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.table(scopeKey, tableName) });
4657
4834
  queryClient.invalidateQueries({ queryKey: sheetsQueryKeys.infiniteTable(scopeKey, tableName) });
4658
- if (deletedId && typeof deletedId !== "object") {
4835
+ const deletedRowKey = tableMeta ? sheetsIdentifierCacheKey(tableMeta, deletedId) : null;
4836
+ if (deletedRowKey !== null) {
4659
4837
  queryClient.removeQueries({
4660
- queryKey: sheetsTableQueryKeys.tableRow(scopeKey, tableName, deletedId)
4838
+ queryKey: sheetsTableQueryKeys.tableRow(scopeKey, tableName, deletedRowKey)
4661
4839
  });
4662
4840
  }
4663
4841
  }
4664
4842
  });
4665
4843
  const findOne = async (id) => {
4666
- if (!table) {
4667
- throw import_data10.createError.notFound(`Table '${tableName}' not found`);
4844
+ if (!table || !tableMeta) {
4845
+ throw import_data11.createError.notFound(`Table '${tableName}' not found`);
4846
+ }
4847
+ const where = sheetsIdentifierToWhere(tableMeta, id);
4848
+ if (!where) {
4849
+ throw import_data11.createError.badRequest(`Cannot resolve a primary-key identity for table '${tableName}'.`);
4668
4850
  }
4669
- const doc = (0, import_data11.buildSelect)(table, tables, {
4670
- where: { id: { equalTo: id } },
4851
+ const doc = (0, import_data12.buildSelect)(table, tables, {
4852
+ where,
4671
4853
  limit: 1
4672
4854
  });
4673
4855
  const variables = transformToPostGraphileVariables(table, {
4674
- where: { id: { equalTo: id } },
4856
+ where,
4675
4857
  limit: 1
4676
4858
  });
4677
4859
  const result = await execute(doc, variables);
4678
- const singularName = (0, import_data11.toCamelCaseSingular)(tableName, table);
4860
+ const singularName = (0, import_data12.toCamelCaseSingular)(tableName, table);
4679
4861
  const singularData = result[singularName];
4680
4862
  if (singularData && typeof singularData === "object") {
4681
4863
  return singularData;
4682
4864
  }
4683
- const queryTableName = (0, import_data11.toCamelCasePlural)(tableName, table);
4865
+ const queryTableName = (0, import_data12.toCamelCasePlural)(tableName, table);
4684
4866
  const data2 = result[queryTableName];
4685
4867
  if (data2 && typeof data2 === "object" && "nodes" in data2) {
4686
4868
  const nodes = data2.nodes || [];
@@ -4721,319 +4903,83 @@ function useSheetsTable(tableName, options = {}) {
4721
4903
  }
4722
4904
 
4723
4905
  // src/adapter/postgraphile-adapter.ts
4724
- var MetaDoc = new import_data12.TypedDocumentString(`
4725
- query Meta {
4726
- _meta {
4727
- tables {
4728
- name
4729
- schemaName
4730
- query {
4731
- all
4732
- create
4733
- delete
4734
- one
4735
- update
4736
- }
4737
- fields {
4738
- name
4739
- isNotNull
4740
- hasDefault
4741
- type {
4742
- gqlType
4743
- isArray
4744
- pgType
4745
- isNotNull
4746
- hasDefault
4747
- subtype
4748
- }
4749
- }
4750
- inflection {
4751
- allRows
4752
- conditionType
4753
- connection
4754
- createInputType
4755
- createPayloadType
4756
- deletePayloadType
4757
- edge
4758
- filterType
4759
- orderByType
4760
- patchType
4761
- tableType
4762
- updatePayloadType
4763
- }
4764
- indexes {
4765
- name
4766
- isUnique
4767
- fields {
4768
- name
4769
- type {
4770
- gqlType
4771
- isArray
4772
- pgType
4773
- }
4774
- }
4775
- }
4776
- constraints {
4777
- primaryKey {
4778
- name
4779
- fields {
4780
- name
4781
- type {
4782
- gqlType
4783
- isArray
4784
- pgType
4785
- }
4786
- }
4787
- }
4788
- unique {
4789
- name
4790
- fields {
4791
- name
4792
- type {
4793
- gqlType
4794
- isArray
4795
- pgType
4796
- }
4797
- }
4798
- }
4799
- foreignKey {
4800
- name
4801
- fields {
4802
- name
4803
- type {
4804
- gqlType
4805
- isArray
4806
- pgType
4807
- }
4808
- }
4809
- refFields {
4810
- name
4811
- type {
4812
- gqlType
4813
- isArray
4814
- pgType
4815
- }
4816
- }
4817
- refTable {
4818
- name
4819
- }
4820
- }
4821
- }
4822
- foreignKeyConstraints {
4823
- name
4824
- fields {
4825
- name
4826
- type {
4827
- gqlType
4828
- isArray
4829
- pgType
4830
- }
4831
- }
4832
- refFields {
4833
- name
4834
- type {
4835
- gqlType
4836
- isArray
4837
- pgType
4838
- }
4839
- }
4840
- refTable {
4841
- name
4842
- }
4843
- }
4844
- primaryKeyConstraints {
4845
- name
4846
- fields {
4847
- name
4848
- type {
4849
- gqlType
4850
- isArray
4851
- pgType
4852
- }
4853
- }
4854
- }
4855
- uniqueConstraints {
4856
- name
4857
- fields {
4858
- name
4859
- type {
4860
- gqlType
4861
- isArray
4862
- pgType
4863
- }
4864
- }
4865
- }
4866
- relations {
4867
- belongsTo {
4868
- fieldName
4869
- isUnique
4870
- keys {
4871
- name
4872
- type {
4873
- gqlType
4874
- isArray
4875
- pgType
4876
- }
4877
- }
4878
- references {
4879
- name
4880
- }
4881
- type
4882
- }
4883
- has {
4884
- fieldName
4885
- isUnique
4886
- keys {
4887
- name
4888
- type {
4889
- gqlType
4890
- isArray
4891
- pgType
4892
- }
4893
- }
4894
- referencedBy {
4895
- name
4896
- }
4897
- type
4898
- }
4899
- hasOne {
4900
- fieldName
4901
- isUnique
4902
- keys {
4903
- name
4904
- type {
4905
- gqlType
4906
- isArray
4907
- pgType
4908
- }
4909
- }
4910
- referencedBy {
4911
- name
4912
- }
4913
- type
4914
- }
4915
- hasMany {
4916
- fieldName
4917
- isUnique
4918
- keys {
4919
- name
4920
- type {
4921
- gqlType
4922
- isArray
4923
- pgType
4924
- }
4925
- }
4926
- referencedBy {
4927
- name
4928
- }
4929
- type
4930
- }
4931
- manyToMany {
4932
- fieldName
4933
- junctionLeftConstraint {
4934
- name
4935
- fields {
4936
- name
4937
- type {
4938
- gqlType
4939
- isArray
4940
- pgType
4941
- }
4942
- }
4943
- refFields {
4944
- name
4945
- type {
4946
- gqlType
4947
- isArray
4948
- pgType
4949
- }
4950
- }
4951
- refTable {
4952
- name
4953
- }
4954
- }
4955
- junctionLeftKeyAttributes {
4956
- name
4957
- type {
4958
- gqlType
4959
- isArray
4960
- pgType
4961
- }
4962
- }
4963
- junctionRightConstraint {
4964
- name
4965
- fields {
4966
- name
4967
- type {
4968
- gqlType
4969
- isArray
4970
- pgType
4971
- }
4972
- }
4973
- refFields {
4974
- name
4975
- type {
4976
- gqlType
4977
- isArray
4978
- pgType
4979
- }
4980
- }
4981
- refTable {
4982
- name
4983
- }
4984
- }
4985
- junctionRightKeyAttributes {
4986
- name
4987
- type {
4988
- gqlType
4989
- isArray
4990
- pgType
4991
- }
4992
- }
4993
- junctionTable {
4994
- name
4995
- }
4996
- leftKeyAttributes {
4997
- name
4998
- type {
4999
- gqlType
5000
- isArray
5001
- pgType
5002
- }
5003
- }
5004
- rightKeyAttributes {
5005
- name
5006
- type {
5007
- gqlType
5008
- isArray
5009
- pgType
5010
- }
5011
- }
5012
- rightTable {
5013
- name
5014
- }
5015
- type
5016
- }
5017
- }
5018
- }
5019
- }
5020
- }
5021
- `);
4906
+ var compatibilityChecks = /* @__PURE__ */ new WeakMap();
4907
+ var enumMappings = /* @__PURE__ */ new WeakMap();
4908
+ async function ensureCurrentMetaContract(execute) {
4909
+ const cached = compatibilityChecks.get(execute);
4910
+ if (cached) return cached;
4911
+ const check = execute(import_data13.META_CONTRACT_INTROSPECTION_DOCUMENT).then(
4912
+ (result) => {
4913
+ (0, import_data13.assertMetaContract)(result);
4914
+ }
4915
+ );
4916
+ compatibilityChecks.set(execute, check);
4917
+ try {
4918
+ await check;
4919
+ } catch (error) {
4920
+ if (compatibilityChecks.get(execute) === check) compatibilityChecks.delete(execute);
4921
+ throw error;
4922
+ }
4923
+ }
4924
+ function hasDeclaredEnums(meta) {
4925
+ return Boolean(meta._meta?.tables?.some(
4926
+ (table) => table?.fields?.some((field) => Boolean(field?.enumValues?.name))
4927
+ ));
4928
+ }
4929
+ function schemaCompatibilityError(missingPaths) {
4930
+ const detail = missingPaths.length > 0 ? ` Missing: ${missingPaths.join(", ")}.` : "";
4931
+ return import_data13.createError.badRequest(
4932
+ `The GraphQL schema does not match the enum values declared by Constructive _meta.${detail}`,
4933
+ "SCHEMA_INTROSPECTION_INCOMPATIBLE"
4934
+ );
4935
+ }
4936
+ function normalizeMutationEnums(ctx, input, execute) {
4937
+ const hasEnumInput = ctx.table.fields.some(
4938
+ (field) => Boolean(field.enumValues?.length) && Object.prototype.hasOwnProperty.call(input, field.name)
4939
+ );
4940
+ if (!hasEnumInput) return input;
4941
+ const mappings = enumMappings.get(execute);
4942
+ if (!mappings) {
4943
+ throw import_data13.createError.badRequest(
4944
+ "Enum schema mappings are unavailable. Load table metadata before mutating enum fields.",
4945
+ "ENUM_MAPPING_UNAVAILABLE"
4946
+ );
4947
+ }
4948
+ return (0, import_data13.normalizeSchemaEnumInputValues)(input, ctx.table, mappings);
4949
+ }
5022
4950
  function createPostGraphileAdapter() {
5023
4951
  return {
5024
4952
  async fetchMeta(execute) {
5025
- return await execute(MetaDoc);
4953
+ await ensureCurrentMetaContract(execute);
4954
+ const meta = await execute(import_data13.META_DOCUMENT);
4955
+ (0, import_data13.assertMetaQuery)(meta);
4956
+ if (!hasDeclaredEnums(meta)) {
4957
+ enumMappings.set(execute, []);
4958
+ return meta;
4959
+ }
4960
+ try {
4961
+ const introspection = await execute(import_data13.SCHEMA_INTROSPECTION_QUERY);
4962
+ const analysis = (0, import_data13.analyzeSchemaIntrospectionCompatibility)(introspection, meta);
4963
+ if (analysis.status !== "compatible") {
4964
+ throw schemaCompatibilityError(analysis.missingPaths);
4965
+ }
4966
+ enumMappings.set(execute, analysis.enumMappings);
4967
+ } catch (error) {
4968
+ enumMappings.delete(execute);
4969
+ throw error;
4970
+ }
4971
+ return meta;
5026
4972
  },
5027
4973
  async listRows(ctx, query, execute) {
5028
4974
  const { table, allTables, tableName } = ctx;
5029
4975
  const { relationFieldMap, ...queryOptions } = query;
5030
4976
  const variables = transformToPostGraphileVariables(table, queryOptions);
5031
- const doc = (0, import_data12.buildSelect)(table, allTables, {
4977
+ const doc = (0, import_data13.buildSelect)(table, allTables, {
5032
4978
  ...queryOptions,
5033
4979
  relationFieldMap
5034
4980
  });
5035
4981
  const result = await execute(doc, variables);
5036
- const queryTableName = (0, import_data12.toCamelCasePlural)(tableName, table);
4982
+ const queryTableName = (0, import_data13.toCamelCasePlural)(tableName, table);
5037
4983
  const connection = result[queryTableName];
5038
4984
  if (connection && typeof connection === "object" && "nodes" in connection) {
5039
4985
  const nodes = connection.nodes || [];
@@ -5046,54 +4992,56 @@ function createPostGraphileAdapter() {
5046
4992
  const directData = connection || [];
5047
4993
  return {
5048
4994
  rows: transformRelationData(directData, table),
5049
- // Non-Relay direct-array response: page length only, not a full filtered count.
5050
4995
  totalCount: directData.length
5051
4996
  };
5052
4997
  },
5053
4998
  async createRow(ctx, data, execute, options = {}) {
5054
4999
  const { table, allTables, tableName } = ctx;
5055
- const doc = (0, import_data12.buildPostGraphileCreate)(table, allTables, {
5000
+ const doc = (0, import_data13.buildPostGraphileCreate)(table, allTables, {
5056
5001
  ...options,
5057
5002
  fieldSelection: options.fieldSelection || "display"
5058
5003
  });
5059
- const singularName = (0, import_data12.toCamelCaseSingular)(tableName, table);
5060
- const sanitizedData = (0, import_data12.prepareCreateInput)(data);
5004
+ const singularName = (0, import_data13.toCamelCaseSingular)(tableName, table);
5005
+ const sanitizedData = normalizeMutationEnums(
5006
+ ctx,
5007
+ (0, import_data13.prepareCreateInput)(data),
5008
+ execute
5009
+ );
5061
5010
  const variables = {
5062
5011
  input: {
5063
5012
  [singularName]: sanitizedData
5064
5013
  }
5065
5014
  };
5066
5015
  const result = await execute(doc, variables);
5067
- const mutationName = (0, import_data12.toCreateMutationName)(tableName, table);
5016
+ const mutationName = (0, import_data13.toCreateMutationName)(tableName, table);
5068
5017
  const createdRow = result[mutationName]?.[singularName] ?? null;
5069
5018
  return createdRow;
5070
5019
  },
5071
5020
  async updateRow(ctx, id, patch, execute, options = {}) {
5072
5021
  const { table, allTables, tableName } = ctx;
5073
- const doc = (0, import_data12.buildPostGraphileUpdate)(table, allTables, {
5022
+ const doc = (0, import_data13.buildPostGraphileUpdate)(table, allTables, {
5074
5023
  ...options,
5075
5024
  fieldSelection: options.fieldSelection || "display"
5076
5025
  });
5077
- const patchFieldName = (0, import_data12.toPatchFieldName)(tableName, table);
5078
- const sanitizedPatch = (0, import_data12.prepareUpdateInput)(patch);
5079
- if (Object.keys(sanitizedPatch).length === 0) {
5080
- return null;
5081
- }
5026
+ const patchFieldName = (0, import_data13.toPatchFieldName)(tableName, table);
5027
+ const sanitizedPatch = (0, import_data13.prepareUpdateInput)(patch);
5028
+ if (Object.keys(sanitizedPatch).length === 0) return null;
5029
+ const normalizedPatch = normalizeMutationEnums(ctx, sanitizedPatch, execute);
5082
5030
  const variables = {
5083
5031
  input: {
5084
- id,
5085
- [patchFieldName]: sanitizedPatch
5032
+ ...typeof id === "object" ? id : { id },
5033
+ [patchFieldName]: normalizedPatch
5086
5034
  }
5087
5035
  };
5088
5036
  const result = await execute(doc, variables);
5089
- const mutationName = (0, import_data12.toUpdateMutationName)(tableName, table);
5090
- const singularName = (0, import_data12.toCamelCaseSingular)(tableName, table);
5037
+ const mutationName = (0, import_data13.toUpdateMutationName)(tableName, table);
5038
+ const singularName = (0, import_data13.toCamelCaseSingular)(tableName, table);
5091
5039
  const updatedRow = result[mutationName]?.[singularName] ?? null;
5092
5040
  return updatedRow;
5093
5041
  },
5094
5042
  async deleteRow(ctx, id, execute, options = {}) {
5095
5043
  const { table, allTables } = ctx;
5096
- const doc = (0, import_data12.buildPostGraphileDelete)(table, allTables, options);
5044
+ const doc = (0, import_data13.buildPostGraphileDelete)(table, allTables, options);
5097
5045
  const variables = {
5098
5046
  input: typeof id === "object" ? id : { id }
5099
5047
  };
@@ -5162,7 +5110,7 @@ function useRelationMetadataCache(tableName) {
5162
5110
  sheetsLogger().debug?.(`Table "${tableName}" not found in metadata`);
5163
5111
  return null;
5164
5112
  }
5165
- return (0, import_data13.cleanTable)(metaTable);
5113
+ return (0, import_data14.cleanTable)(metaTable);
5166
5114
  },
5167
5115
  ...RELATION_CACHE_CONFIG,
5168
5116
  refetchOnMount: true,
@@ -5222,7 +5170,7 @@ function useRelationMetadataCache(tableName) {
5222
5170
  const refName = fk.refTable?.name;
5223
5171
  if (refName && refName.toLowerCase() === (tableName || "").toLowerCase()) {
5224
5172
  const fieldName = fk.fields?.[0]?.name;
5225
- if (fieldName) return (0, import_data13.pgFieldToCamelCase)(fieldName);
5173
+ if (fieldName) return (0, import_data14.pgFieldToCamelCase)(fieldName);
5226
5174
  }
5227
5175
  }
5228
5176
  return void 0;
@@ -5981,6 +5929,9 @@ var DRAFT_ACTION_COLUMN_KEY = "__draft_action__";
5981
5929
 
5982
5930
  // src/grid/hooks/use-cell-editing.ts
5983
5931
  var import_react21 = require("react");
5932
+ function legacyRowIdentifier(row) {
5933
+ return typeof row.id === "string" || typeof row.id === "number" ? row.id : null;
5934
+ }
5984
5935
  function normalizeRelationPatchValue(rawValue, relationKind) {
5985
5936
  let value = rawValue;
5986
5937
  if (typeof value === "string") {
@@ -6004,8 +5955,9 @@ function normalizeRelationPatchValue(rawValue, relationKind) {
6004
5955
  if (value === "") value = null;
6005
5956
  return value;
6006
5957
  }
6007
- function resolveServerPatch(colKey, rawValue, fieldMetaMap, relationInfoByField) {
5958
+ function resolveServerPatch(colKey, rawValue, fieldMetaMap, relationInfoByField, readOnlyFields) {
6008
5959
  if (!colKey || colKey === DRAFT_ACTION_COLUMN_KEY) return { kind: "noop" };
5960
+ if (readOnlyFields?.has(colKey)) return { kind: "noop" };
6009
5961
  const metaField = fieldMetaMap.get(colKey);
6010
5962
  if (colKey === "id" && metaField?.type?.gqlType === "UUID") return { kind: "noop" };
6011
5963
  const relationInfo = relationInfoByField.get(colKey);
@@ -6027,6 +5979,9 @@ function useCellEditing({
6027
5979
  updateDraftCell,
6028
5980
  tableKey,
6029
5981
  update,
5982
+ getRowIdentifier = legacyRowIdentifier,
5983
+ readOnlyFields,
5984
+ canUpdate = true,
6030
5985
  onCellEdit,
6031
5986
  applyOptimisticPatch
6032
5987
  }) {
@@ -6093,18 +6048,21 @@ function useCellEditing({
6093
6048
  });
6094
6049
  return { type: "draft" };
6095
6050
  }
6096
- const resolution = resolveServerPatch(colKey, rawValue, fieldMetaMap, relationInfoByField);
6051
+ if (!canUpdate) return { type: "noop" };
6052
+ const resolution = resolveServerPatch(colKey, rawValue, fieldMetaMap, relationInfoByField, readOnlyFields);
6097
6053
  if (resolution.kind === "noop") return { type: "noop" };
6098
6054
  const { field: patchField, value } = resolution;
6055
+ const rowIdentifier = getRowIdentifier(rowData);
6056
+ if (rowIdentifier === null) return { type: "noop" };
6099
6057
  const revertOptimisticPatch = applyOptimisticPatch?.(rowIndex, { [patchField]: value });
6100
6058
  let result;
6101
6059
  try {
6102
- result = await update(rowData.id, { [patchField]: value });
6060
+ result = await update(rowIdentifier, { [patchField]: value });
6103
6061
  } catch (error) {
6104
6062
  revertOptimisticPatch?.();
6105
6063
  throw error;
6106
6064
  }
6107
- onCellEdit?.(rowData.id, patchField, value);
6065
+ onCellEdit?.(rowIdentifier, patchField, value);
6108
6066
  return {
6109
6067
  type: "server",
6110
6068
  updatedRow: result?.updatedRow ?? null,
@@ -6112,17 +6070,23 @@ function useCellEditing({
6112
6070
  patchValue: value
6113
6071
  };
6114
6072
  },
6115
- [combinedRows, fieldMetaMap, relationInfoByField, tableKey, update, onCellEdit, updateDraftCell, applyOptimisticPatch]
6073
+ [combinedRows, fieldMetaMap, relationInfoByField, tableKey, update, getRowIdentifier, readOnlyFields, canUpdate, onCellEdit, updateDraftCell, applyOptimisticPatch]
6116
6074
  );
6117
6075
  }
6118
6076
 
6119
6077
  // src/grid/hooks/use-batch-commit.ts
6120
6078
  var import_react22 = require("react");
6079
+ function legacyRowIdentifier2(row) {
6080
+ return typeof row.id === "string" || typeof row.id === "number" ? row.id : null;
6081
+ }
6121
6082
  function useBatchCommit({
6122
6083
  combinedRows,
6123
6084
  fieldMetaMap,
6124
6085
  relationInfoByField,
6125
6086
  update,
6087
+ getRowIdentifier = legacyRowIdentifier2,
6088
+ readOnlyFields,
6089
+ canUpdate = true,
6126
6090
  applyOptimisticPatch,
6127
6091
  resyncRow,
6128
6092
  editCell,
@@ -6142,11 +6106,14 @@ function useBatchCommit({
6142
6106
  draftWrites.push(w);
6143
6107
  continue;
6144
6108
  }
6145
- const resolution = resolveServerPatch(w.colKey, w.value, fieldMetaMap, relationInfoByField);
6109
+ if (!canUpdate) continue;
6110
+ const resolution = resolveServerPatch(w.colKey, w.value, fieldMetaMap, relationInfoByField, readOnlyFields);
6146
6111
  if (resolution.kind === "noop") continue;
6112
+ const rowIdentifier = getRowIdentifier(rowData);
6113
+ if (rowIdentifier === null) continue;
6147
6114
  resolved.push({
6148
6115
  rowIndex: w.rowIndex,
6149
- rowId: rowData.id,
6116
+ rowId: rowIdentifier,
6150
6117
  field: resolution.field,
6151
6118
  value: resolution.value,
6152
6119
  // Capture the PRIOR value of the patched field BEFORE any optimistic patch.
@@ -6201,7 +6168,7 @@ function useBatchCommit({
6201
6168
  }
6202
6169
  return { applied: resolved.length };
6203
6170
  },
6204
- [combinedRows, fieldMetaMap, relationInfoByField, update, applyOptimisticPatch, resyncRow, editCell, onCellEdit, record]
6171
+ [combinedRows, fieldMetaMap, relationInfoByField, update, getRowIdentifier, readOnlyFields, canUpdate, applyOptimisticPatch, resyncRow, editCell, onCellEdit, record]
6205
6172
  );
6206
6173
  commitRef.current = commitCells;
6207
6174
  return commitCells;
@@ -6559,6 +6526,7 @@ function resolveGridCellRoute({
6559
6526
  }
6560
6527
 
6561
6528
  // src/grid-dom/use-sheets-content.ts
6529
+ init_cell_type_groups();
6562
6530
  function isDraftId(value) {
6563
6531
  return typeof value === "string" && value.startsWith("draft:");
6564
6532
  }
@@ -6574,11 +6542,24 @@ function tagDraftStyle(cell, hasError) {
6574
6542
  return { ...cell, styleHint: { ...cell.styleHint, draft: true, error: hasError } };
6575
6543
  }
6576
6544
  function useSheetsContent(args) {
6577
- const { data, columnKeys, fieldMetaMap, registry, tableName, options, relationInfoByField, meta } = args;
6545
+ const {
6546
+ data,
6547
+ columnKeys,
6548
+ fieldMetaMap,
6549
+ registry,
6550
+ tableName,
6551
+ options,
6552
+ relationInfoByField,
6553
+ meta,
6554
+ serverRowsReadOnly = false,
6555
+ serverReadOnlyFields,
6556
+ getRowIdentifier,
6557
+ supportsScalarSelfCommit = true
6558
+ } = args;
6578
6559
  const relationFieldNamesFromMeta = (0, import_react26.useMemo)(() => buildRelationFieldNameSet(meta, tableName), [meta, tableName]);
6579
6560
  const cache2 = (0, import_react26.useMemo)(
6580
6561
  () => /* @__PURE__ */ new Map(),
6581
- [data, columnKeys, fieldMetaMap, registry, relationFieldNamesFromMeta, relationInfoByField, options]
6562
+ [data, columnKeys, fieldMetaMap, registry, relationFieldNamesFromMeta, relationInfoByField, options, serverRowsReadOnly, serverReadOnlyFields, getRowIdentifier, supportsScalarSelfCommit]
6582
6563
  );
6583
6564
  const getSheetsCell = (0, import_react26.useCallback)(
6584
6565
  (rowIndex, colKey) => {
@@ -6620,6 +6601,7 @@ function useSheetsContent(args) {
6620
6601
  isDraftIdCell,
6621
6602
  hasForeignKeyField: canEditRelationInline
6622
6603
  });
6604
+ const tableForcedReadOnly = !isDraftRow2 && (serverRowsReadOnly || Boolean(serverReadOnlyFields?.has(colKey)));
6623
6605
  let valueForCell = rawValue;
6624
6606
  if (relationInfo && relationInfo.relationField && relationInfo.relationField !== colKey) {
6625
6607
  const relatedValue = rowData?.[relationInfo.relationField];
@@ -6647,17 +6629,22 @@ function useSheetsContent(args) {
6647
6629
  fieldName: colKey
6648
6630
  };
6649
6631
  const cellType = registry.resolveTypeKey(matchInput, () => route.cellType);
6632
+ const rowIdentifier = !isDraftRow2 ? getRowIdentifier?.(rowData) : null;
6633
+ const selfCommittingEditor = isRelation || MEDIA_TYPES.has(cellType);
6634
+ const lacksScalarEditorIdentity = selfCommittingEditor && (!supportsScalarSelfCommit || rowIdentifier != null && typeof rowIdentifier === "object");
6635
+ const forcedReadOnly = tableForcedReadOnly || lacksScalarEditorIdentity;
6650
6636
  const metadata = {
6651
6637
  cellType,
6652
6638
  fieldName: colKey,
6653
6639
  fieldMeta,
6654
6640
  relationInfo,
6655
6641
  relationOptions: relationInfo ? options || {} : void 0,
6656
- canEdit: route.canEdit,
6657
- isReadonly: route.isReadonly,
6642
+ canEdit: route.canEdit && !forcedReadOnly,
6643
+ isReadonly: route.isReadonly || forcedReadOnly,
6658
6644
  activationBehavior: route.activationBehavior
6659
6645
  };
6660
- const cell = registry.toSheetsCell(cellType, valueForCell, { metadata });
6646
+ const resolvedCell = registry.toSheetsCell(cellType, valueForCell, { metadata });
6647
+ const cell = forcedReadOnly && !resolvedCell.readonly ? { ...resolvedCell, readonly: true } : resolvedCell;
6661
6648
  const displaySafe = suppressDraftIdText(cell, {
6662
6649
  isDraftRow: isDraftRow2,
6663
6650
  colKey,
@@ -6672,7 +6659,7 @@ function useSheetsContent(args) {
6672
6659
  cache2.set(cacheKey, { value: rawValue, resolution });
6673
6660
  return resolution;
6674
6661
  },
6675
- [data, columnKeys, fieldMetaMap, registry, relationFieldNamesFromMeta, relationInfoByField, options]
6662
+ [data, columnKeys, fieldMetaMap, registry, relationFieldNamesFromMeta, relationInfoByField, options, serverRowsReadOnly, serverReadOnlyFields, getRowIdentifier, supportsScalarSelfCommit]
6676
6663
  );
6677
6664
  return { getSheetsCell };
6678
6665
  }
@@ -6729,13 +6716,18 @@ function useGridOperations(data, deleteRow, gridSelection, clearSelection, optio
6729
6716
  } else {
6730
6717
  failures += 1;
6731
6718
  }
6732
- } else if (record?.id) {
6719
+ } else if (options?.canDeleteServerRows !== false) {
6720
+ const identifier = options?.getRowIdentifier ? options.getRowIdentifier(record) : typeof record?.id === "string" || typeof record?.id === "number" ? record.id : null;
6721
+ if (identifier === null) {
6722
+ failures += 1;
6723
+ continue;
6724
+ }
6733
6725
  try {
6734
- await deleteRow(record.id);
6726
+ await deleteRow(identifier);
6735
6727
  successes += 1;
6736
6728
  serverSuccesses += 1;
6737
6729
  } catch (error) {
6738
- sheetsLogger().error(`Failed to delete record ${record.id}:`, error);
6730
+ sheetsLogger().error("Failed to delete record", { identifier, error });
6739
6731
  failures += 1;
6740
6732
  }
6741
6733
  } else {
@@ -7165,9 +7157,9 @@ var import_react31 = require("react");
7165
7157
  // src/hooks/use-sheets-infinite-table.ts
7166
7158
  var import_react30 = require("react");
7167
7159
  var import_react_query5 = require("@tanstack/react-query");
7168
- var import_data14 = require("@constructive-io/data");
7169
7160
  var import_data15 = require("@constructive-io/data");
7170
7161
  var import_data16 = require("@constructive-io/data");
7162
+ var import_data17 = require("@constructive-io/data");
7171
7163
  var sheetsInfiniteTableKeys = {
7172
7164
  all: (scope, tableName) => sheetsQueryKeys.infiniteTable(scope, tableName),
7173
7165
  page: (scope, tableName, pageIndex, optionsKey) => [...sheetsQueryKeys.infiniteTable(scope, tableName), "page", pageIndex, optionsKey],
@@ -7201,7 +7193,7 @@ function useSheetsInfiniteTable(tableName, options = {}) {
7201
7193
  const prevTableNameRef = (0, import_react30.useRef)(tableName);
7202
7194
  const tables = (0, import_react30.useMemo)(() => {
7203
7195
  if (!meta?._meta?.tables) return [];
7204
- return meta._meta.tables.filter((candidate) => candidate != null).map((metaTable) => (0, import_data14.cleanTable)(metaTable));
7196
+ return meta._meta.tables.filter((candidate) => candidate != null).map((metaTable) => (0, import_data15.cleanTable)(metaTable));
7205
7197
  }, [meta]);
7206
7198
  const table = (0, import_react30.useMemo)(
7207
7199
  () => tables.find((candidate) => candidate.name === tableName) ?? null,
@@ -7248,7 +7240,7 @@ function useSheetsInfiniteTable(tableName, options = {}) {
7248
7240
  queryKey: sheetsInfiniteTableKeys.page(scopeKey, tableName, pageIndex, stableOptionsKey),
7249
7241
  queryFn: async () => {
7250
7242
  if (!table) {
7251
- throw import_data15.createError.notFound(`Table '${tableName}' not found`);
7243
+ throw import_data16.createError.notFound(`Table '${tableName}' not found`);
7252
7244
  }
7253
7245
  const queryOptions = {
7254
7246
  first: pageSize,
@@ -7279,7 +7271,7 @@ function useSheetsInfiniteTable(tableName, options = {}) {
7279
7271
  const validatedOrderByEnum = new Set(variables.orderBy ?? []);
7280
7272
  const availableOrderByFields = new Set(table.fields.map((field) => field.name));
7281
7273
  const validatedOrderBy = orderBy?.filter(
7282
- ({ field, direction }) => availableOrderByFields.has(field) && validatedOrderByEnum.has((0, import_data16.toOrderByEnumValue)(field, direction))
7274
+ ({ field, direction }) => availableOrderByFields.has(field) && validatedOrderByEnum.has((0, import_data17.toOrderByEnumValue)(field, direction))
7283
7275
  );
7284
7276
  const res = await adapter.listRows(
7285
7277
  { table, allTables: tables, tableName },
@@ -7609,6 +7601,7 @@ function useInfiniteGridData({
7609
7601
 
7610
7602
  // src/grid/hooks/use-load-grid.ts
7611
7603
  var import_react32 = require("react");
7604
+ var import_data18 = require("@constructive-io/data");
7612
7605
  function buildFieldMetaMap2(fields, tableName, fieldTypeOverrides) {
7613
7606
  const map = /* @__PURE__ */ new Map();
7614
7607
  if (!fields || fields.length === 0) return map;
@@ -7642,6 +7635,10 @@ function useDataLoading({
7642
7635
  return candidate ?? null;
7643
7636
  }, [meta, tableName]);
7644
7637
  const tableSchema = (0, import_react32.useMemo)(() => buildTableSchema(tableMeta), [tableMeta]);
7638
+ const writeCapability = (0, import_react32.useMemo)(
7639
+ () => tableMeta ? (0, import_data18.assessTableWriteCapability)(tableMeta) : null,
7640
+ [tableMeta]
7641
+ );
7645
7642
  const fieldMetaMap = (0, import_react32.useMemo)(() => {
7646
7643
  const candidate = meta?._meta?.tables?.find((t) => t?.name === tableName);
7647
7644
  const fields = candidate?.fields || [];
@@ -7677,8 +7674,12 @@ function useDataLoading({
7677
7674
  const create9 = async (payload) => {
7678
7675
  const result = await createRow(payload);
7679
7676
  const createdRow = result?.createdRow;
7680
- if (!createdRow || typeof createdRow.id !== "string" && typeof createdRow.id !== "number") {
7681
- return { createdRow: null };
7677
+ if (!createdRow || typeof createdRow !== "object" || !tableMeta) {
7678
+ throw new Error(`Create mutation for '${tableName}' did not return a row identity.`);
7679
+ }
7680
+ const identity = resolveSheetsRowIdentity(tableMeta, createdRow);
7681
+ if (identity.status !== "identified") {
7682
+ throw new Error(`Create mutation for '${tableName}' returned an incomplete primary-key identity.`);
7682
7683
  }
7683
7684
  return { createdRow };
7684
7685
  };
@@ -7698,6 +7699,7 @@ function useDataLoading({
7698
7699
  refetch,
7699
7700
  meta,
7700
7701
  tableMeta,
7702
+ writeCapability,
7701
7703
  tableSchema,
7702
7704
  fieldMetaMap,
7703
7705
  allRelationFields
@@ -7714,6 +7716,7 @@ function useDataLoading({
7714
7716
  refetch,
7715
7717
  meta,
7716
7718
  tableMeta,
7719
+ writeCapability,
7717
7720
  tableSchema,
7718
7721
  fieldMetaMap,
7719
7722
  allRelationFields
@@ -7731,7 +7734,8 @@ function buildTableSchema(metaTable) {
7731
7734
  if (!field) continue;
7732
7735
  columns.push(createColumnSchemaFromMeta(field));
7733
7736
  }
7734
- const primaryKeyFields = (metaTable.primaryKeyConstraints ?? []).flatMap((constraint) => constraint?.fields ?? []).map((field) => field?.name).filter((name) => Boolean(name));
7737
+ const identity = (0, import_data18.getRowIdentityDefinition)(metaTable);
7738
+ const primaryKeyFields = identity.status === "keyed" ? identity.fields.map((field) => field.fieldName) : [];
7735
7739
  const inflection = metaTable.inflection;
7736
7740
  const metadata = {
7737
7741
  label: metaTable.name ?? void 0,
@@ -7868,6 +7872,33 @@ function useSheets(props) {
7868
7872
  isInitialLoading: ctx.isLoading && rows.length === 0
7869
7873
  };
7870
7874
  }, [infiniteScroll, infiniteGridData, dataLoadingResult.contextValue]);
7875
+ const writeCapability = (0, import_react33.useMemo)(() => getSheetsWriteCapability(tableMeta), [tableMeta]);
7876
+ const canCreate = canRunSheetsMutation(writeCapability, "create");
7877
+ const canUpdate = canRunSheetsMutation(writeCapability, "update");
7878
+ const canDelete = canRunSheetsMutation(writeCapability, "delete");
7879
+ const primaryKeyFields = (0, import_react33.useMemo)(
7880
+ () => new Set(writeCapability?.status === "mutable" ? writeCapability.primaryKeyFields : []),
7881
+ [writeCapability]
7882
+ );
7883
+ const supportsScalarSelfCommit = writeCapability?.status === "mutable" && writeCapability.primaryKeyFields.length === 1 && writeCapability.primaryKeyFields[0] === "id";
7884
+ const readOnlyReason = writeCapability?.status === "read-only" ? "This table is read-only because it has no primary key." : null;
7885
+ const getRowIdentifier = (0, import_react33.useCallback)(
7886
+ (row) => {
7887
+ if (!tableMeta) return null;
7888
+ const resolution = resolveSheetsRowIdentity(tableMeta, row);
7889
+ return resolution.status === "identified" ? resolution.identifier : null;
7890
+ },
7891
+ [tableMeta]
7892
+ );
7893
+ const getRowId = (0, import_react33.useCallback)(
7894
+ (row, index) => {
7895
+ const draftMeta = getDraftMeta(row);
7896
+ if (draftMeta) return draftMeta.draftRowId;
7897
+ if (row && tableMeta) return sheetsRowKey(tableMeta, row, index);
7898
+ return `${tableMeta?.schemaName ?? ""}:${tableName}:row:${index}`;
7899
+ },
7900
+ [tableMeta, tableName]
7901
+ );
7871
7902
  const lastLoadEmitRef = (0, import_react33.useRef)(null);
7872
7903
  (0, import_react33.useEffect)(() => {
7873
7904
  if (dataError) {
@@ -8018,7 +8049,11 @@ function useSheets(props) {
8018
8049
  tableName,
8019
8050
  options: { relationChipLimit, relationLabelMaxLength },
8020
8051
  relationInfoByField,
8021
- meta: filterMeta
8052
+ meta: filterMeta,
8053
+ serverRowsReadOnly: !canUpdate,
8054
+ serverReadOnlyFields: primaryKeyFields,
8055
+ getRowIdentifier,
8056
+ supportsScalarSelfCommit
8022
8057
  });
8023
8058
  const effectiveColumnOrder = (0, import_react33.useMemo)(() => {
8024
8059
  if (columnKeys.length > 0) return columnKeys;
@@ -8080,9 +8115,11 @@ function useSheets(props) {
8080
8115
  const gridOpsOptions = (0, import_react33.useMemo)(
8081
8116
  () => ({
8082
8117
  onRemoveDraftRow: (draftRowId) => removeDraftRow(tableKey, draftRowId),
8118
+ getRowIdentifier,
8119
+ canDeleteServerRows: canDelete,
8083
8120
  feedback: operationFeedback
8084
8121
  }),
8085
- [removeDraftRow, tableKey, operationFeedback]
8122
+ [removeDraftRow, tableKey, getRowIdentifier, canDelete, operationFeedback]
8086
8123
  );
8087
8124
  const { deleteSelected: baseDeleteSelected } = useGridOperations(
8088
8125
  combinedRows,
@@ -8124,6 +8161,9 @@ function useSheets(props) {
8124
8161
  updateDraftCell,
8125
8162
  tableKey,
8126
8163
  update,
8164
+ getRowIdentifier,
8165
+ readOnlyFields: primaryKeyFields,
8166
+ canUpdate,
8127
8167
  onCellEdit,
8128
8168
  applyOptimisticPatch: applyOptimisticCellPatch
8129
8169
  });
@@ -8141,6 +8181,9 @@ function useSheets(props) {
8141
8181
  fieldMetaMap,
8142
8182
  relationInfoByField,
8143
8183
  update,
8184
+ getRowIdentifier,
8185
+ readOnlyFields: primaryKeyFields,
8186
+ canUpdate,
8144
8187
  applyOptimisticPatch: applyOptimisticCellPatch,
8145
8188
  resyncRow,
8146
8189
  editCell,
@@ -8178,6 +8221,7 @@ function useSheets(props) {
8178
8221
  if (infiniteScroll) infiniteGridData.invalidate();
8179
8222
  }, [infiniteScroll, infiniteGridData]);
8180
8223
  const handleRowAppended = (0, import_react33.useCallback)(async () => {
8224
+ if (!canCreate) return void 0;
8181
8225
  if (draftRows.length > 0) {
8182
8226
  return serverRowCount + draftRows.length - 1;
8183
8227
  }
@@ -8201,6 +8245,7 @@ function useSheets(props) {
8201
8245
  tableKey,
8202
8246
  draftRows,
8203
8247
  serverRowCount,
8248
+ canCreate,
8204
8249
  emit
8205
8250
  ]);
8206
8251
  const { selectedRowCount, selectedDraftRowEntries, hasDraftSelection } = useGridSelectionState({
@@ -8346,6 +8391,11 @@ function useSheets(props) {
8346
8391
  resizeColumn: gridActions.resizeColumn,
8347
8392
  frozenCount,
8348
8393
  selectedRowCount,
8394
+ canCreate,
8395
+ canUpdate,
8396
+ canDelete,
8397
+ readOnlyReason,
8398
+ getRowId,
8349
8399
  isSubmittingDrafts,
8350
8400
  submitDraftButtonDisabled,
8351
8401
  submitDraftLabel,
@@ -9332,7 +9382,7 @@ function parseNumeric(text) {
9332
9382
  const n = Number(trimmed);
9333
9383
  return Number.isFinite(n) ? { ok: true, value: n } : { ok: false, value: null };
9334
9384
  }
9335
- function InlineCellEditor({ value, initialText, numeric, onCommit, onCancel }) {
9385
+ function InlineCellEditor({ ariaLabel, value, initialText, numeric, onCommit, onCancel }) {
9336
9386
  const [text, setText] = (0, import_react36.useState)(() => initialText != null ? initialText : seedText(value));
9337
9387
  const inputRef = (0, import_react36.useRef)(null);
9338
9388
  const gridRef = (0, import_react36.useRef)(null);
@@ -9376,6 +9426,7 @@ function InlineCellEditor({ value, initialText, numeric, onCommit, onCancel }) {
9376
9426
  return /* @__PURE__ */ (0, import_jsx_runtime21.jsx)(
9377
9427
  "input",
9378
9428
  {
9429
+ "aria-label": ariaLabel,
9379
9430
  ref: inputRef,
9380
9431
  value: text,
9381
9432
  onChange: (e) => setText(e.target.value),
@@ -9492,15 +9543,15 @@ var SheetsCellHostInner = (0, import_react37.memo)(
9492
9543
  draftClasses,
9493
9544
  props.className
9494
9545
  ),
9495
- children: isDraftActionCell ? /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(
9546
+ children: isDraftActionCell ? draftAction ? /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(
9496
9547
  DraftActionCellView,
9497
9548
  {
9498
- status: draftAction?.status,
9499
- errored: draftAction?.errored,
9500
- disabled: draftAction?.disabled,
9549
+ status: draftAction.status,
9550
+ errored: draftAction.errored,
9551
+ disabled: draftAction.disabled,
9501
9552
  onSubmit: submitDraft
9502
9553
  }
9503
- ) : props.isEditing ? (
9554
+ ) : null : props.isEditing ? (
9504
9555
  // Inline (in-cell) edit for the simple text-representable types — a bare <input>
9505
9556
  // overlaying the view. `isEditing` is set true ONLY for inline-edit intents (the
9506
9557
  // shell short-circuits inline-toggle/overlay/none before here), so the cell kind is
@@ -9508,6 +9559,7 @@ var SheetsCellHostInner = (0, import_react37.memo)(
9508
9559
  /* @__PURE__ */ (0, import_jsx_runtime22.jsx)(
9509
9560
  InlineCellEditor,
9510
9561
  {
9562
+ ariaLabel: `Edit ${props.resolution.fieldMeta?.name ?? props.colKey}`,
9511
9563
  value: props.value,
9512
9564
  initialText: props.inlineInitialText,
9513
9565
  numeric: props.resolution.cell.kind === "number",
@@ -10333,14 +10385,14 @@ var import_toast2 = require("@constructive-io/ui/toast");
10333
10385
  // src/hooks/use-sheets-upload.ts
10334
10386
  var import_react49 = require("react");
10335
10387
  var import_react_query6 = require("@tanstack/react-query");
10336
- var import_data17 = require("@constructive-io/data");
10337
- var import_data18 = require("@constructive-io/data");
10388
+ var import_data19 = require("@constructive-io/data");
10389
+ var import_data20 = require("@constructive-io/data");
10338
10390
  function resolveUploadNaming(tableName, table) {
10339
10391
  return {
10340
- mutationName: (0, import_data18.toUpdateMutationName)(tableName, table),
10341
- singularName: (0, import_data18.toCamelCaseSingular)(tableName, table),
10342
- patchFieldName: (0, import_data18.toPatchFieldName)(tableName, table),
10343
- updateInputTypeName: (0, import_data18.toUpdateInputTypeName)(tableName)
10392
+ mutationName: (0, import_data20.toUpdateMutationName)(tableName, table),
10393
+ singularName: (0, import_data20.toCamelCaseSingular)(tableName, table),
10394
+ patchFieldName: (0, import_data20.toPatchFieldName)(tableName, table),
10395
+ updateInputTypeName: (0, import_data20.toUpdateInputTypeName)(tableName)
10344
10396
  };
10345
10397
  }
10346
10398
  function resolveTransport(endpoint, getToken, options) {
@@ -10417,7 +10469,7 @@ function useSheetsFieldUpload(tableName, fieldName, recordId, options = {}) {
10417
10469
  const table = (0, import_react49.useMemo)(() => {
10418
10470
  if (!meta?._meta?.tables) return null;
10419
10471
  const candidate = meta._meta.tables.find((item) => item?.name === tableName);
10420
- return candidate ? (0, import_data17.cleanTable)(candidate) : null;
10472
+ return candidate ? (0, import_data19.cleanTable)(candidate) : null;
10421
10473
  }, [meta, tableName]);
10422
10474
  const resolvedNaming = (0, import_react49.useMemo)(() => resolveUploadNaming(tableName, table), [tableName, table]);
10423
10475
  const getToken = (0, import_react49.useMemo)(() => {
@@ -10466,7 +10518,7 @@ function useSheetsImageUpload(tableName, fieldName, recordId, options = {}) {
10466
10518
  const table = (0, import_react49.useMemo)(() => {
10467
10519
  if (!meta?._meta?.tables) return null;
10468
10520
  const candidate = meta._meta.tables.find((item) => item?.name === tableName);
10469
- return candidate ? (0, import_data17.cleanTable)(candidate) : null;
10521
+ return candidate ? (0, import_data19.cleanTable)(candidate) : null;
10470
10522
  }, [meta, tableName]);
10471
10523
  const resolvedNaming = (0, import_react49.useMemo)(() => resolveUploadNaming(tableName, table), [tableName, table]);
10472
10524
  const getToken = (0, import_react49.useMemo)(() => {
@@ -10794,14 +10846,17 @@ var ImageEditor = ({
10794
10846
  import_toast2.toast.info({ message: "Creating row..." });
10795
10847
  setUploadState("submitting-draft");
10796
10848
  const result = await onSubmitDraft();
10797
- if (!result.createdRow?.id) throw new Error("Failed to create row");
10798
- committedRecordIdRef.current = result.createdRow.id;
10849
+ const createdId = result.createdRow?.id;
10850
+ if (typeof createdId !== "string" && typeof createdId !== "number") {
10851
+ throw new Error("Image uploads require a scalar id primary key.");
10852
+ }
10853
+ committedRecordIdRef.current = createdId;
10799
10854
  import_toast2.toast.info({ message: `Uploading ${noun}...` });
10800
10855
  setUploadState("uploading");
10801
10856
  const uploadResult = await executeFieldUpload(
10802
10857
  tableName,
10803
10858
  fieldName,
10804
- result.createdRow.id,
10859
+ createdId,
10805
10860
  selectedFile,
10806
10861
  config.endpoint,
10807
10862
  getToken,
@@ -11630,7 +11685,7 @@ function parseValue(text) {
11630
11685
  if (trimmed === "") return null;
11631
11686
  return Number(trimmed);
11632
11687
  }
11633
- function NumberEditorDom({ value, initialText, onCommit, onCancel }) {
11688
+ function NumberEditorDom({ value, initialText, colKey, fieldMeta, onCommit, onCancel }) {
11634
11689
  const [text, setText] = (0, import_react58.useState)(() => initialText != null ? initialText : seedText2(value));
11635
11690
  const escapedRef = (0, import_react58.useRef)(false);
11636
11691
  const parsed = parseValue(text);
@@ -11667,6 +11722,7 @@ function NumberEditorDom({ value, initialText, onCommit, onCancel }) {
11667
11722
  /* @__PURE__ */ (0, import_jsx_runtime43.jsx)(
11668
11723
  "input",
11669
11724
  {
11725
+ "aria-label": `Edit ${fieldMeta?.name ?? colKey}`,
11670
11726
  value: text,
11671
11727
  onChange: (e) => setText(e.target.value),
11672
11728
  onKeyDown: handleKeyDown,
@@ -11692,9 +11748,9 @@ var import_react_query8 = require("@tanstack/react-query");
11692
11748
  // src/hooks/use-sheets-table-cursor.ts
11693
11749
  var import_react59 = require("react");
11694
11750
  var import_react_query7 = require("@tanstack/react-query");
11695
- var import_data19 = require("@constructive-io/data");
11696
- var import_data20 = require("@constructive-io/data");
11697
11751
  var import_data21 = require("@constructive-io/data");
11752
+ var import_data22 = require("@constructive-io/data");
11753
+ var import_data23 = require("@constructive-io/data");
11698
11754
  function useSheetsTableCursor(tableName, options = {}) {
11699
11755
  const queryClient = (0, import_react_query7.useQueryClient)();
11700
11756
  const { execute, scopeKey } = useSheetsContext();
@@ -11702,7 +11758,7 @@ function useSheetsTableCursor(tableName, options = {}) {
11702
11758
  const adapter = useSheetsAdapter();
11703
11759
  const tables = (0, import_react59.useMemo)(() => {
11704
11760
  if (!meta?._meta?.tables) return [];
11705
- return meta._meta.tables.filter((candidate) => candidate != null).map((metaTable) => (0, import_data19.cleanTable)(metaTable));
11761
+ return meta._meta.tables.filter((candidate) => candidate != null).map((metaTable) => (0, import_data21.cleanTable)(metaTable));
11706
11762
  }, [meta]);
11707
11763
  const table = (0, import_react59.useMemo)(
11708
11764
  () => tables.find((candidate) => candidate.name === tableName) ?? null,
@@ -11734,7 +11790,7 @@ function useSheetsTableCursor(tableName, options = {}) {
11734
11790
  queryKey: sheetsQueryKeys.cursorTable(scopeKey, tableName, stableOptions),
11735
11791
  queryFn: async ({ pageParam }) => {
11736
11792
  if (!table) {
11737
- throw import_data20.createError.notFound(`Table '${tableName}' not found`);
11793
+ throw import_data22.createError.notFound(`Table '${tableName}' not found`);
11738
11794
  }
11739
11795
  const cursor = pageParam;
11740
11796
  const variableOptions = {
@@ -11757,7 +11813,7 @@ function useSheetsTableCursor(tableName, options = {}) {
11757
11813
  const validatedOrderByEnum = new Set(variables.orderBy ?? []);
11758
11814
  const availableOrderByFields = new Set(table.fields.map((field) => field.name));
11759
11815
  const validatedOrderBy = orderBy?.filter(
11760
- ({ field, direction }) => availableOrderByFields.has(field) && validatedOrderByEnum.has((0, import_data21.toOrderByEnumValue)(field, direction))
11816
+ ({ field, direction }) => availableOrderByFields.has(field) && validatedOrderByEnum.has((0, import_data23.toOrderByEnumValue)(field, direction))
11761
11817
  );
11762
11818
  const res = await adapter.listRows(
11763
11819
  { table, allTables: tables, tableName },
@@ -12419,7 +12475,7 @@ var import_button16 = require("@constructive-io/ui/button");
12419
12475
  init_overlay_presets();
12420
12476
  init_cn();
12421
12477
  var import_jsx_runtime47 = require("react/jsx-runtime");
12422
- function TextEditor({ value, initialText, onCommit, onCancel }) {
12478
+ function TextEditor({ value, initialText, colKey, fieldMeta, onCommit, onCancel }) {
12423
12479
  const [text, setText] = (0, import_react63.useState)(() => initialText != null ? initialText : String(value ?? ""));
12424
12480
  const escapedRef = (0, import_react63.useRef)(false);
12425
12481
  function handleKeyDown(e) {
@@ -12445,6 +12501,7 @@ function TextEditor({ value, initialText, onCommit, onCancel }) {
12445
12501
  /* @__PURE__ */ (0, import_jsx_runtime47.jsx)(
12446
12502
  "input",
12447
12503
  {
12504
+ "aria-label": `Edit ${fieldMeta?.name ?? colKey}`,
12448
12505
  value: text,
12449
12506
  onChange: (e) => setText(e.target.value),
12450
12507
  onKeyDown: handleKeyDown,
@@ -13431,10 +13488,6 @@ var Sheets = (0, import_react66.forwardRef)(SheetsInnerComponent);
13431
13488
  var EMPTY_OBJ = {};
13432
13489
  var noop = () => {
13433
13490
  };
13434
- function rowIdAt(rows, index) {
13435
- const id = rows[index]?.id;
13436
- return id != null ? String(id) : String(index);
13437
- }
13438
13491
  var OVERLAY_MARGIN_PX = 12;
13439
13492
  var OVERLAY_MIN_BELOW_PX = 320;
13440
13493
  function SheetsDomInner({
@@ -13496,6 +13549,7 @@ function SheetsDomInner({
13496
13549
  [columnSizing, resizeColumn]
13497
13550
  );
13498
13551
  const combinedRows = shell.combinedRows;
13552
+ const getRowId = shell.getRowId;
13499
13553
  const selection = s.selection.gridSelection;
13500
13554
  const setSelection = s.selection.setGridSelection;
13501
13555
  const activeCell = selection?.current?.cell;
@@ -13503,15 +13557,15 @@ function SheetsDomInner({
13503
13557
  if (!selection) return EMPTY_OBJ;
13504
13558
  const map = {};
13505
13559
  for (const index of selection.rows.toArray()) {
13506
- map[rowIdAt(combinedRows, index)] = true;
13560
+ map[getRowId(combinedRows[index], index)] = true;
13507
13561
  }
13508
13562
  return map;
13509
- }, [selection, combinedRows]);
13563
+ }, [selection, combinedRows, getRowId]);
13510
13564
  const onRowSelectionChange = (0, import_react66.useCallback)(
13511
13565
  (updater) => {
13512
13566
  const next = (0, import_react_table3.functionalUpdate)(updater, rowSelection);
13513
13567
  const indexById = /* @__PURE__ */ new Map();
13514
- for (let i = 0; i < combinedRows.length; i++) indexById.set(rowIdAt(combinedRows, i), i);
13568
+ for (let i = 0; i < combinedRows.length; i++) indexById.set(getRowId(combinedRows[i], i), i);
13515
13569
  let rows = RangeSet.empty();
13516
13570
  let lowest;
13517
13571
  for (const id of Object.keys(next)) {
@@ -13527,7 +13581,7 @@ function SheetsDomInner({
13527
13581
  }
13528
13582
  setSelection({ current: { cell: [0, lowest] }, rows, columns: RangeSet.empty() });
13529
13583
  },
13530
- [rowSelection, combinedRows, setSelection]
13584
+ [rowSelection, combinedRows, getRowId, setSelection]
13531
13585
  );
13532
13586
  const table = useSheetsTableInstance({
13533
13587
  columns,
@@ -13538,7 +13592,8 @@ function SheetsDomInner({
13538
13592
  onColumnSizingChange,
13539
13593
  // Pinning is shell-derived (frozenCount), never edited from the grid → no writer needed.
13540
13594
  onColumnPinningChange: noop,
13541
- onRowSelectionChange
13595
+ onRowSelectionChange,
13596
+ getRowId
13542
13597
  });
13543
13598
  const rowCount = combinedRows.length;
13544
13599
  const shiftAnchorRef = (0, import_react66.useRef)(null);
@@ -13853,7 +13908,7 @@ function SheetsDomInner({
13853
13908
  value: rowValue,
13854
13909
  cell: resolution.cell,
13855
13910
  colKey: active3.colKey,
13856
- rowId: String(combinedRows[active3.rowIndex]?.id ?? ""),
13911
+ rowId: getRowId(combinedRows[active3.rowIndex], active3.rowIndex),
13857
13912
  rowIndex: active3.rowIndex,
13858
13913
  tableName: props.tableName,
13859
13914
  fieldMeta: resolution.fieldMeta,
@@ -13952,9 +14007,10 @@ function SheetsDomInner({
13952
14007
  SheetsEmptyState,
13953
14008
  {
13954
14009
  tableName,
13955
- onAddRow: () => {
14010
+ readOnlyReason: shell.readOnlyReason,
14011
+ onAddRow: shell.canCreate ? () => {
13956
14012
  void s.draft.appendRow();
13957
- }
14013
+ } : void 0
13958
14014
  }
13959
14015
  );
13960
14016
  }
@@ -13976,7 +14032,9 @@ function SheetsDomInner({
13976
14032
  gridSelection: s.selection.gridSelection ?? null,
13977
14033
  setGridSelection: shell.setGridSelectionForControls,
13978
14034
  deleteSelected: s.draft.deleteSelected,
13979
- onAddRow: handleAddRow,
14035
+ onAddRow: shell.canCreate ? handleAddRow : void 0,
14036
+ canDelete: shell.canDelete,
14037
+ readOnlyReason: shell.readOnlyReason,
13980
14038
  onExport: handleExport
13981
14039
  }
13982
14040
  ) }),
@@ -14059,7 +14117,9 @@ function SheetsDomInner({
14059
14117
  isEnabled: isCommandEnabled,
14060
14118
  onAddRow: handleAddRow,
14061
14119
  onDeleteRows: s.draft.deleteSelected,
14062
- selectedRowCount: selection?.rows.length ?? 0
14120
+ selectedRowCount: selection?.rows.length ?? 0,
14121
+ canAddRows: shell.canCreate,
14122
+ canDeleteRows: shell.canDelete
14063
14123
  }
14064
14124
  )
14065
14125
  ] });
@@ -14104,17 +14164,21 @@ var BLUR_HEIGHT_MAX_PX = 140;
14104
14164
  var TableItem = (0, import_react68.memo)(function TableItem2({ table, activeTable, onTableSelect, itemRef }) {
14105
14165
  const isActive = activeTable === table.value;
14106
14166
  return /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(
14107
- "div",
14167
+ import_button20.Button,
14108
14168
  {
14109
14169
  ref: isActive ? itemRef : void 0,
14170
+ "aria-pressed": isActive,
14110
14171
  "data-testid": "table-item",
14172
+ static: true,
14173
+ size: "sm",
14174
+ type: "button",
14175
+ variant: "ghost",
14111
14176
  className: cn(
14112
- `group relative my-1 flex h-8 cursor-pointer items-center justify-between rounded-lg px-2 transition-all
14113
- duration-200`,
14177
+ "group relative my-1 flex h-8 w-full shrink items-center justify-between rounded-lg px-2 text-left text-xs font-normal transition-colors duration-150",
14114
14178
  isActive ? "bg-primary/10 text-foreground ring-primary/30 dark:bg-primary/15 dark:ring-primary/40 ring-1" : "text-muted-foreground hover:text-foreground"
14115
14179
  ),
14116
14180
  onClick: () => onTableSelect(table.value),
14117
- children: /* @__PURE__ */ (0, import_jsx_runtime53.jsx)("div", { className: "flex min-w-0 flex-1 items-center", children: /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(import_tooltip.Tooltip, { children: [
14181
+ children: /* @__PURE__ */ (0, import_jsx_runtime53.jsx)("span", { className: "flex min-w-0 flex-1 items-center", children: /* @__PURE__ */ (0, import_jsx_runtime53.jsxs)(import_tooltip.Tooltip, { children: [
14118
14182
  /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(import_tooltip.TooltipTrigger, { asChild: true, children: /* @__PURE__ */ (0, import_jsx_runtime53.jsx)("span", { className: "truncate text-xs", children: table.label }) }),
14119
14183
  /* @__PURE__ */ (0, import_jsx_runtime53.jsx)(import_tooltip.TooltipContent, { side: "right", align: "start", children: /* @__PURE__ */ (0, import_jsx_runtime53.jsx)("span", { className: "text-xs font-medium", children: table.label }) })
14120
14184
  ] }) })
@@ -14481,7 +14545,8 @@ function createScalarFieldSpec(metaField, options, uniqueFields, primaryFields)
14481
14545
  isArray: metaField.type.isArray,
14482
14546
  pgAlias: metaField.type.pgAlias,
14483
14547
  pgType: metaField.type.pgType,
14484
- subtype: metaField.type.subtype ?? void 0
14548
+ subtype: metaField.type.subtype ?? void 0,
14549
+ encoding: metaField.type.encoding
14485
14550
  });
14486
14551
  if (metaField.type.isArray) {
14487
14552
  return null;
@@ -14509,13 +14574,17 @@ function createScalarFieldSpec(metaField, options, uniqueFields, primaryFields)
14509
14574
  pgAlias: metaField.type.pgAlias ?? void 0,
14510
14575
  pgType: metaField.type.pgType ?? void 0,
14511
14576
  subtype: metaField.type.subtype ?? void 0,
14512
- typmod: metaField.type.typmod ?? void 0
14577
+ typmod: metaField.type.typmod ?? void 0,
14578
+ encoding: metaField.type.encoding ?? void 0
14513
14579
  },
14514
14580
  constraints: {
14515
14581
  isUnique: uniqueFields.has(metaField.name) || void 0,
14516
14582
  isPrimaryKey: primaryFields.has(metaField.name) || void 0
14517
14583
  }
14518
14584
  };
14585
+ if (metaField.enumValues?.values?.length) {
14586
+ spec.enumValues = [...metaField.enumValues.values];
14587
+ }
14519
14588
  if (maxLength != null) {
14520
14589
  spec.maxLength = maxLength;
14521
14590
  }
@@ -14539,6 +14608,7 @@ function createScalarFieldSpec(metaField, options, uniqueFields, primaryFields)
14539
14608
  return spec;
14540
14609
  }
14541
14610
  function buildDescription(metaField) {
14611
+ if (metaField.description) return metaField.description;
14542
14612
  const details = [];
14543
14613
  const { pgAlias, pgType, subtype } = metaField.type;
14544
14614
  if (pgAlias && pgAlias !== pgType) {
@@ -14556,6 +14626,7 @@ function humanize(name) {
14556
14626
  return name.replace(HUMAN_CASE_REGEX, "$1 $2").replace(/^./, (str) => str.toUpperCase());
14557
14627
  }
14558
14628
  function isFieldNullable(metaField) {
14629
+ if (metaField.isNotNull === true || metaField.type.isNotNull === true) return false;
14559
14630
  const gqlType = metaField.type.gqlType;
14560
14631
  if (gqlType.endsWith("!")) return false;
14561
14632
  return true;
@@ -15059,12 +15130,12 @@ function useSheetsLogin() {
15059
15130
  if (!token) {
15060
15131
  throw createInvalidCredentialsError();
15061
15132
  }
15062
- return { token, email: credentials.email };
15133
+ return { token, email: credentials.email, identityKey: signInResult.userId };
15063
15134
  },
15064
- onSuccess: ({ token }) => {
15135
+ onSuccess: ({ token, identityKey }) => {
15065
15136
  const databaseId = config.databaseId || "default";
15066
- setStoredToken(databaseId, token.accessToken, token.expiresAt);
15067
- storeApi.getState().setAuthenticated(token.accessToken, token.expiresAt);
15137
+ setStoredToken(databaseId, token.accessToken, token.expiresAt, identityKey);
15138
+ storeApi.getState().setAuthenticated(token.accessToken, token.expiresAt, identityKey);
15068
15139
  queryClient.invalidateQueries({ queryKey: ["sheets"] });
15069
15140
  }
15070
15141
  });
@@ -15109,13 +15180,13 @@ function useSheetsRegister() {
15109
15180
  );
15110
15181
  const signUpResult = result.signUp?.result;
15111
15182
  const token = signUpResult ? toAuthToken(signUpResult) : null;
15112
- return { token, email: formData.email };
15183
+ return { token, email: formData.email, identityKey: signUpResult?.userId ?? null };
15113
15184
  },
15114
- onSuccess: ({ token }) => {
15185
+ onSuccess: ({ token, identityKey }) => {
15115
15186
  if (token) {
15116
15187
  const databaseId = config.databaseId || "default";
15117
- setStoredToken(databaseId, token.accessToken, token.expiresAt);
15118
- storeApi.getState().setAuthenticated(token.accessToken, token.expiresAt);
15188
+ setStoredToken(databaseId, token.accessToken, token.expiresAt, identityKey);
15189
+ storeApi.getState().setAuthenticated(token.accessToken, token.expiresAt, identityKey);
15119
15190
  }
15120
15191
  queryClient.invalidateQueries({ queryKey: ["sheets"] });
15121
15192
  },