@constructive-io/sheets 0.3.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/README.md +19 -24
  2. package/dist/advanced.cjs +659 -474
  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-FNVHSOQQ.js → chunk-KKAWMVEG.js} +11 -11
  15. package/dist/chunk-KKAWMVEG.js.map +1 -0
  16. package/dist/{chunk-4PGPVMZB.js → chunk-KOZAW264.js} +4 -3
  17. package/dist/chunk-KOZAW264.js.map +1 -0
  18. package/dist/{chunk-ODUBS2NL.js → chunk-KVPVEXWB.js} +40 -17
  19. package/dist/chunk-KVPVEXWB.js.map +1 -0
  20. package/dist/{chunk-TU7ATZ4X.js → chunk-LR64FLWO.js} +301 -410
  21. package/dist/chunk-LR64FLWO.js.map +1 -0
  22. package/dist/chunk-ZETPUEXH.js +494 -0
  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 +1150 -703
  29. package/dist/index.cjs.map +1 -1
  30. package/dist/index.d.cts +123 -35
  31. package/dist/index.d.ts +123 -35
  32. package/dist/index.js +323 -99
  33. package/dist/index.js.map +1 -1
  34. package/dist/{sheets-context-CojEFlaY.d.cts → sheets-context-B03WDhZ9.d.cts} +36 -6
  35. package/dist/{sheets-context-Da55TTR9.d.ts → sheets-context-DmVCOgiX.d.ts} +36 -6
  36. package/dist/styles.css +6 -0
  37. package/dist/testing.cjs +476 -108
  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-4PGPVMZB.js.map +0 -1
  45. package/dist/chunk-FNVHSOQQ.js.map +0 -1
  46. package/dist/chunk-GLVZSPV2.js.map +0 -1
  47. package/dist/chunk-H4JJTMP5.js +0 -160
  48. package/dist/chunk-H4JJTMP5.js.map +0 -1
  49. package/dist/chunk-ODUBS2NL.js.map +0 -1
  50. package/dist/chunk-TU7ATZ4X.js.map +0 -1
  51. package/dist/date-editor-CXKKGNL6.js.map +0 -1
