@sssb/kit 0.0.0 → 0.2.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 (214) hide show
  1. package/LICENSE +21 -0
  2. package/dist/core/webhook-hmac.d.ts +69 -0
  3. package/dist/release.json +1 -0
  4. package/dist/testing/e2e.d.ts +15 -0
  5. package/dist/testing/e2e.js +195 -0
  6. package/package.json +209 -5
  7. package/src/adapters/README.md +6 -0
  8. package/src/adapters/dev-server.ts +21 -0
  9. package/src/adapters/fake/agreements.ts +81 -0
  10. package/src/adapters/fake/analytics.ts +93 -0
  11. package/src/adapters/fake/atomic-write.ts +161 -0
  12. package/src/adapters/fake/audit.ts +58 -0
  13. package/src/adapters/fake/auth.ts +312 -0
  14. package/src/adapters/fake/clock.ts +54 -0
  15. package/src/adapters/fake/data-dir.ts +27 -0
  16. package/src/adapters/fake/db.ts +88 -0
  17. package/src/adapters/fake/email.ts +46 -0
  18. package/src/adapters/fake/jobs.ts +270 -0
  19. package/src/adapters/fake/llm.ts +230 -0
  20. package/src/adapters/fake/pglite-dialect.ts +124 -0
  21. package/src/adapters/fake/service-auth.ts +145 -0
  22. package/src/adapters/fake/simulator-admin.ts +203 -0
  23. package/src/adapters/fake/simulator.ts +94 -0
  24. package/src/adapters/fake/sms.ts +43 -0
  25. package/src/adapters/fake/storage.ts +288 -0
  26. package/src/adapters/fake/webhooks.ts +98 -0
  27. package/src/adapters/index.ts +115 -0
  28. package/src/adapters/real/accept-invite-form.tsx +77 -0
  29. package/src/adapters/real/analytics.ts +28 -0
  30. package/src/adapters/real/auth.ts +216 -0
  31. package/src/adapters/real/contract-data-api.ts +104 -0
  32. package/src/adapters/real/contract-postgres.ts +167 -0
  33. package/src/adapters/real/database-transport.ts +34 -0
  34. package/src/adapters/real/db-data-api.ts +61 -0
  35. package/src/adapters/real/db.ts +88 -0
  36. package/src/adapters/real/email.ts +22 -0
  37. package/src/adapters/real/index.ts +89 -0
  38. package/src/adapters/real/jobs.ts +32 -0
  39. package/src/adapters/real/llm.ts +108 -0
  40. package/src/adapters/real/migrate-handler.ts +66 -0
  41. package/src/adapters/real/providers.tsx +12 -0
  42. package/src/adapters/real/rds-data-codec.ts +508 -0
  43. package/src/adapters/real/rds-data-dialect.ts +470 -0
  44. package/src/adapters/real/rds-data-emulator.ts +351 -0
  45. package/src/adapters/real/s3-storage.ts +233 -0
  46. package/src/adapters/real/sign-in-form.tsx +59 -0
  47. package/src/adapters/real/storage.ts +10 -0
  48. package/src/adapters/sentry/baseline.ts +90 -0
  49. package/src/adapters/sentry/client.ts +17 -0
  50. package/src/adapters/sentry/init.ts +17 -0
  51. package/src/authz/app-exemptions.ts +226 -0
  52. package/src/authz/authorize.ts +214 -0
  53. package/src/authz/route-policy.ts +153 -0
  54. package/src/authz/route-scan.ts +1516 -0
  55. package/src/components/agreements/acceptances-section.tsx +55 -0
  56. package/src/components/agreements/agreement-advisory-banner.tsx +33 -0
  57. package/src/components/agreements/agreement-body.tsx +34 -0
  58. package/src/components/agreements/agreement-gate.tsx +45 -0
  59. package/src/components/app-header.tsx +45 -0
  60. package/src/components/auth/accept-invite-screen.tsx +126 -0
  61. package/src/components/auth/auth-icons.tsx +68 -0
  62. package/src/components/auth/org-switcher.tsx +76 -0
  63. package/src/components/auth/people-picker.tsx +50 -0
  64. package/src/components/auth/preview-row.tsx +64 -0
  65. package/src/components/auth/sign-in-screen.tsx +24 -0
  66. package/src/components/auth/user-menu.tsx +64 -0
  67. package/src/components/demo-badge.tsx +20 -0
  68. package/src/components/demo-banner.tsx +14 -0
  69. package/src/components/gates/gate-interstitial.tsx +23 -0
  70. package/src/components/job-timeline.tsx +64 -0
  71. package/src/components/notifications/notification-bell.tsx +120 -0
  72. package/src/components/notifications/notification-prefs-section.tsx +112 -0
  73. package/src/components/org-screen.tsx +197 -0
  74. package/src/components/profile-screen.tsx +100 -0
  75. package/src/components/simulator/actor-runtime.ts +180 -0
  76. package/src/components/simulator/actor-shell.tsx +275 -0
  77. package/src/components/simulator/actors-app.tsx +119 -0
  78. package/src/components/simulator/errors-app.tsx +84 -0
  79. package/src/components/simulator/events-app.tsx +210 -0
  80. package/src/components/simulator/format-when.ts +20 -0
  81. package/src/components/simulator/hooks-app.tsx +319 -0
  82. package/src/components/simulator/inbound-app.tsx +210 -0
  83. package/src/components/simulator/jobs-app.tsx +471 -0
  84. package/src/components/simulator/mail-app.tsx +290 -0
  85. package/src/components/simulator/messages-app.tsx +64 -0
  86. package/src/components/simulator/people-app.tsx +140 -0
  87. package/src/components/simulator/people-dimensions.ts +16 -0
  88. package/src/components/simulator/simulator-panel.tsx +716 -0
  89. package/src/components/simulator/snapshots-app.tsx +398 -0
  90. package/src/components/simulator/tab-mount.ts +25 -0
  91. package/src/components/simulator/tours-app.tsx +105 -0
  92. package/src/components/webhook-endpoints-card.tsx +172 -0
  93. package/src/core/abilities.ts +459 -0
  94. package/src/core/agreements.ts +139 -0
  95. package/src/core/gates.ts +157 -0
  96. package/src/core/greeting.ts +11 -0
  97. package/src/core/inbound-email.ts +129 -0
  98. package/src/core/jobs.ts +51 -0
  99. package/src/core/keyset.ts +227 -0
  100. package/src/core/llm-models.ts +10 -0
  101. package/src/core/locale.ts +3 -0
  102. package/src/core/notifications.ts +182 -0
  103. package/src/core/presets.ts +456 -0
  104. package/src/core/roles.ts +47 -0
  105. package/src/core/schedules.ts +147 -0
  106. package/src/core/standard-schema.ts +56 -0
  107. package/src/core/state-machine.ts +43 -0
  108. package/src/core/webhook-events.ts +86 -0
  109. package/src/core/webhook-hmac.ts +248 -0
  110. package/src/core/webhook-signing.ts +27 -0
  111. package/src/cutover/rows.json +101 -0
  112. package/src/db/agreements.ts +176 -0
  113. package/src/db/app-roles.ts +197 -0
  114. package/src/db/audit.ts +356 -0
  115. package/src/db/inbound-email.ts +145 -0
  116. package/src/db/jobs.ts +300 -0
  117. package/src/db/jsonb.ts +18 -0
  118. package/src/db/keyset.ts +179 -0
  119. package/src/db/migrate.ts +73 -0
  120. package/src/db/migrations/0001_tenants.ts +25 -0
  121. package/src/db/migrations/0003_organizations.ts +27 -0
  122. package/src/db/migrations/0004_jobs.ts +64 -0
  123. package/src/db/migrations/0005_service_keys.ts +33 -0
  124. package/src/db/migrations/0008_audit_events.ts +51 -0
  125. package/src/db/migrations/0009_job_schedules.ts +52 -0
  126. package/src/db/migrations/0010_webhooks.ts +100 -0
  127. package/src/db/migrations/0011_notifications.ts +98 -0
  128. package/src/db/migrations/0012_inbound_email.ts +74 -0
  129. package/src/db/migrations/0013_agreements.ts +98 -0
  130. package/src/db/migrations/0014_audit_credential.ts +29 -0
  131. package/src/db/migrations/0015_app_user_grant.ts +67 -0
  132. package/src/db/migrations/0016_audit_detail.ts +26 -0
  133. package/src/db/migrations/index.ts +49 -0
  134. package/src/db/notifications.ts +185 -0
  135. package/src/db/org-lookup.ts +104 -0
  136. package/src/db/owner-pass.ts +252 -0
  137. package/src/db/rls-coverage.ts +259 -0
  138. package/src/db/rls-proof-runner.ts +94 -0
  139. package/src/db/rls-proofs.ts +1176 -0
  140. package/src/db/schedules.ts +187 -0
  141. package/src/db/schema.ts +235 -0
  142. package/src/db/seed.ts +176 -0
  143. package/src/db/service-keys.ts +50 -0
  144. package/src/db/tenant-lookup.ts +13 -0
  145. package/src/db/webhooks.ts +483 -0
  146. package/src/db/with-tenant.ts +26 -0
  147. package/src/demo-static/actor-drivers.ts +161 -0
  148. package/src/demo-static/assistant-replay.ts +61 -0
  149. package/src/demo-static/contracts.ts +282 -0
  150. package/src/demo-static/email-html.ts +58 -0
  151. package/src/demo-static/hash-route.ts +24 -0
  152. package/src/demo-static/rows.ts +105 -0
  153. package/src/demo-static/shell.tsx +440 -0
  154. package/src/demo-static/tour/contracts.ts +97 -0
  155. package/src/demo-static/tour/driver.ts +320 -0
  156. package/src/demo-static/tour/tour-overlay.tsx +226 -0
  157. package/src/demo-static/tour/use-tours.tsx +394 -0
  158. package/src/demo-static/world.ts +1479 -0
  159. package/src/email/send.ts +12 -0
  160. package/src/email/templates/digest-email.tsx +61 -0
  161. package/src/email/templates/invite-email.tsx +57 -0
  162. package/src/email/templates/notification-email.tsx +39 -0
  163. package/src/guide.md +118 -0
  164. package/src/i18n/messages/en.json +373 -0
  165. package/src/i18n/messages/es.json +373 -0
  166. package/src/i18n/messages.ts +34 -0
  167. package/src/i18n/namespaces.ts +32 -0
  168. package/src/i18n/request.ts +34 -0
  169. package/src/i18n/routing.ts +7 -0
  170. package/src/inbound-email/handlers.ts +67 -0
  171. package/src/inbound-email/intake.ts +180 -0
  172. package/src/jobs/digest-email.ts +97 -0
  173. package/src/observability/scrub.ts +42 -0
  174. package/src/ports/README.md +8 -0
  175. package/src/ports/analytics.ts +8 -0
  176. package/src/ports/auth.ts +87 -0
  177. package/src/ports/db.ts +27 -0
  178. package/src/ports/email.ts +14 -0
  179. package/src/ports/errors.ts +46 -0
  180. package/src/ports/jobs.ts +48 -0
  181. package/src/ports/llm.ts +85 -0
  182. package/src/ports/storage.ts +132 -0
  183. package/src/seed/contracts.ts +129 -0
  184. package/src/server-lib/assistant.ts +45 -0
  185. package/src/server-lib/defer.ts +53 -0
  186. package/src/server-lib/demo-presets.ts +85 -0
  187. package/src/server-lib/invite.ts +92 -0
  188. package/src/server-lib/notify-deps.ts +15 -0
  189. package/src/server-lib/notify.ts +252 -0
  190. package/src/server-lib/preset-operations.ts +121 -0
  191. package/src/server-lib/scheduled-tick.ts +38 -0
  192. package/src/server-lib/sms.ts +43 -0
  193. package/src/server-lib/webhook-dispatch.ts +75 -0
  194. package/src/service-auth/mailgun.ts +70 -0
  195. package/src/service-auth/verify.ts +73 -0
  196. package/src/service-auth/webhook.ts +60 -0
  197. package/src/testing/checks.json +103 -0
  198. package/src/testing/conformance/authz.ts +46 -0
  199. package/src/testing/conformance/db.ts +258 -0
  200. package/src/testing/conformance/demo-presets.ts +295 -0
  201. package/src/testing/conformance/i18n.ts +80 -0
  202. package/src/testing/conformance/register.ts +200 -0
  203. package/src/testing/conformance/seam-map.ts +205 -0
  204. package/src/testing/conformance/suite.ts +59 -0
  205. package/src/testing/conformance/types.ts +18 -0
  206. package/src/testing/contract.ts +200 -0
  207. package/src/testing/e2e.ts +15 -0
  208. package/src/testing/index.ts +6 -0
  209. package/src/testing/seam-specifiers.json +22 -0
  210. package/src/testing/tmp-dir-marker.d.mts +4 -0
  211. package/src/testing/tmp-dir-marker.mjs +5 -0
  212. package/src/testing/tmp-dir.ts +182 -0
  213. package/src/theme.ts +28 -0
  214. package/README.md +0 -3
