@venturekit/notify 0.0.0-dev.20260507015349

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 (75) hide show
  1. package/LICENSE +191 -0
  2. package/README.md +304 -0
  3. package/dist/admin/index.d.ts +88 -0
  4. package/dist/admin/index.d.ts.map +1 -0
  5. package/dist/admin/index.js +105 -0
  6. package/dist/admin/index.js.map +1 -0
  7. package/dist/bounce-handler.d.ts +65 -0
  8. package/dist/bounce-handler.d.ts.map +1 -0
  9. package/dist/bounce-handler.js +171 -0
  10. package/dist/bounce-handler.js.map +1 -0
  11. package/dist/client.d.ts +113 -0
  12. package/dist/client.d.ts.map +1 -0
  13. package/dist/client.js +213 -0
  14. package/dist/client.js.map +1 -0
  15. package/dist/dispatcher.d.ts +95 -0
  16. package/dist/dispatcher.d.ts.map +1 -0
  17. package/dist/dispatcher.js +251 -0
  18. package/dist/dispatcher.js.map +1 -0
  19. package/dist/index.d.ts +60 -0
  20. package/dist/index.d.ts.map +1 -0
  21. package/dist/index.js +66 -0
  22. package/dist/index.js.map +1 -0
  23. package/dist/providers/email-noop.d.ts +30 -0
  24. package/dist/providers/email-noop.d.ts.map +1 -0
  25. package/dist/providers/email-noop.js +39 -0
  26. package/dist/providers/email-noop.js.map +1 -0
  27. package/dist/providers/email-ses.d.ts +39 -0
  28. package/dist/providers/email-ses.d.ts.map +1 -0
  29. package/dist/providers/email-ses.js +114 -0
  30. package/dist/providers/email-ses.js.map +1 -0
  31. package/dist/providers/index.d.ts +20 -0
  32. package/dist/providers/index.d.ts.map +1 -0
  33. package/dist/providers/index.js +20 -0
  34. package/dist/providers/index.js.map +1 -0
  35. package/dist/providers/push-noop.d.ts +12 -0
  36. package/dist/providers/push-noop.d.ts.map +1 -0
  37. package/dist/providers/push-noop.js +30 -0
  38. package/dist/providers/push-noop.js.map +1 -0
  39. package/dist/providers/sms-noop.d.ts +21 -0
  40. package/dist/providers/sms-noop.d.ts.map +1 -0
  41. package/dist/providers/sms-noop.js +42 -0
  42. package/dist/providers/sms-noop.js.map +1 -0
  43. package/dist/providers/types.d.ts +95 -0
  44. package/dist/providers/types.d.ts.map +1 -0
  45. package/dist/providers/types.js +40 -0
  46. package/dist/providers/types.js.map +1 -0
  47. package/dist/providers/whatsapp-meta.d.ts +63 -0
  48. package/dist/providers/whatsapp-meta.d.ts.map +1 -0
  49. package/dist/providers/whatsapp-meta.js +160 -0
  50. package/dist/providers/whatsapp-meta.js.map +1 -0
  51. package/dist/store/index.d.ts +6 -0
  52. package/dist/store/index.d.ts.map +1 -0
  53. package/dist/store/index.js +5 -0
  54. package/dist/store/index.js.map +1 -0
  55. package/dist/store/postgres.d.ts +36 -0
  56. package/dist/store/postgres.d.ts.map +1 -0
  57. package/dist/store/postgres.js +354 -0
  58. package/dist/store/postgres.js.map +1 -0
  59. package/dist/store/types.d.ts +139 -0
  60. package/dist/store/types.d.ts.map +1 -0
  61. package/dist/store/types.js +14 -0
  62. package/dist/store/types.js.map +1 -0
  63. package/dist/templates/registry.d.ts +55 -0
  64. package/dist/templates/registry.d.ts.map +1 -0
  65. package/dist/templates/registry.js +94 -0
  66. package/dist/templates/registry.js.map +1 -0
  67. package/dist/types.d.ts +214 -0
  68. package/dist/types.d.ts.map +1 -0
  69. package/dist/types.js +12 -0
  70. package/dist/types.js.map +1 -0
  71. package/migrations/vk_notify_001_init.sql +109 -0
  72. package/package.json +109 -0
  73. package/runtime/bounce-handler-stub.ts +35 -0
  74. package/runtime/dispatcher-stub.ts +63 -0
  75. package/runtime/tsconfig.json +19 -0
