@classytic/notifications 2.8.0 → 2.10.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.
@@ -0,0 +1,1133 @@
1
+ import { n as NotificationError, r as PermanentDeliveryError } from "../errors-CsQZKfec.mjs";
2
+ import { createHash, createPrivateKey, sign } from "node:crypto";
3
+ import http2 from "node:http2";
4
+
5
+ //#region src/push/aps.ts
6
+ /** Whether a message shows anything (title or body). Data-only pushes do not. */
7
+ function isVisible(message) {
8
+ return Boolean(message.title) || Boolean(message.body);
9
+ }
10
+ /** The effective interruption level after the entitlement check. */
11
+ function effectiveLevel(level, options) {
12
+ if (level === "critical" && !options.allowCriticalAlerts) return "time-sensitive";
13
+ return level;
14
+ }
15
+ /**
16
+ * Build `aps` for a message. Visible pushes get an `alert` and a sound (`default` unless the
17
+ * message says otherwise; `null` = silent). Data-only pushes get only `content-available: 1`.
18
+ */
19
+ function buildAps(message, options) {
20
+ const visible = isVisible(message);
21
+ const level = effectiveLevel(message.interruptionLevel, options);
22
+ const aps = {};
23
+ if (visible) {
24
+ aps.alert = {
25
+ ...message.title ? { title: message.title } : {},
26
+ ...message.body ? { body: message.body } : {}
27
+ };
28
+ if (message.sound !== null) {
29
+ const name = message.sound ?? "default";
30
+ aps.sound = level === "critical" ? {
31
+ critical: 1,
32
+ name,
33
+ volume: 1
34
+ } : name;
35
+ }
36
+ if (level) aps["interruption-level"] = level;
37
+ if (message.imageUrl) aps["mutable-content"] = 1;
38
+ }
39
+ if (message.contentAvailable || !visible) aps["content-available"] = 1;
40
+ if (message.threadId) aps["thread-id"] = message.threadId;
41
+ if (message.badge !== void 0) aps.badge = message.badge;
42
+ if (message.category) aps.category = message.category;
43
+ return aps;
44
+ }
45
+ /** APNs header values derived from the message (shared with FCM's `apns.headers`). */
46
+ function apnsHeaderValues(message, nowMs) {
47
+ const visible = isVisible(message);
48
+ const priority = !visible ? "5" : message.priority === "normal" ? "5" : "10";
49
+ return {
50
+ pushType: visible ? "alert" : "background",
51
+ priority,
52
+ ...message.ttlSeconds !== void 0 ? { expiration: message.ttlSeconds === 0 ? "0" : String(Math.floor(nowMs / 1e3) + message.ttlSeconds) } : {}
53
+ };
54
+ }
55
+ /** `apns-collapse-id` / FCM collapse keys are capped at 64 bytes; longer is a caller bug, not truncated. */
56
+ function collapseKeyTooLong(key) {
57
+ return key !== void 0 && Buffer.byteLength(key, "utf8") > 64;
58
+ }
59
+
60
+ //#endregion
61
+ //#region src/push/retry.ts
62
+ /**
63
+ * Push retry timing: provider minimums, `Retry-After`, exponential backoff with jitter, a give-up
64
+ * window and the notification's own expiry. Pure functions: nothing here sleeps. The caller (a job
65
+ * queue, arc-notifications' per-device retry job) schedules the next attempt at the returned delay.
66
+ *
67
+ * Sources (ADR 0001 section 5.3, arc-ecosystem `docs/adr/0001-notifications-and-push.md`):
68
+ * - FCM "Scale FCM" [S3]: first retry at least 10 s; on 429 wait `Retry-After`, else 60 s;
69
+ * exponential after that; stop after 60 min of continuous failure; drop requests that are no
70
+ * longer timely. FCM ErrorCode [S2]: "minimum initial delay of 1 minute" for quota (429).
71
+ * - APNs "Handling notification responses" [A3]: 5xx "After 15 minutes, you can retry";
72
+ * 429 `TooManyRequests` "You can retry with a delay" (the 60 s floor is our value).
73
+ * - Network errors and timeouts: 10 s floor (our value, same as FCM's minimum).
74
+ *
75
+ * @module @classytic/notifications/push
76
+ */
77
+ /** The numbers behind every push retry decision. Exported so hosts and docs quote one table. */
78
+ const PUSH_RETRY_DEFAULTS = {
79
+ /** FCM: first retry not sooner than 10 s (5xx, network, timeout) [S3]. */
80
+ fcmMinDelayMs: 1e4,
81
+ /** FCM 429: `Retry-After`, else 60 s; quota errors need a 1 minute initial delay [S2][S3]. */
82
+ fcmQuotaDelayMs: 6e4,
83
+ /** FCM: stop after 60 minutes of continuous failure [S3]. */
84
+ fcmGiveUpAfterMs: 36e5,
85
+ /** APNs 500 / 503: retry after 15 minutes [A3]. */
86
+ apnsServerErrorDelayMs: 9e5,
87
+ /** APNs 429 (`TooManyRequests`, `TooManyProviderTokenUpdates`): 60 s (our value) [A3]. */
88
+ apnsTooManyRequestsDelayMs: 6e4,
89
+ /** Network failure, timeout, credentials store down, unknown provider: 10 s (our value). */
90
+ networkDelayMs: 1e4,
91
+ /** Attempts per device, the first send included (ADR 5.3). */
92
+ maxAttempts: 5,
93
+ /** Backoff growth stops here (a floor or Retry-After above it still wins). */
94
+ maxDelayMs: 36e5,
95
+ /** Upward jitter: a delay is stretched by up to this fraction, never shortened. */
96
+ jitter: .2
97
+ };
98
+ /**
99
+ * The provider's minimum wait before retrying a transient failure with this HTTP status
100
+ * (`0` = network failure / timeout / no request made). `TransientPushError` fills
101
+ * `retryFloorMs` from this table unless the throw site passes its own.
102
+ */
103
+ function pushRetryFloorMs(provider, status) {
104
+ const d = PUSH_RETRY_DEFAULTS;
105
+ if (provider === "fcm") return status === 429 ? d.fcmQuotaDelayMs : d.fcmMinDelayMs;
106
+ if (provider === "apns") {
107
+ if (status === 429) return d.apnsTooManyRequestsDelayMs;
108
+ if (status >= 500) return d.apnsServerErrorDelayMs;
109
+ return d.networkDelayMs;
110
+ }
111
+ return d.networkDelayMs;
112
+ }
113
+ /** Walk an error and its causes (4 deep) for a numeric field. Structural: any copy of the package. */
114
+ function numericField(error, field) {
115
+ let cursor = error;
116
+ for (let depth = 0; cursor !== null && typeof cursor === "object" && depth < 5; depth++) {
117
+ const value = cursor[field];
118
+ if (typeof value === "number" && Number.isFinite(value) && value >= 0) return value;
119
+ cursor = cursor.cause;
120
+ }
121
+ }
122
+ function providerOf(error) {
123
+ let cursor = error;
124
+ for (let depth = 0; cursor !== null && typeof cursor === "object" && depth < 5; depth++) {
125
+ const value = cursor.provider;
126
+ if (typeof value === "string" && value !== "router") return value;
127
+ cursor = cursor.cause;
128
+ }
129
+ }
130
+ /**
131
+ * How long to wait before retry number `attempt` (1 = the first retry, after one failed send):
132
+ * `max(Retry-After, provider floor) x 2^(attempt - 1)`, capped at `maxDelayMs`, then stretched by
133
+ * up to 20 % jitter. Jitter only ever ADDS: the result is never below the provider minimum or the
134
+ * provider's `Retry-After`.
135
+ */
136
+ function pushRetryDelay(error, attempt, options = {}) {
137
+ const random = options.random ?? Math.random;
138
+ const floor = numericField(error, "retryFloorMs") ?? PUSH_RETRY_DEFAULTS.networkDelayMs;
139
+ const retryAfter = numericField(error, "retryAfterMs") ?? 0;
140
+ const base = Math.max(floor, retryAfter);
141
+ const n = Math.max(1, Math.floor(attempt));
142
+ const cap = Math.max(options.maxDelayMs ?? PUSH_RETRY_DEFAULTS.maxDelayMs, base);
143
+ const raw = Math.min(base * 2 ** (n - 1), cap);
144
+ const r = Math.min(Math.max(random(), 0), 1);
145
+ return Math.round(raw + raw * PUSH_RETRY_DEFAULTS.jitter * r);
146
+ }
147
+ /**
148
+ * Decide whether, and when, to retry one push to one device. Never sleeps; the caller schedules a
149
+ * job at `delayMs`. Order: permanent errors stop, then the attempt budget, then the timing check
150
+ * against the give-up window and the notification's expiry.
151
+ */
152
+ function planPushRetry(input) {
153
+ const { error, attempt, firstFailureAt, now } = input;
154
+ if (error?.retryable === false) return {
155
+ retry: false,
156
+ reason: "permanent"
157
+ };
158
+ if (attempt >= (input.maxAttempts ?? PUSH_RETRY_DEFAULTS.maxAttempts)) return {
159
+ retry: false,
160
+ reason: "attempts"
161
+ };
162
+ const delayMs = pushRetryDelay(error, attempt, input);
163
+ const at = now + delayMs;
164
+ if (input.expiresAt !== void 0 && at >= input.expiresAt) return {
165
+ retry: false,
166
+ reason: "expired"
167
+ };
168
+ const window = input.giveUpAfterMs ?? (providerOf(error) === "fcm" ? PUSH_RETRY_DEFAULTS.fcmGiveUpAfterMs : void 0);
169
+ if (window !== void 0 && at - firstFailureAt > window) return {
170
+ retry: false,
171
+ reason: "gave-up"
172
+ };
173
+ return {
174
+ retry: true,
175
+ delayMs,
176
+ at
177
+ };
178
+ }
179
+
180
+ //#endregion
181
+ //#region src/push/errors.ts
182
+ /**
183
+ * Push errors. Every message here is built from provider STATUS fields only (HTTP status, the
184
+ * provider's reason code, a token suffix): never key material, never a full device token, never
185
+ * payload text. A provider's own error body is parsed for its reason code and then dropped,
186
+ * because FCM and APNs bodies may echo the token.
187
+ *
188
+ * @module @classytic/notifications/push
189
+ */
190
+ /**
191
+ * The device token will never work again. Permanent (`retryable: false`): the service does not
192
+ * retry it, and the host should delete the device row (the providers' `onInvalidToken` hook and
193
+ * arc-notifications' device channel do).
194
+ */
195
+ var InvalidPushTokenError = class extends PermanentDeliveryError {
196
+ reason;
197
+ provider;
198
+ /** HTTP status the provider answered. */
199
+ status;
200
+ /** Last 6 characters of the token: enough to correlate, useless to an attacker. */
201
+ tokenSuffix;
202
+ /** Structural marker (survives bundling / duplicate copies of this package). */
203
+ invalidToken = true;
204
+ constructor(provider, reason, status, tokenSuffix) {
205
+ super(`${provider} push: device token is ${reason} (status ${status}, token …${tokenSuffix})`, { code: "PUSH_TOKEN_INVALID" });
206
+ this.name = "InvalidPushTokenError";
207
+ this.reason = reason;
208
+ this.provider = provider;
209
+ this.status = status;
210
+ this.tokenSuffix = tokenSuffix;
211
+ }
212
+ };
213
+ /**
214
+ * A failure no retry fixes that is NOT about the token: a payload the provider rejects, a
215
+ * misconfigured topic or sender, a platform with no provider. The device row is kept.
216
+ */
217
+ var PushRejectedError = class extends PermanentDeliveryError {
218
+ provider;
219
+ status;
220
+ /** The provider's reason code (`BadTopic`, `INVALID_ARGUMENT`, ...), or a local one. */
221
+ reason;
222
+ constructor(provider, status, reason, detail) {
223
+ super(`${provider} push rejected: ${status} ${reason}${detail ? ` (${detail})` : ""}`, { code: "PUSH_REJECTED" });
224
+ this.name = "PushRejectedError";
225
+ this.provider = provider;
226
+ this.status = status;
227
+ this.reason = reason;
228
+ }
229
+ };
230
+ /**
231
+ * Credentials are missing, malformed, or refused by the provider. Permanent: retrying with the
232
+ * same credentials cannot succeed (a rotated credential is picked up on the next send anyway).
233
+ * The message names FIELDS, never values.
234
+ */
235
+ var PushCredentialsError = class extends PermanentDeliveryError {
236
+ provider;
237
+ constructor(provider, message) {
238
+ super(`${provider} credentials: ${message}`, { code: "PUSH_CREDENTIALS" });
239
+ this.name = "PushCredentialsError";
240
+ this.provider = provider;
241
+ }
242
+ };
243
+ /**
244
+ * A transient failure (429, 5xx, timeout, connection reset). Retryable; `retryAfterMs` carries the
245
+ * provider's `Retry-After`, which the service's retry loop honours (`retryAfterHint`), and
246
+ * `retryFloorMs` the provider's minimum wait (FCM 10 s, FCM 429 60 s, APNs 5xx 15 min, APNs 429 60 s;
247
+ * `PUSH_RETRY_DEFAULTS`), which nothing may retry sooner than (2.10).
248
+ */
249
+ var TransientPushError = class extends NotificationError {
250
+ retryable = true;
251
+ provider;
252
+ /** HTTP status, or 0 for a network-level failure. */
253
+ status;
254
+ reason;
255
+ retryAfterMs;
256
+ /**
257
+ * The provider's minimum wait before a retry (ms). Defaults from {@link pushRetryFloorMs}
258
+ * (provider + status); a throw site may pass its own. `withRetry` and `planPushRetry` never
259
+ * retry sooner.
260
+ */
261
+ retryFloorMs;
262
+ constructor(provider, status, reason, options) {
263
+ super(`${provider} push failed (retryable): ${status || "network"} ${reason}` + (options?.retryAfterMs !== void 0 ? ` (retry after ${options.retryAfterMs} ms)` : ""), {
264
+ code: "PUSH_TRANSIENT",
265
+ ...options?.cause ? { cause: options.cause } : {}
266
+ });
267
+ this.name = "TransientPushError";
268
+ this.provider = provider;
269
+ this.status = status;
270
+ this.reason = reason;
271
+ if (options?.retryAfterMs !== void 0) this.retryAfterMs = options.retryAfterMs;
272
+ this.retryFloorMs = options?.retryFloorMs ?? pushRetryFloorMs(provider, status);
273
+ }
274
+ };
275
+ /** Structural check: is this an invalid-token error (from any copy of this package)? */
276
+ function isInvalidPushTokenError(err) {
277
+ return err !== null && typeof err === "object" && (err.invalidToken === true || err.code === "PUSH_TOKEN_INVALID");
278
+ }
279
+
280
+ //#endregion
281
+ //#region src/push/jwt.ts
282
+ /**
283
+ * Compact JWS signing over `node:crypto` (no library): RS256 for Google's OAuth2 service-account
284
+ * grant, ES256 for APNs provider tokens. Only signing lives here; providers never verify tokens.
285
+ *
286
+ * @module @classytic/notifications/push
287
+ */
288
+ const b64url = (input) => Buffer.from(input).toString("base64url");
289
+ /**
290
+ * Sign `header.claims` with `key`. ES256 signatures are emitted in the JOSE `r||s` form
291
+ * (`ieee-p1363`), which is what Apple requires; DER would be rejected.
292
+ */
293
+ function signJwt(alg, key, claims, headerExtra = {}) {
294
+ const header = b64url(JSON.stringify({
295
+ alg,
296
+ ...headerExtra
297
+ }));
298
+ const body = b64url(JSON.stringify(claims));
299
+ const input = Buffer.from(`${header}.${body}`);
300
+ const signature = alg === "ES256" ? sign("sha256", input, {
301
+ key,
302
+ dsaEncoding: "ieee-p1363"
303
+ }) : sign("sha256", input, key);
304
+ return `${header}.${body}.${b64url(signature)}`;
305
+ }
306
+ /** Short, non-reversible fingerprint (hex) of any string: for cache keys and safe log fields. */
307
+ function fingerprint(value, length = 16) {
308
+ return createHash("sha256").update(value).digest("hex").slice(0, length);
309
+ }
310
+
311
+ //#endregion
312
+ //#region src/push/credentials.ts
313
+ /**
314
+ * Push credentials: shapes, validation, and the per-provider resolver.
315
+ *
316
+ * Providers never read the environment. The host passes `credentials` as a value or a FUNCTION;
317
+ * the function is called on every send (make it cheap: return a cached object) and its result is
318
+ * compared by `version` (or, without one, by a fingerprint of the fields). A change re-validates,
319
+ * re-imports the key, and drops cached access/provider tokens, so a rotated key applies on the
320
+ * next send without a restart.
321
+ *
322
+ * Validation errors name FIELDS, never values. Key material lives only in memory: the PEM string
323
+ * the source returned and the `KeyObject` imported from it.
324
+ *
325
+ * @module @classytic/notifications/push
326
+ */
327
+ const GOOGLE_TOKEN_URI = "https://oauth2.googleapis.com/token";
328
+ const APPLE_ID = /^[A-Z0-9]{10}$/;
329
+ const BUNDLE_ID = /^[A-Za-z0-9.-]{1,155}$/;
330
+ const EMAIL = /^[^\s@]+@[^\s@]+$/;
331
+ const PROJECT_ID = /^[a-z0-9][a-z0-9-:.]{3,62}$/;
332
+ function str(obj, ...keys) {
333
+ for (const key of keys) {
334
+ const value = obj[key];
335
+ if (typeof value === "string" && value.trim() !== "") return value.trim();
336
+ }
337
+ }
338
+ /** `\n` escapes (an env var or a JSON copy) become real newlines; surrounding space is dropped. */
339
+ function normalizePem(pem) {
340
+ return pem.replace(/\\n/g, "\n").trim();
341
+ }
342
+ function importKey(provider, pem) {
343
+ try {
344
+ return createPrivateKey(normalizePem(pem));
345
+ } catch {
346
+ throw new PushCredentialsError(provider, "privateKey is not a readable PEM private key");
347
+ }
348
+ }
349
+ /**
350
+ * Accept a Google service-account file in any of the forms hosts store it: the JSON object
351
+ * (snake_case as downloaded, or camelCase), its JSON text, or the base64 of that text.
352
+ */
353
+ function parseFcmServiceAccount(input, version) {
354
+ let obj;
355
+ if (typeof input === "string") {
356
+ const text = input.trim().startsWith("{") ? input : Buffer.from(input.trim(), "base64").toString("utf8");
357
+ try {
358
+ obj = JSON.parse(text);
359
+ } catch {
360
+ throw new PushCredentialsError("fcm", "service account is neither JSON nor base64 of JSON");
361
+ }
362
+ } else obj = input;
363
+ if (obj === null || typeof obj !== "object") throw new PushCredentialsError("fcm", "service account must be an object");
364
+ const projectId = str(obj, "projectId", "project_id");
365
+ const clientEmail = str(obj, "clientEmail", "client_email");
366
+ const privateKey = str(obj, "privateKey", "private_key");
367
+ const privateKeyId = str(obj, "privateKeyId", "private_key_id");
368
+ const tokenUri = str(obj, "tokenUri", "token_uri");
369
+ const v = version ?? str(obj, "version");
370
+ return validateFcmCredentials({
371
+ projectId: projectId ?? "",
372
+ clientEmail: clientEmail ?? "",
373
+ privateKey: privateKey ?? "",
374
+ ...privateKeyId ? { privateKeyId } : {},
375
+ ...tokenUri ? { tokenUri } : {},
376
+ ...v ? { version: v } : {}
377
+ });
378
+ }
379
+ /** Check shape and key type; returns a normalized copy. Throws {@link PushCredentialsError}. */
380
+ function validateFcmCredentials(creds) {
381
+ if (creds === null || typeof creds !== "object") throw new PushCredentialsError("fcm", "credentials must be an object");
382
+ const missing = [
383
+ "projectId",
384
+ "clientEmail",
385
+ "privateKey"
386
+ ].filter((k) => typeof creds[k] !== "string" || creds[k].trim() === "");
387
+ if (missing.length) throw new PushCredentialsError("fcm", `missing ${missing.join(", ")}`);
388
+ if (!PROJECT_ID.test(creds.projectId)) throw new PushCredentialsError("fcm", "projectId is malformed");
389
+ if (!EMAIL.test(creds.clientEmail)) throw new PushCredentialsError("fcm", "clientEmail is malformed");
390
+ if (creds.tokenUri !== void 0 && !/^https?:\/\//.test(creds.tokenUri)) throw new PushCredentialsError("fcm", "tokenUri must be an http(s) URL");
391
+ if (importKey("fcm", creds.privateKey).asymmetricKeyType !== "rsa") throw new PushCredentialsError("fcm", "privateKey must be an RSA key (service-account private_key)");
392
+ return {
393
+ ...creds,
394
+ privateKey: normalizePem(creds.privateKey)
395
+ };
396
+ }
397
+ /** Check shape and key type (EC P-256); returns a normalized copy. Throws {@link PushCredentialsError}. */
398
+ function validateApnsCredentials(creds) {
399
+ if (creds === null || typeof creds !== "object") throw new PushCredentialsError("apns", "credentials must be an object");
400
+ const missing = [
401
+ "keyId",
402
+ "teamId",
403
+ "privateKey",
404
+ "bundleId"
405
+ ].filter((k) => typeof creds[k] !== "string" || creds[k].trim() === "");
406
+ if (missing.length) throw new PushCredentialsError("apns", `missing ${missing.join(", ")}`);
407
+ if (!APPLE_ID.test(creds.keyId)) throw new PushCredentialsError("apns", "keyId must be 10 characters (A-Z, 0-9)");
408
+ if (!APPLE_ID.test(creds.teamId)) throw new PushCredentialsError("apns", "teamId must be 10 characters (A-Z, 0-9)");
409
+ if (!BUNDLE_ID.test(creds.bundleId)) throw new PushCredentialsError("apns", "bundleId is malformed");
410
+ if (creds.environment !== void 0 && creds.environment !== "production" && creds.environment !== "sandbox") throw new PushCredentialsError("apns", "environment must be \"production\" or \"sandbox\"");
411
+ const key = importKey("apns", creds.privateKey);
412
+ if (key.asymmetricKeyType !== "ec" || key.asymmetricKeyDetails?.namedCurve !== "prime256v1") throw new PushCredentialsError("apns", "privateKey must be an EC P-256 key (the .p8 file)");
413
+ return {
414
+ ...creds,
415
+ privateKey: normalizePem(creds.privateKey)
416
+ };
417
+ }
418
+ /** A stable cache key for a credential value: its `version`, else a hash of every field. */
419
+ function credentialsFingerprint(creds) {
420
+ const version = creds.version;
421
+ if (typeof version === "string" && version !== "") return `v:${version}`;
422
+ const entries = Object.entries(creds).sort(([a], [b]) => a < b ? -1 : 1);
423
+ return `h:${fingerprint(JSON.stringify(entries), 32)}`;
424
+ }
425
+ /**
426
+ * Resolve-per-send, derive-on-change. `onRotate` runs when the fingerprint moves (drop cached
427
+ * tokens, reconnect). A source that throws something other than a credentials error (the
428
+ * integrations store is down) surfaces as retryable.
429
+ */
430
+ function createCredentialResolver(provider, source, validate, derive, onRotate) {
431
+ if (source === null || source === void 0) throw new PushCredentialsError(provider, "credentials option is required");
432
+ let current;
433
+ return { async resolve() {
434
+ let raw;
435
+ try {
436
+ raw = typeof source === "function" ? await source() : source;
437
+ } catch (err) {
438
+ if (err instanceof PushCredentialsError || err?.retryable === false) throw err;
439
+ throw new TransientPushError(provider, 0, "credentials-unavailable", { ...err instanceof Error ? { cause: err } : {} });
440
+ }
441
+ if (raw === null || typeof raw !== "object") throw new PushCredentialsError(provider, "credentials source returned nothing");
442
+ const fp = credentialsFingerprint(raw);
443
+ if (current && current.fingerprint === fp) return current;
444
+ const creds = validate(raw);
445
+ const next = {
446
+ creds,
447
+ derived: derive(creds),
448
+ fingerprint: fp
449
+ };
450
+ const previous = current;
451
+ current = next;
452
+ onRotate?.(next, previous);
453
+ return next;
454
+ } };
455
+ }
456
+
457
+ //#endregion
458
+ //#region src/push/internal.ts
459
+ /** Run the dead-token hook, swallowing its failure (cleanup must not change the outcome). */
460
+ async function reportInvalid(handler, token, reason) {
461
+ if (!handler) return;
462
+ try {
463
+ await handler(token, reason);
464
+ } catch {}
465
+ }
466
+ /** The redacted event fields for a failed send, from the typed error. */
467
+ function failureEvent(err) {
468
+ if (err instanceof InvalidPushTokenError) return {
469
+ outcome: "invalid-token",
470
+ status: err.status,
471
+ reason: err.reason
472
+ };
473
+ if (err instanceof PushCredentialsError) return {
474
+ outcome: "credentials",
475
+ status: 0,
476
+ reason: "credentials"
477
+ };
478
+ if (err instanceof PushRejectedError) return {
479
+ outcome: "rejected",
480
+ status: err.status,
481
+ reason: err.reason
482
+ };
483
+ if (err instanceof TransientPushError) return {
484
+ outcome: "transient",
485
+ status: err.status,
486
+ reason: err.reason,
487
+ ...err.retryAfterMs !== void 0 ? { retryAfterMs: err.retryAfterMs } : {}
488
+ };
489
+ return {
490
+ outcome: "transient",
491
+ status: 0,
492
+ reason: "unknown"
493
+ };
494
+ }
495
+ /** Last 6 characters, for messages and logs. */
496
+ function tokenSuffix(token) {
497
+ return token.length <= 6 ? "***" : token.slice(-6);
498
+ }
499
+ /** Non-reversible token hash for joining log rows. */
500
+ function tokenHash(token) {
501
+ return fingerprint(token, 16);
502
+ }
503
+ /**
504
+ * `Retry-After` as milliseconds: delta-seconds or an HTTP-date. Unparseable or negative values
505
+ * are ignored. Capped at one hour so a hostile or broken header cannot park a queue for days.
506
+ */
507
+ function parseRetryAfter(value, now) {
508
+ const raw = Array.isArray(value) ? value[0] : value;
509
+ if (raw === void 0 || raw === null || raw === "") return void 0;
510
+ const trimmed = String(raw).trim();
511
+ let ms;
512
+ if (/^\d+$/.test(trimmed)) ms = Number(trimmed) * 1e3;
513
+ else {
514
+ const at = Date.parse(trimmed);
515
+ if (Number.isNaN(at)) return void 0;
516
+ ms = at - now;
517
+ }
518
+ if (!Number.isFinite(ms) || ms < 0) return void 0;
519
+ return Math.min(ms, 36e5);
520
+ }
521
+ /** A counting semaphore: at most `limit` sends in flight per provider instance. */
522
+ function createGate(limit) {
523
+ if (!Number.isInteger(limit) || limit < 1) throw new Error(`push: maxConcurrency must be a positive integer`);
524
+ let active = 0;
525
+ const waiting = [];
526
+ return async (fn) => {
527
+ if (active >= limit) await new Promise((resolve) => waiting.push(resolve));
528
+ active++;
529
+ try {
530
+ return await fn();
531
+ } finally {
532
+ active--;
533
+ waiting.shift()?.();
534
+ }
535
+ };
536
+ }
537
+ /**
538
+ * Per-process back-pressure after a 429 / 503 with `Retry-After`: until the deadline every send
539
+ * fails fast as retryable with the remaining wait, instead of hammering a provider that already
540
+ * said "not now". Not a circuit breaker: it never opens on its own judgement, only on the
541
+ * provider's explicit instruction, and it closes by itself when the time passes.
542
+ */
543
+ function createCooldown(now) {
544
+ let until = 0;
545
+ return {
546
+ /** Remaining ms of an active cool-down, or 0. */
547
+ remaining() {
548
+ const left = until - now();
549
+ return left > 0 ? left : 0;
550
+ },
551
+ hold(ms) {
552
+ until = Math.max(until, now() + ms);
553
+ }
554
+ };
555
+ }
556
+
557
+ //#endregion
558
+ //#region src/push/fcm.ts
559
+ const FCM_ENDPOINT = "https://fcm.googleapis.com";
560
+ const FCM_SCOPE = "https://www.googleapis.com/auth/firebase.messaging";
561
+ /** FCM data rules: string values only, no reserved keys. */
562
+ const RESERVED_DATA_KEY = /^(from|notification|message_type)$|^(google|gcm)/i;
563
+ const TOKEN_SHAPE = /^[^\s]{1,4096}$/;
564
+ /** Build the FCM v1 `message` object. Exported for tests and for hosts that inspect payloads. */
565
+ function buildFcmMessage(message, options, nowMs) {
566
+ const visible = isVisible(message);
567
+ const headers = apnsHeaderValues(message, nowMs);
568
+ const android = { priority: (message.priority ?? (visible ? "high" : "normal")) === "high" ? "HIGH" : "NORMAL" };
569
+ if (message.ttlSeconds !== void 0) android.ttl = `${message.ttlSeconds}s`;
570
+ if (message.collapseKey) android.collapseKey = message.collapseKey;
571
+ if (visible) {
572
+ const notification = {};
573
+ if (message.collapseKey) notification.tag = message.collapseKey;
574
+ if (message.badge !== void 0) notification.notificationCount = message.badge;
575
+ if (message.channelId) notification.channelId = message.channelId;
576
+ if (message.sound !== null) notification.sound = message.sound ?? "default";
577
+ if (message.category) notification.clickAction = message.category;
578
+ if (Object.keys(notification).length) android.notification = notification;
579
+ }
580
+ const apnsHeaders = {
581
+ "apns-priority": headers.priority,
582
+ "apns-push-type": headers.pushType,
583
+ ...message.collapseKey ? { "apns-collapse-id": message.collapseKey } : {},
584
+ ...headers.expiration !== void 0 ? { "apns-expiration": headers.expiration } : {}
585
+ };
586
+ return {
587
+ token: message.token,
588
+ ...visible ? { notification: {
589
+ ...message.title ? { title: message.title } : {},
590
+ ...message.body ? { body: message.body } : {},
591
+ ...message.imageUrl ? { image: message.imageUrl } : {}
592
+ } } : {},
593
+ ...message.data && Object.keys(message.data).length ? { data: message.data } : {},
594
+ android,
595
+ apns: {
596
+ headers: apnsHeaders,
597
+ payload: { aps: buildAps(message, options) }
598
+ }
599
+ };
600
+ }
601
+ function checkMessage(message) {
602
+ if (typeof message.token !== "string" || !TOKEN_SHAPE.test(message.token)) throw new PushRejectedError("fcm", 0, "invalid-token-format", "token must be a non-empty string without spaces");
603
+ if (collapseKeyTooLong(message.collapseKey)) throw new PushRejectedError("fcm", 0, "collapse-key-too-long", "collapseKey exceeds 64 bytes");
604
+ for (const [key, value] of Object.entries(message.data ?? {})) {
605
+ if (typeof value !== "string") throw new PushRejectedError("fcm", 0, "invalid-data", `data.${key} must be a string`);
606
+ if (RESERVED_DATA_KEY.test(key)) throw new PushRejectedError("fcm", 0, "invalid-data", `data.${key} is reserved by FCM`);
607
+ }
608
+ }
609
+ /** Pull the codes out of an FCM error body; the free-text message is inspected, never kept. */
610
+ function parseFcmError(text) {
611
+ try {
612
+ const err = JSON.parse(text).error ?? {};
613
+ let errorCode;
614
+ let tokenNamed = typeof err.message === "string" && /registration token/i.test(err.message);
615
+ for (const detail of err.details ?? []) {
616
+ if (typeof detail.errorCode === "string") errorCode = detail.errorCode;
617
+ if (detail.fieldViolations?.some((v) => v.field === "message.token")) tokenNamed = true;
618
+ }
619
+ const perDevice = typeof err.message === "string" && /device/i.test(err.message);
620
+ return {
621
+ ...err.status ? { status: err.status } : {},
622
+ ...errorCode ? { errorCode } : {},
623
+ tokenNamed,
624
+ perDevice
625
+ };
626
+ } catch {
627
+ return {
628
+ tokenNamed: false,
629
+ perDevice: false
630
+ };
631
+ }
632
+ }
633
+ function fcmProvider(options) {
634
+ const now = options.now ?? Date.now;
635
+ const doFetch = options.fetch ?? globalThis.fetch;
636
+ if (typeof doFetch !== "function") throw new Error("fcmProvider: no fetch implementation (Node 18+ or options.fetch)");
637
+ const endpoint = (options.endpoint ?? "https://fcm.googleapis.com").replace(/\/+$/, "");
638
+ const timeoutMs = options.timeoutMs ?? 1e4;
639
+ const gate = createGate(options.maxConcurrency ?? 100);
640
+ const cooldown = createCooldown(now);
641
+ let access;
642
+ let refreshing;
643
+ const resolver = createCredentialResolver("fcm", options.credentials, validateFcmCredentials, (creds) => importKey("fcm", creds.privateKey), () => {
644
+ access = void 0;
645
+ });
646
+ const emit = (event, token) => {
647
+ if (!options.onDelivery) return;
648
+ try {
649
+ options.onDelivery({
650
+ provider: "fcm",
651
+ tokenSuffix: tokenSuffix(token),
652
+ tokenHash: tokenHash(token),
653
+ ...event
654
+ });
655
+ } catch {}
656
+ };
657
+ async function request(url, init) {
658
+ try {
659
+ return await doFetch(url, {
660
+ ...init,
661
+ signal: AbortSignal.timeout(timeoutMs)
662
+ });
663
+ } catch (err) {
664
+ const timedOut = err?.name === "TimeoutError";
665
+ throw new TransientPushError("fcm", 0, timedOut ? "timeout" : "network", { ...err instanceof Error ? { cause: err } : {} });
666
+ }
667
+ }
668
+ async function fetchAccessToken(resolved) {
669
+ const { creds, derived: key } = resolved;
670
+ const tokenUri = creds.tokenUri ?? "https://oauth2.googleapis.com/token";
671
+ const iat = Math.floor(now() / 1e3);
672
+ const assertion = signJwt("RS256", key, {
673
+ iss: creds.clientEmail,
674
+ scope: FCM_SCOPE,
675
+ aud: tokenUri,
676
+ iat,
677
+ exp: iat + 3600
678
+ }, {
679
+ typ: "JWT",
680
+ ...creds.privateKeyId ? { kid: creds.privateKeyId } : {}
681
+ });
682
+ const res = await request(tokenUri, {
683
+ method: "POST",
684
+ headers: { "content-type": "application/x-www-form-urlencoded" },
685
+ body: new URLSearchParams({
686
+ grant_type: "urn:ietf:params:oauth:grant-type:jwt-bearer",
687
+ assertion
688
+ }).toString()
689
+ });
690
+ const text = await res.text();
691
+ if (!res.ok) {
692
+ if (res.status === 429 || res.status >= 500) {
693
+ const retryAfterMs = parseRetryAfter(res.headers.get("retry-after"), now());
694
+ throw new TransientPushError("fcm", res.status, "token-endpoint", retryAfterMs !== void 0 ? { retryAfterMs } : {});
695
+ }
696
+ let code = "refused";
697
+ try {
698
+ code = String(JSON.parse(text).error ?? code);
699
+ } catch {}
700
+ throw new PushCredentialsError("fcm", `token endpoint refused the service account (${res.status} ${code})`);
701
+ }
702
+ let parsed;
703
+ try {
704
+ parsed = JSON.parse(text);
705
+ } catch {
706
+ throw new TransientPushError("fcm", res.status, "token-endpoint-malformed");
707
+ }
708
+ if (typeof parsed.access_token !== "string" || parsed.access_token === "") throw new TransientPushError("fcm", res.status, "token-endpoint-malformed");
709
+ const expiresIn = typeof parsed.expires_in === "number" && parsed.expires_in > 0 ? parsed.expires_in : 3600;
710
+ return {
711
+ token: parsed.access_token,
712
+ expiresAt: now() + expiresIn * 1e3,
713
+ fingerprint: resolved.fingerprint
714
+ };
715
+ }
716
+ /** Cached token, or ONE shared refresh for every concurrent caller. */
717
+ async function accessToken(resolved, force) {
718
+ if (!force && access && access.fingerprint === resolved.fingerprint && now() < access.expiresAt - 6e4) return access.token;
719
+ if (refreshing && refreshing.fingerprint === resolved.fingerprint) return (await refreshing.promise).token;
720
+ const promise = fetchAccessToken(resolved);
721
+ const entry = {
722
+ fingerprint: resolved.fingerprint,
723
+ promise
724
+ };
725
+ refreshing = entry;
726
+ try {
727
+ const fresh = await promise;
728
+ access = fresh;
729
+ return fresh.token;
730
+ } finally {
731
+ if (refreshing === entry) refreshing = void 0;
732
+ }
733
+ }
734
+ async function invalid(token, reason, status) {
735
+ await reportInvalid(options.onInvalidToken, token, reason);
736
+ throw new InvalidPushTokenError("fcm", reason, status, tokenSuffix(token));
737
+ }
738
+ async function sendOnce(message, started) {
739
+ const waitMs = cooldown.remaining();
740
+ if (waitMs > 0) throw new TransientPushError("fcm", 429, "cooling-down", { retryAfterMs: waitMs });
741
+ const resolved = await resolver.resolve();
742
+ const body = JSON.stringify({
743
+ ...options.validateOnly ? { validate_only: true } : {},
744
+ message: buildFcmMessage(message, options, now())
745
+ });
746
+ const url = `${endpoint}/v1/projects/${encodeURIComponent(resolved.creds.projectId)}/messages:send`;
747
+ for (let attempt = 0; attempt < 2; attempt++) {
748
+ const res = await request(url, {
749
+ method: "POST",
750
+ headers: {
751
+ authorization: `Bearer ${await accessToken(resolved, attempt > 0)}`,
752
+ "content-type": "application/json; charset=utf-8"
753
+ },
754
+ body
755
+ });
756
+ const text = await res.text();
757
+ if (res.ok) {
758
+ let messageId = "fcm";
759
+ try {
760
+ messageId = String(JSON.parse(text).name ?? messageId);
761
+ } catch {}
762
+ emit({
763
+ outcome: "sent",
764
+ status: res.status,
765
+ messageId,
766
+ latencyMs: now() - started,
767
+ ...platformOf(message)
768
+ }, message.token);
769
+ return { messageId };
770
+ }
771
+ const err = parseFcmError(text);
772
+ const reason = err.errorCode ?? err.status ?? String(res.status);
773
+ if (res.status === 401 && err.errorCode !== "THIRD_PARTY_AUTH_ERROR") {
774
+ access = void 0;
775
+ if (attempt === 0) continue;
776
+ throw new PushCredentialsError("fcm", "access token refused twice (401 UNAUTHENTICATED)");
777
+ }
778
+ if (err.errorCode === "UNREGISTERED" || res.status === 404 && err.status === "NOT_FOUND") return invalid(message.token, "unregistered", res.status);
779
+ if ((err.errorCode === "INVALID_ARGUMENT" || err.status === "INVALID_ARGUMENT") && err.tokenNamed) return invalid(message.token, "invalid-token", res.status);
780
+ if (res.status === 403 && err.errorCode !== "SENDER_ID_MISMATCH") throw new PushCredentialsError("fcm", `service account lacks permission to send (403 ${reason})`);
781
+ if (res.status === 429 || res.status >= 500) {
782
+ const retryAfterMs = parseRetryAfter(res.headers.get("retry-after"), now());
783
+ if (retryAfterMs !== void 0 && !err.perDevice) cooldown.hold(retryAfterMs);
784
+ throw new TransientPushError("fcm", res.status, reason, retryAfterMs !== void 0 ? { retryAfterMs } : {});
785
+ }
786
+ throw new PushRejectedError("fcm", res.status, reason);
787
+ }
788
+ /* c8 ignore next */
789
+ throw new TransientPushError("fcm", 0, "unreachable");
790
+ }
791
+ return { async send(message) {
792
+ const started = now();
793
+ try {
794
+ checkMessage(message);
795
+ return await gate(() => sendOnce(message, started));
796
+ } catch (err) {
797
+ emit({
798
+ ...failureEvent(err),
799
+ latencyMs: now() - started,
800
+ ...platformOf(message)
801
+ }, message.token);
802
+ throw err;
803
+ }
804
+ } };
805
+ }
806
+ function platformOf(message) {
807
+ return message.platform ? { platform: message.platform } : {};
808
+ }
809
+
810
+ //#endregion
811
+ //#region src/push/apns.ts
812
+ const APNS_HOSTS = {
813
+ production: "https://api.push.apple.com",
814
+ sandbox: "https://api.sandbox.push.apple.com"
815
+ };
816
+ /** Default provider-token lifetime: inside Apple's 20 to 60 minute window with margin. */
817
+ const APNS_TOKEN_TTL_MS = 3e6;
818
+ const MIN_TTL_MS = 12e5;
819
+ const MAX_TTL_MS = 36e5;
820
+ const MAX_PAYLOAD_BYTES = 4096;
821
+ const DEVICE_TOKEN = /^[0-9a-fA-F]{16,400}$/;
822
+ /** The APNs JSON payload for a message. Exported for tests and payload inspection. */
823
+ function buildApnsPayload(message, options) {
824
+ const custom = { ...message.data ?? {} };
825
+ if (message.imageUrl) custom.imageUrl = message.imageUrl;
826
+ return {
827
+ ...custom,
828
+ aps: buildAps(message, options)
829
+ };
830
+ }
831
+ function apnsProvider(options) {
832
+ const now = options.now ?? Date.now;
833
+ const tokenTtlMs = options.tokenTtlMs ?? 3e6;
834
+ if (tokenTtlMs < MIN_TTL_MS || tokenTtlMs >= MAX_TTL_MS) throw new Error("apnsProvider: tokenTtlMs must be at least 20 minutes and under 60 minutes (Apple)");
835
+ if (options.host && !options.host.startsWith("https://") && !options.allowPlaintext) throw new Error("apnsProvider: host must be https:// (allowPlaintext is for tests only)");
836
+ const timeoutMs = options.requestTimeoutMs ?? 1e4;
837
+ const gate = createGate(options.maxConcurrency ?? 500);
838
+ const cooldown = createCooldown(now);
839
+ const connect = options.connect ?? ((authority, connectOptions) => http2.connect(authority, connectOptions));
840
+ let providerToken;
841
+ const sessions = /* @__PURE__ */ new Map();
842
+ const resolver = createCredentialResolver("apns", options.credentials, validateApnsCredentials, (creds) => importKey("apns", creds.privateKey), (next) => {
843
+ providerToken = void 0;
844
+ const keep = authorityOf(next.creds);
845
+ for (const [authority, entry] of sessions) if (authority !== keep) {
846
+ sessions.delete(authority);
847
+ entry.session.close();
848
+ }
849
+ });
850
+ function authorityOf(creds) {
851
+ return options.host ?? APNS_HOSTS[creds.environment ?? "production"];
852
+ }
853
+ function bearer(resolved, force) {
854
+ const t = now();
855
+ if (!force && providerToken && providerToken.fingerprint === resolved.fingerprint && t - providerToken.issuedAt < tokenTtlMs) return providerToken.token;
856
+ const token = signJwt("ES256", resolved.derived, {
857
+ iss: resolved.creds.teamId,
858
+ iat: Math.floor(t / 1e3)
859
+ }, { kid: resolved.creds.keyId });
860
+ providerToken = {
861
+ token,
862
+ issuedAt: t,
863
+ fingerprint: resolved.fingerprint
864
+ };
865
+ return token;
866
+ }
867
+ function sessionFor(authority) {
868
+ const existing = sessions.get(authority);
869
+ if (existing && !existing.session.closed && !existing.session.destroyed) return existing;
870
+ const session = connect(authority, options.connectOptions);
871
+ const entry = {
872
+ session,
873
+ active: 0
874
+ };
875
+ const drop = () => {
876
+ if (sessions.get(authority) === entry) sessions.delete(authority);
877
+ };
878
+ session.on("error", drop);
879
+ session.on("goaway", drop);
880
+ session.on("close", drop);
881
+ session.unref();
882
+ sessions.set(authority, entry);
883
+ return entry;
884
+ }
885
+ function post(authority, headers, body) {
886
+ return new Promise((resolve, reject) => {
887
+ let entry;
888
+ let stream;
889
+ try {
890
+ entry = sessionFor(authority);
891
+ stream = entry.session.request(headers);
892
+ } catch (err) {
893
+ reject(new TransientPushError("apns", 0, "network", err instanceof Error ? { cause: err } : {}));
894
+ return;
895
+ }
896
+ if (entry.active++ === 0) entry.session.ref();
897
+ let settled = false;
898
+ const finish = (fn) => {
899
+ if (settled) return;
900
+ settled = true;
901
+ if (--entry.active === 0 && !entry.session.destroyed) entry.session.unref();
902
+ fn();
903
+ };
904
+ let status = 0;
905
+ let apnsId;
906
+ let retryAfter;
907
+ let raw = "";
908
+ stream.setEncoding("utf8");
909
+ stream.setTimeout(timeoutMs, () => {
910
+ stream.close(http2.constants.NGHTTP2_CANCEL);
911
+ finish(() => reject(new TransientPushError("apns", 0, "timeout")));
912
+ });
913
+ stream.on("response", (h) => {
914
+ status = Number(h[":status"] ?? 0);
915
+ const id = h["apns-id"];
916
+ apnsId = Array.isArray(id) ? id[0] : id;
917
+ retryAfter = h["retry-after"];
918
+ });
919
+ stream.on("data", (chunk) => {
920
+ if (raw.length < 4096) raw += chunk;
921
+ });
922
+ stream.on("error", (err) => {
923
+ finish(() => reject(new TransientPushError("apns", 0, "network", { cause: err })));
924
+ });
925
+ stream.on("end", () => {
926
+ let reason;
927
+ if (raw) try {
928
+ const parsed = JSON.parse(raw);
929
+ if (typeof parsed.reason === "string") reason = parsed.reason;
930
+ } catch {
931
+ reason = void 0;
932
+ }
933
+ finish(() => resolve({
934
+ status,
935
+ ...apnsId ? { apnsId } : {},
936
+ ...reason ? { reason } : {},
937
+ ...retryAfter !== void 0 ? { retryAfter } : {}
938
+ }));
939
+ });
940
+ stream.end(body);
941
+ });
942
+ }
943
+ const emit = (event, token) => {
944
+ if (!options.onDelivery) return;
945
+ try {
946
+ options.onDelivery({
947
+ provider: "apns",
948
+ tokenSuffix: tokenSuffix(token),
949
+ tokenHash: tokenHash(token),
950
+ ...event
951
+ });
952
+ } catch {}
953
+ };
954
+ async function invalid(token, reason, status) {
955
+ await reportInvalid(options.onInvalidToken, token, reason);
956
+ throw new InvalidPushTokenError("apns", reason, status, tokenSuffix(token));
957
+ }
958
+ function checkMessage(message) {
959
+ if (typeof message.token !== "string" || !DEVICE_TOKEN.test(message.token)) throw new PushRejectedError("apns", 0, "invalid-token-format", "APNs device tokens are hex strings");
960
+ if (collapseKeyTooLong(message.collapseKey)) throw new PushRejectedError("apns", 0, "collapse-key-too-long", "collapseKey exceeds 64 bytes");
961
+ if (message.data && "aps" in message.data) throw new PushRejectedError("apns", 0, "invalid-data", "data.aps is reserved by APNs");
962
+ const body = JSON.stringify(buildApnsPayload(message, options));
963
+ if (Buffer.byteLength(body, "utf8") > MAX_PAYLOAD_BYTES) throw new PushRejectedError("apns", 0, "payload-too-large", "payload exceeds 4096 bytes");
964
+ return body;
965
+ }
966
+ async function sendOnce(message, body, started) {
967
+ const waitMs = cooldown.remaining();
968
+ if (waitMs > 0) throw new TransientPushError("apns", 429, "cooling-down", { retryAfterMs: waitMs });
969
+ const resolved = await resolver.resolve();
970
+ const authority = authorityOf(resolved.creds);
971
+ const values = apnsHeaderValues(message, now());
972
+ for (let attempt = 0; attempt < 2; attempt++) {
973
+ const res = await post(authority, {
974
+ ":method": "POST",
975
+ ":path": `/3/device/${message.token}`,
976
+ authorization: `bearer ${bearer(resolved, attempt > 0)}`,
977
+ "apns-topic": resolved.creds.bundleId,
978
+ "apns-push-type": values.pushType,
979
+ "apns-priority": values.priority,
980
+ ...values.expiration !== void 0 ? { "apns-expiration": values.expiration } : {},
981
+ ...message.collapseKey ? { "apns-collapse-id": message.collapseKey } : {},
982
+ "content-type": "application/json"
983
+ }, body);
984
+ if (res.status === 200) {
985
+ const messageId = res.apnsId ?? "apns";
986
+ emit({
987
+ outcome: "sent",
988
+ status: 200,
989
+ messageId,
990
+ latencyMs: now() - started,
991
+ ...message.platform ? { platform: message.platform } : {}
992
+ }, message.token);
993
+ return { messageId };
994
+ }
995
+ const reason = res.reason ?? String(res.status);
996
+ if (res.status === 410 || res.reason === "Unregistered") return invalid(message.token, "unregistered", res.status);
997
+ if (res.reason === "BadDeviceToken") return invalid(message.token, "bad-device-token", res.status);
998
+ if (res.status === 403) {
999
+ if (res.reason === "ExpiredProviderToken" || res.reason === "InvalidProviderToken") {
1000
+ providerToken = void 0;
1001
+ if (attempt === 0) continue;
1002
+ }
1003
+ throw new PushCredentialsError("apns", `Apple refused the provider token (403 ${reason})`);
1004
+ }
1005
+ if (res.status === 429 || res.status >= 500) {
1006
+ const retryAfterMs = parseRetryAfter(res.retryAfter, now());
1007
+ if (res.reason === "TooManyProviderTokenUpdates") cooldown.hold(retryAfterMs ?? 6e4);
1008
+ else if (res.status >= 500 && retryAfterMs !== void 0) cooldown.hold(retryAfterMs);
1009
+ throw new TransientPushError("apns", res.status, reason, retryAfterMs !== void 0 ? { retryAfterMs } : {});
1010
+ }
1011
+ throw new PushRejectedError("apns", res.status, reason);
1012
+ }
1013
+ /* c8 ignore next */
1014
+ throw new TransientPushError("apns", 0, "unreachable");
1015
+ }
1016
+ return {
1017
+ async send(message) {
1018
+ const started = now();
1019
+ try {
1020
+ const body = checkMessage(message);
1021
+ return await gate(() => sendOnce(message, body, started));
1022
+ } catch (err) {
1023
+ emit({
1024
+ ...failureEvent(err),
1025
+ latencyMs: now() - started,
1026
+ ...message.platform ? { platform: message.platform } : {}
1027
+ }, message.token);
1028
+ throw err;
1029
+ }
1030
+ },
1031
+ async close() {
1032
+ const open = [...sessions.values()];
1033
+ sessions.clear();
1034
+ await Promise.all(open.map(({ session }) => new Promise((resolve) => {
1035
+ if (session.closed || session.destroyed) return resolve();
1036
+ session.on("close", () => resolve());
1037
+ session.close();
1038
+ })));
1039
+ }
1040
+ };
1041
+ }
1042
+
1043
+ //#endregion
1044
+ //#region src/push/router.ts
1045
+ function pushRouter(options) {
1046
+ const table = {
1047
+ ...options.android ? { android: options.android } : {},
1048
+ ...options.ios ? { ios: options.ios } : {},
1049
+ ...options.web ? { web: options.web } : {}
1050
+ };
1051
+ const platforms = Object.keys(table);
1052
+ if (platforms.length === 0) throw new Error("pushRouter: configure at least one platform provider");
1053
+ return {
1054
+ platforms,
1055
+ async send(message) {
1056
+ const platform = message.platform ?? options.defaultPlatform;
1057
+ if (!platform) throw new PushRejectedError("router", 0, "platform-missing", "message.platform is required");
1058
+ const provider = table[platform];
1059
+ if (!provider) throw new PushRejectedError("router", 0, "platform-disabled", `no provider for ${platform}`);
1060
+ return provider.send(message.platform ? message : {
1061
+ ...message,
1062
+ platform
1063
+ });
1064
+ },
1065
+ async close() {
1066
+ const distinct = new Set(Object.values(table));
1067
+ await Promise.all([...distinct].map((p) => p.close?.()));
1068
+ }
1069
+ };
1070
+ }
1071
+
1072
+ //#endregion
1073
+ //#region src/push/payload.ts
1074
+ /**
1075
+ * Opaque id or enum: letters, digits, `_ - . :`, 1 to 64 characters (`task_offer`,
1076
+ * `order.created`, an ObjectId, a UUID). No spaces, so no sentence or name fits.
1077
+ */
1078
+ const OPAQUE_ID = /^[A-Za-z0-9_.:-]{1,64}$/;
1079
+ function check(options, data) {
1080
+ const pattern = options.valuePattern ?? OPAQUE_ID;
1081
+ const allowed = /* @__PURE__ */ new Set(["type", ...options.allowedKeys]);
1082
+ const out = {};
1083
+ for (const [key, value] of Object.entries(data)) {
1084
+ if (value === void 0) continue;
1085
+ if (!allowed.has(key)) throw new PushRejectedError("router", 0, "content-not-allowed", `data.${key} is not allowed in a content-free push`);
1086
+ if (typeof value !== "string" || !pattern.test(value)) throw new PushRejectedError("router", 0, "content-not-allowed", `data.${key} must be an opaque id`);
1087
+ out[key] = value;
1088
+ }
1089
+ if (!out.type) throw new PushRejectedError("router", 0, "content-not-allowed", "data.type is required");
1090
+ if (options.types && !options.types.includes(out.type)) throw new PushRejectedError("router", 0, "content-not-allowed", "data.type is not a known push type");
1091
+ return out;
1092
+ }
1093
+ /**
1094
+ * Build content-free messages. `title` should be GENERIC ("New task offered to you"), already in
1095
+ * the device's language; omit it for a silent data-only push.
1096
+ */
1097
+ function createContentFreeBuilder(options) {
1098
+ return (input) => {
1099
+ const data = check(options, {
1100
+ ...input.refs ?? {},
1101
+ type: input.type
1102
+ });
1103
+ const title = input.title ?? "";
1104
+ return {
1105
+ title,
1106
+ body: "",
1107
+ data,
1108
+ contentAvailable: title === ""
1109
+ };
1110
+ };
1111
+ }
1112
+ /**
1113
+ * Wrap a provider so ONLY content-free messages pass: empty body, no image, data limited to the
1114
+ * allowed keys and opaque values. Anything else is a permanent `PushRejectedError` before any
1115
+ * network call.
1116
+ */
1117
+ function contentFreeOnly(provider, options) {
1118
+ return {
1119
+ async send(message) {
1120
+ if (message.body) throw new PushRejectedError("router", 0, "content-not-allowed", "a content-free push has no body");
1121
+ if (message.imageUrl) throw new PushRejectedError("router", 0, "content-not-allowed", "a content-free push has no image");
1122
+ const data = check(options, message.data ?? {});
1123
+ return provider.send({
1124
+ ...message,
1125
+ data
1126
+ });
1127
+ },
1128
+ ...provider.close ? { close: () => provider.close?.() } : {}
1129
+ };
1130
+ }
1131
+
1132
+ //#endregion
1133
+ export { APNS_HOSTS, APNS_TOKEN_TTL_MS, FCM_ENDPOINT, FCM_SCOPE, GOOGLE_TOKEN_URI, InvalidPushTokenError, OPAQUE_ID, PUSH_RETRY_DEFAULTS, PushCredentialsError, PushRejectedError, TransientPushError, apnsProvider, buildApnsPayload, buildAps, buildFcmMessage, contentFreeOnly, createContentFreeBuilder, credentialsFingerprint, effectiveLevel, fcmProvider, fingerprint, isInvalidPushTokenError, normalizePem, parseFcmServiceAccount, parseRetryAfter, planPushRetry, pushRetryDelay, pushRetryFloorMs, pushRouter, signJwt, tokenHash, tokenSuffix, validateApnsCredentials, validateFcmCredentials };