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