@blamejs/core 0.15.12 → 0.15.14

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 (365) hide show
  1. package/CHANGELOG.md +4 -0
  2. package/index.js +2 -0
  3. package/lib/a2a-tasks.js +45 -29
  4. package/lib/acme.js +6 -5
  5. package/lib/agent-event-bus.js +18 -4
  6. package/lib/agent-idempotency.js +7 -6
  7. package/lib/agent-orchestrator.js +2 -5
  8. package/lib/agent-saga.js +3 -5
  9. package/lib/agent-snapshot.js +32 -2
  10. package/lib/agent-tenant.js +2 -5
  11. package/lib/ai-adverse-decision.js +2 -15
  12. package/lib/ai-aedt-bias-audit.js +2 -1
  13. package/lib/ai-capability.js +1 -6
  14. package/lib/ai-content-detect.js +1 -3
  15. package/lib/ai-dp.js +1 -5
  16. package/lib/ai-frontier-protocol.js +1 -1
  17. package/lib/ai-input.js +2 -2
  18. package/lib/ai-model-manifest.js +1 -1
  19. package/lib/ai-output.js +16 -7
  20. package/lib/ai-pref.js +3 -8
  21. package/lib/ai-quota.js +3 -14
  22. package/lib/api-key.js +37 -28
  23. package/lib/api-snapshot.js +4 -1
  24. package/lib/app-shutdown.js +7 -1
  25. package/lib/archive-adapters.js +2 -4
  26. package/lib/archive-entry-policy.js +32 -0
  27. package/lib/archive-gz.js +9 -0
  28. package/lib/archive-read.js +14 -24
  29. package/lib/archive-tar-read.js +56 -24
  30. package/lib/archive.js +6 -12
  31. package/lib/arg-parser.js +7 -6
  32. package/lib/asn1-der.js +70 -22
  33. package/lib/asyncapi-traits.js +2 -6
  34. package/lib/atomic-file.js +312 -33
  35. package/lib/audit-chain.js +183 -54
  36. package/lib/audit-daily-review.js +36 -16
  37. package/lib/audit-emit.js +82 -0
  38. package/lib/audit-sign.js +258 -0
  39. package/lib/audit-tools.js +108 -23
  40. package/lib/audit.js +91 -2
  41. package/lib/auth/access-lock.js +7 -29
  42. package/lib/auth/bot-challenge.js +1 -1
  43. package/lib/auth/ciba.js +43 -4
  44. package/lib/auth/dpop.js +29 -36
  45. package/lib/auth/fido-mds3.js +14 -16
  46. package/lib/auth/jwt-external.js +26 -8
  47. package/lib/auth/jwt.js +15 -17
  48. package/lib/auth/lockout.js +24 -27
  49. package/lib/auth/oauth.js +67 -45
  50. package/lib/auth/oid4vci.js +55 -32
  51. package/lib/auth/oid4vp.js +3 -2
  52. package/lib/auth/openid-federation.js +6 -6
  53. package/lib/auth/passkey.js +4 -4
  54. package/lib/auth/password.js +8 -2
  55. package/lib/auth/saml.js +70 -40
  56. package/lib/auth/sd-jwt-vc-holder.js +2 -14
  57. package/lib/auth/sd-jwt-vc-issuer.js +2 -14
  58. package/lib/auth/sd-jwt-vc.js +25 -5
  59. package/lib/auth/status-list.js +21 -9
  60. package/lib/auth/step-up.js +15 -13
  61. package/lib/auth-bot-challenge.js +27 -39
  62. package/lib/backup/bundle.js +18 -20
  63. package/lib/backup/crypto.js +23 -8
  64. package/lib/backup/index.js +55 -67
  65. package/lib/backup/manifest.js +7 -1
  66. package/lib/bounded-map.js +112 -1
  67. package/lib/breach-deadline.js +1 -11
  68. package/lib/break-glass.js +41 -22
  69. package/lib/cache.js +7 -18
  70. package/lib/cbor.js +36 -12
  71. package/lib/cdn-cache-control.js +15 -12
  72. package/lib/cert.js +8 -13
  73. package/lib/chain-writer.js +162 -47
  74. package/lib/cli.js +10 -2
  75. package/lib/client-hints.js +7 -9
  76. package/lib/cloud-events.js +43 -33
  77. package/lib/cluster-storage.js +9 -41
  78. package/lib/cms-codec.js +2 -1
  79. package/lib/codepoint-class.js +84 -1
  80. package/lib/compliance-ai-act-logging.js +1 -6
  81. package/lib/compliance-ai-act-transparency.js +2 -4
  82. package/lib/compliance-eaa.js +2 -12
  83. package/lib/compliance-sanctions-fetcher.js +21 -28
  84. package/lib/compliance-sanctions.js +11 -21
  85. package/lib/compliance.js +3 -10
  86. package/lib/config-drift.js +24 -20
  87. package/lib/content-credentials.js +11 -8
  88. package/lib/content-digest.js +21 -12
  89. package/lib/cookies.js +15 -13
  90. package/lib/cose.js +39 -11
  91. package/lib/cra-report.js +1 -11
  92. package/lib/crdt.js +2 -1
  93. package/lib/crypto-field.js +34 -33
  94. package/lib/crypto.js +138 -7
  95. package/lib/csp.js +239 -3
  96. package/lib/daemon.js +46 -42
  97. package/lib/data-act.js +46 -13
  98. package/lib/db-file-lifecycle.js +14 -6
  99. package/lib/db-query.js +75 -49
  100. package/lib/db.js +66 -27
  101. package/lib/dbsc.js +5 -6
  102. package/lib/ddl-change-control.js +18 -14
  103. package/lib/deprecate.js +4 -5
  104. package/lib/did.js +6 -2
  105. package/lib/dora.js +43 -13
  106. package/lib/dr-runbook.js +1 -1
  107. package/lib/dsa.js +2 -1
  108. package/lib/dsr.js +30 -20
  109. package/lib/early-hints.js +19 -0
  110. package/lib/eat.js +5 -1
  111. package/lib/external-db-migrate.js +21 -22
  112. package/lib/external-db.js +74 -30
  113. package/lib/fda-21cfr11.js +42 -13
  114. package/lib/fdx.js +22 -18
  115. package/lib/file-upload.js +80 -66
  116. package/lib/flag-evaluation-context.js +5 -8
  117. package/lib/flag-providers.js +6 -2
  118. package/lib/forms.js +1 -1
  119. package/lib/framework-error.js +12 -0
  120. package/lib/framework-schema.js +19 -0
  121. package/lib/fsm.js +7 -12
  122. package/lib/gate-contract.js +911 -39
  123. package/lib/gdpr-ropa.js +22 -22
  124. package/lib/graphql-federation.js +18 -5
  125. package/lib/guard-agent-registry.js +2 -1
  126. package/lib/guard-all.js +3 -2
  127. package/lib/guard-archive.js +9 -30
  128. package/lib/guard-auth.js +23 -80
  129. package/lib/guard-cidr.js +20 -96
  130. package/lib/guard-csv.js +135 -196
  131. package/lib/guard-domain.js +23 -106
  132. package/lib/guard-dsn.js +17 -14
  133. package/lib/guard-email.js +46 -53
  134. package/lib/guard-envelope.js +2 -2
  135. package/lib/guard-event-bus-topic.js +2 -1
  136. package/lib/guard-filename.js +12 -60
  137. package/lib/guard-graphql.js +28 -75
  138. package/lib/guard-html-wcag.js +15 -2
  139. package/lib/guard-html.js +74 -128
  140. package/lib/guard-idempotency-key.js +2 -1
  141. package/lib/guard-image.js +280 -77
  142. package/lib/guard-imap-command.js +9 -10
  143. package/lib/guard-jmap.js +1 -1
  144. package/lib/guard-json.js +101 -109
  145. package/lib/guard-jsonpath.js +20 -88
  146. package/lib/guard-jwt.js +32 -114
  147. package/lib/guard-list-id.js +2 -7
  148. package/lib/guard-list-unsubscribe.js +2 -7
  149. package/lib/guard-mail-compose.js +5 -6
  150. package/lib/guard-mail-move.js +3 -2
  151. package/lib/guard-mail-query.js +5 -3
  152. package/lib/guard-mail-sieve.js +6 -7
  153. package/lib/guard-managesieve-command.js +6 -5
  154. package/lib/guard-markdown.js +76 -110
  155. package/lib/guard-message-id.js +5 -6
  156. package/lib/guard-mime.js +20 -99
  157. package/lib/guard-oauth.js +19 -73
  158. package/lib/guard-pdf.js +65 -72
  159. package/lib/guard-pop3-command.js +13 -14
  160. package/lib/guard-posture-chain.js +2 -1
  161. package/lib/guard-regex.js +24 -99
  162. package/lib/guard-saga-config.js +2 -1
  163. package/lib/guard-shell.js +22 -87
  164. package/lib/guard-smtp-command.js +9 -12
  165. package/lib/guard-sql.js +15 -13
  166. package/lib/guard-stream-args.js +2 -1
  167. package/lib/guard-svg.js +103 -149
  168. package/lib/guard-template.js +23 -80
  169. package/lib/guard-tenant-id.js +2 -1
  170. package/lib/guard-text.js +592 -0
  171. package/lib/guard-time.js +27 -95
  172. package/lib/guard-uuid.js +21 -93
  173. package/lib/guard-xml.js +76 -106
  174. package/lib/guard-yaml.js +24 -60
  175. package/lib/html-balance.js +7 -3
  176. package/lib/http-client-cache.js +5 -12
  177. package/lib/http-client-cookie-jar.js +35 -16
  178. package/lib/http-client.js +233 -74
  179. package/lib/http-message-signature.js +3 -2
  180. package/lib/i18n-messageformat.js +5 -7
  181. package/lib/i18n.js +83 -26
  182. package/lib/iab-tcf.js +3 -2
  183. package/lib/importmap-integrity.js +41 -1
  184. package/lib/inbox.js +8 -8
  185. package/lib/incident-report.js +12 -27
  186. package/lib/ip-utils.js +49 -6
  187. package/lib/jobs.js +3 -2
  188. package/lib/json-patch.js +1 -1
  189. package/lib/json-path.js +24 -3
  190. package/lib/jtd.js +2 -2
  191. package/lib/keychain.js +6 -18
  192. package/lib/legal-hold.js +30 -23
  193. package/lib/log-stream-cloudwatch.js +44 -112
  194. package/lib/log-stream-otlp-grpc.js +17 -14
  195. package/lib/log-stream-otlp.js +16 -80
  196. package/lib/log-stream-webhook.js +20 -92
  197. package/lib/log.js +2 -2
  198. package/lib/mail-agent.js +2 -2
  199. package/lib/mail-arc-sign.js +8 -3
  200. package/lib/mail-arf.js +4 -3
  201. package/lib/mail-auth.js +43 -69
  202. package/lib/mail-bimi.js +35 -55
  203. package/lib/mail-bounce.js +3 -3
  204. package/lib/mail-crypto-pgp.js +3 -2
  205. package/lib/mail-crypto-smime.js +71 -6
  206. package/lib/mail-dav.js +8 -35
  207. package/lib/mail-deploy.js +15 -14
  208. package/lib/mail-dkim.js +19 -38
  209. package/lib/mail-greylist.js +17 -30
  210. package/lib/mail-helo.js +4 -7
  211. package/lib/mail-journal.js +13 -9
  212. package/lib/mail-mdn.js +12 -7
  213. package/lib/mail-rbl.js +7 -12
  214. package/lib/mail-scan.js +5 -7
  215. package/lib/mail-send-deliver.js +33 -20
  216. package/lib/mail-server-imap.js +32 -87
  217. package/lib/mail-server-jmap.js +39 -52
  218. package/lib/mail-server-managesieve.js +29 -83
  219. package/lib/mail-server-mx.js +33 -74
  220. package/lib/mail-server-net.js +177 -0
  221. package/lib/mail-server-pop3.js +30 -83
  222. package/lib/mail-server-rate-limit.js +30 -6
  223. package/lib/mail-server-registry.js +1 -1
  224. package/lib/mail-server-submission.js +34 -73
  225. package/lib/mail-server-tls.js +98 -2
  226. package/lib/mail-spam-score.js +9 -12
  227. package/lib/mail-store-fts.js +1 -1
  228. package/lib/mail-store.js +3 -2
  229. package/lib/mail.js +28 -13
  230. package/lib/markup-escape.js +31 -0
  231. package/lib/markup-tokenizer.js +78 -0
  232. package/lib/mcp-tool-registry.js +26 -23
  233. package/lib/mcp.js +7 -5
  234. package/lib/mdoc.js +36 -14
  235. package/lib/metrics.js +46 -33
  236. package/lib/middleware/age-gate.js +3 -23
  237. package/lib/middleware/api-encrypt.js +13 -24
  238. package/lib/middleware/assetlinks.js +2 -7
  239. package/lib/middleware/bearer-auth.js +2 -1
  240. package/lib/middleware/body-parser.js +41 -52
  241. package/lib/middleware/bot-disclose.js +7 -10
  242. package/lib/middleware/bot-guard.js +28 -28
  243. package/lib/middleware/clear-site-data.js +5 -1
  244. package/lib/middleware/compression.js +9 -0
  245. package/lib/middleware/cors.js +32 -23
  246. package/lib/middleware/csrf-protect.js +73 -23
  247. package/lib/middleware/daily-byte-quota.js +12 -30
  248. package/lib/middleware/deny-response.js +19 -1
  249. package/lib/middleware/fetch-metadata.js +35 -4
  250. package/lib/middleware/idempotency-key.js +4 -20
  251. package/lib/middleware/network-allowlist.js +61 -30
  252. package/lib/middleware/rate-limit.js +45 -44
  253. package/lib/middleware/scim-server.js +5 -3
  254. package/lib/middleware/security-headers.js +33 -7
  255. package/lib/middleware/security-txt.js +2 -6
  256. package/lib/middleware/speculation-rules.js +6 -3
  257. package/lib/middleware/tus-upload.js +14 -29
  258. package/lib/middleware/web-app-manifest.js +2 -7
  259. package/lib/migrations.js +4 -13
  260. package/lib/mime-parse.js +34 -17
  261. package/lib/module-loader.js +44 -0
  262. package/lib/money.js +105 -0
  263. package/lib/mtls-ca.js +125 -41
  264. package/lib/network-byte-quota.js +4 -18
  265. package/lib/network-dane.js +8 -6
  266. package/lib/network-dns-resolver.js +98 -7
  267. package/lib/network-dns.js +9 -2
  268. package/lib/network-dnssec.js +18 -17
  269. package/lib/network-heartbeat.js +3 -2
  270. package/lib/network-smtp-policy.js +52 -46
  271. package/lib/network-tls.js +67 -47
  272. package/lib/network-tsig.js +2 -2
  273. package/lib/nis2-report.js +2 -12
  274. package/lib/nist-crosswalk.js +1 -1
  275. package/lib/nonce-store.js +81 -3
  276. package/lib/ntp-check.js +28 -0
  277. package/lib/numeric-bounds.js +31 -8
  278. package/lib/object-store/azure-blob-bucket-ops.js +2 -6
  279. package/lib/object-store/azure-blob.js +6 -47
  280. package/lib/object-store/gcs-bucket-ops.js +4 -2
  281. package/lib/object-store/gcs.js +14 -75
  282. package/lib/object-store/http-put.js +2 -7
  283. package/lib/object-store/http-request.js +157 -0
  284. package/lib/object-store/local.js +37 -17
  285. package/lib/object-store/sigv4-bucket-ops.js +2 -1
  286. package/lib/object-store/sigv4.js +10 -79
  287. package/lib/observability-otlp-exporter.js +29 -29
  288. package/lib/observability.js +95 -0
  289. package/lib/openapi-paths-builder.js +7 -3
  290. package/lib/otel-export.js +7 -10
  291. package/lib/outbox.js +54 -41
  292. package/lib/pagination.js +11 -15
  293. package/lib/parsers/safe-env.js +5 -4
  294. package/lib/parsers/safe-ini.js +10 -4
  295. package/lib/parsers/safe-toml.js +11 -9
  296. package/lib/parsers/safe-xml.js +3 -3
  297. package/lib/parsers/safe-yaml.js +28 -9
  298. package/lib/pick.js +63 -5
  299. package/lib/pipl-cn.js +69 -59
  300. package/lib/privacy-pass.js +8 -6
  301. package/lib/problem-details.js +2 -5
  302. package/lib/pubsub.js +4 -8
  303. package/lib/queue-local.js +10 -3
  304. package/lib/redact.js +9 -4
  305. package/lib/render.js +4 -2
  306. package/lib/request-helpers.js +334 -29
  307. package/lib/resource-access-lock.js +3 -3
  308. package/lib/restore-bundle.js +46 -18
  309. package/lib/restore-rollback.js +10 -4
  310. package/lib/restore.js +24 -22
  311. package/lib/retention.js +23 -9
  312. package/lib/router.js +17 -4
  313. package/lib/safe-async.js +457 -0
  314. package/lib/safe-buffer.js +137 -6
  315. package/lib/safe-decompress.js +2 -1
  316. package/lib/safe-dns.js +2 -1
  317. package/lib/safe-ical.js +14 -28
  318. package/lib/safe-icap.js +1 -1
  319. package/lib/safe-json.js +51 -8
  320. package/lib/safe-jsonpath.js +6 -5
  321. package/lib/safe-mime.js +25 -29
  322. package/lib/safe-redirect.js +2 -5
  323. package/lib/safe-schema.js +7 -6
  324. package/lib/safe-sieve.js +1 -1
  325. package/lib/safe-sql.js +126 -0
  326. package/lib/safe-vcard.js +13 -27
  327. package/lib/sandbox-worker.js +15 -2
  328. package/lib/sandbox.js +4 -3
  329. package/lib/scheduler.js +22 -13
  330. package/lib/sec-cyber.js +82 -37
  331. package/lib/seeders.js +4 -11
  332. package/lib/self-update-standalone-verifier.js +16 -0
  333. package/lib/self-update.js +92 -69
  334. package/lib/session-device-binding.js +112 -66
  335. package/lib/session.js +219 -7
  336. package/lib/sql.js +228 -81
  337. package/lib/sse.js +6 -10
  338. package/lib/static.js +201 -111
  339. package/lib/storage.js +4 -2
  340. package/lib/structured-fields.js +275 -16
  341. package/lib/template.js +7 -5
  342. package/lib/tenant-quota.js +53 -38
  343. package/lib/tsa.js +16 -17
  344. package/lib/validate-opts.js +154 -8
  345. package/lib/vault/index.js +5 -0
  346. package/lib/vault/passphrase-ops.js +22 -26
  347. package/lib/vault/passphrase-source.js +8 -3
  348. package/lib/vault/rotate.js +13 -18
  349. package/lib/vault/seal-pem-file.js +34 -49
  350. package/lib/vault-aad.js +3 -2
  351. package/lib/vc.js +3 -8
  352. package/lib/vendor/MANIFEST.json +10 -10
  353. package/lib/vendor/public-suffix-list.dat +23 -10
  354. package/lib/vendor/public-suffix-list.data.js +5498 -5494
  355. package/lib/vex.js +35 -13
  356. package/lib/web-push-vapid.js +23 -20
  357. package/lib/webhook-dispatcher.js +706 -0
  358. package/lib/webhook.js +59 -19
  359. package/lib/websocket-channels.js +9 -7
  360. package/lib/websocket.js +8 -4
  361. package/lib/worm.js +3 -4
  362. package/lib/ws-client.js +65 -56
  363. package/lib/x509-chain.js +44 -0
  364. package/package.json +1 -1
  365. package/sbom.cdx.json +6 -6
