@databricks/appkit-ui 0.86.0 → 0.88.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 (45) hide show
  1. package/dist/js/database/client.d.ts.map +1 -1
  2. package/dist/js/database/client.js +41 -9
  3. package/dist/js/database/client.js.map +1 -1
  4. package/dist/react/beta.d.ts +14 -1
  5. package/dist/react/beta.js +9 -1
  6. package/dist/react/hooks/analytics-request-store.js +1 -1
  7. package/dist/react/hooks/analytics-request-store.js.map +1 -1
  8. package/dist/react/hooks/database-request-store.d.ts +33 -0
  9. package/dist/react/hooks/database-request-store.d.ts.map +1 -0
  10. package/dist/react/hooks/database-request-store.js +145 -0
  11. package/dist/react/hooks/database-request-store.js.map +1 -0
  12. package/dist/react/hooks/request-store.js +26 -5
  13. package/dist/react/hooks/request-store.js.map +1 -1
  14. package/dist/react/hooks/use-database-create.d.ts +55 -0
  15. package/dist/react/hooks/use-database-create.d.ts.map +1 -0
  16. package/dist/react/hooks/use-database-create.js +45 -0
  17. package/dist/react/hooks/use-database-create.js.map +1 -0
  18. package/dist/react/hooks/use-database-delete.d.ts +50 -0
  19. package/dist/react/hooks/use-database-delete.d.ts.map +1 -0
  20. package/dist/react/hooks/use-database-delete.js +47 -0
  21. package/dist/react/hooks/use-database-delete.js.map +1 -0
  22. package/dist/react/hooks/use-database-list.d.ts +40 -0
  23. package/dist/react/hooks/use-database-list.d.ts.map +1 -0
  24. package/dist/react/hooks/use-database-list.js +29 -0
  25. package/dist/react/hooks/use-database-list.js.map +1 -0
  26. package/dist/react/hooks/use-database-read.d.ts +75 -0
  27. package/dist/react/hooks/use-database-read.d.ts.map +1 -0
  28. package/dist/react/hooks/use-database-read.js +136 -0
  29. package/dist/react/hooks/use-database-read.js.map +1 -0
  30. package/dist/react/hooks/use-database-record.d.ts +37 -0
  31. package/dist/react/hooks/use-database-record.d.ts.map +1 -0
  32. package/dist/react/hooks/use-database-record.js +53 -0
  33. package/dist/react/hooks/use-database-record.js.map +1 -0
  34. package/dist/react/hooks/use-database-update.d.ts +52 -0
  35. package/dist/react/hooks/use-database-update.d.ts.map +1 -0
  36. package/dist/react/hooks/use-database-update.js +42 -0
  37. package/dist/react/hooks/use-database-update.js.map +1 -0
  38. package/dist/react/hooks/use-database-write.d.ts +32 -0
  39. package/dist/react/hooks/use-database-write.d.ts.map +1 -0
  40. package/dist/react/hooks/use-database-write.js +94 -0
  41. package/dist/react/hooks/use-database-write.js.map +1 -0
  42. package/docs/development/type-generation.md +11 -0
  43. package/docs/plugins/database.md +233 -14
  44. package/package.json +1 -1
  45. package/sbom.cdx.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"client.d.ts","names":[],"sources":["../../../src/js/database/client.ts"],"mappings":";;;;;;UAoCiB,sBAAA;;AAAjB;;;WAKW,MAAA,GAAS,WAAA;AAAA;AAIpB;AAAA,UAAiB,WAAA;EAAW;;;;;;;;;;;;;;EAe1B,IAAA,WAAe,mBAAA,EACb,MAAA,EAAQ,CAAA,EACR,MAAA,cACA,IAAA,GAAO,sBAAA,GACN,OAAA,CAAQ,gBAAA,CAAiB,eAAA,CAAgB,CAAA;EAC5C,IAAA,WAAe,cAAA,kBAAgC,kBAAA,CAAmB,CAAA,GAChE,MAAA,EAAQ,CAAA,EACR,MAAA,EAAQ,CAAA,GAAI,mBAAA,CAAoB,CAAA,EAAG,kBAAA,CAAmB,CAAA,IACtD,IAAA,GAAO,sBAAA,GACN,OAAA,CAAQ,gBAAA,CAAiB,eAAA,CAAgB,CAAA,EAAG,CAAA;EAFjC;;;;;;;;;;;;;EAiBd,GAAA,WACY,mBAAA,kBACM,oBAAA,CAAqB,CAAA,IAAK,MAAA,gBAE1C,MAAA,EAAQ,CAAA,EACR,EAAA,EAAI,UAAA,CAAW,CAAA,GACf,MAAA,GAAS,CAAA,GAAI,mBAAA,CAAoB,CAAA,EAAG,oBAAA,CAAqB,CAAA,IACzD,IAAA,GAAO,sBAAA,GACN,OAAA,CAAQ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iB,eAAA,CAAgB,CAAA,EAAG,CAAA;EAiBH;;;;;;;;;;;;;EAF5C,GAAA,WACY,mBAAA,kBACM,oBAAA,CAAqB,CAAA,IAAK,MAAA,gBAE1C,MAAA,EAAQ,CAAA,EACR,EAAA,EAAI,UAAA,CAAW,CAAA,GACf,MAAA,GAAS,CAAA,GAAI,mBAAA,CAAoB,CAAA,EAAG,oBAAA,CAAqB,CAAA,IACzD,IAAA,GAAO,sBAAA,GACN,OAAA,CAAQ,iBAAA,CAAkB,CAAA,EAAG,CAAA;EAiBf;;;;;;;;;;;;;;;EAAjB,MAAA,WAAiB,cAAA,kBAAgC,cAAA,CAAe,CAAA,GAC9D,MAAA,EAAQ,CAAA,EACR,MAAA,EAAQ,CAAA,GAAI,mBAAA,CAAoB,CAAA,EAAG,cAAA,CAAe,CAAA,IAClD,IAAA,GAAO,sBAAA,GACN,OAAA,CAAQ,WAAA,CAAY,CAAA;EAYb;;;;;;;;;EADV,MAAA,WAAiB,mBAAA,kBAAqC,cAAA,CAAe,CAAA,GACnE,MAAA,EAAQ,CAAA,EACR,EAAA,EAAI,UAAA,CAAW,CAAA,GACf,MAAA,EAAQ,CAAA,GAAI,mBAAA,CAAoB,CAAA,EAAG,cAAA,CAAe,CAAA,IAClD,IAAA,GAAO,sBAAA,GACN,OAAA,CAAQ,WAAA,CAAY,CAAA;EAAZ;;;;;;;;;EAWX,MAAA,WAAiB,mBAAA,EACf,MAAA,EAAQ,CAAA,EACR,EAAA,EAAI,UAAA,CAAW,CAAA,GACf,IAAA,GAAO,sBAAA,GACN,OAAA;AAAA;;;;;;cA+VQ,WAAA,EAAa,WAAA"}
@@ -8,16 +8,32 @@ function isRecord(value) {
8
8
  return typeof value === "object" && value !== null && !Array.isArray(value);
9
9
  }
10
10
  /**
11
+ * An id that URL resolution would not keep as one path segment: `""` and
12
+ * `"."` collapse onto the list route and `".."` climbs above the table, so a
13
+ * keyed request would silently reach another route.
14
+ */
15
+ function isUnaddressableId(segment) {
16
+ return segment === "" || segment === "." || segment === "..";
17
+ }
18
+ /**
11
19
  * Find the route the server published for one operation. The plugin publishes
12
20
  * only what its `api` configuration exposes, so a missing entry is refused
13
- * here with `NOT_EXPOSED` and no request is sent.
21
+ * here with `NOT_EXPOSED` and no request is sent. An id that is not one path
22
+ * segment is refused with `INVALID_REQUEST`, also without a request.
23
+ *
24
+ * @internal Shared with the React hooks; not part of the public surface.
14
25
  */
15
26
  function resolveDatabaseUrl(entity, operation, id, query) {
16
27
  const name = `${entity}.${operation}`;
17
28
  const endpoints = getClientConfig().endpoints.database;
18
29
  const path = isRecord(endpoints) && Object.hasOwn(endpoints, name) ? endpoints[name] : void 0;
19
30
  if (typeof path !== "string") throw new DatabaseApiError("NOT_EXPOSED", null, `Database operation "${name}" is not exposed`);
20
- const url = id === void 0 ? path : path.replace(":id", encodeURIComponent(String(id)));
31
+ let url = path;
32
+ if (id !== void 0) {
33
+ const segment = String(id);
34
+ if (isUnaddressableId(segment)) throw new DatabaseApiError("INVALID_REQUEST", null, "Database id must be a non-empty path segment");
35
+ url = path.replace(":id", encodeURIComponent(segment));
36
+ }
21
37
  return query ? `${url}?${query}` : url;
22
38
  }
23
39
  /** Keep only details shaped like the server's; they name public fields only. */
