@webhooks-cc/sdk 0.2.0 → 0.3.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.mjs CHANGED
@@ -34,18 +34,148 @@ var RateLimitError = class extends WebhooksCCError {
34
34
  }
35
35
  };
36
36
 
37
+ // src/utils.ts
38
+ var DURATION_REGEX = /^(\d+(?:\.\d+)?)\s*(ms|s|m|h)$/;
39
+ function parseDuration(input) {
40
+ if (typeof input === "number") {
41
+ if (!Number.isFinite(input) || input < 0) {
42
+ throw new Error(`Invalid duration: must be a finite non-negative number, got ${input}`);
43
+ }
44
+ return input;
45
+ }
46
+ const trimmed = input.trim();
47
+ const asNumber = Number(trimmed);
48
+ if (!isNaN(asNumber) && trimmed.length > 0) {
49
+ if (!Number.isFinite(asNumber) || asNumber < 0) {
50
+ throw new Error(`Invalid duration: must be a finite non-negative number, got "${input}"`);
51
+ }
52
+ return asNumber;
53
+ }
54
+ const match = DURATION_REGEX.exec(trimmed);
55
+ if (!match) {
56
+ throw new Error(`Invalid duration: "${input}"`);
57
+ }
58
+ const value = parseFloat(match[1]);
59
+ switch (match[2]) {
60
+ case "ms":
61
+ return value;
62
+ case "s":
63
+ return value * 1e3;
64
+ case "m":
65
+ return value * 6e4;
66
+ case "h":
67
+ return value * 36e5;
68
+ default:
69
+ throw new Error(`Invalid duration: "${input}"`);
70
+ }
71
+ }
72
+
73
+ // src/sse.ts
74
+ async function* parseSSE(stream) {
75
+ const reader = stream.getReader();
76
+ const decoder = new TextDecoder();
77
+ let buffer = "";
78
+ let currentEvent = "message";
79
+ let dataLines = [];
80
+ try {
81
+ while (true) {
82
+ const { done, value } = await reader.read();
83
+ if (done) break;
84
+ buffer += decoder.decode(value, { stream: true });
85
+ const lines = buffer.split("\n");
86
+ buffer = lines.pop();
87
+ for (const line of lines) {
88
+ if (line === "" || line === "\r") {
89
+ if (dataLines.length > 0) {
90
+ yield { event: currentEvent, data: dataLines.join("\n") };
91
+ dataLines = [];
92
+ currentEvent = "message";
93
+ }
94
+ continue;
95
+ }
96
+ const trimmedLine = line.endsWith("\r") ? line.slice(0, -1) : line;
97
+ if (trimmedLine.startsWith(":")) {
98
+ const rawComment = trimmedLine.slice(1);
99
+ yield {
100
+ event: "comment",
101
+ data: rawComment.startsWith(" ") ? rawComment.slice(1) : rawComment
102
+ };
103
+ continue;
104
+ }
105
+ const colonIdx = trimmedLine.indexOf(":");
106
+ if (colonIdx === -1) continue;
107
+ const field = trimmedLine.slice(0, colonIdx);
108
+ const rawVal = trimmedLine.slice(colonIdx + 1);
109
+ const val = rawVal.startsWith(" ") ? rawVal.slice(1) : rawVal;
110
+ switch (field) {
111
+ case "event":
112
+ currentEvent = val;
113
+ break;
114
+ case "data":
115
+ dataLines.push(val);
116
+ break;
117
+ }
118
+ }
119
+ }
120
+ if (buffer.length > 0) {
121
+ const trimmedLine = buffer.endsWith("\r") ? buffer.slice(0, -1) : buffer;
122
+ if (trimmedLine.startsWith(":")) {
123
+ const rawComment = trimmedLine.slice(1);
124
+ yield {
125
+ event: "comment",
126
+ data: rawComment.startsWith(" ") ? rawComment.slice(1) : rawComment
127
+ };
128
+ } else {
129
+ const colonIdx = trimmedLine.indexOf(":");
130
+ if (colonIdx !== -1) {
131
+ const field = trimmedLine.slice(0, colonIdx);
132
+ const rawVal = trimmedLine.slice(colonIdx + 1);
133
+ const val = rawVal.startsWith(" ") ? rawVal.slice(1) : rawVal;
134
+ if (field === "event") currentEvent = val;
135
+ else if (field === "data") dataLines.push(val);
136
+ }
137
+ }
138
+ }
139
+ if (dataLines.length > 0) {
140
+ yield { event: currentEvent, data: dataLines.join("\n") };
141
+ }
142
+ } finally {
143
+ await reader.cancel();
144
+ reader.releaseLock();
145
+ }
146
+ }
147
+
37
148
  // src/client.ts
