@assemora/notifications 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2026 Assemora
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Where a notification goes out (SPEC.md §81).
3
+ *
4
+ * The interface names no messenger. A channel is handed an address and a message and
5
+ * says nothing else about either: what a chat id is, how a bot authenticates and what
6
+ * a 429 means belong to the driver, the way a bucket belongs to the storage driver and
7
+ * Redis to the queue adapter (ADR-0023).
8
+ *
9
+ * A message is text and only text. Nothing here carries markup, a template or a
10
+ * payload a channel would interpret, because the values in it come from an order a
11
+ * stranger typed: a name holding `<b>` or `*` must arrive as those characters and not
12
+ * as an instruction. A driver that has to escape something escapes it, and the
13
+ * contract stays "this is what the person reads".
14
+ */
15
+ import { AssemoraError } from '@assemora/core';
16
+ export type NotificationMessage = {
17
+ readonly text: string;
18
+ };
19
+ export type NotificationChannel = {
20
+ /** What a recipient's `channel` column holds, and what the driver is chosen by. */
21
+ readonly name: string;
22
+ /**
23
+ * Delivers, or throws.
24
+ *
25
+ * Two failures are worth telling apart and the driver is the only layer that can:
26
+ * `rejected()` for an address that will never work — a wrong chat id, a bot nobody
27
+ * has started — and `unreachable()` for a network that was down for a minute. The
28
+ * first must not be retried, and retrying it is how a queue spends an afternoon on
29
+ * a typo.
30
+ */
31
+ send(address: string, message: NotificationMessage): Promise<void>;
32
+ };
33
+ export declare const NOTIFICATION_REJECTED = "NOTIFICATION_REJECTED";
34
+ export declare const NOTIFICATION_UNREACHABLE = "NOTIFICATION_UNREACHABLE";
35
+ /** The channel answered, and the answer was no. Trying again changes nothing. */
36
+ export declare const rejected: (message: string, details?: unknown) => AssemoraError;
37
+ /** Nobody answered. The same message may well arrive a minute from now. */
38
+ export declare const unreachable: (message: string, details?: unknown) => AssemoraError;
39
+ export declare const isRejection: (error: unknown) => boolean;
40
+ export declare const useChannels: (channels: readonly NotificationChannel[]) => void;
41
+ export declare const channelNames: () => readonly string[];
42
+ export declare const channelNamed: (name: string) => NotificationChannel | undefined;
43
+ export declare const clearChannels: () => void;
44
+ //# sourceMappingURL=channel.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"channel.d.ts","sourceRoot":"","sources":["../src/channel.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,OAAO,EAAE,aAAa,EAAE,MAAM,gBAAgB,CAAA;AAE9C,MAAM,MAAM,mBAAmB,GAAG;IAChC,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;CACtB,CAAA;AAED,MAAM,MAAM,mBAAmB,GAAG;IAChC,mFAAmF;IACnF,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAA;IACrB;;;;;;;;OAQG;IACH,IAAI,CAAC,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,mBAAmB,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;CACnE,CAAA;AAED,eAAO,MAAM,qBAAqB,0BAA0B,CAAA;AAC5D,eAAO,MAAM,wBAAwB,6BAA6B,CAAA;AAElE,iFAAiF;AACjF,eAAO,MAAM,QAAQ,YAAa,MAAM,YAAY,OAAO,KAAG,aAI1D,CAAA;AAEJ,2EAA2E;AAC3E,eAAO,MAAM,WAAW,YAAa,MAAM,YAAY,OAAO,KAAG,aAQ7D,CAAA;AAEJ,eAAO,MAAM,WAAW,UAAW,OAAO,KAAG,OAC2B,CAAA;AAWxE,eAAO,MAAM,WAAW,aAAc,SAAS,mBAAmB,EAAE,KAAG,IAEtE,CAAA;AAED,eAAO,MAAM,YAAY,QAAO,SAAS,MAAM,EAA4B,CAAA;AAE3E,eAAO,MAAM,YAAY,SAAU,MAAM,KAAG,mBAAmB,GAAG,SAAiC,CAAA;AAEnG,eAAO,MAAM,aAAa,QAAO,IAEhC,CAAA"}
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Where a notification goes out (SPEC.md §81).
3
+ *
4
+ * The interface names no messenger. A channel is handed an address and a message and
5
+ * says nothing else about either: what a chat id is, how a bot authenticates and what
6
+ * a 429 means belong to the driver, the way a bucket belongs to the storage driver and
7
+ * Redis to the queue adapter (ADR-0023).
8
+ *
9
+ * A message is text and only text. Nothing here carries markup, a template or a
10
+ * payload a channel would interpret, because the values in it come from an order a
11
+ * stranger typed: a name holding `<b>` or `*` must arrive as those characters and not
12
+ * as an instruction. A driver that has to escape something escapes it, and the
13
+ * contract stays "this is what the person reads".
14
+ */
15
+ import { AssemoraError } from '@assemora/core';
16
+ export const NOTIFICATION_REJECTED = 'NOTIFICATION_REJECTED';
17
+ export const NOTIFICATION_UNREACHABLE = 'NOTIFICATION_UNREACHABLE';
18
+ /** The channel answered, and the answer was no. Trying again changes nothing. */
19
+ export const rejected = (message, details) => new AssemoraError(NOTIFICATION_REJECTED, message, {
20
+ status: 422,
21
+ ...(details === undefined ? {} : { details }),
22
+ });
23
+ /** Nobody answered. The same message may well arrive a minute from now. */
24
+ export const unreachable = (message, details) => new AssemoraError(NOTIFICATION_UNREACHABLE, message, {
25
+ status: 503,
26
+ // An unreachable messenger is not this application failing, and a delivery that
27
+ // retries and succeeds is not an incident anybody has to be paged about
28
+ // (SPEC.md §88).
29
+ expected: true,
30
+ ...(details === undefined ? {} : { details }),
31
+ });
32
+ export const isRejection = (error) => error instanceof AssemoraError && error.code === NOTIFICATION_REJECTED;
33
+ /**
34
+ * The channels this process can send over.
35
+ *
36
+ * A process-wide slot, like the storage driver and the job bus: `notifications()` is
37
+ * given the drivers and the command that sends has no application in scope. One
38
+ * process runs one application, which is the trade those two already make.
39
+ */
40
+ let configured = new Map();
41
+ export const useChannels = (channels) => {
42
+ configured = new Map(channels.map((channel) => [channel.name, channel]));
43
+ };
44
+ export const channelNames = () => [...configured.keys()];
45
+ export const channelNamed = (name) => configured.get(name);
46
+ export const clearChannels = () => {
47
+ configured = new Map();
48
+ };
49
+ //# sourceMappingURL=channel.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C,CAAC,OAAO,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC,CAAC,CAAA;AAC1E,CAAC,CAAA;AAED,MAAM,CAAC,MAAM,YAAY,GAAG,GAAsB,EAAE,CAAC,CAAC,GAAG,UAAU,CAAC,IAAI,EAAE,CAAC,CAAA;AAE3E,MAAM,CAAC,MAAM,YAAY,GAAG,CAAC,IAAY,EAAmC,EAAE,CAAC,UAAU,CAAC,GAAG,CAAC,IAAI,CAAC,CAAA;AAEnG,MAAM,CAAC,MAAM,aAAa,GAAG,GAAS,EAAE;IACtC,UAAU,GAAG,IAAI,GAAG,EAAE,CAAA;AACxB,CAAC,CAAA"}
@@ -0,0 +1,42 @@
1
+ export declare const SendNotification: import("@assemora/core").CommandDefinition<{
2
+ topic: import("@assemora/schema").StringSchema;
3
+ payload: import("@assemora/schema").UnknownSchema;
4
+ }, {
5
+ readonly deliveries: readonly {
6
+ readonly address: string;
7
+ readonly channel: string;
8
+ readonly id: string;
9
+ readonly status: "failed" | "pending" | "sent";
10
+ }[];
11
+ readonly topic: string;
12
+ }>;
13
+ export declare const RecordDelivery: import("@assemora/core").CommandDefinition<{
14
+ deliveryId: import("@assemora/schema").StringSchema;
15
+ outcome: import("@assemora/schema").EnumSchema<"failed" | "sent">;
16
+ error: import("@assemora/schema").OptionalSchema<string>;
17
+ }, {
18
+ readonly attempts: number;
19
+ readonly id: string;
20
+ readonly status: "failed" | "pending" | "sent";
21
+ }>;
22
+ export declare const notificationCommands: readonly [import("@assemora/core").CommandDefinition<{
23
+ topic: import("@assemora/schema").StringSchema;
24
+ payload: import("@assemora/schema").UnknownSchema;
25
+ }, {
26
+ readonly deliveries: readonly {
27
+ readonly address: string;
28
+ readonly channel: string;
29
+ readonly id: string;
30
+ readonly status: "failed" | "pending" | "sent";
31
+ }[];
32
+ readonly topic: string;
33
+ }>, import("@assemora/core").CommandDefinition<{
34
+ deliveryId: import("@assemora/schema").StringSchema;
35
+ outcome: import("@assemora/schema").EnumSchema<"failed" | "sent">;
36
+ error: import("@assemora/schema").OptionalSchema<string>;
37
+ }, {
38
+ readonly attempts: number;
39
+ readonly id: string;
40
+ readonly status: "failed" | "pending" | "sent";
41
+ }>];
42
+ //# sourceMappingURL=commands.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"commands.d.ts","sourceRoot":"","sources":["../src/commands.ts"],"names":[],"mappings":"AAuDA,eAAO,MAAM,gBAAgB;;;;;;;;;;;EAwF3B,CAAA;AAEF,eAAO,MAAM,cAAc;;;;;;;;EAsBzB,CAAA;AAEF,eAAO,MAAM,oBAAoB;;;;;;;;;;;;;;;;;;;GAA8C,CAAA"}
@@ -0,0 +1,135 @@
1
+ /**
2
+ * Announcing, and recording what came of it (SPEC.md §14, §81).
3
+ *
4
+ * Two commands, because two things happen at two different times. `notifications.send`
5
+ * decides who is to be told and writes one pending row per address — all inside the
6
+ * transaction of whoever is sending, so an order that rolls back tells nobody.
7
+ * `notifications.record` writes down what the channel answered, minutes later and in
8
+ * the job that did the sending.
9
+ *
10
+ * Both are commands and not internal writes, so they are validated, authorized and
11
+ * audited like everything else (SPEC.md §14). Neither of them is granted to anybody
12
+ * here: authorization denies by default, and who may announce is the application's
13
+ * decision, not this package's. A package that registered a policy for its own
14
+ * subject would be an installed dependency handing out permissions nobody granted.
15
+ * An application that announces from a job writes it once:
16
+ *
17
+ * ```ts
18
+ * export const notificationPolicy = policy('notifications', {
19
+ * // The site announces its own events; a request never does.
20
+ * send: ({ context }) => context.source === 'job',
21
+ * record: ({ context }) => context.source === 'job',
22
+ * })
23
+ * ```
24
+ */
25
+ import { command, NotFoundError, ValidationError } from '@assemora/core';
26
+ import { array, enumOf, number, object, string, unknown as unknownSchema, uuid, } from '@assemora/schema';
27
+ import { channelNamed } from './channel.js';
28
+ import { DeliverNotification } from './jobs.js';
29
+ import { DELIVERY_STATUSES, NotificationDelivery, NotificationRecipient } from './models.js';
30
+ import { notificationFor, notificationTopics, renderMessage } from './notification.js';
31
+ /**
32
+ * How much of a channel's refusal is kept.
33
+ *
34
+ * Enough to name the reason, and not so much that a driver quoting the request back
35
+ * fills the column. It is read in a list.
36
+ */
37
+ const REASON_LIMIT = 500;
38
+ const shorten = (reason) => reason.length > REASON_LIMIT ? `${reason.slice(0, REASON_LIMIT - 1)}…` : reason;
39
+ /** Whether a recipient asked for this topic. No topics ticked means all of them. */
40
+ const wants = (topics, topic) => topics.length === 0 || topics.includes(topic);
41
+ export const SendNotification = command('notifications.send', {
42
+ description: 'Announces a declared topic to every active recipient subscribed to it. The payload is validated against the topic',
43
+ input: { topic: string(), payload: unknownSchema() },
44
+ output: {
45
+ topic: string(),
46
+ deliveries: array(object({
47
+ id: uuid(),
48
+ channel: string(),
49
+ address: string(),
50
+ status: enumOf(...DELIVERY_STATUSES),
51
+ })),
52
+ },
53
+ handle: async ({ topic, payload }, context) => {
54
+ const definition = notificationFor(topic);
55
+ if (definition === undefined) {
56
+ // A refusal a caller can act on: the topics are declared, so the list of what
57
+ // they could have meant is known and short.
58
+ throw new ValidationError([
59
+ {
60
+ path: ['topic'],
61
+ code: 'unknown_topic',
62
+ message: `"${topic}" is not a declared notification. Declared: ${notificationTopics().join(', ') || 'none'}`,
63
+ params: { topic, declared: notificationTopics() },
64
+ },
65
+ ], `"${topic}" is not a declared notification`);
66
+ }
67
+ const parsed = definition.input.parse(payload);
68
+ if (!parsed.ok) {
69
+ throw new ValidationError(parsed.issues, `"${topic}" was sent a payload it cannot accept`);
70
+ }
71
+ // Once, not once per recipient: the message is a function of the payload, and two
72
+ // people reading different text for one event is a support call nobody can answer.
73
+ const message = renderMessage(definition, parsed.value);
74
+ const subscribed = (await NotificationRecipient.where('active', true).get()).filter((recipient) => wants(recipient.topics, topic));
75
+ const deliveries = [];
76
+ for (const recipient of subscribed) {
77
+ const configured = channelNamed(recipient.channel) !== undefined;
78
+ const delivery = await NotificationDelivery.create({
79
+ topic,
80
+ channel: recipient.channel,
81
+ address: recipient.address,
82
+ recipientId: recipient.id,
83
+ body: message.text,
84
+ // A recipient pointing at a driver this process was not given is a
85
+ // misconfiguration, and it is written down as a failed delivery rather than
86
+ // skipped: the log is where somebody looks when the kitchen says nothing
87
+ // arrived, and a row that is not there answers nothing.
88
+ ...(configured
89
+ ? {}
90
+ : {
91
+ status: 'failed',
92
+ error: `No channel named "${recipient.channel}" is configured`,
93
+ }),
94
+ });
95
+ if (configured)
96
+ context.dispatch(DeliverNotification({ deliveryId: delivery.id }));
97
+ deliveries.push({
98
+ id: delivery.id,
99
+ channel: delivery.channel,
100
+ address: delivery.address,
101
+ status: delivery.status,
102
+ });
103
+ }
104
+ if (deliveries.length === 0) {
105
+ // Not a failure. A site with nobody in its address book is the ordinary state of
106
+ // a site the day before somebody adds the staff chat, and the sending code has
107
+ // no way to know that and nothing to do about it.
108
+ context.logger.info('A notification reached nobody', { topic });
109
+ }
110
+ return { topic, deliveries };
111
+ },
112
+ });
113
+ export const RecordDelivery = command('notifications.record', {
114
+ description: 'Writes down what a channel answered for one delivery',
115
+ input: {
116
+ deliveryId: uuid(),
117
+ outcome: enumOf('sent', 'failed'),
118
+ error: string().optional(),
119
+ },
120
+ output: { id: uuid(), status: enumOf(...DELIVERY_STATUSES), attempts: number().integer() },
121
+ handle: async ({ deliveryId, outcome, error }) => {
122
+ const delivery = await NotificationDelivery.find(deliveryId);
123
+ if (delivery === null)
124
+ throw new NotFoundError('That delivery does not exist');
125
+ await delivery.update({
126
+ status: outcome,
127
+ attempts: delivery.attempts + 1,
128
+ error: error === undefined ? null : shorten(error),
129
+ sentAt: outcome === 'sent' ? new Date() : delivery.sentAt,
130
+ });
131
+ return { id: delivery.id, status: delivery.status, attempts: delivery.attempts };
132
+ },
133
+ });
134
+ export const notificationCommands = [SendNotification, RecordDelivery];
135
+ //# sourceMappingURL=commands.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"commands.js","sourceRoot":"","sources":["../src/commands.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;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+ * `@assemora/notifications` — what an application announces, to whom, over what
3
+ * (SPEC.md §81).
4
+ *
5
+ * §81 lists notifications among the side effects an event exists for and stops there.
6
+ * This is the contract behind that word: a topic is declared like a command, a
7
+ * recipient is a row somebody adds in Studio, a delivery is a record of one attempt,
8
+ * and a channel is a driver — the same three-part shape storage and queues already
9
+ * have. Nothing here knows what Telegram is except `telegram.ts`.
10
+ *
11
+ * ```ts
12
+ * export const OrderPlaced = notification('orders.placed', {
13
+ * input: { code: string(), total: integer() },
14
+ * render: (order) => `Order ${order.code} — ${order.total}`,
15
+ * })
16
+ *
17
+ * // inside a job, once the order is really an order:
18
+ * await context.commands.execute('notifications.send', {
19
+ * topic: 'orders.placed',
20
+ * payload: { code: order.code, total: order.total },
21
+ * })
22
+ * ```
23
+ *
24
+ * Who may send is the application's decision: authorization denies by default and
25
+ * this package registers no policy of its own — see `commands.ts` for the four lines
26
+ * an application writes.
27
+ */
28
+ export { channelNamed, channelNames, clearChannels, isRejection, NOTIFICATION_REJECTED, NOTIFICATION_UNREACHABLE, type NotificationChannel, type NotificationMessage, rejected, unreachable, useChannels, } from './channel.js';
29
+ export { notificationCommands, RecordDelivery, SendNotification } from './commands.js';
30
+ export { DeliverNotification, notificationJobs } from './jobs.js';
31
+ export { DELIVERY_STATUSES, type DeliveryStatus, NotificationDelivery, NotificationRecipient, notificationModels, } from './models.js';
32
+ export { type NotificationsOptions, notifications } from './module.js';
33
+ export { type AnyNotification, clearNotifications, type NotificationDefinition, type NotificationDescriptor, notification, notificationFor, notificationTopics, renderMessage, useNotifications, } from './notification.js';
34
+ export { DELIVERIES, type NotificationResourceOptions, notificationResources, RECIPIENTS, } from './resources.js';
35
+ export { type TelegramOptions, telegram } from './telegram.js';
36
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH,OAAO,EACL,YAAY,EACZ,YAAY,EACZ,aAAa,EACb,WAAW,EACX,qBAAqB,EACrB,wBAAwB,EACxB,KAAK,mBAAmB,EACxB,KAAK,mBAAmB,EACxB,QAAQ,EACR,WAAW,EACX,WAAW,GACZ,MAAM,cAAc,CAAA;AACrB,OAAO,EAAE,oBAAoB,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAA;AACtF,OAAO,EAAE,mBAAmB,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAA;AACjE,OAAO,EACL,iBAAiB,EACjB,KAAK,cAAc,EACnB,oBAAoB,EACpB,qBAAqB,EACrB,kBAAkB,GACnB,MAAM,aAAa,CAAA;AACpB,OAAO,EAAE,KAAK,oBAAoB,EAAE,aAAa,EAAE,MAAM,aAAa,CAAA;AACtE,OAAO,EACL,KAAK,eAAe,EACpB,kBAAkB,EAClB,KAAK,sBAAsB,EAC3B,KAAK,sBAAsB,EAC3B,YAAY,EACZ,eAAe,EACf,kBAAkB,EAClB,aAAa,EACb,gBAAgB,GACjB,MAAM,mBAAmB,CAAA;AAC1B,OAAO,EACL,UAAU,EACV,KAAK,2BAA2B,EAChC,qBAAqB,EACrB,UAAU,GACX,MAAM,gBAAgB,CAAA;AACvB,OAAO,EAAE,KAAK,eAAe,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAA"}
package/dist/index.js ADDED
@@ -0,0 +1,36 @@
1
+ /**
2
+ * `@assemora/notifications` — what an application announces, to whom, over what
3
+ * (SPEC.md §81).
4
+ *
5
+ * §81 lists notifications among the side effects an event exists for and stops there.
6
+ * This is the contract behind that word: a topic is declared like a command, a
7
+ * recipient is a row somebody adds in Studio, a delivery is a record of one attempt,
8
+ * and a channel is a driver — the same three-part shape storage and queues already
9
+ * have. Nothing here knows what Telegram is except `telegram.ts`.
10
+ *
11
+ * ```ts
12
+ * export const OrderPlaced = notification('orders.placed', {
13
+ * input: { code: string(), total: integer() },
14
+ * render: (order) => `Order ${order.code} — ${order.total}`,
15
+ * })
16
+ *
17
+ * // inside a job, once the order is really an order:
18
+ * await context.commands.execute('notifications.send', {
19
+ * topic: 'orders.placed',
20
+ * payload: { code: order.code, total: order.total },
21
+ * })
22
+ * ```
23
+ *
24
+ * Who may send is the application's decision: authorization denies by default and
25
+ * this package registers no policy of its own — see `commands.ts` for the four lines
26
+ * an application writes.
27
+ */
28
+ export { channelNamed, channelNames, clearChannels, isRejection, NOTIFICATION_REJECTED, NOTIFICATION_UNREACHABLE, rejected, unreachable, useChannels, } from './channel.js';
29
+ export { notificationCommands, RecordDelivery, SendNotification } from './commands.js';
30
+ export { DeliverNotification, notificationJobs } from './jobs.js';
31
+ export { DELIVERY_STATUSES, NotificationDelivery, NotificationRecipient, notificationModels, } from './models.js';
32
+ export { notifications } from './module.js';
33
+ export { clearNotifications, notification, notificationFor, notificationTopics, renderMessage, useNotifications, } from './notification.js';
34
+ export { DELIVERIES, notificationResources, RECIPIENTS, } from './resources.js';
35
+ export { telegram } from './telegram.js';
36
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AAEH,OAAO,EACL,YAAY,EACZ,YAAY,EACZ,aAAa,EACb,WAAW,EACX,qBAAqB,EACrB,wBAAwB,EAGxB,QAAQ,EACR,WAAW,EACX,WAAW,GACZ,MAAM,cAAc,CAAA;AACrB,OAAO,EAAE,oBAAoB,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,eAAe,CAAA;AACtF,OAAO,EAAE,mBAAmB,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAA;AACjE,OAAO,EACL,iBAAiB,EAEjB,oBAAoB,EACpB,qBAAqB,EACrB,kBAAkB,GACnB,MAAM,aAAa,CAAA;AACpB,OAAO,EAA6B,aAAa,EAAE,MAAM,aAAa,CAAA;AACtE,OAAO,EAEL,kBAAkB,EAGlB,YAAY,EACZ,eAAe,EACf,kBAAkB,EAClB,aAAa,EACb,gBAAgB,GACjB,MAAM,mBAAmB,CAAA;AAC1B,OAAO,EACL,UAAU,EAEV,qBAAqB,EACrB,UAAU,GACX,MAAM,gBAAgB,CAAA;AACvB,OAAO,EAAwB,QAAQ,EAAE,MAAM,eAAe,CAAA"}
package/dist/jobs.d.ts ADDED
@@ -0,0 +1,7 @@
1
+ export declare const DeliverNotification: import("@assemora/core").JobDefinition<{
2
+ deliveryId: import("@assemora/schema").StringSchema;
3
+ }>;
4
+ export declare const notificationJobs: readonly [import("@assemora/core").JobDefinition<{
5
+ deliveryId: import("@assemora/schema").StringSchema;
6
+ }>];
7
+ //# sourceMappingURL=jobs.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jobs.d.ts","sourceRoot":"","sources":["../src/jobs.ts"],"names":[],"mappings":"AAkBA,eAAO,MAAM,mBAAmB;;EA8C9B,CAAA;AAEF,eAAO,MAAM,gBAAgB;;GAAiC,CAAA"}