@productcraft/notify 0.0.0-stage → 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,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 ProductCraft
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,243 @@
1
- # Temporary Holding Version
1
+ # @productcraft/notify
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Node.js / TypeScript client for **ProductCraft Notify**: one call notifies a user across an in-app inbox, email (sent through ProductCraft Mail), web push, APNs and FCM, with per-user preferences per category and channel, fallbacks, quiet hours, templates per channel and locale, delivery history and signed webhooks.
4
+
5
+ Notify does not replace your own push credentials: Apple and Google tie push to your developer accounts, so you upload your APNs key and Firebase service account once (stored encrypted, never returned). Notify takes care of what comes after: device tokens, pruning dead ones, per-platform payloads, retries, fallbacks and delivery feedback.
6
+
7
+ Every method, type, error class and mock is generated from the production OpenAPI spec. Notify is in preview.
8
+
9
+ ## Install
10
+
11
+ ```sh
12
+ npm install @productcraft/notify
13
+ ```
14
+
15
+ Node 20.3 or later, Bun, Deno, edge runtimes and browsers (the `client({ token })` scope). Or install the umbrella package for every product: `npm install productcraft`.
16
+
17
+ ## Quick start (your server)
18
+
19
+ ```ts
20
+ import { Notify } from "@productcraft/notify";
21
+
22
+ // Reads PRODUCTCRAFT_API_KEY (and PRODUCTCRAFT_WORKSPACE_ID) from the environment.
23
+ const notify = new Notify({ workspaceId: "9b2f6c1e-0d6a-4a63-9a43-2f1c3e4d5a6b" });
24
+
25
+ // Tell Notify who the user is (your own user id is the key).
26
+ await notify.recipients.identify("user_123", { email: "ada@example.com", locale: "en" });
27
+
28
+ // Notify them: the notification type decides the channels, templates and fallback order.
29
+ const sent = await notify.notifications.send({
30
+ type: "comment_created",
31
+ recipients: ["user_123"],
32
+ data: { author: "Grace", post_title: "Hello" },
33
+ });
34
+ // The result is `Notify.NotificationSendResponse`: the accepted notification, or the plan when
35
+ // you pass `dry_run: true` (nothing is stored or sent).
36
+ if ("id" in sent) console.log(sent.id, sent.status);
37
+ ```
38
+
39
+ `notifications.send` always carries an `Idempotency-Key` (the SDK generates one per call and reuses it on retries; pass `{ idempotencyKey }` to tie it to your own event id).
40
+
41
+ ## In the browser or an app: `notify.client({ token })`
42
+
43
+ Never ship an API key to a browser or an app. Your backend mints a short-lived **recipient token** for the signed-in user, and the client side calls Notify with only that token:
44
+
45
+ ```ts
46
+ import { Notify } from "@productcraft/notify";
47
+
48
+ // Server: an endpoint that returns a token for the signed-in user.
49
+ const server = new Notify({ apiKey: process.env.PRODUCTCRAFT_API_KEY, workspaceId: "9b2f6c1e-0d6a-4a63-9a43-2f1c3e4d5a6b" });
50
+ const { token } = await server.recipientTokens.mint({ recipient: "user_123" });
51
+
52
+ // Browser or app: no API key, just the token.
53
+ const me = new Notify().client({ token });
54
+ const page = await me.inbox.list({ status: "unread" });
55
+ const ids = page.data.map((item) => item.id);
56
+ if (ids.length) await me.inbox.mark({ ids, action: "read" });
57
+ ```
58
+
59
+ `client({ token })` sends `Authorization: Bearer <token>` and nothing else: no API key, no environment fallback. It refuses a `pcft_` key. Tokens expire (one hour by default); fetch a new one when a call fails with `RECIPIENT_TOKEN_EXPIRED`. For a stateful inbox with real-time updates, use `@productcraft/notify-js` or `@productcraft/notify-react` once they ship.
60
+
61
+ ## Credentials
62
+
63
+ Pass `apiKey` (a workspace key, `pcft_live_…`), or omit it and the client reads `PRODUCTCRAFT_API_KEY`. The environment fallback is server-only: never put a key in `NEXT_PUBLIC_*` or any variable a bundler inlines into browser code (a workspace key in a browser throws unless you set `dangerouslyAllowBrowser: true`).
64
+
65
+ <!-- generated:start (scripts/gen-sdk.mjs; edits between the markers are overwritten) -->
66
+
67
+ ## Resources
68
+
69
+ Full reference: [api.md](./api.md).
70
+
71
+ - `notify.categories`: `create`, `delete`, `list`, `retrieve`, `update`
72
+ - `notify.channels`: `apns.deleteCredential`, `apns.uploadCredential`, `fcm.deleteCredential`, `fcm.uploadCredential`, `list`, `webpush.generateVapidKeys`, `webpush.importVapidKeys`, `webpush.retrieve`
73
+ - `notify.client(…).devices`: `delete`, `register`
74
+ - `notify.client(…).inbox`: `counts`, `interact`, `list`, `mark`
75
+ - `notify.client(…).preferences`: `retrieve`, `update`
76
+ - `notify.client(…).webpush`: `vapidPublicKey`
77
+ - `notify.deliveries`: `list`, `retrieve`
78
+ - `notify.export`: `retrieve`
79
+ - `notify.notificationTypes`: `archive`, `create`, `list`, `preview`, `replaceByKey`, `retrieve`, `templates.delete`, `templates.retrieve`, `templates.revert`, `templates.update`, `templates.versions`, `update`
80
+ - `notify.notifications`: `cancel`, `cancelByKey`, `list`, `retract`, `retrieve`, `send`
81
+ - `notify.recipientTokens`: `mint`
82
+ - `notify.recipients`: `bulkIdentify`, `delete`, `devices.create`, `devices.delete`, `devices.list`, `identify`, `inbox.list`, `list`, `preferences.replace`, `preferences.retrieve`, `preferences.update`, `retrieve`, `revokeTokens`, `timeline`, `update`
83
+ - `notify.settings`: `retrieve`, `revokeAllTokens`, `update`
84
+ - `notify.setupStatus`: `retrieve`
85
+ - `notify.stats`: `retrieve`
86
+ - `notify.webhooks`: `endpoints.create`, `endpoints.delete`, `endpoints.list`, `endpoints.retrieve`, `endpoints.rotateSecret`, `endpoints.test`, `endpoints.update`, `eventTypes.list`, `events.list`, `events.replay`, `events.retrieve`
87
+
88
+ ## Pagination
89
+
90
+ List methods return a `PagePromise`: `for await` walks every item across pages, `await` gives one page.
91
+
92
+ ```ts
93
+ import { Notify } from "@productcraft/notify";
94
+ const notify = new Notify({ apiKey: process.env.PRODUCTCRAFT_API_KEY });
95
+ for await (const item of notify.recipients.list({ limit: 50 })) console.log(item);
96
+ const page = await notify.recipients.list();
97
+ if (page.hasNextPage()) await page.getNextPage();
98
+ const all = await notify.recipients.list().toArray({ maxItems: 500 });
99
+ ```
100
+
101
+ ## Errors
102
+
103
+ Every failure is a class you can catch. `APIError` carries `status`, `code`, `message`, `errors[]`, `requestId` and `docUrl`.
104
+
105
+ ```ts
106
+ import { Notify, NotFoundError, RateLimitError, APIError } from "@productcraft/notify";
107
+ const notify = new Notify();
108
+ try {
109
+ await notify.categories.retrieve("00000000-0000-0000-0000-000000000000");
110
+ } catch (err) {
111
+ if (err instanceof NotFoundError) console.log(err.code, err.requestId, err.docUrl);
112
+ else if (err instanceof RateLimitError) console.log(err.retryAfter);
113
+ else if (err instanceof APIError) console.log(err.status, err.errors);
114
+ else throw err;
115
+ }
116
+ ```
117
+
118
+ ## Retries and timeouts
119
+
120
+ Network errors, 408, 429, 5xx and `409 IDEMPOTENCY_IN_PROGRESS` are retried twice by default with exponential backoff and jitter, honouring `Retry-After` up to 60 s. A POST or PATCH without an idempotency key is never retried. Each attempt times out after 60 s, so the worst case with defaults is about 3 minutes; pass `signal: AbortSignal.timeout(ms)` for an overall deadline.
121
+
122
+ ```ts
123
+ import { Notify } from "@productcraft/notify";
124
+ const notify = new Notify({ maxRetries: 3, timeout: 20_000 });
125
+ await notify.recipients.list({}, { maxRetries: 0, signal: AbortSignal.timeout(5_000) });
126
+ ```
127
+
128
+ ## Idempotency
129
+
130
+ Writes that support it send an `Idempotency-Key` automatically and reuse it on every retry. Pass your own to make a retry across processes safe. If the API's idempotency store is unavailable it runs the request without it (fail-open), so a retry during that window can execute twice.
131
+
132
+ ```ts
133
+ import { Notify } from "@productcraft/notify";
134
+ const notify = new Notify({ apiKey: process.env.PRODUCTCRAFT_API_KEY });
135
+ const result = await notify.notifications.send({
136
+ recipients: ["user_123", { email: "a@example.com", external_id: "user_456", locale: "pt-PT" }],
137
+ type: "invoice.paid",
138
+ }, { idempotencyKey: "order-1234" });
139
+ ```
140
+
141
+ ## Webhooks
142
+
143
+ `notify.webhooks.unwrap()` verifies the signature against the **raw** body and returns a typed `Notify.UnwrapWebhookEvent`. The secret comes from `{ secret }`, the client's `webhookSecret`, or `PRODUCTCRAFT_NOTIFY_WEBHOOK_SECRET`.
144
+
145
+ Next.js route handler:
146
+
147
+ ```ts
148
+ import { Notify } from "@productcraft/notify";
149
+ const notify = new Notify();
150
+ export async function POST(req: Request) {
151
+ const event = await notify.webhooks.unwrap({ payload: await req.text(), headers: req.headers });
152
+ switch (event.type) {
153
+ case "credential.invalid":
154
+ console.log(event.data);
155
+ break;
156
+ default:
157
+ break; // UnknownWebhookEvent: types added later
158
+ }
159
+ return new Response(null, { status: 204 });
160
+ }
161
+ ```
162
+
163
+ Express (keep the body raw):
164
+
165
+ ```ts
166
+ import express from "express";
167
+ import { Notify } from "@productcraft/notify";
168
+ const notify = new Notify();
169
+ const app = express();
170
+ app.post("/webhooks", express.raw({ type: "application/json" }), async (req, res) => {
171
+ const event = await notify.webhooks.unwrap({ payload: req.body, headers: req.headers });
172
+ console.log(event.type);
173
+ res.sendStatus(204);
174
+ });
175
+ ```
176
+
177
+ Hono:
178
+
179
+ ```ts
180
+ import { Hono } from "hono";
181
+ import { Notify } from "@productcraft/notify";
182
+ const notify = new Notify();
183
+ const app = new Hono();
184
+ app.post("/webhooks", async (c) => {
185
+ const event = await notify.webhooks.unwrap({ payload: await c.req.text(), headers: c.req.raw.headers });
186
+ console.log(event.type);
187
+ return c.body(null, 204);
188
+ });
189
+ ```
190
+
191
+ Testing a handler: `webhooks.sign()` signs an event the way ProductCraft does, so a test needs no live delivery and no hand-rolled HMAC.
192
+
193
+ ```ts
194
+ import { Notify } from "@productcraft/notify";
195
+ const notify = new Notify({ webhookSecret: "whsec_MfKQ9r8GKYqrTwjUPD8ILPZIo2LaLaSw" });
196
+ const { payload, headers } = await notify.webhooks.sign({ payload: { id: "evt_test_1", type: "credential.invalid", created_at: new Date().toISOString(), data: {} } });
197
+ const event = await notify.webhooks.unwrap({ payload, headers });
198
+ console.log(event.type);
199
+ ```
200
+
201
+ ## Raw responses
202
+
203
+ Every returned object has a non-enumerable `lastResponse` (`requestId`, `status`, `headers`). `.withResponse()` adds the `Response` and parsed rate-limit headers.
204
+
205
+ ```ts
206
+ import { Notify } from "@productcraft/notify";
207
+ const notify = new Notify({ apiKey: process.env.PRODUCTCRAFT_API_KEY });
208
+ const id = "9b2f6c1e-0d6a-4a63-9a43-2f1c3e4d5a6b";
209
+ const obj = await notify.categories.retrieve(id);
210
+ console.log(obj.lastResponse.requestId);
211
+ const { data, response, requestId, rateLimit } = await notify.categories.retrieve(id).withResponse();
212
+ console.log(data, response.status, requestId, rateLimit?.remaining);
213
+ ```
214
+
215
+ ## Testing
216
+
217
+ `@productcraft/notify/testing` exports `createMockFetch()`, a `fetch` that answers every operation with its spec example. Override one operation by name. It also exports `signWebhook({ payload, secret })`, which signs a test event for your webhook handler (the same as `webhooks.sign()`, without a client).
218
+
219
+ ```ts
220
+ import { Notify } from "@productcraft/notify";
221
+ import { createMockFetch } from "@productcraft/notify/testing";
222
+ const fetch = createMockFetch();
223
+ const notify = new Notify({ apiKey: "test", workspaceId: "9b2f6c1e-0d6a-4a63-9a43-2f1c3e4d5a6b", fetch });
224
+ await notify.recipients.list();
225
+ console.log(fetch.calls.length);
226
+ ```
227
+
228
+ ## Escape hatch
229
+
230
+ `.client` is the typed `openapi-fetch` client over the same credential and base URL (no retries). Use it for anything the resource methods do not cover.
231
+
232
+ ```ts
233
+ import { Notify } from "@productcraft/notify";
234
+ const notify = new Notify({ apiKey: process.env.PRODUCTCRAFT_API_KEY });
235
+ const { data, error } = await notify.client.GET("/v1/workspaces/{workspace_id}/categories", { params: { path: { workspace_id: "9b2f6c1e-0d6a-4a63-9a43-2f1c3e4d5a6b" } } });
236
+ console.log(data, error);
237
+ ```
238
+
239
+ <!-- generated:end -->
240
+
241
+ ## License
242
+
243
+ MIT