38
149
  var DEFAULT_BASE_URL = "https://webhooks.cc";
150
+ var DEFAULT_WEBHOOK_URL = "https://go.webhooks.cc";
39
151
  var DEFAULT_TIMEOUT = 3e4;
152
+ var SDK_VERSION = "0.3.0";
40
153
  var MIN_POLL_INTERVAL = 10;
41
154
  var MAX_POLL_INTERVAL = 6e4;
155
+ var ALLOWED_METHODS = /* @__PURE__ */ new Set(["GET", "HEAD", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"]);
156
+ var HOP_BY_HOP_HEADERS = /* @__PURE__ */ new Set([
157
+ "host",
158
+ "connection",
159
+ "content-length",
160
+ "transfer-encoding",
161
+ "keep-alive",
162
+ "te",
163
+ "trailer",
164
+ "upgrade"
165
+ ]);
166
+ var SENSITIVE_HEADERS = /* @__PURE__ */ new Set(["authorization", "cookie", "proxy-authorization", "set-cookie"]);
42
167
  var ApiError = WebhooksCCError;
43
168
  function mapStatusToError(status, message, response) {
169
+ const isGeneric = message.length < 30;
44
170
  switch (status) {
45
- case 401:
46
- return new UnauthorizedError(message);
47
- case 404:
48
- return new NotFoundError(message);
171
+ case 401: {
172
+ const hint = isGeneric ? `${message} \u2014 Get an API key at https://webhooks.cc/account` : message;
173
+ return new UnauthorizedError(hint);
174
+ }
175
+ case 404: {
176
+ const hint = isGeneric ? `${message} \u2014 Use client.endpoints.list() to see available endpoints.` : message;
177
+ return new NotFoundError(hint);
178
+ }
49
179
  case 429: {
50
180
  const retryAfterHeader = response.headers.get("retry-after");
51
181
  let retryAfter;
@@ -80,9 +210,44 @@ var WebhooksCC = class {
80
210
  validatePathSegment(slug, "slug");
81
211
  return this.request("GET", `/endpoints/${slug}`);
82
212
  },
213
+ update: async (slug, options) => {
214
+ validatePathSegment(slug, "slug");
215
+ if (options.mockResponse && options.mockResponse !== null) {
216
+ const { status } = options.mockResponse;
217
+ if (!Number.isInteger(status) || status < 100 || status > 599) {
218
+ throw new Error(`Invalid mock response status: ${status}. Must be an integer 100-599.`);
219
+ }
220
+ }
221
+ return this.request("PATCH", `/endpoints/${slug}`, options);
222
+ },
83
223
  delete: async (slug) => {
84
224
  validatePathSegment(slug, "slug");
85
225
  await this.request("DELETE", `/endpoints/${slug}`);
226
+ },
227
+ send: async (slug, options = {}) => {
228
+ validatePathSegment(slug, "slug");
229
+ const rawMethod = (options.method ?? "POST").toUpperCase();
230
+ if (!ALLOWED_METHODS.has(rawMethod)) {
231
+ throw new Error(
232
+ `Invalid HTTP method: "${options.method}". Must be one of: ${[...ALLOWED_METHODS].join(", ")}`
233
+ );
234
+ }
235
+ const { headers = {}, body } = options;
236
+ const method = rawMethod;
237
+ const url = `${this.webhookUrl}/w/${slug}`;
238
+ const fetchHeaders = { ...headers };
239
+ const hasContentType = Object.keys(fetchHeaders).some(
240
+ (k) => k.toLowerCase() === "content-type"
241
+ );
242
+ if (body !== void 0 && !hasContentType) {
243
+ fetchHeaders["Content-Type"] = "application/json";
244
+ }
245
+ return fetch(url, {
246
+ method,
247
+ headers: fetchHeaders,
248
+ body: body !== void 0 ? typeof body === "string" ? body : JSON.stringify(body) : void 0,
249
+ signal: AbortSignal.timeout(this.timeout)
250
+ });
86
251
  }
87
252
  };
88
253
  this.requests = {
@@ -115,13 +280,15 @@ var WebhooksCC = class {
115
280
  */
116
281
  waitFor: async (endpointSlug, options = {}) => {
117
282
  validatePathSegment(endpointSlug, "endpointSlug");
118
- const { timeout = 3e4, pollInterval = 500, match } = options;
283
+ const timeout = parseDuration(options.timeout ?? 3e4);
284
+ const rawPollInterval = parseDuration(options.pollInterval ?? 500);
285
+ const { match } = options;
119
286
  const safePollInterval = Math.max(
120
287
  MIN_POLL_INTERVAL,
121
- Math.min(MAX_POLL_INTERVAL, pollInterval)
288
+ Math.min(MAX_POLL_INTERVAL, rawPollInterval)
122
289
  );
123
290
  const start = Date.now();
124
- let lastChecked = 0;
291
+ let lastChecked = start - 5 * 60 * 1e3;
125
292
  const MAX_ITERATIONS = 1e4;
126
293
  let iterations = 0;
127
294
  while (Date.now() - start < timeout && iterations < MAX_ITERATIONS) {
@@ -153,10 +320,187 @@ var WebhooksCC = class {
153
320
  await sleep(safePollInterval);
154
321
  }
155
322
  throw new TimeoutError(timeout);
323
+ },
324
+ /**
325
+ * Replay a captured request to a target URL.
326
+ *
327
+ * Fetches the original request by ID and re-sends it to the specified URL
328
+ * with the original method, headers, and body. Hop-by-hop headers are stripped.
329
+ */
330
+ replay: async (requestId, targetUrl) => {
331
+ validatePathSegment(requestId, "requestId");
332
+ let parsed;
333
+ try {
334
+ parsed = new URL(targetUrl);
335
+ } catch {
336
+ throw new Error(`Invalid targetUrl: "${targetUrl}" is not a valid URL`);
337
+ }
338
+ if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
339
+ throw new Error(`Invalid targetUrl: only http and https protocols are supported`);
340
+ }
341
+ const captured = await this.requests.get(requestId);
342
+ const headers = {};
343
+ for (const [key, val] of Object.entries(captured.headers)) {
344
+ const lower = key.toLowerCase();
345
+ if (!HOP_BY_HOP_HEADERS.has(lower) && !SENSITIVE_HEADERS.has(lower)) {
346
+ headers[key] = val;
347
+ }
348
+ }
349
+ const upperMethod = captured.method.toUpperCase();
350
+ const body = upperMethod === "GET" || upperMethod === "HEAD" ? void 0 : captured.body ?? void 0;
351
+ return fetch(targetUrl, {
352
+ method: captured.method,
353
+ headers,
354
+ body,
355
+ signal: AbortSignal.timeout(this.timeout)
356
+ });
357
+ },
358
+ /**
359
+ * Stream incoming requests via SSE as an async iterator.
360
+ *
361
+ * Connects to the SSE endpoint and yields Request objects as they arrive.
362
+ * The connection is closed when the iterator is broken, the signal is aborted,
363
+ * or the timeout expires.
364
+ *
365
+ * No automatic reconnection — if the connection drops, the iterator ends.
366
+ */
367
+ subscribe: (slug, options = {}) => {
368
+ validatePathSegment(slug, "slug");
369
+ const { signal, timeout } = options;
370
+ const baseUrl = this.baseUrl;
371
+ const apiKey = this.apiKey;
372
+ const timeoutMs = timeout !== void 0 ? parseDuration(timeout) : void 0;
373
+ return {
374
+ [Symbol.asyncIterator]() {
375
+ const controller = new AbortController();
376
+ let timeoutId;
377
+ let iterator = null;
378
+ let started = false;
379
+ const onAbort = () => controller.abort();
380
+ if (signal) {
381
+ if (signal.aborted) {
382
+ controller.abort();
383
+ } else {
384
+ signal.addEventListener("abort", onAbort, { once: true });
385
+ }
386
+ }
387
+ if (timeoutMs !== void 0) {
388
+ timeoutId = setTimeout(() => controller.abort(), timeoutMs);
389
+ }
390
+ const cleanup = () => {
391
+ if (timeoutId !== void 0) clearTimeout(timeoutId);
392
+ if (signal) signal.removeEventListener("abort", onAbort);
393
+ };
394
+ const start = async () => {
395
+ const url = `${baseUrl}/api/stream/${slug}`;
396
+ const connectController = new AbortController();
397
+ const connectTimeout = setTimeout(() => connectController.abort(), 3e4);
398
+ controller.signal.addEventListener("abort", () => connectController.abort(), {
399
+ once: true
400
+ });
401
+ let response;
402
+ try {
403
+ response = await fetch(url, {
404
+ headers: { Authorization: `Bearer ${apiKey}` },
405
+ signal: connectController.signal
406
+ });
407
+ } finally {
408
+ clearTimeout(connectTimeout);
409
+ }
410
+ if (!response.ok) {
411
+ cleanup();
412
+ const text = await response.text();
413
+ throw mapStatusToError(response.status, text, response);
414
+ }
415
+ if (!response.body) {
416
+ cleanup();
417
+ throw new Error("SSE response has no body");
418
+ }
419
+ controller.signal.addEventListener(
420
+ "abort",
421
+ () => {
422
+ response.body?.cancel().catch(() => {
423
+ });
424
+ },
425
+ { once: true }
426
+ );
427
+ return parseSSE(response.body);
428
+ };
429
+ return {
430
+ [Symbol.asyncIterator]() {
431
+ return this;
432
+ },
433
+ async next() {
434
+ try {
435
+ if (!started) {
436
+ started = true;
437
+ iterator = await start();
438
+ }
439
+ while (iterator) {
440
+ const { done, value } = await iterator.next();
441
+ if (done) {
442
+ cleanup();
443
+ return { done: true, value: void 0 };
444
+ }
445
+ if (value.event === "request") {
446
+ try {
447
+ const data = JSON.parse(value.data);
448
+ if (!data.endpointId || !data.method || !data.headers || !data.receivedAt) {
449
+ continue;
450
+ }
451
+ const req = {
452
+ id: data._id ?? data.id,
453
+ endpointId: data.endpointId,
454
+ method: data.method,
455
+ path: data.path ?? "/",
456
+ headers: data.headers,
457
+ body: data.body ?? void 0,
458
+ queryParams: data.queryParams ?? {},
459
+ contentType: data.contentType ?? void 0,
460
+ ip: data.ip ?? "unknown",
461
+ size: data.size ?? 0,
462
+ receivedAt: data.receivedAt
463
+ };
464
+ return { done: false, value: req };
465
+ } catch {
466
+ continue;
467
+ }
468
+ }
469
+ if (value.event === "timeout" || value.event === "endpoint_deleted") {
470
+ cleanup();
471
+ return { done: true, value: void 0 };
472
+ }
473
+ }
474
+ cleanup();
475
+ return { done: true, value: void 0 };
476
+ } catch (error) {
477
+ cleanup();
478
+ controller.abort();
479
+ if (error instanceof Error && error.name === "AbortError") {
480
+ return { done: true, value: void 0 };
481
+ }
482
+ throw error;
483
+ }
484
+ },
485
+ async return() {
486
+ cleanup();
487
+ controller.abort();
488
+ if (iterator) {
489
+ await iterator.return(void 0);
490
+ }
491
+ return { done: true, value: void 0 };
492
+ }
493
+ };
494
+ }
495
+ };
156
496
  }
157
497
  };
498
+ if (!options.apiKey || typeof options.apiKey !== "string") {
499
+ throw new Error("Missing or invalid apiKey. Get one at https://webhooks.cc/account");
500
+ }
158
501
  this.apiKey = options.apiKey;
159
- this.baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;
502
+ this.baseUrl = stripTrailingSlashes(options.baseUrl ?? DEFAULT_BASE_URL);
503
+ this.webhookUrl = stripTrailingSlashes(options.webhookUrl ?? DEFAULT_WEBHOOK_URL);
160
504
  this.timeout = options.timeout ?? DEFAULT_TIMEOUT;
161
505
  this.hooks = options.hooks ?? {};
162
506
  }
@@ -221,10 +565,73 @@ var WebhooksCC = class {
221
565
  clearTimeout(timeoutId);
222
566
  }
223
567
  }
568
+ /** Returns a static description of all SDK operations (no API call). */
569
+ describe() {
570
+ return {
571
+ version: SDK_VERSION,
572
+ endpoints: {
573
+ create: {
574
+ description: "Create a webhook endpoint",
575
+ params: { name: "string?" }
576
+ },
577
+ list: {
578
+ description: "List all endpoints",
579
+ params: {}
580
+ },
581
+ get: {
582
+ description: "Get endpoint by slug",
583
+ params: { slug: "string" }
584
+ },
585
+ update: {
586
+ description: "Update endpoint settings",
587
+ params: { slug: "string", name: "string?", mockResponse: "object?" }
588
+ },
589
+ delete: {
590
+ description: "Delete endpoint and its requests",
591
+ params: { slug: "string" }
592
+ },
593
+ send: {
594
+ description: "Send a test webhook to endpoint",
595
+ params: { slug: "string", method: "string?", headers: "object?", body: "unknown?" }
596
+ }
597
+ },
598
+ requests: {
599
+ list: {
600
+ description: "List captured requests",
601
+ params: { endpointSlug: "string", limit: "number?", since: "number?" }
602
+ },
603
+ get: {
604
+ description: "Get request by ID",
605
+ params: { requestId: "string" }
606
+ },
607
+ waitFor: {
608
+ description: "Poll until a matching request arrives",
609
+ params: {
610
+ endpointSlug: "string",
611
+ timeout: "number|string?",
612
+ match: "function?"
613
+ }
614
+ },
615
+ subscribe: {
616
+ description: "Stream requests via SSE",
617
+ params: { slug: "string", signal: "AbortSignal?", timeout: "number|string?" }
618
+ },
619
+ replay: {
620
+ description: "Replay a captured request to a URL",
621
+ params: { requestId: "string", targetUrl: "string" }
622
+ }
623
+ }
624
+ };
625
+ }
224
626
  };
225
627
  function sleep(ms) {
226
628
  return new Promise((resolve) => setTimeout(resolve, ms));
227
629
  }
630
+ function stripTrailingSlashes(url) {
631
+ let i = url.length;
632
+ while (i > 0 && url[i - 1] === "/") i--;
633
+ return i === url.length ? url : url.slice(0, i);
634
+ }
228
635
 
229
636
  // src/helpers.ts
230
637
  function parseJsonBody(request) {
@@ -249,6 +656,66 @@ function matchJsonField(field, value) {
249
656
  return body[field] === value;
250
657
  };
251
658
  }
659
+ function isShopifyWebhook(request) {
660
+ return Object.keys(request.headers).some((k) => k.toLowerCase() === "x-shopify-hmac-sha256");
661
+ }
662
+ function isSlackWebhook(request) {
663
+ return Object.keys(request.headers).some((k) => k.toLowerCase() === "x-slack-signature");
664
+ }
665
+ function isTwilioWebhook(request) {
666
+ return Object.keys(request.headers).some((k) => k.toLowerCase() === "x-twilio-signature");
667
+ }
668
+ function isPaddleWebhook(request) {
669
+ return Object.keys(request.headers).some((k) => k.toLowerCase() === "paddle-signature");
670
+ }
671
+ function isLinearWebhook(request) {
672
+ return Object.keys(request.headers).some((k) => k.toLowerCase() === "linear-signature");
673
+ }
674
+
675
+ // src/matchers.ts
676
+ function matchMethod(method) {
677
+ const upper = method.toUpperCase();
678
+ return (request) => request.method.toUpperCase() === upper;
679
+ }
680
+ function matchHeader(name, value) {
681
+ const lowerName = name.toLowerCase();
682
+ return (request) => {
683
+ const entry = Object.entries(request.headers).find(([k]) => k.toLowerCase() === lowerName);
684
+ if (!entry) return false;
685
+ if (value === void 0) return true;
686
+ return entry[1] === value;
687
+ };
688
+ }
689
+ function matchBodyPath(path, value) {
690
+ const keys = path.split(".");
691
+ return (request) => {
692
+ const body = parseJsonBody(request);
693
+ if (typeof body !== "object" || body === null) return false;
694
+ let current = body;
695
+ for (const key of keys) {
696
+ if (current === null || current === void 0) return false;
697
+ if (Array.isArray(current)) {
698
+ const idx = Number(key);
699
+ if (!Number.isInteger(idx) || idx < 0 || idx >= current.length) return false;
700
+ current = current[idx];
701
+ } else if (typeof current === "object") {
702
+ if (!Object.prototype.hasOwnProperty.call(current, key)) return false;
703
+ current = current[key];
704
+ } else {
705
+ return false;
706
+ }
707
+ }
708
+ return current === value;
709
+ };
710
+ }
711
+ function matchAll(first, ...rest) {
712
+ const matchers = [first, ...rest];
713
+ return (request) => matchers.every((m) => m(request));
714
+ }
715
+ function matchAny(first, ...rest) {
716
+ const matchers = [first, ...rest];
717
+ return (request) => matchers.some((m) => m(request));
718
+ }
252
719
  export {
253
720
  ApiError,
254
721
  NotFoundError,
@@ -258,7 +725,19 @@ export {
258
725
  WebhooksCC,
259
726
  WebhooksCCError,
260
727
  isGitHubWebhook,
728
+ isLinearWebhook,
729
+ isPaddleWebhook,
730
+ isShopifyWebhook,
731
+ isSlackWebhook,
261
732
  isStripeWebhook,
733
+ isTwilioWebhook,
734
+ matchAll,
735
+ matchAny,
736
+ matchBodyPath,
737
+ matchHeader,
262
738
  matchJsonField,
263
- parseJsonBody
739
+ matchMethod,
740
+ parseDuration,
741
+ parseJsonBody,
742
+ parseSSE
264
743
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@webhooks-cc/sdk",
3
- "version": "0.2.0",
3
+ "version": "0.3.1",
4
4
  "description": "TypeScript SDK for webhooks.cc — create endpoints, capture requests, assert in tests",
5
5
  "main": "dist/index.js",
6
6
  "module": "dist/index.mjs",