@molecule/api-push-notifications-molecule 1.1.1 → 1.1.2

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 (2) hide show
  1. package/README.md +199 -11
  2. package/package.json +4 -4
package/README.md CHANGED
@@ -3,17 +3,17 @@ AUTO-GENERATED — DO NOT EDIT THIS FILE.
3
3
  Generated by `mlcl sync-docs` from the package's src/index.ts JSDoc + mlcl/registry.json.
4
4
  Edits here are overwritten on the next commit (molecule's pre-commit hook regenerates).
5
5
  To change this document, edit the module-level JSDoc in src/index.ts.
6
- Generated: 2026-10-08T03:25:11.137Z
6
+ Generated: 2026-10-16T23:31:01.976Z
7
7
  -->
8
8
 
9
9
  # @molecule/api-push-notifications-molecule
10
10
 
11
+ molecule.dev hosted push notifications provider — web push delivered through your molecule project, VAPID handled for you
12
+
11
13
  > **Auto-generated, AI-first package reference** for the [molecule.dev](https://molecule.dev) ecosystem.
12
14
  > It is written to be read by coding agents as much as by people, and is generated from this
13
15
  > package's source — edit `src/index.ts` JSDoc, not this file.
14
16
 
15
- molecule.dev hosted push notifications provider — web push delivered through your molecule project, VAPID handled for you
16
-
17
17
  ## Type
18
18
 
19
19
  `provider`
@@ -63,13 +63,201 @@ interface ProcessEnv {
63
63
 
64
64
  ### Classes
65
65
 
66
+ #### `MoleculeServiceError`
67
+
68
+ Error thrown for a refused or failed hosted-service call.
69
+
70
+ ```typescript
71
+ class MoleculeServiceError extends Error {
72
+ /** HTTP status from molecule.dev. */
73
+ readonly status: number
74
+ /** Stable error key from molecule.dev, e.g. `broker.error.budgetExceeded`. */
75
+ readonly errorKey: string | undefined
76
+
77
+ /**
78
+ * Create the error.
79
+ *
80
+ * @param message - Human-readable message.
81
+ * @param status - HTTP status.
82
+ * @param errorKey - Stable error key, when the service sent one.
83
+ * @param cause - The underlying error, if any.
84
+ */
85
+ constructor(message: string, status: number, errorKey?: string, cause?: unknown) {
86
+ super(message, cause === undefined ? undefined : { cause })
87
+ this.name = 'MoleculeServiceError'
88
+ this.status = status
89
+ this.errorKey = errorKey
90
+ }
91
+ }
92
+ ```
93
+
66
94
  #### `MoleculePushProvider`
67
95
 
68
96
  Push provider backed by molecule.dev's hosted service.
69
97
 
70
- #### `MoleculeServiceError`
98
+ ````typescript
99
+ class MoleculePushProvider implements PushNotificationProvider {
100
+ readonly name = 'molecule'
71
101
 
72
- Error thrown for a refused or failed hosted-service call.
102
+ private readonly apiKey: string
103
+ private readonly servicesUrl: string
104
+ private readonly timeoutMs: number
105
+ private cachedPublicKey: string | undefined
106
+
107
+ /**
108
+ * Create the provider.
109
+ *
110
+ * @param config - Options; each falls back to its env var.
111
+ */
112
+ constructor(config: MoleculePushConfig = {}) {
113
+ this.apiKey = config.apiKey ?? process.env.MOLECULE_API_KEY ?? ''
114
+ this.servicesUrl = resolveServicesUrl(
115
+ config.servicesUrl ?? process.env.MOLECULE_SERVICES_URL ?? DEFAULT_SERVICES_URL,
116
+ )
117
+ this.timeoutMs = config.timeoutMs ?? 15_000
118
+ }
119
+
120
+ /**
121
+ * Nothing to configure locally — molecule.dev holds the VAPID keys and
122
+ * signs every send. The parameter is accepted so the provider satisfies
123
+ * the core interface; a self-hosted setup should use
124
+ * `@molecule/api-push-notifications-web-push` instead.
125
+ *
126
+ * @param _config - Ignored.
127
+ */
128
+ configure(_config?: VapidConfig): void {}
129
+
130
+ /**
131
+ * Sends a push notification to a subscription endpoint.
132
+ *
133
+ * @param subscription - The push subscription (endpoint + keys).
134
+ * @param payload - The notification payload (title + display options).
135
+ * @returns The push service's answer: `statusCode` 201 means delivered;
136
+ * 404/410 mean the subscription is dead and should be pruned.
137
+ */
138
+ async send(subscription: PushSubscription, payload: NotificationPayload): Promise<SendResult> {
139
+ assertValidSubscription(subscription)
140
+ assertValidPayload(payload)
141
+ return this.request<SendResult>('send', { subscription, payload })
142
+ }
143
+
144
+ /**
145
+ * Sends a push notification to multiple subscriptions. One refused or
146
+ * failed subscription never aborts the batch — each entry carries either
147
+ * `result` or `error` (a dead subscription arrives as a `result` whose
148
+ * `statusCode` is 404/410; prune on it).
149
+ *
150
+ * @param subscriptions - The push subscriptions to send to.
151
+ * @param payload - The notification payload with title and optional display options.
152
+ * @returns One result entry per subscription.
153
+ */
154
+ async sendMany(
155
+ subscriptions: PushSubscription[],
156
+ payload: NotificationPayload,
157
+ ): Promise<SendManyResult[]> {
158
+ const settled = await Promise.allSettled(
159
+ (subscriptions ?? []).map((subscription) => this.send(subscription, payload)),
160
+ )
161
+ return settled.map((outcome, i) =>
162
+ outcome.status === 'fulfilled'
163
+ ? { subscription: subscriptions[i], result: outcome.value }
164
+ : { subscription: subscriptions[i], error: outcome.reason as Error },
165
+ )
166
+ }
167
+
168
+ /**
169
+ * Returns molecule.dev's public VAPID key — the `applicationServerKey` a
170
+ * browser's `pushManager.subscribe()` must be given for the resulting
171
+ * subscriptions to be sendable through molecule.dev.
172
+ *
173
+ * The core's method is SYNCHRONOUS while the key lives behind a service
174
+ * call, so this returns the cache: `undefined` until {@link fetchPublicKey}
175
+ * has run (or a send cached it). Await the fetch first:
176
+ *
177
+ * ```typescript
178
+ * await provider.fetchPublicKey() // once, e.g. at startup
179
+ * const applicationServerKey = provider.getPublicKey()
180
+ * ```
181
+ *
182
+ * @returns The cached public key, or `undefined` before the first fetch.
183
+ */
184
+ getPublicKey(): string | undefined {
185
+ return this.cachedPublicKey
186
+ }
187
+
188
+ /**
189
+ * Fetches molecule.dev's public VAPID key from the hosted service and
190
+ * caches it for {@link getPublicKey}.
191
+ *
192
+ * @returns The public key string.
193
+ */
194
+ async fetchPublicKey(): Promise<string> {
195
+ const { publicKey } = await this.request<{ publicKey: string }>('vapid-key', {})
196
+ this.cachedPublicKey = publicKey
197
+ return publicKey
198
+ }
199
+
200
+ /**
201
+ * Not supported on the hosted path: sends are signed with molecule.dev's
202
+ * VAPID identity, and subscriptions are bound to the key they were created
203
+ * with — a locally generated pair could never receive a hosted send. Use
204
+ * `@molecule/api-push-notifications-web-push` (which serves your own keys)
205
+ * when you need your own identity.
206
+ *
207
+ * @throws {MoleculeServiceError} Always, with the self-hosted pointer.
208
+ */
209
+ generateVapidKeys(): never {
210
+ throw new MoleculeServiceError(
211
+ "generateVapidKeys() is a self-hosted concern: the hosted service signs sends with molecule.dev's VAPID identity. Use @molecule/api-push-notifications-web-push to serve your own keys.",
212
+ 400,
213
+ 'hostedServices.error.invalidInput',
214
+ )
215
+ }
216
+
217
+ /** One POST to the hosted service. */
218
+ private async request<T>(
219
+ operation: 'send' | 'vapid-key',
220
+ body: Record<string, unknown>,
221
+ ): Promise<T> {
222
+ if (!this.apiKey) {
223
+ throw new MoleculeServiceError(
224
+ 'MOLECULE_API_KEY is not set. Create a project API key on molecule.dev (or with `mlcl apikey create`) and put it in the API .env.',
225
+ 401,
226
+ 'hostedServices.error.tokenInvalid',
227
+ )
228
+ }
229
+ const response = await fetch(`${this.servicesUrl}/push/${operation}`, {
230
+ method: 'POST',
231
+ headers: { authorization: `Bearer ${this.apiKey}`, 'content-type': 'application/json' },
232
+ body: JSON.stringify(body),
233
+ signal: AbortSignal.timeout(this.timeoutMs),
234
+ })
235
+ const text = await response.text()
236
+ let data: unknown
237
+ try {
238
+ data = text ? JSON.parse(text) : {}
239
+ } catch (error) {
240
+ // A proxy/gateway error page, not the service: report the status only.
241
+ throw new MoleculeServiceError(
242
+ `molecule.dev returned ${response.status} with a non-JSON body.`,
243
+ response.status,
244
+ undefined,
245
+ error,
246
+ )
247
+ }
248
+ if (!response.ok) {
249
+ const err = data as { error?: string; errorKey?: string }
250
+ const hint = HINTS[response.status]
251
+ throw new MoleculeServiceError(
252
+ `molecule.dev push/${operation} failed (${response.status}): ${err.error ?? 'error'}${hint ? ` ${hint}` : ''}`,
253
+ response.status,
254
+ err.errorKey,
255
+ )
256
+ }
257
+ return data as T
258
+ }
259
+ }
260
+ ````
73
261
 
74
262
  ### Functions
75
263
 
@@ -87,20 +275,20 @@ function createProvider(config?: MoleculePushConfig): PushNotificationProvider
87
275
 
88
276
  ### Constants
89
277
 
90
- #### `DEFAULT_SERVICES_URL`
278
+ #### `provider`
91
279
 
92
- Default hosted services base URL.
280
+ The provider implementation (wire with `setProvider`).
93
281
 
94
282
  ```typescript
95
- const DEFAULT_SERVICES_URL: 'https://api.molecule.dev/api/v1/services'
283
+ const provider: PushNotificationProvider
96
284
  ```
97
285
 
98
- #### `provider`
286
+ #### `DEFAULT_SERVICES_URL`
99
287
 
100
- The provider implementation (wire with `setProvider`).
288
+ Default hosted services base URL.
101
289
 
102
290
  ```typescript
103
- const provider: PushNotificationProvider
291
+ const DEFAULT_SERVICES_URL: 'https://api.molecule.dev/api/v1/services'
104
292
  ```
105
293
 
106
294
  #### `PUSH_SERVICE_LIMITS`
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@molecule/api-push-notifications-molecule",
3
- "version": "1.1.1",
3
+ "version": "1.1.2",
4
4
  "description": "molecule.dev hosted push notifications provider — web push delivery through your molecule project, VAPID handled for you",
5
5
  "homepage": "https://www.molecule.dev/packages/api-push-notifications-molecule",
6
6
  "type": "module",
@@ -39,10 +39,10 @@
39
39
  "@molecule/api-secrets": "^1.0.1"
40
40
  },
41
41
  "devDependencies": {
42
- "@molecule/api-push-notifications": "1.0.2",
43
- "@types/node": "26.1.2",
42
+ "@molecule/api-push-notifications": "1.0.3",
43
+ "@types/node": "26.6.5",
44
44
  "typescript": "6.0.3",
45
- "vitest": "4.1.11"
45
+ "vitest": "4.1.12"
46
46
  },
47
47
  "author": "Molecule Dev, Inc. (https://molecule.dev)",
48
48
  "publishConfig": {