@hamur/notifications 0.0.0-stage → 0.0.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 (45) hide show
  1. package/LICENSE +22 -0
  2. package/README.md +14 -2
  3. package/dist/src/index.js +235 -0
  4. package/dist/src/server/index.js +282 -0
  5. package/dist/src/test.js +32 -0
  6. package/dist/types/src/build/scan.d.ts +27 -0
  7. package/dist/types/src/build/setup.d.ts +4 -0
  8. package/dist/types/src/index.d.ts +11 -0
  9. package/dist/types/src/module.d.ts +3 -0
  10. package/dist/types/src/options.d.ts +9 -0
  11. package/dist/types/src/server/broadcast.d.ts +6 -0
  12. package/dist/types/src/server/deliver.d.ts +27 -0
  13. package/dist/types/src/server/inbox.d.ts +23 -0
  14. package/dist/types/src/server/index.d.ts +17 -0
  15. package/dist/types/src/server/notify.d.ts +20 -0
  16. package/dist/types/src/server/queue.d.ts +7 -0
  17. package/dist/types/src/server/recipient.d.ts +2 -0
  18. package/dist/types/src/server/record.d.ts +3 -0
  19. package/dist/types/src/server/runtime.d.ts +6 -0
  20. package/dist/types/src/server/task.d.ts +4 -0
  21. package/dist/types/src/server/topic.d.ts +3 -0
  22. package/dist/types/src/server/webhook.d.ts +10 -0
  23. package/dist/types/src/test.d.ts +5 -0
  24. package/dist/types/src/types.d.ts +87 -0
  25. package/package.json +42 -4
  26. package/src/build/scan.ts +119 -0
  27. package/src/build/setup.ts +111 -0
  28. package/src/env.d.ts +26 -0
  29. package/src/index.ts +13 -0
  30. package/src/module.ts +11 -0
  31. package/src/options.ts +52 -0
  32. package/src/server/broadcast.ts +9 -0
  33. package/src/server/deliver.ts +57 -0
  34. package/src/server/inbox.ts +121 -0
  35. package/src/server/index.ts +74 -0
  36. package/src/server/notify.ts +127 -0
  37. package/src/server/queue.ts +22 -0
  38. package/src/server/recipient.ts +10 -0
  39. package/src/server/record.ts +16 -0
  40. package/src/server/runtime.ts +42 -0
  41. package/src/server/task.ts +14 -0
  42. package/src/server/topic.ts +18 -0
  43. package/src/server/webhook.ts +71 -0
  44. package/src/test.ts +35 -0
  45. package/src/types.ts +93 -0