package/dist/advanced.cjs CHANGED
@@ -377,8 +377,10 @@ var init_date_editor = __esm({
377
377
  const isDateTimeType = dateType === "datetime" || dateType === "timestamptz";
378
378
  const handleDateSelect = (0, import_react3.useCallback)(
379
379
  (dateValue2) => {
380
- setSelectedDate(dateValue2);
381
- const jsDate = dateValueToDate(dateValue2);
380
+ if (Array.isArray(dateValue2)) return;
381
+ const selectedValue = dateValue2;
382
+ setSelectedDate(selectedValue);
383
+ const jsDate = dateValueToDate(selectedValue);
382
384
  if (jsDate) {
383
385
  if (isDateTimeType && currentDateValue) {
384
386
  const currentDate = new Date(currentDateValue);
@@ -1623,20 +1625,20 @@ function useSheetsStoreApi() {
1623
1625
  // src/hooks/use-sheets-upload.ts
1624
1626
  var import_react12 = require("react");
1625
1627
  var import_react_query3 = require("@tanstack/react-query");
1626
- var import_data9 = require("@constructive-io/data");
1628
+ var import_data11 = require("@constructive-io/data");
1627
1629
 
1628
1630
  // src/hooks/use-sheets-meta.ts
1629
1631
  var import_react_query2 = require("@tanstack/react-query");
1630
1632
 
1631
1633
  // src/adapter/postgraphile-adapter.ts
1632
- var import_data6 = require("@constructive-io/data");
1634
+ var import_data7 = require("@constructive-io/data");
1633
1635
 
1634
1636
  // src/hooks/use-sheets-table.ts
1635
1637
  var import_react11 = require("react");
1636
1638
  var import_react_query = require("@tanstack/react-query");
1637
- var import_data3 = require("@constructive-io/data");
1638
1639
  var import_data4 = require("@constructive-io/data");
1639
1640
  var import_data5 = require("@constructive-io/data");
1641
+ var import_data6 = require("@constructive-io/data");
1640
1642
 
1641
1643
  // src/hooks/query-keys.ts
1642
1644
  var sheetsQueryKeys = {
@@ -1862,14 +1864,56 @@ async function validateOrderByVariables(variables, table, scopeKey, queryClient,
1862
1864
  }
1863
1865
  }
1864
1866
 
1865
- // src/hooks/use-sheets-table.ts
1866
- function extractRowId(row) {
1867
- if (!row || typeof row !== "object") {
1868
- return null;
1867
+ // src/row-identity.ts
1868
+ var import_data3 = require("@constructive-io/data");
1869
+ function isLegacyScalarId(primaryKey) {
1870
+ const entries = Object.entries(primaryKey);
1871
+ return entries.length === 1 && entries[0][0] === "id" && (typeof entries[0][1] === "string" || typeof entries[0][1] === "number");
1872
+ }
1873
+ function resolveSheetsRowIdentity(table, row) {
1874
+ const resolution = (0, import_data3.resolveRowIdentity)(table, row);
1875
+ if (resolution.status === "read-only") {
1876
+ return { status: "unavailable", reason: "no-primary-key" };
1877
+ }
1878
+ if (resolution.status === "invalid-row") {
1879
+ return { status: "unavailable", reason: "invalid-row" };
1880
+ }
1881
+ const primaryKey = (0, import_data3.rowIdentityToPrimaryKey)(resolution.identity);
1882
+ return {
1883
+ status: "identified",
1884
+ identifier: isLegacyScalarId(primaryKey) ? primaryKey.id : primaryKey,
1885
+ primaryKey,
1886
+ key: (0, import_data3.serializeRowIdentity)(resolution.identity)
1887
+ };
1888
+ }
1889
+ function resolveSheetsIdentifier(table, identifier) {
1890
+ const row = typeof identifier === "object" && identifier !== null ? identifier : { id: identifier };
1891
+ return resolveSheetsRowIdentity(table, row);
1892
+ }
1893
+ function sheetsIdentifierToWhere(table, identifier) {
1894
+ const resolution = resolveSheetsIdentifier(table, identifier);
1895
+ if (resolution.status !== "identified") return null;
1896
+ return Object.fromEntries(
1897
+ Object.entries(resolution.primaryKey).map(([field, value]) => [field, { equalTo: value }])
1898
+ );
1899
+ }
1900
+ function sheetsIdentifierCacheKey(table, identifier) {
1901
+ const resolution = resolveSheetsIdentifier(table, identifier);
1902
+ if (resolution.status !== "identified") return null;
1903
+ return typeof resolution.identifier === "object" ? resolution.key : resolution.identifier;
1904
+ }
1905
+ function assertSheetsMutationAllowed(table, operation) {
1906
+ const capability = (0, import_data3.assessTableWriteCapability)(table);
1907
+ if (capability.status === "read-only") {
1908
+ throw new Error(`Table '${table.name}' is read-only because it has no primary key.`);
1909
+ }
1910
+ if (!capability.operations[operation]) {
1911
+ const article = operation === "update" ? "an" : "a";
1912
+ throw new Error(`Table '${table.name}' does not expose ${article} ${operation} mutation.`);
1869
1913
  }
1870
- const candidate = row.id;
1871
- return typeof candidate === "string" || typeof candidate === "number" ? candidate : null;
1872
1914
  }
1915
+
1916
+ // src/hooks/use-sheets-table.ts
1873
1917
  function transformRelationData(data, table) {
1874
1918
  if (!data) return [];
1875
1919
  if (!Array.isArray(data)) return data;
@@ -1921,10 +1965,10 @@ function transformToPostGraphileVariables(table, options = {}) {
1921
1965
  }
1922
1966
  if (options.orderBy && options.orderBy.length > 0) {
1923
1967
  const availableFields = new Set(table.fields.map((field) => field.name));
1924
- variables.orderBy = options.orderBy.filter(({ field }) => availableFields.has(field)).map(({ field, direction }) => (0, import_data5.toOrderByEnumValue)(field, direction));
1968
+ variables.orderBy = options.orderBy.filter(({ field }) => availableFields.has(field)).map(({ field, direction }) => (0, import_data6.toOrderByEnumValue)(field, direction));
1925
1969
  }
1926
1970
  if (options.where) {
1927
- variables.filter = options.where;
1971
+ variables.where = options.where;
1928
1972
  }
1929
1973
  return variables;
1930
1974
  }
@@ -1933,14 +1977,33 @@ function useSheetsTable(tableName, options = {}) {
1933
1977
  const { execute, scopeKey } = useSheetsContext();
1934
1978
  const { data: meta } = useSheetsMeta();
1935
1979
  const adapter = useSheetsAdapter();
1936
- const tables = (0, import_react11.useMemo)(() => {
1980
+ const metaTables = (0, import_react11.useMemo)(() => {
1937
1981
  if (!meta?._meta?.tables) return [];
1938
- return meta._meta.tables.filter((candidate) => candidate != null).map((metaTable) => (0, import_data3.cleanTable)(metaTable));
1982
+ return meta._meta.tables.filter((candidate) => candidate != null);
1939
1983
  }, [meta]);
1984
+ const tables = (0, import_react11.useMemo)(() => metaTables.map(import_data4.cleanTable), [metaTables]);
1940
1985
  const table = (0, import_react11.useMemo)(
1941
1986
  () => tables.find((candidate) => candidate.name === tableName) ?? null,
1942
1987
  [tables, tableName]
1943
1988
  );
1989
+ const tableMeta = (0, import_react11.useMemo)(
1990
+ () => metaTables.find((candidate) => candidate.name === tableName) ?? null,
1991
+ [metaTables, tableName]
1992
+ );
1993
+ const resolveIdentifier = (identifier) => {
1994
+ if (!tableMeta) throw import_data5.createError.notFound(`Table '${tableName}' not found`);
1995
+ const resolution = resolveSheetsIdentifier(tableMeta, identifier);
1996
+ if (resolution.status !== "identified") {
1997
+ throw import_data5.createError.badRequest(`Cannot resolve a primary-key identity for table '${tableName}'.`);
1998
+ }
1999
+ return resolution.identifier;
2000
+ };
2001
+ const rowCacheKey = (row) => {
2002
+ if (!tableMeta || !row) return null;
2003
+ const resolution = resolveSheetsRowIdentity(tableMeta, row);
2004
+ if (resolution.status !== "identified") return null;
2005
+ return typeof resolution.identifier === "object" ? resolution.key : resolution.identifier;
2006
+ };
1944
2007
  const { enabled = true, select: fieldSelection, mutationOptions = {}, ...queryOptions } = options;
1945
2008
  const finalQueryOptions = {
1946
2009
  ...queryOptions,
@@ -1955,7 +2018,7 @@ function useSheetsTable(tableName, options = {}) {
1955
2018
  queryKey: sheetsTableQueryKeys.tableRows(scopeKey, tableName, finalQueryOptions),
1956
2019
  queryFn: async () => {
1957
2020
  if (!table) {
1958
- throw import_data4.createError.notFound(`Table '${tableName}' not found`);
2021
+ throw import_data5.createError.notFound(`Table '${tableName}' not found`);
1959
2022
  }
1960
2023
  const variables = transformToPostGraphileVariables(table, finalQueryOptions);
1961
2024
  const [relationFieldMap] = await Promise.all([
@@ -1971,7 +2034,7 @@ function useSheetsTable(tableName, options = {}) {
1971
2034
  const validatedOrderByEnum = new Set(variables.orderBy ?? []);
1972
2035
  const availableOrderByFields = new Set(table.fields.map((field) => field.name));
1973
2036
  const validatedOrderBy = finalQueryOptions.orderBy?.filter(
1974
- ({ field, direction }) => availableOrderByFields.has(field) && validatedOrderByEnum.has((0, import_data5.toOrderByEnumValue)(field, direction))
2037
+ ({ field, direction }) => availableOrderByFields.has(field) && validatedOrderByEnum.has((0, import_data6.toOrderByEnumValue)(field, direction))
1975
2038
  );
1976
2039
  const { rows, totalCount: totalCount2 } = await adapter.listRows(
1977
2040
  { table, allTables: tables, tableName },
@@ -1997,10 +2060,11 @@ function useSheetsTable(tableName, options = {}) {
1997
2060
  const createMutation = (0, import_react_query.useMutation)({
1998
2061
  mutationKey: sheetsTableMutationKeys.create(scopeKey, tableName),
1999
2062
  mutationFn: async (data2) => {
2000
- if (!table) {
2001
- throw import_data4.createError.notFound(`Table '${tableName}' not found`);
2063
+ if (!table || !tableMeta) {
2064
+ throw import_data5.createError.notFound(`Table '${tableName}' not found`);
2002
2065
  }
2003
- const allTables = meta?._meta?.tables ? meta._meta.tables.filter((t) => t != null).map(import_data3.cleanTable) : [];
2066
+ assertSheetsMutationAllowed(tableMeta, "create");
2067
+ const allTables = meta?._meta?.tables ? meta._meta.tables.filter((t) => t != null).map(import_data4.cleanTable) : [];
2004
2068
  const createdRow = await adapter.createRow({ table, allTables, tableName }, data2, execute, {
2005
2069
  ...mutationOptions,
2006
2070
  fieldSelection: mutationOptions.fieldSelection || fieldSelection || "display"
@@ -2010,20 +2074,22 @@ function useSheetsTable(tableName, options = {}) {
2010
2074
  onSuccess: ({ createdRow }) => {
2011
2075
  queryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.table(scopeKey, tableName) });
2012
2076
  queryClient.invalidateQueries({ queryKey: sheetsQueryKeys.infiniteTable(scopeKey, tableName) });
2013
- const createdRowId = extractRowId(createdRow);
2014
- if (createdRowId !== null) {
2015
- queryClient.setQueryData(sheetsTableQueryKeys.tableRow(scopeKey, tableName, createdRowId), createdRow);
2077
+ const createdRowKey = rowCacheKey(createdRow);
2078
+ if (createdRowKey !== null) {
2079
+ queryClient.setQueryData(sheetsTableQueryKeys.tableRow(scopeKey, tableName, createdRowKey), createdRow);
2016
2080
  }
2017
2081
  }
2018
2082
  });
2019
2083
  const updateMutation = (0, import_react_query.useMutation)({
2020
2084
  mutationKey: sheetsTableMutationKeys.update(scopeKey, tableName),
2021
2085
  mutationFn: async ({ id, patch }) => {
2022
- if (!table) {
2023
- throw import_data4.createError.notFound(`Table '${tableName}' not found`);
2086
+ if (!table || !tableMeta) {
2087
+ throw import_data5.createError.notFound(`Table '${tableName}' not found`);
2024
2088
  }
2025
- const allTables = meta?._meta?.tables ? meta._meta.tables.filter((t) => t != null).map(import_data3.cleanTable) : [];
2026
- const updatedRow = await adapter.updateRow({ table, allTables, tableName }, id, patch, execute, {
2089
+ assertSheetsMutationAllowed(tableMeta, "update");
2090
+ const mutationIdentifier = resolveIdentifier(id);
2091
+ const allTables = meta?._meta?.tables ? meta._meta.tables.filter((t) => t != null).map(import_data4.cleanTable) : [];
2092
+ const updatedRow = await adapter.updateRow({ table, allTables, tableName }, mutationIdentifier, patch, execute, {
2027
2093
  ...mutationOptions,
2028
2094
  fieldSelection: mutationOptions.fieldSelection || fieldSelection || "display"
2029
2095
  });
@@ -2038,6 +2104,7 @@ function useSheetsTable(tableName, options = {}) {
2038
2104
  onMutate: async ({ id, patch }) => {
2039
2105
  const tablePrefix = sheetsTableQueryKeys.table(scopeKey, tableName);
2040
2106
  await queryClient.cancelQueries({ queryKey: tablePrefix });
2107
+ const targetKey = tableMeta ? sheetsIdentifierCacheKey(tableMeta, id) : null;
2041
2108
  const isRowsKey = (key) => key[key.length - 2] === "rows";
2042
2109
  const previousRows = queryClient.getQueriesData({ queryKey: tablePrefix }).filter(([key]) => isRowsKey(key));
2043
2110
  for (const [key] of previousRows) {
@@ -2045,7 +2112,7 @@ function useSheetsTable(tableName, options = {}) {
2045
2112
  if (!old) return old;
2046
2113
  let changed = false;
2047
2114
  const rows = old.rows.map((row) => {
2048
- if (extractRowId(row) === id) {
2115
+ if (targetKey !== null && rowCacheKey(row) === targetKey) {
2049
2116
  changed = true;
2050
2117
  return { ...row, ...patch };
2051
2118
  }
@@ -2061,51 +2128,58 @@ function useSheetsTable(tableName, options = {}) {
2061
2128
  },
2062
2129
  onSuccess: ({ updatedRow }) => {
2063
2130
  queryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.table(scopeKey, tableName) });
2064
- const updatedRowId = extractRowId(updatedRow);
2065
- if (updatedRowId !== null) {
2066
- queryClient.setQueryData(sheetsTableQueryKeys.tableRow(scopeKey, tableName, updatedRowId), updatedRow);
2131
+ const updatedRowKey = rowCacheKey(updatedRow);
2132
+ if (updatedRowKey !== null) {
2133
+ queryClient.setQueryData(sheetsTableQueryKeys.tableRow(scopeKey, tableName, updatedRowKey), updatedRow);
2067
2134
  }
2068
2135
  }
2069
2136
  });
2070
2137
  const deleteMutation = (0, import_react_query.useMutation)({
2071
2138
  mutationKey: sheetsTableMutationKeys.delete(scopeKey, tableName),
2072
2139
  mutationFn: async (idOrPk) => {
2073
- if (!table) {
2074
- throw import_data4.createError.notFound(`Table '${tableName}' not found`);
2140
+ if (!table || !tableMeta) {
2141
+ throw import_data5.createError.notFound(`Table '${tableName}' not found`);
2075
2142
  }
2076
- const allTables = meta?._meta?.tables ? meta._meta.tables.filter((t) => t != null).map(import_data3.cleanTable) : [];
2077
- await adapter.deleteRow({ table, allTables, tableName }, idOrPk, execute, mutationOptions);
2143
+ assertSheetsMutationAllowed(tableMeta, "delete");
2144
+ const mutationIdentifier = resolveIdentifier(idOrPk);
2145
+ const allTables = meta?._meta?.tables ? meta._meta.tables.filter((t) => t != null).map(import_data4.cleanTable) : [];
2146
+ await adapter.deleteRow({ table, allTables, tableName }, mutationIdentifier, execute, mutationOptions);
2078
2147
  return { deletedId: idOrPk, __rawResult: {} };
2079
2148
  },
2080
2149
  onSuccess: ({ deletedId }) => {
2081
2150
  queryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.table(scopeKey, tableName) });
2082
2151
  queryClient.invalidateQueries({ queryKey: sheetsQueryKeys.infiniteTable(scopeKey, tableName) });
2083
- if (deletedId && typeof deletedId !== "object") {
2152
+ const deletedRowKey = tableMeta ? sheetsIdentifierCacheKey(tableMeta, deletedId) : null;
2153
+ if (deletedRowKey !== null) {
2084
2154
  queryClient.removeQueries({
2085
- queryKey: sheetsTableQueryKeys.tableRow(scopeKey, tableName, deletedId)
2155
+ queryKey: sheetsTableQueryKeys.tableRow(scopeKey, tableName, deletedRowKey)
2086
2156
  });
2087
2157
  }
2088
2158
  }
2089
2159
  });
2090
2160
  const findOne = async (id) => {
2091
- if (!table) {
2092
- throw import_data4.createError.notFound(`Table '${tableName}' not found`);
2161
+ if (!table || !tableMeta) {
2162
+ throw import_data5.createError.notFound(`Table '${tableName}' not found`);
2163
+ }
2164
+ const where = sheetsIdentifierToWhere(tableMeta, id);
2165
+ if (!where) {
2166
+ throw import_data5.createError.badRequest(`Cannot resolve a primary-key identity for table '${tableName}'.`);
2093
2167
  }
2094
- const doc = (0, import_data5.buildSelect)(table, tables, {
2095
- where: { id: { equalTo: id } },
2168
+ const doc = (0, import_data6.buildSelect)(table, tables, {
2169
+ where,
2096
2170
  limit: 1
2097
2171
  });
2098
2172
  const variables = transformToPostGraphileVariables(table, {
2099
- where: { id: { equalTo: id } },
2173
+ where,
2100
2174
  limit: 1
2101
2175
  });
2102
2176
  const result = await execute(doc, variables);
2103
- const singularName = (0, import_data5.toCamelCaseSingular)(tableName, table);
2177
+ const singularName = (0, import_data6.toCamelCaseSingular)(tableName, table);
2104
2178
  const singularData = result[singularName];
2105
2179
  if (singularData && typeof singularData === "object") {
2106
2180
  return singularData;
2107
2181
  }
2108
- const queryTableName = (0, import_data5.toCamelCasePlural)(tableName, table);
2182
+ const queryTableName = (0, import_data6.toCamelCasePlural)(tableName, table);
2109
2183
  const data2 = result[queryTableName];
2110
2184
  if (data2 && typeof data2 === "object" && "nodes" in data2) {
2111
2185
  const nodes = data2.nodes || [];
@@ -2146,319 +2220,83 @@ function useSheetsTable(tableName, options = {}) {
2146
2220
  }
2147
2221
 
2148
2222
  // src/adapter/postgraphile-adapter.ts
2149
- var MetaDoc = new import_data6.TypedDocumentString(`
2150
- query Meta {
2151
- _meta {
2152
- tables {
2153
- name
2154
- schemaName
2155
- query {
2156
- all
2157
- create
2158
- delete
2159
- one
2160
- update
2161
- }
2162
- fields {
2163
- name
2164
- isNotNull
2165
- hasDefault
2166
- type {
2167
- gqlType
2168
- isArray
2169
- pgType
2170
- isNotNull
2171
- hasDefault
2172
- subtype
2173
- }
2174
- }
2175
- inflection {
2176
- allRows
2177
- conditionType
2178
- connection
2179
- createInputType
2180
- createPayloadType
2181
- deletePayloadType
2182
- edge
2183
- filterType
2184
- orderByType
2185
- patchType
2186
- tableType
2187
- updatePayloadType
2188
- }
2189
- indexes {
2190
- name
2191
- isUnique
2192
- fields {
2193
- name
2194
- type {
2195
- gqlType
2196
- isArray
2197
- pgType
2198
- }
2199
- }
2200
- }
2201
- constraints {
2202
- primaryKey {
2203
- name
2204
- fields {
2205
- name
2206
- type {
2207
- gqlType
2208
- isArray
2209
- pgType
2210
- }
2211
- }
2212
- }
2213
- unique {
2214
- name
2215
- fields {
2216
- name
2217
- type {
2218
- gqlType
2219
- isArray
2220
- pgType
2221
- }
2222
- }
2223
- }
2224
- foreignKey {
2225
- name
2226
- fields {
2227
- name
2228
- type {
2229
- gqlType
2230
- isArray
2231
- pgType
2232
- }
2233
- }
2234
- refFields {
2235
- name
2236
- type {
2237
- gqlType
2238
- isArray
2239
- pgType
2240
- }
2241
- }
2242
- refTable {
2243
- name
2244
- }
2245
- }
2246
- }
2247
- foreignKeyConstraints {
2248
- name
2249
- fields {
2250
- name
2251
- type {
2252
- gqlType
2253
- isArray
2254
- pgType
2255
- }
2256
- }
2257
- refFields {
2258
- name
2259
- type {
2260
- gqlType
2261
- isArray
2262
- pgType
2263
- }
2264
- }
2265
- refTable {
2266
- name
2267
- }
2268
- }
2269
- primaryKeyConstraints {
2270
- name
2271
- fields {
2272
- name
2273
- type {
2274
- gqlType
2275
- isArray
2276
- pgType
2277
- }
2278
- }
2279
- }
2280
- uniqueConstraints {
2281
- name
2282
- fields {
2283
- name
2284
- type {
2285
- gqlType
2286
- isArray
2287
- pgType
2288
- }
2289
- }
2290
- }
2291
- relations {
2292
- belongsTo {
2293
- fieldName
2294
- isUnique
2295
- keys {
2296
- name
2297
- type {
2298
- gqlType
2299
- isArray
2300
- pgType
2301
- }
2302
- }
2303
- references {
2304
- name
2305
- }
2306
- type
2307
- }
2308
- has {
2309
- fieldName
2310
- isUnique
2311
- keys {
2312
- name
2313
- type {
2314
- gqlType
2315
- isArray
2316
- pgType
2317
- }
2318
- }
2319
- referencedBy {
2320
- name
2321
- }
2322
- type
2323
- }
2324
- hasOne {
2325
- fieldName
2326
- isUnique
2327
- keys {
2328
- name
2329
- type {
2330
- gqlType
2331
- isArray
2332
- pgType
2333
- }
2334
- }
2335
- referencedBy {
2336
- name
2337
- }
2338
- type
2339
- }
2340
- hasMany {
2341
- fieldName
2342
- isUnique
2343
- keys {
2344
- name
2345
- type {
2346
- gqlType
2347
- isArray
2348
- pgType
2349
- }
2350
- }
2351
- referencedBy {
2352
- name
2353
- }
2354
- type
2355
- }
2356
- manyToMany {
2357
- fieldName
2358
- junctionLeftConstraint {
2359
- name
2360
- fields {
2361
- name
2362
- type {
2363
- gqlType
2364
- isArray
2365
- pgType
2366
- }
2367
- }
2368
- refFields {
2369
- name
2370
- type {
2371
- gqlType
2372
- isArray
2373
- pgType
2374
- }
2375
- }
2376
- refTable {
2377
- name
2378
- }
2379
- }
2380
- junctionLeftKeyAttributes {
2381
- name
2382
- type {
2383
- gqlType
2384
- isArray
2385
- pgType
2386
- }
2387
- }
2388
- junctionRightConstraint {
2389
- name
2390
- fields {
2391
- name
2392
- type {
2393
- gqlType
2394
- isArray
2395
- pgType
2396
- }
2397
- }
2398
- refFields {
2399
- name
2400
- type {
2401
- gqlType
2402
- isArray
2403
- pgType
2404
- }
2405
- }
2406
- refTable {
2407
- name
2408
- }
2409
- }
2410
- junctionRightKeyAttributes {
2411
- name
2412
- type {
2413
- gqlType
2414
- isArray
2415
- pgType
2416
- }
2417
- }
2418
- junctionTable {
2419
- name
2420
- }
2421
- leftKeyAttributes {
2422
- name
2423
- type {
2424
- gqlType
2425
- isArray
2426
- pgType
2427
- }
2428
- }
2429
- rightKeyAttributes {
2430
- name
2431
- type {
2432
- gqlType
2433
- isArray
2434
- pgType
2435
- }
2436
- }
2437
- rightTable {
2438
- name
2439
- }
2440
- type
2441
- }
2442
- }
2443
- }
2444
- }
2445
- }
2446
- `);
2223
+ var compatibilityChecks = /* @__PURE__ */ new WeakMap();
2224
+ var enumMappings = /* @__PURE__ */ new WeakMap();
2225
+ async function ensureCurrentMetaContract(execute) {
2226
+ const cached = compatibilityChecks.get(execute);
2227
+ if (cached) return cached;
2228
+ const check = execute(import_data7.META_CONTRACT_INTROSPECTION_DOCUMENT).then(
2229
+ (result) => {
2230
+ (0, import_data7.assertMetaContract)(result);
2231
+ }
2232
+ );
2233
+ compatibilityChecks.set(execute, check);
2234
+ try {
2235
+ await check;
2236
+ } catch (error) {
2237
+ if (compatibilityChecks.get(execute) === check) compatibilityChecks.delete(execute);
2238
+ throw error;
2239
+ }
2240
+ }
2241
+ function hasDeclaredEnums(meta) {
2242
+ return Boolean(meta._meta?.tables?.some(
2243
+ (table) => table?.fields?.some((field) => Boolean(field?.enumValues?.name))
2244
+ ));
2245
+ }
2246
+ function schemaCompatibilityError(missingPaths) {
2247
+ const detail = missingPaths.length > 0 ? ` Missing: ${missingPaths.join(", ")}.` : "";
2248
+ return import_data7.createError.badRequest(
2249
+ `The GraphQL schema does not match the enum values declared by Constructive _meta.${detail}`,
2250
+ "SCHEMA_INTROSPECTION_INCOMPATIBLE"
2251
+ );
2252
+ }
2253
+ function normalizeMutationEnums(ctx, input, execute) {
2254
+ const hasEnumInput = ctx.table.fields.some(
2255
+ (field) => Boolean(field.enumValues?.length) && Object.prototype.hasOwnProperty.call(input, field.name)
2256
+ );
2257
+ if (!hasEnumInput) return input;
2258
+ const mappings = enumMappings.get(execute);
2259
+ if (!mappings) {
2260
+ throw import_data7.createError.badRequest(
2261
+ "Enum schema mappings are unavailable. Load table metadata before mutating enum fields.",
2262
+ "ENUM_MAPPING_UNAVAILABLE"
2263
+ );
2264
+ }
2265
+ return (0, import_data7.normalizeSchemaEnumInputValues)(input, ctx.table, mappings);
2266
+ }
2447
2267
  function createPostGraphileAdapter() {
2448
2268
  return {
2449
2269
  async fetchMeta(execute) {
2450
- return await execute(MetaDoc);
2270
+ await ensureCurrentMetaContract(execute);
2271
+ const meta = await execute(import_data7.META_DOCUMENT);
2272
+ (0, import_data7.assertMetaQuery)(meta);
2273
+ if (!hasDeclaredEnums(meta)) {
2274
+ enumMappings.set(execute, []);
2275
+ return meta;
2276
+ }
2277
+ try {
2278
+ const introspection = await execute(import_data7.SCHEMA_INTROSPECTION_QUERY);
2279
+ const analysis = (0, import_data7.analyzeSchemaIntrospectionCompatibility)(introspection, meta);
2280
+ if (analysis.status !== "compatible") {
2281
+ throw schemaCompatibilityError(analysis.missingPaths);
2282
+ }
2283
+ enumMappings.set(execute, analysis.enumMappings);
2284
+ } catch (error) {
2285
+ enumMappings.delete(execute);
2286
+ throw error;
2287
+ }
2288
+ return meta;
2451
2289
  },
2452
2290
  async listRows(ctx, query, execute) {
2453
2291
  const { table, allTables, tableName } = ctx;
2454
2292
  const { relationFieldMap, ...queryOptions } = query;
2455
2293
  const variables = transformToPostGraphileVariables(table, queryOptions);
2456
- const doc = (0, import_data6.buildSelect)(table, allTables, {
2294
+ const doc = (0, import_data7.buildSelect)(table, allTables, {
2457
2295
  ...queryOptions,
2458
2296
  relationFieldMap
2459
2297
  });
2460
2298
  const result = await execute(doc, variables);
2461
- const queryTableName = (0, import_data6.toCamelCasePlural)(tableName, table);
2299
+ const queryTableName = (0, import_data7.toCamelCasePlural)(tableName, table);
2462
2300
  const connection = result[queryTableName];
2463
2301
  if (connection && typeof connection === "object" && "nodes" in connection) {
2464
2302
  const nodes = connection.nodes || [];
@@ -2471,54 +2309,56 @@ function createPostGraphileAdapter() {
2471
2309
  const directData = connection || [];
2472
2310
  return {
2473
2311
  rows: transformRelationData(directData, table),
2474
- // Non-Relay direct-array response: page length only, not a full filtered count.
2475
2312
  totalCount: directData.length
2476
2313
  };
2477
2314
  },
2478
2315
  async createRow(ctx, data, execute, options = {}) {
2479
2316
  const { table, allTables, tableName } = ctx;
2480
- const doc = (0, import_data6.buildPostGraphileCreate)(table, allTables, {
2317
+ const doc = (0, import_data7.buildPostGraphileCreate)(table, allTables, {
2481
2318
  ...options,
2482
2319
  fieldSelection: options.fieldSelection || "display"
2483
2320
  });
2484
- const singularName = (0, import_data6.toCamelCaseSingular)(tableName, table);
2485
- const sanitizedData = (0, import_data6.prepareCreateInput)(data);
2321
+ const singularName = (0, import_data7.toCamelCaseSingular)(tableName, table);
2322
+ const sanitizedData = normalizeMutationEnums(
2323
+ ctx,
2324
+ (0, import_data7.prepareCreateInput)(data),
2325
+ execute
2326
+ );
2486
2327
  const variables = {
2487
2328
  input: {
2488
2329
  [singularName]: sanitizedData
2489
2330
  }
2490
2331
  };
2491
2332
  const result = await execute(doc, variables);
2492
- const mutationName = (0, import_data6.toCreateMutationName)(tableName, table);
2333
+ const mutationName = (0, import_data7.toCreateMutationName)(tableName, table);
2493
2334
  const createdRow = result[mutationName]?.[singularName] ?? null;
2494
2335
  return createdRow;
2495
2336
  },
2496
2337
  async updateRow(ctx, id, patch, execute, options = {}) {
2497
2338
  const { table, allTables, tableName } = ctx;
2498
- const doc = (0, import_data6.buildPostGraphileUpdate)(table, allTables, {
2339
+ const doc = (0, import_data7.buildPostGraphileUpdate)(table, allTables, {
2499
2340
  ...options,
2500
2341
  fieldSelection: options.fieldSelection || "display"
2501
2342
  });
2502
- const patchFieldName = (0, import_data6.toPatchFieldName)(tableName, table);
2503
- const sanitizedPatch = (0, import_data6.prepareUpdateInput)(patch);
2504
- if (Object.keys(sanitizedPatch).length === 0) {
2505
- return null;
2506
- }
2343
+ const patchFieldName = (0, import_data7.toPatchFieldName)(tableName, table);
2344
+ const sanitizedPatch = (0, import_data7.prepareUpdateInput)(patch);
2345
+ if (Object.keys(sanitizedPatch).length === 0) return null;
2346
+ const normalizedPatch = normalizeMutationEnums(ctx, sanitizedPatch, execute);
2507
2347
  const variables = {
2508
2348
  input: {
2509
- id,
2510
- [patchFieldName]: sanitizedPatch
2349
+ ...typeof id === "object" ? id : { id },
2350
+ [patchFieldName]: normalizedPatch
2511
2351
  }
2512
2352
  };
2513
2353
  const result = await execute(doc, variables);
2514
- const mutationName = (0, import_data6.toUpdateMutationName)(tableName, table);
2515
- const singularName = (0, import_data6.toCamelCaseSingular)(tableName, table);
2354
+ const mutationName = (0, import_data7.toUpdateMutationName)(tableName, table);
2355
+ const singularName = (0, import_data7.toCamelCaseSingular)(tableName, table);
2516
2356
  const updatedRow = result[mutationName]?.[singularName] ?? null;
2517
2357
  return updatedRow;
2518
2358
  },
2519
2359
  async deleteRow(ctx, id, execute, options = {}) {
2520
2360
  const { table, allTables } = ctx;
2521
- const doc = (0, import_data6.buildPostGraphileDelete)(table, allTables, options);
2361
+ const doc = (0, import_data7.buildPostGraphileDelete)(table, allTables, options);
2522
2362
  const variables = {
2523
2363
  input: typeof id === "object" ? id : { id }
2524
2364
  };
@@ -2554,20 +2394,346 @@ function useSheetsMeta(options = {}) {
2554
2394
  }
2555
2395
 
2556
2396
  // src/hooks/use-sheets-upload.ts
2557
- var import_data10 = require("@constructive-io/data");
2397
+ var import_data12 = require("@constructive-io/data");
2558
2398
 
2559
2399
  // src/context/sheets-execute.ts
2400
+ var import_graphql2 = require("graphql");
2401
+ var import_data9 = require("@constructive-io/data");
2402
+
2403
+ // src/context/sheets-upload-presigned.ts
2560
2404
  var import_graphql = require("graphql");
2561
- var import_data7 = require("@constructive-io/data");
2562
2405
  var import_data8 = require("@constructive-io/data");
2406
+ async function sha256HexFromBuffer(buffer) {
2407
+ if (!globalThis.crypto?.subtle) {
2408
+ throw import_data8.createError.badRequest("Web Crypto (crypto.subtle) is unavailable; cannot hash file for upload.");
2409
+ }
2410
+ const digest = await crypto.subtle.digest("SHA-256", buffer);
2411
+ const bytes = new Uint8Array(digest);
2412
+ let hex = "";
2413
+ for (let i = 0; i < bytes.length; i++) {
2414
+ hex += bytes[i].toString(16).padStart(2, "0");
2415
+ }
2416
+ return hex;
2417
+ }
2418
+ var capabilityCache = /* @__PURE__ */ new Map();
2419
+ function discoverUploadCapability(endpoint, execute) {
2420
+ const cached = capabilityCache.get(endpoint);
2421
+ if (cached) return cached;
2422
+ const promise = (async () => {
2423
+ const data = await execute((0, import_graphql.getIntrospectionQuery)());
2424
+ const schema = data?.__schema;
2425
+ if (!schema) {
2426
+ throw import_data8.createError.badRequest("Uploads are not enabled for this endpoint.");
2427
+ }
2428
+ return resolveUploadCapability(schema);
2429
+ })();
2430
+ promise.catch(() => capabilityCache.delete(endpoint));
2431
+ capabilityCache.set(endpoint, promise);
2432
+ return promise;
2433
+ }
2434
+ function namedTypeName(ref) {
2435
+ let cur = ref;
2436
+ while (cur && (cur.kind === "NON_NULL" || cur.kind === "LIST")) {
2437
+ cur = cur.ofType ?? null;
2438
+ }
2439
+ return cur?.name ?? null;
2440
+ }
2441
+ function isListTypeRef(ref) {
2442
+ let cur = ref;
2443
+ while (cur && cur.kind === "NON_NULL") {
2444
+ cur = cur.ofType ?? null;
2445
+ }
2446
+ return cur?.kind === "LIST";
2447
+ }
2448
+ var PK_FIELD_NAME = "id";
2449
+ function resolveUploadCapability(schema) {
2450
+ const typeByName = /* @__PURE__ */ new Map();
2451
+ for (const t of schema.types) {
2452
+ if (t.name) typeByName.set(t.name, t);
2453
+ }
2454
+ const objectHasFields = (typeName, names) => {
2455
+ if (!typeName) return false;
2456
+ const t = typeByName.get(typeName);
2457
+ if (!t?.fields) return false;
2458
+ const present = new Set(t.fields.map((f) => f.name));
2459
+ return names.every((n) => present.has(n));
2460
+ };
2461
+ const inputHasFields = (typeName, names) => {
2462
+ if (!typeName) return false;
2463
+ const t = typeByName.get(typeName);
2464
+ if (!t?.inputFields) return false;
2465
+ const present = new Set(t.inputFields.map((f) => f.name));
2466
+ return names.every((n) => present.has(n));
2467
+ };
2468
+ const PAYLOAD_FIELDS = ["uploadUrl", "fileId", "deduplicated"];
2469
+ const INPUT_FIELDS = ["contentHash", "bucketKey", "contentType", "size"];
2470
+ const mutationType = schema.mutationType ? typeByName.get(schema.mutationType.name) : null;
2471
+ const queryType = schema.queryType ? typeByName.get(schema.queryType.name) : null;
2472
+ let upload = null;
2473
+ for (const field of mutationType?.fields ?? []) {
2474
+ const inputArg = field.args.find((a) => a.name === "input");
2475
+ if (!inputArg) continue;
2476
+ const inputTypeName = namedTypeName(inputArg.type);
2477
+ const payloadTypeName = namedTypeName(field.type);
2478
+ if (inputHasFields(inputTypeName, INPUT_FIELDS) && objectHasFields(payloadTypeName, PAYLOAD_FIELDS)) {
2479
+ upload = { uploadFieldName: field.name, inputTypeName };
2480
+ break;
2481
+ }
2482
+ }
2483
+ if (!upload) {
2484
+ throw import_data8.createError.badRequest("Uploads are not enabled for this endpoint.");
2485
+ }
2486
+ const downloadById = resolveDownloadByIdField(schema, typeByName, queryType, upload.uploadFieldName);
2487
+ return {
2488
+ ...upload,
2489
+ ...downloadById
2490
+ };
2491
+ }
2492
+ function resolveDownloadByIdField(schema, typeByName, queryType, uploadFieldName) {
2493
+ const fileTypesWithDownloadUrl = /* @__PURE__ */ new Set();
2494
+ for (const t of schema.types) {
2495
+ if (t.kind === "OBJECT" && t.name && t.fields?.some((f) => f.name === "downloadUrl")) {
2496
+ fileTypesWithDownloadUrl.add(t.name);
2497
+ }
2498
+ }
2499
+ for (const field of queryType?.fields ?? []) {
2500
+ const returnTypeName = namedTypeName(field.type);
2501
+ if (!returnTypeName || !fileTypesWithDownloadUrl.has(returnTypeName)) continue;
2502
+ if (field.args.length === 1 && field.args[0].name === PK_FIELD_NAME) {
2503
+ return {
2504
+ fileByIdField: field.name,
2505
+ fileByIdArgName: "id",
2506
+ fileTypeName: returnTypeName,
2507
+ idScalarName: namedTypeName(field.args[0].type) ?? void 0
2508
+ };
2509
+ }
2510
+ }
2511
+ const connection = resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, uploadFieldName);
2512
+ if (connection) return connection;
2513
+ const nodeField = queryType?.fields?.find(
2514
+ (f) => f.name === "node" && f.args.some((a) => a.name === "nodeId")
2515
+ );
2516
+ if (nodeField && fileTypesWithDownloadUrl.size > 0) {
2517
+ const preferred = uploadFieldName.replace(/^upload/, "");
2518
+ const fileTypeName = fileTypesWithDownloadUrl.has(preferred) ? preferred : [...fileTypesWithDownloadUrl][0];
2519
+ return { fileByIdField: "node", fileByIdArgName: "nodeId", fileTypeName };
2520
+ }
2521
+ throw import_data8.createError.badRequest("Uploads are not enabled for this endpoint.");
2522
+ }
2523
+ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, uploadFieldName) {
2524
+ const EQUALITY_OPERATORS = ["equalTo", "eq"];
2525
+ const candidates = [];
2526
+ for (const field of queryType?.fields ?? []) {
2527
+ const connTypeName = namedTypeName(field.type);
2528
+ if (!connTypeName) continue;
2529
+ const connType = typeByName.get(connTypeName);
2530
+ if (connType?.kind !== "OBJECT" || !connType.fields) continue;
2531
+ const nodesField = connType.fields.find((f) => {
2532
+ if (!isListTypeRef(f.type)) return false;
2533
+ const elem = namedTypeName(f.type);
2534
+ return elem != null && fileTypesWithDownloadUrl.has(elem);
2535
+ });
2536
+ if (!nodesField) continue;
2537
+ const fileTypeName = namedTypeName(nodesField.type);
2538
+ for (const arg of field.args) {
2539
+ const filterTypeName = namedTypeName(arg.type);
2540
+ const filterType = filterTypeName ? typeByName.get(filterTypeName) : null;
2541
+ if (filterType?.kind !== "INPUT_OBJECT" || !filterType.inputFields) continue;
2542
+ const idField = filterType.inputFields.find((f) => f.name === PK_FIELD_NAME);
2543
+ if (!idField) continue;
2544
+ const idFieldTypeName = namedTypeName(idField.type);
2545
+ const idFieldType = idFieldTypeName ? typeByName.get(idFieldTypeName) : null;
2546
+ if (idFieldType?.kind === "INPUT_OBJECT" && idFieldType.inputFields) {
2547
+ const opField = EQUALITY_OPERATORS.map(
2548
+ (op) => idFieldType.inputFields.find((f) => f.name === op)
2549
+ ).find((f) => f != null);
2550
+ if (opField) {
2551
+ candidates.push({
2552
+ fileByIdField: field.name,
2553
+ fileByIdArgName: "connection",
2554
+ fileTypeName,
2555
+ idScalarName: namedTypeName(opField.type) ?? void 0,
2556
+ connectionFilterArgName: arg.name,
2557
+ connectionIdField: idField.name,
2558
+ connectionIdOperator: opField.name,
2559
+ connectionNodesField: nodesField.name
2560
+ });
2561
+ break;
2562
+ }
2563
+ continue;
2564
+ }
2565
+ if (idFieldType?.kind === "SCALAR" || !idFieldType && idFieldTypeName) {
2566
+ candidates.push({
2567
+ fileByIdField: field.name,
2568
+ fileByIdArgName: "connection",
2569
+ fileTypeName,
2570
+ idScalarName: idFieldTypeName ?? void 0,
2571
+ connectionFilterArgName: arg.name,
2572
+ connectionIdField: idField.name,
2573
+ connectionNodesField: nodesField.name
2574
+ });
2575
+ break;
2576
+ }
2577
+ }
2578
+ }
2579
+ if (candidates.length === 0) return null;
2580
+ const preferred = uploadFieldName.replace(/^upload/, "");
2581
+ return candidates.find((c) => c.fileTypeName === preferred) ?? candidates[0];
2582
+ }
2583
+ async function callUploadOp(execute, cap, input) {
2584
+ const mutation = `
2585
+ mutation SheetsUpload($input: ${cap.inputTypeName}!) {
2586
+ ${cap.uploadFieldName}(input: $input) {
2587
+ uploadUrl
2588
+ fileId
2589
+ key
2590
+ deduplicated
2591
+ }
2592
+ }
2593
+ `.trim();
2594
+ const data = await execute(mutation, {
2595
+ input: {
2596
+ bucketKey: input.bucketKey,
2597
+ contentHash: input.contentHash,
2598
+ contentType: input.contentType,
2599
+ size: input.size,
2600
+ filename: input.filename
2601
+ }
2602
+ });
2603
+ const payload = data?.[cap.uploadFieldName];
2604
+ if (!payload) {
2605
+ throw import_data8.createError.badRequest("Upload failed: no payload returned from upload mutation.");
2606
+ }
2607
+ return payload;
2608
+ }
2609
+ async function presignedPut(url, buffer, contentType, onProgress) {
2610
+ const total = buffer.byteLength;
2611
+ if (onProgress && typeof XMLHttpRequest !== "undefined") {
2612
+ await putWithXHR(url, buffer, contentType, total, onProgress);
2613
+ return;
2614
+ }
2615
+ let response;
2616
+ try {
2617
+ response = await fetch(url, {
2618
+ method: "PUT",
2619
+ headers: { "Content-Type": contentType },
2620
+ body: buffer
2621
+ });
2622
+ } catch (error) {
2623
+ throw import_data8.createError.network(error instanceof Error ? error : void 0);
2624
+ }
2625
+ if (!response.ok) {
2626
+ const body = await response.text().catch(() => "");
2627
+ throw import_data8.createError.badRequest(`Upload failed: ${response.status} ${response.statusText}${body ? ` \u2014 ${body}` : ""}`);
2628
+ }
2629
+ onProgress?.({ loaded: total, total, percentage: 100 });
2630
+ }
2631
+ function putWithXHR(url, buffer, contentType, total, onProgress) {
2632
+ return new Promise((resolve, reject) => {
2633
+ const xhr = new XMLHttpRequest();
2634
+ xhr.open("PUT", url);
2635
+ xhr.setRequestHeader("Content-Type", contentType);
2636
+ xhr.upload.addEventListener("progress", (event) => {
2637
+ if (event.lengthComputable) {
2638
+ onProgress({
2639
+ loaded: event.loaded,
2640
+ total: event.total,
2641
+ percentage: Math.round(event.loaded / event.total * 100)
2642
+ });
2643
+ }
2644
+ });
2645
+ xhr.addEventListener("load", () => {
2646
+ if (xhr.status >= 200 && xhr.status < 300) {
2647
+ onProgress({ loaded: total, total, percentage: 100 });
2648
+ resolve();
2649
+ } else {
2650
+ reject(import_data8.createError.badRequest(`Upload failed: ${xhr.status} ${xhr.statusText}${xhr.responseText ? ` \u2014 ${xhr.responseText}` : ""}`));
2651
+ }
2652
+ });
2653
+ xhr.addEventListener("error", () => reject(import_data8.createError.network()));
2654
+ xhr.send(buffer);
2655
+ });
2656
+ }
2657
+ function toGlobalId(typeName, id) {
2658
+ if (typeof btoa !== "function") {
2659
+ throw import_data8.createError.badRequest("Cannot encode the file node id: btoa is unavailable in this environment.");
2660
+ }
2661
+ return btoa(JSON.stringify([typeName, id]));
2662
+ }
2663
+ async function fetchDownloadUrl(execute, cap, fileId) {
2664
+ if (cap.fileByIdArgName === "nodeId") {
2665
+ const nodeId = toGlobalId(cap.fileTypeName, fileId);
2666
+ const query2 = `
2667
+ query SheetsDownloadUrl($nodeId: ID!) {
2668
+ ${cap.fileByIdField}(nodeId: $nodeId) {
2669
+ ... on ${cap.fileTypeName} {
2670
+ downloadUrl
2671
+ }
2672
+ }
2673
+ }
2674
+ `.trim();
2675
+ const data2 = await execute(query2, { nodeId });
2676
+ const node = data2?.[cap.fileByIdField];
2677
+ const url2 = node?.downloadUrl;
2678
+ if (!url2) {
2679
+ throw import_data8.createError.badRequest("Upload succeeded but no downloadUrl was returned for the file.");
2680
+ }
2681
+ return url2;
2682
+ }
2683
+ if (cap.fileByIdArgName === "connection") {
2684
+ const idScalar2 = cap.idScalarName ?? "ID";
2685
+ const filterArg = cap.connectionFilterArgName;
2686
+ const idField = cap.connectionIdField;
2687
+ const nodesField = cap.connectionNodesField;
2688
+ const filterLiteral = cap.connectionIdOperator ? `{ ${idField}: { ${cap.connectionIdOperator}: $id } }` : `{ ${idField}: $id }`;
2689
+ const query2 = `
2690
+ query SheetsDownloadUrl($id: ${idScalar2}!) {
2691
+ ${cap.fileByIdField}(${filterArg}: ${filterLiteral}, first: 1) {
2692
+ ${nodesField} {
2693
+ downloadUrl
2694
+ }
2695
+ }
2696
+ }
2697
+ `.trim();
2698
+ const data2 = await execute(
2699
+ query2,
2700
+ { id: fileId }
2701
+ );
2702
+ const conn = data2?.[cap.fileByIdField];
2703
+ const url2 = conn?.[nodesField]?.[0]?.downloadUrl;
2704
+ if (!url2) {
2705
+ throw import_data8.createError.badRequest("Upload succeeded but no downloadUrl was returned for the file.");
2706
+ }
2707
+ return url2;
2708
+ }
2709
+ const idScalar = cap.idScalarName ?? "ID";
2710
+ const query = `
2711
+ query SheetsDownloadUrl($id: ${idScalar}!) {
2712
+ ${cap.fileByIdField}(id: $id) {
2713
+ id
2714
+ downloadUrl
2715
+ }
2716
+ }
2717
+ `.trim();
2718
+ const data = await execute(query, { id: fileId });
2719
+ const file = data?.[cap.fileByIdField];
2720
+ const url = file?.downloadUrl;
2721
+ if (!url) {
2722
+ throw import_data8.createError.badRequest("Upload succeeded but no downloadUrl was returned for the file.");
2723
+ }
2724
+ return url;
2725
+ }
2726
+
2727
+ // src/context/sheets-execute.ts
2728
+ var import_data10 = require("@constructive-io/data");
2563
2729
  function documentToString(document2) {
2564
2730
  if (typeof document2 === "string") return document2;
2565
2731
  if (document2 instanceof String) return document2.toString();
2566
2732
  if (document2 && typeof document2 === "object" && "kind" in document2) {
2567
- return (0, import_graphql.print)(document2);
2733
+ return (0, import_graphql2.print)(document2);
2568
2734
  }
2569
2735
  if (document2 === null || document2 === void 0) {
2570
- throw import_data7.createError.badRequest("Invalid GraphQL document: null or undefined");
2736
+ throw import_data9.createError.badRequest("Invalid GraphQL document: null or undefined");
2571
2737
  }
2572
2738
  return String(document2);
2573
2739
  }
@@ -2582,18 +2748,18 @@ function parseGraphQLResponse(response, onAuthError) {
2582
2748
  const message = error.message || "GraphQL query failed";
2583
2749
  if (code === "UNAUTHENTICATED" || hasAuthMessage(message)) {
2584
2750
  onAuthError?.();
2585
- return import_data7.createError.unauthorized("Authentication required. Please log in again.");
2751
+ return import_data9.createError.unauthorized("Authentication required. Please log in again.");
2586
2752
  }
2587
2753
  if (code === "FORBIDDEN") {
2588
- return import_data7.createError.forbidden("You do not have permission to perform this action.");
2754
+ return import_data9.createError.forbidden("You do not have permission to perform this action.");
2589
2755
  }
2590
- return import_data7.createError.graphql(message, code);
2756
+ return import_data9.createError.graphql(message, code);
2591
2757
  }
2592
2758
  function createSheetsExecute(config, getToken) {
2593
2759
  return async (document2, variables) => {
2594
2760
  const url = config.endpoint;
2595
2761
  if (!url) {
2596
- throw import_data7.createError.badRequest("No GraphQL endpoint configured.");
2762
+ throw import_data9.createError.badRequest("No GraphQL endpoint configured.");
2597
2763
  }
2598
2764
  const token = getToken();
2599
2765
  const headers = {
@@ -2614,29 +2780,29 @@ function createSheetsExecute(config, getToken) {
2614
2780
  })
2615
2781
  });
2616
2782
  } catch (error) {
2617
- throw import_data7.createError.network(error instanceof Error ? error : void 0);
2783
+ throw import_data9.createError.network(error instanceof Error ? error : void 0);
2618
2784
  }
2619
2785
  if (!response.ok) {
2620
2786
  const { status, statusText } = response;
2621
2787
  if (status === 401) {
2622
2788
  config.onAuthError?.();
2623
- throw import_data7.createError.unauthorized("Authentication required. Please log in again.");
2789
+ throw import_data9.createError.unauthorized("Authentication required. Please log in again.");
2624
2790
  }
2625
2791
  if (status === 403) {
2626
- throw import_data7.createError.forbidden("You do not have permission to perform this action.");
2792
+ throw import_data9.createError.forbidden("You do not have permission to perform this action.");
2627
2793
  }
2628
2794
  if (status === 404) {
2629
- throw import_data7.createError.notFound("The requested endpoint does not exist.");
2795
+ throw import_data9.createError.notFound("The requested endpoint does not exist.");
2630
2796
  }
2631
2797
  try {
2632
2798
  const body = await response.json();
2633
2799
  if (body.errors?.length) {
2634
- throw import_data7.createError.graphql(body.errors[0].message || `Request failed: ${status}`, body.errors[0].extensions?.code);
2800
+ throw import_data9.createError.graphql(body.errors[0].message || `Request failed: ${status}`, body.errors[0].extensions?.code);
2635
2801
  }
2636
2802
  } catch (e) {
2637
- if (e instanceof import_data7.DataError) throw e;
2803
+ if (e instanceof import_data9.DataError) throw e;
2638
2804
  }
2639
- throw import_data7.createError.badRequest(`Request failed: ${status} ${statusText}`);
2805
+ throw import_data9.createError.badRequest(`Request failed: ${status} ${statusText}`);
2640
2806
  }
2641
2807
  const result = await response.json();
2642
2808
  const graphqlError = parseGraphQLResponse(result, config.onAuthError);
@@ -2647,74 +2813,50 @@ function createSheetsExecute(config, getToken) {
2647
2813
  };
2648
2814
  }
2649
2815
  function createSheetsUpload(config, getToken) {
2650
- return async (file, path) => {
2816
+ const execute = config.execute ?? createSheetsExecute(config, getToken);
2817
+ return async (file, _path, options) => {
2651
2818
  if (!config.endpoint) {
2652
- throw import_data7.createError.badRequest("No GraphQL endpoint configured.");
2653
- }
2654
- const url = config.endpoint.replace(/\/graphql\/?$/, "/upload");
2655
- const token = getToken();
2656
- const formData = new FormData();
2657
- formData.append("file", file);
2658
- if (path) formData.append("path", path);
2659
- const headers = {};
2660
- if (token) {
2661
- headers["Authorization"] = `Bearer ${token}`;
2662
- }
2663
- let response;
2664
- try {
2665
- response = await fetch(url, {
2666
- method: "POST",
2667
- headers,
2668
- body: formData
2669
- });
2670
- } catch (error) {
2671
- throw import_data7.createError.network(error instanceof Error ? error : void 0);
2672
- }
2673
- if (!response.ok) {
2674
- if (response.status === 401) {
2675
- config.onAuthError?.();
2676
- throw import_data7.createError.unauthorized("Authentication required. Please log in again.");
2677
- }
2678
- if (response.status === 403) {
2679
- throw import_data7.createError.forbidden("You do not have permission to perform this action.");
2680
- }
2681
- try {
2682
- const body = await response.json();
2683
- const graphqlError = parseGraphQLResponse(body, config.onAuthError);
2684
- if (graphqlError) {
2685
- throw graphqlError;
2686
- }
2687
- if (body.errors?.length) {
2688
- const firstError = body.errors[0];
2689
- throw import_data7.createError.graphql(firstError.message || "Upload failed", firstError.extensions?.code);
2690
- }
2691
- } catch (error) {
2692
- if (error instanceof import_data7.DataError) throw error;
2693
- }
2694
- if (response.status === 400) throw import_data7.createError.badRequest("No file provided for upload.");
2695
- if (response.status === 413) throw import_data7.createError.badRequest("File is too large. Maximum size is 10 MB.");
2696
- throw import_data7.createError.badRequest(`Upload failed: ${response.status} ${response.statusText}`);
2819
+ throw import_data9.createError.badRequest("No GraphQL endpoint configured.");
2697
2820
  }
2698
- const result = await response.json();
2699
- if (result.errors?.length) {
2700
- const graphqlError = parseGraphQLResponse(result, config.onAuthError);
2701
- if (graphqlError) {
2702
- throw graphqlError;
2821
+ const bucketKey = config.upload?.bucketKey ?? "public";
2822
+ const contentType = file.type || "application/octet-stream";
2823
+ const buffer = await file.arrayBuffer();
2824
+ const contentHash = await sha256HexFromBuffer(buffer);
2825
+ const cap = await discoverUploadCapability(config.endpoint, execute);
2826
+ const payload = await callUploadOp(execute, cap, {
2827
+ bucketKey,
2828
+ contentHash,
2829
+ contentType,
2830
+ size: file.size,
2831
+ filename: file.name
2832
+ });
2833
+ if (!payload.deduplicated) {
2834
+ if (!payload.uploadUrl) {
2835
+ throw import_data9.createError.badRequest("Upload failed: server returned no uploadUrl for a non-deduplicated file.");
2703
2836
  }
2704
- const firstError = result.errors[0];
2705
- throw import_data7.createError.graphql(firstError.message || "Upload failed", firstError.extensions?.code);
2837
+ await presignedPut(payload.uploadUrl, buffer, contentType, options?.onProgress);
2838
+ } else {
2839
+ options?.onProgress?.({ loaded: file.size, total: file.size, percentage: 100 });
2706
2840
  }
2707
- return result;
2841
+ const url = await fetchDownloadUrl(execute, cap, payload.fileId);
2842
+ return {
2843
+ url,
2844
+ filename: file.name,
2845
+ mime: file.type,
2846
+ size: file.size,
2847
+ key: payload.key,
2848
+ fileId: payload.fileId
2849
+ };
2708
2850
  };
2709
2851
  }
2710
2852
 
2711
2853
  // src/hooks/use-sheets-upload.ts
2712
2854
  function resolveUploadNaming(tableName, table) {
2713
2855
  return {
2714
- mutationName: (0, import_data10.toUpdateMutationName)(tableName, table),
2715
- singularName: (0, import_data10.toCamelCaseSingular)(tableName, table),
2716
- patchFieldName: (0, import_data10.toPatchFieldName)(tableName, table),
2717
- updateInputTypeName: (0, import_data10.toUpdateInputTypeName)(tableName)
2856
+ mutationName: (0, import_data12.toUpdateMutationName)(tableName, table),
2857
+ singularName: (0, import_data12.toCamelCaseSingular)(tableName, table),
2858
+ patchFieldName: (0, import_data12.toPatchFieldName)(tableName, table),
2859
+ updateInputTypeName: (0, import_data12.toUpdateInputTypeName)(tableName)
2718
2860
  };
2719
2861
  }
2720
2862
  function resolveTransport(endpoint, getToken, options) {
@@ -2791,7 +2933,7 @@ function useSheetsFieldUpload(tableName, fieldName, recordId, options = {}) {
2791
2933
  const table = (0, import_react12.useMemo)(() => {
2792
2934
  if (!meta?._meta?.tables) return null;
2793
2935
  const candidate = meta._meta.tables.find((item) => item?.name === tableName);
2794
- return candidate ? (0, import_data9.cleanTable)(candidate) : null;
2936
+ return candidate ? (0, import_data11.cleanTable)(candidate) : null;
2795
2937
  }, [meta, tableName]);
2796
2938
  const resolvedNaming = (0, import_react12.useMemo)(() => resolveUploadNaming(tableName, table), [tableName, table]);
2797
2939
  const getToken = (0, import_react12.useMemo)(() => {
@@ -2967,6 +3109,20 @@ function RemoveButton({ onClick, label }) {
2967
3109
  }
2968
3110
  ) });
2969
3111
  }
3112
+ function FilePreview({ name, size, mime }) {
3113
+ const hasMime = !!mime && mime !== "unknown";
3114
+ return /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { className: "flex size-full flex-col items-center justify-center gap-2 p-4 text-center", children: [
3115
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("div", { className: "bg-muted/60 flex size-12 shrink-0 items-center justify-center rounded-lg", "aria-hidden": "true", children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_lucide_react4.FileIcon, { className: "text-muted-foreground size-6" }) }),
3116
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { className: "min-w-0 max-w-full", children: [
3117
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("p", { className: "truncate text-sm font-medium", title: name, children: name || "File" }),
3118
+ (size || hasMime) && /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("p", { className: "text-muted-foreground mt-0.5 text-xs", children: [
3119
+ size ? formatFileSize(size) : null,
3120
+ size && hasMime ? " \u2022 " : null,
3121
+ hasMime ? /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("span", { className: "uppercase", children: mime }) : null
3122
+ ] })
3123
+ ] })
3124
+ ] });
3125
+ }
2970
3126
  var ImageEditor = ({
2971
3127
  value,
2972
3128
  onFinishedEditing,
@@ -2976,8 +3132,11 @@ var ImageEditor = ({
2976
3132
  onSaveComplete,
2977
3133
  isDraftRow = false,
2978
3134
  onSubmitDraft,
2979
- onDraftUploadComplete
3135
+ onDraftUploadComplete,
3136
+ acceptAnyFile = false
2980
3137
  }) => {
3138
+ const noun = acceptAnyFile ? "file" : "image";
3139
+ const Noun = acceptAnyFile ? "File" : "Image";
2981
3140
  const [uploadState, setUploadState] = (0, import_react15.useState)("idle");
2982
3141
  const { config } = useSheetsContext();
2983
3142
  const storeApi = useSheetsStoreApi();
@@ -3000,10 +3159,12 @@ var ImageEditor = ({
3000
3159
  const isUploading = uploadState === "uploading";
3001
3160
  const isBusy = uploadState !== "idle";
3002
3161
  const imageUrl = (0, import_react15.useMemo)(() => getImageUrl(imageValue), [imageValue]);
3003
- const imageStatus = useImageStatus(imageUrl || void 0);
3004
- const imageLoadFailed = imageUrl != null && imageStatus === "error";
3005
- const hasImage = imageUrl != null && !imageLoadFailed;
3006
3162
  const imageMetadata = (0, import_react15.useMemo)(() => getImageMetadata(imageValue), [imageValue]);
3163
+ const storedMime = imageMetadata?.mime;
3164
+ const storedIsImage = !acceptAnyFile || !!storedMime && storedMime.startsWith("image/");
3165
+ const imageStatus = useImageStatus(storedIsImage ? imageUrl || void 0 : void 0);
3166
+ const imageLoadFailed = storedIsImage && imageUrl != null && imageStatus === "error";
3167
+ const hasImage = imageUrl != null && !imageLoadFailed && storedIsImage;
3007
3168
  const revokePreviewUrl = (0, import_react15.useCallback)(() => {
3008
3169
  if (previewUrlRef.current) {
3009
3170
  URL.revokeObjectURL(previewUrlRef.current);
@@ -3023,8 +3184,8 @@ var ImageEditor = ({
3023
3184
  setImageValue(normalized);
3024
3185
  onSaveComplete?.({ imageData: normalized });
3025
3186
  onFinishedEditing();
3026
- import_toast.toast.success({ message: "Image uploaded successfully" });
3027
- }, [resetFileState, onSaveComplete, onFinishedEditing]);
3187
+ import_toast.toast.success({ message: `${Noun} uploaded successfully` });
3188
+ }, [resetFileState, onSaveComplete, onFinishedEditing, Noun]);
3028
3189
  const handleUploadError = (0, import_react15.useCallback)((error) => {
3029
3190
  setUploadState("idle");
3030
3191
  sheetsLogger().error("[image-editor] upload failed:", error);
@@ -3044,20 +3205,22 @@ var ImageEditor = ({
3044
3205
  const handleFileSelection = (0, import_react15.useCallback)((acceptedFiles) => {
3045
3206
  if (acceptedFiles.length === 0) return;
3046
3207
  const file = acceptedFiles[0];
3047
- if (!file.type.startsWith("image/")) {
3048
- import_toast.toast.error({ message: "Please select an image file" });
3049
- return;
3050
- }
3051
- if (file.size > 10 * 1024 * 1024) {
3052
- import_toast.toast.error({ message: "File size must be less than 10MB" });
3053
- return;
3208
+ if (!acceptAnyFile) {
3209
+ if (!file.type.startsWith("image/")) {
3210
+ import_toast.toast.error({ message: "Please select an image file" });
3211
+ return;
3212
+ }
3213
+ if (file.size > 10 * 1024 * 1024) {
3214
+ import_toast.toast.error({ message: "File size must be less than 10MB" });
3215
+ return;
3216
+ }
3054
3217
  }
3055
3218
  revokePreviewUrl();
3056
3219
  setSelectedFile(file);
3057
3220
  const url = URL.createObjectURL(file);
3058
3221
  previewUrlRef.current = url;
3059
3222
  setPreviewUrl(url);
3060
- }, [revokePreviewUrl]);
3223
+ }, [revokePreviewUrl, acceptAnyFile]);
3061
3224
  const handleDragEnter = (0, import_react15.useCallback)((e) => {
3062
3225
  e.preventDefault();
3063
3226
  e.stopPropagation();
@@ -3092,7 +3255,7 @@ var ImageEditor = ({
3092
3255
  const committedId = committedRecordIdRef.current ?? recordId;
3093
3256
  if (committedRecordIdRef.current != null) {
3094
3257
  try {
3095
- import_toast.toast.info({ message: "Uploading image..." });
3258
+ import_toast.toast.info({ message: `Uploading ${noun}...` });
3096
3259
  setUploadState("uploading");
3097
3260
  const uploadResult = await executeFieldUpload(
3098
3261
  tableName,
@@ -3108,7 +3271,7 @@ var ImageEditor = ({
3108
3271
  resetFileState();
3109
3272
  setImageValue(normalized);
3110
3273
  onDraftUploadComplete?.();
3111
- import_toast.toast.success({ message: "Image uploaded successfully" });
3274
+ import_toast.toast.success({ message: `${Noun} uploaded successfully` });
3112
3275
  onFinishedEditing();
3113
3276
  } catch (error) {
3114
3277
  onDraftUploadComplete?.();
@@ -3126,14 +3289,17 @@ var ImageEditor = ({
3126
3289
  import_toast.toast.info({ message: "Creating row..." });
3127
3290
  setUploadState("submitting-draft");
3128
3291
  const result = await onSubmitDraft();
3129
- if (!result.createdRow?.id) throw new Error("Failed to create row");
3130
- committedRecordIdRef.current = result.createdRow.id;
3131
- import_toast.toast.info({ message: "Uploading image..." });
3292
+ const createdId = result.createdRow?.id;
3293
+ if (typeof createdId !== "string" && typeof createdId !== "number") {
3294
+ throw new Error("Image uploads require a scalar id primary key.");
3295
+ }
3296
+ committedRecordIdRef.current = createdId;
3297
+ import_toast.toast.info({ message: `Uploading ${noun}...` });
3132
3298
  setUploadState("uploading");
3133
3299
  const uploadResult = await executeFieldUpload(
3134
3300
  tableName,
3135
3301
  fieldName,
3136
- result.createdRow.id,
3302
+ createdId,
3137
3303
  selectedFile,
3138
3304
  config.endpoint,
3139
3305
  getToken,
@@ -3144,7 +3310,7 @@ var ImageEditor = ({
3144
3310
  resetFileState();
3145
3311
  setImageValue(normalized);
3146
3312
  onDraftUploadComplete?.();
3147
- import_toast.toast.success({ message: "Row created and image uploaded" });
3313
+ import_toast.toast.success({ message: `Row created and ${noun} uploaded` });
3148
3314
  onFinishedEditing();
3149
3315
  } catch (error) {
3150
3316
  onDraftUploadComplete?.();
@@ -3159,7 +3325,7 @@ var ImageEditor = ({
3159
3325
  }
3160
3326
  setUploadState("uploading");
3161
3327
  uploadMutation.mutate(selectedFile);
3162
- }, [selectedFile, uploadMutation, tableName, fieldName, recordId, isDraftRow, onSubmitDraft, config.endpoint, config.onAuthError, getToken, resetFileState, onDraftUploadComplete, onFinishedEditing]);
3328
+ }, [selectedFile, uploadMutation, tableName, fieldName, recordId, isDraftRow, onSubmitDraft, config.endpoint, config.onAuthError, getToken, resetFileState, onDraftUploadComplete, onFinishedEditing, noun, Noun]);
3163
3329
  const handleSave = (0, import_react15.useCallback)(() => {
3164
3330
  if (!imageValue) {
3165
3331
  onFinishedEditing(null);
@@ -3184,12 +3350,13 @@ var ImageEditor = ({
3184
3350
  handleSave();
3185
3351
  }
3186
3352
  }, [handleSave]);
3187
- const dropzoneKey = isBusy ? "busy" : previewUrl ? "preview" : hasImage ? "loaded" : imageLoadFailed ? "broken" : "empty";
3353
+ const hasStoredFile = acceptAnyFile && !!imageUrl && !storedIsImage;
3354
+ const dropzoneKey = isBusy ? "busy" : previewUrl ? "preview" : hasImage ? "loaded" : hasStoredFile ? "file" : imageLoadFailed ? "broken" : "empty";
3188
3355
  const renderDropzoneContent = () => {
3189
3356
  if (isBusy) {
3190
3357
  return /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { "data-state": uploadState, className: "text-muted-foreground flex w-full flex-col items-center justify-center p-6", children: [
3191
3358
  /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_lucide_react4.Loader2, { className: "mb-2 size-6 animate-spin" }),
3192
- /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("p", { className: "text-sm", children: isSubmittingDraft ? "Creating row..." : "Uploading image..." }),
3359
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("p", { className: "text-sm", children: isSubmittingDraft ? "Creating row..." : `Uploading ${noun}...` }),
3193
3360
  isUploading && uploadProgress && /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { className: "mt-3 w-full max-w-xs", children: [
3194
3361
  /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("div", { className: "bg-muted h-1.5 overflow-hidden rounded-full", children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
3195
3362
  "div",
@@ -3206,8 +3373,9 @@ var ImageEditor = ({
3206
3373
  ] });
3207
3374
  }
3208
3375
  if (previewUrl) {
3376
+ const selectedIsImage = !acceptAnyFile || (selectedFile?.type.startsWith("image/") ?? false);
3209
3377
  return /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { className: "relative w-full", style: { height: "13rem" }, children: [
3210
- /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("img", { src: previewUrl, alt: selectedFile?.name || "Uploaded image", className: "size-full object-contain p-2" }),
3378
+ selectedIsImage ? /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("img", { src: previewUrl, alt: selectedFile?.name || "Selected file", className: "size-full object-contain p-2" }) : /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(FilePreview, { name: selectedFile?.name, size: selectedFile?.size, mime: selectedFile?.type }),
3211
3379
  /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(RemoveButton, { onClick: removeFile, label: "Remove selected file" })
3212
3380
  ] });
3213
3381
  }
@@ -3226,6 +3394,12 @@ var ImageEditor = ({
3226
3394
  /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(RemoveButton, { onClick: handleRemoveImage, label: "Remove image" })
3227
3395
  ] });
3228
3396
  }
3397
+ if (hasStoredFile) {
3398
+ return /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { className: "relative w-full", style: { height: "13rem" }, children: [
3399
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(FilePreview, { name: imageMetadata?.filename, size: imageMetadata?.size, mime: imageMetadata?.mime }),
3400
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(RemoveButton, { onClick: handleRemoveImage, label: "Remove file" })
3401
+ ] });
3402
+ }
3229
3403
  if (imageLoadFailed) {
3230
3404
  return /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { className: "flex w-full flex-col items-center justify-center px-4 py-6 text-center", children: [
3231
3405
  /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
@@ -3279,8 +3453,12 @@ var ImageEditor = ({
3279
3453
  }
3280
3454
  return /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { className: "flex w-full flex-col items-center justify-center px-4 py-6 text-center", children: [
3281
3455
  /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("div", { className: "bg-muted/60 mb-3 flex size-10 shrink-0 items-center justify-center rounded-full", "aria-hidden": "true", children: /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_lucide_react4.UploadIcon, { className: "text-muted-foreground size-4" }) }),
3282
- /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("p", { className: "text-sm font-medium", children: "Drop image here or browse" }),
3283
- /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("p", { className: "text-muted-foreground mt-1 text-xs", children: "SVG, PNG, JPG or GIF (max. 10MB)" }),
3456
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("p", { className: "text-sm font-medium", children: [
3457
+ "Drop ",
3458
+ noun,
3459
+ " here or browse"
3460
+ ] }),
3461
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("p", { className: "text-muted-foreground mt-1 text-xs", children: acceptAnyFile ? "Any file type" : "SVG, PNG, JPG or GIF (max. 10MB)" }),
3284
3462
  /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)(
3285
3463
  import_button5.Button,
3286
3464
  {
@@ -3294,7 +3472,8 @@ var ImageEditor = ({
3294
3472
  disabled: isBusy,
3295
3473
  children: [
3296
3474
  /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_lucide_react4.UploadIcon, { className: "-ms-0.5 opacity-60", "aria-hidden": "true" }),
3297
- "Select image"
3475
+ "Select ",
3476
+ noun
3298
3477
  ]
3299
3478
  }
3300
3479
  )
@@ -3309,17 +3488,17 @@ var ImageEditor = ({
3309
3488
  style: overlayMaxHeight > 0 ? { maxHeight: overlayMaxHeight } : void 0,
3310
3489
  children: /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { onKeyDown: handleEditorKeyDown, className: "flex min-h-0 flex-1 flex-col", children: [
3311
3490
  /* @__PURE__ */ (0, import_jsx_runtime11.jsxs)("div", { className: "flex shrink-0 items-center gap-2 border-b px-6 py-3", children: [
3312
- /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_lucide_react4.ImageIcon, { className: "text-muted-foreground size-4" }),
3313
- /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("h3", { className: "text-sm font-medium", children: imageUrl ? "Edit Image" : "Add Image" })
3491
+ acceptAnyFile ? /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_lucide_react4.FileIcon, { className: "text-muted-foreground size-4" }) : /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(import_lucide_react4.ImageIcon, { className: "text-muted-foreground size-4" }),
3492
+ /* @__PURE__ */ (0, import_jsx_runtime11.jsx)("h3", { className: "text-sm font-medium", children: imageUrl ? `Edit ${Noun}` : `Add ${Noun}` })
3314
3493
  ] }),
3315
3494
  /* @__PURE__ */ (0, import_jsx_runtime11.jsx)(
3316
3495
  "input",
3317
3496
  {
3318
3497
  ref: fileInputRef,
3319
3498
  type: "file",
3320
- accept: "image/*",
3499
+ accept: acceptAnyFile ? void 0 : "image/*",
3321
3500
  className: "hidden",
3322
- "aria-label": "Upload image file",
3501
+ "aria-label": `Upload ${noun}`,
3323
3502
  tabIndex: -1,
3324
3503
  onChange: (e) => {
3325
3504
  const files = Array.from(e.target.files || []);
@@ -3393,6 +3572,7 @@ var import_jsx_runtime12 = require("react/jsx-runtime");
3393
3572
  var DRAFT_PREFIX = "draft:";
3394
3573
  function ImageEditorDom({
3395
3574
  value,
3575
+ cell,
3396
3576
  colKey,
3397
3577
  rowId,
3398
3578
  tableName,
@@ -3402,6 +3582,8 @@ function ImageEditorDom({
3402
3582
  onInvalidateData
3403
3583
  }) {
3404
3584
  const isDraftRow = rowId.startsWith(DRAFT_PREFIX);
3585
+ const cellType = cell.meta?.cellType;
3586
+ const acceptAnyFile = cellType != null && cellType !== "image";
3405
3587
  const handleSaveComplete = onCommitPatch ? (saveData) => onCommitPatch({ [colKey]: saveData.imageData }) : void 0;
3406
3588
  const handleSubmitDraft = isDraftRow && onSubmitDraftRow ? async () => {
3407
3589
  const createdRow = await onSubmitDraftRow(rowId);
@@ -3411,6 +3593,7 @@ function ImageEditorDom({
3411
3593
  ImageEditor,
3412
3594
  {
3413
3595
  value,
3596
+ acceptAnyFile,
3414
3597
  onFinishedEditing: () => onCancel(),
3415
3598
  tableName,
3416
3599
  fieldName: colKey,
@@ -3945,7 +4128,7 @@ function parseValue(text) {
3945
4128
  if (trimmed === "") return null;
3946
4129
  return Number(trimmed);
3947
4130
  }
3948
- function NumberEditorDom({ value, initialText, onCommit, onCancel }) {
4131
+ function NumberEditorDom({ value, initialText, colKey, fieldMeta, onCommit, onCancel }) {
3949
4132
  const [text, setText] = (0, import_react21.useState)(() => initialText != null ? initialText : seedText(value));
3950
4133
  const escapedRef = (0, import_react21.useRef)(false);
3951
4134
  const parsed = parseValue(text);
@@ -3982,6 +4165,7 @@ function NumberEditorDom({ value, initialText, onCommit, onCancel }) {
3982
4165
  /* @__PURE__ */ (0, import_jsx_runtime19.jsx)(
3983
4166
  "input",
3984
4167
  {
4168
+ "aria-label": `Edit ${fieldMeta?.name ?? colKey}`,
3985
4169
  value: text,
3986
4170
  onChange: (e) => setText(e.target.value),
3987
4171
  onKeyDown: handleKeyDown,
@@ -4007,9 +4191,9 @@ var import_react_query5 = require("@tanstack/react-query");
4007
4191
  // src/hooks/use-sheets-table-cursor.ts
4008
4192
  var import_react22 = require("react");
4009
4193
  var import_react_query4 = require("@tanstack/react-query");
4010
- var import_data11 = require("@constructive-io/data");
4011
- var import_data12 = require("@constructive-io/data");
4012
4194
  var import_data13 = require("@constructive-io/data");
4195
+ var import_data14 = require("@constructive-io/data");
4196
+ var import_data15 = require("@constructive-io/data");
4013
4197
  function useSheetsTableCursor(tableName, options = {}) {
4014
4198
  const queryClient = (0, import_react_query4.useQueryClient)();
4015
4199
  const { execute, scopeKey } = useSheetsContext();
@@ -4017,7 +4201,7 @@ function useSheetsTableCursor(tableName, options = {}) {
4017
4201
  const adapter = useSheetsAdapter();
4018
4202
  const tables = (0, import_react22.useMemo)(() => {
4019
4203
  if (!meta?._meta?.tables) return [];
4020
- return meta._meta.tables.filter((candidate) => candidate != null).map((metaTable) => (0, import_data11.cleanTable)(metaTable));
4204
+ return meta._meta.tables.filter((candidate) => candidate != null).map((metaTable) => (0, import_data13.cleanTable)(metaTable));
4021
4205
  }, [meta]);
4022
4206
  const table = (0, import_react22.useMemo)(
4023
4207
  () => tables.find((candidate) => candidate.name === tableName) ?? null,
@@ -4049,7 +4233,7 @@ function useSheetsTableCursor(tableName, options = {}) {
4049
4233
  queryKey: sheetsQueryKeys.cursorTable(scopeKey, tableName, stableOptions),
4050
4234
  queryFn: async ({ pageParam }) => {
4051
4235
  if (!table) {
4052
- throw import_data12.createError.notFound(`Table '${tableName}' not found`);
4236
+ throw import_data14.createError.notFound(`Table '${tableName}' not found`);
4053
4237
  }
4054
4238
  const cursor = pageParam;
4055
4239
  const variableOptions = {
@@ -4072,7 +4256,7 @@ function useSheetsTableCursor(tableName, options = {}) {
4072
4256
  const validatedOrderByEnum = new Set(variables.orderBy ?? []);
4073
4257
  const availableOrderByFields = new Set(table.fields.map((field) => field.name));
4074
4258
  const validatedOrderBy = orderBy?.filter(
4075
- ({ field, direction }) => availableOrderByFields.has(field) && validatedOrderByEnum.has((0, import_data13.toOrderByEnumValue)(field, direction))
4259
+ ({ field, direction }) => availableOrderByFields.has(field) && validatedOrderByEnum.has((0, import_data15.toOrderByEnumValue)(field, direction))
4076
4260
  );
4077
4261
  const res = await adapter.listRows(
4078
4262
  { table, allTables: tables, tableName },
@@ -4734,7 +4918,7 @@ var import_button11 = require("@constructive-io/ui/button");
4734
4918
  init_overlay_presets();
4735
4919
  init_cn();
4736
4920
  var import_jsx_runtime23 = require("react/jsx-runtime");
4737
- function TextEditor({ value, initialText, onCommit, onCancel }) {
4921
+ function TextEditor({ value, initialText, colKey, fieldMeta, onCommit, onCancel }) {
4738
4922
  const [text, setText] = (0, import_react26.useState)(() => initialText != null ? initialText : String(value ?? ""));
4739
4923
  const escapedRef = (0, import_react26.useRef)(false);
4740
4924
  function handleKeyDown(e) {
@@ -4760,6 +4944,7 @@ function TextEditor({ value, initialText, onCommit, onCancel }) {
4760
4944
  /* @__PURE__ */ (0, import_jsx_runtime23.jsx)(
4761
4945
  "input",
4762
4946
  {
4947
+ "aria-label": `Edit ${fieldMeta?.name ?? colKey}`,
4763
4948
  value: text,
4764
4949
  onChange: (e) => setText(e.target.value),
4765
4950
  onKeyDown: handleKeyDown,