@@ -0,0 +1,508 @@
1
+ import type { ArrayValue, ColumnMetadata, Field, SqlParameter } from '@aws-sdk/client-rds-data'
2
+
3
+ /**
4
+ * The pure half of the RDS Data API dialect (./rds-data-dialect.ts): SQL rewriting, value encoding,
5
+ * result decoding and error normalization. No I/O, so every rule here is unit-tested directly
6
+ * (./rds-data-codec.test.ts) and the contract suite proves the composition against real Postgres.
7
+ *
8
+ * The one idea everything here serves: SSSB's SQL is written for node-postgres, which sends each
9
+ * parameter as text with NO type and lets Postgres infer it from context (`id = $1` makes `$1` a uuid).
10
+ * The Data API cannot do that — an untyped string arrives as `varchar`, and `uuid = varchar` is an error
11
+ * on real Aurora. So the dialect asks Postgres what it would have inferred (PREPARE, then
12
+ * `pg_prepared_statements.parameter_types`), and sends every value as a string wrapped in an explicit
13
+ * `CAST(:name AS <that type>)`. That reproduces node-postgres's semantics instead of approximating them
14
+ * with per-value guesses, and it is also what lets an array reach the server at all: the Data API
15
+ * rejects array parameters, but an array literal cast to `uuid[]` is a string.
16
+ *
17
+ * The type in that CAST never carries a length, and a domain is replaced by the type it is built on.
18
+ * An explicit cast to `char(3)`, `bit(4)` or a domain over `varchar(3)` truncates or pads a value that
19
+ * does not fit, where node-postgres's untyped parameter is checked against the column on assignment and
20
+ * refused. Casting to the bare base type leaves that check to the same assignment, so a value that is too
21
+ * long fails the same way on both transports when it is stored in a column or passed to a function, and a
22
+ * domain's own CHECK still runs. An explicit cast to such a domain written in the SQL itself
23
+ * (`${value}::code3`) is the exception: the value meets an explicit cast and is truncated, where
24
+ * node-postgres refuses it. That limit is accepted (ADR-0002's addendum of 2026-11-16).
25
+ */
26
+
27
+ // ---------------------------------------------------------------------------------------------
28
+ // SQL scanning
29
+ // ---------------------------------------------------------------------------------------------
30
+
31
+ const IDENT_CHAR = /[A-Za-z0-9_$\u0080-￿]/
32
+
33
+ /** A stretch of SQL: real code, or something Postgres reads as one token whose inside is not code. */
34
+ export interface SqlSegment {
35
+ readonly text: string
36
+ /** False for a string literal, a quoted identifier, a comment or a dollar-quoted body. */
37
+ readonly code: boolean
38
+ }
39
+
40
+ /**
41
+ * Splits SQL into code and the stretches that can hide a `$1`, a `:name` or a `;`. Both the dialect and
42
+ * the test-only emulator read SQL through this one scanner, so they cannot disagree about where code is.
43
+ *
44
+ * Postgres's own lexical rules, the parts that matter here: `'…'` (with `''`), `E'…'` (with backslash
45
+ * escapes as well), `"…"` (with `""`), `--` to end of line, nested block comments, and `$tag$…$tag$`. A
46
+ * `$` directly after an identifier character is part of that identifier, not a placeholder or a dollar
47
+ * quote, and `$1` is code.
48
+ */
49
+ export function sqlSegments(sql: string): SqlSegment[] {
50
+ const segments: SqlSegment[] = []
51
+ let code = ''
52
+ let i = 0
53
+ const literal = (stop: number) => {
54
+ if (code) segments.push({ text: code, code: true })
55
+ code = ''
56
+ segments.push({ text: sql.slice(i, stop), code: false })
57
+ i = stop
58
+ }
59
+ while (i < sql.length) {
60
+ const ch = sql[i]!
61
+ const next = sql[i + 1]
62
+ const prev = i > 0 ? sql[i - 1]! : ''
63
+ if (ch === '-' && next === '-') {
64
+ const end = sql.indexOf('\n', i)
65
+ literal(end === -1 ? sql.length : end)
66
+ } else if (ch === '/' && next === '*') {
67
+ literal(blockCommentEnd(sql, i))
68
+ } else if (ch === "'") {
69
+ const escapes = (prev === 'E' || prev === 'e') && !IDENT_CHAR.test(i > 1 ? sql[i - 2]! : '')
70
+ literal(quotedEnd(sql, i, "'", escapes))
71
+ } else if (ch === '"') {
72
+ literal(quotedEnd(sql, i, '"', false))
73
+ } else if (ch === '$' && !IDENT_CHAR.test(prev) && !/^\$\d/.test(sql.slice(i, i + 2))) {
74
+ const tag = /^\$([A-Za-z_][A-Za-z0-9_]*)?\$/.exec(sql.slice(i))
75
+ if (tag) {
76
+ const close = sql.indexOf(tag[0], i + tag[0].length)
77
+ literal(close === -1 ? sql.length : close + tag[0].length)
78
+ } else {
79
+ code += ch
80
+ i += 1
81
+ }
82
+ } else {
83
+ code += ch
84
+ i += 1
85
+ }
86
+ }
87
+ if (code) segments.push({ text: code, code: true })
88
+ return segments
89
+ }
90
+
91
+ const PLACEHOLDER = new RegExp(`(?<!${IDENT_CHAR.source})\\$(\\d+)`, 'g')
92
+
93
+ /**
94
+ * Rewrites every `$n` placeholder that is real SQL — not inside a string literal, a quoted identifier,
95
+ * a comment or a dollar-quoted body (`sqlSegments`) — with `replace(n)`. Returns the SQL unchanged when
96
+ * it has none.
97
+ */
98
+ export function rewritePlaceholders(sql: string, replace: (index: number) => string): string {
99
+ return sqlSegments(sql)
100
+ .map((segment) =>
101
+ segment.code ? segment.text.replace(PLACEHOLDER, (_, n: string) => replace(Number(n))) : segment.text,
102
+ )
103
+ .join('')
104
+ }
105
+
106
+ /**
107
+ * Whether `sql` is more than one statement: a `;` in code with anything after it but whitespace, comments
108
+ * and further `;`. The Data API refuses multistatements, and a second statement is also where a COMMIT
109
+ * could hide from the guard below.
110
+ */
111
+ export function isMultistatement(sql: string): boolean {
112
+ let ended = false
113
+ for (const segment of sqlSegments(sql)) {
114
+ if (!segment.code) {
115
+ const comment = segment.text.startsWith('--') || segment.text.startsWith('/*')
116
+ if (ended && !comment) return true
117
+ continue
118
+ }
119
+ for (const ch of segment.text) {
120
+ if (ch === ';') ended = true
121
+ else if (ended && !/\s/.test(ch)) return true
122
+ }
123
+ }
124
+ return false
125
+ }
126
+
127
+ function quotedEnd(sql: string, start: number, quote: string, backslashEscapes: boolean): number {
128
+ let i = start + 1
129
+ while (i < sql.length) {
130
+ const ch = sql[i]!
131
+ if (backslashEscapes && ch === '\\') {
132
+ i += 2
133
+ } else if (ch === quote) {
134
+ if (sql[i + 1] === quote) i += 2
135
+ else return i + 1
136
+ } else {
137
+ i += 1
138
+ }
139
+ }
140
+ return sql.length
141
+ }
142
+
143
+ function blockCommentEnd(sql: string, start: number): number {
144
+ let depth = 0
145
+ let i = start
146
+ while (i < sql.length) {
147
+ if (sql[i] === '/' && sql[i + 1] === '*') {
148
+ depth += 1
149
+ i += 2
150
+ } else if (sql[i] === '*' && sql[i + 1] === '/') {
151
+ depth -= 1
152
+ i += 2
153
+ if (depth === 0) return i
154
+ } else {
155
+ i += 1
156
+ }
157
+ }
158
+ return sql.length
159
+ }
160
+
161
+ /** The index past any whitespace and comments (and opening parentheses and `;`, if asked) from `i` on. */
162
+ function skipBlank(sql: string, i: number, punctuation: boolean): number {
163
+ while (i < sql.length) {
164
+ const ch = sql[i]!
165
+ if (/\s/.test(ch) || (punctuation && (ch === '(' || ch === ';'))) {
166
+ i += 1
167
+ } else if (ch === '-' && sql[i + 1] === '-') {
168
+ const end = sql.indexOf('\n', i)
169
+ i = end === -1 ? sql.length : end + 1
170
+ } else if (ch === '/' && sql[i + 1] === '*') {
171
+ i = blockCommentEnd(sql, i)
172
+ } else {
173
+ break
174
+ }
175
+ }
176
+ return i
177
+ }
178
+
179
+ /**
180
+ * The statement's first keyword, lower-cased, past leading whitespace, comments, parentheses and `;` (an
181
+ * empty statement first: `;commit` is a COMMIT).
182
+ */
183
+ export function leadingKeyword(sql: string): string {
184
+ const i = skipBlank(sql, 0, true)
185
+ return (/^[A-Za-z_]+/.exec(sql.slice(i))?.[0] ?? '').toLowerCase()
186
+ }
187
+
188
+ /** The Data API names parameters; these are the names the rewritten SQL refers to. */
189
+ const parameterName = (index: number): string => `kp${index}`
190
+
191
+ /**
192
+ * `(CAST(:kpN AS <type>))` — or `(:kpN)` when the describe step gave no usable type (none, or `unknown`).
193
+ * Parenthesized, because a
194
+ * placeholder can follow a colon (`arr[1:$1]`), and `1:CAST(` would make the Data API read a parameter
195
+ * named `CAST`.
196
+ */
197
+ export function castPlaceholder(index: number, type: string | undefined): string {
198
+ const name = `:${parameterName(index)}`
199
+ return type && type !== 'unknown' ? `(CAST(${name} AS ${type}))` : `(${name})`
200
+ }
201
+
202
+ /**
203
+ * The statement to PREPARE when asking Postgres for `sql`'s parameter types. PREPARE refuses EXPLAIN, but
204
+ * an EXPLAIN's parameters are its statement's, numbered the same, so the prefix (and its options) is
205
+ * dropped for the question and kept for the statement itself.
206
+ */
207
+ export function describableSql(sql: string): string {
208
+ let i = skipBlank(sql, 0, false)
209
+ const explain = /^explain\b/i.exec(sql.slice(i))
210
+ if (!explain) return sql
211
+ i += explain[0].length
212
+ for (;;) {
213
+ i = skipBlank(sql, i, false)
214
+ const rest = sql.slice(i)
215
+ const legacy = /^(?:analy[sz]e|verbose)\b/i.exec(rest)
216
+ if (legacy) {
217
+ i += legacy[0].length
218
+ continue
219
+ }
220
+ // `(` opens an option list unless it opens the statement itself: `explain (select …)`. An option
221
+ // list holds no parentheses of its own.
222
+ if (rest.startsWith('(') && !/^\(\s*(?:select|with|values|table|\()/i.test(rest)) {
223
+ const close = sql.indexOf(')', i)
224
+ if (close === -1) return sql
225
+ i = close + 1
226
+ continue
227
+ }
228
+ return sql.slice(i)
229
+ }
230
+ }
231
+
232
+ // ---------------------------------------------------------------------------------------------
233
+ // What the Data API cannot do
234
+ // ---------------------------------------------------------------------------------------------
235
+
236
+ /** Statements that open, end or abandon a transaction by SQL instead of through the Data API's calls. */
237
+ const TRANSACTION_CONTROL = new Set(['begin', 'start', 'commit', 'end', 'abort', 'rollback'])
238
+
239
+ /** Statements whose only effect is session state, which AWS resets (`DISCARD ALL`) between calls. */
240
+ const SESSION_STATE = new Set(['set', 'reset', 'prepare', 'deallocate', 'discard', 'listen', 'unlisten', 'load'])
241
+
242
+ /**
243
+ * Why `sql` cannot run as written through the Data API, or `null` if it can. Checked before every call,
244
+ * so the failure names the cause instead of the statement silently doing nothing:
245
+ *
246
+ * - transaction control in SQL (`BEGIN`, `COMMIT`, …) bypasses BeginTransaction/CommitTransaction, and
247
+ * outside a transaction would be committed by the call that sent it. `ROLLBACK TO` (a savepoint) is
248
+ * fine inside a transaction.
249
+ * - outside a transaction, a statement that only changes session state (`SET`, `SET ROLE`, `PREPARE`,
250
+ * a temporary table, `set_config(…, false)`, a session-level advisory lock) is lost before the next
251
+ * call, because the Data API resets the connection with `DISCARD ALL` whenever it reuses it. `SET LOCAL`
252
+ * would be a no-op.
253
+ *
254
+ * A heuristic over the leading keyword, not a parser: it exists to fail loudly on the mistakes someone
255
+ * would actually make, and it does not claim to catch an alias.
256
+ */
257
+ export function unsupportedStatement(sql: string, inTransaction: boolean): string | null {
258
+ if (isMultistatement(sql)) {
259
+ return 'more than one statement in one call — the Data API refuses multistatements; send each statement on its own'
260
+ }
261
+ const keyword = leadingKeyword(sql)
262
+ if (TRANSACTION_CONTROL.has(keyword)) {
263
+ const savepoint = keyword === 'rollback' && /^\s*rollback\s+to\b/i.test(sql.replace(/^[\s(]+/, ''))
264
+ if (!(inTransaction && savepoint)) {
265
+ return `\`${keyword.toUpperCase()}\` in SQL bypasses the Data API's transactions — use db.transaction() or withTenant()`
266
+ }
267
+ }
268
+ if (!inTransaction) {
269
+ if (SESSION_STATE.has(keyword)) {
270
+ return `\`${keyword.toUpperCase()}\` outside a transaction is lost before the next Data API call (the connection is reset with DISCARD ALL) — run it inside db.transaction() or withTenant()`
271
+ }
272
+ if (keyword === 'create' && /^\s*create\s+(?:global\s+|local\s+)?temp(?:orary)?\b/i.test(sql)) {
273
+ return 'a temporary table outside a transaction is dropped before the next Data API call — create and use it inside one transaction'
274
+ }
275
+ if (/set_config\s*\([^)]*,\s*false\s*\)/i.test(sql)) {
276
+ return '`set_config(…, false)` outside a transaction is lost before the next Data API call — use set_config(…, true) inside a transaction'
277
+ }
278
+ if (/pg_(?:try_)?advisory_lock(?:_shared)?\s*\(/i.test(sql)) {
279
+ return 'a session-level advisory lock outside a transaction is released by the connection reset before the next Data API call — take pg_advisory_xact_lock inside a transaction'
280
+ }
281
+ }
282
+ return null
283
+ }
284
+
285
+ // ---------------------------------------------------------------------------------------------
286
+ // Values in
287
+ // ---------------------------------------------------------------------------------------------
288
+
289
+ /**
290
+ * One parameter, as a string the server parses with the type's own input function (the explicit CAST
291
+ * in the SQL), or as a NULL. Follows what node-postgres sends for the same JS value, so a value means
292
+ * the same thing on both transports: a plain object is JSON, an array is a Postgres array literal, a byte
293
+ * array is `\x` hex. A `Date` is the same instant, written in UTC where node-postgres writes local time
294
+ * with an offset. That is identical for a `timestamptz` (SSSB's only instant type; its dates travel as
295
+ * strings); a `date` or `timestamp` target would differ in a process not running in UTC, which Lambda is.
296
+ */
297
+ export function toSqlParameter(index: number, value: unknown): SqlParameter {
298
+ const name = parameterName(index)
299
+ if (value === null || value === undefined) return { name, value: { isNull: true } }
300
+ return { name, value: { stringValue: serializeValue(value) } }
301
+ }
302
+
303
+ function serializeValue(value: unknown): string {
304
+ if (Array.isArray(value)) return arrayLiteral(value)
305
+ return serializeScalar(value)
306
+ }
307
+
308
+ function serializeScalar(value: unknown): string {
309
+ if (typeof value === 'string') return value
310
+ if (typeof value === 'number' || typeof value === 'bigint') return String(value)
311
+ if (typeof value === 'boolean') return value ? 'true' : 'false'
312
+ if (value instanceof Date) {
313
+ if (Number.isNaN(value.getTime())) throw new TypeError('cannot send an invalid Date to the database')
314
+ return value.toISOString()
315
+ }
316
+ if (value instanceof Uint8Array) return `\\x${Buffer.from(value).toString('hex')}`
317
+ return JSON.stringify(value)
318
+ }
319
+
320
+ function arrayLiteral(values: readonly unknown[]): string {
321
+ const items = values.map((item) => {
322
+ if (item === null || item === undefined) return 'NULL'
323
+ if (Array.isArray(item)) return arrayLiteral(item)
324
+ return `"${serializeScalar(item).replace(/\\/g, '\\\\').replace(/"/g, '\\"')}"`
325
+ })
326
+ return `{${items.join(',')}}`
327
+ }
328
+
329
+ // ---------------------------------------------------------------------------------------------
330
+ // Values out
331
+ // ---------------------------------------------------------------------------------------------
332
+
333
+ /**
334
+ * One result row, keyed by column label, each value decoded to what node-postgres returns through SSSB's
335
+ * pg adapter (../real/db.ts): `int8`/`numeric` as strings (but `numeric[]` elements as numbers, as
336
+ * node-postgres has it), `json`/`jsonb` parsed, `timestamptz` as a `Date` (`±Infinity` for infinity),
337
+ * `date` as the wire string, `bytea` as a Buffer, arrays element by element. Types SSSB's migrations do
338
+ * not use and node-postgres parses into objects (`interval`) come back as the Data API's string.
339
+ */
340
+ export function decodeRow(record: readonly Field[], columns: readonly ColumnMetadata[]): Record<string, unknown> {
341
+ const row: Record<string, unknown> = {}
342
+ columns.forEach((column, i) => {
343
+ row[column.label || column.name || `?column?`] = decodeField(record[i], column.typeName ?? '')
344
+ })
345
+ return row
346
+ }
347
+
348
+ export function decodeField(field: Field | undefined, typeName: string): unknown {
349
+ if (!field || field.isNull) return null
350
+ const type = typeName.toLowerCase().replace(/^"|"$/g, '')
351
+ if (field.arrayValue !== undefined) return decodeArray(field.arrayValue, type.replace(/^_/, ''))
352
+ const raw = field.stringValue ?? field.longValue ?? field.doubleValue ?? field.booleanValue ?? field.blobValue
353
+ return decodeScalar(raw, type)
354
+ }
355
+
356
+ function decodeArray(value: ArrayValue, baseType: string): unknown[] {
357
+ if (value.arrayValues) return value.arrayValues.map((inner) => (inner ? decodeArray(inner, baseType) : null))
358
+ const items: readonly unknown[] =
359
+ value.stringValues ?? value.longValues ?? value.doubleValues ?? value.booleanValues ?? []
360
+ // node-postgres parses `numeric[]` elements as floats while a bare `numeric` stays a string.
361
+ const elementType = baseType === 'numeric' ? 'float8' : baseType
362
+ return items.map((item) => (item === null || item === undefined ? null : decodeScalar(item, elementType)))
363
+ }
364
+
365
+ function decodeScalar(raw: unknown, type: string): unknown {
366
+ if (raw === undefined || raw === null) return null
367
+ switch (type) {
368
+ // PgJDBC names an auto-increment column `serial`/`bigserial`, not its storage type.
369
+ case 'int2':
370
+ case 'int4':
371
+ case 'oid':
372
+ case 'serial':
373
+ case 'smallserial':
374
+ case 'float4':
375
+ case 'float8':
376
+ return Number(raw)
377
+ case 'int8':
378
+ case 'bigserial':
379
+ case 'numeric':
380
+ case 'money':
381
+ return String(raw)
382
+ case 'bool':
383
+ return typeof raw === 'boolean' ? raw : raw === 't' || raw === 'true'
384
+ case 'json':
385
+ case 'jsonb':
386
+ return JSON.parse(String(raw))
387
+ case 'timestamptz':
388
+ return parseTimestamp(String(raw), true)
389
+ case 'timestamp':
390
+ return parseTimestamp(String(raw), false)
391
+ case 'bytea':
392
+ return raw instanceof Uint8Array ? Buffer.from(raw) : Buffer.from(String(raw).replace(/^\\x/, ''), 'hex')
393
+ default:
394
+ return raw
395
+ }
396
+ }
397
+
398
+ const TIMESTAMP = /^(\d{4,})-(\d\d)-(\d\d)[ T](\d\d):(\d\d):(\d\d)(?:\.(\d+))?(Z|[+-]\d\d(?::?\d\d)?)?( BC)?$/
399
+
400
+ /**
401
+ * The Data API returns `timestamptz` as a UTC wall-clock string (`2026-11-16 23:00:00.123456`), and
402
+ * node-postgres returns a `Date`; this makes the first into the second, as node-postgres would: `±Infinity`
403
+ * for `±infinity`, a negative year for `BC`, years below 100 as themselves (not 19xx). A `timestamp`
404
+ * without a zone is read as local time, as node-postgres does. Sub-millisecond digits are truncated, as a
405
+ * `Date` holds no more. Anything unparseable comes back as the string.
406
+ */
407
+ function parseTimestamp(value: string, utc: boolean): Date | number | string {
408
+ if (value === 'infinity') return Infinity
409
+ if (value === '-infinity') return -Infinity
410
+ const m = TIMESTAMP.exec(value)
411
+ if (!m) return value
412
+ const [, y, mo, d, h, mi, s, frac, zone, bc] = m
413
+ const year = bc ? 1 - Number(y) : Number(y)
414
+ const ms = Number((frac ?? '').padEnd(3, '0').slice(0, 3))
415
+ const date = new Date(0)
416
+ if (utc || zone) {
417
+ // setUTCFullYear, not Date.UTC: Date.UTC reads a year below 100 as 19xx.
418
+ date.setUTCFullYear(year, Number(mo) - 1, Number(d))
419
+ date.setUTCHours(Number(h), Number(mi), Number(s), ms)
420
+ if (zone && zone !== 'Z') {
421
+ const sign = zone.startsWith('-') ? -1 : 1
422
+ const [zh, zm] = zone
423
+ .slice(1)
424
+ .replace(':', '')
425
+ .match(/^(\d\d)(\d\d)?$/)!
426
+ .slice(1)
427
+ date.setTime(date.getTime() - sign * (Number(zh) * 60 + Number(zm ?? 0)) * 60_000)
428
+ }
429
+ return date
430
+ }
431
+ date.setFullYear(year, Number(mo) - 1, Number(d))
432
+ date.setHours(Number(h), Number(mi), Number(s), ms)
433
+ return date
434
+ }
435
+
436
+ // ---------------------------------------------------------------------------------------------
437
+ // Errors
438
+ // ---------------------------------------------------------------------------------------------
439
+
440
+ /**
441
+ * A database error from the Data API, carrying what SSSB's code reads from a node-postgres error:
442
+ * `code` (the SQLSTATE) and, where Postgres names one, `constraint`. The Data API returns only a
443
+ * message, sometimes ending `; SQLState: 23505` and sometimes not, so the SQLSTATE is taken from the
444
+ * message when present and otherwise derived from Postgres's own wording for the errors code acts on.
445
+ * The original error is the `cause`.
446
+ */
447
+ export class RdsDataDatabaseError extends Error {
448
+ readonly code: string | undefined
449
+ readonly constraint: string | undefined
450
+
451
+ constructor(message: string, code: string | undefined, constraint: string | undefined, cause: unknown) {
452
+ super(message, { cause })
453
+ this.name = 'RdsDataDatabaseError'
454
+ this.code = code
455
+ this.constraint = constraint
456
+ }
457
+ }
458
+
459
+ /**
460
+ * What CommitTransaction's `transactionStatus` says happened. The API reference lists no values; AWS's
461
+ * own CLI example answers a commit with "Transaction Committed", and step 1 of docs/runbooks/data-api.md
462
+ * records what a live cluster sends. Anything else is not taken for a commit.
463
+ */
464
+ export function commitOutcome(status: string | undefined): 'committed' | 'rolled back' | 'unknown' {
465
+ const said = status?.trim().toLowerCase()
466
+ if (said === 'transaction committed') return 'committed'
467
+ if (said !== undefined && /\brollback\b|\brolled back\b/.test(said)) return 'rolled back'
468
+ return 'unknown'
469
+ }
470
+
471
+ /** Raised before a call is made, for something the Data API cannot do (see unsupportedStatement). */
472
+ export class RdsDataUnsupportedError extends Error {
473
+ constructor(message: string) {
474
+ super(`RDS Data API: ${message}`)
475
+ this.name = 'RdsDataUnsupportedError'
476
+ }
477
+ }
478
+
479
+ const MESSAGE_CODES: readonly [RegExp, string][] = [
480
+ [/duplicate key value violates unique constraint "([^"]+)"/, '23505'],
481
+ [/violates foreign key constraint "([^"]+)"/, '23503'],
482
+ [/violates check constraint "([^"]+)"/, '23514'],
483
+ [/violates exclusion constraint "([^"]+)"/, '23P01'],
484
+ [/violates not-null constraint/, '23502'],
485
+ [/new row violates row-level security policy/, '42501'],
486
+ [/permission denied for/, '42501'],
487
+ [/could not serialize access/, '40001'],
488
+ [/deadlock detected/, '40P01'],
489
+ [/relation "[^"]+" does not exist/, '42P01'],
490
+ ]
491
+
492
+ const DATABASE_ERROR_NAMES = new Set(['DatabaseErrorException', 'BadRequestException'])
493
+
494
+ export function normalizeDatabaseError(error: unknown): unknown {
495
+ if (!(error instanceof Error) || !DATABASE_ERROR_NAMES.has(error.name)) return error
496
+ const message = error.message
497
+ const stated = /SQLState:\s*([0-9A-Z]{5})/.exec(message)?.[1]
498
+ let code = stated
499
+ let constraint: string | undefined
500
+ for (const [pattern, patternCode] of MESSAGE_CODES) {
501
+ const match = pattern.exec(message)
502
+ if (!match) continue
503
+ code ??= patternCode
504
+ constraint = match[1]
505
+ break
506
+ }
507
+ return new RdsDataDatabaseError(message, code, constraint, error)
508
+ }