@blamejs/core 0.4.1

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 (160) hide show
  1. package/CHANGELOG.md +230 -0
  2. package/LICENSE +201 -0
  3. package/LTS-CALENDAR.md +29 -0
  4. package/MIGRATING.md +7 -0
  5. package/NOTICE +59 -0
  6. package/README.md +100 -0
  7. package/bin/blamejs.js +13 -0
  8. package/index.js +253 -0
  9. package/lib/api-key.js +705 -0
  10. package/lib/api-snapshot.js +335 -0
  11. package/lib/app-shutdown.js +381 -0
  12. package/lib/app.js +364 -0
  13. package/lib/atomic-file.js +525 -0
  14. package/lib/audit-chain.js +168 -0
  15. package/lib/audit-sign.js +319 -0
  16. package/lib/audit-tools.js +682 -0
  17. package/lib/audit.js +753 -0
  18. package/lib/auth/jwt.js +280 -0
  19. package/lib/auth/oauth.js +691 -0
  20. package/lib/auth/passkey.js +185 -0
  21. package/lib/auth/password.js +139 -0
  22. package/lib/auth/totp.js +17 -0
  23. package/lib/auth-header.js +81 -0
  24. package/lib/backup/bundle.js +219 -0
  25. package/lib/backup/crypto.js +174 -0
  26. package/lib/backup/index.js +490 -0
  27. package/lib/backup/manifest.js +275 -0
  28. package/lib/bundler.js +295 -0
  29. package/lib/cache.js +819 -0
  30. package/lib/chain-writer.js +234 -0
  31. package/lib/cli-helpers.js +201 -0
  32. package/lib/cli.js +1377 -0
  33. package/lib/cluster-provider-db.js +245 -0
  34. package/lib/cluster-storage.js +166 -0
  35. package/lib/cluster.js +691 -0
  36. package/lib/consent.js +222 -0
  37. package/lib/constants.js +186 -0
  38. package/lib/cookies.js +293 -0
  39. package/lib/credential-hash.js +303 -0
  40. package/lib/crypto-field.js +159 -0
  41. package/lib/crypto.js +250 -0
  42. package/lib/db-query.js +297 -0
  43. package/lib/db-schema.js +250 -0
  44. package/lib/db.js +1054 -0
  45. package/lib/deprecate.js +226 -0
  46. package/lib/dev.js +324 -0
  47. package/lib/error-page.js +424 -0
  48. package/lib/events.js +135 -0
  49. package/lib/external-db.js +422 -0
  50. package/lib/forms.js +378 -0
  51. package/lib/framework-error.js +189 -0
  52. package/lib/framework-schema.js +604 -0
  53. package/lib/handlers.js +350 -0
  54. package/lib/html-balance.js +227 -0
  55. package/lib/http-client.js +615 -0
  56. package/lib/i18n.js +780 -0
  57. package/lib/jobs.js +181 -0
  58. package/lib/lazy-require.js +48 -0
  59. package/lib/log-stream-local.js +137 -0
  60. package/lib/log-stream-webhook.js +170 -0
  61. package/lib/log-stream.js +211 -0
  62. package/lib/log.js +355 -0
  63. package/lib/mail-bounce.js +507 -0
  64. package/lib/mail.js +701 -0
  65. package/lib/metrics.js +647 -0
  66. package/lib/middleware/api-encrypt.js +553 -0
  67. package/lib/middleware/attach-user.js +156 -0
  68. package/lib/middleware/body-parser.js +883 -0
  69. package/lib/middleware/bot-guard.js +148 -0
  70. package/lib/middleware/compression.js +436 -0
  71. package/lib/middleware/cors.js +236 -0
  72. package/lib/middleware/csp-nonce.js +332 -0
  73. package/lib/middleware/csrf-protect.js +275 -0
  74. package/lib/middleware/error-handler.js +46 -0
  75. package/lib/middleware/health.js +358 -0
  76. package/lib/middleware/index.js +52 -0
  77. package/lib/middleware/rate-limit.js +319 -0
  78. package/lib/middleware/request-id.js +53 -0
  79. package/lib/middleware/require-auth.js +95 -0
  80. package/lib/middleware/security-headers.js +91 -0
  81. package/lib/migrations.js +353 -0
  82. package/lib/mtls-ca.js +333 -0
  83. package/lib/mtls-engine-default.js +285 -0
  84. package/lib/nonce-store.js +177 -0
  85. package/lib/notify.js +643 -0
  86. package/lib/ntp-check.js +178 -0
  87. package/lib/object-store/azure-blob.js +467 -0
  88. package/lib/object-store/gcs.js +469 -0
  89. package/lib/object-store/http-put.js +153 -0
  90. package/lib/object-store/index.js +140 -0
  91. package/lib/object-store/local.js +163 -0
  92. package/lib/object-store/retry.js +15 -0
  93. package/lib/object-store/sigv4.js +535 -0
  94. package/lib/observability.js +114 -0
  95. package/lib/pagination.js +371 -0
  96. package/lib/parsers/index.js +64 -0
  97. package/lib/parsers/safe-csv.js +224 -0
  98. package/lib/parsers/safe-env.js +614 -0
  99. package/lib/parsers/safe-toml.js +745 -0
  100. package/lib/parsers/safe-xml.js +379 -0
  101. package/lib/parsers/safe-yaml.js +977 -0
  102. package/lib/permissions.js +430 -0
  103. package/lib/pqc-agent.js +85 -0
  104. package/lib/pqc-gate.js +266 -0
  105. package/lib/protocol-dispatcher.js +144 -0
  106. package/lib/queue-local.js +327 -0
  107. package/lib/queue.js +430 -0
  108. package/lib/redact.js +192 -0
  109. package/lib/render.js +193 -0
  110. package/lib/request-helpers.js +178 -0
  111. package/lib/restore-bundle.js +239 -0
  112. package/lib/restore-rollback.js +254 -0
  113. package/lib/restore.js +301 -0
  114. package/lib/retry.js +329 -0
  115. package/lib/router.js +437 -0
  116. package/lib/safe-async.js +520 -0
  117. package/lib/safe-buffer.js +162 -0
  118. package/lib/safe-json.js +532 -0
  119. package/lib/safe-schema.js +1176 -0
  120. package/lib/safe-sql.js +157 -0
  121. package/lib/safe-url.js +109 -0
  122. package/lib/scheduler.js +680 -0
  123. package/lib/seeders.js +622 -0
  124. package/lib/session.js +304 -0
  125. package/lib/slug.js +243 -0
  126. package/lib/static.js +268 -0
  127. package/lib/storage.js +470 -0
  128. package/lib/subject.js +281 -0
  129. package/lib/template.js +781 -0
  130. package/lib/testing.js +621 -0
  131. package/lib/totp.js +285 -0
  132. package/lib/tracing.js +484 -0
  133. package/lib/validate-opts.js +56 -0
  134. package/lib/vault/index.js +299 -0
  135. package/lib/vault/passphrase-ops.js +311 -0
  136. package/lib/vault/passphrase-source.js +198 -0
  137. package/lib/vault/rotate.js +761 -0
  138. package/lib/vault/wrap.js +289 -0
  139. package/lib/vendor/MANIFEST.json +84 -0
  140. package/lib/vendor/argon2/argon2.cjs +466 -0
  141. package/lib/vendor/argon2/argon2.d.cts +62 -0
  142. package/lib/vendor/argon2/package.json +1 -0
  143. package/lib/vendor/argon2/prebuilds/darwin-arm64/argon2.armv8.glibc.node +0 -0
  144. package/lib/vendor/argon2/prebuilds/darwin-x64/argon2.glibc.node +0 -0
  145. package/lib/vendor/argon2/prebuilds/freebsd-arm64/argon2.armv8.glibc.node +0 -0
  146. package/lib/vendor/argon2/prebuilds/freebsd-x64/argon2.glibc.node +0 -0
  147. package/lib/vendor/argon2/prebuilds/linux-arm/argon2.armv7.glibc.node +0 -0
  148. package/lib/vendor/argon2/prebuilds/linux-arm/argon2.armv7.musl.node +0 -0
  149. package/lib/vendor/argon2/prebuilds/linux-arm64/argon2.armv8.glibc.node +0 -0
  150. package/lib/vendor/argon2/prebuilds/linux-arm64/argon2.armv8.musl.node +0 -0
  151. package/lib/vendor/argon2/prebuilds/linux-x64/argon2.glibc.node +0 -0
  152. package/lib/vendor/argon2/prebuilds/linux-x64/argon2.musl.node +0 -0
  153. package/lib/vendor/argon2/prebuilds/win32-x64/argon2.glibc.node +0 -0
  154. package/lib/vendor/noble-ciphers.cjs +9 -0
  155. package/lib/vendor/pki.cjs +181 -0
  156. package/lib/vendor/simplewebauthn-server.cjs +328 -0
  157. package/lib/webhook.js +632 -0
  158. package/lib/websocket-channels.js +413 -0
  159. package/lib/websocket.js +833 -0
  160. package/package.json +39 -0