package/lib/sql.js CHANGED
@@ -439,7 +439,7 @@ class SqlFunction {
439
439
  throw _err("b.sql.fn(name): name must be a string", "sql-builder/bad-fn");
440
440
  }
441
441
  var key = name.toUpperCase();
442
- if (SQL_FUNCTIONS[key] === undefined) {
442
+ if (!Object.prototype.hasOwnProperty.call(SQL_FUNCTIONS, key)) {
443
443
  throw _err("b.sql.fn(name): '" + name + "' is not an allowlisted SQL function " +
444
444
  "(NOW / CURRENT_TIMESTAMP / CURRENT_DATE / CURRENT_TIME); a bound value uses a ? " +
445
445
  "placeholder, an arbitrary expression uses a guarded raw fragment", "sql-builder/bad-fn");
@@ -513,7 +513,7 @@ function _castType(type, dialect) {
513
513
  throw _err("cast type must be a non-empty string", "sql-builder/bad-cast");
514
514
  }
515
515
  var key = type.toLowerCase();
516
- if (CAST_TYPES[key] === undefined) {
516
+ if (!Object.prototype.hasOwnProperty.call(CAST_TYPES, key)) {
517
517
  throw _err("cast type '" + type + "' is not on the allowlist (jsonb / json / " +
518
518
  "interval / uuid / text / int / bigint / timestamptz / boolean)", "sql-builder/bad-cast");
519
519
  }
@@ -1107,39 +1107,11 @@ function _checkRawFragment(sql, params, opts, where) {
1107
1107
  // comments are skipped. Single linear pass, no backtracking regex. Same
1108
1108
  // shape as db-query.js's scanner.
1109
1109
  function _assertRawNoStringLiteral(sql, where) {
1110
- var i = 0;
1111
- var len = sql.length;
1112
- while (i < len) {
1113
- var ch = sql.charAt(i);
1114
- var next = i + 1 < len ? sql.charAt(i + 1) : "";
1115
- if (ch === '"') {
1116
- i += 1;
1117
- while (i < len) {
1118
- if (sql.charAt(i) === '"') {
1119
- if (sql.charAt(i + 1) === '"') { i += 2; continue; }
1120
- i += 1; break;
1121
- }
1122
- i += 1;
1123
- }
1124
- continue;
1125
- }
1126
- if (ch === "-" && next === "-") {
1127
- while (i < len && sql.charAt(i) !== "\n") i += 1;
1128
- continue;
1129
- }
1130
- if (ch === "/" && next === "*") {
1131
- i += 2;
1132
- while (i < len && !(sql.charAt(i) === "*" && sql.charAt(i + 1) === "/")) i += 1;
1133
- i += 2;
1134
- continue;
1135
- }
1136
- if (ch === "'") {
1137
- throw _err(where + ": raw SQL must not contain a string literal ('...') - bind " +
1138
- "every value with a ? placeholder, or pass { allowLiterals: true } when the " +
1139
- "literal is static and operator-controlled", "sql-builder/raw-literal");
1140
- }
1141
- i += 1;
1142
- }
1110
+ safeSql.assertNoRawStringLiteral(sql, where, function (w) {
1111
+ return _err(w + ": raw SQL must not contain a string literal ('...') - bind " +
1112
+ "every value with a ? placeholder, or pass { allowLiterals: true } when the " +
1113
+ "literal is static and operator-controlled", "sql-builder/raw-literal");
1114
+ });
1143
1115
  }
1144
1116
 
1145
1117
  // Refuse the two-char Postgres JSONB key-existence tokens (?| / ?&) in a raw
@@ -1188,51 +1160,10 @@ function _assertNoRawJsonbKeyOp(sql, where) {
1188
1160
  var _countPlaceholders = safeSql.countPlaceholders;
1189
1161
 
1190
1162
  // Translate the builder's `?` placeholders to a dialect's positional form
1191
- // (Postgres `$1..$N`; SQLite / MySQL keep `?`). Quote / comment-aware single
1192
- // pass - a `?` inside a string literal, a quoted identifier, or a comment is
1193
- // NOT a placeholder and is left untouched. This is the toExternalSql terminal
1194
- // for code that hands the SQL to an operator-supplied driver directly (no
1195
- // clusterStorage in the path to do the rewrite). The translator lives here -
1196
- // the builder owns its driver-final output rendering - rather than reaching
1197
- // into clusterStorage (which transitively requires this module).
1198
- function _toPositional(sql, dialect) {
1199
- if (dialect !== "postgres") return sql;
1200
- var out = "";
1201
- var n = 0;
1202
- var i = 0;
1203
- var len = sql.length;
1204
- while (i < len) {
1205
- var c = sql.charAt(i);
1206
- var nx = i + 1 < len ? sql.charAt(i + 1) : "";
1207
- if (c === "'" || c === '"' || c === "`") {
1208
- out += c;
1209
- i += 1;
1210
- while (i < len) {
1211
- var q = sql.charAt(i);
1212
- if (q === c) {
1213
- if (sql.charAt(i + 1) === c) { out += c + c; i += 2; continue; }
1214
- out += c; i += 1; break;
1215
- }
1216
- out += q; i += 1;
1217
- }
1218
- continue;
1219
- }
1220
- if (c === "-" && nx === "-") {
1221
- while (i < len && sql.charAt(i) !== "\n") { out += sql.charAt(i); i += 1; }
1222
- continue;
1223
- }
1224
- if (c === "/" && nx === "*") {
1225
- out += "/*"; i += 2;
1226
- while (i < len && !(sql.charAt(i) === "*" && sql.charAt(i + 1) === "/")) { out += sql.charAt(i); i += 1; }
1227
- if (i < len) { out += "*/"; i += 2; }
1228
- continue;
1229
- }
1230
- if (c === "?") { n += 1; out += "$" + n; i += 1; continue; }
1231
- out += c;
1232
- i += 1;
1233
- }
1234
- return out;
1235
- }
1163
+ // (Postgres `$1..$N`; SQLite / MySQL keep `?`); composed from safe-sql so the
1164
+ // quote / comment / backtick skip rules live in one place. The toExternalSql
1165
+ // terminal for code that hands the SQL to an operator-supplied driver directly.
1166
+ var _toPositional = safeSql.toPositional;
1236
1167
 
1237
1168
  /**
1238
1169
  * @primitive b.sql.toExternalSql
@@ -1922,6 +1853,163 @@ class InsertBuilder extends Builder {
1922
1853
  }
1923
1854
  }
1924
1855
 
1856
+ // ---- INSERT ... SELECT ... WHERE (conditional / append-only) --------
1857
+ //
1858
+ // A conditional INSERT that materialises its row from a value-less SELECT
1859
+ // guarded by a WHERE - INSERT INTO t (cols) SELECT <cells> WHERE <guard>.
1860
+ // The append-only-ledger debit idiom: the new row is written ONLY when a
1861
+ // guard derived from the table itself holds (a store-credit / gift-card /
1862
+ // points / metered-quota balance that lives on the latest row, with no
1863
+ // mutable counter row to increment()). The SELECT has no FROM - it is a
1864
+ // single computed row that the WHERE either admits (one row inserted) or
1865
+ // rejects (zero rows), evaluated atomically inside the INSERT against the
1866
+ // table the guard's correlated subquery / EXISTS references, so two racing
1867
+ // debits cannot both pass the balance check.
1868
+ //
1869
+ // Standard-SQL across sqlite / Postgres / MySQL - the only dialect-divergent
1870
+ // clause is RETURNING (Postgres / SQLite; refused on MySQL by the shared
1871
+ // _renderReturning, which the MySQL caller replaces with an explicit read).
1872
+ // Every SELECT cell routes through the SAME _renderValueCell choke-point
1873
+ // INSERT VALUES uses (so a cell is a bound ?, a b.sql.cast(...) ?::type, or a
1874
+ // b.sql.fn(...) allowlisted server function - no param), and the guard is a
1875
+ // full Predicate (the whole where-family: whereExists / whereSub / whereOp /
1876
+ // whereRaw / whereGroup compose, which is how a balance fence is expressed).
1877
+ //
1878
+ // Safety default: an INSERT...SELECT with no WHERE is just an INSERT...VALUES
1879
+ // and shipping it un-guarded is almost always a bug, so the verb THROWS
1880
+ // without a where() unless allowNoWhere() opts in - the same discipline
1881
+ // update / delete apply.
1882
+ class InsertSelectWhereBuilder extends Builder {
1883
+ constructor(tableNameOrRef, opts) {
1884
+ super("insert-select-where", tableNameOrRef, opts);
1885
+ this._columns = null;
1886
+ this._values = null; // single row, aligned to _columns
1887
+ this._where = new Predicate(this, "AND");
1888
+ this._returning = null;
1889
+ this._allowNoWhere = false;
1890
+ }
1891
+
1892
+ // Declare the target column list (validated + gated). values() infers it
1893
+ // from a row object's keys when omitted, exactly like INSERT.
1894
+ columns(cols) {
1895
+ if (!Array.isArray(cols) || cols.length === 0) {
1896
+ throw _err("columns() expects a non-empty array", "sql-builder/bad-columns");
1897
+ }
1898
+ var self = this;
1899
+ cols.forEach(function (c) { self._assertColumnMember(c, "insertSelectWhere"); _validateColumn(c); });
1900
+ this._columns = cols.slice();
1901
+ return this;
1902
+ }
1903
+
1904
+ // values(obj) - one row from a column->value map (sets _columns from the
1905
+ // keys when not already declared). values(array) - one positional row
1906
+ // aligned to a prior columns() call. A single row only: the SELECT
1907
+ // materialises exactly one candidate row gated by the WHERE.
1908
+ values(rowOrArray) {
1909
+ if (Array.isArray(rowOrArray)) {
1910
+ if (this._columns === null) {
1911
+ throw _err("values(array) requires a prior columns([...]) call", "sql-builder/no-columns");
1912
+ }
1913
+ if (rowOrArray.length !== this._columns.length) {
1914
+ throw _err("values(array): " + rowOrArray.length + " values but " +
1915
+ this._columns.length + " columns", "sql-builder/value-count");
1916
+ }
1917
+ this._values = rowOrArray.slice();
1918
+ return this;
1919
+ }
1920
+ if (rowOrArray && typeof rowOrArray === "object") {
1921
+ var keys = Object.keys(rowOrArray);
1922
+ if (keys.length === 0) throw _err("insertSelectWhere row object is empty", "sql-builder/empty-values");
1923
+ if (this._columns === null) this.columns(keys);
1924
+ var self = this;
1925
+ this._values = this._columns.map(function (c) {
1926
+ if (!Object.prototype.hasOwnProperty.call(rowOrArray, c)) {
1927
+ throw _err("insertSelectWhere row is missing column '" + c + "'", "sql-builder/missing-column");
1928
+ }
1929
+ return rowOrArray[c];
1930
+ });
1931
+ keys.forEach(function (k) {
1932
+ if (self._columns.indexOf(k) === -1) {
1933
+ throw _err("insertSelectWhere row has column '" + k + "' not in the column set",
1934
+ "sql-builder/extra-column");
1935
+ }
1936
+ });
1937
+ return this;
1938
+ }
1939
+ throw _err("insertSelectWhere values() requires a row object or a value array aligned to columns()",
1940
+ "sql-builder/bad-values");
1941
+ }
1942
+
1943
+ // A deliberate un-guarded conditional insert opts in here - same shape as
1944
+ // update / delete. Without it the verb refuses an empty WHERE.
1945
+ allowNoWhere() { this._allowNoWhere = true; return this; }
1946
+
1947
+ where() { this._where.where.apply(this._where, arguments); return this; }
1948
+ andWhere() { this._where.andWhere.apply(this._where, arguments); return this; }
1949
+ orWhere() { this._where.orWhere.apply(this._where, arguments); return this; }
1950
+ whereOp(col, op, value) { this._where.whereOp(col, op, value); return this; }
1951
+ orWhereOp(col, op, value) { this._where.orWhereOp(col, op, value); return this; }
1952
+ whereIn(col, values) { this._where.whereIn(col, values); return this; }
1953
+ whereNotIn(col, values) { this._where.whereNotIn(col, values); return this; }
1954
+ orWhereIn(col, values) { this._where.orWhereIn(col, values); return this; }
1955
+ whereInArray(col, values) { this._where.whereInArray(col, values); return this; }
1956
+ orWhereInArray(col, values) { this._where.orWhereInArray(col, values); return this; }
1957
+ whereInJsonEach(col, jsonArrayString) { this._where.whereInJsonEach(col, jsonArrayString); return this; }
1958
+ whereMatch(target, expr) { this._where.whereMatch(target, expr); return this; }
1959
+ whereNull(col) { this._where.whereNull(col); return this; }
1960
+ whereNotNull(col) { this._where.whereNotNull(col); return this; }
1961
+ orWhereNull(col) { this._where.orWhereNull(col); return this; }
1962
+ whereLike(col, term, mode) { this._where.whereLike(col, term, mode); return this; }
1963
+ orWhereLike(col, term, mode) { this._where.orWhereLike(col, term, mode); return this; }
1964
+ whereBetween(col, low, high) { this._where.whereBetween(col, low, high); return this; }
1965
+ whereSub(col, op, sub) { this._where.whereSub(col, op, sub); return this; }
1966
+ whereExists(sub) { this._where.whereExists(sub); return this; }
1967
+ whereNotExists(sub) { this._where.whereNotExists(sub); return this; }
1968
+ orWhereExists(sub) { this._where.orWhereExists(sub); return this; }
1969
+ whereGroup(closure) { this._where.whereGroup(closure); return this; }
1970
+ orWhereGroup(closure) { this._where.orWhereGroup(closure); return this; }
1971
+ whereRaw(sql, params, opts) { this._where.whereRaw(sql, params, opts); return this; }
1972
+ orWhereRaw(sql, params, opts) { this._where.orWhereRaw(sql, params, opts); return this; }
1973
+
1974
+ returning(cols) { this._returning = _normReturning(cols); return this; }
1975
+
1976
+ _render() {
1977
+ if (this._columns === null || this._values === null) {
1978
+ throw _err("insertSelectWhere requires columns + a values() row", "sql-builder/empty-values");
1979
+ }
1980
+ if (this._where.length === 0 && !this._allowNoWhere) {
1981
+ throw _err("refusing unconditional insertSelectWhere - call where(...) first or " +
1982
+ "allowNoWhere() (an un-guarded INSERT...SELECT is just INSERT...VALUES)",
1983
+ "sql-builder/no-where");
1984
+ }
1985
+ var dialect = this._dialect;
1986
+ var params = [];
1987
+ var quotedCols = this._columns.map(function (c) { return _quoteId(c, dialect); }).join(", ");
1988
+
1989
+ // Each SELECT cell renders through the same choke-point INSERT VALUES
1990
+ // uses: `?` (bound), `?::type` (cast), or an allowlisted server-function
1991
+ // token (NOW() / CURRENT_TIMESTAMP - no param).
1992
+ var cells = [];
1993
+ for (var v = 0; v < this._values.length; v += 1) {
1994
+ var rendered = _renderValueCell(this._values[v], dialect);
1995
+ cells.push(rendered.sql);
1996
+ for (var rp = 0; rp < rendered.params.length; rp += 1) params.push(rendered.params[rp]);
1997
+ }
1998
+
1999
+ var sql = "INSERT INTO " + this._table.ref(dialect) + " (" + quotedCols + ") SELECT " +
2000
+ cells.join(", ");
2001
+
2002
+ var w = this._where.build();
2003
+ if (w.sql) {
2004
+ sql += " WHERE " + w.sql;
2005
+ for (var wi = 0; wi < w.params.length; wi += 1) params.push(w.params[wi]);
2006
+ }
2007
+
2008
+ sql += _renderReturning(this._returning, dialect);
2009
+ return _emit(sql, params);
2010
+ }
2011
+ }
2012
+
1925
2013
  // ---- UPDATE ---------------------------------------------------------
1926
2014
 
1927
2015
  class UpdateBuilder extends Builder {
@@ -3431,7 +3519,7 @@ var catalog = Object.freeze({
3431
3519
  * b.sql.pragma("journal_mode").sql; // -> 'PRAGMA journal_mode' (read)
3432
3520
  */
3433
3521
  function pragma(verb, arg) {
3434
- if (typeof verb !== "string" || CATALOG_PRAGMA_VERBS[verb] === undefined) {
3522
+ if (typeof verb !== "string" || !Object.prototype.hasOwnProperty.call(CATALOG_PRAGMA_VERBS, verb)) {
3435
3523
  throw _err("pragma: verb '" + verb + "' is not on the allowlist (journal_mode / " +
3436
3524
  "synchronous / wal_checkpoint); a PRAGMA outside this set is refused by design",
3437
3525
  "sql-builder/bad-pragma");
@@ -3699,6 +3787,64 @@ function select(tableNameOrRef, opts) { return new SelectBuilder(tableNameOrRef,
3699
3787
  */
3700
3788
  function insert(tableNameOrRef, opts) { return new InsertBuilder(tableNameOrRef, opts); }
3701
3789
 
3790
+ /**
3791
+ * @primitive b.sql.insertSelectWhere
3792
+ * @signature b.sql.insertSelectWhere(table, opts?)
3793
+ * @since 0.15.13
3794
+ * @status stable
3795
+ * @related b.sql.insert, b.sql.upsert, b.sql.update
3796
+ *
3797
+ * Start a conditional `INSERT ... SELECT ... WHERE` builder - a row written
3798
+ * ONLY when a guard derived from the table itself holds. Emits
3799
+ * `INSERT INTO t (cols) SELECT <cells> WHERE <guard>`: the value-less SELECT
3800
+ * is a single computed candidate row the WHERE either admits (one row
3801
+ * inserted) or rejects (zero rows). It is the race-free append-only-ledger
3802
+ * debit - a store-credit / gift-card / wallet / points / metered-quota /
3803
+ * seat-counter balance that lives only on the latest row, with no mutable
3804
+ * counter row to `increment()`. The guard's correlated subquery / `EXISTS`
3805
+ * is evaluated atomically inside the INSERT, so two concurrent debits cannot
3806
+ * both pass the same balance check.
3807
+ *
3808
+ * Supply the row via `columns([...])` + `values([...])` (positional),
3809
+ * `values({ ... })` (one row object, inferring the column list from its
3810
+ * keys), then the guard via the full `where` family (`whereExists` /
3811
+ * `whereSub` / `whereOp` / `whereGroup` / `whereRaw` all compose - the
3812
+ * balance fence is typically an `EXISTS` against the same table). Each SELECT
3813
+ * cell routes through the same choke-point INSERT `values()` uses, so a cell
3814
+ * may be a bound `?`, a `b.sql.cast(...)` (`?::type`), or a `b.sql.fn(...)`
3815
+ * allowlisted server function (`NOW()`, no param). Standard SQL across sqlite
3816
+ * / Postgres / MySQL; only `RETURNING` diverges (Postgres / SQLite - refused
3817
+ * on MySQL, run an explicit read).
3818
+ *
3819
+ * Safety default: an INSERT...SELECT with no WHERE is just an
3820
+ * INSERT...VALUES, so the verb THROWS without a `where()` unless
3821
+ * `allowNoWhere()` opts in - the same discipline `update` / `delete` apply.
3822
+ *
3823
+ * @opts
3824
+ * dialect: string, // postgres | sqlite | mysql (default sqlite)
3825
+ * schema: string, // schema qualifier
3826
+ * prefix: string, // operator app-table namespace prefix
3827
+ * allowedColumns: array, // column-membership gate set
3828
+ *
3829
+ * @example
3830
+ * // Append a -25 debit ONLY if the wallet's balance row still covers it -
3831
+ * // a race-free conditional insert with no read-modify-write. The guard is
3832
+ * // an EXISTS over a same-dialect sub-builder (no raw statement verb).
3833
+ * var covered = b.sql.select("wallet", { dialect: "postgres" })
3834
+ * .selectRaw("1")
3835
+ * .whereRaw('"id" = ? AND "balance" >= ?', ["w-1", 25]);
3836
+ * b.sql.insertSelectWhere("wallet_ledger", { dialect: "postgres" })
3837
+ * .values({ wallet_id: "w-1", amount: -25, at: b.sql.fn("NOW") })
3838
+ * .whereExists(covered)
3839
+ * .returning(["id"])
3840
+ * .toSql();
3841
+ * // -> { sql: 'INSERT INTO wallet_ledger ("wallet_id", "amount", "at") ' +
3842
+ * // 'SELECT ?, ?, NOW() WHERE EXISTS (SELECT 1 FROM wallet ' +
3843
+ * // 'WHERE ("id" = ? AND "balance" >= ?)) RETURNING "id"',
3844
+ * // params: ["w-1", -25, "w-1", 25] }
3845
+ */
3846
+ function insertSelectWhere(tableNameOrRef, opts) { return new InsertSelectWhereBuilder(tableNameOrRef, opts); }
3847
+
3702
3848
  /**
3703
3849
  * @primitive b.sql.update
3704
3850
  * @signature b.sql.update(table, opts?)
@@ -3806,6 +3952,7 @@ module.exports = {
3806
3952
  // Verbs
3807
3953
  select: select,
3808
3954
  insert: insert,
3955
+ insertSelectWhere: insertSelectWhere,
3809
3956
  update: update,
3810
3957
  delete: del,
3811
3958
  upsert: upsert,
package/lib/sse.js CHANGED
@@ -76,6 +76,8 @@
76
76
 
77
77
  var C = require("./constants");
78
78
  var audit = require("./audit");
79
+ var validateOpts = require("./validate-opts");
80
+ var numericBounds = require("./numeric-bounds");
79
81
  var { SseError } = require("./framework-error");
80
82
 
81
83
  // Per W3C SSE — the wire format uses LF as terminator. A single LF
@@ -228,10 +230,8 @@ function _readLastEventId(req) {
228
230
  function create(req, res, opts) {
229
231
  opts = opts || {};
230
232
  var errorClass = opts.errorClass || SseError;
231
- if (!res || typeof res.write !== "function" || typeof res.end !== "function") {
232
- throw errorClass.factory("sse/bad-res",
233
- "sse.create: res must be a writable response stream");
234
- }
233
+ validateOpts.requireMethods(res, ["write", "end"],
234
+ "sse.create: res (writable response stream)", errorClass, "sse/bad-res");
235
235
  var heartbeatMs = opts.heartbeatMs;
236
236
  if (heartbeatMs === undefined) heartbeatMs = C.TIME.seconds(15);
237
237
  if (typeof heartbeatMs !== "number" || !isFinite(heartbeatMs) ||
@@ -255,12 +255,8 @@ function create(req, res, opts) {
255
255
  // never affected. Config-time input → throw on a bad value.
256
256
  var maxBufferedBytes = opts.maxBufferedBytes;
257
257
  if (maxBufferedBytes === undefined) maxBufferedBytes = C.BYTES.mib(1);
258
- if (typeof maxBufferedBytes !== "number" || !isFinite(maxBufferedBytes) ||
259
- maxBufferedBytes <= 0 || Math.floor(maxBufferedBytes) !== maxBufferedBytes) {
260
- throw errorClass.factory("sse/bad-opts",
261
- "sse.create: maxBufferedBytes must be a positive integer byte count (got " +
262
- JSON.stringify(maxBufferedBytes) + ")");
263
- }
258
+ numericBounds.requirePositiveFiniteInt(maxBufferedBytes,
259
+ "sse.create: maxBufferedBytes", errorClass, "sse/bad-opts");
264
260
 
265
261
  var lastEventId = _readLastEventId(req);
266
262