fastify-auto-sqlapi 0.5.0 → 1.0.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 (212) hide show
  1. package/AGENTS.md +5 -5
  2. package/AGENTS_BACKEND.md +166 -130
  3. package/AGENTS_FRONTEND.md +60 -38
  4. package/BREAKING_CHANGES.md +9 -893
  5. package/CHANGELOG.md +258 -15
  6. package/README.md +71 -45
  7. package/dist/bin/generate-schema.js +12 -12
  8. package/dist/bin/generate-tables.js +1 -2
  9. package/dist/bin/utils.d.ts +2 -6
  10. package/dist/bin/utils.d.ts.map +1 -1
  11. package/dist/bin/utils.js +13 -33
  12. package/dist/index.d.ts +13 -33
  13. package/dist/index.d.ts.map +1 -1
  14. package/dist/index.js +6 -37
  15. package/dist/lib/adapters/mysql-adapter.d.ts +5 -2
  16. package/dist/lib/adapters/mysql-adapter.d.ts.map +1 -1
  17. package/dist/lib/adapters/pg-adapter.d.ts +5 -2
  18. package/dist/lib/adapters/pg-adapter.d.ts.map +1 -1
  19. package/dist/lib/agent/manifest.d.ts +27 -10
  20. package/dist/lib/agent/manifest.d.ts.map +1 -1
  21. package/dist/lib/agent/manifest.js +43 -26
  22. package/dist/lib/agent/tool-schemas.d.ts +5 -4
  23. package/dist/lib/agent/tool-schemas.d.ts.map +1 -1
  24. package/dist/lib/agent/tool-schemas.js +5 -5
  25. package/dist/lib/cli/config.d.ts +37 -2
  26. package/dist/lib/cli/config.d.ts.map +1 -1
  27. package/dist/lib/cli/config.js +106 -16
  28. package/dist/lib/cli/mysql-introspect.d.ts +6 -1
  29. package/dist/lib/cli/mysql-introspect.d.ts.map +1 -1
  30. package/dist/lib/cli/mysql-introspect.js +15 -15
  31. package/dist/lib/cli/pg-introspect.d.ts +0 -1
  32. package/dist/lib/cli/pg-introspect.d.ts.map +1 -1
  33. package/dist/lib/cli/pg-introspect.js +2 -13
  34. package/dist/lib/cli/tables-codegen.d.ts +0 -4
  35. package/dist/lib/cli/tables-codegen.d.ts.map +1 -1
  36. package/dist/lib/cli/tables-codegen.js +24 -87
  37. package/dist/lib/db.d.ts +42 -17
  38. package/dist/lib/db.d.ts.map +1 -1
  39. package/dist/lib/db.js +114 -40
  40. package/dist/lib/dialect.d.ts +5 -0
  41. package/dist/lib/dialect.d.ts.map +1 -1
  42. package/dist/lib/dialect.js +3 -0
  43. package/dist/lib/engine/bulk/bulk-delete.d.ts +5 -0
  44. package/dist/lib/engine/bulk/bulk-delete.d.ts.map +1 -1
  45. package/dist/lib/engine/bulk/bulk-delete.js +66 -30
  46. package/dist/lib/engine/bulk/bulk-upsert.d.ts.map +1 -1
  47. package/dist/lib/engine/bulk/bulk-upsert.js +45 -26
  48. package/dist/lib/engine/read-hooks.d.ts +3 -3
  49. package/dist/lib/engine/read-hooks.d.ts.map +1 -1
  50. package/dist/lib/engine/read-hooks.js +3 -3
  51. package/dist/lib/engine/rest/delete.d.ts.map +1 -1
  52. package/dist/lib/engine/rest/delete.js +12 -18
  53. package/dist/lib/engine/rest/get.js +8 -8
  54. package/dist/lib/engine/rest/insert.d.ts.map +1 -1
  55. package/dist/lib/engine/rest/insert.js +31 -18
  56. package/dist/lib/engine/rest/update.d.ts.map +1 -1
  57. package/dist/lib/engine/rest/update.js +34 -17
  58. package/dist/lib/engine/search/aggregations.d.ts +3 -3
  59. package/dist/lib/engine/search/aggregations.d.ts.map +1 -1
  60. package/dist/lib/engine/search/aggregations.js +20 -16
  61. package/dist/lib/engine/search/conditions.d.ts +9 -5
  62. package/dist/lib/engine/search/conditions.d.ts.map +1 -1
  63. package/dist/lib/engine/search/conditions.js +31 -20
  64. package/dist/lib/engine/search/fields.d.ts +44 -11
  65. package/dist/lib/engine/search/fields.d.ts.map +1 -1
  66. package/dist/lib/engine/search/fields.js +94 -28
  67. package/dist/lib/engine/search/join-families.d.ts +7 -7
  68. package/dist/lib/engine/search/join-families.d.ts.map +1 -1
  69. package/dist/lib/engine/search/join-families.js +84 -75
  70. package/dist/lib/engine/search/joins.d.ts +15 -7
  71. package/dist/lib/engine/search/joins.d.ts.map +1 -1
  72. package/dist/lib/engine/search/joins.js +23 -13
  73. package/dist/lib/engine/search/order-by.d.ts +11 -12
  74. package/dist/lib/engine/search/order-by.d.ts.map +1 -1
  75. package/dist/lib/engine/search/order-by.js +24 -28
  76. package/dist/lib/engine/search/search.d.ts.map +1 -1
  77. package/dist/lib/engine/search/search.js +111 -62
  78. package/dist/lib/engine/validate.d.ts +21 -3
  79. package/dist/lib/engine/validate.d.ts.map +1 -1
  80. package/dist/lib/engine/validate.js +106 -16
  81. package/dist/lib/engine/write-helpers.d.ts +69 -16
  82. package/dist/lib/engine/write-helpers.d.ts.map +1 -1
  83. package/dist/lib/engine/write-helpers.js +257 -105
  84. package/dist/lib/errors.d.ts +42 -10
  85. package/dist/lib/errors.d.ts.map +1 -1
  86. package/dist/lib/errors.js +69 -15
  87. package/dist/lib/nullable.d.ts +3 -2
  88. package/dist/lib/nullable.d.ts.map +1 -1
  89. package/dist/lib/nullable.js +14 -5
  90. package/dist/lib/read-access.d.ts +33 -21
  91. package/dist/lib/read-access.d.ts.map +1 -1
  92. package/dist/lib/read-access.js +42 -23
  93. package/dist/lib/schema/bulk-delete.d.ts +13 -7
  94. package/dist/lib/schema/bulk-delete.d.ts.map +1 -1
  95. package/dist/lib/schema/bulk-delete.js +18 -8
  96. package/dist/lib/schema/bulk-upsert.d.ts +3 -3
  97. package/dist/lib/schema/bulk-upsert.d.ts.map +1 -1
  98. package/dist/lib/schema/bulk-upsert.js +9 -14
  99. package/dist/lib/schema/get.d.ts +1 -1
  100. package/dist/lib/schema/get.d.ts.map +1 -1
  101. package/dist/lib/schema/get.js +2 -2
  102. package/dist/lib/schema/helpers.d.ts +41 -23
  103. package/dist/lib/schema/helpers.d.ts.map +1 -1
  104. package/dist/lib/schema/helpers.js +80 -33
  105. package/dist/lib/schema/insert.d.ts +1 -1
  106. package/dist/lib/schema/insert.d.ts.map +1 -1
  107. package/dist/lib/schema/insert.js +12 -20
  108. package/dist/lib/schema/search.d.ts +2 -13
  109. package/dist/lib/schema/search.d.ts.map +1 -1
  110. package/dist/lib/schema/search.js +64 -61
  111. package/dist/lib/schema/update.d.ts +1 -1
  112. package/dist/lib/schema/update.d.ts.map +1 -1
  113. package/dist/lib/schema/update.js +6 -13
  114. package/dist/lib/sql-api.d.ts +47 -25
  115. package/dist/lib/sql-api.d.ts.map +1 -1
  116. package/dist/lib/sql-api.js +70 -27
  117. package/dist/lib/table-helpers.d.ts +92 -14
  118. package/dist/lib/table-helpers.d.ts.map +1 -1
  119. package/dist/lib/table-helpers.js +367 -128
  120. package/dist/lib/tenant.d.ts +16 -22
  121. package/dist/lib/tenant.d.ts.map +1 -1
  122. package/dist/lib/tenant.js +38 -54
  123. package/dist/lib/write-access.d.ts +15 -9
  124. package/dist/lib/write-access.d.ts.map +1 -1
  125. package/dist/lib/write-access.js +12 -4
  126. package/dist/routes/auto/agent-manifest.routes.d.ts +1 -1
  127. package/dist/routes/auto/agent-manifest.routes.js +2 -2
  128. package/dist/routes/auto/bulk-delete.routes.d.ts +2 -2
  129. package/dist/routes/auto/bulk-delete.routes.d.ts.map +1 -1
  130. package/dist/routes/auto/bulk-delete.routes.js +1 -7
  131. package/dist/routes/auto/bulk-upsert.routes.d.ts +2 -2
  132. package/dist/routes/auto/bulk-upsert.routes.d.ts.map +1 -1
  133. package/dist/routes/auto/bulk-upsert.routes.js +2 -2
  134. package/dist/routes/auto/delete.routes.d.ts +2 -2
  135. package/dist/routes/auto/delete.routes.d.ts.map +1 -1
  136. package/dist/routes/auto/delete.routes.js +8 -10
  137. package/dist/routes/auto/get.routes.d.ts +2 -2
  138. package/dist/routes/auto/get.routes.d.ts.map +1 -1
  139. package/dist/routes/auto/get.routes.js +5 -5
  140. package/dist/routes/auto/insert.routes.d.ts +2 -2
  141. package/dist/routes/auto/insert.routes.d.ts.map +1 -1
  142. package/dist/routes/auto/insert.routes.js +1 -7
  143. package/dist/routes/auto/plugin.d.ts +6 -0
  144. package/dist/routes/auto/plugin.d.ts.map +1 -1
  145. package/dist/routes/auto/plugin.js +60 -36
  146. package/dist/routes/auto/route-helpers.d.ts +26 -12
  147. package/dist/routes/auto/route-helpers.d.ts.map +1 -1
  148. package/dist/routes/auto/route-helpers.js +50 -19
  149. package/dist/routes/auto/search.routes.d.ts +2 -2
  150. package/dist/routes/auto/search.routes.d.ts.map +1 -1
  151. package/dist/routes/auto/search.routes.js +36 -24
  152. package/dist/routes/auto/update.routes.d.ts +2 -2
  153. package/dist/routes/auto/update.routes.d.ts.map +1 -1
  154. package/dist/routes/auto/update.routes.js +1 -8
  155. package/dist/routes/sql-api-decorator.d.ts +30 -12
  156. package/dist/routes/sql-api-decorator.d.ts.map +1 -1
  157. package/dist/routes/sql-api-decorator.js +44 -27
  158. package/dist/types/cli.d.ts +17 -6
  159. package/dist/types/cli.d.ts.map +1 -1
  160. package/dist/types/computed.d.ts +1 -1
  161. package/dist/types/computed.d.ts.map +1 -1
  162. package/dist/types/conditions.d.ts +3 -1
  163. package/dist/types/conditions.d.ts.map +1 -1
  164. package/dist/types/db.d.ts +44 -4
  165. package/dist/types/db.d.ts.map +1 -1
  166. package/dist/types/dml.d.ts +26 -17
  167. package/dist/types/dml.d.ts.map +1 -1
  168. package/dist/types/hooks.d.ts +62 -0
  169. package/dist/types/hooks.d.ts.map +1 -0
  170. package/dist/types/hooks.js +1 -0
  171. package/dist/types/join.d.ts +25 -8
  172. package/dist/types/join.d.ts.map +1 -1
  173. package/dist/types/plugin.d.ts +58 -19
  174. package/dist/types/plugin.d.ts.map +1 -1
  175. package/dist/types/plugin.js +2 -0
  176. package/dist/types/request.d.ts +2 -2
  177. package/dist/types/schema.d.ts +3 -3
  178. package/dist/types/schema.d.ts.map +1 -1
  179. package/dist/types/search.d.ts +28 -13
  180. package/dist/types/search.d.ts.map +1 -1
  181. package/dist/types/search.js +2 -1
  182. package/dist/types/table.d.ts +109 -94
  183. package/dist/types/table.d.ts.map +1 -1
  184. package/dist/types/table.js +7 -2
  185. package/dist/types/tenant.d.ts +28 -2
  186. package/dist/types/tenant.d.ts.map +1 -1
  187. package/dist/types/tenant.js +7 -1
  188. package/dist/types/validation.d.ts +69 -13
  189. package/dist/types/validation.d.ts.map +1 -1
  190. package/dist/types.d.ts +1 -0
  191. package/dist/types.d.ts.map +1 -1
  192. package/dist/types.js +1 -0
  193. package/docs/GLOSSARY.md +11 -5
  194. package/docs/adr/0003-bulk-not-transactional.md +2 -1
  195. package/docs/adr/0006-raw-db-errors.md +2 -1
  196. package/docs/adr/0013-sanitized-db-errors.md +2 -1
  197. package/docs/adr/0014-what-follows-a-write-join.md +1 -1
  198. package/docs/adr/0022-stay-on-0x-while-every-consumer-is-first-party.md +88 -0
  199. package/docs/adr/0023-a-write-runs-in-a-transaction-or-not-at-all.md +60 -0
  200. package/docs/adr/0024-the-consumer-maps-driver-codes-through-dberrors.md +78 -0
  201. package/docs/adr/0025-validatebulk-replaces-validate-in-a-bulk-upsert.md +46 -0
  202. package/docs/adr/0026-update-carries-its-primary-key-in-main.md +43 -0
  203. package/docs/adr/0027-the-1-0-contract.md +74 -0
  204. package/docs/adr/0028-select-star-is-the-default-projection.md +64 -0
  205. package/docs/adr/0029-a-write-names-its-child-rows-by-action.md +96 -0
  206. package/docs/adr/0030-a-child-row-is-validated-by-its-own-table.md +117 -0
  207. package/docs/adr/0031-an-insert-excluded-upsert-key-addresses-an-existing-row.md +58 -0
  208. package/docs/adr/0032-tenant-scope-names-schema-fields.md +56 -0
  209. package/docs/adr/README.md +12 -1
  210. package/docs/upgrading/0.x.md +906 -0
  211. package/docs/upgrading/1.0.md +628 -0
  212. package/package.json +4 -5