package/LICENSE ADDED
@@ -0,0 +1,191 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to the Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by the Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding any notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ Copyright 2025 VentureKit Contributors
180
+
181
+ Licensed under the Apache License, Version 2.0 (the "License");
182
+ you may not use this file except in compliance with the License.
183
+ You may obtain a copy of the License at
184
+
185
+ http://www.apache.org/licenses/LICENSE-2.0
186
+
187
+ Unless required by applicable law or agreed to in writing, software
188
+ distributed under the License is distributed on an "AS IS" BASIS,
189
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
190
+ See the License for the specific language governing permissions and
191
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,304 @@
1
+ # @venturekit/notify
2
+
3
+ Transactional notifications for VentureKit applications — email (AWS SESv2), WhatsApp (Meta Cloud API), with SMS / push as placeholders. Backed by a Postgres outbox + auto-provisioned cron dispatcher Lambda.
4
+
5
+ > **Pre-release** — API may change before 1.0.
6
+
7
+ ## What you get
8
+
9
+ Declare one `notify` intent in `vk.config.ts` and `vk deploy` provisions:
10
+
11
+ - **SES email identity** (single-address or whole-domain, with DKIM signing when domain-based)
12
+ - **SES configuration set** with bounce / complaint / delivery / open / click events streaming into an SNS topic
13
+ - **SNS bounce-handler Lambda** that records every event in `notification_event_log` and auto-suppresses hard-bounced addresses
14
+ - **Postgres outbox** schema (`notifications`, `notification_preferences`, `notification_event_log`) shipped with the package and merged into the project's migration runner
15
+ - **EventBridge cron** + **dispatcher Lambda** that drains the outbox once per minute (configurable) and calls each row's provider
16
+ - **Secrets Manager secret** for the Meta WhatsApp API token (operator pastes the value after first deploy)
17
+ - **IAM grants** (`ses:SendEmail`, `ses:SendRawEmail`, `secretsmanager:GetSecretValue`) scoped to the resources above on the shared Lambda execution role
18
+
19
+ Application code only touches `notify.enqueue({...})`. Retry, preference filtering, address suppression, bounce processing, and template rendering all happen behind the scenes.
20
+
21
+ ## Quick start
22
+
23
+ ### 1. Declare the intent
24
+
25
+ ```ts
26
+ // vk.config.ts
27
+ import { defineVenture } from '@venturekit/infra';
28
+
29
+ export default defineVenture({
30
+ base,
31
+ security,
32
+ databases: [{ id: 'main', type: 'postgres', name: 'app' }],
33
+ notify: [
34
+ {
35
+ id: 'main',
36
+ channels: ['email', 'whatsapp'],
37
+ defaultFrom: 'no-reply@app.com',
38
+ domain: 'app.com', // optional: SES verifies the whole domain
39
+ hostedZoneId: 'Z123…', // optional: auto-publish DKIM CNAMEs in Route53
40
+ whatsapp: {
41
+ phoneNumberId: '105954992345678', // from Meta Business Suite
42
+ },
43
+ },
44
+ ],
45
+ envs: { dev, prod },
46
+ });
47
+ ```
48
+
49
+ ### 2. Build the runtime client
50
+
51
+ ```ts
52
+ // src/lib/notify.ts
53
+ import {
54
+ createNotifyClient,
55
+ createPostgresNotifyStore,
56
+ createSesEmailProvider,
57
+ createMetaWhatsAppProvider,
58
+ createSecretsTokenResolver,
59
+ } from '@venturekit/notify';
60
+ import { findUserById } from '@/db/repos/users';
61
+
62
+ export const notify = createNotifyClient({
63
+ store: createPostgresNotifyStore(),
64
+ defaultFrom: process.env.VENTURE_NOTIFY_FROM,
65
+ providers: [
66
+ createSesEmailProvider({
67
+ region: process.env.AWS_REGION!,
68
+ configurationSetName: process.env.VENTURE_NOTIFY_CONFIG_SET,
69
+ }),
70
+ createMetaWhatsAppProvider({
71
+ phoneNumberId: process.env.VENTURE_NOTIFY_WHATSAPP_PHONE_ID!,
72
+ tokenResolver: createSecretsTokenResolver({
73
+ secretArn: process.env.VENTURE_NOTIFY_WHATSAPP_TOKEN_SECRET!,
74
+ }),
75
+ }),
76
+ ],
77
+ // Map user ids -> channel-specific addresses. Phase 1 expects the
78
+ // consumer to own this lookup; future phases may add a default that
79
+ // reads from a user table convention.
80
+ addressResolver: async (userId, channel) => {
81
+ const user = await findUserById(userId);
82
+ if (channel === 'email') return user?.email ?? null;
83
+ if (channel === 'whatsapp') return user?.whatsappNumber ?? null;
84
+ return null;
85
+ },
86
+ });
87
+
88
+ // Templates live in code in Phase 1. Register them at module load so
89
+ // the dispatcher's first invocation already sees them.
90
+ notify.registerTemplate({
91
+ key: 'application_registered',
92
+ channel: 'email',
93
+ category: 'transactional_application',
94
+ render: ({ groupName }: { groupName: string }) => ({
95
+ subject: `Inscription confirmée: ${groupName}`,
96
+ text: `Votre inscription au groupe ${groupName} est confirmée.`,
97
+ html: `<p>Votre inscription au groupe <b>${groupName}</b> est confirmée.</p>`,
98
+ }),
99
+ });
100
+ ```
101
+
102
+ VentureKit's auto-provisioned dispatcher imports this module via `VENTURE_NOTIFY_CLIENT_MODULE` (default `./lib/notify.js`). Override the env var per intent if your project uses a different path.
103
+
104
+ ### 3. Send
105
+
106
+ ```ts
107
+ // src/routes/applications/post.ts
108
+ import { notify } from '@/lib/notify';
109
+
110
+ await notify.enqueue({
111
+ recipientUserId: ctx.user.id,
112
+ channel: 'email',
113
+ templateKey: 'application_registered',
114
+ payload: { groupName: 'Île-de-France #4' },
115
+ relatedKind: 'application',
116
+ relatedId: applicationId,
117
+ });
118
+ ```
119
+
120
+ The handler returns synchronously after the row hits the outbox. The dispatcher cron picks it up on the next tick (≤ 1 minute by default) and calls SES.
121
+
122
+ ## Architecture
123
+
124
+ ```
125
+ ┌────────────────────┐ ┌──────────────────────┐ ┌──────────────────┐
126
+ │ Route handler │ │ Outbox (Postgres) │ │ Dispatcher cron │
127
+ │ notify.enqueue() │───►│ notifications │◄───│ every 1 minute │
128
+ └────────────────────┘ │ + preferences │ │ drain pending │
129
+ │ + event_log │ │ call provider │
130
+ └──────────────────────┘ │ mark sent/fail │
131
+ └────┬─────────────┘
132
+ │
133
+ ┌────────────────────────────────────────────┴─────┐
134
+ ▼ ▼
135
+ ┌──────────────────────┐ ┌──────────────────────┐
136
+ │ AWS SESv2 │ │ Meta Graph API │
137
+ │ SendEmail │ │ /messages │
138
+ └──────────┬───────────┘ └──────────────────────┘
139
+ │
140
+ ▼
141
+ ┌──────────────────────┐
142
+ │ SES events SNS │
143
+ │ bounce / complaint │──────► Bounce handler Lambda ──► event_log
144
+ └──────────────────────┘ │
145
+ ▼
146
+ Address suppressed
147
+ in future sends
148
+ ```
149
+
150
+ Three persistent failure modes are recorded distinctly:
151
+
152
+ | Status | Meaning | Retried? |
153
+ | --- | --- | --- |
154
+ | `pending` | Awaiting next cron tick. | Yes — claimed by `claimPending()`. |
155
+ | `sent` | Provider accepted delivery. | No. May still flip to `bounced`. |
156
+ | `failed` | Provider rejected (hard error) or transient retries exhausted. | Manually via admin retry. |
157
+ | `bounced` | Bounce / complaint event arrived after `sent`. | Address auto-suppressed. |
158
+ | `cancelled` | Suppressed at enqueue (opt-out, address suppression). | No. |
159
+
160
+ ## Channels
161
+
162
+ | Channel | Phase 1 provider | Real impl? |
163
+ | --- | --- | --- |
164
+ | `email` | AWS SESv2 (`@aws-sdk/client-sesv2`, lazy-loaded) | ✅ |
165
+ | `whatsapp` | Meta Cloud API (Graph `/messages`, `fetch`) | ✅ |
166
+ | `sms` | `noop-sms` placeholder — logs and returns success | ❌ — register a real provider in your `createNotifyClient({ providers })` array. |
167
+ | `push` | `noop-push` placeholder | ❌ — same as above. |
168
+
169
+ The dispatcher uses whichever provider is registered last for a given channel — wire your own SNS / Twilio / Pinpoint provider by passing it in the `providers` array; it overrides the noop.
170
+
171
+ ## Outbox tracking
172
+
173
+ Phase 1 persistence is **always Postgres**. `NotifyIntent.tracking` exists in the type for forward-compatibility but only `'postgres'` is implemented. Auto-applied migrations create:
174
+
175
+ - `notifications` — outbox / audit log
176
+ - `notification_preferences` — per-(user, channel, category) opt-in
177
+ - `notification_event_log` — bounce / complaint / delivery / open / click events
178
+
179
+ Migrations live under `node_modules/@venturekit/notify/migrations/vk_notify_*.sql`. The infra package merges them into the project's CodeBuild migration runner asset on every `vk deploy`. Filename collisions with project-shipped migrations throw at synth time — VentureKit packages prefix their files with `vk_<package>_` to avoid that hazard.
180
+
181
+ ## Templates
182
+
183
+ Phase 1 keeps templates in code. Each template is a typed `(payload) -> { subject?, text, html?, whatsapp? }` function registered at boot:
184
+
185
+ ```ts
186
+ notify.registerTemplate<{ name: string }>({
187
+ key: 'welcome',
188
+ channel: 'email',
189
+ category: 'transactional_account',
190
+ render: ({ name }) => ({
191
+ subject: `Welcome, ${name}`,
192
+ text: `Hi ${name}, welcome aboard.`,
193
+ html: `<p>Hi <b>${name}</b>, welcome aboard.</p>`,
194
+ }),
195
+ });
196
+ ```
197
+
198
+ Templates without a `category` bypass the per-user opt-out check — useful for password resets, security alerts, etc., that the user can never opt out of.
199
+
200
+ WhatsApp template messages need Meta-pre-approved templates and use the `RenderedMessage.whatsapp` block:
201
+
202
+ ```ts
203
+ notify.registerTemplate({
204
+ key: 'application_received',
205
+ channel: 'whatsapp',
206
+ category: 'transactional_application',
207
+ render: ({ name, groupName }: { name: string; groupName: string }) => ({
208
+ text: `Hi ${name}, your application to ${groupName} is in.`,
209
+ whatsapp: {
210
+ metaTemplateName: 'application_received_v1',
211
+ languageCode: 'fr',
212
+ components: [
213
+ {
214
+ type: 'body',
215
+ parameters: [
216
+ { type: 'text', text: name },
217
+ { type: 'text', text: groupName },
218
+ ],
219
+ },
220
+ ],
221
+ },
222
+ }),
223
+ });
224
+ ```
225
+
226
+ Phase 2 will introduce DB-backed templates with admin UI editing — see the project roadmap.
227
+
228
+ ## Admin / inbox helpers
229
+
230
+ `@venturekit/notify/admin` exposes route-helper functions consumers wire into their own handlers (no automatic mounting — pick your own auth/scope conventions):
231
+
232
+ ```ts
233
+ // src/routes/admin/notifications/list/get.ts
234
+ import { handler } from '@venturekit/runtime';
235
+ import { adminListNotifications } from '@venturekit/notify/admin';
236
+ import { notify } from '@/lib/notify';
237
+
238
+ export const main = handler(async (ctx) => {
239
+ ctx.requireScope('admin.notifications.read');
240
+ const url = new URL(ctx.request.url);
241
+ return adminListNotifications(notify, {
242
+ limit: Number(url.searchParams.get('limit') ?? 50),
243
+ offset: Number(url.searchParams.get('offset') ?? 0),
244
+ status: url.searchParams.get('status') as never,
245
+ search: url.searchParams.get('q') ?? undefined,
246
+ });
247
+ });
248
+ ```
249
+
250
+ Available helpers:
251
+
252
+ - `adminListNotifications(client, options)` — paginated list with status / channel / template / search filters
253
+ - `adminGetNotification(client, id)`
254
+ - `adminSendNotification(client, input)` — equivalent to `client.enqueue(...)`, separate name for audit logging
255
+ - `adminRetryNotification(client, id)` — flips `failed` / `bounced` back to `pending`
256
+ - `adminCancelNotification(client, id)` — cancels a `pending` row before dispatch
257
+ - `adminClearSuppression(client, channel, address)` — lifts a bounce / complaint suppression
258
+ - `listUserPreferences(client, userId)` / `upsertUserPreference(client, ...)` — per-user opt-in management
259
+ - `listNotificationsForUser(client, userId, options)` — buyer-portal inbox view
260
+
261
+ ## Local dev (`vk dev`)
262
+
263
+ Declaring a notify intent with the `email` channel adds a **MailHog** service to `~/.vk/docker-compose.yml`:
264
+
265
+ - SMTP at `localhost:1025`
266
+ - Web inbox at `http://localhost:8025`
267
+
268
+ VK's local-mode runtime injects `VENTURE_NOTIFY_DRIVER=local` so the email provider falls through to the noop / log adapter — Phase 1 doesn't auto-route through MailHog yet (planned for Phase 2). Until then operators can spin a custom email provider against MailHog by passing `endpoint: 'http://localhost:1025'` in `createSesEmailProvider` (the SES SDK lets you point at any SMTP, MailHog accepts).
269
+
270
+ ## Environment variables
271
+
272
+ The infra package injects these on every Lambda when a notify intent is declared:
273
+
274
+ | Variable | Source |
275
+ | --- | --- |
276
+ | `VENTURE_NOTIFY_FROM` | First notify intent's `defaultFrom` |
277
+ | `VENTURE_NOTIFY_CONFIG_SET` | First notify intent's SES configuration set name |
278
+ | `VENTURE_NOTIFY_EVENTS_TOPIC_ARN` | First notify intent's SES events SNS topic ARN |
279
+ | `VENTURE_NOTIFY_WHATSAPP_PHONE_ID` | First notify intent's `whatsapp.phoneNumberId` |
280
+ | `VENTURE_NOTIFY_WHATSAPP_API_VERSION` | First notify intent's `whatsapp.apiVersion` |
281
+ | `VENTURE_NOTIFY_WHATSAPP_TOKEN_SECRET` | Secrets Manager ARN for the WhatsApp token |
282
+ | `NOTIFY_<ID>_FROM` / `NOTIFY_<ID>_CONFIG_SET` / `NOTIFY_<ID>_EVENTS_TOPIC_ARN` | Per-id overrides for projects with multiple intents |
283
+ | `VENTURE_NOTIFY_BATCH_SIZE` | Dispatcher cron — overrides default 50 |
284
+ | `VENTURE_NOTIFY_CLIENT_MODULE` | Path to the consumer's notify-client module (default `./lib/notify.js`) |
285
+
286
+ ## Migrating from `@venturekit-pro/comms`
287
+
288
+ The 0.x cut of `@venturekit-pro/comms` shipped email + push + SMS + WhatsApp + chat in one package. The split:
289
+
290
+ - **Notifications (this package, free tier):** all four channels (email / WhatsApp / SMS / push), templates, preferences, outbox, dispatcher.
291
+ - **Chat (`@venturekit-pro/chat`, Pro):** rooms, participants, messages, presence — unchanged API.
292
+
293
+ Migrate with one install:
294
+
295
+ ```bash
296
+ pnpm add @venturekit/notify @venturekit-pro/chat
297
+ pnpm remove @venturekit-pro/comms
298
+ ```
299
+
300
+ Then update imports — the chat manager API is unchanged, the notify API is intent-driven (declare in `vk.config.ts`, get auto-provisioned SES + outbox + cron).
301
+
302
+ ## License
303
+
304
+ Apache-2.0
@@ -0,0 +1,88 @@
1
+ /**
2
+ * @venturekit/notify — admin route helpers
3
+ *
4
+ * Building blocks for the `/admin/notifications/*` API surface. Phase 1
5
+ * exposes pure functions consumers wire into their own route handlers
6
+ * (so they can pick their own auth/scope conventions); a future phase
7
+ * may ship a fully-baked `mountAdminRoutes(api, scope)` helper.
8
+ *
9
+ * Each helper takes a {@link NotifyClient} (which carries the store
10
+ * and templates) plus the request input, and returns a JSON-ready
11
+ * value. The HTTP shell (status code, scope check) stays in the
12
+ * consumer's hands.
13
+ *
14
+ * ```ts
15
+ * // src/routes/admin/notifications/list/get.ts
16
+ * import { handler } from '@venturekit/runtime';
17
+ * import { adminListNotifications } from '@venturekit/notify/admin';
18
+ * import { notify } from '@/lib/notify';
19
+ *
20
+ * export const main = handler(async (ctx) => {
21
+ * ctx.requireScope('admin.notifications.read');
22
+ * const url = new URL(ctx.request.url);
23
+ * return adminListNotifications(notify, {
24
+ * limit: Number(url.searchParams.get('limit') ?? 50),
25
+ * offset: Number(url.searchParams.get('offset') ?? 0),
26
+ * channel: url.searchParams.get('channel') as never,
27
+ * status: url.searchParams.get('status') as never,
28
+ * search: url.searchParams.get('q') ?? undefined,
29
+ * });
30
+ * });
31
+ * ```
32
+ */
33
+ import type { NotifyClient } from '../client.js';
34
+ import type { AdminListOptions, ListForUserOptions } from '../store/types.js';
35
+ import type { EnqueueInput, NotificationPreferenceRow, NotificationRow, NotifyChannel } from '../types.js';
36
+ export interface AdminListResult {
37
+ rows: NotificationRow[];
38
+ total: number;
39
+ /** Echo of `limit` for API consumers paginating client-side. */
40
+ limit: number;
41
+ /** Echo of `offset`. */
42
+ offset: number;
43
+ }
44
+ /**
45
+ * List outbox rows (admin view). Accepts every filter from
46
+ * {@link AdminListOptions}. Always returns a `total` count so the UI
47
+ * can render pagination controls.
48
+ */
49
+ export declare function adminListNotifications(client: NotifyClient, options?: AdminListOptions): Promise<AdminListResult>;
50
+ export declare function adminGetNotification(client: NotifyClient, id: string): Promise<NotificationRow | null>;
51
+ export interface AdminSendInput extends EnqueueInput {
52
+ }
53
+ /**
54
+ * Admin-driven send. Equivalent to `client.enqueue(...)` — exposed as a
55
+ * named admin helper so route handlers can audit-log the operator who
56
+ * triggered it without reaching into the client API directly.
57
+ */
58
+ export declare function adminSendNotification(client: NotifyClient, input: AdminSendInput): Promise<{
59
+ id: string;
60
+ channel: NotifyChannel;
61
+ suppressed: boolean;
62
+ }>;
63
+ /**
64
+ * Move a `'failed'` / `'bounced'` row back to `'pending'`. Returns
65
+ * `null` when the row isn't found or wasn't in a retryable state.
66
+ */
67
+ export declare function adminRetryNotification(client: NotifyClient, id: string): Promise<NotificationRow | null>;
68
+ /**
69
+ * Cancel a `'pending'` row before the dispatcher claims it. Returns
70
+ * `null` when the row isn't found or has already left `'pending'`.
71
+ */
72
+ export declare function adminCancelNotification(client: NotifyClient, id: string): Promise<NotificationRow | null>;
73
+ /**
74
+ * Lift a hard-bounce / complaint suppression. Use sparingly — SES
75
+ * complaint feedback is reliable and re-sending after a complaint is
76
+ * a fast path to deliverability problems.
77
+ */
78
+ export declare function adminClearSuppression(client: NotifyClient, channel: NotifyChannel, address: string): Promise<void>;
79
+ /** List a user's stored opt-in/opt-out preferences. */
80
+ export declare function listUserPreferences(client: NotifyClient, userId: string): Promise<NotificationPreferenceRow[]>;
81
+ /** Upsert a single `(user, channel, category)` preference. */
82
+ export declare function upsertUserPreference(client: NotifyClient, input: Omit<NotificationPreferenceRow, 'updatedAtISO'>): Promise<NotificationPreferenceRow>;
83
+ /**
84
+ * List a user's notifications (newest first). Used by the buyer-portal
85
+ * inbox in projects like Groupi.
86
+ */
87
+ export declare function listNotificationsForUser(client: NotifyClient, userId: string, options?: ListForUserOptions): Promise<NotificationRow[]>;
88
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/admin/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA+BG;AAEH,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,cAAc,CAAC;AACjD,OAAO,KAAK,EACV,gBAAgB,EAChB,kBAAkB,EACnB,MAAM,mBAAmB,CAAC;AAC3B,OAAO,KAAK,EACV,YAAY,EACZ,yBAAyB,EACzB,eAAe,EACf,aAAa,EACd,MAAM,aAAa,CAAC;AAIrB,MAAM,WAAW,eAAe;IAC9B,IAAI,EAAE,eAAe,EAAE,CAAC;IACxB,KAAK,EAAE,MAAM,CAAC;IACd,gEAAgE;IAChE,KAAK,EAAE,MAAM,CAAC;IACd,wBAAwB;IACxB,MAAM,EAAE,MAAM,CAAC;CAChB;AAED;;;;GAIG;AACH,wBAAsB,sBAAsB,CAC1C,MAAM,EAAE,YAAY,EACpB,OAAO,GAAE,gBAAqB,GAC7B,OAAO,CAAC,eAAe,CAAC,CAQ1B;AAID,wBAAsB,oBAAoB,CACxC,MAAM,EAAE,YAAY,EACpB,EAAE,EAAE,MAAM,GACT,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC,CAEjC;AAID,MAAM,WAAW,cAAe,SAAQ,YAAY;CAAG;AAEvD;;;;GAIG;AACH,wBAAsB,qBAAqB,CACzC,MAAM,EAAE,YAAY,EACpB,KAAK,EAAE,cAAc,GACpB,OAAO,CAAC;IAAE,EAAE,EAAE,MAAM,CAAC;IAAC,OAAO,EAAE,aAAa,CAAC;IAAC,UAAU,EAAE,OAAO,CAAA;CAAE,CAAC,CAOtE;AAID;;;GAGG;AACH,wBAAsB,sBAAsB,CAC1C,MAAM,EAAE,YAAY,EACpB,EAAE,EAAE,MAAM,GACT,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC,CAEjC;AAED;;;GAGG;AACH,wBAAsB,uBAAuB,CAC3C,MAAM,EAAE,YAAY,EACpB,EAAE,EAAE,MAAM,GACT,OAAO,CAAC,eAAe,GAAG,IAAI,CAAC,CAEjC;AAID;;;;GAIG;AACH,wBAAsB,qBAAqB,CACzC,MAAM,EAAE,YAAY,EACpB,OAAO,EAAE,aAAa,EACtB,OAAO,EAAE,MAAM,GACd,OAAO,CAAC,IAAI,CAAC,CAEf;AAID,uDAAuD;AACvD,wBAAsB,mBAAmB,CACvC,MAAM,EAAE,YAAY,EACpB,MAAM,EAAE,MAAM,GACb,OAAO,CAAC,yBAAyB,EAAE,CAAC,CAEtC;AAED,8DAA8D;AAC9D,wBAAsB,oBAAoB,CACxC,MAAM,EAAE,YAAY,EACpB,KAAK,EAAE,IAAI,CAAC,yBAAyB,EAAE,cAAc,CAAC,GACrD,OAAO,CAAC,yBAAyB,CAAC,CAEpC;AAID;;;GAGG;AACH,wBAAsB,wBAAwB,CAC5C,MAAM,EAAE,YAAY,EACpB,MAAM,EAAE,MAAM,EACd,OAAO,GAAE,kBAAuB,GAC/B,OAAO,CAAC,eAAe,EAAE,CAAC,CAE5B"}