@@ -0,0 +1,27 @@
1
+ import type { MailMessage } from "@hamur/mail";
2
+ import type { Logger } from "hamur/server";
3
+ import type { Delivery, DeliveryRecord, NotificationOptions, Recipient, WebhookTarget } from "../types.ts";
4
+ import type { openTopic } from "./broadcast.ts";
5
+ import type { Inbox } from "./inbox.ts";
6
+ /** What performing a delivery takes. */
7
+ export interface DeliverDeps {
8
+ /** The definition of a notification; rejects for an unknown name. */
9
+ load: (name: string) => Promise<NotificationOptions<unknown, unknown>>;
10
+ deliverMail: (message: MailMessage, delivery: {
11
+ id: string;
12
+ site?: string;
13
+ queued: boolean;
14
+ }, log: Pick<Logger, "error">) => Promise<Error | undefined>;
15
+ storeRow: Inbox["add"];
16
+ /** Rejects for a recipient that can have no topic. */
17
+ openTopic: (to: Recipient) => Promise<ReturnType<typeof openTopic>>;
18
+ /** `notifications.webhook`. */
19
+ webhook?: WebhookTarget;
20
+ postWebhook: (target: WebhookTarget, id: string, body: string) => Promise<void>;
21
+ /** Set in a test build. */
22
+ record?: (delivery: DeliveryRecord) => Promise<void>;
23
+ }
24
+ /** `webhook to Tenant::"9"`. */
25
+ export declare const shownDelivery: ({ channel, to }: Pick<Delivery, "channel" | "to">) => string;
26
+ /** One delivery. It resolves to the failure of a mail that may have arrived all the same, which must not be sent again. */
27
+ export declare function deliver(deps: DeliverDeps, { id, name, channel, to, input, site, webhook }: Delivery, queued: boolean, log: Pick<Logger, "error">): Promise<Error | undefined>;
@@ -0,0 +1,23 @@
1
+ import type { Database } from "@hamur/db";
2
+ import type { cursorQuery } from "@hamur/db/server";
3
+ import type { CursorPage } from "hamur/server";
4
+ import type { NotificationRow, Recipient } from "../types.ts";
5
+ type Owner = Pick<Recipient, "type" | "id">;
6
+ export interface Inbox {
7
+ /** Adds the row of one delivery; a second run of the delivery leaves the first row as it is. */
8
+ add(delivery: {
9
+ id: string;
10
+ name: string;
11
+ to: Owner;
12
+ payload: unknown;
13
+ }): Promise<void>;
14
+ list(to: Owner, options?: {
15
+ unread?: boolean;
16
+ limit?: number;
17
+ cursor?: string;
18
+ }): Promise<CursorPage<NotificationRow>>;
19
+ markRead(to: Owner, ids: readonly string[] | "all"): Promise<number>;
20
+ }
21
+ /** The rows of the app's `table`, which every statement but the insert narrows to one recipient. */
22
+ export declare function createInbox(database: () => Database, keyset: typeof cursorQuery, name: string): Inbox;
23
+ export {};
@@ -0,0 +1,17 @@
1
+ import { type CursorPage } from "hamur/server";
2
+ import type { Notification, NotificationInput, NotificationName, NotificationOptions, NotificationRow, Recipient } from "../types.ts";
3
+ /** The default export of a file of `server/notifications/`; its channels are the keys among `mail`, `database`, `broadcast` and `webhook`. */
4
+ export declare function defineNotification<In, Out = In>(options: NotificationOptions<In, Out>): Notification<In>;
5
+ /** Tells each recipient through the notification's channels, one queued delivery per recipient and channel. */
6
+ export declare function notify<N extends NotificationName>(to: Recipient | readonly Recipient[], name: N, input: NotificationInput<N>, options?: {
7
+ queue?: boolean;
8
+ }): Promise<void>;
9
+ export { notificationTopic } from "./topic.ts";
10
+ /** A page of the notifications the database channel keeps for `to`, the newest first. */
11
+ export declare function listNotifications(to: Pick<Recipient, "type" | "id">, options?: {
12
+ unread?: boolean;
13
+ limit?: number;
14
+ cursor?: string;
15
+ }): Promise<CursorPage<NotificationRow>>;
16
+ /** Marks unread notifications of `to` read, and no one else's; resolves to how many it marked. */
17
+ export declare function markNotificationsRead(to: Pick<Recipient, "type" | "id">, ids: readonly string[] | "all"): Promise<number>;
@@ -0,0 +1,20 @@
1
+ import type { Logger } from "hamur/server";
2
+ import { type Delivery, type Recipient } from "../types.ts";
3
+ import type { QueuedDelivery } from "./queue.ts";
4
+ import { type DeliverDeps } from "./deliver.ts";
5
+ export interface NotifyDeps extends DeliverDeps {
6
+ /** `notifications.queue`. */
7
+ queue: boolean;
8
+ pack: (delivery: Delivery) => Promise<QueuedDelivery>;
9
+ /** Throws for a payload the queue cannot take; the function it returns queues it. */
10
+ prepare: (delivery: QueuedDelivery) => () => Promise<void>;
11
+ /** The `site.url` of the current request. */
12
+ site: () => string | undefined;
13
+ log: () => Pick<Logger, "warn" | "error">;
14
+ }
15
+ /** `notify` over the definitions, the queue and the channels. */
16
+ export declare function createNotify(deps: NotifyDeps): (to: Recipient | readonly Recipient[], name: string, input: unknown, options?: {
17
+ queue?: boolean;
18
+ }) => Promise<void>;
19
+ /** The run of `notifications:deliver`. A rejection makes the queue run this delivery again, and only this one. */
20
+ export declare function runDelivery(deps: DeliverDeps, delivery: Delivery, log: Pick<Logger, "error">): Promise<void>;
@@ -0,0 +1,7 @@
1
+ import type { Delivery } from "../types.ts";
2
+ /** The payload of `notifications:deliver`: the recipient's webhook is sealed, so a queue's record shows neither its secret nor a token in its URL. */
3
+ export interface QueuedDelivery extends Omit<Delivery, "webhook"> {
4
+ webhook?: string;
5
+ }
6
+ export declare function packDelivery({ webhook, ...delivery }: Delivery): Promise<QueuedDelivery>;
7
+ export declare function unpackDelivery({ webhook, ...delivery }: QueuedDelivery): Promise<Delivery>;
@@ -0,0 +1,2 @@
1
+ import type { Recipient } from "../types.ts";
2
+ export declare function checkRecipient({ type, id }: Pick<Recipient, "type" | "id">): void;
@@ -0,0 +1,3 @@
1
+ import type { DeliveryRecord } from "../types.ts";
2
+ /** Adds one line to `notifications.jsonl`, in the order of the calls. */
3
+ export declare function record(file: string, delivery: DeliveryRecord): Promise<void>;
@@ -0,0 +1,6 @@
1
+ import type { DeliverDeps } from "./deliver.ts";
2
+ import type { Inbox } from "./inbox.ts";
3
+ /** The rows of the database channel, imported at the first use. */
4
+ export declare function useInbox(caller: string): Promise<Inbox>;
5
+ /** What a delivery in the call and the task `notifications:deliver` share. */
6
+ export declare const deliverDeps: DeliverDeps;
@@ -0,0 +1,4 @@
1
+ import { type QueuedDelivery } from "./queue.ts";
2
+ /** Performs one delivery that `notify` queued. */
3
+ declare const _default: import("hamur/server").Task<QueuedDelivery, void>;
4
+ export default _default;
@@ -0,0 +1,3 @@
1
+ import type { Recipient } from "../types.ts";
2
+ /** The topic the broadcast channel publishes to for `to`; no two recipients share one. */
3
+ export declare function notificationTopic(to: Pick<Recipient, "type" | "id">): string;
@@ -0,0 +1,10 @@
1
+ import type { WebhookTarget } from "../types.ts";
2
+ type Send = (url: string, init: RequestInit) => Promise<Response>;
3
+ /** The `webhook-signature` of Standard Webhooks: HMAC-SHA256 of `<id>.<timestamp>.<body>`. */
4
+ export declare function signWebhook(secret: string, id: string, timestamp: number, body: string): Promise<string>;
5
+ /** One signed `POST`, through the guarded fetch. Every non-2xx answer fails, a redirect included; the body of an answer is not read. */
6
+ export declare function postWebhook(target: WebhookTarget, id: string, body: string, { send, now }?: {
7
+ send?: Send;
8
+ now?: () => number;
9
+ }): Promise<void>;
10
+ export {};
@@ -0,0 +1,5 @@
1
+ import type { DeliveryRecord, NotificationName } from "./types.ts";
2
+ /** The deliveries the test app recorded, oldest first; `name` keeps one notification's. */
3
+ export declare function sentNotifications(options?: {
4
+ name?: NotificationName;
5
+ }): Promise<DeliveryRecord[]>;
@@ -0,0 +1,87 @@
1
+ import type { MailAddress, MailMessage } from "@hamur/mail";
2
+ import type { EnvRef } from "hamur";
3
+ import type { StandardSchemaV1 } from "hamur/server";
4
+ import type { HamurNotifications } from "./index.ts";
5
+ /** In the order a notification's deliveries are made. */
6
+ export declare const CHANNELS: readonly ["mail", "database", "broadcast", "webhook"];
7
+ export type NotificationChannel = (typeof CHANNELS)[number];
8
+ export interface WebhookTarget {
9
+ url: string;
10
+ /** A Standard Webhooks secret, `whsec_…`. */
11
+ secret: EnvRef | string;
12
+ }
13
+ export interface Recipient {
14
+ /** An entity type name, such as `User`. */
15
+ type: string;
16
+ id: string;
17
+ email?: MailAddress;
18
+ /** The recipient's own endpoint; default `notifications.webhook`. */
19
+ webhook?: WebhookTarget;
20
+ /** Read by `via()`. */
21
+ prefs?: Record<string, unknown>;
22
+ }
23
+ export interface NotificationsConfig {
24
+ /** Default true: `notify` queues one task per delivery. */
25
+ queue?: boolean;
26
+ /** The endpoint of a recipient without one. */
27
+ webhook?: {
28
+ url: string;
29
+ secret: EnvRef;
30
+ };
31
+ /** The table of the database channel; default `"notifications"`. */
32
+ table?: string;
33
+ /** The connection of `db.connections` that has the table; default `"default"`. */
34
+ connection?: string;
35
+ }
36
+ export type NotificationName = keyof HamurNotifications extends never ? string : keyof HamurNotifications & string;
37
+ export type NotificationInput<N> = N extends keyof HamurNotifications ? HamurNotifications[N] extends {
38
+ input: infer I;
39
+ } ? I : unknown : unknown;
40
+ /** What `defineNotification` takes; a channel's function gets the validated input and the recipient without its `webhook`. */
41
+ export interface NotificationOptions<In, Out> {
42
+ input: StandardSchemaV1<In, Out>;
43
+ mail?: (input: Out, to: Recipient) => Omit<MailMessage, "to">;
44
+ database?: (input: Out, to: Recipient) => unknown;
45
+ broadcast?: (input: Out, to: Recipient) => unknown;
46
+ webhook?: (input: Out, to: Recipient) => unknown;
47
+ via?: (to: Recipient, input: Out) => readonly NotificationChannel[];
48
+ }
49
+ /** A notification; `In` is what `notify` takes. */
50
+ export interface Notification<In = unknown> {
51
+ /** Types only: never set. */
52
+ readonly "~types"?: {
53
+ input: In;
54
+ };
55
+ }
56
+ /** A notification of the database channel, as `listNotifications` returns it. */
57
+ export interface NotificationRow {
58
+ id: string;
59
+ notification: NotificationName;
60
+ /** What the notification's `database` function returned. */
61
+ data: unknown;
62
+ readAt: Date | null;
63
+ createdAt: Date;
64
+ }
65
+ /** One (recipient, channel) of a `notify` call. */
66
+ export interface Delivery {
67
+ /** A UUID v7, the same on every attempt: the `webhook-id`, the row's `id`, and the left side of a mail's Message-ID. */
68
+ id: string;
69
+ name: string;
70
+ channel: NotificationChannel;
71
+ /** Without `webhook`. */
72
+ to: Recipient;
73
+ input: unknown;
74
+ webhook?: WebhookTarget;
75
+ /** The `site.url` of the request `notify` was called in, a tenant's own with `site.tenants`; a mail links to it. */
76
+ site?: string;
77
+ }
78
+ /** A line of `notifications.jsonl` in a test build. */
79
+ export interface DeliveryRecord {
80
+ name: string;
81
+ channel: NotificationChannel;
82
+ recipient: {
83
+ type: string;
84
+ id: string;
85
+ };
86
+ payload: unknown;
87
+ }
package/package.json CHANGED
@@ -1,6 +1,44 @@
1
1
  {
2
2
  "name": "@hamur/notifications",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.1",
4
+ "type": "module",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/productdevbook/hamur.git",
9
+ "directory": "packages/notifications"
10
+ },
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/types/src/index.d.ts",
14
+ "default": "./dist/src/index.js"
15
+ },
16
+ "./server": {
17
+ "types": "./dist/types/src/server/index.d.ts",
18
+ "default": "./dist/src/server/index.js"
19
+ },
20
+ "./test": {
21
+ "types": "./dist/types/src/test.d.ts",
22
+ "default": "./dist/src/test.js"
23
+ },
24
+ "./package.json": "./package.json"
25
+ },
26
+ "files": [
27
+ "dist",
28
+ "src"
29
+ ],
30
+ "dependencies": {},
31
+ "peerDependencies": {
32
+ "@hamur/db": "^0.0.1",
33
+ "@hamur/mail": "^0.0.1",
34
+ "hamur": "~0.0.1"
35
+ },
36
+ "peerDependenciesMeta": {
37
+ "@hamur/db": {
38
+ "optional": true
39
+ },
40
+ "@hamur/mail": {
41
+ "optional": true
42
+ }
43
+ }
44
+ }
@@ -0,0 +1,119 @@
1
+ import { readdirSync, readFileSync } from "node:fs"
2
+ import { isAbsolute, join, relative, sep } from "node:path"
3
+ import { DiagnosticError } from "hamur/kit"
4
+ import { defaultCallKeys } from "hamur/server/internal"
5
+ import { CHANNELS, type NotificationChannel } from "../types.ts"
6
+
7
+ export interface NotificationFile {
8
+ name: string
9
+ file: string
10
+ }
11
+
12
+ export interface NotificationRecord extends NotificationFile {
13
+ channels: NotificationChannel[]
14
+ }
15
+
16
+ /** What the channels of a notification need of the build. */
17
+ export interface ChannelSupport {
18
+ mail: boolean
19
+ db: boolean
20
+ publish: boolean
21
+ /** False with `cloudflare.websocket: "worker"`, where `publish` always rejects. */
22
+ topics: boolean
23
+ /** Where the database channel keeps its rows. */
24
+ inbox: { table: string; connection: string }
25
+ }
26
+
27
+ const IGNORED = /\.(?:test|spec|d)\.ts$/
28
+ const SEGMENT = /^[A-Za-z0-9][A-Za-z0-9_-]*$/
29
+
30
+ const slashes = (path: string): string => path.split(sep).join("/")
31
+
32
+ function filesOf(dir: string, prefix: string): NotificationFile[] {
33
+ let entries
34
+ try {
35
+ entries = readdirSync(dir, { withFileTypes: true })
36
+ } catch {
37
+ return []
38
+ }
39
+ return entries
40
+ .filter(({ name }) => !/^[_.]/.test(name))
41
+ .flatMap((entry) => {
42
+ const file = join(dir, entry.name)
43
+ if (entry.isDirectory()) return filesOf(file, `${prefix}${entry.name}:`)
44
+ if (!entry.isFile() || !entry.name.endsWith(".ts") || IGNORED.test(entry.name)) return []
45
+ return [{ name: prefix + entry.name.slice(0, -".ts".length), file }]
46
+ })
47
+ }
48
+
49
+ /** `notifications/**` of the app's server folder, then each layer's; the first of a name wins. */
50
+ export function scanNotifications(serverDirs: readonly string[]): NotificationFile[] {
51
+ const found = new Map<string, NotificationFile>()
52
+ for (const dir of serverDirs)
53
+ for (const entry of filesOf(join(dir, "notifications"), ""))
54
+ if (!found.has(entry.name)) found.set(entry.name, entry)
55
+ return [...found.values()].sort((a, b) => (a.name < b.name ? -1 : 1))
56
+ }
57
+
58
+ /** Each notification's channels, read without running it, or the build error of the first file that is wrong. */
59
+ export function readNotifications(
60
+ files: readonly NotificationFile[],
61
+ rootDir: string,
62
+ support: ChannelSupport,
63
+ ): NotificationRecord[] {
64
+ return files.map(({ name, file }) => {
65
+ const path = relative(rootDir, file)
66
+ const shown = slashes(path.startsWith("..") || isAbsolute(path) ? file : path)
67
+ const bad = name.split(":").find((segment) => !SEGMENT.test(segment))
68
+ if (bad !== undefined)
69
+ throw new DiagnosticError(
70
+ "HAMUR_E6807",
71
+ `${shown}: a notification name segment holds A-Z, a-z, 0-9, _ and - (got ${JSON.stringify(bad)})`,
72
+ )
73
+ const keys = defaultCallKeys(readFileSync(file, "utf8"), "defineNotification")
74
+ if (!keys) throw new DiagnosticError("HAMUR_E6802", `${shown} must default-export defineNotification({ ... })`)
75
+ if (keys.includes("..."))
76
+ throw new DiagnosticError(
77
+ "HAMUR_E6808",
78
+ `${shown}: the options of defineNotification are written out (the build reads them)`,
79
+ )
80
+ const channels = CHANNELS.filter((channel) => keys.includes(channel))
81
+ if (!channels.length)
82
+ throw new DiagnosticError("HAMUR_E6803", `${shown} has no channel: give it mail, database, broadcast or webhook`)
83
+ if (channels.includes("mail") && !support.mail)
84
+ throw new DiagnosticError("HAMUR_E6804", `${shown}: the mail channel needs @hamur/mail in modules`)
85
+ if (channels.includes("database") && !support.db)
86
+ throw new DiagnosticError(
87
+ "HAMUR_E6805",
88
+ `${shown}: the database channel needs @hamur/db and the table ${JSON.stringify(support.inbox.table)} in db ${JSON.stringify(support.inbox.connection)}; add a migration that creates it`,
89
+ )
90
+ if (channels.includes("broadcast") && !support.publish)
91
+ throw new DiagnosticError(
92
+ "HAMUR_E6806",
93
+ `${shown}: the broadcast channel needs a preset that publishes (bun, node, cloudflare)`,
94
+ )
95
+ if (channels.includes("broadcast") && !support.topics)
96
+ throw new DiagnosticError("HAMUR_E6806", `${shown}: the broadcast channel needs cloudflare.websocket: "durable"`)
97
+ return { name, file, channels }
98
+ })
99
+ }
100
+
101
+ /** `.hamur/types/notifications.d.ts`, the input each notification takes in `HamurNotifications`. */
102
+ export function notificationTypes(files: readonly NotificationFile[], typesDir: string): string {
103
+ if (!files.length) return "export {};\n"
104
+ return [
105
+ `type NotificationTypes<T> = T extends { readonly "~types"?: infer Types } ? NonNullable<Types> : never;`,
106
+ "",
107
+ `declare module "@hamur/notifications" {`,
108
+ " interface HamurNotifications {",
109
+ ...files.map(
110
+ ({ name, file }) =>
111
+ ` ${JSON.stringify(name)}: NotificationTypes<typeof import(${JSON.stringify(slashes(relative(typesDir, file)))}).default>;`,
112
+ ),
113
+ " }",
114
+ "}",
115
+ "",
116
+ "export {};",
117
+ "",
118
+ ].join("\n")
119
+ }
@@ -0,0 +1,111 @@
1
+ import { rmSync } from "node:fs"
2
+ import { dirname, join, relative } from "node:path"
3
+ import {
4
+ addTask,
5
+ addTemplate,
6
+ addTypeTemplate,
7
+ createResolver,
8
+ DiagnosticError,
9
+ hasModule,
10
+ useInstalledModules,
11
+ type HamurContext,
12
+ } from "hamur/kit"
13
+ import type { ResolvedNotificationsOptions } from "../options.ts"
14
+ import type { NotificationChannel } from "../types.ts"
15
+ import { notificationTypes, readNotifications, scanNotifications, type NotificationRecord } from "./scan.ts"
16
+
17
+ const SERVER = "@hamur/notifications/server"
18
+ /** The presets that publish; `hamur dev` runs on Bun whatever the preset. */
19
+ const PUBLISH = new Set(["bun", "node", "cloudflare"])
20
+
21
+ /** The columns of the app's table. */
22
+ const COLUMNS = ["id", "recipient_type", "recipient_id", "notification", "data", "read_at", "created_at"]
23
+
24
+ type TableProblem = (
25
+ hamur: HamurContext,
26
+ options: { connection: string; table: string; columns: readonly string[] },
27
+ ) => Promise<string | undefined>
28
+
29
+ const uses = (notifications: readonly NotificationRecord[], channel: NotificationChannel): boolean =>
30
+ notifications.some(({ channels }) => channels.includes(channel))
31
+
32
+ /** The import guard, the task, the types, the build checks and `#hamur/notifications/config`. */
33
+ export function setupNotifications(options: ResolvedNotificationsOptions, hamur: HamurContext): void {
34
+ const { dev, preset, cloudflare, rootDir, buildDir } = hamur.options
35
+ const testBuild = process.env.HAMUR_TEST_BUILD === "1"
36
+ const recordFile = join(buildDir, "notifications.jsonl")
37
+ if (testBuild) rmSync(recordFile, { force: true })
38
+
39
+ const protection = hamur.options.build.importProtection
40
+ const client = (protection.client ??= {})
41
+ ;(client.deny ??= []).push(SERVER)
42
+
43
+ const r = createResolver(import.meta.url)
44
+ addTask({ name: "notifications:deliver", file: r.resolve("../server/task.ts") })
45
+
46
+ const serverDirs = [hamur.options.serverDir, ...hamur.options.layers.map((layer) => layer.serverDir)]
47
+ const { table, connection } = options
48
+ const support = {
49
+ mail: false,
50
+ db: false,
51
+ publish: dev || PUBLISH.has(preset),
52
+ topics: dev || preset !== "cloudflare" || cloudflare.websocket !== "worker",
53
+ inbox: { table, connection },
54
+ }
55
+ let dbDir = rootDir
56
+ hamur.hooks.hook("modules:done", () => {
57
+ support.mail = hasModule("@hamur/mail")
58
+ support.db = hasModule("@hamur/db")
59
+ // a layer may install it where the app's root does not reach, so its entries are resolved from the module's own file
60
+ const file = useInstalledModules().find(({ name }) => name === "db")?.file
61
+ if (file !== undefined) dbDir = dirname(file)
62
+ })
63
+ const read = (found = support): NotificationRecord[] =>
64
+ readNotifications(scanNotifications(serverDirs), rootDir, found)
65
+ hamur.hooks.hook("build:before", async () => {
66
+ if (!uses(read(), "database")) return
67
+ const { tableProblem } = (await import(Bun.resolveSync("@hamur/db/cli", dbDir))) as { tableProblem: TableProblem }
68
+ if (await tableProblem(hamur, { connection, table, columns: [] })) read({ ...support, db: false })
69
+ const problem = await tableProblem(hamur, { connection, table, columns: COLUMNS })
70
+ if (problem) throw new DiagnosticError("HAMUR_E6809", `@hamur/notifications: ${problem}`)
71
+ })
72
+ hamur.hooks.hook("dev:change", (change) => {
73
+ if (serverDirs.some((dir) => !relative(join(dir, "notifications"), change.file).startsWith("..")))
74
+ change.rebuildServer = true
75
+ })
76
+
77
+ addTypeTemplate({
78
+ filename: "notifications.d.ts",
79
+ getContents: () => notificationTypes(scanNotifications(serverDirs), join(buildDir, "types")),
80
+ })
81
+ addTemplate({
82
+ filename: "notifications/database",
83
+ getContents: () =>
84
+ support.db
85
+ ? `import { cursorQuery, useDatabase } from ${JSON.stringify(Bun.resolveSync("@hamur/db/server", dbDir))};
86
+ import { createInbox } from ${JSON.stringify(r.resolve("../server/inbox.ts"))};
87
+ export const inbox = createInbox(() => useDatabase(${JSON.stringify(connection)}), cursorQuery, ${JSON.stringify(table)});
88
+ `
89
+ : "export {};\n",
90
+ })
91
+ addTemplate({
92
+ filename: "notifications/config",
93
+ getContents: () => {
94
+ const notifications = read()
95
+ const entries = notifications.map(
96
+ ({ name, file }) => ` ${JSON.stringify(name)}: () => import(${JSON.stringify(file)}),\n`,
97
+ )
98
+ return [
99
+ `export const queue = ${options.queue};`,
100
+ `export const webhook = ${JSON.stringify(options.webhook)};`,
101
+ `export const notifications = {\n${entries.join("")}};`,
102
+ `export const loadMail = ${uses(notifications, "mail") ? `() => import("#hamur/mail/deliver")` : "undefined"};`,
103
+ `export const loadDatabase = ${uses(notifications, "database") ? `() => import("#hamur/notifications/database")` : "undefined"};`,
104
+ `export const loadBroadcast = ${uses(notifications, "broadcast") ? `() => import(${JSON.stringify(r.resolve("../server/broadcast.ts"))})` : "undefined"};`,
105
+ `export const loadRecord = ${testBuild ? `() => import(${JSON.stringify(r.resolve("../server/record.ts"))})` : "undefined"};`,
106
+ `export const recordFile = ${JSON.stringify(testBuild ? recordFile : "")};`,
107
+ "",
108
+ ].join("\n")
109
+ },
110
+ })
111
+ }
package/src/env.d.ts ADDED
@@ -0,0 +1,26 @@
1
+ declare module "#hamur/notifications/config" {
2
+ /** `notifications.queue`. */
3
+ export const queue: boolean
4
+ /** `notifications.webhook`. */
5
+ export const webhook: import("./types.ts").WebhookTarget | undefined
6
+ /** Notification name → its file of `server/notifications/`, whose default export is `defineNotification(…)`. */
7
+ export const notifications: Record<string, () => Promise<{ default: unknown }>>
8
+ /** The sender of `@hamur/mail`; `undefined` without the module or without a mail channel. */
9
+ export const loadMail:
10
+ | (() => Promise<{
11
+ deliverMail(
12
+ message: import("@hamur/mail").MailMessage,
13
+ delivery: { id: string; site?: string; queued: boolean },
14
+ log: Pick<import("hamur/server").Logger, "error">,
15
+ ): Promise<Error | undefined>
16
+ }>)
17
+ | undefined
18
+ /** The rows of the database channel; `undefined` in an app without one. */
19
+ export const loadDatabase: (() => Promise<{ inbox: import("./server/inbox.ts").Inbox }>) | undefined
20
+ /** The topics of the broadcast channel; `undefined` in an app without one. */
21
+ export const loadBroadcast: (() => Promise<typeof import("./server/broadcast.ts")>) | undefined
22
+ /** A build of `hamur/test`, which records each delivery; `undefined` in every other. */
23
+ export const loadRecord:
24
+ (() => Promise<{ record(file: string, delivery: import("./types.ts").DeliveryRecord): Promise<void> }>) | undefined
25
+ export const recordFile: string
26
+ }
package/src/index.ts ADDED
@@ -0,0 +1,13 @@
1
+ import type { NotificationsConfig } from "./types.ts"
2
+
3
+ export { default } from "./module.ts"
4
+ export type { NotificationName, NotificationRow, NotificationsConfig, Recipient } from "./types.ts"
5
+
6
+ /** Filled in by typegen from `server/notifications/`: each notification's name and the input `notify` takes. */
7
+ export interface HamurNotifications {}
8
+
9
+ declare module "hamur" {
10
+ interface HamurModuleOptions {
11
+ notifications?: NotificationsConfig
12
+ }
13
+ }
package/src/module.ts ADDED
@@ -0,0 +1,11 @@
1
+ import { defineModule } from "hamur/kit"
2
+ import { setupNotifications } from "./build/setup.ts"
3
+ import { resolveOptions } from "./options.ts"
4
+ import type { NotificationsConfig } from "./types.ts"
5
+
6
+ export default defineModule<NotificationsConfig>({
7
+ meta: { name: "notifications", configKey: "notifications" },
8
+ setup(input, hamur) {
9
+ setupNotifications(resolveOptions(input), hamur)
10
+ },
11
+ })
package/src/options.ts ADDED
@@ -0,0 +1,52 @@
1
+ import { DiagnosticError, isEnvRef } from "hamur/kit"
2
+ import { urlProblem } from "hamur/server/internal"
3
+ import type { NotificationsConfig } from "./types.ts"
4
+
5
+ const KEYS = ["queue", "webhook", "table", "connection"]
6
+ const WEBHOOK_KEYS = ["url", "secret"]
7
+ const TABLE = /^[A-Za-z_][A-Za-z0-9_]*$/
8
+
9
+ export interface ResolvedNotificationsOptions {
10
+ queue: boolean
11
+ table: string
12
+ connection: string
13
+ webhook?: NonNullable<NotificationsConfig["webhook"]>
14
+ }
15
+
16
+ function fail(message: string): never {
17
+ throw new DiagnosticError("HAMUR_E6801", message)
18
+ }
19
+
20
+ const shown = (value: unknown): string => (typeof value === "function" ? "a function" : String(JSON.stringify(value)))
21
+
22
+ const isObject = (value: unknown): value is Record<string, unknown> =>
23
+ typeof value === "object" && value !== null && !Array.isArray(value)
24
+
25
+ function checkKeys(label: string, value: Record<string, unknown>, keys: string[]): void {
26
+ for (const key of Object.keys(value))
27
+ if (!keys.includes(key)) fail(`${label} has no ${JSON.stringify(key)} (it takes: ${keys.join(", ")})`)
28
+ }
29
+
30
+ function resolveWebhook(input: unknown): NonNullable<NotificationsConfig["webhook"]> {
31
+ if (!isObject(input)) fail(`notifications.webhook must be an object with url and secret (got ${shown(input)})`)
32
+ checkKeys("notifications.webhook", input, WEBHOOK_KEYS)
33
+ const { url, secret } = input
34
+ if (typeof url !== "string") fail(`notifications.webhook.url must be an https: URL (got ${shown(url)})`)
35
+ const problem = urlProblem(url)
36
+ if (problem !== undefined) fail(`notifications.webhook.url cannot be used: ${problem}`)
37
+ if (!isEnvRef(secret))
38
+ fail('notifications.webhook.secret must be env("NAME"); a secret in the config file ends up in the repository')
39
+ return { url, secret }
40
+ }
41
+
42
+ /** The checked options, or the load error of the first value that is wrong. */
43
+ export function resolveOptions(input: unknown = {}): ResolvedNotificationsOptions {
44
+ if (!isObject(input)) fail(`notifications must be an object (got ${shown(input)})`)
45
+ checkKeys("notifications", input, KEYS)
46
+ const { queue = true, webhook, table = "notifications", connection = "default" } = input
47
+ if (typeof queue !== "boolean") fail(`notifications.queue must be a boolean (got ${shown(queue)})`)
48
+ if (typeof table !== "string" || !TABLE.test(table))
49
+ fail(`notifications.table must be a table name of A-Z, a-z, 0-9 and _ (got ${shown(table)})`)
50
+ if (typeof connection !== "string") fail(`notifications.connection must be a string (got ${shown(connection)})`)
51
+ return { queue, table, connection, ...(webhook === undefined ? {} : { webhook: resolveWebhook(webhook) }) }
52
+ }
@@ -0,0 +1,9 @@
1
+ import { publishTopic } from "hamur/server/internal"
2
+ import type { Recipient } from "../types.ts"
3
+ import { notificationTopic } from "./topic.ts"
4
+
5
+ /** What publishes to the topic of `to`. */
6
+ export function openTopic(to: Recipient): (message: { notification: string; data: unknown }) => Promise<void> {
7
+ const topic = notificationTopic(to)
8
+ return (message) => publishTopic(topic, message)
9
+ }