@@ -1,31 +1,47 @@
1
+ import { STATUS_CODES } from 'node:http';
1
2
  /**
2
- * Build a plain Error decorated with `statusCode` (and optionally `validationErrors`),
3
- * which Fastify reads to emit the corresponding HTTP response.
3
+ * Build a plain Error decorated with `statusCode`, which the plugin's error handler reads to
4
+ * emit the corresponding HTTP response.
5
+ *
6
+ * A 400 should also say what was wrong with the input: `field` is rendered as the single
7
+ * entry of the response's `fields` array, so an engine rejection reaches the client in the
8
+ * same shape as a schema or `validate` error. Another status takes a `field` only where the
9
+ * client must read a code, e.g. a 409 a hook raises. `message` is copied into the field: a
10
+ * caller with nothing to say beyond the code sets `validationErrors` itself (`dbErrors`).
4
11
  *
5
12
  * Using a function instead of a custom class keeps the throw sites lightweight
6
13
  * and matches the existing convention across the codebase.
7
14
  */
8
- export function httpError(statusCode, message) {
15
+ export function httpError(statusCode, message, field) {
9
16
  const err = new Error(message);
10
17
  err.statusCode = statusCode;
18
+ if (field)
19
+ err.validationErrors = [{ path: field.path ?? '', code: field.code, message }];
11
20
  return err;
12
21
  }
22
+ /** The errors `sanitizeRouteError` produced: already safe, never sanitized twice. */
23
+ const SANITIZED = new WeakSet();
24
+ /** Whether `err` is the safe replacement `sanitizeRouteError` built for another error. */
25
+ export function isSanitized(err) {
26
+ return typeof err === 'object' && err !== null && SANITIZED.has(err);
27
+ }
13
28
  /**
14
29
  * Replace an error escaping a route handler with one that carries no database detail.
15
30
  *
16
31
  * Driver messages name tables, columns and constraints, and the route error handler sends
17
32
  * `error.message` verbatim — so a unique violation describes the schema to whoever
18
33
  * triggered it. Errors the plugin raises itself are deliberate `4xx` with messages written
19
- * for clients (`httpError`, `validationErrors`) and pass through untouched; everything
20
- * else becomes a bare `500`.
34
+ * for clients (`httpError`, `validationErrors`) and pass through untouched; a driver error
35
+ * whose `code` the consumer listed in `dbErrors` gets that status and the consumer's code, as
36
+ * the single entry of `fields`; everything else becomes a bare `500`. The plugin maps no code of
37
+ * its own: which ones deserve a status depends on the database, its version and the product
38
+ * (ADR 0006).
21
39
  *
22
- * The original is attached as `cause`, so a consumer `setErrorHandler` can still apply its
23
- * own policy — mapping SQLSTATE to a status code stays the consumer's decision (ADR 0006).
24
- * No status code is remapped here: a `500` stays a `500`.
40
+ * The original is attached as `cause`, and logged by the route under the same `reqId`.
25
41
  *
26
42
  * `requestId` is carried on the sanitized error and rendered in the response body: it is the
27
43
  * same value Fastify logs as `reqId` on every line, so the log entry holding the real error
28
- * is one grep away from the client's `500`.
44
+ * is one grep away from the client's response.
29
45
  *
30
46
  * With `exposeDebugInfo`, the original is also described in a `debugInfo` payload rendered
31
47
  * beside those fields — additive, so the response a client codes against is the same one it
@@ -33,19 +49,57 @@ export function httpError(statusCode, message) {
33
49
  * consumer, who may wire it to an environment variable, and no option may open an external
34
50
  * channel as a side effect of meaning something internal. See ADR 0013.
35
51
  */
36
- export function sanitizeRouteError(err, requestId, exposeDebugInfo = false) {
52
+ export function sanitizeRouteError(err, policy = {}) {
37
53
  const statusCode = err?.statusCode;
38
54
  if (typeof statusCode === 'number' && statusCode >= 400 && statusCode < 500)
39
55
  return err;
40
- const safe = httpError(500, 'Internal Server Error');
41
- safe.name = 'Internal Server Error';
56
+ const mapped = mapDbError(err, policy.dbErrors);
57
+ const safe = (mapped
58
+ ? httpError(mapped.status, STATUS_CODES[mapped.status] ?? 'Error')
59
+ : httpError(500, 'Internal Server Error'));
60
+ // The consumer's code is the whole answer: the reason phrase is already the envelope's
61
+ // `message`, repeating it in the field would say nothing more.
62
+ if (mapped)
63
+ safe.validationErrors = [{ path: '', code: mapped.code }];
42
64
  safe.cause = err;
43
- if (requestId)
44
- safe.requestId = requestId;
45
- if (exposeDebugInfo)
65
+ if (policy.requestId)
66
+ safe.requestId = policy.requestId;
67
+ if (policy.exposeDebugInfo)
46
68
  safe.debugInfo = describeError(err);
69
+ SANITIZED.add(safe);
47
70
  return safe;
48
71
  }
72
+ /** The consumer's `dbErrors` entry for this error's driver code; undefined when none. */
73
+ function mapDbError(err, dbErrors) {
74
+ const driverCode = err?.code;
75
+ if (!dbErrors || typeof driverCode !== 'string' || !Object.hasOwn(dbErrors, driverCode))
76
+ return undefined;
77
+ return dbErrors[driverCode];
78
+ }
79
+ /**
80
+ * Refuse a `dbErrors` option a route could not honour, at registration rather than on the
81
+ * first failing request: every entry is `{ status, code }`, the status an integer in 400–599,
82
+ * the code a non-empty string.
83
+ */
84
+ export function assertDbErrors(dbErrors) {
85
+ if (dbErrors === undefined)
86
+ return;
87
+ if (dbErrors === null || typeof dbErrors !== 'object' || Array.isArray(dbErrors)) {
88
+ throw new Error('dbErrors must be an object keyed by driver error code');
89
+ }
90
+ for (const [driverCode, entry] of Object.entries(dbErrors)) {
91
+ if (typeof entry !== 'object' || entry === null) {
92
+ throw new Error(`dbErrors["${driverCode}"]: expected { status, code }, got ${JSON.stringify(entry)}`);
93
+ }
94
+ const { status, code } = entry;
95
+ if (typeof status !== 'number' || !Number.isInteger(status) || status < 400 || status > 599) {
96
+ throw new Error(`dbErrors["${driverCode}"]: the status must be an integer between 400 and 599, got ${JSON.stringify(status)}`);
97
+ }
98
+ if (typeof code !== 'string' || code === '') {
99
+ throw new Error(`dbErrors["${driverCode}"]: the code must be a non-empty string, got ${JSON.stringify(code)}`);
100
+ }
101
+ }
102
+ }
49
103
  /**
50
104
  * Driver properties worth handing a developer, across both supported drivers: `pg` puts the
51
105
  * schema detail in `constraint`/`detail`/`table`/`column`, `mysql2` in `errno`/`sqlState`/
@@ -1,4 +1,4 @@
1
- import { type Static, type TSchema, type TUnsafe } from '@sinclair/typebox';
1
+ import { type Static, type TSchema, type TUnsafe } from 'typebox';
2
2
  /**
3
3
  * Mark a schema as nullable using the JSON-Schema type-array form
4
4
  * (`{ type: ['integer', 'null'] }`).
@@ -11,7 +11,8 @@ import { type Static, type TSchema, type TUnsafe } from '@sinclair/typebox';
11
11
  * type array, while a bare `Type.Optional(T)` coerces NULL to the type's zero value.
12
12
  *
13
13
  * Schemas without a `type` keyword (e.g. `Type.Any()`) already admit null and are
14
- * returned unchanged.
14
+ * returned unchanged. An Optional input stays Optional: TypeBox keeps that modifier in a
15
+ * non-enumerable key, which the spread below does not copy.
15
16
  */
16
17
  export declare function Nullable<T extends TSchema>(schema: T): TUnsafe<Static<T> | null>;
17
18
  //# sourceMappingURL=nullable.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"nullable.d.ts","sourceRoot":"","sources":["../../src/lib/nullable.ts"],"names":[],"mappings":"AAAA,OAAO,EAAQ,KAAK,MAAM,EAAE,KAAK,OAAO,EAAE,KAAK,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAElF;;;;;;;;;;;;;GAaG;AACH,wBAAgB,QAAQ,CAAC,CAAC,SAAS,OAAO,EAAE,MAAM,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,CAMhF"}
1
+ {"version":3,"file":"nullable.d.ts","sourceRoot":"","sources":["../../src/lib/nullable.ts"],"names":[],"mappings":"AAAA,OAAO,EAAoB,KAAK,MAAM,EAAE,KAAK,OAAO,EAAE,KAAK,OAAO,EAAE,MAAM,SAAS,CAAC;AAEpF;;;;;;;;;;;;;;GAcG;AACH,wBAAgB,QAAQ,CAAC,CAAC,SAAS,OAAO,EAAE,MAAM,EAAE,CAAC,GAAG,OAAO,CAAC,MAAM,CAAC,CAAC,CAAC,GAAG,IAAI,CAAC,CAOhF"}
@@ -1,4 +1,4 @@
1
- import { Type } from '@sinclair/typebox';
1
+ import { Type, IsOptional } from 'typebox';
2
2
  /**
3
3
  * Mark a schema as nullable using the JSON-Schema type-array form
4
4
  * (`{ type: ['integer', 'null'] }`).
@@ -11,14 +11,23 @@ import { Type } from '@sinclair/typebox';
11
11
  * type array, while a bare `Type.Optional(T)` coerces NULL to the type's zero value.
12
12
  *
13
13
  * Schemas without a `type` keyword (e.g. `Type.Any()`) already admit null and are
14
- * returned unchanged.
14
+ * returned unchanged. An Optional input stays Optional: TypeBox keeps that modifier in a
15
+ * non-enumerable key, which the spread below does not copy.
15
16
  */
16
17
  export function Nullable(schema) {
17
18
  const type = schema.type;
18
19
  if (!type)
19
- return schema;
20
+ return alreadyNullable(schema);
20
21
  const types = Array.isArray(type) ? type : [type];
21
22
  if (types.includes('null'))
22
- return schema;
23
- return Type.Unsafe({ ...schema, type: [...types, 'null'] });
23
+ return alreadyNullable(schema);
24
+ const nullable = Type.Unsafe({ ...schema, type: [...types, 'null'] });
25
+ return IsOptional(schema) ? Type.Optional(nullable) : nullable;
26
+ }
27
+ /**
28
+ * A schema that already admits null, returned as-is: its static type already includes
29
+ * `null` (or is `any`), so only the TypeBox wrapper type differs from `TUnsafe`.
30
+ */
31
+ function alreadyNullable(schema) {
32
+ return schema;
24
33
  }
@@ -1,14 +1,21 @@
1
+ import type { TSchema } from 'typebox';
1
2
  import type { QueryClient } from './db.js';
2
- import type { ITable, SchemaDefinition } from '../types.js';
3
+ import type { TableConfig, SchemaDefinition } from '../types.js';
3
4
  /**
4
- * Read visibility (`ITable.readExclude`).
5
+ * Read visibility (`TableConfig.readExclude`).
5
6
  *
6
7
  * Excluded fields are never projected by any read query and cannot be referenced
7
- * from filters, conditions, orderBy, aggregations or join selections: allowing a
8
+ * from filters, conditions, orderBy, aggregations or a join `select`: allowing a
8
9
  * field to be filtered while hiding it from the output would still leak its value
9
10
  * by bisection. Write paths (insert/update/upsert) are deliberately unaffected —
10
11
  * a field can be writable but never readable (e.g. a password hash).
11
12
  */
13
+ /**
14
+ * A table's `extraFilters` as a record of fields, whichever form the config used: a record
15
+ * of TypeBox schemas or a `Type.Object` (its `properties`). Told apart by the object's own
16
+ * `type: 'object'`, which a record of fields — whose values are schemas — never carries.
17
+ */
18
+ export declare function extraFilterFields(tableConf: TableConfig | undefined): Record<string, TSchema>;
12
19
  /**
13
20
  * Own-property membership for a field map.
14
21
  *
@@ -21,25 +28,27 @@ import type { ITable, SchemaDefinition } from '../types.js';
21
28
  export declare function hasOwnField(map: Record<string, unknown> | undefined, key: string): boolean;
22
29
  /** The value at `key`, but only when it is the map's own property. */
23
30
  export declare function ownField<T>(map: Record<string, T> | undefined, key: string): T | undefined;
24
- /** Throws 400 when `field` is read-excluded on `tableConf`. */
25
- export declare function assertReadable(tableConf: ITable | undefined, field: string): void;
31
+ /**
32
+ * Throws 400 when `field` is read-excluded on `tableConf`. `at` is the request path of the
33
+ * reference being checked, for the response's `fields`; '' when the caller does not know it.
34
+ */
35
+ export declare function assertReadable(tableConf: TableConfig | undefined, field: string, at?: string): void;
26
36
  /**
27
37
  * Throws 400 when a filter map targets a read-excluded field. Keys that are not
28
38
  * excluded pass through untouched (extraFilters and computed names included).
29
39
  */
30
- export declare function assertFiltersReadable(filters: Record<string, unknown> | undefined, tableConf: ITable | undefined): void;
40
+ export declare function assertFiltersReadable(filters: Record<string, unknown> | undefined, tableConf: TableConfig | undefined, at?: string): void;
31
41
  /**
32
42
  * Throws 400 when a filter map carries a key the engine would never visit.
33
43
  *
34
44
  * Filters are matched against the schema fields, the table's `extraFilters` and its computed
35
- * fields; anything else used to be dropped without a word, so a mistyped key returned MORE
36
- * rows than the caller asked for and nothing said so. That is the dangerous direction to fail
37
- * in — filters are also how consumers narrow visibility — and it contradicted every
38
- * neighbouring path, where an unknown field in `selection`, `conditions`, `orderBy` or an
39
- * aggregation is already a 400.
45
+ * fields; anything else is refused. Dropped without a word, a mistyped key would return MORE
46
+ * rows than the caller asked for and nothing would say so. That is the dangerous direction to
47
+ * fail in — filters are also how consumers narrow visibility — and every neighbouring path
48
+ * agrees: an unknown field in `select`, `conditions`, `orderBy` or an aggregation is a 400.
40
49
  *
41
50
  * `schema` is the schema the relation was declared with, which for a join may be a trimmed
42
- * copy: a field outside it is unknown here exactly as it is for `selection`.
51
+ * copy: a field outside it is unknown here exactly as it is for `select`.
43
52
  *
44
53
  * `allowExtraFilters` is false on the joinLeft path, whose condition is built inline
45
54
  * (`buildLeftJoinClauses`) and never runs the table's `extendedCondition`.
@@ -47,21 +56,24 @@ export declare function assertFiltersReadable(filters: Record<string, unknown> |
47
56
  * Call AFTER `assertFiltersReadable`, so a read-excluded field keeps its own message
48
57
  * instead of being reported as unknown.
49
58
  */
50
- export declare function assertKnownFilterKeys(filters: Record<string, unknown> | undefined, schema: SchemaDefinition, tableConf: ITable | undefined, allowExtraFilters?: boolean): void;
59
+ export declare function assertKnownFilterKeys(filters: Record<string, unknown> | undefined, schema: SchemaDefinition, tableConf: TableConfig | undefined, allowExtraFilters?: boolean, at?: string): void;
51
60
  /** Schema field names that may be read, in schema declaration order. */
52
- export declare function readableFieldNames(tableConf: ITable | undefined, schema: SchemaDefinition): string[];
61
+ export declare function readableFieldNames(tableConf: TableConfig | undefined, schema: SchemaDefinition): string[];
53
62
  /**
54
- * SELECT column list for a table with read exclusions, or `undefined` when the
55
- * table has none (callers keep their existing `*` projection).
63
+ * The SELECT projection of a table's own rows: its readable columns spelled out when the
64
+ * table has `readExclude`, `"table".*` otherwise.
56
65
  *
57
- * Columns are qualified with the table name: read queries may carry a tenant
58
- * `through` INNER JOIN, where a bare column name shared with the through table
59
- * would be ambiguous.
66
+ * Always qualified with the table name, never a bare `*`. A read query may carry a JOIN — a
67
+ * filtered or ordered `joinLeft`, a tenant `through` INNER JOIN — and a bare `*` would
68
+ * project the joined table's columns into the row too; on a name clash (`id`, `name`,
69
+ * `createdAt`…) the driver keeps the LAST value read, the joined one, so every main row
70
+ * would carry the parent's id. Callers compose this string further (computed projections),
71
+ * which is why the qualification has to be in the string itself and not only in `db.select`.
60
72
  */
61
- export declare function readableSelectColumns(tableConf: ITable | undefined, schema: SchemaDefinition, db: QueryClient): string | undefined;
73
+ export declare function readableSelectColumns(tableConf: TableConfig | undefined, schema: SchemaDefinition, db: QueryClient): string;
62
74
  /**
63
75
  * The same list, always spelled out. Used where `*` is not an acceptable fallback: a
64
76
  * relation narrowed by a `fields` allowlist must project the allowlist, not the table.
65
77
  */
66
- export declare function explicitSelectColumns(tableConf: ITable | undefined, schema: SchemaDefinition, db: QueryClient): string;
78
+ export declare function explicitSelectColumns(tableConf: TableConfig | undefined, schema: SchemaDefinition, db: QueryClient): string;
67
79
  //# sourceMappingURL=read-access.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"read-access.d.ts","sourceRoot":"","sources":["../../src/lib/read-access.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAC3C,OAAO,KAAK,EAAE,MAAM,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAG5D;;;;;;;;GAQG;AAEH;;;;;;;;GAQG;AACH,wBAAgB,WAAW,CACzB,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,EACxC,GAAG,EAAE,MAAM,GACV,OAAO,CAET;AAED,sEAAsE;AACtE,wBAAgB,QAAQ,CAAC,CAAC,EACxB,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,GAAG,SAAS,EAClC,GAAG,EAAE,MAAM,GACV,CAAC,GAAG,SAAS,CAEf;AAMD,+DAA+D;AAC/D,wBAAgB,cAAc,CAAC,SAAS,EAAE,MAAM,GAAG,SAAS,EAAE,KAAK,EAAE,MAAM,GAAG,IAAI,CAIjF;AAED;;;GAGG;AACH,wBAAgB,qBAAqB,CACnC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,EAC5C,SAAS,EAAE,MAAM,GAAG,SAAS,GAC5B,IAAI,CAKN;AAED;;;;;;;;;;;;;;;;;;GAkBG;AACH,wBAAgB,qBAAqB,CACnC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,EAC5C,MAAM,EAAE,gBAAgB,EACxB,SAAS,EAAE,MAAM,GAAG,SAAS,EAC7B,iBAAiB,UAAO,GACvB,IAAI,CAkBN;AAED,wEAAwE;AACxE,wBAAgB,kBAAkB,CAChC,SAAS,EAAE,MAAM,GAAG,SAAS,EAC7B,MAAM,EAAE,gBAAgB,GACvB,MAAM,EAAE,CAIV;AAED;;;;;;;GAOG;AACH,wBAAgB,qBAAqB,CACnC,SAAS,EAAE,MAAM,GAAG,SAAS,EAC7B,MAAM,EAAE,gBAAgB,EACxB,EAAE,EAAE,WAAW,GACd,MAAM,GAAG,SAAS,CAGpB;AAED;;;GAGG;AACH,wBAAgB,qBAAqB,CACnC,SAAS,EAAE,MAAM,GAAG,SAAS,EAC7B,MAAM,EAAE,gBAAgB,EACxB,EAAE,EAAE,WAAW,GACd,MAAM,CAKR"}
1
+ {"version":3,"file":"read-access.d.ts","sourceRoot":"","sources":["../../src/lib/read-access.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,OAAO,EAAW,MAAM,SAAS,CAAC;AAChD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,SAAS,CAAC;AAC3C,OAAO,KAAK,EAAE,WAAW,EAAE,gBAAgB,EAAE,MAAM,aAAa,CAAC;AAGjE;;;;;;;;GAQG;AAEH;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,SAAS,EAAE,WAAW,GAAG,SAAS,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAO7F;AAED;;;;;;;;GAQG;AACH,wBAAgB,WAAW,CACzB,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,EACxC,GAAG,EAAE,MAAM,GACV,OAAO,CAET;AAED,sEAAsE;AACtE,wBAAgB,QAAQ,CAAC,CAAC,EACxB,GAAG,EAAE,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,GAAG,SAAS,EAClC,GAAG,EAAE,MAAM,GACV,CAAC,GAAG,SAAS,CAEf;AAMD;;;GAGG;AACH,wBAAgB,cAAc,CAAC,SAAS,EAAE,WAAW,GAAG,SAAS,EAAE,KAAK,EAAE,MAAM,EAAE,EAAE,SAAK,GAAG,IAAI,CAI/F;AAED;;;GAGG;AACH,wBAAgB,qBAAqB,CACnC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,EAC5C,SAAS,EAAE,WAAW,GAAG,SAAS,EAClC,EAAE,SAAY,GACb,IAAI,CAKN;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,wBAAgB,qBAAqB,CACnC,OAAO,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,SAAS,EAC5C,MAAM,EAAE,gBAAgB,EACxB,SAAS,EAAE,WAAW,GAAG,SAAS,EAClC,iBAAiB,UAAO,EACxB,EAAE,SAAY,GACb,IAAI,CAmBN;AAED,wEAAwE;AACxE,wBAAgB,kBAAkB,CAChC,SAAS,EAAE,WAAW,GAAG,SAAS,EAClC,MAAM,EAAE,gBAAgB,GACvB,MAAM,EAAE,CAIV;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,qBAAqB,CACnC,SAAS,EAAE,WAAW,GAAG,SAAS,EAClC,MAAM,EAAE,gBAAgB,EACxB,EAAE,EAAE,WAAW,GACd,MAAM,CAGR;AAED;;;GAGG;AACH,wBAAgB,qBAAqB,CACnC,SAAS,EAAE,WAAW,GAAG,SAAS,EAClC,MAAM,EAAE,gBAAgB,EACxB,EAAE,EAAE,WAAW,GACd,MAAM,CAKR"}
@@ -1,13 +1,27 @@
1
1
  import { httpError } from './errors.js';
2
2
  /**
3
- * Read visibility (`ITable.readExclude`).
3
+ * Read visibility (`TableConfig.readExclude`).
4
4
  *
5
5
  * Excluded fields are never projected by any read query and cannot be referenced
6
- * from filters, conditions, orderBy, aggregations or join selections: allowing a
6
+ * from filters, conditions, orderBy, aggregations or a join `select`: allowing a
7
7
  * field to be filtered while hiding it from the output would still leak its value
8
8
  * by bisection. Write paths (insert/update/upsert) are deliberately unaffected —
9
9
  * a field can be writable but never readable (e.g. a password hash).
10
10
  */
11
+ /**
12
+ * A table's `extraFilters` as a record of fields, whichever form the config used: a record
13
+ * of TypeBox schemas or a `Type.Object` (its `properties`). Told apart by the object's own
14
+ * `type: 'object'`, which a record of fields — whose values are schemas — never carries.
15
+ */
16
+ export function extraFilterFields(tableConf) {
17
+ const ef = tableConf?.extraFilters;
18
+ if (!ef)
19
+ return {};
20
+ if (ef.type === 'object' && typeof ef.properties === 'object') {
21
+ return ef.properties;
22
+ }
23
+ return ef;
24
+ }
11
25
  /**
12
26
  * Own-property membership for a field map.
13
27
  *
@@ -27,35 +41,37 @@ export function ownField(map, key) {
27
41
  function isReadExcluded(tableConf, field) {
28
42
  return tableConf?.readExclude?.includes(field) ?? false;
29
43
  }
30
- /** Throws 400 when `field` is read-excluded on `tableConf`. */
31
- export function assertReadable(tableConf, field) {
44
+ /**
45
+ * Throws 400 when `field` is read-excluded on `tableConf`. `at` is the request path of the
46
+ * reference being checked, for the response's `fields`; '' when the caller does not know it.
47
+ */
48
+ export function assertReadable(tableConf, field, at = '') {
32
49
  if (isReadExcluded(tableConf, field)) {
33
- throw httpError(400, `Field is not readable: ${field}`);
50
+ throw httpError(400, `Field is not readable: ${field}`, { code: 'not_readable', path: at });
34
51
  }
35
52
  }
36
53
  /**
37
54
  * Throws 400 when a filter map targets a read-excluded field. Keys that are not
38
55
  * excluded pass through untouched (extraFilters and computed names included).
39
56
  */
40
- export function assertFiltersReadable(filters, tableConf) {
57
+ export function assertFiltersReadable(filters, tableConf, at = 'filters') {
41
58
  if (!filters || !tableConf?.readExclude?.length)
42
59
  return;
43
60
  for (const key of Object.keys(filters)) {
44
- assertReadable(tableConf, key);
61
+ assertReadable(tableConf, key, `${at}.${key}`);
45
62
  }
46
63
  }
47
64
  /**
48
65
  * Throws 400 when a filter map carries a key the engine would never visit.
49
66
  *
50
67
  * Filters are matched against the schema fields, the table's `extraFilters` and its computed
51
- * fields; anything else used to be dropped without a word, so a mistyped key returned MORE
52
- * rows than the caller asked for and nothing said so. That is the dangerous direction to fail
53
- * in — filters are also how consumers narrow visibility — and it contradicted every
54
- * neighbouring path, where an unknown field in `selection`, `conditions`, `orderBy` or an
55
- * aggregation is already a 400.
68
+ * fields; anything else is refused. Dropped without a word, a mistyped key would return MORE
69
+ * rows than the caller asked for and nothing would say so. That is the dangerous direction to
70
+ * fail in — filters are also how consumers narrow visibility — and every neighbouring path
71
+ * agrees: an unknown field in `select`, `conditions`, `orderBy` or an aggregation is a 400.
56
72
  *
57
73
  * `schema` is the schema the relation was declared with, which for a join may be a trimmed
58
- * copy: a field outside it is unknown here exactly as it is for `selection`.
74
+ * copy: a field outside it is unknown here exactly as it is for `select`.
59
75
  *
60
76
  * `allowExtraFilters` is false on the joinLeft path, whose condition is built inline
61
77
  * (`buildLeftJoinClauses`) and never runs the table's `extendedCondition`.
@@ -63,7 +79,7 @@ export function assertFiltersReadable(filters, tableConf) {
63
79
  * Call AFTER `assertFiltersReadable`, so a read-excluded field keeps its own message
64
80
  * instead of being reported as unknown.
65
81
  */
66
- export function assertKnownFilterKeys(filters, schema, tableConf, allowExtraFilters = true) {
82
+ export function assertKnownFilterKeys(filters, schema, tableConf, allowExtraFilters = true, at = 'filters') {
67
83
  if (!filters)
68
84
  return;
69
85
  for (const [key, value] of Object.entries(filters)) {
@@ -75,13 +91,13 @@ export function assertKnownFilterKeys(filters, schema, tableConf, allowExtraFilt
75
91
  continue;
76
92
  if (ownField(tableConf?.computedFields, key))
77
93
  continue;
78
- if (hasOwnField(tableConf?.extraFilters, key)) {
94
+ if (hasOwnField(extraFilterFields(tableConf), key)) {
79
95
  if (allowExtraFilters)
80
96
  continue;
81
97
  throw httpError(400, `Filter '${key}' is an extraFilter: extraFilters are not applied on joinLeft ` +
82
- `(only schema fields and computed fields are). Use joinMustExist on the same relation.`);
98
+ `(only schema fields and computed fields are). Use joinMustExist on the same relation.`, { code: 'extra_filter_not_allowed', path: `${at}.${key}` });
83
99
  }
84
- throw httpError(400, `Unknown filter field: ${key}`);
100
+ throw httpError(400, `Unknown filter field: ${key}`, { code: 'unknown_field', path: `${at}.${key}` });
85
101
  }
86
102
  }
87
103
  /** Schema field names that may be read, in schema declaration order. */
@@ -92,16 +108,19 @@ export function readableFieldNames(tableConf, schema) {
92
108
  return fields.filter((f) => !isReadExcluded(tableConf, f));
93
109
  }
94
110
  /**
95
- * SELECT column list for a table with read exclusions, or `undefined` when the
96
- * table has none (callers keep their existing `*` projection).
111
+ * The SELECT projection of a table's own rows: its readable columns spelled out when the
112
+ * table has `readExclude`, `"table".*` otherwise.
97
113
  *
98
- * Columns are qualified with the table name: read queries may carry a tenant
99
- * `through` INNER JOIN, where a bare column name shared with the through table
100
- * would be ambiguous.
114
+ * Always qualified with the table name, never a bare `*`. A read query may carry a JOIN — a
115
+ * filtered or ordered `joinLeft`, a tenant `through` INNER JOIN — and a bare `*` would
116
+ * project the joined table's columns into the row too; on a name clash (`id`, `name`,
117
+ * `createdAt`…) the driver keeps the LAST value read, the joined one, so every main row
118
+ * would carry the parent's id. Callers compose this string further (computed projections),
119
+ * which is why the qualification has to be in the string itself and not only in `db.select`.
101
120
  */
102
121
  export function readableSelectColumns(tableConf, schema, db) {
103
122
  if (!tableConf?.readExclude?.length)
104
- return undefined;
123
+ return `${db.qi(schema.tableName)}.*`;
105
124
  return explicitSelectColumns(tableConf, schema, db);
106
125
  }
107
126
  /**
@@ -1,10 +1,16 @@
1
+ import { Type } from 'typebox';
1
2
  import type { DbTables } from '../../types.js';
2
- export declare function BulkDeleteTableBody(dbTables: DbTables, tableName: string, maxItems?: number): import("@sinclair/typebox").TArray<import("@sinclair/typebox").TObject<{
3
- [x: string]: any;
4
- }>>;
5
- export declare function BulkDeleteTableResponse(dbTables: DbTables, tableName: string): import("@sinclair/typebox").TArray<import("@sinclair/typebox").TObject<{
6
- main: import("@sinclair/typebox").TObject<{
7
- [x: string]: any;
8
- }>;
3
+ /**
4
+ * `{ ids: [...] }`: the primary keys to delete, the same body for every table whatever its PK is
5
+ * called. A single-column key takes the values, typed as the PK field; a composite key takes one
6
+ * object per row naming every key field and nothing else (`{ postId: 1, tagId: 2 }`), so no id
7
+ * can match on one column alone. `maxItems` (the plugin's `maxBulkItems`) caps the ids.
8
+ */
9
+ export declare function BulkDeleteTableBody(dbTables: DbTables, tableName: string, maxItems?: number): Type.TObject<{
10
+ ids: Type.TArray<Type.TSchema>;
11
+ }>;
12
+ /** One `{ main: <key> }` per deleted row, the key naming every primary key field. */
13
+ export declare function BulkDeleteTableResponse(dbTables: DbTables, tableName: string): Type.TArray<Type.TObject<{
14
+ main: Type.TObject<Record<string, Type.TSchema>>;
9
15
  }>>;
10
16
  //# sourceMappingURL=bulk-delete.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"bulk-delete.d.ts","sourceRoot":"","sources":["../../../src/lib/schema/bulk-delete.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAE/C,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM;;IAS3F;AAED,wBAAgB,uBAAuB,CAAC,QAAQ,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM;;;;IAU5E"}
1
+ {"version":3,"file":"bulk-delete.d.ts","sourceRoot":"","sources":["../../../src/lib/schema/bulk-delete.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAgB,MAAM,SAAS,CAAC;AAC7C,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAG/C;;;;;GAKG;AACH,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM;;GAW3F;AAED,qFAAqF;AACrF,wBAAgB,uBAAuB,CAAC,QAAQ,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM;;IAO5E"}
@@ -1,16 +1,26 @@
1
- import { Type } from '@sinclair/typebox';
2
- import { primaryAsString } from '../../types.js';
1
+ import { Type } from 'typebox';
2
+ import { asRequired, pkSchema } from './helpers.js';
3
+ /**
4
+ * `{ ids: [...] }`: the primary keys to delete, the same body for every table whatever its PK is
5
+ * called. A single-column key takes the values, typed as the PK field; a composite key takes one
6
+ * object per row naming every key field and nothing else (`{ postId: 1, tagId: 2 }`), so no id
7
+ * can match on one column alone. `maxItems` (the plugin's `maxBulkItems`) caps the ids.
8
+ */
3
9
  export function BulkDeleteTableBody(dbTables, tableName, maxItems) {
4
10
  const tableConf = dbTables[tableName];
5
- const pkField = primaryAsString(tableConf.primary);
6
- const pkType = tableConf.Schema.fields[pkField];
7
- return Type.Array(Type.Object({ [pkField]: pkType }, { additionalProperties: false }), maxItems != null ? { maxItems } : {});
11
+ const pkFields = Array.isArray(tableConf.primary) ? tableConf.primary : [tableConf.primary];
12
+ const typeOf = (f) => asRequired(tableConf.schema.fields[f] ?? Type.String());
13
+ const id = pkFields.length === 1
14
+ ? typeOf(pkFields[0])
15
+ : Type.Object(Object.fromEntries(pkFields.map((f) => [f, typeOf(f)])), { additionalProperties: false });
16
+ return Type.Object({
17
+ ids: Type.Array(id, maxItems != null ? { maxItems } : {}),
18
+ }, { additionalProperties: false });
8
19
  }
20
+ /** One `{ main: <key> }` per deleted row, the key naming every primary key field. */
9
21
  export function BulkDeleteTableResponse(dbTables, tableName) {
10
22
  const tableConf = dbTables[tableName];
11
- const pkField = primaryAsString(tableConf.primary);
12
- const pkType = tableConf.Schema.fields[pkField];
13
23
  return Type.Array(Type.Object({
14
- main: Type.Object({ [pkField]: pkType }),
24
+ main: Type.Object(pkSchema(tableConf, tableConf.schema, '')),
15
25
  }));
16
26
  }
@@ -1,5 +1,5 @@
1
- import { type TSchema } from '@sinclair/typebox';
1
+ import { Type } from 'typebox';
2
2
  import type { DbTables } from '../../types.js';
3
- export declare function BulkUpsertTableBody(dbTables: DbTables, tableName: string, maxItems?: number): import("@sinclair/typebox").TArray<import("@sinclair/typebox").TObject<Record<string, TSchema>>>;
4
- export declare function BulkUpsertTableResponse(dbTables: DbTables, tableName: string): import("@sinclair/typebox").TArray<import("@sinclair/typebox").TObject<Record<string, TSchema>>>;
3
+ export declare function BulkUpsertTableBody(dbTables: DbTables, tableName: string, maxItems?: number): Type.TArray<Type.TObject<Record<string, Type.TSchema>>>;
4
+ export declare function BulkUpsertTableResponse(dbTables: DbTables, tableName: string): Type.TArray<Type.TObject<Record<string, Type.TSchema>>>;
5
5
  //# sourceMappingURL=bulk-upsert.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"bulk-upsert.d.ts","sourceRoot":"","sources":["../../../src/lib/schema/bulk-upsert.ts"],"names":[],"mappings":"AAAA,OAAO,EAAQ,KAAK,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAEvD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAU/C,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,oGAuB3F;AAED,wBAAgB,uBAAuB,CAAC,QAAQ,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,oGAa5E"}
1
+ {"version":3,"file":"bulk-upsert.d.ts","sourceRoot":"","sources":["../../../src/lib/schema/bulk-upsert.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,IAAI,EAAgB,MAAM,SAAS,CAAC;AAE7C,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAU/C,wBAAgB,mBAAmB,CAAC,QAAQ,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,2DAkB3F;AAED,wBAAgB,uBAAuB,CAAC,QAAQ,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,2DAW5E"}
@@ -1,30 +1,25 @@
1
- import { Type } from '@sinclair/typebox';
1
+ import { Type } from 'typebox';
2
2
  import { primaryAsString } from '../../types.js';
3
3
  import { writableFields } from '../write-access.js';
4
- import { pkSchema, applySchemaOverrides, attachWriteJoinSections, writeJoinBodyFields, writeJoinResponseFields, } from './helpers.js';
4
+ import { pkSchema, applySchemaOverrides, attachRequestSections, attachOutcomeSections, WriteActionSchema, } from './helpers.js';
5
5
  export function BulkUpsertTableBody(dbTables, tableName, maxItems) {
6
6
  const tableConf = dbTables[tableName];
7
- const schema = tableConf.Schema;
7
+ const schema = tableConf.schema;
8
8
  // additionalProperties:false makes the schema the real write whitelist (no mass assignment).
9
- const mainSchema = Type.Partial(Type.Object(writableFields(applySchemaOverrides({ ...schema.fields }, tableConf), tableConf, schema), { additionalProperties: false }));
9
+ // It goes on Partial itself: Partial rebuilds the object and drops the source's options.
10
+ const mainSchema = Type.Partial(Type.Object(writableFields(applySchemaOverrides({ ...schema.fields }, tableConf), tableConf, schema)), { additionalProperties: false });
10
11
  const itemProperties = {
11
12
  main: mainSchema,
12
13
  };
13
- attachWriteJoinSections(itemProperties, tableConf, dbTables, {
14
- withDeletions: true,
15
- secondaryFields: writeJoinBodyFields,
16
- strictItems: true,
17
- });
14
+ attachRequestSections(itemProperties, tableConf, dbTables, { withDelete: true });
18
15
  return Type.Array(Type.Object(itemProperties), maxItems != null ? { maxItems } : {});
19
16
  }
20
17
  export function BulkUpsertTableResponse(dbTables, tableName) {
21
18
  const tableConf = dbTables[tableName];
22
19
  const responseProperties = {
23
- main: Type.Object(pkSchema(tableConf, tableConf.Schema, primaryAsString(tableConf.primary))),
20
+ main: Type.Object(pkSchema(tableConf, tableConf.schema, primaryAsString(tableConf.primary))),
21
+ action: WriteActionSchema,
24
22
  };
25
- attachWriteJoinSections(responseProperties, tableConf, dbTables, {
26
- withDeletions: true,
27
- secondaryFields: writeJoinResponseFields,
28
- });
23
+ attachOutcomeSections(responseProperties, tableConf, dbTables, { deletions: 'all' });
29
24
  return Type.Array(Type.Object(responseProperties));
30
25
  }
@@ -1,4 +1,4 @@
1
- import { type TObject } from '@sinclair/typebox';
1
+ import { type TObject } from 'typebox';
2
2
  import type { DbTables } from '../../types.js';
3
3
  /**
4
4
  * Response shape of `GET /rest/:table/:id`.
@@ -1 +1 @@
1
- {"version":3,"file":"get.d.ts","sourceRoot":"","sources":["../../../src/lib/schema/get.ts"],"names":[],"mappings":"AAAA,OAAO,EAAQ,KAAK,OAAO,EAAE,MAAM,mBAAmB,CAAC;AAEvD,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAE/C;;;;;;;;;GASG;AACH,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAK/E"}
1
+ {"version":3,"file":"get.d.ts","sourceRoot":"","sources":["../../../src/lib/schema/get.ts"],"names":[],"mappings":"AAAA,OAAO,EAAQ,KAAK,OAAO,EAAE,MAAM,SAAS,CAAC;AAE7C,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAC;AAE/C;;;;;;;;;GASG;AACH,wBAAgB,gBAAgB,CAAC,QAAQ,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,GAAG,OAAO,CAK/E"}
@@ -1,4 +1,4 @@
1
- import { Type } from '@sinclair/typebox';
1
+ import { Type } from 'typebox';
2
2
  import { readableFields } from './helpers.js';
3
3
  /**
4
4
  * Response shape of `GET /rest/:table/:id`.
@@ -13,6 +13,6 @@ import { readableFields } from './helpers.js';
13
13
  export function GetTableResponse(dbTables, tableName) {
14
14
  const tableConf = dbTables[tableName];
15
15
  return Type.Object({
16
- main: Type.Partial(Type.Object(readableFields(tableConf.Schema, tableConf))),
16
+ main: Type.Partial(Type.Object(readableFields(tableConf.schema, tableConf))),
17
17
  });
18
18
  }