@cardonjs/notify 0.0.0-stage → 0.1.9

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,8 @@
1
+ import type { Logger } from "@cardonjs/core";
2
+ import type { NotificationChannel } from "./notify.js";
3
+ /**
4
+ * Development channel: validates the message, logs one `info` record with the title length
5
+ * and the tag (never the title, body, url, data or target) and answers `sent`.
6
+ */
7
+ export declare function logChannel<Target = unknown>(logger: Logger): NotificationChannel<Target>;
8
+ //# sourceMappingURL=log-channel.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"log-channel.d.ts","sourceRoot":"","sources":["../src/log-channel.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,gBAAgB,CAAC;AAC7C,OAAO,KAAK,EAAE,mBAAmB,EAAc,MAAM,aAAa,CAAC;AAKnE;;;GAGG;AACH,wBAAgB,UAAU,CAAC,MAAM,GAAG,OAAO,EAAE,MAAM,EAAE,MAAM,GAAG,mBAAmB,CAAC,MAAM,CAAC,CAexF"}
@@ -0,0 +1,23 @@
1
+ import { validMessage } from "./validation.js";
2
+ const SENT = Object.freeze({ status: "sent" });
3
+ /**
4
+ * Development channel: validates the message, logs one `info` record with the title length
5
+ * and the tag (never the title, body, url, data or target) and answers `sent`.
6
+ */
7
+ export function logChannel(logger) {
8
+ if (typeof logger !== "object" || logger === null || typeof logger.info !== "function") {
9
+ throw new TypeError("logChannel: logger must be a Logger.");
10
+ }
11
+ return {
12
+ async send(_target, input) {
13
+ const message = validMessage(input);
14
+ logger.info("notification sent", {
15
+ channel: "log",
16
+ titleLength: [...message.title].length,
17
+ tag: message.tag ?? null,
18
+ });
19
+ return SENT;
20
+ },
21
+ };
22
+ }
23
+ //# sourceMappingURL=log-channel.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"log-channel.js","sourceRoot":"","sources":["../src/log-channel.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAE/C,MAAM,IAAI,GAAe,MAAM,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;AAE3D;;;GAGG;AACH,MAAM,UAAU,UAAU,CAAmB,MAAc;IACzD,IAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,MAAM,KAAK,IAAI,IAAI,OAAO,MAAM,CAAC,IAAI,KAAK,UAAU,EAAE,CAAC;QACvF,MAAM,IAAI,SAAS,CAAC,sCAAsC,CAAC,CAAC;IAC9D,CAAC;IACD,OAAO;QACL,KAAK,CAAC,IAAI,CAAC,OAAO,EAAE,KAAK;YACvB,MAAM,OAAO,GAAG,YAAY,CAAC,KAAK,CAAC,CAAC;YACpC,MAAM,CAAC,IAAI,CAAC,mBAAmB,EAAE;gBAC/B,OAAO,EAAE,KAAK;gBACd,WAAW,EAAE,CAAC,GAAG,OAAO,CAAC,KAAK,CAAC,CAAC,MAAM;gBACtC,GAAG,EAAE,OAAO,CAAC,GAAG,IAAI,IAAI;aACzB,CAAC,CAAC;YACH,OAAO,IAAI,CAAC;QACd,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,33 @@
1
+ /** One notification. Validate it with `assertValidMessage`; every channel does before any I/O. */
2
+ export interface NotificationMessage {
3
+ /** 1 to 120 characters. */
4
+ readonly title: string;
5
+ /** 0 to 500 characters. */
6
+ readonly body: string;
7
+ /** Opened on click: an `https:` URL or a path starting with a single `/`. At most 2000 characters. */
8
+ readonly url?: string;
9
+ /** 1 to 64 of `[A-Za-z0-9_-:.]`. A notification with the same tag replaces the one shown. */
10
+ readonly tag?: string;
11
+ /** Flat: at most 20 keys, each a string, a finite number, a boolean or `null`. */
12
+ readonly data?: Readonly<Record<string, string | number | boolean | null>>;
13
+ }
14
+ export type SendResult = {
15
+ readonly status: "sent";
16
+ }
17
+ /** The target no longer exists: delete it. */
18
+ | {
19
+ readonly status: "gone";
20
+ } | {
21
+ readonly status: "failed";
22
+ readonly retryable: boolean;
23
+ };
24
+ /** Sends one message to one target (a push subscription, an email address, ...). */
25
+ export interface NotificationChannel<Target> {
26
+ /**
27
+ * Never rejects for anything the provider answers or for network failures (that is a
28
+ * `failed` result). Throws `TypeError` only for an invalid message or target built by the
29
+ * server; messages never echo values.
30
+ */
31
+ send(target: Target, message: NotificationMessage): Promise<SendResult>;
32
+ }
33
+ //# sourceMappingURL=notify.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"notify.d.ts","sourceRoot":"","sources":["../src/notify.ts"],"names":[],"mappings":"AAAA,kGAAkG;AAClG,MAAM,WAAW,mBAAmB;IAClC,2BAA2B;IAC3B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,2BAA2B;IAC3B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,sGAAsG;IACtG,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC;IACtB,6FAA6F;IAC7F,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAC;IACtB,kFAAkF;IAClF,QAAQ,CAAC,IAAI,CAAC,EAAE,QAAQ,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,OAAO,GAAG,IAAI,CAAC,CAAC,CAAC;CAC5E;AAED,MAAM,MAAM,UAAU,GAClB;IAAE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;CAAE;AAC7B,8CAA8C;GAC5C;IAAE,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAA;CAAE,GAC3B;IAAE,QAAQ,CAAC,MAAM,EAAE,QAAQ,CAAC;IAAC,QAAQ,CAAC,SAAS,EAAE,OAAO,CAAA;CAAE,CAAC;AAE/D,oFAAoF;AACpF,MAAM,WAAW,mBAAmB,CAAC,MAAM;IACzC;;;;OAIG;IACH,IAAI,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,mBAAmB,GAAG,OAAO,CAAC,UAAU,CAAC,CAAC;CACzE"}
package/dist/notify.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=notify.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"notify.js","sourceRoot":"","sources":["../src/notify.ts"],"names":[],"mappings":""}
@@ -0,0 +1,17 @@
1
+ import type { NotificationMessage } from "./notify.js";
2
+ type TemplateFunction = (data: any) => NotificationMessage;
3
+ export interface Templates<T extends Record<string, TemplateFunction>> {
4
+ /**
5
+ * Renders a template and returns a frozen, validated copy (`validMessage`); an unknown name
6
+ * throws a `TypeError`.
7
+ */
8
+ render<K extends keyof T & string>(name: K, data: Parameters<T[K]>[0]): NotificationMessage;
9
+ }
10
+ /**
11
+ * Typed templates: plain functions from data to a message, not a template engine. Another
12
+ * language is another function. `templates.render("orderReady", data)` returns a validated
13
+ * `NotificationMessage`.
14
+ */
15
+ export declare function defineTemplates<T extends Record<string, TemplateFunction>>(templates: T): Templates<T>;
16
+ export {};
17
+ //# sourceMappingURL=templates.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"templates.d.ts","sourceRoot":"","sources":["../src/templates.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAIvD,KAAK,gBAAgB,GAAG,CAAC,IAAI,EAAE,GAAG,KAAK,mBAAmB,CAAC;AAE3D,MAAM,WAAW,SAAS,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC;IACnE;;;OAGG;IACH,MAAM,CAAC,CAAC,SAAS,MAAM,CAAC,GAAG,MAAM,EAAE,IAAI,EAAE,CAAC,EAAE,IAAI,EAAE,UAAU,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,mBAAmB,CAAC;CAC7F;AAED;;;;GAIG;AACH,wBAAgB,eAAe,CAAC,CAAC,SAAS,MAAM,CAAC,MAAM,EAAE,gBAAgB,CAAC,EACxE,SAAS,EAAE,CAAC,GACX,SAAS,CAAC,CAAC,CAAC,CAqBd"}
@@ -0,0 +1,30 @@
1
+ import { validMessage } from "./validation.js";
2
+ /**
3
+ * Typed templates: plain functions from data to a message, not a template engine. Another
4
+ * language is another function. `templates.render("orderReady", data)` returns a validated
5
+ * `NotificationMessage`.
6
+ */
7
+ export function defineTemplates(templates) {
8
+ if (typeof templates !== "object" || templates === null || Array.isArray(templates)) {
9
+ throw new TypeError("defineTemplates: templates must be an object of functions.");
10
+ }
11
+ // Copied once: later changes to the object do not change the templates.
12
+ const table = new Map();
13
+ for (const [name, template] of Object.entries(templates)) {
14
+ if (typeof template !== "function") {
15
+ throw new TypeError("defineTemplates: every template must be a function.");
16
+ }
17
+ table.set(name, template);
18
+ }
19
+ return {
20
+ render(name, data) {
21
+ const template = typeof name === "string" ? table.get(name) : undefined;
22
+ // The name is not echoed: it may come from stored data.
23
+ if (template === undefined)
24
+ throw new TypeError("defineTemplates: unknown template.");
25
+ // A frozen, validated copy of what the template returned.
26
+ return validMessage(template(data));
27
+ },
28
+ };
29
+ }
30
+ //# sourceMappingURL=templates.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"templates.js","sourceRoot":"","sources":["../src/templates.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AAa/C;;;;GAIG;AACH,MAAM,UAAU,eAAe,CAC7B,SAAY;IAEZ,IAAI,OAAO,SAAS,KAAK,QAAQ,IAAI,SAAS,KAAK,IAAI,IAAI,KAAK,CAAC,OAAO,CAAC,SAAS,CAAC,EAAE,CAAC;QACpF,MAAM,IAAI,SAAS,CAAC,4DAA4D,CAAC,CAAC;IACpF,CAAC;IACD,wEAAwE;IACxE,MAAM,KAAK,GAAG,IAAI,GAAG,EAA4B,CAAC;IAClD,KAAK,MAAM,CAAC,IAAI,EAAE,QAAQ,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,SAAS,CAAC,EAAE,CAAC;QACzD,IAAI,OAAO,QAAQ,KAAK,UAAU,EAAE,CAAC;YACnC,MAAM,IAAI,SAAS,CAAC,qDAAqD,CAAC,CAAC;QAC7E,CAAC;QACD,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,QAAQ,CAAC,CAAC;IAC5B,CAAC;IACD,OAAO;QACL,MAAM,CAAC,IAAI,EAAE,IAAI;YACf,MAAM,QAAQ,GAAG,OAAO,IAAI,KAAK,QAAQ,CAAC,CAAC,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC;YACxE,wDAAwD;YACxD,IAAI,QAAQ,KAAK,SAAS;gBAAE,MAAM,IAAI,SAAS,CAAC,oCAAoC,CAAC,CAAC;YACtF,0DAA0D;YAC1D,OAAO,YAAY,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,CAAC;QACtC,CAAC;KACF,CAAC;AACJ,CAAC"}
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Test-only in-memory channel. Import it from `@cardonjs/notify/testing`; never use it in
3
+ * production.
4
+ */
5
+ import type { NotificationChannel, NotificationMessage } from "./notify.js";
6
+ export interface SentNotification<Target> {
7
+ readonly target: Target;
8
+ readonly message: NotificationMessage;
9
+ }
10
+ export interface MemoryChannelOptions<Target> {
11
+ /**
12
+ * What identifies a target for `markGone`. Default: the target itself (compared like `Set`
13
+ * keys: the same object or primitive). Use e.g. `(s) => s.endpoint` so a row reloaded from
14
+ * storage matches the one marked gone.
15
+ */
16
+ readonly key?: (target: Target) => unknown;
17
+ }
18
+ export interface MemoryChannel<Target> extends NotificationChannel<Target> {
19
+ /** Every message delivered (`sent`), oldest first. Copies: changing them changes nothing. */
20
+ sent(): SentNotification<Target>[];
21
+ /** From now on, sends to this target (by `key`) answer `gone`. */
22
+ markGone(target: Target): void;
23
+ /** The next send to a live target answers `failed` with this `retryable` (queued, one per call). */
24
+ failNext(retryable: boolean): void;
25
+ /** How many sends reached the "provider" (passed validation): sent, gone or failed. */
26
+ attempts(): number;
27
+ }
28
+ /**
29
+ * **Test-only.** A channel that records what it delivers. `undefined` and `null` targets are a
30
+ * `TypeError` (a missing target is always a bug); any other value is a target.
31
+ */
32
+ export declare function memoryChannel<Target>(options?: MemoryChannelOptions<Target>): MemoryChannel<Target>;
33
+ //# sourceMappingURL=testing.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testing.d.ts","sourceRoot":"","sources":["../src/testing.ts"],"names":[],"mappings":"AAAA;;;GAGG;AACH,OAAO,KAAK,EAAE,mBAAmB,EAAE,mBAAmB,EAAc,MAAM,aAAa,CAAC;AAGxF,MAAM,WAAW,gBAAgB,CAAC,MAAM;IACtC,QAAQ,CAAC,MAAM,EAAE,MAAM,CAAC;IACxB,QAAQ,CAAC,OAAO,EAAE,mBAAmB,CAAC;CACvC;AAED,MAAM,WAAW,oBAAoB,CAAC,MAAM;IAC1C;;;;OAIG;IACH,QAAQ,CAAC,GAAG,CAAC,EAAE,CAAC,MAAM,EAAE,MAAM,KAAK,OAAO,CAAC;CAC5C;AAED,MAAM,WAAW,aAAa,CAAC,MAAM,CAAE,SAAQ,mBAAmB,CAAC,MAAM,CAAC;IACxE,6FAA6F;IAC7F,IAAI,IAAI,gBAAgB,CAAC,MAAM,CAAC,EAAE,CAAC;IACnC,kEAAkE;IAClE,QAAQ,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IAC/B,oGAAoG;IACpG,QAAQ,CAAC,SAAS,EAAE,OAAO,GAAG,IAAI,CAAC;IACnC,uFAAuF;IACvF,QAAQ,IAAI,MAAM,CAAC;CACpB;AAKD;;;GAGG;AACH,wBAAgB,aAAa,CAAC,MAAM,EAClC,OAAO,GAAE,oBAAoB,CAAC,MAAM,CAAM,GACzC,aAAa,CAAC,MAAM,CAAC,CAiCvB"}
@@ -0,0 +1,44 @@
1
+ import { validMessage } from "./validation.js";
2
+ const SENT = Object.freeze({ status: "sent" });
3
+ const GONE = Object.freeze({ status: "gone" });
4
+ /**
5
+ * **Test-only.** A channel that records what it delivers. `undefined` and `null` targets are a
6
+ * `TypeError` (a missing target is always a bug); any other value is a target.
7
+ */
8
+ export function memoryChannel(options = {}) {
9
+ const key = options.key ?? ((target) => target);
10
+ if (typeof key !== "function")
11
+ throw new TypeError("memoryChannel: key must be a function.");
12
+ const delivered = [];
13
+ const gone = new Set();
14
+ const failures = [];
15
+ let attempts = 0;
16
+ return {
17
+ async send(target, input) {
18
+ const message = validMessage(input);
19
+ if (target === undefined || target === null) {
20
+ throw new TypeError("memoryChannel: the target is required.");
21
+ }
22
+ attempts++;
23
+ if (gone.has(key(target)))
24
+ return GONE;
25
+ const retryable = failures.shift();
26
+ if (retryable !== undefined)
27
+ return Object.freeze({ status: "failed", retryable });
28
+ delivered.push(Object.freeze({ target, message }));
29
+ return SENT;
30
+ },
31
+ sent: () => delivered.map(({ target, message }) => ({ target, message: structuredClone(message) })),
32
+ markGone(target) {
33
+ gone.add(key(target));
34
+ },
35
+ failNext(retryable) {
36
+ if (typeof retryable !== "boolean") {
37
+ throw new TypeError("memoryChannel: failNext takes a boolean.");
38
+ }
39
+ failures.push(retryable);
40
+ },
41
+ attempts: () => attempts,
42
+ };
43
+ }
44
+ //# sourceMappingURL=testing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testing.js","sourceRoot":"","sources":["../src/testing.ts"],"names":[],"mappings":"AAKA,OAAO,EAAE,YAAY,EAAE,MAAM,iBAAiB,CAAC;AA2B/C,MAAM,IAAI,GAAe,MAAM,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;AAC3D,MAAM,IAAI,GAAe,MAAM,CAAC,MAAM,CAAC,EAAE,MAAM,EAAE,MAAM,EAAE,CAAC,CAAC;AAE3D;;;GAGG;AACH,MAAM,UAAU,aAAa,CAC3B,OAAO,GAAiC,EAAE;IAE1C,MAAM,GAAG,GAAG,OAAO,CAAC,GAAG,IAAI,CAAC,CAAC,MAAc,EAAW,EAAE,CAAC,MAAM,CAAC,CAAC;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,SAAS;YAChB,IAAI,OAAO,SAAS,KAAK,SAAS,EAAE,CAAC;gBACnC,MAAM,IAAI,SAAS,CAAC,0CAA0C,CAAC,CAAC;YAClE,CAAC;YACD,QAAQ,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;QAC3B,CAAC;QACD,QAAQ,EAAE,GAAG,EAAE,CAAC,QAAQ;KACzB,CAAC;AACJ,CAAC"}
@@ -0,0 +1,24 @@
1
+ import type { NotificationMessage } from "./notify.js";
2
+ export declare const MAX_TITLE_LENGTH = 120;
3
+ export declare const MAX_BODY_LENGTH = 500;
4
+ export declare const MAX_URL_LENGTH = 2000;
5
+ export declare const MAX_DATA_KEYS = 20;
6
+ /** UTF-8 bytes of the message JSON (`{ title, body, url, tag, data }`). */
7
+ export declare const MAX_MESSAGE_BYTES = 3000;
8
+ /**
9
+ * A frozen, normalised copy of a valid {@link NotificationMessage}, or a `TypeError`. The rules:
10
+ * only the five fields, title 1-120 (not blank) and body 0-500 characters (code points,
11
+ * well-formed strings), a safe `url`, a `tag` of `[A-Za-z0-9_-:.]`, flat `data` with at most
12
+ * 20 keys, and at most 3000 bytes of JSON. Each property is read once and only the copy is
13
+ * checked, so a getter or a Proxy cannot change the message after validation: channels send the
14
+ * copy. Absent fields are omitted; `data` is copied and frozen. The error message names the
15
+ * rule, never the value.
16
+ */
17
+ export declare function validMessage(message: unknown): NotificationMessage;
18
+ /**
19
+ * Throws a `TypeError` unless `message` is a valid {@link NotificationMessage} (the rules of
20
+ * {@link validMessage}, which it calls). A type guard; to send, use the copy `validMessage`
21
+ * returns.
22
+ */
23
+ export declare function assertValidMessage(message: unknown): asserts message is NotificationMessage;
24
+ //# sourceMappingURL=validation.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validation.d.ts","sourceRoot":"","sources":["../src/validation.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,aAAa,CAAC;AAEvD,eAAO,MAAM,gBAAgB,MAAM,CAAC;AACpC,eAAO,MAAM,eAAe,MAAM,CAAC;AACnC,eAAO,MAAM,cAAc,OAAO,CAAC;AACnC,eAAO,MAAM,aAAa,KAAK,CAAC;AAChC,2EAA2E;AAC3E,eAAO,MAAM,iBAAiB,OAAO,CAAC;AAuGtC;;;;;;;;GAQG;AACH,wBAAgB,YAAY,CAAC,OAAO,EAAE,OAAO,GAAG,mBAAmB,CAkClE;AAED;;;;GAIG;AACH,wBAAgB,kBAAkB,CAAC,OAAO,EAAE,OAAO,GAAG,OAAO,CAAC,OAAO,IAAI,mBAAmB,CAE3F"}
@@ -0,0 +1,175 @@
1
+ import { isLocalHttpUrl } from "@cardonjs/core";
2
+ export const MAX_TITLE_LENGTH = 120;
3
+ export const MAX_BODY_LENGTH = 500;
4
+ export const MAX_URL_LENGTH = 2000;
5
+ export const MAX_DATA_KEYS = 20;
6
+ /** UTF-8 bytes of the message JSON (`{ title, body, url, tag, data }`). */
7
+ export const MAX_MESSAGE_BYTES = 3000;
8
+ const FIELDS = new Set(["title", "body", "url", "tag", "data"]);
9
+ const TAG = /^[A-Za-z0-9_\-:.]{1,64}$/;
10
+ /** C0 controls, DEL and C1 controls. */
11
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: the point is to find them.
12
+ const CONTROL = /[\u0000-\u001f\u007f-\u009f]/;
13
+ const WEB_PREFIX = /^https?:\/\//i;
14
+ const BASE = "https://base.invalid";
15
+ const encoder = new TextEncoder();
16
+ function invalid(problem) {
17
+ throw new TypeError(`Invalid notification message: ${problem}.`);
18
+ }
19
+ function isPlainObject(value) {
20
+ if (typeof value !== "object" || value === null || Array.isArray(value))
21
+ return false;
22
+ const proto = Object.getPrototypeOf(value);
23
+ return proto === Object.prototype || proto === null;
24
+ }
25
+ /** No lone surrogates: they cannot be encoded as UTF-8 and would not arrive intact. */
26
+ function isWellFormed(value) {
27
+ for (let i = 0; i < value.length; i++) {
28
+ const code = value.charCodeAt(i);
29
+ if (code >= 0xd800 && code <= 0xdbff) {
30
+ const next = value.charCodeAt(i + 1);
31
+ if (!(next >= 0xdc00 && next <= 0xdfff))
32
+ return false;
33
+ i++;
34
+ }
35
+ else if (code >= 0xdc00 && code <= 0xdfff) {
36
+ return false;
37
+ }
38
+ }
39
+ return true;
40
+ }
41
+ /** Length in Unicode code points (an emoji outside the BMP counts once). */
42
+ function codePoints(value) {
43
+ let count = 0;
44
+ for (const _ of value)
45
+ count++;
46
+ return count;
47
+ }
48
+ function text(value, field, min, max) {
49
+ if (typeof value !== "string" || !isWellFormed(value)) {
50
+ invalid(`${field} must be a well-formed string`);
51
+ }
52
+ const length = codePoints(value);
53
+ if (length < min || length > max)
54
+ invalid(`${field} must be ${min} to ${max} characters`);
55
+ return value;
56
+ }
57
+ /**
58
+ * An `https:` URL (without credentials), an `http:` URL on a local development host
59
+ * (`localhost`, `127.0.0.1`, `[::1]`; see `isLocalDevelopmentHost`), or a path starting with a
60
+ * single `/`. Never `javascript:`, `data:`, `http:` on any other host or a protocol-relative
61
+ * `//host` (nor `/\host`, which browsers read the same way).
62
+ */
63
+ function isMessageUrl(value) {
64
+ if (value.length === 0 || value.length > MAX_URL_LENGTH || CONTROL.test(value))
65
+ return false;
66
+ if (value.startsWith("/")) {
67
+ if (value.startsWith("//") || value.includes("\\"))
68
+ return false;
69
+ try {
70
+ return new URL(value, BASE).origin === BASE;
71
+ }
72
+ catch {
73
+ return false;
74
+ }
75
+ }
76
+ if (!WEB_PREFIX.test(value))
77
+ return false;
78
+ try {
79
+ const url = new URL(value);
80
+ if (url.username !== "" || url.password !== "")
81
+ return false;
82
+ return url.protocol === "https:" || isLocalHttpUrl(value);
83
+ }
84
+ catch {
85
+ return false;
86
+ }
87
+ }
88
+ /** A frozen copy of flat `data`, each key and value read once. */
89
+ function dataOf(value) {
90
+ if (!isPlainObject(value))
91
+ invalid("data must be a plain object");
92
+ if (Object.getOwnPropertySymbols(value).length > 0)
93
+ invalid("data keys must be strings");
94
+ const keys = Object.keys(value);
95
+ if (keys.length > MAX_DATA_KEYS)
96
+ invalid(`data must have at most ${MAX_DATA_KEYS} keys`);
97
+ const entries = [];
98
+ for (const key of keys) {
99
+ if (!isWellFormed(key))
100
+ invalid("data keys must be well-formed strings");
101
+ const entry = value[key];
102
+ if (typeof entry === "string") {
103
+ if (!isWellFormed(entry))
104
+ invalid("data values must be well-formed strings");
105
+ }
106
+ else if (typeof entry === "number") {
107
+ if (!Number.isFinite(entry))
108
+ invalid("data numbers must be finite");
109
+ }
110
+ else if (typeof entry !== "boolean" && entry !== null) {
111
+ invalid("data values must be strings, numbers, booleans or null (flat)");
112
+ }
113
+ entries.push([key, entry]);
114
+ }
115
+ // `fromEntries` defines own properties, so a "__proto__" key stays a plain key.
116
+ return Object.freeze(Object.fromEntries(entries));
117
+ }
118
+ /**
119
+ * A frozen, normalised copy of a valid {@link NotificationMessage}, or a `TypeError`. The rules:
120
+ * only the five fields, title 1-120 (not blank) and body 0-500 characters (code points,
121
+ * well-formed strings), a safe `url`, a `tag` of `[A-Za-z0-9_-:.]`, flat `data` with at most
122
+ * 20 keys, and at most 3000 bytes of JSON. Each property is read once and only the copy is
123
+ * checked, so a getter or a Proxy cannot change the message after validation: channels send the
124
+ * copy. Absent fields are omitted; `data` is copied and frozen. The error message names the
125
+ * rule, never the value.
126
+ */
127
+ export function validMessage(message) {
128
+ if (!isPlainObject(message))
129
+ invalid("it must be a plain object");
130
+ if (Object.getOwnPropertySymbols(message).length > 0)
131
+ invalid("it has an unknown field");
132
+ for (const key of Object.keys(message)) {
133
+ if (!FIELDS.has(key))
134
+ invalid("it has an unknown field");
135
+ }
136
+ const rawTitle = message.title;
137
+ const rawBody = message.body;
138
+ const url = message.url;
139
+ const tag = message.tag;
140
+ const rawData = message.data;
141
+ const title = text(rawTitle, "title", 1, MAX_TITLE_LENGTH);
142
+ if (title.trim() === "")
143
+ invalid("title must not be blank");
144
+ const body = text(rawBody, "body", 0, MAX_BODY_LENGTH);
145
+ if (url !== undefined && (typeof url !== "string" || !isMessageUrl(url))) {
146
+ invalid("url must be an https URL, an http URL on localhost, or a path starting with a single /");
147
+ }
148
+ if (tag !== undefined && (typeof tag !== "string" || !TAG.test(tag))) {
149
+ invalid("tag must be 1 to 64 of A-Z, a-z, 0-9, _, -, : and .");
150
+ }
151
+ const data = rawData === undefined ? undefined : dataOf(rawData);
152
+ const copy = {
153
+ title,
154
+ body,
155
+ };
156
+ if (url !== undefined)
157
+ copy.url = url;
158
+ if (tag !== undefined)
159
+ copy.tag = tag;
160
+ if (data !== undefined)
161
+ copy.data = data;
162
+ if (encoder.encode(JSON.stringify(copy)).length > MAX_MESSAGE_BYTES) {
163
+ invalid(`its JSON must be at most ${MAX_MESSAGE_BYTES} bytes`);
164
+ }
165
+ return Object.freeze(copy);
166
+ }
167
+ /**
168
+ * Throws a `TypeError` unless `message` is a valid {@link NotificationMessage} (the rules of
169
+ * {@link validMessage}, which it calls). A type guard; to send, use the copy `validMessage`
170
+ * returns.
171
+ */
172
+ export function assertValidMessage(message) {
173
+ validMessage(message);
174
+ }
175
+ //# sourceMappingURL=validation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"validation.js","sourceRoot":"","sources":["../src/validation.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,cAAc,EAAE,MAAM,gBAAgB,CAAC;AAGhD,MAAM,CAAC,MAAM,gBAAgB,GAAG,GAAG,CAAC;AACpC,MAAM,CAAC,MAAM,eAAe,GAAG,GAAG,CAAC;AACnC,MAAM,CAAC,MAAM,cAAc,GAAG,IAAI,CAAC;AACnC,MAAM,CAAC,MAAM,aAAa,GAAG,EAAE,CAAC;AAChC,2EAA2E;AAC3E,MAAM,CAAC,MAAM,iBAAiB,GAAG,IAAI,CAAC;AAEtC,MAAM,MAAM,GAAwB,IAAI,GAAG,CAAC,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,KAAK,EAAE,MAAM,CAAC,CAAC,CAAC;AACrF,MAAM,GAAG,GAAG,0BAA0B,CAAC;AACvC,wCAAwC;AACxC,s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AE,MAAM,EAAE,CAAC,EAAE,eAAe,CAAC,CAAC;IACvD,IAAI,GAAG,KAAK,SAAS,IAAI,CAAC,OAAO,GAAG,KAAK,QAAQ,IAAI,CAAC,YAAY,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC;QACzE,OAAO,CACL,wFAAwF,CACzF,CAAC;IACJ,CAAC;IACD,IAAI,GAAG,KAAK,SAAS,IAAI,CAAC,OAAO,GAAG,KAAK,QAAQ,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,CAAC;QACrE,OAAO,CAAC,qDAAqD,CAAC,CAAC;IACjE,CAAC;IACD,MAAM,IAAI,GAAG,OAAO,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,MAAM,CAAC,OAAO,CAAC,CAAC;IACjE,MAAM,IAAI,GAA2E;QACnF,KAAK;QACL,IAAI;KACL,CAAC;IACF,IAAI,GAAG,KAAK,SAAS;QAAE,IAAI,CAAC,GAAG,GAAG,GAAa,CAAC;IAChD,IAAI,GAAG,KAAK,SAAS;QAAE,IAAI,CAAC,GAAG,GAAG,GAAa,CAAC;IAChD,IAAI,IAAI,KAAK,SAAS;QAAE,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;IACzC,IAAI,OAAO,CAAC,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,MAAM,GAAG,iBAAiB,EAAE,CAAC;QACpE,OAAO,CAAC,4BAA4B,iBAAiB,QAAQ,CAAC,CAAC;IACjE,CAAC;IACD,OAAO,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;AAC7B,CAAC;AAED;;;;GAIG;AACH,MAAM,UAAU,kBAAkB,CAAC,OAAgB;IACjD,YAAY,CAAC,OAAO,CAAC,CAAC;AACxB,CAAC"}
package/llms.txt ADDED
@@ -0,0 +1,161 @@
1
+ # @cardonjs/notify
2
+
3
+ The notifications interface of Cardón: the `NotificationChannel` type every notification adapter
4
+ returns (one message to one target), the message checks every channel runs before any I/O, typed
5
+ templates, a development channel that only logs, the shared contract suite for adapters and a
6
+ test-only in-memory channel. Adapters such as `@cardonjs/notify-webpush` build the channel; business
7
+ logic receives it through the context and never touches a provider SDK. Standard web APIs only
8
+ (Workers, Node, Bun, Deno); it does not depend on `hono`.
9
+
10
+ Full documentation: README.md in this package.
11
+
12
+ ## Install
13
+
14
+ ```sh
15
+ pnpm add @cardonjs/notify @cardonjs/core
16
+ ```
17
+
18
+ `@cardonjs/core` is a required peer (`Logger`). `@cardonjs/testing` is an optional peer, only needed by
19
+ `@cardonjs/notify/contract` (in adapter tests): `pnpm add -D @cardonjs/testing`.
20
+
21
+ ## Exports
22
+
23
+ ### `@cardonjs/notify`
24
+
25
+ - `validMessage(message: unknown): NotificationMessage`: returns a frozen, normalised copy of the
26
+ message, or throws a `TypeError` (which never echoes the value) when it breaks the rules below.
27
+ - `assertValidMessage(message: unknown): asserts message is NotificationMessage`: the same check
28
+ as a TypeScript type guard.
29
+ - `defineTemplates(templates)`: takes an object of functions `(data) => NotificationMessage` and
30
+ returns `Templates<T>` with `render(name, data)`. `render` is typed by name and data, returns
31
+ the frozen copy from `validMessage`, and throws a `TypeError` for an unknown name (not echoed).
32
+ - `logChannel<Target = unknown>(logger: Logger): NotificationChannel<Target>`: development
33
+ channel. Validates the message, logs one `info` record with the title length and the tag only,
34
+ and answers `sent`.
35
+ - `MAX_TITLE_LENGTH` (120), `MAX_BODY_LENGTH` (500), `MAX_URL_LENGTH` (2000), `MAX_DATA_KEYS`
36
+ (20), `MAX_MESSAGE_BYTES` (3000): the message limits.
37
+ - Types: `NotificationChannel<Target>`, `NotificationMessage`, `SendResult`, `Templates<T>`.
38
+
39
+ `NotificationChannel<Target>` has one method:
40
+ `send(target: Target, message: NotificationMessage): Promise<SendResult>`.
41
+
42
+ `SendResult` is `{ status: "sent" }`, `{ status: "gone" }` (the target no longer exists: delete
43
+ it) or `{ status: "failed"; retryable: boolean }`.
44
+
45
+ `NotificationMessage` fields (only these five are allowed):
46
+
47
+ - `title: string`: 1..120 characters, not blank.
48
+ - `body: string`: 0..500 characters (required, may be empty).
49
+ - `url?: string`: opened on click. An `https:` URL without credentials, or a path starting with a
50
+ single `/` (not `//host` nor `/\host`); no control characters; at most 2000 characters.
51
+ - `tag?: string`: 1..64 of `[A-Za-z0-9_-:.]`; replaces a shown notification with the same tag.
52
+ - `data?: Record<string, string | number | boolean | null>`: flat, at most 20 keys.
53
+
54
+ Characters are counted as Unicode code points, strings must be well-formed (no lone surrogates),
55
+ and the JSON `{ title, body, url, tag, data }` must be at most 3000 UTF-8 bytes.
56
+
57
+ ### `@cardonjs/notify/contract`
58
+
59
+ Needs `@cardonjs/testing`. For adapter tests only.
60
+
61
+ - `channelContract`: `readonly ContractCase<ChannelContractHarness<unknown>>[]`, the shared cases
62
+ every `NotificationChannel` adapter must pass. Each case has `name` and `run(harness)`; run them
63
+ with the adapter's own test runner.
64
+ - `GONE_CASE`: the name of the gone case, which passes without checking anything when
65
+ `goneTarget` is `null`; report it as skipped (`it.skip(GONE_CASE, ...)`) in that case.
66
+ - Type `ChannelContractHarness<Target>`: `create()` (the channel, called once per case),
67
+ `liveTarget()` (resolves `{ target, received() }`, where `received()` resolves the decoded
68
+ messages the provider got), `goneTarget` (a function resolving a gone target, or `null` when the
69
+ provider never reports gone while sending), `undelivered?` (optional fields the channel does not
70
+ deliver by design, only `"url"`, `"tag"`, `"data"`; anything else fails every case), `failingTargets()` (resolves a non-empty
71
+ `{ target, retryable }[]`), `invalidTargets()` (non-empty `unknown[]`), `attempts()` (how many
72
+ requests the provider has received so far, for all targets).
73
+
74
+ ### `@cardonjs/notify/testing`
75
+
76
+ - `memoryChannel<Target>(options?: MemoryChannelOptions<Target>): MemoryChannel<Target>`: a
77
+ test-only in-memory channel that records what it delivers. On top of `send` it has `sent()` (every
78
+ delivered `{ target, message }`, oldest first, as copies), `markGone(target)` (sends to that
79
+ target answer `gone` from now on), `failNext(retryable)` (the next send to a live target answers
80
+ `failed` with that `retryable`; queued, one per call) and `attempts()` (sends that passed
81
+ validation: sent, gone or failed).
82
+ - Option `key?: (target) => unknown`: what identifies a target for `markGone`. Default: the target
83
+ itself, compared like `Set` keys.
84
+ - Types: `MemoryChannel<Target>`, `MemoryChannelOptions<Target>`, `SentNotification<Target>`.
85
+
86
+ ## Minimal example
87
+
88
+ ```ts
89
+ import {
90
+ defineTemplates,
91
+ type NotificationChannel,
92
+ type NotificationMessage,
93
+ } from "@cardonjs/notify";
94
+
95
+ export const templates = defineTemplates({
96
+ orderReady: (data: { orderId: string; store: string }) => ({
97
+ title: "Your order is ready",
98
+ body: `Pick it up at ${data.store}.`,
99
+ url: `/orders/${data.orderId}`,
100
+ tag: `order-${data.orderId}`,
101
+ }),
102
+ });
103
+
104
+ /** Sends to every target; deletes the gone ones. Returns how many were sent. */
105
+ export async function sendToAll<Target>(
106
+ channel: NotificationChannel<Target>,
107
+ targets: readonly Target[],
108
+ message: NotificationMessage,
109
+ removeGone: (target: Target) => Promise<void>,
110
+ ): Promise<{ sent: number; failed: number }> {
111
+ let sent = 0;
112
+ let failed = 0;
113
+ for (const target of targets) {
114
+ const result = await channel.send(target, message);
115
+ if (result.status === "sent") sent++;
116
+ else if (result.status === "gone") await removeGone(target);
117
+ else failed++;
118
+ }
119
+ return { sent, failed };
120
+ }
121
+
122
+ // Typed: the name must exist and the data must match it.
123
+ const message = templates.render("orderReady", { orderId: "1001", store: "Centro" });
124
+ ```
125
+
126
+ ## Rules and common mistakes
127
+
128
+ - `send` never rejects for a provider answer or a network failure: read the `SendResult`. It
129
+ throws a `TypeError` only for an invalid message or target, which is a bug in the server.
130
+ - Delete the target on `gone`. `failed` carries `retryable`: try again later, or give up.
131
+ - Never put secrets in `title`, `body`, `tag` or `data`: they are shown on a lock screen, stored
132
+ by the provider or logged. Send an id and let the app load the details. The one exception is
133
+ a single-use link in `url` on a channel that delivers privately to one person (email).
134
+ - Build `url` from your own routes, never from client input. `javascript:` and `data:` are
135
+ never accepted; `http:` only for a canonical loopback origin (`isLocalHttpUrl(value)`:
136
+ starts with exactly `http://localhost`, `http://127.0.0.1` or `http://[::1]`, optional port,
137
+ then end or `/?#`; `127.1`, `LOCALHOST` and the like are refused), in every environment. The
138
+ link still travels through the provider like any other; refuse loopback origins outside
139
+ development in your app. Every channel must accept such a URL (the contract checks it).
140
+ - `isLocalHttpUrl(value: string)` and `isLocalDevelopmentHost(hostname)` are re-exported from
141
+ `@cardonjs/core`: the rule of message URLs and of the `@cardonjs/users` and `@cardonjs/notify-email`
142
+ options. Give `isLocalHttpUrl` the raw string you will use.
143
+ - `validMessage` returns a copy and reads each property exactly once: send the copy, not the
144
+ original object.
145
+ - `memoryChannel` is test-only: never use it in production. `undefined` and `null` targets are a
146
+ `TypeError`. Pass `memoryChannel({ key: (s) => s.endpoint })` so a row reloaded from storage
147
+ matches the one marked gone.
148
+ - `logChannel` is for development, where there are no provider keys yet. It never logs the title,
149
+ body, url, data or target.
150
+ - An adapter calls `validMessage` first and uses only the copy, checks its target before any I/O,
151
+ makes exactly one provider request per valid send (no internal retries), maps every provider
152
+ answer and network failure to a `SendResult`, and must pass `channelContract`.
153
+
154
+ ## Out of scope
155
+
156
+ - No retries, no outbox, no preferences: a channel sends once. Retrying `failed` results comes
157
+ with background jobs.
158
+ - No storage of targets: who the targets of a user are (stored push subscriptions, a verified
159
+ email) is your data, not the channel's.
160
+ - No template engine: templates are plain typed functions; another language is another function.
161
+ - No provider implementation: that is an adapter such as `@cardonjs/notify-webpush`.