pushq 0.1.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 pushq contributors
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 ADDED
@@ -0,0 +1,63 @@
1
+ # pushq (TypeScript / JavaScript)
2
+
3
+ Client for [pushq](https://github.com/blissfulrays/pushq) — a self-hosted HTTP push
4
+ task queue (open-source alternative to GCP Cloud Tasks). Zero dependencies,
5
+ `fetch`-based: works in Node 18+, Bun, Deno, and edge runtimes.
6
+
7
+ ```bash
8
+ npm install pushq
9
+ ```
10
+
11
+ ## Enqueue
12
+
13
+ ```ts
14
+ import { Pushq } from "pushq";
15
+
16
+ const pq = new Pushq({ baseUrl: "http://localhost:8080", apiKey: "pq_..." });
17
+
18
+ // Queues are created/updated at runtime — idempotent, safe to call on every enqueue.
19
+ await pq.upsertQueue("account-42", {
20
+ rateLimits: { maxDispatchesPerSecond: 10, maxConcurrentDispatches: 5 },
21
+ target: { baseUrl: "https://api.example.com", signingSecret: "whsec_..." },
22
+ });
23
+
24
+ await pq.createTask("account-42", {
25
+ path: "/hooks/send-message", // resolved against the queue's baseUrl
26
+ jsonBody: { userId: 1 },
27
+ delaySeconds: 3600, // or scheduleTime: new Date(...)
28
+ taskId: "follow_up_abc", // optional: dedup (409 on collision)
29
+ retry: { maxAttempts: 3 }, // per-task override of the queue config
30
+ });
31
+
32
+ // Operate queues at runtime
33
+ await pq.pauseQueue("account-42");
34
+ await pq.resumeQueue("account-42");
35
+ await pq.purgeQueue("account-42");
36
+ const stats = await pq.queueStats("account-42", { idPrefix: "follow_up_" });
37
+ ```
38
+
39
+ ## Verify deliveries (Express / Hono / edge)
40
+
41
+ pushq signs deliveries using the [Standard Webhooks](https://www.standardwebhooks.com)
42
+ scheme (`webhook-id`, `webhook-timestamp`, `webhook-signature` headers).
43
+
44
+ ```ts
45
+ import { verifySignature, WebhookVerificationError } from "pushq";
46
+
47
+ app.post("/hooks/send-message", async (req, res) => {
48
+ try {
49
+ // Returns "queue/task_id" — stable across retries, use as an idempotency key.
50
+ const id = await verifySignature({
51
+ secret: "whsec_...",
52
+ headers: req.headers,
53
+ payload: rawBody, // the exact raw request body
54
+ });
55
+ } catch (err) {
56
+ return res.status(401).end();
57
+ }
58
+ // ...
59
+ });
60
+ ```
61
+
62
+ Errors reject with `PushqError` carrying `.status`, `.code`
63
+ (`already_exists`, `not_found`, `failed_precondition`, …), and `.detail`.
package/dist/index.cjs ADDED
@@ -0,0 +1,447 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ Pushq: () => Pushq,
24
+ PushqError: () => PushqError,
25
+ WebhookVerificationError: () => WebhookVerificationError,
26
+ sign: () => sign,
27
+ verifySignature: () => verifySignature
28
+ });
29
+ module.exports = __toCommonJS(index_exports);
30
+
31
+ // src/wire.ts
32
+ var toB64 = (data) => {
33
+ let bin = "";
34
+ for (const b of data) bin += String.fromCharCode(b);
35
+ return btoa(bin);
36
+ };
37
+ var fromB64 = (s) => {
38
+ const bin = atob(s);
39
+ const out = new Uint8Array(bin.length);
40
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
41
+ return out;
42
+ };
43
+ var date = (s) => s ? new Date(s) : void 0;
44
+ function retryToWire(r) {
45
+ if (!r) return void 0;
46
+ return prune({
47
+ max_attempts: r.maxAttempts,
48
+ max_retry_duration_seconds: r.maxRetryDurationSeconds,
49
+ min_backoff_seconds: r.minBackoffSeconds,
50
+ max_backoff_seconds: r.maxBackoffSeconds,
51
+ max_doublings: r.maxDoublings
52
+ });
53
+ }
54
+ function retryFromWire(w) {
55
+ if (!w) return void 0;
56
+ return {
57
+ maxAttempts: w.max_attempts,
58
+ maxRetryDurationSeconds: w.max_retry_duration_seconds,
59
+ minBackoffSeconds: w.min_backoff_seconds,
60
+ maxBackoffSeconds: w.max_backoff_seconds,
61
+ maxDoublings: w.max_doublings
62
+ };
63
+ }
64
+ function prune(obj) {
65
+ const out = {};
66
+ let any = false;
67
+ for (const [k, v] of Object.entries(obj)) {
68
+ if (v !== void 0) {
69
+ out[k] = v;
70
+ any = true;
71
+ }
72
+ }
73
+ return any ? out : void 0;
74
+ }
75
+ function queueConfigToWire(cfg) {
76
+ const target = cfg.target ? prune({
77
+ base_url: cfg.target.baseUrl,
78
+ method: cfg.target.method,
79
+ headers: cfg.target.headers,
80
+ signing_secret: cfg.target.signingSecret
81
+ }) : void 0;
82
+ const rateLimits = cfg.rateLimits ? prune({
83
+ max_dispatches_per_second: cfg.rateLimits.maxDispatchesPerSecond,
84
+ max_burst_size: cfg.rateLimits.maxBurstSize,
85
+ max_concurrent_dispatches: cfg.rateLimits.maxConcurrentDispatches
86
+ }) : void 0;
87
+ return prune({
88
+ state: cfg.state,
89
+ rate_limits: rateLimits,
90
+ retry: retryToWire(cfg.retry),
91
+ target,
92
+ dead_letter_queue: cfg.deadLetterQueue
93
+ }) ?? {};
94
+ }
95
+ function queueFromWire(w) {
96
+ return {
97
+ name: w.name,
98
+ state: w.state,
99
+ rateLimits: {
100
+ maxDispatchesPerSecond: w.rate_limits.max_dispatches_per_second,
101
+ maxBurstSize: w.rate_limits.max_burst_size,
102
+ maxConcurrentDispatches: w.rate_limits.max_concurrent_dispatches
103
+ },
104
+ retry: retryFromWire(w.retry),
105
+ target: {
106
+ baseUrl: w.target?.base_url,
107
+ method: w.target?.method,
108
+ headers: w.target?.headers,
109
+ hasSigningSecret: !!w.target?.has_signing_secret
110
+ },
111
+ deadLetterQueue: w.dead_letter_queue,
112
+ purgedAt: date(w.purged_at),
113
+ createdAt: new Date(w.created_at),
114
+ updatedAt: new Date(w.updated_at)
115
+ };
116
+ }
117
+ function statsFromWire(w) {
118
+ return {
119
+ state: w.state,
120
+ pending: w.pending,
121
+ running: w.running,
122
+ succeeded: w.succeeded,
123
+ failed: w.failed,
124
+ scheduledFuture: w.scheduled_future,
125
+ oldestDueAt: date(w.oldest_due_at),
126
+ oldestDueAgeSeconds: w.oldest_due_age_seconds,
127
+ dispatchedLast1m: w.dispatched_last_1m,
128
+ errorsLast1m: w.errors_last_1m,
129
+ dispatchedLast1h: w.dispatched_last_1h,
130
+ errorsLast1h: w.errors_last_1h,
131
+ lastPurge: date(w.last_purge)
132
+ };
133
+ }
134
+ function taskCreateToWire(t) {
135
+ if (t.body !== void 0 && t.jsonBody !== void 0) {
136
+ throw new Error("pushq: provide body or jsonBody, not both");
137
+ }
138
+ let bodyBase64;
139
+ if (typeof t.body === "string") {
140
+ bodyBase64 = toB64(new TextEncoder().encode(t.body));
141
+ } else if (t.body instanceof Uint8Array) {
142
+ bodyBase64 = toB64(t.body);
143
+ }
144
+ const schedule = t.scheduleTime instanceof Date ? t.scheduleTime.toISOString() : t.scheduleTime;
145
+ return prune({
146
+ task_id: t.taskId,
147
+ url: t.url,
148
+ path: t.path,
149
+ method: t.method,
150
+ headers: t.headers,
151
+ body_base64: bodyBase64,
152
+ json_body: t.jsonBody,
153
+ schedule_time: schedule,
154
+ delay_seconds: t.delaySeconds,
155
+ dispatch_deadline_seconds: t.dispatchDeadlineSeconds,
156
+ retry: retryToWire(t.retry)
157
+ }) ?? {};
158
+ }
159
+ function taskFromWire(w) {
160
+ return {
161
+ id: w.id,
162
+ queue: w.queue,
163
+ state: w.state,
164
+ url: w.url,
165
+ method: w.method,
166
+ headers: w.headers,
167
+ body: w.body_base64 ? fromB64(w.body_base64) : void 0,
168
+ scheduleTime: new Date(w.schedule_time),
169
+ createdAt: new Date(w.created_at),
170
+ dispatchDeadlineSeconds: w.dispatch_deadline_seconds,
171
+ retry: retryFromWire(w.retry),
172
+ dispatchCount: w.dispatch_count,
173
+ responseCount: w.response_count,
174
+ firstAttemptAt: date(w.first_attempt_at),
175
+ finishedAt: date(w.finished_at),
176
+ lastAttempt: w.last_attempt ? { at: new Date(w.last_attempt.at), status: w.last_attempt.status, error: w.last_attempt.error } : void 0
177
+ };
178
+ }
179
+ function attemptFromWire(w) {
180
+ return {
181
+ number: w.number,
182
+ dispatchTime: new Date(w.dispatch_time),
183
+ responseTime: date(w.response_time),
184
+ responseStatus: w.response_status,
185
+ errorKind: w.error_kind,
186
+ errorSnippet: w.error_snippet,
187
+ durationMs: w.duration_ms
188
+ };
189
+ }
190
+ function batchResultFromWire(w) {
191
+ return {
192
+ index: w.index,
193
+ task: w.task ? taskFromWire(w.task) : void 0,
194
+ error: w.error
195
+ };
196
+ }
197
+
198
+ // src/client.ts
199
+ var PushqError = class extends Error {
200
+ constructor(status, code, detail) {
201
+ super(`pushq: ${code} (${status}): ${detail}`);
202
+ this.name = "PushqError";
203
+ this.status = status;
204
+ this.code = code;
205
+ this.detail = detail;
206
+ }
207
+ };
208
+ var Pushq = class {
209
+ constructor(opts) {
210
+ this.base = opts.baseUrl.replace(/\/+$/, "");
211
+ this.apiKey = opts.apiKey;
212
+ this.timeoutMs = opts.timeoutMs ?? 3e4;
213
+ this.fetchFn = opts.fetch ?? globalThis.fetch;
214
+ if (!this.fetchFn) throw new Error("pushq: no fetch available; pass options.fetch");
215
+ }
216
+ // --- queues ---
217
+ /** Create or replace queue config (idempotent; never changes run state). */
218
+ async upsertQueue(name, cfg = {}) {
219
+ return queueFromWire(await this.request("PUT", `/v1/queues/${enc(name)}`, queueConfigToWire(cfg)));
220
+ }
221
+ /** Create a queue; rejects with already_exists if present. */
222
+ async createQueue(name, cfg = {}) {
223
+ return queueFromWire(await this.request("POST", `/v1/queues`, { name, ...queueConfigToWire(cfg) }));
224
+ }
225
+ async getQueue(name) {
226
+ return queueFromWire(await this.request("GET", `/v1/queues/${enc(name)}`));
227
+ }
228
+ /** Update only the provided fields (can set state, including "disabled"). */
229
+ async patchQueue(name, patch) {
230
+ return queueFromWire(await this.request("PATCH", `/v1/queues/${enc(name)}`, queueConfigToWire(patch)));
231
+ }
232
+ /** Admin role required. */
233
+ async listQueues(params = {}) {
234
+ const w = await this.request("GET", `/v1/queues${query({
235
+ name_prefix: params.namePrefix,
236
+ page_size: params.pageSize,
237
+ page_token: params.pageToken
238
+ })}`);
239
+ return { items: (w.queues ?? []).map(queueFromWire), nextPageToken: w.next_page_token || void 0 };
240
+ }
241
+ /** Admin role required. Deletes the queue and every task in it. */
242
+ async deleteQueue(name) {
243
+ await this.request("DELETE", `/v1/queues/${enc(name)}`);
244
+ }
245
+ async pauseQueue(name) {
246
+ return queueFromWire(await this.request("POST", `/v1/queues/${enc(name)}:pause`));
247
+ }
248
+ async resumeQueue(name) {
249
+ return queueFromWire(await this.request("POST", `/v1/queues/${enc(name)}:resume`));
250
+ }
251
+ /** Deletes every task created up to now (exact watermark; IDs become reusable). */
252
+ async purgeQueue(name) {
253
+ return queueFromWire(await this.request("POST", `/v1/queues/${enc(name)}:purge`));
254
+ }
255
+ async queueStats(name, opts = {}) {
256
+ return statsFromWire(await this.request(
257
+ "GET",
258
+ `/v1/queues/${enc(name)}/stats${query({ id_prefix: opts.idPrefix })}`
259
+ ));
260
+ }
261
+ // --- tasks ---
262
+ async createTask(queue, task) {
263
+ return taskFromWire(await this.request("POST", `/v1/queues/${enc(queue)}/tasks`, taskCreateToWire(task)));
264
+ }
265
+ /** Enqueue up to 500 tasks; non-atomic, per-item results in order. */
266
+ async createTasks(queue, tasks) {
267
+ const w = await this.request("POST", `/v1/queues/${enc(queue)}/tasks:batch`, {
268
+ tasks: tasks.map(taskCreateToWire)
269
+ });
270
+ return (w.results ?? []).map(batchResultFromWire);
271
+ }
272
+ async getTask(queue, id, opts = {}) {
273
+ return taskFromWire(await this.request(
274
+ "GET",
275
+ `/v1/queues/${enc(queue)}/tasks/${enc(id)}${query({ view: opts.view })}`
276
+ ));
277
+ }
278
+ async listTasks(queue, params = {}) {
279
+ const w = await this.request("GET", `/v1/queues/${enc(queue)}/tasks${query({
280
+ state: params.state,
281
+ id_prefix: params.idPrefix,
282
+ view: params.view,
283
+ page_size: params.pageSize,
284
+ page_token: params.pageToken
285
+ })}`);
286
+ return { items: (w.tasks ?? []).map(taskFromWire), nextPageToken: w.next_page_token || void 0 };
287
+ }
288
+ /** Deletes a task; the ID stays reserved for the dedup window. */
289
+ async deleteTask(queue, id) {
290
+ await this.request("DELETE", `/v1/queues/${enc(queue)}/tasks/${enc(id)}`);
291
+ }
292
+ /** Force immediate dispatch, bypassing rate limits and PAUSED state. */
293
+ async runTask(queue, id) {
294
+ return taskFromWire(await this.request("POST", `/v1/queues/${enc(queue)}/tasks/${enc(id)}:run`));
295
+ }
296
+ async listAttempts(queue, id) {
297
+ const w = await this.request("GET", `/v1/queues/${enc(queue)}/tasks/${enc(id)}/attempts`);
298
+ return (w.attempts ?? []).map(attemptFromWire);
299
+ }
300
+ // --- plumbing ---
301
+ async request(method, path, body) {
302
+ const headers = { Accept: "application/json" };
303
+ if (this.apiKey) headers.Authorization = `Bearer ${this.apiKey}`;
304
+ if (body !== void 0) headers["Content-Type"] = "application/json";
305
+ const resp = await this.fetchFn(this.base + path, {
306
+ method,
307
+ headers,
308
+ body: body === void 0 ? void 0 : JSON.stringify(body),
309
+ signal: AbortSignal.timeout(this.timeoutMs)
310
+ });
311
+ if (resp.status === 204) return void 0;
312
+ const text = await resp.text();
313
+ let parsed;
314
+ try {
315
+ parsed = text ? JSON.parse(text) : void 0;
316
+ } catch {
317
+ parsed = void 0;
318
+ }
319
+ if (!resp.ok) {
320
+ throw new PushqError(
321
+ resp.status,
322
+ parsed?.code ?? "internal",
323
+ parsed?.detail ?? parsed?.title ?? text.slice(0, 200) ?? resp.statusText
324
+ );
325
+ }
326
+ return parsed;
327
+ }
328
+ };
329
+ var enc = encodeURIComponent;
330
+ function query(params) {
331
+ const parts = [];
332
+ for (const [k, v] of Object.entries(params)) {
333
+ if (v !== void 0 && v !== "") parts.push(`${k}=${encodeURIComponent(String(v))}`);
334
+ }
335
+ return parts.length ? `?${parts.join("&")}` : "";
336
+ }
337
+
338
+ // src/webhooks.ts
339
+ var WebhookVerificationError = class extends Error {
340
+ constructor(message) {
341
+ super(`pushq webhook verification failed: ${message}`);
342
+ this.name = "WebhookVerificationError";
343
+ }
344
+ };
345
+ async function verifySignature(opts) {
346
+ const get = headerGetter(opts.headers);
347
+ const id = get("webhook-id");
348
+ const tsRaw = get("webhook-timestamp");
349
+ const sigHeader = get("webhook-signature");
350
+ if (!id || !tsRaw || !sigHeader) {
351
+ throw new WebhookVerificationError("missing webhook-id/-timestamp/-signature headers");
352
+ }
353
+ const ts = Number(tsRaw);
354
+ if (!Number.isFinite(ts)) throw new WebhookVerificationError("invalid timestamp");
355
+ const tolerance = opts.toleranceSeconds ?? 300;
356
+ if (tolerance > 0) {
357
+ const now = (opts.now ?? /* @__PURE__ */ new Date()).getTime() / 1e3;
358
+ if (Math.abs(now - ts) > tolerance) {
359
+ throw new WebhookVerificationError("timestamp outside tolerance");
360
+ }
361
+ }
362
+ const payload = typeof opts.payload === "string" ? new TextEncoder().encode(opts.payload) : opts.payload;
363
+ const prefix = new TextEncoder().encode(`${id}.${ts}.`);
364
+ const message = new Uint8Array(prefix.length + payload.length);
365
+ message.set(prefix);
366
+ message.set(payload, prefix.length);
367
+ const key = await crypto.subtle.importKey(
368
+ "raw",
369
+ signingKey(opts.secret),
370
+ { name: "HMAC", hash: "SHA-256" },
371
+ false,
372
+ ["verify"]
373
+ );
374
+ for (const part of sigHeader.split(/\s+/)) {
375
+ const [version, sig] = splitOnce(part, ",");
376
+ if (version !== "v1" || !sig) continue;
377
+ let sigBytes;
378
+ try {
379
+ sigBytes = b64decode(sig);
380
+ } catch {
381
+ continue;
382
+ }
383
+ if (await crypto.subtle.verify("HMAC", key, toArrayBuffer(sigBytes), toArrayBuffer(message))) {
384
+ return id;
385
+ }
386
+ }
387
+ throw new WebhookVerificationError("no matching signature");
388
+ }
389
+ async function sign(secret, msgId, timestampSeconds, payload) {
390
+ const body = typeof payload === "string" ? new TextEncoder().encode(payload) : payload;
391
+ const prefix = new TextEncoder().encode(`${msgId}.${timestampSeconds}.`);
392
+ const message = new Uint8Array(prefix.length + body.length);
393
+ message.set(prefix);
394
+ message.set(body, prefix.length);
395
+ const key = await crypto.subtle.importKey(
396
+ "raw",
397
+ signingKey(secret),
398
+ { name: "HMAC", hash: "SHA-256" },
399
+ false,
400
+ ["sign"]
401
+ );
402
+ const mac = new Uint8Array(await crypto.subtle.sign("HMAC", key, toArrayBuffer(message)));
403
+ return `v1,${b64encode(mac)}`;
404
+ }
405
+ function signingKey(secret) {
406
+ if (secret.startsWith("whsec_")) {
407
+ return toArrayBuffer(b64decode(secret.slice("whsec_".length)));
408
+ }
409
+ return toArrayBuffer(new TextEncoder().encode(secret));
410
+ }
411
+ function headerGetter(headers) {
412
+ if (typeof headers.get === "function") {
413
+ return (name) => headers.get(name) ?? void 0;
414
+ }
415
+ const lower = {};
416
+ for (const [k, v] of Object.entries(headers)) {
417
+ if (v === void 0) continue;
418
+ lower[k.toLowerCase()] = Array.isArray(v) ? v[0] : v;
419
+ }
420
+ return (name) => lower[name.toLowerCase()];
421
+ }
422
+ function splitOnce(s, sep) {
423
+ const i = s.indexOf(sep);
424
+ return i === -1 ? [s, void 0] : [s.slice(0, i), s.slice(i + 1)];
425
+ }
426
+ function b64decode(s) {
427
+ const bin = atob(s);
428
+ const out = new Uint8Array(bin.length);
429
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
430
+ return out;
431
+ }
432
+ function b64encode(data) {
433
+ let bin = "";
434
+ for (const b of data) bin += String.fromCharCode(b);
435
+ return btoa(bin);
436
+ }
437
+ function toArrayBuffer(view) {
438
+ return view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength);
439
+ }
440
+ // Annotate the CommonJS export names for ESM import in node:
441
+ 0 && (module.exports = {
442
+ Pushq,
443
+ PushqError,
444
+ WebhookVerificationError,
445
+ sign,
446
+ verifySignature
447
+ });