package/lib/notify.js ADDED
@@ -0,0 +1,643 @@
1
+ "use strict";
2
+ /**
3
+ * b.notify — generic notification dispatcher.
4
+ *
5
+ * Composes existing primitives — retry/backoff (b.retry), per-call
6
+ * timeout (b.safeAsync.withTimeout), per-channel circuit breaker
7
+ * (b.retry.CircuitBreaker), span+counter wrapping
8
+ * (b.observability.tap), audit emission (b.audit.safeEmit),
9
+ * 5 W's actor context (b.requestHelpers.extractActorContext), URL
10
+ * validation (b.safeUrl.parse), HTTP I/O (b.httpClient.request), PII
11
+ * redaction (b.redact.redact). Notify never re-implements any of these
12
+ * — its job is to coordinate them around a transport abstraction.
13
+ *
14
+ * var notify = b.notify.create({
15
+ * channels: {
16
+ * slack: b.notify.transports.httpJson({ url: process.env.SLACK_HOOK }),
17
+ * sms: operatorTwilioShim,
18
+ * log: b.notify.transports.log(),
19
+ * },
20
+ * audit: b.audit,
21
+ * });
22
+ *
23
+ * await notify.send({ channel: "slack", message: { text: "Hello" } });
24
+ *
25
+ * Transport contract:
26
+ *
27
+ * {
28
+ * name: "slack",
29
+ * send: async function (message, sendOpts) {
30
+ * // Returns { id?, status, attempts?, durationMs? }
31
+ * // Throws on permanent failure. For transient failures, throw
32
+ * // with err.statusCode in b.retry.RETRYABLE_HTTP_STATUS or
33
+ * // err.code in b.retry.RETRYABLE_NET_ERRORS — retry classifies
34
+ * // them automatically. Operators can also set err.transient =
35
+ * // true for shapes outside that classification.
36
+ * },
37
+ * }
38
+ *
39
+ * What this primitive intentionally does NOT do (per scope):
40
+ * - Ship vendor SDKs (Twilio / FCM / APNs / Slack-API): operator brings
41
+ * transports; the framework provides the contract + httpJson +
42
+ * log + test built-ins.
43
+ * - Render templates / handle i18n: operator uses b.template + b.i18n.
44
+ * - Track recipient preferences: operator app concern.
45
+ * - Replace b.mail (SMTP/MIME stays its own primitive).
46
+ * - Replace b.websocketChannels (different abstraction —
47
+ * transient pub/sub, not retry-on-fail delivery).
48
+ */
49
+
50
+ var lazyRequire = require("./lazy-require");
51
+ var requestHelpers = require("./request-helpers");
52
+ var safeAsync = require("./safe-async");
53
+ var safeUrl = require("./safe-url");
54
+ var validateOpts = require("./validate-opts");
55
+ var C = require("./constants");
56
+ var { NotifyError } = require("./framework-error");
57
+
58
+ // Lazy-required modules to avoid load-order cycles. retry / observability /
59
+ // redact / httpClient don't currently import notify, but treating them
60
+ // the same way every primitive does keeps the load-order story uniform.
61
+ var retryModule = lazyRequire(function () { return require("./retry"); });
62
+ var observability = lazyRequire(function () { return require("./observability"); });
63
+ var redactModule = lazyRequire(function () { return require("./redact"); });
64
+ var httpClientModule = lazyRequire(function () { return require("./http-client"); });
65
+
66
+ var _err = NotifyError.factory;
67
+
68
+ var DEFAULTS = Object.freeze({
69
+ auditSuccess: true,
70
+ auditFailures: true,
71
+ defaultTimeoutMs: C.TIME.seconds(30),
72
+ // defaultRetry inherits from b.retry.DEFAULT_RETRY at create time so
73
+ // we get the framework's policy without forking the constants.
74
+ });
75
+
76
+ // ---- Tier-A validation ----
77
+
78
+ function _isFiniteNonNegative(n) {
79
+ return typeof n === "number" && isFinite(n) && n >= 0;
80
+ }
81
+
82
+ function _validateTransport(name, t) {
83
+ if (!t || typeof t !== "object") {
84
+ throw _err("BAD_OPT", "notify: transport for channel '" + name +
85
+ "' must be an object with a send() function");
86
+ }
87
+ if (typeof t.send !== "function") {
88
+ throw _err("BAD_OPT", "notify: transport for channel '" + name +
89
+ "' is missing required send() function");
90
+ }
91
+ }
92
+
93
+ function _validateChannelEntry(name, entry) {
94
+ if (typeof entry !== "object" || entry === null) {
95
+ throw _err("BAD_OPT", "notify: channel '" + name + "' must map to a transport or { transport, ... } object");
96
+ }
97
+ // Two accepted shapes:
98
+ // - Transport object directly: { name, send }
99
+ // - Channel-config object: { transport, retry?, breaker?, timeoutMs?, serialize? }
100
+ if (typeof entry.send === "function") {
101
+ return { transport: entry, retry: null, breaker: null, timeoutMs: null, serialize: false };
102
+ }
103
+ if (entry.transport === undefined) {
104
+ throw _err("BAD_OPT", "notify: channel '" + name +
105
+ "': must be a transport (with send fn) OR an object with .transport");
106
+ }
107
+ _validateTransport(name, entry.transport);
108
+ if (entry.retry !== undefined && (typeof entry.retry !== "object" || entry.retry === null)) {
109
+ throw _err("BAD_OPT", "notify: channel '" + name + "' retry must be a b.retry.withRetry opts object");
110
+ }
111
+ if (entry.breaker !== undefined && entry.breaker !== null && typeof entry.breaker !== "object") {
112
+ throw _err("BAD_OPT", "notify: channel '" + name + "' breaker must be a b.retry.CircuitBreaker opts object or null");
113
+ }
114
+ if (entry.timeoutMs !== undefined && entry.timeoutMs !== 0 && !_isFiniteNonNegative(entry.timeoutMs)) {
115
+ throw _err("BAD_OPT", "notify: channel '" + name + "' timeoutMs must be a non-negative finite number (0 disables)");
116
+ }
117
+ if (entry.serialize !== undefined && typeof entry.serialize !== "boolean") {
118
+ throw _err("BAD_OPT", "notify: channel '" + name + "' serialize must be a boolean");
119
+ }
120
+ return {
121
+ transport: entry.transport,
122
+ retry: entry.retry || null,
123
+ breaker: entry.breaker || null,
124
+ timeoutMs: (entry.timeoutMs !== undefined) ? entry.timeoutMs : null,
125
+ serialize: entry.serialize === true,
126
+ };
127
+ }
128
+
129
+ function _validateCreateOpts(opts) {
130
+ if (!opts || typeof opts !== "object") {
131
+ throw _err("BAD_OPT", "notify.create: opts must be an object");
132
+ }
133
+ if (!opts.channels || typeof opts.channels !== "object") {
134
+ throw _err("BAD_OPT", "notify.create: channels must be an object mapping channel names to transports");
135
+ }
136
+ var keys = Object.keys(opts.channels);
137
+ if (keys.length === 0) {
138
+ throw _err("BAD_OPT", "notify.create: channels object must have at least one channel");
139
+ }
140
+ if (opts.audit !== undefined && opts.audit !== null) {
141
+ if (typeof opts.audit !== "object" || typeof opts.audit.safeEmit !== "function") {
142
+ throw _err("BAD_OPT", "notify.create: audit must be a b.audit-shaped object (safeEmit fn)");
143
+ }
144
+ }
145
+ if (opts.auditSuccess !== undefined && typeof opts.auditSuccess !== "boolean") {
146
+ throw _err("BAD_OPT", "notify.create: auditSuccess must be a boolean");
147
+ }
148
+ if (opts.auditFailures !== undefined && typeof opts.auditFailures !== "boolean") {
149
+ throw _err("BAD_OPT", "notify.create: auditFailures must be a boolean");
150
+ }
151
+ if (opts.redact !== undefined && opts.redact !== null && typeof opts.redact !== "function") {
152
+ throw _err("BAD_OPT", "notify.create: redact must be a function returning a redacted message");
153
+ }
154
+ if (opts.defaultTimeoutMs !== undefined &&
155
+ opts.defaultTimeoutMs !== 0 &&
156
+ !_isFiniteNonNegative(opts.defaultTimeoutMs)) {
157
+ throw _err("BAD_OPT", "notify.create: defaultTimeoutMs must be a non-negative finite number (0 disables)");
158
+ }
159
+ if (opts.defaultRetry !== undefined && opts.defaultRetry !== null &&
160
+ (typeof opts.defaultRetry !== "object")) {
161
+ throw _err("BAD_OPT", "notify.create: defaultRetry must be a b.retry.withRetry opts object");
162
+ }
163
+ if (opts.defaultBreaker !== undefined && opts.defaultBreaker !== null &&
164
+ typeof opts.defaultBreaker !== "object") {
165
+ throw _err("BAD_OPT", "notify.create: defaultBreaker must be a b.retry.CircuitBreaker opts object");
166
+ }
167
+ if (opts.queue !== undefined && opts.queue !== null) {
168
+ if (typeof opts.queue !== "object" || typeof opts.queue.enqueue !== "function") {
169
+ throw _err("BAD_OPT", "notify.create: queue must be a b.queue-shaped handle (enqueue fn)");
170
+ }
171
+ }
172
+ if (opts.clock !== undefined && typeof opts.clock !== "function") {
173
+ throw _err("BAD_OPT", "notify.create: clock must be a function");
174
+ }
175
+ }
176
+
177
+ // ---- Built-in transports ----
178
+
179
+ // httpJson — POST JSON to a URL via b.httpClient. Default `transient`
180
+ // classifier defers to b.retry.isRetryable so HTTP/network classification
181
+ // matches the rest of the framework.
182
+ function httpJson(opts) {
183
+ if (!opts || typeof opts !== "object") {
184
+ throw _err("BAD_OPT", "notify.transports.httpJson: opts must be { url, ... }");
185
+ }
186
+ if (typeof opts.url !== "string" || opts.url.length === 0) {
187
+ throw _err("BAD_OPT", "notify.transports.httpJson: url is required");
188
+ }
189
+ var allowedProtocols = opts.allowHttp ? safeUrl.ALLOW_HTTP_ALL : safeUrl.ALLOW_HTTP_TLS;
190
+ // Validate URL at create time so bad URLs surface at boot, not at first send.
191
+ safeUrl.parse(opts.url, { allowedProtocols: allowedProtocols, errorClass: NotifyError });
192
+
193
+ var method = opts.method || "POST";
194
+ var bodyFormat = opts.bodyFormat || "json";
195
+ if (bodyFormat !== "json" && bodyFormat !== "form") {
196
+ throw _err("BAD_OPT", "notify.transports.httpJson: bodyFormat must be 'json' or 'form'");
197
+ }
198
+ var staticHeaders = opts.headers || {};
199
+ var signing = opts.signing || null;
200
+ if (signing && typeof signing.sign !== "function") {
201
+ throw _err("BAD_OPT", "notify.transports.httpJson: signing must have a sign(body) function");
202
+ }
203
+ var successStatus = (typeof opts.successStatus === "function")
204
+ ? opts.successStatus
205
+ : function (s) { return typeof s === "number" && s >= 200 && s < 300; };
206
+ var customClient = opts.httpClient || null;
207
+ var name = opts.name || "httpJson";
208
+
209
+ return {
210
+ name: name,
211
+ send: async function (message, sendOpts) {
212
+ var client = customClient || httpClientModule();
213
+ var body;
214
+ var contentType;
215
+ if (bodyFormat === "form") {
216
+ body = new URLSearchParams(message || {}).toString();
217
+ contentType = "application/x-www-form-urlencoded";
218
+ } else {
219
+ body = JSON.stringify(message || {});
220
+ contentType = "application/json";
221
+ }
222
+ var headers = Object.assign({ "Content-Type": contentType }, staticHeaders);
223
+ if (sendOpts && sendOpts.headers) Object.assign(headers, sendOpts.headers);
224
+ if (signing) {
225
+ // signing.sign(body) returns either a headers object or a string.
226
+ // The shape mirrors b.webhook.signer outputs so operators can plug
227
+ // a webhook signer in directly.
228
+ var signed = signing.sign(body);
229
+ if (signed && typeof signed === "object" && !Array.isArray(signed)) {
230
+ if (signed.headers) Object.assign(headers, signed.headers);
231
+ else Object.assign(headers, signed);
232
+ }
233
+ }
234
+ var startedAt = Date.now();
235
+ var res = await client.request({
236
+ method: method,
237
+ url: opts.url,
238
+ headers: headers,
239
+ body: body,
240
+ allowedProtocols: allowedProtocols,
241
+ errorClass: NotifyError,
242
+ });
243
+ var status = (res && (res.statusCode || res.status)) || 0;
244
+ if (!successStatus(status)) {
245
+ // Throw a plain Error (not NotifyError) so b.retry.isRetryable
246
+ // can classify on err.statusCode. NotifyError is alwaysPermanent
247
+ // by design — wrapping a 429 in it would tell retry "don't try
248
+ // again" before retry's HTTP-status classifier ever runs.
249
+ // We only convert to NotifyError after retry exhaustion (in the
250
+ // caller), which is when the error truly IS permanent.
251
+ var httpErr = new Error(
252
+ "notify.httpJson: " + opts.url + " responded " + status);
253
+ httpErr.code = "HTTP_FAILURE";
254
+ httpErr.statusCode = status;
255
+ throw httpErr;
256
+ }
257
+ return {
258
+ id: null,
259
+ status: "delivered",
260
+ attempts: 1,
261
+ durationMs: Date.now() - startedAt,
262
+ response: res,
263
+ };
264
+ },
265
+ };
266
+ }
267
+
268
+ // log — fire-and-forget developer logger. Never throws; audit + obs still emit.
269
+ function logTransport(opts) {
270
+ opts = opts || {};
271
+ var logger;
272
+ if (opts.logger && typeof opts.logger.info === "function") {
273
+ logger = opts.logger;
274
+ } else {
275
+ var bootLog = require("./log");
276
+ logger = bootLog.boot("notify.log");
277
+ // boot returns a fn-with-fields shape; tolerate both.
278
+ if (typeof logger === "function") {
279
+ logger = { info: logger, error: function (m) { try { console.error(m); } catch (_e) {} } };
280
+ }
281
+ if (typeof logger.error !== "function") {
282
+ logger.error = function (m) { try { console.error(m); } catch (_e) {} };
283
+ }
284
+ }
285
+ return {
286
+ name: opts.name || "log",
287
+ send: async function (message, _sendOpts) {
288
+ try { logger.info(JSON.stringify(message)); }
289
+ catch (_e) { /* logger best-effort */ }
290
+ return { id: null, status: "delivered", attempts: 1, durationMs: 0 };
291
+ },
292
+ };
293
+ }
294
+
295
+ // test — captures sends to .sent for fixture inspection. Never throws.
296
+ function testTransport() {
297
+ var sent = [];
298
+ return {
299
+ name: "test",
300
+ sent: sent,
301
+ send: async function (message, sendOpts) {
302
+ sent.push({
303
+ message: message,
304
+ sendOpts: sendOpts || null,
305
+ sentAt: Date.now(),
306
+ });
307
+ return { id: null, status: "delivered", attempts: 1, durationMs: 0 };
308
+ },
309
+ clear: function () { sent.length = 0; },
310
+ };
311
+ }
312
+
313
+ // ---- Public create ----
314
+
315
+ function create(opts) {
316
+ opts = opts || {};
317
+ validateOpts(opts, [
318
+ "channels", "audit", "auditSuccess", "auditFailures",
319
+ "redact", "defaultTimeoutMs", "defaultRetry", "defaultBreaker",
320
+ "queue", "clock",
321
+ ], "notify");
322
+ _validateCreateOpts(opts);
323
+
324
+ var auditSuccess = (opts.auditSuccess === undefined) ? DEFAULTS.auditSuccess : opts.auditSuccess;
325
+ var auditFailures = (opts.auditFailures === undefined) ? DEFAULTS.auditFailures : opts.auditFailures;
326
+ var audit = opts.audit || null;
327
+ var redactFn = (typeof opts.redact === "function")
328
+ ? opts.redact
329
+ // Default: b.redact.redact — the framework's PII detector chain.
330
+ : function (m) { return redactModule().redact(m); };
331
+ var defaultTimeoutMs = (opts.defaultTimeoutMs === undefined)
332
+ ? DEFAULTS.defaultTimeoutMs : opts.defaultTimeoutMs;
333
+ var defaultRetry = opts.defaultRetry || null;
334
+ var defaultBreaker = opts.defaultBreaker || null;
335
+ var operatorQueue = opts.queue || null;
336
+ var clock = opts.clock || function () { return Date.now(); };
337
+
338
+ // Build channel registry: name → { transport, retry, breaker, timeoutMs, serialize, mutex? }
339
+ var channels = {};
340
+ var channelNames = Object.keys(opts.channels);
341
+ for (var i = 0; i < channelNames.length; i++) {
342
+ var n = channelNames[i];
343
+ var entry = _validateChannelEntry(n, opts.channels[n]);
344
+ var registry = {
345
+ transport: entry.transport,
346
+ retry: entry.retry || defaultRetry,
347
+ timeoutMs: (entry.timeoutMs === null) ? defaultTimeoutMs : entry.timeoutMs,
348
+ breaker: null,
349
+ mutex: null,
350
+ };
351
+ var breakerOpts = entry.breaker || defaultBreaker;
352
+ if (breakerOpts) {
353
+ registry.breaker = new (retryModule().CircuitBreaker)(n, breakerOpts);
354
+ }
355
+ if (entry.serialize) registry.mutex = new safeAsync.Mutex();
356
+ channels[n] = registry;
357
+ }
358
+
359
+ function _emitObs(name, labels) {
360
+ try { observability().event(name, 1, labels || {}); }
361
+ catch (_e) { /* Tier B */ }
362
+ }
363
+
364
+ function _emitAudit(action, info) {
365
+ if (!audit) return;
366
+ try { audit.safeEmit(Object.assign({ action: action }, info || {})); }
367
+ catch (_e) { /* audit best-effort */ }
368
+ }
369
+
370
+ function _actor(callerOpts) {
371
+ var override = {};
372
+ if (callerOpts && callerOpts.context && typeof callerOpts.context === "object") {
373
+ for (var k in callerOpts.context) {
374
+ if (Object.prototype.hasOwnProperty.call(callerOpts.context, k)) {
375
+ override[k] = callerOpts.context[k];
376
+ }
377
+ }
378
+ }
379
+ return requestHelpers.extractActorContext(callerOpts && callerOpts.req, override);
380
+ }
381
+
382
+ function _redactedMetadata(channel, message, extra) {
383
+ var redactedMessage;
384
+ try { redactedMessage = redactFn(message); }
385
+ catch (_e) { redactedMessage = "[redact-failed]"; }
386
+ return Object.assign({
387
+ channel: channel,
388
+ message: redactedMessage,
389
+ }, extra || {});
390
+ }
391
+
392
+ // Send a single message to one channel. The whole call is wrapped in
393
+ // observability.tap (span+counter), inside which we layer:
394
+ //
395
+ // withRetry( withTimeout( breaker.wrap( transport.send ) ) )
396
+ //
397
+ // Each layer comes from an existing primitive — notify never
398
+ // re-implements retry / timeout / breaker / span+counter logic.
399
+ async function send(input) {
400
+ if (!input || typeof input !== "object") {
401
+ throw _err("BAD_OPT", "notify.send: input must be { channel, message, ... }");
402
+ }
403
+ if (typeof input.channel !== "string" || input.channel.length === 0) {
404
+ throw _err("BAD_OPT", "notify.send: channel must be a non-empty string");
405
+ }
406
+ if (input.message === undefined || input.message === null) {
407
+ throw _err("MISSING_MESSAGE", "notify.send: message is required");
408
+ }
409
+ var channel = input.channel;
410
+ var entry = channels[channel];
411
+ if (!entry) {
412
+ throw _err("NO_CHANNEL", "notify.send: unknown channel '" + channel + "'");
413
+ }
414
+ var perCallTimeoutMs = (input.timeoutMs !== undefined) ? input.timeoutMs : entry.timeoutMs;
415
+ var perCallRetry = input.retry || entry.retry;
416
+ var message = input.message;
417
+
418
+ var attemptCount = 0;
419
+ var startedAt = clock();
420
+ var transport = entry.transport;
421
+ var transportName = transport.name || channel;
422
+
423
+ // The retryable single attempt. Each call to this function is one
424
+ // transport.send invocation (so withRetry's loop is the only retry
425
+ // mechanism — no double-retry inside the breaker or transport).
426
+ async function _oneAttempt(attemptIdx) {
427
+ attemptCount = attemptIdx;
428
+ _emitObs("notify.send.attempt", { channel: channel, attempt: attemptIdx });
429
+ var sendPromise = entry.transport.send(message, input.sendOpts || null);
430
+ // withTimeout from b.safeAsync — never re-implement timer races.
431
+ var timed = (perCallTimeoutMs > 0)
432
+ ? safeAsync.withTimeout(sendPromise, perCallTimeoutMs, { name: "notify." + channel })
433
+ : sendPromise;
434
+ try {
435
+ return await timed;
436
+ } catch (e) {
437
+ // Map withTimeout's async/timeout into a transient error so retry
438
+ // classifies it correctly (operators can still opt OUT by setting
439
+ // err.permanent in their transport).
440
+ if (e && e.code === "async/timeout") {
441
+ _emitObs("notify.send.timeout", { channel: channel });
442
+ var te = _err("TIMEOUT",
443
+ "notify.send: '" + channel + "' transport timed out after " + perCallTimeoutMs + "ms");
444
+ // Mark transient via a NETWORK-style code so b.retry.isRetryable
445
+ // routes it through the retry path.
446
+ te.code = "ETIMEDOUT";
447
+ throw te;
448
+ }
449
+ throw e;
450
+ }
451
+ }
452
+
453
+ // Wrap each attempt with the breaker, if configured.
454
+ async function _attemptWithBreaker(attemptIdx) {
455
+ if (entry.breaker) {
456
+ try {
457
+ return await entry.breaker.wrap(function () { return _oneAttempt(attemptIdx); });
458
+ } catch (e) {
459
+ if (e && e.code === "CIRCUIT_OPEN") {
460
+ _emitObs("notify.send.breaker.open", { channel: channel });
461
+ }
462
+ throw e;
463
+ }
464
+ }
465
+ return _oneAttempt(attemptIdx);
466
+ }
467
+
468
+ // Optional serialize: only one in-flight send per channel at a time.
469
+ async function _attemptSerialized(attemptIdx) {
470
+ if (!entry.mutex) return _attemptWithBreaker(attemptIdx);
471
+ await entry.mutex.acquire();
472
+ try { return await _attemptWithBreaker(attemptIdx); }
473
+ finally { entry.mutex.release(); }
474
+ }
475
+
476
+ // Outer span+counter wrapping via b.observability.tap so a single call
477
+ // produces both a span (under the operator's tracer) AND a counter.
478
+ return observability().tap("notify.send", { channel: channel }, async function () {
479
+ try {
480
+ // b.retry.withRetry IS the retry loop. Notify never hand-rolls
481
+ // backoff/jitter/classification — the framework owns it.
482
+ var result = await retryModule().withRetry(function (attempt) {
483
+ return _attemptSerialized(attempt);
484
+ }, perCallRetry);
485
+
486
+ var durationMs = clock() - startedAt;
487
+ _emitObs("notify.send.success", { channel: channel, durationMs: durationMs });
488
+ if (auditSuccess) {
489
+ _emitAudit("notify.send.success", {
490
+ actor: _actor(input),
491
+ resource: { kind: "notify.channel", id: channel },
492
+ outcome: "success",
493
+ metadata: _redactedMetadata(channel, message, {
494
+ transport: transportName,
495
+ attempts: attemptCount,
496
+ durationMs: durationMs,
497
+ }),
498
+ });
499
+ }
500
+ return Object.assign({}, result, {
501
+ channel: channel,
502
+ attempts: attemptCount,
503
+ durationMs: durationMs,
504
+ });
505
+ } catch (e) {
506
+ _emitObs("notify.send.failure", {
507
+ channel: channel,
508
+ reason: (e && e.code) || "unknown",
509
+ });
510
+ if (auditFailures) {
511
+ _emitAudit("notify.send.failure", {
512
+ actor: _actor(input),
513
+ resource: { kind: "notify.channel", id: channel },
514
+ outcome: "failure",
515
+ reason: (e && e.code) || "send-failed",
516
+ metadata: _redactedMetadata(channel, message, {
517
+ transport: transportName,
518
+ attempts: attemptCount,
519
+ message_: (e && e.message) || String(e),
520
+ }),
521
+ });
522
+ }
523
+ // If the error is already a NotifyError, propagate verbatim.
524
+ // Otherwise wrap so callers always catch a single class while
525
+ // keeping the cause chain.
526
+ if (e && e.isNotifyError) throw e;
527
+ var wrapped = _err("SEND_FAILED",
528
+ "notify.send: '" + channel + "' failed after " + attemptCount + " attempt(s): " +
529
+ ((e && e.message) || String(e)));
530
+ wrapped.cause = e;
531
+ if (e && typeof e.statusCode === "number") wrapped.statusCode = e.statusCode;
532
+ throw wrapped;
533
+ }
534
+ });
535
+ }
536
+
537
+ // sendBatch: settle each input independently. One channel down doesn't
538
+ // fail the whole batch; the result array carries either the success
539
+ // shape OR a NotifyError for each input position.
540
+ async function sendBatch(inputs) {
541
+ if (!Array.isArray(inputs)) {
542
+ throw _err("BAD_OPT", "notify.sendBatch: inputs must be an array");
543
+ }
544
+ var promises = inputs.map(function (input) {
545
+ return send(input).then(
546
+ function (result) { return result; },
547
+ function (err) { return err; }
548
+ );
549
+ });
550
+ var results = await Promise.all(promises);
551
+ var ok = 0;
552
+ var failed = 0;
553
+ for (var i = 0; i < results.length; i++) {
554
+ if (results[i] && results[i].isNotifyError) failed++;
555
+ else ok++;
556
+ }
557
+ _emitObs("notify.batch", { size: inputs.length, ok: ok, failed: failed });
558
+ return results;
559
+ }
560
+
561
+ // queue: enqueue an async send onto the operator's b.queue. Requires a
562
+ // queue handle wired at create() OR per-call. Notify registers a
563
+ // default handler for `notifyQueueName` on first use.
564
+ var _queueHandlerRegistered = {};
565
+ async function queue(input, queueOpts) {
566
+ queueOpts = queueOpts || {};
567
+ var q = queueOpts.queue || operatorQueue;
568
+ if (!q || typeof q.enqueue !== "function") {
569
+ throw _err("NO_QUEUE", "notify.queue: requires a b.queue handle (pass at create or per-call)");
570
+ }
571
+ if (!input || typeof input !== "object" || typeof input.channel !== "string") {
572
+ throw _err("BAD_OPT", "notify.queue: input must be { channel, message, ... }");
573
+ }
574
+ var queueName = queueOpts.queueName || "notify";
575
+ // Handler registration is operator-driven for the b.queue primitive
576
+ // — operators have their own worker boot. We don't try to start
577
+ // workers here. The handler signature follows b.jobs / b.queue
578
+ // conventions: receives { input } and re-invokes notify.send.
579
+ if (!_queueHandlerRegistered[queueName] && typeof q.registerHandler === "function") {
580
+ try {
581
+ q.registerHandler(queueName, async function (job) {
582
+ var payload = (job && job.payload) || job;
583
+ return send(payload);
584
+ });
585
+ _queueHandlerRegistered[queueName] = true;
586
+ } catch (_e) { /* operator may register their own handler */ }
587
+ }
588
+ var jobId = await q.enqueue(queueName, input);
589
+ _emitObs("notify.queue.enqueued", { channel: input.channel, queueName: queueName });
590
+ return { jobId: jobId };
591
+ }
592
+
593
+ function addChannel(name, transport, channelOpts) {
594
+ if (channels[name]) {
595
+ throw _err("CHANNEL_EXISTS", "notify.addChannel: channel '" + name + "' already exists");
596
+ }
597
+ channelOpts = channelOpts || {};
598
+ var entry = _validateChannelEntry(name,
599
+ channelOpts.transport || channelOpts.send || transport
600
+ ? Object.assign({ transport: transport }, channelOpts)
601
+ : transport);
602
+ var registry = {
603
+ transport: entry.transport,
604
+ retry: entry.retry || defaultRetry,
605
+ timeoutMs: (entry.timeoutMs === null) ? defaultTimeoutMs : entry.timeoutMs,
606
+ breaker: null,
607
+ mutex: null,
608
+ };
609
+ var breakerOpts = entry.breaker || defaultBreaker;
610
+ if (breakerOpts) registry.breaker = new (retryModule().CircuitBreaker)(name, breakerOpts);
611
+ if (entry.serialize) registry.mutex = new safeAsync.Mutex();
612
+ channels[name] = registry;
613
+ }
614
+
615
+ function listChannels() {
616
+ return Object.keys(channels);
617
+ }
618
+
619
+ function transportFor(name) {
620
+ var entry = channels[name];
621
+ return entry ? entry.transport : null;
622
+ }
623
+
624
+ return {
625
+ send: send,
626
+ sendBatch: sendBatch,
627
+ queue: queue,
628
+ addChannel: addChannel,
629
+ channels: listChannels,
630
+ transport: transportFor,
631
+ };
632
+ }
633
+
634
+ module.exports = {
635
+ create: create,
636
+ NotifyError: NotifyError,
637
+ DEFAULTS: DEFAULTS,
638
+ transports: {
639
+ httpJson: httpJson,
640
+ log: logTransport,
641
+ test: testTransport,
642
+ },
643
+ };