@@ -39,6 +55,8 @@ async function failure(response) {
39
55
  * anything but the shape `accept` expects. A `204` has no body, so `accept`
40
56
  * sees `undefined`. An abort rejects with the signal's own reason, so a
41
57
  * caller can tell cancellation from failure.
58
+ *
59
+ * @internal Shared with the React hooks; not part of the public surface.
42
60
  */
43
61
  async function requestDatabase(url, init, accept) {
44
62
  const headers = new Headers(init.headers);
@@ -65,11 +83,17 @@ async function requestDatabase(url, init, accept) {
65
83
  if (!accept(body)) throw new DatabaseApiError(write ? "OUTCOME_UNKNOWN" : "INTERNAL", response.status, write ? "Database write may have completed; response has an unexpected shape" : "Database response has an unexpected shape");
66
84
  return body;
67
85
  }
68
- /** The `{ items, limit, offset }` envelope a list route answers with. */
86
+ /**
87
+ * The `{ items, limit, offset }` envelope a list route answers with.
88
+ * @internal Shared with the React hooks; not part of the public surface.
89
+ */
69
90
  function isDatabaseListPage(body) {
70
91
  return isRecord(body) && Array.isArray(body.items) && typeof body.limit === "number" && typeof body.offset === "number";
71
92
  }
72
- /** A detail route answers one bare row; a serializer returns an object too. */
93
+ /**
94
+ * A detail route answers one bare row; a serializer returns an object too.
95
+ * @internal Shared with the React hooks; not part of the public surface.
96
+ */
73
97
  function isDatabaseRow(body) {
74
98
  return isRecord(body);
75
99
  }
@@ -97,17 +121,25 @@ function jsonWrite(method, values, signal) {
97
121
  }
98
122
  }
99
123
  /**
100
- * Untyped create behind `databaseApi.create`; its signature carries the
101
- * checks, while the entity is still a literal.
124
+ * Untyped create behind `databaseApi.create` and `useDatabaseCreate`; their
125
+ * signatures carry the checks, while the entity is still a literal.
126
+ *
127
+ * @internal Shared with the React hooks; not part of the public surface.
102
128
  */
103
129
  async function createDatabaseRow(entity, values, init = {}) {
104
130
  return requestDatabase(resolveDatabaseUrl(entity, "create"), jsonWrite("POST", values, init.signal), isDatabaseRow);
105
131
  }
106
- /** Untyped update behind `databaseApi.update`. */
132
+ /**
133
+ * Untyped update, shared by the typed client and the write hooks.
134
+ * @internal Not part of the public surface.
135
+ */
107
136
  async function updateDatabaseRow(entity, id, values, init = {}) {
108
137
  return requestDatabase(resolveDatabaseUrl(entity, "update", id), jsonWrite("PATCH", values, init.signal), isDatabaseRow);
109
138
  }
110
- /** Untyped delete behind `databaseApi.remove`. */
139
+ /**
140
+ * Untyped delete, shared by the typed client and the write hooks.
141
+ * @internal Not part of the public surface.
142
+ */
111
143
  async function deleteDatabaseRow(entity, id, init = {}) {
112
144
  await requestDatabase(resolveDatabaseUrl(entity, "delete", id), {
113
145
  method: "DELETE",
@@ -161,5 +193,5 @@ const databaseApi = {
161
193
  };
162
194
 
163
195
  //#endregion
164
- export { databaseApi };
196
+ export { createDatabaseRow, databaseApi, deleteDatabaseRow, isDatabaseListPage, isDatabaseRow, requestDatabase, resolveDatabaseUrl, updateDatabaseRow };
165
197
  //# sourceMappingURL=client.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"client.js","names":[],"sources":["../../../src/js/database/client.ts"],"sourcesContent":["import {\n type DatabaseErrorDetail,\n type DatabaseListPage,\n type DatabaseListQuery,\n databaseErrorCategoryForStatus,\n encodeDatabaseListQuery,\n encodeDatabaseRecordQuery,\n type ExactDatabaseParams,\n} from \"shared\";\n\nimport { getClientConfig } from \"../config\";\nimport {\n DatabaseApiError,\n invalidDatabaseQuery,\n invalidDatabaseWrite,\n} from \"./errors\";\nimport type {\n DatabaseEntity,\n DatabaseId,\n DatabaseInsert,\n DatabaseKeyedEntity,\n DatabaseListParams,\n DatabaseListRow,\n DatabaseRecordParams,\n DatabaseRecordRow,\n DatabaseRow,\n DatabaseUpdate,\n} from \"./types\";\n\n/** Suffix of the endpoint names `DatabasePlugin` publishes for each table. */\ntype DatabaseOperation = \"list\" | \"detail\" | \"create\" | \"update\" | \"delete\";\n\n/** An id as a keyed route addresses it in its path. */\ntype IdLike = string | number | bigint;\n\n/** Per-call options for a database request. */\nexport interface DatabaseRequestOptions {\n /**\n * Cancels the request; the promise then rejects with the abort reason.\n * Cancelling a write does not undo it once the server has committed.\n */\n readonly signal?: AbortSignal;\n}\n\n/** Typed calls to the routes `DatabasePlugin` generates under `/api/database`. */\nexport interface DatabaseApi {\n /**\n * Read one page from `GET /api/database/<entity>`. Rows are public rows as\n * JSON carries them, narrowed by `select` and widened by `include`.\n *\n * @example\n * ```typescript\n * const page = await databaseApi.list(\"notes\", {\n * where: { board_id: 7 },\n * order: { created_at: \"desc\" },\n * limit: 5,\n * });\n * page.items[0]?.body;\n * ```\n */\n list<K extends DatabaseKeyedEntity>(\n entity: K,\n params?: undefined,\n init?: DatabaseRequestOptions,\n ): Promise<DatabaseListPage<DatabaseListRow<K>>>;\n list<K extends DatabaseEntity, const P extends DatabaseListParams<K>>(\n entity: K,\n params: P & ExactDatabaseParams<P, DatabaseListParams<K>>,\n init?: DatabaseRequestOptions,\n ): Promise<DatabaseListPage<DatabaseListRow<K, P>>>;\n\n /**\n * Read one row from `GET /api/database/<entity>/:id`. Only entities with a\n * public primary key have this route; a missing row rejects with\n * `NOT_FOUND`.\n *\n * @example\n * ```typescript\n * const board = await databaseApi.get(\"boards\", 7, {\n * include: { notes: { limit: 20 } },\n * });\n * board.notes.length;\n * ```\n */\n get<\n K extends DatabaseKeyedEntity,\n const P extends DatabaseRecordParams<K> = Record<never, never>,\n >(\n entity: K,\n id: DatabaseId<K>,\n params?: P & ExactDatabaseParams<P, DatabaseRecordParams<K>>,\n init?: DatabaseRequestOptions,\n ): Promise<DatabaseRecordRow<K, P>>;\n\n /**\n * Create one row with `POST /api/database/<entity>` and return it as the\n * database holds it after any `beforeCreate` hook. Private, generated, and\n * undeclared fields are compile errors, as the server refuses them.\n *\n * @example\n * ```typescript\n * const note = await databaseApi.create(\"notes\", {\n * board_id: 7,\n * author: \"ada\",\n * body: \"Ship it\",\n * });\n * note.id;\n * ```\n */\n create<K extends DatabaseEntity, const V extends DatabaseInsert<K>>(\n entity: K,\n values: V & ExactDatabaseParams<V, DatabaseInsert<K>>,\n init?: DatabaseRequestOptions,\n ): Promise<DatabaseRow<K>>;\n\n /**\n * Change some fields of one row with `PATCH /api/database/<entity>/:id` and\n * return the updated row. A missing row rejects with `NOT_FOUND`.\n *\n * @example\n * ```typescript\n * await databaseApi.update(\"notes\", 7, { body: \"Shipped\" });\n * ```\n */\n update<K extends DatabaseKeyedEntity, const V extends DatabaseUpdate<K>>(\n entity: K,\n id: DatabaseId<K>,\n values: V & ExactDatabaseParams<V, DatabaseUpdate<K>>,\n init?: DatabaseRequestOptions,\n ): Promise<DatabaseRow<K>>;\n\n /**\n * Delete one row with `DELETE /api/database/<entity>/:id`. A missing row\n * rejects with `NOT_FOUND`.\n *\n * @example\n * ```typescript\n * await databaseApi.remove(\"notes\", 7);\n * ```\n */\n remove<K extends DatabaseKeyedEntity>(\n entity: K,\n id: DatabaseId<K>,\n init?: DatabaseRequestOptions,\n ): Promise<void>;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * Find the route the server published for one operation. The plugin publishes\n * only what its `api` configuration exposes, so a missing entry is refused\n * here with `NOT_EXPOSED` and no request is sent.\n */\nfunction resolveDatabaseUrl(\n entity: string,\n operation: DatabaseOperation,\n id?: IdLike,\n query?: string,\n): string {\n const name = `${entity}.${operation}`;\n const endpoints = getClientConfig().endpoints.database;\n const path =\n isRecord(endpoints) && Object.hasOwn(endpoints, name)\n ? endpoints[name]\n : undefined;\n if (typeof path !== \"string\") {\n throw new DatabaseApiError(\n \"NOT_EXPOSED\",\n null,\n `Database operation \"${name}\" is not exposed`,\n );\n }\n const url =\n id === undefined\n ? path\n : path.replace(\":id\", encodeURIComponent(String(id)));\n return query ? `${url}?${query}` : url;\n}\n\n/** Keep only details shaped like the server's; they name public fields only. */\nfunction publicDetails(value: unknown): DatabaseErrorDetail[] {\n if (!Array.isArray(value)) return [];\n return value.flatMap((detail): DatabaseErrorDetail[] =>\n isRecord(detail) &&\n typeof detail.message === \"string\" &&\n Array.isArray(detail.path) &&\n detail.path.every((segment) => typeof segment === \"string\")\n ? [{ path: [...detail.path], message: detail.message }]\n : [],\n );\n}\n\n/** Decode a failure envelope; a non-JSON body still keeps its category. */\nasync function failure(response: Response): Promise<DatabaseApiError> {\n const body: unknown = await response.json().catch(() => undefined);\n const envelope = isRecord(body) ? body : {};\n return new DatabaseApiError(\n databaseErrorCategoryForStatus(response.status),\n response.status,\n typeof envelope.error === \"string\"\n ? envelope.error\n : `Database request failed with status ${response.status}`,\n publicDetails(envelope.details),\n );\n}\n\n/**\n * Send one request and decode its JSON body, throwing `DatabaseApiError` for\n * anything but the shape `accept` expects. A `204` has no body, so `accept`\n * sees `undefined`. An abort rejects with the signal's own reason, so a\n * caller can tell cancellation from failure.\n */\nasync function requestDatabase<T>(\n url: string,\n init: RequestInit,\n accept: (body: unknown) => body is T,\n): Promise<T> {\n const headers = new Headers(init.headers);\n headers.set(\"Accept\", \"application/json\");\n const write = init.method !== \"GET\";\n let response: Response;\n try {\n response = await fetch(url, { ...init, headers });\n } catch (error) {\n if (init.signal?.aborted) throw error;\n throw new DatabaseApiError(\n write ? \"OUTCOME_UNKNOWN\" : \"TRANSIENT\",\n null,\n write\n ? \"Database write may have completed; check its result before retrying\"\n : \"Database read failed before receiving a response\",\n [],\n { cause: error },\n );\n }\n if (!response.ok) throw await failure(response);\n\n let body: unknown;\n try {\n body = response.status === 204 ? undefined : await response.json();\n } catch (error) {\n if (init.signal?.aborted) throw error;\n throw new DatabaseApiError(\n write ? \"OUTCOME_UNKNOWN\" : \"INTERNAL\",\n response.status,\n write\n ? \"Database write may have completed; response is not JSON\"\n : \"Database response is not JSON\",\n [],\n { cause: error },\n );\n }\n if (!accept(body)) {\n throw new DatabaseApiError(\n write ? \"OUTCOME_UNKNOWN\" : \"INTERNAL\",\n response.status,\n write\n ? \"Database write may have completed; response has an unexpected shape\"\n : \"Database response has an unexpected shape\",\n );\n }\n return body;\n}\n\n/** The `{ items, limit, offset }` envelope a list route answers with. */\nfunction isDatabaseListPage(body: unknown): body is DatabaseListPage<unknown> {\n return (\n isRecord(body) &&\n Array.isArray(body.items) &&\n typeof body.limit === \"number\" &&\n typeof body.offset === \"number\"\n );\n}\n\n/** A detail route answers one bare row; a serializer returns an object too. */\nfunction isDatabaseRow(body: unknown): body is Record<string, unknown> {\n return isRecord(body);\n}\n\n/** A delete answers `204` with nothing to decode. */\nfunction isNoContent(body: unknown): body is undefined {\n return body === undefined;\n}\n\n/** A write must not lose a non-finite number to JSON's implicit null coercion. */\nfunction jsonWriteValue(_key: string, value: unknown): unknown {\n if (typeof value === \"number\" && !Number.isFinite(value)) {\n throw invalidDatabaseWrite(\n \"Database write numbers must be finite; use null explicitly to clear a value\",\n );\n }\n return typeof value === \"bigint\" ? value.toString() : value;\n}\n\n/** A write sends its values as a JSON body, the only type its route parses. */\nfunction jsonWrite(\n method: \"POST\" | \"PATCH\",\n values: object,\n signal: AbortSignal | undefined,\n): RequestInit {\n try {\n return {\n method,\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(values, jsonWriteValue),\n signal,\n };\n } catch (error) {\n if (error instanceof DatabaseApiError) throw error;\n throw invalidDatabaseWrite();\n }\n}\n\n/**\n * Untyped create behind `databaseApi.create`; its signature carries the\n * checks, while the entity is still a literal.\n */\nasync function createDatabaseRow(\n entity: string,\n values: object,\n init: DatabaseRequestOptions = {},\n): Promise<Record<string, unknown>> {\n const url = resolveDatabaseUrl(entity, \"create\");\n return requestDatabase(\n url,\n jsonWrite(\"POST\", values, init.signal),\n isDatabaseRow,\n );\n}\n\n/** Untyped update behind `databaseApi.update`. */\nasync function updateDatabaseRow(\n entity: string,\n id: IdLike,\n values: object,\n init: DatabaseRequestOptions = {},\n): Promise<Record<string, unknown>> {\n const url = resolveDatabaseUrl(entity, \"update\", id);\n return requestDatabase(\n url,\n jsonWrite(\"PATCH\", values, init.signal),\n isDatabaseRow,\n );\n}\n\n/** Untyped delete behind `databaseApi.remove`. */\nasync function deleteDatabaseRow(\n entity: string,\n id: IdLike,\n init: DatabaseRequestOptions = {},\n): Promise<void> {\n const url = resolveDatabaseUrl(entity, \"delete\", id);\n await requestDatabase(\n url,\n { method: \"DELETE\", signal: init.signal },\n isNoContent,\n );\n}\n\nfunction list<K extends DatabaseKeyedEntity>(\n entity: K,\n params?: undefined,\n init?: DatabaseRequestOptions,\n): Promise<DatabaseListPage<DatabaseListRow<K>>>;\nfunction list<K extends DatabaseEntity, const P extends DatabaseListParams<K>>(\n entity: K,\n params: P & ExactDatabaseParams<P, DatabaseListParams<K>>,\n init?: DatabaseRequestOptions,\n): Promise<DatabaseListPage<DatabaseListRow<K, P>>>;\nasync function list(\n entity: string,\n params?: DatabaseListQuery,\n init: DatabaseRequestOptions = {},\n): Promise<DatabaseListPage<unknown>> {\n let query: string;\n try {\n query = encodeDatabaseListQuery(params ?? {});\n } catch (error) {\n throw invalidDatabaseQuery(error);\n }\n const url = resolveDatabaseUrl(entity, \"list\", undefined, query);\n const page = await requestDatabase(\n url,\n { method: \"GET\", signal: init.signal },\n isDatabaseListPage,\n );\n return page;\n}\n\nasync function get<\n K extends DatabaseKeyedEntity,\n const P extends DatabaseRecordParams<K> = Record<never, never>,\n>(\n entity: K,\n id: DatabaseId<K>,\n params?: P & ExactDatabaseParams<P, DatabaseRecordParams<K>>,\n init: DatabaseRequestOptions = {},\n): Promise<DatabaseRecordRow<K, P>> {\n let query: string;\n try {\n query = encodeDatabaseRecordQuery(params ?? {});\n } catch (error) {\n throw invalidDatabaseQuery(error);\n }\n const url = resolveDatabaseUrl(entity, \"detail\", id, query);\n const row = await requestDatabase(\n url,\n { method: \"GET\", signal: init.signal },\n isDatabaseRow,\n );\n return row as DatabaseRecordRow<K, P>;\n}\n\nasync function create<\n K extends DatabaseEntity,\n const V extends DatabaseInsert<K>,\n>(\n entity: K,\n values: V & ExactDatabaseParams<V, DatabaseInsert<K>>,\n init: DatabaseRequestOptions = {},\n): Promise<DatabaseRow<K>> {\n // `values` is an insert object; a still-generic `K` only widens its type.\n const row = await createDatabaseRow(entity, values as object, init);\n // The server projected the row it holds; the types describe that wire.\n return row as DatabaseRow<K>;\n}\n\nasync function update<\n K extends DatabaseKeyedEntity,\n const V extends DatabaseUpdate<K>,\n>(\n entity: K,\n id: DatabaseId<K>,\n values: V & ExactDatabaseParams<V, DatabaseUpdate<K>>,\n init: DatabaseRequestOptions = {},\n): Promise<DatabaseRow<K>> {\n const row = await updateDatabaseRow(entity, id, values as object, init);\n return row as DatabaseRow<K>;\n}\n\nfunction remove<K extends DatabaseKeyedEntity>(\n entity: K,\n id: DatabaseId<K>,\n init: DatabaseRequestOptions = {},\n): Promise<void> {\n return deleteDatabaseRow(entity, id, init);\n}\n\n/**\n * Typed browser client for the routes `DatabasePlugin` generates. Entity names,\n * params, and rows come from the generated `database.d.ts`; routes come from\n * the endpoints the server published in the boot payload.\n */\nexport const databaseApi: DatabaseApi = { list, get, create, update, remove };\n"],"mappings":";;;;;;AAmJA,SAAS,SAAS,OAAkD;AAClE,QAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,MAAM;;;;;;;AAQ7E,SAAS,mBACP,QACA,WACA,IACA,OACQ;CACR,MAAM,OAAO,GAAG,OAAO,GAAG;CAC1B,MAAM,YAAY,iBAAiB,CAAC,UAAU;CAC9C,MAAM,OACJ,SAAS,UAAU,IAAI,OAAO,OAAO,WAAW,KAAK,GACjD,UAAU,QACV;AACN,KAAI,OAAO,SAAS,SAClB,OAAM,IAAI,iBACR,eACA,MACA,uBAAuB,KAAK,kBAC7B;CAEH,MAAM,MACJ,OAAO,SACH,OACA,KAAK,QAAQ,OAAO,mBAAmB,OAAO,GAAG,CAAC,CAAC;AACzD,QAAO,QAAQ,GAAG,IAAI,GAAG,UAAU;;;AAIrC,SAAS,cAAc,OAAuC;AAC5D,KAAI,CAAC,MAAM,QAAQ,MAAM,CAAE,QAAO,EAAE;AACpC,QAAO,MAAM,SAAS,WACpB,SAAS,OAAO,IAChB,OAAO,OAAO,YAAY,YAC1B,MAAM,QAAQ,OAAO,KAAK,IAC1B,OAAO,KAAK,OAAO,YAAY,OAAO,YAAY,SAAS,GACvD,CAAC;EAAE,MAAM,CAAC,GAAG,OAAO,KAAK;EAAE,SAAS,OAAO;EAAS,CAAC,GACrD,EAAE,CACP;;;AAIH,eAAe,QAAQ,UAA+C;CACpE,MAAM,OAAgB,MAAM,SAAS,MAAM,CAAC,YAAY,OAAU;CAClE,MAAM,WAAW,SAAS,KAAK,GAAG,OAAO,EAAE;AAC3C,QAAO,IAAI,iBACT,+BAA+B,SAAS,OAAO,EAC/C,SAAS,QACT,OAAO,SAAS,UAAU,WACtB,SAAS,QACT,uCAAuC,SAAS,UACpD,cAAc,SAAS,QAAQ,CAChC;;;;;;;;AASH,eAAe,gBACb,KACA,MACA,QACY;CAC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ACA,QACA,OAA+B,EAAE,EACR;AAEzB,QADY,MAAM,kBAAkB,QAAQ,IAAI,QAAkB,KAAK;;AAIzE,SAAS,OACP,QACA,IACA,OAA+B,EAAE,EAClB;AACf,QAAO,kBAAkB,QAAQ,IAAI,KAAK;;;;;;;AAQ5C,MAAa,cAA2B;CAAE;CAAM;CAAK;CAAQ;CAAQ;CAAQ"}
1
+ {"version":3,"file":"client.js","names":[],"sources":["../../../src/js/database/client.ts"],"sourcesContent":["import {\n type DatabaseErrorDetail,\n type DatabaseListPage,\n type DatabaseListQuery,\n databaseErrorCategoryForStatus,\n encodeDatabaseListQuery,\n encodeDatabaseRecordQuery,\n type ExactDatabaseParams,\n} from \"shared\";\n\nimport { getClientConfig } from \"../config\";\nimport {\n DatabaseApiError,\n invalidDatabaseQuery,\n invalidDatabaseWrite,\n} from \"./errors\";\nimport type {\n DatabaseEntity,\n DatabaseId,\n DatabaseInsert,\n DatabaseKeyedEntity,\n DatabaseListParams,\n DatabaseListRow,\n DatabaseRecordParams,\n DatabaseRecordRow,\n DatabaseRow,\n DatabaseUpdate,\n} from \"./types\";\n\n/**\n * Suffix of the endpoint names `DatabasePlugin` publishes for each table.\n * @internal Shared with the React hooks; not part of the public surface.\n */\nexport type DatabaseOperation =\n | \"list\"\n | \"detail\"\n | \"create\"\n | \"update\"\n | \"delete\";\n\n/**\n * An id as a keyed route addresses it in its path.\n * @internal Shared with the React hooks; not part of the public surface.\n */\nexport type IdLike = string | number | bigint;\n\n/** Per-call options for a database request. */\nexport interface DatabaseRequestOptions {\n /**\n * Cancels the request; the promise then rejects with the abort reason.\n * Cancelling a write does not undo it once the server has committed.\n */\n readonly signal?: AbortSignal;\n}\n\n/** Typed calls to the routes `DatabasePlugin` generates under `/api/database`. */\nexport interface DatabaseApi {\n /**\n * Read one page from `GET /api/database/<entity>`. Rows are public rows as\n * JSON carries them, narrowed by `select` and widened by `include`.\n *\n * @example\n * ```typescript\n * const page = await databaseApi.list(\"notes\", {\n * where: { board_id: 7 },\n * order: { created_at: \"desc\" },\n * limit: 5,\n * });\n * page.items[0]?.body;\n * ```\n */\n list<K extends DatabaseKeyedEntity>(\n entity: K,\n params?: undefined,\n init?: DatabaseRequestOptions,\n ): Promise<DatabaseListPage<DatabaseListRow<K>>>;\n list<K extends DatabaseEntity, const P extends DatabaseListParams<K>>(\n entity: K,\n params: P & ExactDatabaseParams<P, DatabaseListParams<K>>,\n init?: DatabaseRequestOptions,\n ): Promise<DatabaseListPage<DatabaseListRow<K, P>>>;\n\n /**\n * Read one row from `GET /api/database/<entity>/:id`. Only entities with a\n * public primary key have this route; a missing row rejects with\n * `NOT_FOUND`.\n *\n * @example\n * ```typescript\n * const board = await databaseApi.get(\"boards\", 7, {\n * include: { notes: { limit: 20 } },\n * });\n * board.notes.length;\n * ```\n */\n get<\n K extends DatabaseKeyedEntity,\n const P extends DatabaseRecordParams<K> = Record<never, never>,\n >(\n entity: K,\n id: DatabaseId<K>,\n params?: P & ExactDatabaseParams<P, DatabaseRecordParams<K>>,\n init?: DatabaseRequestOptions,\n ): Promise<DatabaseRecordRow<K, P>>;\n\n /**\n * Create one row with `POST /api/database/<entity>` and return it as the\n * database holds it after any `beforeCreate` hook. Private, generated, and\n * undeclared fields are compile errors, as the server refuses them.\n *\n * @example\n * ```typescript\n * const note = await databaseApi.create(\"notes\", {\n * board_id: 7,\n * author: \"ada\",\n * body: \"Ship it\",\n * });\n * note.id;\n * ```\n */\n create<K extends DatabaseEntity, const V extends DatabaseInsert<K>>(\n entity: K,\n values: V & ExactDatabaseParams<V, DatabaseInsert<K>>,\n init?: DatabaseRequestOptions,\n ): Promise<DatabaseRow<K>>;\n\n /**\n * Change some fields of one row with `PATCH /api/database/<entity>/:id` and\n * return the updated row. A missing row rejects with `NOT_FOUND`.\n *\n * @example\n * ```typescript\n * await databaseApi.update(\"notes\", 7, { body: \"Shipped\" });\n * ```\n */\n update<K extends DatabaseKeyedEntity, const V extends DatabaseUpdate<K>>(\n entity: K,\n id: DatabaseId<K>,\n values: V & ExactDatabaseParams<V, DatabaseUpdate<K>>,\n init?: DatabaseRequestOptions,\n ): Promise<DatabaseRow<K>>;\n\n /**\n * Delete one row with `DELETE /api/database/<entity>/:id`. A missing row\n * rejects with `NOT_FOUND`.\n *\n * @example\n * ```typescript\n * await databaseApi.remove(\"notes\", 7);\n * ```\n */\n remove<K extends DatabaseKeyedEntity>(\n entity: K,\n id: DatabaseId<K>,\n init?: DatabaseRequestOptions,\n ): Promise<void>;\n}\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\n/**\n * An id that URL resolution would not keep as one path segment: `\"\"` and\n * `\".\"` collapse onto the list route and `\"..\"` climbs above the table, so a\n * keyed request would silently reach another route.\n */\nfunction isUnaddressableId(segment: string): boolean {\n return segment === \"\" || segment === \".\" || segment === \"..\";\n}\n\n/**\n * Find the route the server published for one operation. The plugin publishes\n * only what its `api` configuration exposes, so a missing entry is refused\n * here with `NOT_EXPOSED` and no request is sent. An id that is not one path\n * segment is refused with `INVALID_REQUEST`, also without a request.\n *\n * @internal Shared with the React hooks; not part of the public surface.\n */\nexport function resolveDatabaseUrl(\n entity: string,\n operation: DatabaseOperation,\n id?: IdLike,\n query?: string,\n): string {\n const name = `${entity}.${operation}`;\n const endpoints = getClientConfig().endpoints.database;\n const path =\n isRecord(endpoints) && Object.hasOwn(endpoints, name)\n ? endpoints[name]\n : undefined;\n if (typeof path !== \"string\") {\n throw new DatabaseApiError(\n \"NOT_EXPOSED\",\n null,\n `Database operation \"${name}\" is not exposed`,\n );\n }\n let url = path;\n if (id !== undefined) {\n const segment = String(id);\n if (isUnaddressableId(segment)) {\n // The id may be user input from a route param; do not echo it.\n throw new DatabaseApiError(\n \"INVALID_REQUEST\",\n null,\n \"Database id must be a non-empty path segment\",\n );\n }\n url = path.replace(\":id\", encodeURIComponent(segment));\n }\n return query ? `${url}?${query}` : url;\n}\n\n/** Keep only details shaped like the server's; they name public fields only. */\nfunction publicDetails(value: unknown): DatabaseErrorDetail[] {\n if (!Array.isArray(value)) return [];\n return value.flatMap((detail): DatabaseErrorDetail[] =>\n isRecord(detail) &&\n typeof detail.message === \"string\" &&\n Array.isArray(detail.path) &&\n detail.path.every((segment) => typeof segment === \"string\")\n ? [{ path: [...detail.path], message: detail.message }]\n : [],\n );\n}\n\n/** Decode a failure envelope; a non-JSON body still keeps its category. */\nasync function failure(response: Response): Promise<DatabaseApiError> {\n const body: unknown = await response.json().catch(() => undefined);\n const envelope = isRecord(body) ? body : {};\n return new DatabaseApiError(\n databaseErrorCategoryForStatus(response.status),\n response.status,\n typeof envelope.error === \"string\"\n ? envelope.error\n : `Database request failed with status ${response.status}`,\n publicDetails(envelope.details),\n );\n}\n\n/**\n * Send one request and decode its JSON body, throwing `DatabaseApiError` for\n * anything but the shape `accept` expects. A `204` has no body, so `accept`\n * sees `undefined`. An abort rejects with the signal's own reason, so a\n * caller can tell cancellation from failure.\n *\n * @internal Shared with the React hooks; not part of the public surface.\n */\nexport async function requestDatabase<T>(\n url: string,\n init: RequestInit,\n accept: (body: unknown) => body is T,\n): Promise<T> {\n const headers = new Headers(init.headers);\n headers.set(\"Accept\", \"application/json\");\n const write = init.method !== \"GET\";\n let response: Response;\n try {\n response = await fetch(url, { ...init, headers });\n } catch (error) {\n if (init.signal?.aborted) throw error;\n throw new DatabaseApiError(\n write ? \"OUTCOME_UNKNOWN\" : \"TRANSIENT\",\n null,\n write\n ? \"Database write may have completed; check its result before retrying\"\n : \"Database read failed before receiving a response\",\n [],\n { cause: error },\n );\n }\n if (!response.ok) throw await failure(response);\n\n let body: unknown;\n try {\n body = response.status === 204 ? undefined : await response.json();\n } catch (error) {\n if (init.signal?.aborted) throw error;\n throw new DatabaseApiError(\n write ? \"OUTCOME_UNKNOWN\" : \"INTERNAL\",\n response.status,\n write\n ? \"Database write may have completed; response is not JSON\"\n : \"Database response is not JSON\",\n [],\n { cause: error },\n );\n }\n if (!accept(body)) {\n throw new DatabaseApiError(\n write ? \"OUTCOME_UNKNOWN\" : \"INTERNAL\",\n response.status,\n write\n ? \"Database write may have completed; response has an unexpected shape\"\n : \"Database response has an unexpected shape\",\n );\n }\n return body;\n}\n\n/**\n * The `{ items, limit, offset }` envelope a list route answers with.\n * @internal Shared with the React hooks; not part of the public surface.\n */\nexport function isDatabaseListPage(\n body: unknown,\n): body is DatabaseListPage<unknown> {\n return (\n isRecord(body) &&\n Array.isArray(body.items) &&\n typeof body.limit === \"number\" &&\n typeof body.offset === \"number\"\n );\n}\n\n/**\n * A detail route answers one bare row; a serializer returns an object too.\n * @internal Shared with the React hooks; not part of the public surface.\n */\nexport function isDatabaseRow(body: unknown): body is Record<string, unknown> {\n return isRecord(body);\n}\n\n/** A delete answers `204` with nothing to decode. */\nfunction isNoContent(body: unknown): body is undefined {\n return body === undefined;\n}\n\n/** A write must not lose a non-finite number to JSON's implicit null coercion. */\nfunction jsonWriteValue(_key: string, value: unknown): unknown {\n if (typeof value === \"number\" && !Number.isFinite(value)) {\n throw invalidDatabaseWrite(\n \"Database write numbers must be finite; use null explicitly to clear a value\",\n );\n }\n return typeof value === \"bigint\" ? value.toString() : value;\n}\n\n/** A write sends its values as a JSON body, the only type its route parses. */\nfunction jsonWrite(\n method: \"POST\" | \"PATCH\",\n values: object,\n signal: AbortSignal | undefined,\n): RequestInit {\n try {\n return {\n method,\n headers: { \"Content-Type\": \"application/json\" },\n body: JSON.stringify(values, jsonWriteValue),\n signal,\n };\n } catch (error) {\n if (error instanceof DatabaseApiError) throw error;\n throw invalidDatabaseWrite();\n }\n}\n\n/**\n * Untyped create behind `databaseApi.create` and `useDatabaseCreate`; their\n * signatures carry the checks, while the entity is still a literal.\n *\n * @internal Shared with the React hooks; not part of the public surface.\n */\nexport async function createDatabaseRow(\n entity: string,\n values: object,\n init: DatabaseRequestOptions = {},\n): Promise<Record<string, unknown>> {\n const url = resolveDatabaseUrl(entity, \"create\");\n return requestDatabase(\n url,\n jsonWrite(\"POST\", values, init.signal),\n isDatabaseRow,\n );\n}\n\n/**\n * Untyped update, shared by the typed client and the write hooks.\n * @internal Not part of the public surface.\n */\nexport async function updateDatabaseRow(\n entity: string,\n id: IdLike,\n values: object,\n init: DatabaseRequestOptions = {},\n): Promise<Record<string, unknown>> {\n const url = resolveDatabaseUrl(entity, \"update\", id);\n return requestDatabase(\n url,\n jsonWrite(\"PATCH\", values, init.signal),\n isDatabaseRow,\n );\n}\n\n/**\n * Untyped delete, shared by the typed client and the write hooks.\n * @internal Not part of the public surface.\n */\nexport async function deleteDatabaseRow(\n entity: string,\n id: IdLike,\n init: DatabaseRequestOptions = {},\n): Promise<void> {\n const url = resolveDatabaseUrl(entity, \"delete\", id);\n await requestDatabase(\n url,\n { method: \"DELETE\", signal: init.signal },\n isNoContent,\n );\n}\n\nfunction list<K extends DatabaseKeyedEntity>(\n entity: K,\n params?: undefined,\n init?: DatabaseRequestOptions,\n): Promise<DatabaseListPage<DatabaseListRow<K>>>;\nfunction list<K extends DatabaseEntity, const P extends DatabaseListParams<K>>(\n entity: K,\n params: P & ExactDatabaseParams<P, DatabaseListParams<K>>,\n init?: DatabaseRequestOptions,\n): Promise<DatabaseListPage<DatabaseListRow<K, P>>>;\nasync function list(\n entity: string,\n params?: DatabaseListQuery,\n init: DatabaseRequestOptions = {},\n): Promise<DatabaseListPage<unknown>> {\n let query: string;\n try {\n query = encodeDatabaseListQuery(params ?? {});\n } catch (error) {\n throw invalidDatabaseQuery(error);\n }\n const url = resolveDatabaseUrl(entity, \"list\", undefined, query);\n const page = await requestDatabase(\n url,\n { method: \"GET\", signal: init.signal },\n isDatabaseListPage,\n );\n return page;\n}\n\nasync function get<\n K extends DatabaseKeyedEntity,\n const P extends DatabaseRecordParams<K> = Record<never, never>,\n>(\n entity: K,\n id: DatabaseId<K>,\n params?: P & ExactDatabaseParams<P, DatabaseRecordParams<K>>,\n init: DatabaseRequestOptions = {},\n): Promise<DatabaseRecordRow<K, P>> {\n let query: string;\n try {\n query = encodeDatabaseRecordQuery(params ?? {});\n } catch (error) {\n throw invalidDatabaseQuery(error);\n }\n const url = resolveDatabaseUrl(entity, \"detail\", id, query);\n const row = await requestDatabase(\n url,\n { method: \"GET\", signal: init.signal },\n isDatabaseRow,\n );\n return row as DatabaseRecordRow<K, P>;\n}\n\nasync function create<\n K extends DatabaseEntity,\n const V extends DatabaseInsert<K>,\n>(\n entity: K,\n values: V & ExactDatabaseParams<V, DatabaseInsert<K>>,\n init: DatabaseRequestOptions = {},\n): Promise<DatabaseRow<K>> {\n // `values` is an insert object; a still-generic `K` only widens its type.\n const row = await createDatabaseRow(entity, values as object, init);\n // The server projected the row it holds; the types describe that wire.\n return row as DatabaseRow<K>;\n}\n\nasync function update<\n K extends DatabaseKeyedEntity,\n const V extends DatabaseUpdate<K>,\n>(\n entity: K,\n id: DatabaseId<K>,\n values: V & ExactDatabaseParams<V, DatabaseUpdate<K>>,\n init: DatabaseRequestOptions = {},\n): Promise<DatabaseRow<K>> {\n const row = await updateDatabaseRow(entity, id, values as object, init);\n return row as DatabaseRow<K>;\n}\n\nfunction remove<K extends DatabaseKeyedEntity>(\n entity: K,\n id: DatabaseId<K>,\n init: DatabaseRequestOptions = {},\n): Promise<void> {\n return deleteDatabaseRow(entity, id, init);\n}\n\n/**\n * Typed browser client for the routes `DatabasePlugin` generates. Entity names,\n * params, and rows come from the generated `database.d.ts`; routes come from\n * the endpoints the server published in the boot payload.\n */\nexport const databaseApi: DatabaseApi = { list, get, create, update, remove };\n"],"mappings":";;;;;;AA8JA,SAAS,SAAS,OAAkD;AAClE,QAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,MAAM;;;;;;;AAQ7E,SAAS,kBAAkB,SAA0B;AACnD,QAAO,YAAY,MAAM,YAAY,OAAO,YAAY;;;;;;;;;;AAW1D,SAAgB,mBACd,QACA,WACA,IACA,OACQ;CACR,MAAM,OAAO,GAAG,OAAO,GAAG;CAC1B,MAAM,YAAY,iBAAiB,CAAC,UA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IAAI,KAAK;;;;;;;AAQ5C,MAAa,cAA2B;CAAE;CAAM;CAAK;CAAQ;CAAQ;CAAQ"}
@@ -1,3 +1,16 @@
1
+ import { DatabaseListPage } from "../shared/src/database/api-types.js";
2
+ import { DatabaseErrorDetail } from "../shared/src/database/errors.js";
3
+ import { DatabaseEntity, DatabaseId, DatabaseInsert, DatabaseKeyedEntity, DatabaseListParams, DatabaseListRow, DatabaseRecordParams, DatabaseRecordRow, DatabaseRow, DatabaseUpdate } from "../js/database/types.js";
4
+ import { DatabaseApiError, DatabaseApiErrorCode } from "../js/database/errors.js";
5
+ import "../js/beta.js";
1
6
  import { AiSearchClientConfig, AiSearchIndexSummary, AiSearchQueryType, AiSearchRequest, AiSearchResponse, AiSearchResult } from "./hooks/types.js";
2
7
  import { UseAiSearchQueryOptions, UseAiSearchQueryResult, useAiSearchQuery } from "./hooks/use-ai-search-query.js";
3
- export { type AiSearchClientConfig, type AiSearchIndexSummary, type AiSearchQueryType, type AiSearchRequest, type AiSearchResponse, type AiSearchResult, type UseAiSearchQueryOptions, type UseAiSearchQueryResult, useAiSearchQuery };
8
+ import { DatabaseInvalidation, invalidateDatabaseReads } from "./hooks/database-request-store.js";
9
+ import { UseDatabaseWriteOptions, UseDatabaseWriteState } from "./hooks/use-database-write.js";
10
+ import { UseDatabaseCreateOptions, UseDatabaseCreateResult, useDatabaseCreate } from "./hooks/use-database-create.js";
11
+ import { UseDatabaseDeleteOptions, UseDatabaseDeleteResult, useDatabaseDelete } from "./hooks/use-database-delete.js";
12
+ import { DatabaseRowShape, DatabaseShape, UseDatabaseReadOptions, UseDatabaseReadResult, serialized } from "./hooks/use-database-read.js";
13
+ import { UseDatabaseListOptions, UseDatabaseListResult, useDatabaseList } from "./hooks/use-database-list.js";
14
+ import { UseDatabaseRecordOptions, UseDatabaseRecordResult, useDatabaseRecord } from "./hooks/use-database-record.js";
15
+ import { UseDatabaseUpdateOptions, UseDatabaseUpdateResult, useDatabaseUpdate } from "./hooks/use-database-update.js";
16
+ export { type AiSearchClientConfig, type AiSearchIndexSummary, type AiSearchQueryType, type AiSearchRequest, type AiSearchResponse, type AiSearchResult, DatabaseApiError, type DatabaseApiErrorCode, type DatabaseEntity, type DatabaseErrorDetail, type DatabaseId, type DatabaseInsert, type DatabaseInvalidation, type DatabaseKeyedEntity, type DatabaseListPage, type DatabaseListParams, type DatabaseListRow, type DatabaseRecordParams, type DatabaseRecordRow, type DatabaseRow, type DatabaseRowShape, type DatabaseShape, type DatabaseUpdate, type UseAiSearchQueryOptions, type UseAiSearchQueryResult, type UseDatabaseCreateOptions, type UseDatabaseCreateResult, type UseDatabaseDeleteOptions, type UseDatabaseDeleteResult, type UseDatabaseListOptions, type UseDatabaseListResult, type UseDatabaseReadOptions, type UseDatabaseReadResult, type UseDatabaseRecordOptions, type UseDatabaseRecordResult, type UseDatabaseUpdateOptions, type UseDatabaseUpdateResult, type UseDatabaseWriteOptions, type UseDatabaseWriteState, invalidateDatabaseReads, serialized, useAiSearchQuery, useDatabaseCreate, useDatabaseDelete, useDatabaseList, useDatabaseRecord, useDatabaseUpdate };
@@ -1,3 +1,11 @@
1
+ import { DatabaseApiError } from "../js/database/errors.js";
1
2
  import { useAiSearchQuery } from "./hooks/use-ai-search-query.js";
3
+ import { invalidateDatabaseReads } from "./hooks/database-request-store.js";
4
+ import { useDatabaseCreate } from "./hooks/use-database-create.js";
5
+ import { useDatabaseDelete } from "./hooks/use-database-delete.js";
6
+ import { serialized } from "./hooks/use-database-read.js";
7
+ import { useDatabaseList } from "./hooks/use-database-list.js";
8
+ import { useDatabaseRecord } from "./hooks/use-database-record.js";
9
+ import { useDatabaseUpdate } from "./hooks/use-database-update.js";
2
10
 
3
- export { useAiSearchQuery };
11
+ export { DatabaseApiError, invalidateDatabaseReads, serialized, useAiSearchQuery, useDatabaseCreate, useDatabaseDelete, useDatabaseList, useDatabaseRecord, useDatabaseUpdate };
@@ -131,7 +131,7 @@ const store = createRequestStore(EMPTY_SNAPSHOT);
131
131
  * Returns a `release` function that must be called on unmount.
132
132
  */
133
133
  function retain(key, options, autoStart = true) {
134
- return store.retain(key, runAnalyticsRequest(options), autoStart);
134
+ return store.retain(key, runAnalyticsRequest(options), { autoStart });
135
135
  }
136
136
  const start = store.start;
137
137
  const subscribe = store.subscribe;
@@ -1 +1 @@
1
- {"version":3,"file":"analytics-request-store.js","names":[],"sources":["../../../src/react/hooks/analytics-request-store.ts"],"sourcesContent":["import { ArrowClient, connectSSE } from \"@/js\";\n\nimport {\n type AnalyticsSseHandlerContext,\n GENERIC_LOAD_ERROR,\n handleAnalyticsSseError,\n handleAnalyticsSseMessage,\n userFacingFetchError,\n} from \"./analytics-sse\";\nimport {\n createRequestStore,\n type RequestControls,\n type RequestRunner,\n} from \"./request-store\";\nimport type { WarehouseStatus } from \"./types\";\n\n/**\n * Shared in-flight request store for `useAnalyticsQuery`: an instance of the\n * generic {@link createRequestStore} lifecycle wired to the analytics\n * transports. Multiple hook instances resolving to the same request (query\n * key, parameters, format, dev mode) share one network request and see the\n * same result and mid-flight `warehouse_status` updates.\n *\n * The lifecycle (dedup, refcount, deferred teardown) lives in the factory; this\n * module only supplies the snapshot shape and how a request runs — SSE via\n * `analytics-sse.ts` or a direct Arrow fetch.\n */\n\n/** Options describing the request a keyed entry runs. */\ninterface AnalyticsRequestOptions {\n /** Full request URL (already includes the encoded query key and dev suffix). */\n url: string;\n /** Serialized `{ parameters, format }` body. */\n payload: string;\n /** Response format; selects the transport. */\n format: string;\n}\n\n/** Immutable per-key request state; mirrors the hook's public result shape. */\ninterface AnalyticsRequestSnapshot {\n data: unknown;\n loading: boolean;\n error: string | null;\n errorCode: string | null;\n warehouseStatus: WarehouseStatus | null;\n}\n\n/** Idle snapshot returned for keys with no live entry. Referentially stable. */\nconst EMPTY_SNAPSHOT: AnalyticsRequestSnapshot = {\n data: null,\n loading: false,\n error: null,\n errorCode: null,\n warehouseStatus: null,\n};\n\n/** Snapshot a request resets to when it (re)starts. */\nconst LOADING_SNAPSHOT: AnalyticsRequestSnapshot = {\n data: null,\n loading: true,\n error: null,\n errorCode: null,\n warehouseStatus: null,\n};\n\ntype Controls = RequestControls<AnalyticsRequestSnapshot>;\n\n/**\n * Fetch the real column names for a statement from the fallback endpoint,\n * used when a very wide schema's names didn't fit in the response header.\n * Returns undefined on any failure so decoding falls back to the raw Arrow\n * schema names.\n */\nasync function fetchArrowColumns(\n statementId: string,\n signal: AbortSignal,\n): Promise<string[] | undefined> {\n try {\n const res = await fetch(\n `/api/analytics/columns/${encodeURIComponent(statementId)}`,\n { signal },\n );\n if (!res.ok) return undefined;\n const body = (await res.json()) as { columns?: unknown };\n return Array.isArray(body.columns) ? (body.columns as string[]) : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Fetch an ARROW_STREAM query result as raw Arrow IPC bytes directly from\n * the query endpoint (no SSE, no second /arrow-result request) and decode\n * it into a Table. The server streams the bytes back as the POST response\n * body; errors before the first byte arrive as a JSON `{ error, errorCode }`.\n */\nasync function fetchArrowDirect(\n controls: Controls,\n options: AnalyticsRequestOptions,\n): Promise<void> {\n const { signal } = controls;\n try {\n const response = await fetch(options.url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: options.payload,\n signal,\n });\n if (signal.aborted) return;\n\n if (!response.ok) {\n let message = GENERIC_LOAD_ERROR;\n let code: string | null = null;\n try {\n const body = (await response.json()) as {\n error?: string;\n errorCode?: string;\n };\n if (body.error) message = body.error;\n if (typeof body.errorCode === \"string\") code = body.errorCode;\n } catch {\n // Non-JSON error body — keep the generic message.\n }\n controls.patch({ loading: false, error: message, errorCode: code });\n return;\n }\n\n const buffer = await response.arrayBuffer();\n if (signal.aborted) return;\n // Databricks encodes ARROW_STREAM columns positionally (col_0, …); the\n // server sends the real manifest names so we can relabel the decoded\n // Table (charts look columns up by name). Normally inline in the\n // `X-Appkit-Arrow-Columns` header; for very wide schemas the header\n // carries only a statement-id reference and we fetch the names.\n let columnNames: string[] | undefined;\n const header = response.headers.get(\"X-Appkit-Arrow-Columns\");\n if (header) {\n try {\n columnNames = JSON.parse(decodeURIComponent(header));\n } catch {\n // Malformed header — fall back to the raw Arrow schema names.\n }\n } else {\n const ref = response.headers.get(\"X-Appkit-Arrow-Columns-Ref\");\n if (ref) {\n columnNames = await fetchArrowColumns(ref, signal);\n }\n }\n const table = await ArrowClient.processArrowBuffer(\n new Uint8Array(buffer),\n columnNames,\n );\n controls.patch({ loading: false, data: table });\n } catch (error) {\n if (signal.aborted) return;\n controls.patch({ loading: false, error: userFacingFetchError(error) });\n }\n}\n\n/**\n * Build the runner for a request: reset to loading, then run the\n * format-appropriate transport, reporting state through `controls.patch`.\n */\nfunction runAnalyticsRequest(\n options: AnalyticsRequestOptions,\n): RequestRunner<AnalyticsRequestSnapshot> {\n return (controls) => {\n controls.patch(LOADING_SNAPSHOT);\n\n // ARROW_STREAM: the server streams raw Arrow IPC bytes back on the query\n // response body (no SSE). Fetch and decode directly.\n if (options.format === \"ARROW_STREAM\") {\n void fetchArrowDirect(controls, options);\n return;\n }\n\n // Adapt the shared SSE handler onto the snapshot model. No warehouse\n // publisher lives here — the hook mirrors status from the snapshot — so\n // `unpublishWarehouseStatus` is a no-op.\n const sseContext: AnalyticsSseHandlerContext = {\n source: \"useAnalyticsQuery\",\n resource: { url: options.url },\n defaultExecutionError: \"Unable to execute query\",\n unpublishOnMalformedMessage: false,\n signal: controls.signal,\n abort: controls.abort,\n setLoading: (loading) => controls.patch({ loading }),\n setError: (error) => controls.patch({ error }),\n setErrorCode: (errorCode) => controls.patch({ errorCode }),\n onWarehouseStatus: (status) =>\n controls.patch({ warehouseStatus: status }),\n onResult: (message) => controls.patch({ data: message.data }),\n unpublishWarehouseStatus: () => {},\n };\n\n connectSSE({\n url: options.url,\n payload: options.payload,\n signal: controls.signal,\n onMessage: (message) =>\n handleAnalyticsSseMessage(message.data, sseContext),\n onError: (error) => handleAnalyticsSseError(error, sseContext),\n });\n };\n}\n\nconst store = createRequestStore<AnalyticsRequestSnapshot>(EMPTY_SNAPSHOT);\n\n/**\n * Register a subscriber for `key`, starting the shared request on first use.\n * Returns a `release` function that must be called on unmount.\n */\nexport function retain(\n key: string,\n options: AnalyticsRequestOptions,\n autoStart = true,\n): () => void {\n return store.retain(key, runAnalyticsRequest(options), autoStart);\n}\n\nexport const start = store.start;\nexport const subscribe = store.subscribe;\nexport const getSnapshot = store.getSnapshot;\n\n/** Test-only: abort every in-flight request and clear the store. */\nexport const resetAnalyticsRequestStore = store.reset;\n"],"mappings":";;;;;;;AAgDA,MAAM,iBAA2C;CAC/C,MAAM;CACN,SAAS;CACT,OAAO;CACP,WAAW;CACX,iBAAiB;CAClB;;AAGD,MAAM,mBAA6C;CACjD,MAAM;CACN,SAAS;CACT,OAAO;CACP,WAAW;CACX,iBAAiB;CAClB;;;;;;;AAUD,eAAe,kBACb,aACA,QAC+B;AAC/B,KAAI;EACF,MAAM,MAAM,MAAM,MAChB,0BAA0B,mBAAmB,YAAY,IACzD,EAAE,QAAQ,CACX;AACD,MAAI,CAAC,IAAI,GAAI,QAAO;EACpB,MAAM,OAAQ,MAAM,IAAI,MAAM;AAC9B,SAAO,MAAM,QAAQ,KAAK,QAAQ,GAAI,KAAK,UAAuB;SAC5D;AACN;;;;;;;;;AAUJ,eAAe,iBACb,UACA,SACe;CACf,MAAM,EAAE,WAAW;AACnB,KAAI;EACF,MAAM,WAAW,MAAM,MAAM,QAAQ,KAAK;GACxC,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAC/C,MAAM,QAAQ;GACd;GACD,CAAC;AACF,MAAI,OAAO,QAAS;AAEpB,MAAI,CAAC,SAAS,IAAI;GAChB,IAAI,UAAU;GACd,IAAI,OAAsB;AAC1B,OAAI;IACF,MAAM,OAAQ,MAAM,SAAS,MAAM;AAInC,QAAI,KAAK,MAAO,WAAU,KAAK;AAC/B,QAAI,OAAO,KAAK,cAAc,SAAU,QAAO,KAAK;WAC9C;AAGR,YAAS,MAAM;IAAE,SAAS;IAAO,OA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0B,QAAQ,MAAM,WAAW;GACrD,UAAU,UAAU,wBAAwB,OAAO,WAAW;GAC/D,CAAC;;;AAIN,MAAM,QAAQ,mBAA6C,eAAe;;;;;AAM1E,SAAgB,OACd,KACA,SACA,YAAY,MACA;AACZ,QAAO,MAAM,OAAO,KAAK,oBAAoB,QAAQ,EAAE,UAAU;;AAGnE,MAAa,QAAQ,MAAM;AAC3B,MAAa,YAAY,MAAM;AAC/B,MAAa,cAAc,MAAM;;AAGjC,MAAa,6BAA6B,MAAM"}
1
+ {"version":3,"file":"analytics-request-store.js","names":[],"sources":["../../../src/react/hooks/analytics-request-store.ts"],"sourcesContent":["import { ArrowClient, connectSSE } from \"@/js\";\n\nimport {\n type AnalyticsSseHandlerContext,\n GENERIC_LOAD_ERROR,\n handleAnalyticsSseError,\n handleAnalyticsSseMessage,\n userFacingFetchError,\n} from \"./analytics-sse\";\nimport {\n createRequestStore,\n type RequestControls,\n type RequestRunner,\n} from \"./request-store\";\nimport type { WarehouseStatus } from \"./types\";\n\n/**\n * Shared in-flight request store for `useAnalyticsQuery`: an instance of the\n * generic {@link createRequestStore} lifecycle wired to the analytics\n * transports. Multiple hook instances resolving to the same request (query\n * key, parameters, format, dev mode) share one network request and see the\n * same result and mid-flight `warehouse_status` updates.\n *\n * The lifecycle (dedup, refcount, deferred teardown) lives in the factory; this\n * module only supplies the snapshot shape and how a request runs — SSE via\n * `analytics-sse.ts` or a direct Arrow fetch.\n */\n\n/** Options describing the request a keyed entry runs. */\ninterface AnalyticsRequestOptions {\n /** Full request URL (already includes the encoded query key and dev suffix). */\n url: string;\n /** Serialized `{ parameters, format }` body. */\n payload: string;\n /** Response format; selects the transport. */\n format: string;\n}\n\n/** Immutable per-key request state; mirrors the hook's public result shape. */\ninterface AnalyticsRequestSnapshot {\n data: unknown;\n loading: boolean;\n error: string | null;\n errorCode: string | null;\n warehouseStatus: WarehouseStatus | null;\n}\n\n/** Idle snapshot returned for keys with no live entry. Referentially stable. */\nconst EMPTY_SNAPSHOT: AnalyticsRequestSnapshot = {\n data: null,\n loading: false,\n error: null,\n errorCode: null,\n warehouseStatus: null,\n};\n\n/** Snapshot a request resets to when it (re)starts. */\nconst LOADING_SNAPSHOT: AnalyticsRequestSnapshot = {\n data: null,\n loading: true,\n error: null,\n errorCode: null,\n warehouseStatus: null,\n};\n\ntype Controls = RequestControls<AnalyticsRequestSnapshot>;\n\n/**\n * Fetch the real column names for a statement from the fallback endpoint,\n * used when a very wide schema's names didn't fit in the response header.\n * Returns undefined on any failure so decoding falls back to the raw Arrow\n * schema names.\n */\nasync function fetchArrowColumns(\n statementId: string,\n signal: AbortSignal,\n): Promise<string[] | undefined> {\n try {\n const res = await fetch(\n `/api/analytics/columns/${encodeURIComponent(statementId)}`,\n { signal },\n );\n if (!res.ok) return undefined;\n const body = (await res.json()) as { columns?: unknown };\n return Array.isArray(body.columns) ? (body.columns as string[]) : undefined;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Fetch an ARROW_STREAM query result as raw Arrow IPC bytes directly from\n * the query endpoint (no SSE, no second /arrow-result request) and decode\n * it into a Table. The server streams the bytes back as the POST response\n * body; errors before the first byte arrive as a JSON `{ error, errorCode }`.\n */\nasync function fetchArrowDirect(\n controls: Controls,\n options: AnalyticsRequestOptions,\n): Promise<void> {\n const { signal } = controls;\n try {\n const response = await fetch(options.url, {\n method: \"POST\",\n headers: { \"Content-Type\": \"application/json\" },\n body: options.payload,\n signal,\n });\n if (signal.aborted) return;\n\n if (!response.ok) {\n let message = GENERIC_LOAD_ERROR;\n let code: string | null = null;\n try {\n const body = (await response.json()) as {\n error?: string;\n errorCode?: string;\n };\n if (body.error) message = body.error;\n if (typeof body.errorCode === \"string\") code = body.errorCode;\n } catch {\n // Non-JSON error body — keep the generic message.\n }\n controls.patch({ loading: false, error: message, errorCode: code });\n return;\n }\n\n const buffer = await response.arrayBuffer();\n if (signal.aborted) return;\n // Databricks encodes ARROW_STREAM columns positionally (col_0, …); the\n // server sends the real manifest names so we can relabel the decoded\n // Table (charts look columns up by name). Normally inline in the\n // `X-Appkit-Arrow-Columns` header; for very wide schemas the header\n // carries only a statement-id reference and we fetch the names.\n let columnNames: string[] | undefined;\n const header = response.headers.get(\"X-Appkit-Arrow-Columns\");\n if (header) {\n try {\n columnNames = JSON.parse(decodeURIComponent(header));\n } catch {\n // Malformed header — fall back to the raw Arrow schema names.\n }\n } else {\n const ref = response.headers.get(\"X-Appkit-Arrow-Columns-Ref\");\n if (ref) {\n columnNames = await fetchArrowColumns(ref, signal);\n }\n }\n const table = await ArrowClient.processArrowBuffer(\n new Uint8Array(buffer),\n columnNames,\n );\n controls.patch({ loading: false, data: table });\n } catch (error) {\n if (signal.aborted) return;\n controls.patch({ loading: false, error: userFacingFetchError(error) });\n }\n}\n\n/**\n * Build the runner for a request: reset to loading, then run the\n * format-appropriate transport, reporting state through `controls.patch`.\n */\nfunction runAnalyticsRequest(\n options: AnalyticsRequestOptions,\n): RequestRunner<AnalyticsRequestSnapshot> {\n return (controls) => {\n controls.patch(LOADING_SNAPSHOT);\n\n // ARROW_STREAM: the server streams raw Arrow IPC bytes back on the query\n // response body (no SSE). Fetch and decode directly.\n if (options.format === \"ARROW_STREAM\") {\n void fetchArrowDirect(controls, options);\n return;\n }\n\n // Adapt the shared SSE handler onto the snapshot model. No warehouse\n // publisher lives here — the hook mirrors status from the snapshot — so\n // `unpublishWarehouseStatus` is a no-op.\n const sseContext: AnalyticsSseHandlerContext = {\n source: \"useAnalyticsQuery\",\n resource: { url: options.url },\n defaultExecutionError: \"Unable to execute query\",\n unpublishOnMalformedMessage: false,\n signal: controls.signal,\n abort: controls.abort,\n setLoading: (loading) => controls.patch({ loading }),\n setError: (error) => controls.patch({ error }),\n setErrorCode: (errorCode) => controls.patch({ errorCode }),\n onWarehouseStatus: (status) =>\n controls.patch({ warehouseStatus: status }),\n onResult: (message) => controls.patch({ data: message.data }),\n unpublishWarehouseStatus: () => {},\n };\n\n connectSSE({\n url: options.url,\n payload: options.payload,\n signal: controls.signal,\n onMessage: (message) =>\n handleAnalyticsSseMessage(message.data, sseContext),\n onError: (error) => handleAnalyticsSseError(error, sseContext),\n });\n };\n}\n\nconst store = createRequestStore<AnalyticsRequestSnapshot>(EMPTY_SNAPSHOT);\n\n/**\n * Register a subscriber for `key`, starting the shared request on first use.\n * Returns a `release` function that must be called on unmount.\n */\nexport function retain(\n key: string,\n options: AnalyticsRequestOptions,\n autoStart = true,\n): () => void {\n return store.retain(key, runAnalyticsRequest(options), { autoStart });\n}\n\nexport const start = store.start;\nexport const subscribe = store.subscribe;\nexport const getSnapshot = store.getSnapshot;\n\n/** Test-only: abort every in-flight request and clear the store. */\nexport const resetAnalyticsRequestStore = store.reset;\n"],"mappings":";;;;;;;AAgDA,MAAM,iBAA2C;CAC/C,MAAM;CACN,SAAS;CACT,OAAO;CACP,WAAW;CACX,iBAAiB;CAClB;;AAGD,MAAM,mBAA6C;CACjD,MAAM;CACN,SAAS;CACT,OAAO;CACP,WAAW;CACX,iBAAiB;CAClB;;;;;;;AAUD,eAAe,kBACb,aACA,QAC+B;AAC/B,KAAI;EACF,MAAM,MAAM,MAAM,MAChB,0BAA0B,mBAAmB,YAAY,IACzD,EAAE,QAAQ,CACX;AACD,MAAI,CAAC,IAAI,GAAI,QAAO;EACpB,MAAM,OAAQ,MAAM,IAAI,MAAM;AAC9B,SAAO,MAAM,QAAQ,KAAK,QAAQ,GAAI,KAAK,UAAuB;SAC5D;AACN;;;;;;;;;AAUJ,eAAe,iBACb,UACA,SACe;CACf,MAAM,EAAE,WAAW;AACnB,KAAI;EACF,MAAM,WAAW,MAAM,MAAM,QAAQ,KAAK;GACxC,QAAQ;GACR,SAAS,EAAE,gBAAgB,oBAAoB;GAC/C,MAAM,QAAQ;GACd;GACD,CAAC;AACF,MAAI,OAAO,QAAS;AAEpB,MAAI,CAAC,SAAS,IAAI;GAChB,IAAI,UAAU;GACd,IAAI,OAAsB;AAC1B,OAAI;IACF,MAAM,OAAQ,MAAM,SAAS,MAAM;A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,QAAQ,MAAM,CAAC;GAC7D,gCAAgC;GACjC;AAED,aAAW;GACT,KAAK,QAAQ;GACb,SAAS,QAAQ;GACjB,QAAQ,SAAS;GACjB,YAAY,YACV,0BAA0B,QAAQ,MAAM,WAAW;GACrD,UAAU,UAAU,wBAAwB,OAAO,WAAW;GAC/D,CAAC;;;AAIN,MAAM,QAAQ,mBAA6C,eAAe;;;;;AAM1E,SAAgB,OACd,KACA,SACA,YAAY,MACA;AACZ,QAAO,MAAM,OAAO,KAAK,oBAAoB,QAAQ,EAAE,EAAE,WAAW,CAAC;;AAGvE,MAAa,QAAQ,MAAM;AAC3B,MAAa,YAAY,MAAM;AAC/B,MAAa,cAAc,MAAM;;AAGjC,MAAa,6BAA6B,MAAM"}
@@ -0,0 +1,33 @@
1
+ import { DatabaseEntity } from "../../js/database/types.js";
2
+ import "../../js/database/errors.js";
3
+
4
+ //#region src/react/hooks/database-request-store.d.ts
5
+ /**
6
+ * Which mounted reads to restart after a write: `true` for every database
7
+ * read, a table list for the reads that touch those tables, `false` for none.
8
+ */
9
+ type DatabaseInvalidation = boolean | readonly DatabaseEntity[];
10
+ /**
11
+ * Restart mounted database reads after a write the hooks did not make, such
12
+ * as a `databaseApi` call or a custom route that changes rows. The write hooks
13
+ * call this on success with their `invalidate` option.
14
+ *
15
+ * `true` (the default) restarts every read. A table list restarts the reads
16
+ * that show rows of those tables: reads rooted at them, and reads whose
17
+ * includes reach them through the relations the server published. `false`
18
+ * restarts none.
19
+ *
20
+ * Resolves once the current runs of those reads have answered, failed, or
21
+ * been torn down. A superseding refresh is followed rather than counted as
22
+ * complete; it never rejects.
23
+ *
24
+ * @example
25
+ * ```ts
26
+ * await fetch(`/api/boards/${boardId}/archive`, { method: "POST" });
27
+ * await invalidateDatabaseReads(["boards", "notes"]);
28
+ * ```
29
+ */
30
+ declare function invalidateDatabaseReads(scope?: DatabaseInvalidation): Promise<void>;
31
+ //#endregion
32
+ export { DatabaseInvalidation, invalidateDatabaseReads };
33
+ //# sourceMappingURL=database-request-store.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"database-request-store.d.ts","names":[],"sources":["../../../src/react/hooks/database-request-store.ts"],"mappings":";;;;;;AAWA;;KAAY,oBAAA,sBAA0C,cAAA;;;;;;;;;;;;;;;;;;;;;iBAiLtC,uBAAA,CACd,KAAA,GAAO,oBAAA,GACN,OAAA"}
@@ -0,0 +1,145 @@
1
+ import { getPluginClientConfig } from "../../js/config.js";
2
+ import { DatabaseApiError } from "../../js/database/errors.js";
3
+ import { requestDatabase } from "../../js/database/client.js";
4
+ import { createRequestStore } from "./request-store.js";
5
+
6
+ //#region src/react/hooks/database-request-store.ts
7
+ /** Snapshot for keys with no live entry. Referentially stable. */
8
+ const IDLE_DATABASE_READ = Object.freeze({
9
+ data: null,
10
+ loading: false,
11
+ error: null
12
+ });
13
+ function isRecord(value) {
14
+ return typeof value === "object" && value !== null && !Array.isArray(value);
15
+ }
16
+ function publishedRelations() {
17
+ const { relations } = getPluginClientConfig("database");
18
+ return isRecord(relations) ? relations : {};
19
+ }
20
+ /**
21
+ * Walk a read's include tree through the relations the server published, so
22
+ * a write to `notes` can find a `boards` read that includes its notes.
23
+ */
24
+ function databaseReadScope(entity, include) {
25
+ const relations = publishedRelations();
26
+ const tables = new Set([entity]);
27
+ let open = false;
28
+ const walk = (table, tree) => {
29
+ if (!isRecord(tree)) return;
30
+ const edges = relations[table];
31
+ for (const [name, options] of Object.entries(tree)) {
32
+ const target = isRecord(edges) && Object.hasOwn(edges, name) ? edges[name] : void 0;
33
+ if (typeof target !== "string") {
34
+ open = true;
35
+ continue;
36
+ }
37
+ tables.add(target);
38
+ if (isRecord(options)) walk(target, options.include);
39
+ }
40
+ };
41
+ walk(entity, include);
42
+ return {
43
+ tables,
44
+ open
45
+ };
46
+ }
47
+ /** Anything a request rejects with other than an abort, as the hooks report it. */
48
+ function asDatabaseApiError(error) {
49
+ if (error instanceof DatabaseApiError) return error;
50
+ return new DatabaseApiError("INTERNAL", null, error instanceof Error ? error.message : "Database request failed", [], { cause: error });
51
+ }
52
+ /** Resolves once `signal` aborts, even if the transport ignores it. */
53
+ function whenAborted(signal) {
54
+ return new Promise((resolve) => {
55
+ if (signal.aborted) resolve();
56
+ else signal.addEventListener("abort", () => resolve(), { once: true });
57
+ });
58
+ }
59
+ /**
60
+ * Build the runner for one read. A restart keeps the last result visible
61
+ * while it loads, and a run superseded by a restart or torn down after its
62
+ * last release never patches the entry. A `NOT_FOUND` drops the last result:
63
+ * the row is gone, so showing it beside the error would mislead. The returned
64
+ * promise settles once the run has patched its outcome or was aborted.
65
+ */
66
+ function runDatabaseRead(url, accept) {
67
+ return ({ signal, patch }) => {
68
+ patch({
69
+ loading: true,
70
+ error: null
71
+ });
72
+ const outcome = requestDatabase(url, {
73
+ method: "GET",
74
+ signal
75
+ }, accept).then((data) => {
76
+ if (!signal.aborted) patch({
77
+ data,
78
+ loading: false,
79
+ error: null
80
+ });
81
+ }, (cause) => {
82
+ if (signal.aborted) return;
83
+ const error = asDatabaseApiError(cause);
84
+ patch(error.code === "NOT_FOUND" ? {
85
+ data: null,
86
+ loading: false,
87
+ error
88
+ } : {
89
+ loading: false,
90
+ error
91
+ });
92
+ });
93
+ return Promise.race([outcome, whenAborted(signal)]);
94
+ };
95
+ }
96
+ const store = createRequestStore(IDLE_DATABASE_READ);
97
+ /**
98
+ * Register a subscriber for the read of `url`, starting it on first use.
99
+ * `scope` is kept from the first subscriber; it is derived from the same
100
+ * params as `url`, so every subscriber of one URL has the same scope.
101
+ * Returns a `release` function that must be called on unmount.
102
+ */
103
+ function retainDatabaseRead(url, accept, scope) {
104
+ return store.retain(url, runDatabaseRead(url, accept), { meta: scope });
105
+ }
106
+ /**
107
+ * Restart mounted database reads after a write the hooks did not make, such
108
+ * as a `databaseApi` call or a custom route that changes rows. The write hooks
109
+ * call this on success with their `invalidate` option.
110
+ *
111
+ * `true` (the default) restarts every read. A table list restarts the reads
112
+ * that show rows of those tables: reads rooted at them, and reads whose
113
+ * includes reach them through the relations the server published. `false`
114
+ * restarts none.
115
+ *
116
+ * Resolves once the current runs of those reads have answered, failed, or
117
+ * been torn down. A superseding refresh is followed rather than counted as
118
+ * complete; it never rejects.
119
+ *
120
+ * @example
121
+ * ```ts
122
+ * await fetch(`/api/boards/${boardId}/archive`, { method: "POST" });
123
+ * await invalidateDatabaseReads(["boards", "notes"]);
124
+ * ```
125
+ */
126
+ function invalidateDatabaseReads(scope = true) {
127
+ if (scope === false) return Promise.resolve();
128
+ if (scope === true) return store.restartStarted();
129
+ const written = new Set(scope);
130
+ if (written.size === 0) return Promise.resolve();
131
+ return store.restartStarted((_url, read) => {
132
+ if (read === void 0 || read.open) return true;
133
+ for (const table of read.tables) if (written.has(table)) return true;
134
+ return false;
135
+ });
136
+ }
137
+ const startDatabaseRead = store.start;
138
+ const subscribeDatabaseRead = store.subscribe;
139
+ const getDatabaseReadSnapshot = store.getSnapshot;
140
+ /** Test-only: abort every in-flight read and clear the store. */
141
+ const resetDatabaseRequestStore = store.reset;
142
+
143
+ //#endregion
144
+ export { IDLE_DATABASE_READ, asDatabaseApiError, databaseReadScope, getDatabaseReadSnapshot, invalidateDatabaseReads, retainDatabaseRead, startDatabaseRead, subscribeDatabaseRead };
145
+ //# sourceMappingURL=database-request-store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"database-request-store.js","names":[],"sources":["../../../src/react/hooks/database-request-store.ts"],"sourcesContent":["import { getPluginClientConfig } from \"@/js/config\";\nimport { requestDatabase } from \"@/js/database/client\";\nimport { DatabaseApiError } from \"@/js/database/errors\";\nimport type { DatabaseEntity } from \"@/js/database/types\";\n\nimport { createRequestStore, type RequestRunner } from \"./request-store\";\n\n/**\n * Which mounted reads to restart after a write: `true` for every database\n * read, a table list for the reads that touch those tables, `false` for none.\n */\nexport type DatabaseInvalidation = boolean | readonly DatabaseEntity[];\n\n/**\n * Shared in-flight read store for the database hooks: an instance of the\n * generic {@link createRequestStore} lifecycle wired to the database client's\n * transport. Hook instances that resolve to the same URL share one request and\n * one snapshot while any of them is mounted.\n *\n * Nothing outlives its last subscriber, so this deduplicates reads; it is not\n * a cache.\n */\n\n/** Immutable per-key read state; mirrors the hooks' public result shape. */\ninterface DatabaseReadSnapshot {\n data: unknown;\n loading: boolean;\n error: DatabaseApiError | null;\n}\n\n/** Snapshot for keys with no live entry. Referentially stable. */\nexport const IDLE_DATABASE_READ: DatabaseReadSnapshot = Object.freeze({\n data: null,\n loading: false,\n error: null,\n});\n\n/** Checks a decoded body is the envelope the read's route answers with. */\ntype ResponseGuard = (body: unknown) => body is object;\n\n/**\n * The tables one read shows rows of: the one it is rooted at and every table\n * its includes reach. `open` marks a read with an include the server did not\n * describe, which any scoped invalidation restarts rather than risk missing.\n */\ninterface DatabaseReadScope {\n readonly tables: ReadonlySet<string>;\n readonly open: boolean;\n}\n\n/** `{ table: { relation: targetTable } }`, as `DatabasePlugin` publishes it. */\ntype PublishedRelations = Record<string, Record<string, unknown>>;\n\nfunction isRecord(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n}\n\nfunction publishedRelations(): PublishedRelations {\n const { relations } = getPluginClientConfig<{ relations?: unknown }>(\n \"database\",\n );\n return isRecord(relations) ? (relations as PublishedRelations) : {};\n}\n\n/**\n * Walk a read's include tree through the relations the server published, so\n * a write to `notes` can find a `boards` read that includes its notes.\n */\nexport function databaseReadScope(\n entity: string,\n include: unknown,\n): DatabaseReadScope {\n const relations = publishedRelations();\n const tables = new Set<string>([entity]);\n let open = false;\n\n const walk = (table: string, tree: unknown): void => {\n if (!isRecord(tree)) return;\n const edges = relations[table];\n for (const [name, options] of Object.entries(tree)) {\n const target =\n isRecord(edges) && Object.hasOwn(edges, name) ? edges[name] : undefined;\n if (typeof target !== \"string\") {\n open = true;\n continue;\n }\n tables.add(target);\n if (isRecord(options)) walk(target, options.include);\n }\n };\n walk(entity, include);\n\n return { tables, open };\n}\n\n/** Anything a request rejects with other than an abort, as the hooks report it. */\nexport function asDatabaseApiError(error: unknown): DatabaseApiError {\n if (error instanceof DatabaseApiError) return error;\n return new DatabaseApiError(\n \"INTERNAL\",\n null,\n error instanceof Error ? error.message : \"Database request failed\",\n [],\n { cause: error },\n );\n}\n\n/** Resolves once `signal` aborts, even if the transport ignores it. */\nfunction whenAborted(signal: AbortSignal): Promise<void> {\n return new Promise((resolve) => {\n if (signal.aborted) resolve();\n else signal.addEventListener(\"abort\", () => resolve(), { once: true });\n });\n}\n\n/**\n * Build the runner for one read. A restart keeps the last result visible\n * while it loads, and a run superseded by a restart or torn down after its\n * last release never patches the entry. A `NOT_FOUND` drops the last result:\n * the row is gone, so showing it beside the error would mislead. The returned\n * promise settles once the run has patched its outcome or was aborted.\n */\nfunction runDatabaseRead(\n url: string,\n accept: ResponseGuard,\n): RequestRunner<DatabaseReadSnapshot> {\n return ({ signal, patch }) => {\n patch({ loading: true, error: null });\n const outcome = requestDatabase(\n url,\n { method: \"GET\", signal },\n accept,\n ).then(\n (data) => {\n if (!signal.aborted) patch({ data, loading: false, error: null });\n },\n (cause: unknown) => {\n if (signal.aborted) return;\n const error = asDatabaseApiError(cause);\n patch(\n error.code === \"NOT_FOUND\"\n ? { data: null, loading: false, error }\n : { loading: false, error },\n );\n },\n );\n return Promise.race([outcome, whenAborted(signal)]);\n };\n}\n\nconst store = createRequestStore<DatabaseReadSnapshot, DatabaseReadScope>(\n IDLE_DATABASE_READ,\n);\n\n/**\n * Register a subscriber for the read of `url`, starting it on first use.\n * `scope` is kept from the first subscriber; it is derived from the same\n * params as `url`, so every subscriber of one URL has the same scope.\n * Returns a `release` function that must be called on unmount.\n */\nexport function retainDatabaseRead(\n url: string,\n accept: ResponseGuard,\n scope: DatabaseReadScope,\n): () => void {\n return store.retain(url, runDatabaseRead(url, accept), { meta: scope });\n}\n\n/**\n * Restart mounted database reads after a write the hooks did not make, such\n * as a `databaseApi` call or a custom route that changes rows. The write hooks\n * call this on success with their `invalidate` option.\n *\n * `true` (the default) restarts every read. A table list restarts the reads\n * that show rows of those tables: reads rooted at them, and reads whose\n * includes reach them through the relations the server published. `false`\n * restarts none.\n *\n * Resolves once the current runs of those reads have answered, failed, or\n * been torn down. A superseding refresh is followed rather than counted as\n * complete; it never rejects.\n *\n * @example\n * ```ts\n * await fetch(`/api/boards/${boardId}/archive`, { method: \"POST\" });\n * await invalidateDatabaseReads([\"boards\", \"notes\"]);\n * ```\n */\nexport function invalidateDatabaseReads(\n scope: DatabaseInvalidation = true,\n): Promise<void> {\n if (scope === false) return Promise.resolve();\n if (scope === true) return store.restartStarted();\n const written = new Set<string>(scope);\n if (written.size === 0) return Promise.resolve();\n return store.restartStarted((_url, read) => {\n if (read === undefined || read.open) return true;\n for (const table of read.tables) if (written.has(table)) return true;\n return false;\n });\n}\n\nexport const startDatabaseRead = store.start;\nexport const subscribeDatabaseRead = store.subscribe;\nexport const getDatabaseReadSnapshot = store.getSnapshot;\n\n/** Test-only: abort every in-flight read and clear the store. */\nexport const resetDatabaseRequestStore = store.reset;\n"],"mappings":";;;;;;;AA+BA,MAAa,qBAA2C,OAAO,OAAO;CACpE,MAAM;CACN,SAAS;CACT,OAAO;CACR,CAAC;AAkBF,SAAS,SAAS,OAAkD;AAClE,QAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,MAAM;;AAG7E,SAAS,qBAAyC;CAChD,MAAM,EAAE,cAAc,sBACpB,WACD;AACD,QAAO,SAAS,UAAU,GAAI,YAAmC,EAAE;;;;;;AAOrE,SAAgB,kBACd,QACA,SACmB;CACnB,MAAM,YAAY,oBAAoB;CACtC,MAAM,SAAS,IAAI,IAAY,CAAC,OAAO,CAAC;CACxC,IAAI,OAAO;CAEX,MAAM,QAAQ,OAAe,SAAwB;AACnD,MAAI,CAAC,SAAS,KAAK,CAAE;EACrB,MAAM,QAAQ,UAAU;AACxB,OAAK,MAAM,CAAC,MAAM,YAAY,OAAO,QAAQ,KAAK,EAAE;GAClD,MAAM,SACJ,SAAS,MAA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AE,MAAM,OAAO,CAAC;;;;;;;;;;;;;;;;;;;;;;AAuBzE,SAAgB,wBACd,QAA8B,MACf;AACf,KAAI,UAAU,MAAO,QAAO,QAAQ,SAAS;AAC7C,KAAI,UAAU,KAAM,QAAO,MAAM,gBAAgB;CACjD,MAAM,UAAU,IAAI,IAAY,MAAM;AACtC,KAAI,QAAQ,SAAS,EAAG,QAAO,QAAQ,SAAS;AAChD,QAAO,MAAM,gBAAgB,MAAM,SAAS;AAC1C,MAAI,SAAS,UAAa,KAAK,KAAM,QAAO;AAC5C,OAAK,MAAM,SAAS,KAAK,OAAQ,KAAI,QAAQ,IAAI,MAAM,CAAE,QAAO;AAChE,SAAO;GACP;;AAGJ,MAAa,oBAAoB,MAAM;AACvC,MAAa,wBAAwB,MAAM;AAC3C,MAAa,0BAA0B,MAAM;;AAG7C,MAAa,4BAA4B,MAAM"}
@@ -7,14 +7,15 @@ function createRequestStore(idle) {
7
7
  if (!listeners) return;
8
8
  for (const listener of listeners) listener();
9
9
  }
10
- function start(key) {
10
+ /** Run `key` again; resolves when that run settles (at once for a void run). */
11
+ function run(key) {
11
12
  const entry = entries.get(key);
12
- if (!entry) return;
13
+ if (!entry) return Promise.resolve();
13
14
  entry.abortController?.abort();
14
15
  entry.started = true;
15
16
  const abortController = new AbortController();
16
17
  entry.abortController = abortController;
17
- entry.run({
18
+ const settled = entry.run({
18
19
  signal: abortController.signal,
19
20
  abort: () => abortController.abort(),
20
21
  patch(next) {
@@ -25,6 +26,19 @@ function createRequestStore(idle) {
25
26
  notify(key);
26
27
  }
27
28
  });
29
+ const pending = Promise.resolve(settled).catch(() => {});
30
+ if (entry.abortController === abortController) entry.pending = pending;
31
+ return pending;
32
+ }
33
+ async function waitForCurrentRuns(targets) {
34
+ while (true) {
35
+ const pending = targets.map(([key, entry]) => entries.get(key) === entry && entry.refCount > 0 ? entry.pending : null);
36
+ await Promise.all(pending);
37
+ if (targets.every(([key, entry], index) => entries.get(key) !== entry || entry.refCount <= 0 || entry.pending === pending[index])) return;
38
+ }
39
+ }
40
+ function start(key) {
41
+ run(key);
28
42
  }
29
43
  function release(key) {
30
44
  const entry = entries.get(key);
@@ -39,16 +53,18 @@ function createRequestStore(idle) {
39
53
  }, 0);
40
54
  }
41
55
  return {
42
- retain(key, run, autoStart = true) {
56
+ retain(key, runner, { autoStart = true, meta } = {}) {
43
57
  let entry = entries.get(key);
44
58
  if (!entry) {
45
59
  entry = {
46
60
  snapshot: idle,
61
+ meta,
47
62
  refCount: 0,
48
63
  abortController: null,
49
64
  teardownTimer: null,
50
65
  started: false,
51
- run
66
+ pending: null,
67
+ run: runner
52
68
  };
53
69
  entries.set(key, entry);
54
70
  }
@@ -61,6 +77,11 @@ function createRequestStore(idle) {
61
77
  return () => release(key);
62
78
  },
63
79
  start,
80
+ async restartStarted(match) {
81
+ const targets = [...entries].filter(([key, entry]) => entry.started && entry.refCount > 0 && (!match || match(key, entry.meta)));
82
+ for (const [key, entry] of targets) if (entries.get(key) === entry && entry.refCount > 0) start(key);
83
+ await waitForCurrentRuns(targets);
84
+ },
64
85
  subscribe(key, listener) {
65
86
  let listeners = listenersByKey.get(key);
66
87
  if (!listeners) {
@@ -1 +1 @@
1
- {"version":3,"file":"request-store.js","names":[],"sources":["../../../src/react/hooks/request-store.ts"],"sourcesContent":["/**\n * Generic keyed request store: coalesces identical in-flight requests so N\n * subscribers of the same key share one run, and fans state updates back out\n * via `useSyncExternalStore`.\n *\n * Owns only the lifecycle — refcount, deferred teardown, subscribe/notify — and\n * is transport-agnostic: the caller's `run` performs the actual fetch (SSE,\n * Arrow, plain fetch, …) and reports state through `controls.patch`. The\n * snapshot type `S` and its reset policy live entirely with the caller.\n *\n * Dedup-only: an entry lives exactly as long as it has subscribers. When the\n * last one releases, teardown is deferred a tick (so a React StrictMode\n * unmount→remount reuses the in-flight request instead of aborting it); if no\n * one re-subscribes by then, the request is aborted and the entry dropped.\n */\n\n/** What a `run` uses to drive its request and report state. */\nexport interface RequestControls<S> {\n /** Aborted when the request is superseded or torn down. */\n signal: AbortSignal;\n /** Abort this run's transport (e.g. to close a stream on a fatal frame). */\n abort(): void;\n /** Merge fields into the entry's snapshot and notify subscribers. */\n patch(next: Partial<S>): void;\n}\n\n/** Starts a request and reports state through `controls`. */\nexport type RequestRunner<S> = (controls: RequestControls<S>) => void;\n\ninterface RequestStore<S> {\n /**\n * Register a subscriber for `key`, creating and starting the shared request\n * on first use. Returns a `release` function to call on unmount.\n *\n * @param run Runs the request; stored on the entry and re-invoked by\n * `start`. Only the first caller's `run` is used (later joiners share it).\n * @param autoStart Start the request on creation. Default true.\n */\n retain(key: string, run: RequestRunner<S>, autoStart?: boolean): () => void;\n /** (Re)start the request for `key`: abort any in-flight run, then re-run. */\n start(key: string): void;\n subscribe(key: string, listener: () => void): () => void;\n getSnapshot(key: string): S;\n /** Test-only: abort every in-flight request and clear the store. */\n reset(): void;\n}\n\ninterface Entry<S> {\n snapshot: S;\n refCount: number;\n abortController: AbortController | null;\n teardownTimer: ReturnType<typeof setTimeout> | null;\n /** True once `start` has run at least once; guards re-run on late `retain`. */\n started: boolean;\n run: RequestRunner<S>;\n}\n\nexport function createRequestStore<S>(idle: S): RequestStore<S> {\n const entries = new Map<string, Entry<S>>();\n\n // Keyed separately from `entries`: `subscribe` can run before `retain`\n // creates the entry, so listeners must survive independently of entry life.\n const listenersByKey = new Map<string, Set<() => void>>();\n\n function notify(key: string): void {\n const listeners = listenersByKey.get(key);\n if (!listeners) return;\n for (const listener of listeners) listener();\n }\n\n function start(key: string): void {\n const entry = entries.get(key);\n if (!entry) return;\n\n entry.abortController?.abort();\n entry.started = true;\n\n const abortController = new AbortController();\n entry.abortController = abortController;\n\n entry.run({\n signal: abortController.signal,\n abort: () => abortController.abort(),\n patch(next) {\n entry.snapshot = { ...entry.snapshot, ...next };\n notify(key);\n },\n });\n }\n\n function release(key: string): void {\n const entry = entries.get(key);\n if (!entry) return;\n entry.refCount -= 1;\n if (entry.refCount > 0) return;\n\n // Defer teardown one tick: a StrictMode unmount→remount (or fast route\n // swap) re-`retain`s within the same tick and reuses the request.\n entry.teardownTimer = setTimeout(() => {\n const current = entries.get(key);\n if (!current || current.refCount > 0) return;\n current.abortController?.abort();\n entries.delete(key);\n }, 0);\n }\n\n return {\n retain(key, run, autoStart = true) {\n let entry = entries.get(key);\n if (!entry) {\n entry = {\n snapshot: idle,\n refCount: 0,\n abortController: null,\n teardownTimer: null,\n started: false,\n run,\n };\n entries.set(key, entry);\n }\n\n // A late joiner cancels any pending teardown so it keeps the live request.\n if (entry.teardownTimer !== null) {\n clearTimeout(entry.teardownTimer);\n entry.teardownTimer = null;\n }\n entry.refCount += 1;\n\n if (autoStart && !entry.started) {\n start(key);\n }\n\n return () => release(key);\n },\n\n start,\n\n subscribe(key, listener) {\n let listeners = listenersByKey.get(key);\n if (!listeners) {\n listeners = new Set();\n listenersByKey.set(key, listeners);\n }\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n if (listeners.size === 0) listenersByKey.delete(key);\n };\n },\n\n getSnapshot(key) {\n return entries.get(key)?.snapshot ?? idle;\n },\n\n reset() {\n for (const entry of entries.values()) {\n if (entry.teardownTimer !== null) clearTimeout(entry.teardownTimer);\n entry.abortController?.abort();\n }\n entries.clear();\n listenersByKey.clear();\n },\n };\n}\n"],"mappings":";AAyDA,SAAgB,mBAAsB,MAA0B;CAC9D,MAAM,0BAAU,IAAI,KAAuB;CAI3C,MAAM,iCAAiB,IAAI,KAA8B;CAEzD,SAAS,OAAO,KAAmB;EACjC,MAAM,YAAY,eAAe,IAAI,IAAI;AACzC,MAAI,CAAC,UAAW;AAChB,OAAK,MAAM,YAAY,UAAW,WAAU;;CAG9C,SAAS,MAAM,KAAmB;EAChC,MAAM,QAAQ,QAAQ,IAAI,IAAI;AAC9B,MAAI,CAAC,MAAO;AAEZ,QAAM,iBAAiB,OAAO;AAC9B,QAAM,UAAU;EAEhB,MAAM,kBAAkB,IAAI,iBAAiB;AAC7C,QAAM,kBAAkB;AAExB,QA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AAS,QAAQ,QAAQ,EAAE;AACpC,QAAI,MAAM,kBAAkB,KAAM,cAAa,MAAM,cAAc;AACnE,UAAM,iBAAiB,OAAO;;AAEhC,WAAQ,OAAO;AACf,kBAAe,OAAO;;EAEzB"}
1
+ {"version":3,"file":"request-store.js","names":[],"sources":["../../../src/react/hooks/request-store.ts"],"sourcesContent":["/**\n * Generic keyed request store: coalesces identical in-flight requests so N\n * subscribers of the same key share one run, and fans state updates back out\n * via `useSyncExternalStore`.\n *\n * Owns only the lifecycle — refcount, deferred teardown, subscribe/notify — and\n * is transport-agnostic: the caller's `run` performs the actual fetch (SSE,\n * Arrow, plain fetch, …) and reports state through `controls.patch`. The\n * snapshot type `S` and its reset policy live entirely with the caller.\n *\n * Dedup-only: an entry lives exactly as long as it has subscribers. When the\n * last one releases, teardown is deferred a tick (so a React StrictMode\n * unmount→remount reuses the in-flight request instead of aborting it); if no\n * one re-subscribes by then, the request is aborted and the entry dropped.\n */\n\n/** What a `run` uses to drive its request and report state. */\nexport interface RequestControls<S> {\n /** Aborted when the request is superseded or torn down. */\n signal: AbortSignal;\n /** Abort this run's transport (e.g. to close a stream on a fatal frame). */\n abort(): void;\n /** Merge fields into the entry's snapshot and notify subscribers. */\n patch(next: Partial<S>): void;\n}\n\n/**\n * Starts a request and reports state through `controls`. It may return a\n * promise that settles once the run has reported its outcome or was aborted;\n * `restartStarted` waits on it. It must not reject.\n */\nexport type RequestRunner<S> = (\n controls: RequestControls<S>,\n) => void | Promise<void>;\n\n/** How `retain` creates an entry; ignored when the entry already exists. */\ninterface RetainOptions<M> {\n /** Start the request on creation. Default true. */\n autoStart?: boolean;\n /** Caller data kept with the entry and handed to `restartStarted`'s match. */\n meta?: M;\n}\n\ninterface RequestStore<S, M> {\n /**\n * Register a subscriber for `key`, creating and starting the shared request\n * on first use. Returns a `release` function to call on unmount.\n *\n * @param run Runs the request; stored on the entry and re-invoked by\n * `start`. Only the first caller's `run` is used (later joiners share it).\n * @param options `autoStart` and `meta`, both taken from the first caller.\n */\n retain(\n key: string,\n run: RequestRunner<S>,\n options?: RetainOptions<M>,\n ): () => void;\n /** (Re)start the request for `key`: abort any in-flight run, then re-run. */\n start(key: string): void;\n /**\n * `start` every subscribed entry that has run at least once and that\n * `match` accepts (every such entry without one), then wait for their current\n * runs, following any superseding restart. An entry retained with\n * `autoStart: false` that never ran stays idle, and one whose last subscriber\n * left is not restarted.\n */\n restartStarted(\n match?: (key: string, meta: M | undefined) => boolean,\n ): Promise<void>;\n subscribe(key: string, listener: () => void): () => void;\n getSnapshot(key: string): S;\n /** Test-only: abort every in-flight request and clear the store. */\n reset(): void;\n}\n\ninterface Entry<S, M> {\n snapshot: S;\n meta: M | undefined;\n refCount: number;\n abortController: AbortController | null;\n teardownTimer: ReturnType<typeof setTimeout> | null;\n /** True once `start` has run at least once; guards re-run on late `retain`. */\n started: boolean;\n pending: Promise<void> | null;\n run: RequestRunner<S>;\n}\n\nexport function createRequestStore<S, M = never>(idle: S): RequestStore<S, M> {\n const entries = new Map<string, Entry<S, M>>();\n\n // Keyed separately from `entries`: `subscribe` can run before `retain`\n // creates the entry, so listeners must survive independently of entry life.\n const listenersByKey = new Map<string, Set<() => void>>();\n\n function notify(key: string): void {\n const listeners = listenersByKey.get(key);\n if (!listeners) return;\n for (const listener of listeners) listener();\n }\n\n /** Run `key` again; resolves when that run settles (at once for a void run). */\n function run(key: string): Promise<void> {\n const entry = entries.get(key);\n if (!entry) return Promise.resolve();\n\n entry.abortController?.abort();\n entry.started = true;\n\n const abortController = new AbortController();\n entry.abortController = abortController;\n\n const settled = entry.run({\n signal: abortController.signal,\n abort: () => abortController.abort(),\n patch(next) {\n entry.snapshot = { ...entry.snapshot, ...next };\n notify(key);\n },\n });\n // A runner must not reject; guard anyway so a restart never does.\n const pending = Promise.resolve(settled).catch(() => {});\n // A synchronous snapshot listener may have already started a newer run.\n if (entry.abortController === abortController) entry.pending = pending;\n return pending;\n }\n\n async function waitForCurrentRuns(\n targets: [string, Entry<S, M>][],\n ): Promise<void> {\n while (true) {\n const pending = targets.map(([key, entry]) =>\n entries.get(key) === entry && entry.refCount > 0 ? entry.pending : null,\n );\n await Promise.all(pending);\n // One key may restart after settling while another key is still pending.\n if (\n targets.every(\n ([key, entry], index) =>\n entries.get(key) !== entry ||\n entry.refCount <= 0 ||\n entry.pending === pending[index],\n )\n )\n return;\n }\n }\n\n function start(key: string): void {\n void run(key);\n }\n\n function release(key: string): void {\n const entry = entries.get(key);\n if (!entry) return;\n entry.refCount -= 1;\n if (entry.refCount > 0) return;\n\n // Defer teardown one tick: a StrictMode unmount→remount (or fast route\n // swap) re-`retain`s within the same tick and reuses the request.\n entry.teardownTimer = setTimeout(() => {\n const current = entries.get(key);\n if (!current || current.refCount > 0) return;\n current.abortController?.abort();\n entries.delete(key);\n }, 0);\n }\n\n return {\n retain(key, runner, { autoStart = true, meta } = {}) {\n let entry = entries.get(key);\n if (!entry) {\n entry = {\n snapshot: idle,\n meta,\n refCount: 0,\n abortController: null,\n teardownTimer: null,\n started: false,\n pending: null,\n run: runner,\n };\n entries.set(key, entry);\n }\n\n // A late joiner cancels any pending teardown so it keeps the live request.\n if (entry.teardownTimer !== null) {\n clearTimeout(entry.teardownTimer);\n entry.teardownTimer = null;\n }\n entry.refCount += 1;\n\n if (autoStart && !entry.started) {\n start(key);\n }\n\n return () => release(key);\n },\n\n start,\n\n async restartStarted(match) {\n // Collect first: a restarted run patches, and a patch notifies. An entry\n // with no subscriber is waiting for teardown; restarting it would only\n // send a request that teardown aborts a tick later.\n const targets = [...entries].filter(\n ([key, entry]) =>\n entry.started &&\n entry.refCount > 0 &&\n (!match || match(key, entry.meta)),\n );\n for (const [key, entry] of targets) {\n if (entries.get(key) === entry && entry.refCount > 0) start(key);\n }\n await waitForCurrentRuns(targets);\n },\n\n subscribe(key, listener) {\n let listeners = listenersByKey.get(key);\n if (!listeners) {\n listeners = new Set();\n listenersByKey.set(key, listeners);\n }\n listeners.add(listener);\n return () => {\n listeners.delete(listener);\n if (listeners.size === 0) listenersByKey.delete(key);\n };\n },\n\n getSnapshot(key) {\n return entries.get(key)?.snapshot ?? idle;\n },\n\n reset() {\n for (const entry of entries.values()) {\n if (entry.teardownTimer !== null) clearTimeout(entry.teardownTimer);\n entry.abortController?.abort();\n }\n entries.clear();\n listenersByKey.clear();\n },\n };\n}\n"],"mappings":";AAuFA,SAAgB,mBAAiC,MAA6B;CAC5E,MAAM,0BAAU,IAAI,KAA0B;CAI9C,MAAM,iCAAiB,IAAI,KAA8B;CAEzD,SAAS,OAAO,KAAmB;EACjC,MAAM,YAAY,eAAe,IAAI,IAAI;AACzC,MAAI,CAAC,UAAW;AAChB,OAAK,MAAM,YAAY,UAAW,WAAU;;;CAI9C,SAAS,IAAI,KAA4B;EACvC,MAAM,QAAQ,QAAQ,IAAI,IAAI;AAC9B,MAAI,CAAC,MAAO,QAAO,QAAQ,SAAS;AAEpC,QAAM,iBAAiB,OAAO;AAC9B,QAAM,UAAU;EAEhB,MAAM,kBAAkB,IAAI,iBAAiB;AAC7C,QAAM,kBAAkB;EAExB,MAAM,UAAU,MAAM,IAAI;GACxB,QAAQ,gBAAgB;GACxB,aAAa,gBAAgB,OAAO;GACpC,MAAM,MAAM;AACV,UAAM,WAAW;KAAE,GAAG,MAAM;KAAU,GAAG;KAAM;AAC/C,WAAO,IAAI;;GAEd,CAAC;EAEF,MAAM,UAAU,QAAQ,QAAQ,QAAQ,CAAC,YAAY,GAAG;AAExD,MAAI,MAAM,oBAAoB,gBAAiB,OAAM,UAAU;AAC/D,SAAO;;CAGT,eAAe,mBACb,SACe;AACf,SAAO,MAAM;GACX,MAAM,UAAU,QAAQ,KAAK,CAAC,KAAK,WACjC,QAAQ,IAAI,IAAI,KAAK,SAAS,MAAM,WAAW,IAAI,MAAM,UAAU,KACpE;AACD,SAAM,QAAQ,IAAI,QAAQ;AAE1B,OACE,QAAQ,OACL,CAAC,KAAK,QAAQ,UACb,QAAQ,IAAI,IAAI,KAAK,SACrB,MAAM,YAAY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