@trimlynk/sdk 0.0.0-stage → 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 (172) hide show
  1. package/LICENSE +19 -0
  2. package/README.md +68 -2
  3. package/dist/cjs/cli/commands/analytics.d.ts +3 -0
  4. package/dist/cjs/cli/commands/analytics.js +80 -0
  5. package/dist/cjs/cli/commands/auth.d.ts +4 -0
  6. package/dist/cjs/cli/commands/auth.js +122 -0
  7. package/dist/cjs/cli/commands/campaigns.d.ts +6 -0
  8. package/dist/cjs/cli/commands/campaigns.js +229 -0
  9. package/dist/cjs/cli/commands/config.d.ts +3 -0
  10. package/dist/cjs/cli/commands/config.js +51 -0
  11. package/dist/cjs/cli/commands/conversions.d.ts +4 -0
  12. package/dist/cjs/cli/commands/conversions.js +160 -0
  13. package/dist/cjs/cli/commands/links.d.ts +6 -0
  14. package/dist/cjs/cli/commands/links.js +270 -0
  15. package/dist/cjs/cli/commands/webhooks.d.ts +10 -0
  16. package/dist/cjs/cli/commands/webhooks.js +510 -0
  17. package/dist/cjs/cli/configStore.d.ts +10 -0
  18. package/dist/cjs/cli/configStore.js +63 -0
  19. package/dist/cjs/cli/credentials.d.ts +23 -0
  20. package/dist/cjs/cli/credentials.js +235 -0
  21. package/dist/cjs/cli/exitCodes.d.ts +9 -0
  22. package/dist/cjs/cli/exitCodes.js +12 -0
  23. package/dist/cjs/cli/formatting.d.ts +19 -0
  24. package/dist/cjs/cli/formatting.js +110 -0
  25. package/dist/cjs/cli/index.d.ts +3 -0
  26. package/dist/cjs/cli/index.js +278 -0
  27. package/dist/cjs/cli/types.d.ts +13 -0
  28. package/dist/cjs/cli/types.js +2 -0
  29. package/dist/cjs/client.d.ts +89 -0
  30. package/dist/cjs/client.js +126 -0
  31. package/dist/cjs/config.d.ts +49 -0
  32. package/dist/cjs/config.js +67 -0
  33. package/dist/cjs/errors.d.ts +60 -0
  34. package/dist/cjs/errors.js +149 -0
  35. package/dist/cjs/events.d.ts +50 -0
  36. package/dist/cjs/events.js +153 -0
  37. package/dist/cjs/http.d.ts +30 -0
  38. package/dist/cjs/http.js +148 -0
  39. package/dist/cjs/index.d.ts +28 -0
  40. package/dist/cjs/index.js +58 -0
  41. package/dist/cjs/package.json +3 -0
  42. package/dist/cjs/pagination.d.ts +54 -0
  43. package/dist/cjs/pagination.js +111 -0
  44. package/dist/cjs/resources/analytics.d.ts +35 -0
  45. package/dist/cjs/resources/analytics.js +74 -0
  46. package/dist/cjs/resources/campaigns.d.ts +65 -0
  47. package/dist/cjs/resources/campaigns.js +139 -0
  48. package/dist/cjs/resources/conversions.d.ts +37 -0
  49. package/dist/cjs/resources/conversions.js +82 -0
  50. package/dist/cjs/resources/links.d.ts +95 -0
  51. package/dist/cjs/resources/links.js +199 -0
  52. package/dist/cjs/resources/webhooks.d.ts +66 -0
  53. package/dist/cjs/resources/webhooks.js +178 -0
  54. package/dist/cjs/security.d.ts +53 -0
  55. package/dist/cjs/security.js +156 -0
  56. package/dist/cjs/types.d.ts +149 -0
  57. package/dist/cjs/types.js +347 -0
  58. package/dist/cjs/utm.d.ts +36 -0
  59. package/dist/cjs/utm.js +44 -0
  60. package/dist/esm/cli/commands/analytics.d.ts +4 -0
  61. package/dist/esm/cli/commands/analytics.d.ts.map +1 -0
  62. package/dist/esm/cli/commands/analytics.js +77 -0
  63. package/dist/esm/cli/commands/analytics.js.map +1 -0
  64. package/dist/esm/cli/commands/auth.d.ts +5 -0
  65. package/dist/esm/cli/commands/auth.d.ts.map +1 -0
  66. package/dist/esm/cli/commands/auth.js +118 -0
  67. package/dist/esm/cli/commands/auth.js.map +1 -0
  68. package/dist/esm/cli/commands/campaigns.d.ts +7 -0
  69. package/dist/esm/cli/commands/campaigns.d.ts.map +1 -0
  70. package/dist/esm/cli/commands/campaigns.js +223 -0
  71. package/dist/esm/cli/commands/campaigns.js.map +1 -0
  72. package/dist/esm/cli/commands/config.d.ts +4 -0
  73. package/dist/esm/cli/commands/config.d.ts.map +1 -0
  74. package/dist/esm/cli/commands/config.js +48 -0
  75. package/dist/esm/cli/commands/config.js.map +1 -0
  76. package/dist/esm/cli/commands/conversions.d.ts +5 -0
  77. package/dist/esm/cli/commands/conversions.d.ts.map +1 -0
  78. package/dist/esm/cli/commands/conversions.js +156 -0
  79. package/dist/esm/cli/commands/conversions.js.map +1 -0
  80. package/dist/esm/cli/commands/links.d.ts +7 -0
  81. package/dist/esm/cli/commands/links.d.ts.map +1 -0
  82. package/dist/esm/cli/commands/links.js +264 -0
  83. package/dist/esm/cli/commands/links.js.map +1 -0
  84. package/dist/esm/cli/commands/webhooks.d.ts +11 -0
  85. package/dist/esm/cli/commands/webhooks.d.ts.map +1 -0
  86. package/dist/esm/cli/commands/webhooks.js +500 -0
  87. package/dist/esm/cli/commands/webhooks.js.map +1 -0
  88. package/dist/esm/cli/configStore.d.ts +11 -0
  89. package/dist/esm/cli/configStore.d.ts.map +1 -0
  90. package/dist/esm/cli/configStore.js +54 -0
  91. package/dist/esm/cli/configStore.js.map +1 -0
  92. package/dist/esm/cli/credentials.d.ts +24 -0
  93. package/dist/esm/cli/credentials.d.ts.map +1 -0
  94. package/dist/esm/cli/credentials.js +226 -0
  95. package/dist/esm/cli/credentials.js.map +1 -0
  96. package/dist/esm/cli/exitCodes.d.ts +10 -0
  97. package/dist/esm/cli/exitCodes.d.ts.map +1 -0
  98. package/dist/esm/cli/exitCodes.js +10 -0
  99. package/dist/esm/cli/exitCodes.js.map +1 -0
  100. package/dist/esm/cli/formatting.d.ts +20 -0
  101. package/dist/esm/cli/formatting.d.ts.map +1 -0
  102. package/dist/esm/cli/formatting.js +95 -0
  103. package/dist/esm/cli/formatting.js.map +1 -0
  104. package/dist/esm/cli/index.d.ts +4 -0
  105. package/dist/esm/cli/index.d.ts.map +1 -0
  106. package/dist/esm/cli/index.js +276 -0
  107. package/dist/esm/cli/index.js.map +1 -0
  108. package/dist/esm/cli/types.d.ts +14 -0
  109. package/dist/esm/cli/types.d.ts.map +1 -0
  110. package/dist/esm/cli/types.js +2 -0
  111. package/dist/esm/cli/types.js.map +1 -0
  112. package/dist/esm/client.d.ts +90 -0
  113. package/dist/esm/client.d.ts.map +1 -0
  114. package/dist/esm/client.js +123 -0
  115. package/dist/esm/client.js.map +1 -0
  116. package/dist/esm/config.d.ts +50 -0
  117. package/dist/esm/config.d.ts.map +1 -0
  118. package/dist/esm/config.js +64 -0
  119. package/dist/esm/config.js.map +1 -0
  120. package/dist/esm/errors.d.ts +61 -0
  121. package/dist/esm/errors.d.ts.map +1 -0
  122. package/dist/esm/errors.js +130 -0
  123. package/dist/esm/errors.js.map +1 -0
  124. package/dist/esm/events.d.ts +51 -0
  125. package/dist/esm/events.d.ts.map +1 -0
  126. package/dist/esm/events.js +149 -0
  127. package/dist/esm/events.js.map +1 -0
  128. package/dist/esm/http.d.ts +31 -0
  129. package/dist/esm/http.d.ts.map +1 -0
  130. package/dist/esm/http.js +145 -0
  131. package/dist/esm/http.js.map +1 -0
  132. package/dist/esm/index.d.ts +29 -0
  133. package/dist/esm/index.d.ts.map +1 -0
  134. package/dist/esm/index.js +16 -0
  135. package/dist/esm/index.js.map +1 -0
  136. package/dist/esm/pagination.d.ts +55 -0
  137. package/dist/esm/pagination.d.ts.map +1 -0
  138. package/dist/esm/pagination.js +106 -0
  139. package/dist/esm/pagination.js.map +1 -0
  140. package/dist/esm/resources/analytics.d.ts +36 -0
  141. package/dist/esm/resources/analytics.d.ts.map +1 -0
  142. package/dist/esm/resources/analytics.js +71 -0
  143. package/dist/esm/resources/analytics.js.map +1 -0
  144. package/dist/esm/resources/campaigns.d.ts +66 -0
  145. package/dist/esm/resources/campaigns.d.ts.map +1 -0
  146. package/dist/esm/resources/campaigns.js +136 -0
  147. package/dist/esm/resources/campaigns.js.map +1 -0
  148. package/dist/esm/resources/conversions.d.ts +38 -0
  149. package/dist/esm/resources/conversions.d.ts.map +1 -0
  150. package/dist/esm/resources/conversions.js +79 -0
  151. package/dist/esm/resources/conversions.js.map +1 -0
  152. package/dist/esm/resources/links.d.ts +96 -0
  153. package/dist/esm/resources/links.d.ts.map +1 -0
  154. package/dist/esm/resources/links.js +196 -0
  155. package/dist/esm/resources/links.js.map +1 -0
  156. package/dist/esm/resources/webhooks.d.ts +67 -0
  157. package/dist/esm/resources/webhooks.d.ts.map +1 -0
  158. package/dist/esm/resources/webhooks.js +175 -0
  159. package/dist/esm/resources/webhooks.js.map +1 -0
  160. package/dist/esm/security.d.ts +54 -0
  161. package/dist/esm/security.d.ts.map +1 -0
  162. package/dist/esm/security.js +153 -0
  163. package/dist/esm/security.js.map +1 -0
  164. package/dist/esm/types.d.ts +150 -0
  165. package/dist/esm/types.d.ts.map +1 -0
  166. package/dist/esm/types.js +335 -0
  167. package/dist/esm/types.js.map +1 -0
  168. package/dist/esm/utm.d.ts +37 -0
  169. package/dist/esm/utm.d.ts.map +1 -0
  170. package/dist/esm/utm.js +42 -0
  171. package/dist/esm/utm.js.map +1 -0
  172. package/package.json +91 -4
@@ -0,0 +1,199 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.LinksResource = void 0;
4
+ const pagination_js_1 = require("../pagination.js");
5
+ const types_js_1 = require("../types.js");
6
+ const utm_js_1 = require("../utm.js");
7
+ /**
8
+ * Resource client for creating, retrieving, updating, and deleting shortened URLs.
9
+ */
10
+ class LinksResource {
11
+ http;
12
+ constructor(httpClient) {
13
+ this.http = httpClient;
14
+ }
15
+ /**
16
+ * Create a new shortened link with optional slug, tags, expiration, and UTM parameters.
17
+ *
18
+ * @param params - Link creation parameters.
19
+ * @returns The newly created {@link Link} resource.
20
+ * @example
21
+ * ```ts
22
+ * const link = await client.links.create({
23
+ * originalUrl: "https://example.com/pricing",
24
+ * customSlug: "pricing",
25
+ * utmSource: "twitter",
26
+ * autoDecorateUtm: true,
27
+ * });
28
+ * ```
29
+ */
30
+ async create(params) {
31
+ let destUrl = params.originalUrl;
32
+ if (params.autoDecorateUtm &&
33
+ (params.utmSource || params.utmMedium || params.utmCampaign)) {
34
+ destUrl = (0, utm_js_1.buildUtmUrl)(params.originalUrl, {
35
+ source: params.utmSource,
36
+ medium: params.utmMedium,
37
+ campaign: params.utmCampaign,
38
+ });
39
+ }
40
+ const payload = { originalUrl: destUrl };
41
+ const resolvedSlug = params.customSlug ?? params.slug ?? params.customUrl;
42
+ if (resolvedSlug !== undefined)
43
+ payload["customSlug"] = resolvedSlug;
44
+ if (params.title !== undefined)
45
+ payload["title"] = params.title;
46
+ if (params.tags !== undefined)
47
+ payload["tags"] = params.tags;
48
+ if (params.utmSource !== undefined)
49
+ payload["utmSource"] = params.utmSource;
50
+ if (params.utmMedium !== undefined)
51
+ payload["utmMedium"] = params.utmMedium;
52
+ if (params.utmCampaign !== undefined)
53
+ payload["utmCampaign"] = params.utmCampaign;
54
+ if (params.expiresAt !== undefined) {
55
+ payload["expiresAt"] =
56
+ params.expiresAt instanceof Date
57
+ ? params.expiresAt.toISOString()
58
+ : String(params.expiresAt);
59
+ }
60
+ const resp = await this.http.request({
61
+ method: "POST",
62
+ path: "/links",
63
+ jsonBody: payload,
64
+ idempotencyKey: params.idempotencyKey,
65
+ requestId: params.requestId,
66
+ });
67
+ const data = extractDataRecord(resp.data);
68
+ return types_js_1.Link.fromApi(data, resp.requestId, resp.idempotentReplay);
69
+ }
70
+ /**
71
+ * Create multiple shortened links concurrently with bounded concurrency, preserving input order.
72
+ *
73
+ * @param items - Array of link creation parameter objects.
74
+ * @param options - Concurrency options (`concurrency`, default: `5`).
75
+ * @returns Array of created {@link Link} objects in the same order as `items`.
76
+ * @example
77
+ * ```ts
78
+ * const links = await client.links.createMany(
79
+ * [{ originalUrl: "https://example.com/a" }, { originalUrl: "https://example.com/b" }],
80
+ * { concurrency: 4 },
81
+ * );
82
+ * ```
83
+ */
84
+ async createMany(items, options = {}) {
85
+ if (items.length === 0)
86
+ return [];
87
+ if (items.length === 1)
88
+ return [await this.create(items[0])];
89
+ const concurrency = Math.max(1, options.concurrency ?? 5);
90
+ const results = new Array(items.length);
91
+ let nextIndex = 0;
92
+ const worker = async () => {
93
+ while (nextIndex < items.length) {
94
+ const idx = nextIndex++;
95
+ results[idx] = await this.create(items[idx]);
96
+ }
97
+ };
98
+ const workers = Array.from({ length: Math.min(concurrency, items.length) }, () => worker());
99
+ await Promise.all(workers);
100
+ return results;
101
+ }
102
+ async list(params = {}) {
103
+ const limit = Math.max(1, Math.min(params.limit ?? 50, 100));
104
+ const resp = await this.http.request({
105
+ method: "GET",
106
+ path: "/links",
107
+ params: {
108
+ page: params.page ?? 1,
109
+ limit,
110
+ search: params.search,
111
+ tag: params.tag,
112
+ sort: params.sort,
113
+ },
114
+ requestId: params.requestId,
115
+ });
116
+ const itemsData = Array.isArray(resp.data?.["data"])
117
+ ? resp.data["data"]
118
+ : [];
119
+ const paginationData = isRecord(resp.data?.["pagination"]) ? resp.data["pagination"] : {};
120
+ const items = itemsData.map((item) => types_js_1.Link.fromApi(item, resp.requestId));
121
+ return new pagination_js_1.PaginatedList(items, pagination_js_1.PaginationMetadata.fromApi(paginationData), resp.requestId);
122
+ }
123
+ async get(linkId, requestId) {
124
+ const resp = await this.http.request({
125
+ method: "GET",
126
+ path: `/links/${linkId}`,
127
+ requestId,
128
+ });
129
+ return types_js_1.Link.fromApi(extractDataRecord(resp.data), resp.requestId);
130
+ }
131
+ async update(linkId, params) {
132
+ const payload = {};
133
+ if (params.originalUrl !== undefined)
134
+ payload["originalUrl"] = params.originalUrl;
135
+ const resolvedSlug = params.customSlug ?? params.slug ?? params.customUrl;
136
+ if (resolvedSlug !== undefined)
137
+ payload["customSlug"] = resolvedSlug;
138
+ if (params.title !== undefined)
139
+ payload["title"] = params.title;
140
+ if (params.tags !== undefined)
141
+ payload["tags"] = params.tags;
142
+ if (params.utmSource !== undefined)
143
+ payload["utmSource"] = params.utmSource;
144
+ if (params.utmMedium !== undefined)
145
+ payload["utmMedium"] = params.utmMedium;
146
+ if (params.utmCampaign !== undefined)
147
+ payload["utmCampaign"] = params.utmCampaign;
148
+ if (params.isActive !== undefined)
149
+ payload["isActive"] = params.isActive;
150
+ if (params.expiresAt !== undefined) {
151
+ payload["expiresAt"] =
152
+ params.expiresAt instanceof Date
153
+ ? params.expiresAt.toISOString()
154
+ : String(params.expiresAt);
155
+ }
156
+ const resp = await this.http.request({
157
+ method: "PATCH",
158
+ path: `/links/${linkId}`,
159
+ jsonBody: payload,
160
+ requestId: params.requestId,
161
+ });
162
+ return types_js_1.Link.fromApi(extractDataRecord(resp.data), resp.requestId);
163
+ }
164
+ async delete(linkId, requestId) {
165
+ const resp = await this.http.request({
166
+ method: "DELETE",
167
+ path: `/links/${linkId}`,
168
+ requestId,
169
+ });
170
+ const data = extractDataRecord(resp.data);
171
+ return (0, types_js_1.parseDeleteResult)(Object.keys(data).length > 0 ? data : { id: linkId }, resp.requestId);
172
+ }
173
+ /**
174
+ * Fetch a link by ID or slug and save its QR code image directly to disk.
175
+ *
176
+ * @param linkId - The link ID or CUID.
177
+ * @param outputPath - Destination file path (e.g. `"./qr.png"`).
178
+ * @param requestId - Optional request tracing ID.
179
+ * @returns Canonical absolute path to the saved QR image file.
180
+ */
181
+ async downloadQr(linkId, outputPath, requestId) {
182
+ const link = await this.get(linkId, requestId);
183
+ return link.saveQr(outputPath, this.http.config.fetch);
184
+ }
185
+ iter(params = {}) {
186
+ return new pagination_js_1.AutoPagingIterator((page, limit) => this.list({ ...params, page, limit }), params.limit ?? 50);
187
+ }
188
+ }
189
+ exports.LinksResource = LinksResource;
190
+ function isRecord(val) {
191
+ return Boolean(val) && typeof val === "object" && !Array.isArray(val);
192
+ }
193
+ function extractDataRecord(body) {
194
+ if (!isRecord(body))
195
+ return {};
196
+ if (isRecord(body["data"]))
197
+ return body["data"];
198
+ return body;
199
+ }
@@ -0,0 +1,66 @@
1
+ import { WebhookEvent } from "../events.js";
2
+ import type { HttpClient } from "../http.js";
3
+ import { AutoPagingIterator, PaginatedList } from "../pagination.js";
4
+ import { VerifyWebhookSignatureOptions } from "../security.js";
5
+ import { DeleteResult, TestWebhookResult, Webhook, WebhookDelivery } from "../types.js";
6
+ export interface CreateWebhookParams {
7
+ url: string;
8
+ events: string[];
9
+ description?: string | undefined;
10
+ secret?: string | undefined;
11
+ idempotencyKey?: string | undefined;
12
+ requestId?: string | undefined;
13
+ }
14
+ export interface ListWebhooksParams {
15
+ page?: number | undefined;
16
+ limit?: number | undefined;
17
+ requestId?: string | undefined;
18
+ }
19
+ export interface UpdateWebhookParams {
20
+ url?: string | undefined;
21
+ events?: string[] | undefined;
22
+ description?: string | undefined;
23
+ isActive?: boolean | undefined;
24
+ secret?: unknown;
25
+ requestId?: string | undefined;
26
+ }
27
+ export interface ConstructWebhookEventOptions {
28
+ payload?: string | Buffer | Uint8Array | Record<string, unknown> | undefined;
29
+ rawPayload?: string | Buffer | Uint8Array | Record<string, unknown> | undefined;
30
+ signatureHeader: string;
31
+ timestamp?: string | number | undefined;
32
+ secret: string;
33
+ toleranceSeconds?: number | null | undefined;
34
+ }
35
+ /**
36
+ * Resource client for managing webhook endpoints, inspecting deliveries, and verifying signatures.
37
+ */
38
+ export declare class WebhooksResource {
39
+ private readonly http;
40
+ constructor(httpClient: HttpClient);
41
+ /**
42
+ * Register a new external webhook endpoint.
43
+ *
44
+ * @param params - Webhook registration options (`url`, `events`, optional `description`, `secret`, `idempotencyKey`).
45
+ * @returns The newly registered {@link Webhook} (save `webhook.secret` securely; it is only returned on creation).
46
+ * @example
47
+ * ```ts
48
+ * const webhook = await client.webhooks.create({
49
+ * url: "https://example.com/webhooks/trimlynk",
50
+ * events: ["click.created", "conversion.created"],
51
+ * });
52
+ * ```
53
+ */
54
+ create(params: CreateWebhookParams): Promise<Webhook>;
55
+ list(params?: ListWebhooksParams): Promise<PaginatedList<Webhook>>;
56
+ get(webhookId: string, requestId?: string): Promise<Webhook>;
57
+ update(webhookId: string, params: UpdateWebhookParams): Promise<Webhook>;
58
+ delete(webhookId: string, requestId?: string): Promise<DeleteResult>;
59
+ test(webhookId: string, requestId?: string): Promise<TestWebhookResult>;
60
+ deliveries(webhookId: string, params?: ListWebhooksParams): Promise<PaginatedList<WebhookDelivery>>;
61
+ retry(webhookId: string, deliveryId: string, requestId?: string): Promise<Record<string, unknown>>;
62
+ iter(params?: Omit<ListWebhooksParams, "page" | "requestId">): AutoPagingIterator<Webhook>;
63
+ iterDeliveries(webhookId: string, params?: Omit<ListWebhooksParams, "page" | "requestId">): AutoPagingIterator<WebhookDelivery>;
64
+ constructEvent(options: ConstructWebhookEventOptions): WebhookEvent;
65
+ verifySignature(options: VerifyWebhookSignatureOptions): boolean;
66
+ }
@@ -0,0 +1,178 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WebhooksResource = void 0;
4
+ const errors_js_1 = require("../errors.js");
5
+ const events_js_1 = require("../events.js");
6
+ const pagination_js_1 = require("../pagination.js");
7
+ const security_js_1 = require("../security.js");
8
+ const types_js_1 = require("../types.js");
9
+ /**
10
+ * Resource client for managing webhook endpoints, inspecting deliveries, and verifying signatures.
11
+ */
12
+ class WebhooksResource {
13
+ http;
14
+ constructor(httpClient) {
15
+ this.http = httpClient;
16
+ }
17
+ /**
18
+ * Register a new external webhook endpoint.
19
+ *
20
+ * @param params - Webhook registration options (`url`, `events`, optional `description`, `secret`, `idempotencyKey`).
21
+ * @returns The newly registered {@link Webhook} (save `webhook.secret` securely; it is only returned on creation).
22
+ * @example
23
+ * ```ts
24
+ * const webhook = await client.webhooks.create({
25
+ * url: "https://example.com/webhooks/trimlynk",
26
+ * events: ["click.created", "conversion.created"],
27
+ * });
28
+ * ```
29
+ */
30
+ async create(params) {
31
+ const payload = {
32
+ url: params.url,
33
+ events: params.events,
34
+ };
35
+ if (params.description !== undefined)
36
+ payload["description"] = params.description;
37
+ if (params.secret !== undefined)
38
+ payload["secret"] = params.secret;
39
+ const resp = await this.http.request({
40
+ method: "POST",
41
+ path: "/webhooks",
42
+ jsonBody: payload,
43
+ idempotencyKey: params.idempotencyKey,
44
+ requestId: params.requestId,
45
+ });
46
+ const data = isRecord(resp.data?.["data"]) ? resp.data["data"] : resp.data ?? {};
47
+ return (0, types_js_1.parseWebhook)(data, resp.requestId, resp.idempotentReplay);
48
+ }
49
+ async list(params = {}) {
50
+ const limit = Math.max(1, Math.min(params.limit ?? 50, 100));
51
+ const resp = await this.http.request({
52
+ method: "GET",
53
+ path: "/webhooks",
54
+ params: {
55
+ page: params.page ?? 1,
56
+ limit,
57
+ },
58
+ requestId: params.requestId,
59
+ });
60
+ const itemsData = Array.isArray(resp.data?.["data"])
61
+ ? resp.data["data"]
62
+ : [];
63
+ const paginationData = isRecord(resp.data?.["pagination"]) ? resp.data["pagination"] : {};
64
+ const items = itemsData.map((item) => (0, types_js_1.parseWebhook)(item, resp.requestId));
65
+ return new pagination_js_1.PaginatedList(items, pagination_js_1.PaginationMetadata.fromApi(paginationData), resp.requestId);
66
+ }
67
+ async get(webhookId, requestId) {
68
+ const resp = await this.http.request({
69
+ method: "GET",
70
+ path: `/webhooks/${webhookId}`,
71
+ requestId,
72
+ });
73
+ const data = isRecord(resp.data?.["data"]) ? resp.data["data"] : resp.data ?? {};
74
+ return (0, types_js_1.parseWebhook)(data, resp.requestId);
75
+ }
76
+ async update(webhookId, params) {
77
+ if (params.secret !== undefined && params.secret !== null) {
78
+ throw new errors_js_1.InvalidRequestError("Updating webhook signing secret via PATCH /webhooks/:id is not supported. Webhook signing secrets are immutable platform credentials generated upon creation.", { code: "unsupported_parameter", statusCode: 400 });
79
+ }
80
+ const payload = {};
81
+ if (params.url !== undefined)
82
+ payload["url"] = params.url;
83
+ if (params.events !== undefined)
84
+ payload["events"] = params.events;
85
+ if (params.description !== undefined)
86
+ payload["description"] = params.description;
87
+ if (params.isActive !== undefined)
88
+ payload["isActive"] = params.isActive;
89
+ const resp = await this.http.request({
90
+ method: "PATCH",
91
+ path: `/webhooks/${webhookId}`,
92
+ jsonBody: payload,
93
+ requestId: params.requestId,
94
+ });
95
+ const data = isRecord(resp.data?.["data"]) ? resp.data["data"] : resp.data ?? {};
96
+ return (0, types_js_1.parseWebhook)(data, resp.requestId);
97
+ }
98
+ async delete(webhookId, requestId) {
99
+ const resp = await this.http.request({
100
+ method: "DELETE",
101
+ path: `/webhooks/${webhookId}`,
102
+ requestId,
103
+ });
104
+ const data = isRecord(resp.data?.["data"]) ? resp.data["data"] : resp.data ?? {};
105
+ return (0, types_js_1.parseDeleteResult)(Object.keys(data).length > 0 ? data : { id: webhookId }, resp.requestId);
106
+ }
107
+ async test(webhookId, requestId) {
108
+ const resp = await this.http.request({
109
+ method: "POST",
110
+ path: `/webhooks/${webhookId}/test`,
111
+ requestId,
112
+ });
113
+ const data = isRecord(resp.data?.["data"]) ? resp.data["data"] : resp.data ?? {};
114
+ return (0, types_js_1.parseTestWebhookResult)(Object.keys(data).length > 0 ? data : { id: webhookId }, resp.requestId);
115
+ }
116
+ async deliveries(webhookId, params = {}) {
117
+ const limit = Math.max(1, Math.min(params.limit ?? 50, 100));
118
+ const resp = await this.http.request({
119
+ method: "GET",
120
+ path: `/webhooks/${webhookId}/deliveries`,
121
+ params: {
122
+ page: params.page ?? 1,
123
+ limit,
124
+ },
125
+ requestId: params.requestId,
126
+ });
127
+ const itemsData = Array.isArray(resp.data?.["data"])
128
+ ? resp.data["data"]
129
+ : [];
130
+ const paginationData = isRecord(resp.data?.["pagination"]) ? resp.data["pagination"] : {};
131
+ const items = itemsData.map((item) => (0, types_js_1.parseWebhookDelivery)(item, resp.requestId));
132
+ return new pagination_js_1.PaginatedList(items, pagination_js_1.PaginationMetadata.fromApi(paginationData), resp.requestId);
133
+ }
134
+ async retry(webhookId, deliveryId, requestId) {
135
+ const resp = await this.http.request({
136
+ method: "POST",
137
+ path: `/webhooks/${webhookId}/deliveries/${deliveryId}/retry`,
138
+ requestId,
139
+ });
140
+ const data = isRecord(resp.data?.["data"]) ? resp.data["data"] : resp.data;
141
+ return isRecord(data) && Object.keys(data).length > 0
142
+ ? data
143
+ : { id: deliveryId, retried: true };
144
+ }
145
+ iter(params = {}) {
146
+ return new pagination_js_1.AutoPagingIterator((page, limit) => this.list({ page, limit }), params.limit ?? 50);
147
+ }
148
+ iterDeliveries(webhookId, params = {}) {
149
+ return new pagination_js_1.AutoPagingIterator((page, limit) => this.deliveries(webhookId, { page, limit }), params.limit ?? 50);
150
+ }
151
+ constructEvent(options) {
152
+ if (options.payload !== undefined && options.rawPayload !== undefined) {
153
+ throw new Error("Cannot specify both 'payload' and 'rawPayload'. Pass only one.");
154
+ }
155
+ const target = options.payload ?? options.rawPayload;
156
+ if (target === undefined || target === null) {
157
+ throw new Error("payload (or rawPayload) is required to construct a webhook event.");
158
+ }
159
+ const rawToValidate = typeof target === "object" && !Buffer.isBuffer(target) && !(target instanceof Uint8Array)
160
+ ? JSON.stringify(target)
161
+ : target;
162
+ (0, security_js_1.validateWebhookSignature)({
163
+ rawPayload: rawToValidate,
164
+ signatureHeader: options.signatureHeader,
165
+ timestamp: options.timestamp,
166
+ secret: options.secret,
167
+ toleranceSeconds: options.toleranceSeconds,
168
+ });
169
+ return (0, events_js_1.parseWebhookEvent)(target);
170
+ }
171
+ verifySignature(options) {
172
+ return (0, security_js_1.verifyWebhookSignature)(options);
173
+ }
174
+ }
175
+ exports.WebhooksResource = WebhooksResource;
176
+ function isRecord(val) {
177
+ return Boolean(val) && typeof val === "object" && !Array.isArray(val);
178
+ }
@@ -0,0 +1,53 @@
1
+ /** Supported raw payload types for HMAC-SHA256 webhook signature verification. */
2
+ export type RawWebhookPayload = string | Buffer | Uint8Array;
3
+ /**
4
+ * Options for verifying or validating a TrimLynk webhook signature.
5
+ */
6
+ export interface VerifyWebhookSignatureOptions {
7
+ /** Raw unparsed request body string or bytes (mutually exclusive with `payload`). */
8
+ rawPayload?: RawWebhookPayload | undefined;
9
+ /** Alias for `rawPayload` (mutually exclusive with `rawPayload`). */
10
+ payload?: RawWebhookPayload | undefined;
11
+ /** Value of the `X-TrimLynk-Signature` header (supports `t=...,v1=...`, `v1=...`, or bare hex). */
12
+ signatureHeader: string;
13
+ /** Optional `X-TrimLynk-Timestamp` header value if not embedded as `t=` in `signatureHeader`. */
14
+ timestamp?: string | number | undefined;
15
+ /** Webhook signing secret (`whsec_...`). */
16
+ secret: string;
17
+ /** Replay tolerance window in seconds (default: `300`). Pass `null` or `0` to disable timestamp checks. */
18
+ toleranceSeconds?: number | null | undefined;
19
+ }
20
+ /**
21
+ * Validate an incoming TrimLynk webhook HMAC-SHA256 signature, throwing typed errors on failure.
22
+ *
23
+ * @param options - Webhook payload, signature header, signing secret, and replay tolerance options.
24
+ * @throws {InvalidSignatureHeaderError} If payload, signature header, secret, or timestamp is missing or malformed.
25
+ * @throws {SignatureExpiredError} If the timestamp is outside the replay tolerance window.
26
+ * @throws {SignatureMismatchError} If the computed HMAC-SHA256 digest does not match the header.
27
+ *
28
+ * @example
29
+ * ```ts
30
+ * validateWebhookSignature({
31
+ * rawPayload: rawBody,
32
+ * signatureHeader: req.headers["x-trimlynk-signature"],
33
+ * secret: process.env.TRIMLYNK_WEBHOOK_SECRET!,
34
+ * });
35
+ * ```
36
+ */
37
+ export declare function validateWebhookSignature(options: VerifyWebhookSignatureOptions): void;
38
+ /**
39
+ * Verify an incoming TrimLynk webhook HMAC-SHA256 signature using constant-time comparison.
40
+ *
41
+ * @param options - Webhook payload, signature header, signing secret, and replay tolerance options.
42
+ * @returns `true` if authentic and within replay tolerance, `false` otherwise.
43
+ *
44
+ * @example
45
+ * ```ts
46
+ * const ok = verifyWebhookSignature({
47
+ * rawPayload: rawBody,
48
+ * signatureHeader: req.headers["x-trimlynk-signature"],
49
+ * secret: process.env.TRIMLYNK_WEBHOOK_SECRET!,
50
+ * });
51
+ * ```
52
+ */
53
+ export declare function verifyWebhookSignature(options: VerifyWebhookSignatureOptions): boolean;
@@ -0,0 +1,156 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validateWebhookSignature = validateWebhookSignature;
4
+ exports.verifyWebhookSignature = verifyWebhookSignature;
5
+ const node_crypto_1 = require("node:crypto");
6
+ const errors_js_1 = require("./errors.js");
7
+ function resolvePayloadBytes(rawPayload) {
8
+ if (rawPayload === undefined || rawPayload === null) {
9
+ throw new errors_js_1.InvalidSignatureHeaderError("Webhook rawPayload cannot be empty");
10
+ }
11
+ if (typeof rawPayload === "string") {
12
+ if (rawPayload.length === 0) {
13
+ throw new errors_js_1.InvalidSignatureHeaderError("Webhook rawPayload cannot be empty");
14
+ }
15
+ return Buffer.from(rawPayload, "utf8");
16
+ }
17
+ if (Buffer.isBuffer(rawPayload)) {
18
+ if (rawPayload.length === 0) {
19
+ throw new errors_js_1.InvalidSignatureHeaderError("Webhook rawPayload cannot be empty");
20
+ }
21
+ return rawPayload;
22
+ }
23
+ if (rawPayload instanceof Uint8Array) {
24
+ if (rawPayload.byteLength === 0) {
25
+ throw new errors_js_1.InvalidSignatureHeaderError("Webhook rawPayload cannot be empty");
26
+ }
27
+ return Buffer.from(rawPayload.buffer, rawPayload.byteOffset, rawPayload.byteLength);
28
+ }
29
+ throw new errors_js_1.InvalidSignatureHeaderError(`Unsupported payload type: ${typeof rawPayload}`);
30
+ }
31
+ /**
32
+ * Validate an incoming TrimLynk webhook HMAC-SHA256 signature, throwing typed errors on failure.
33
+ *
34
+ * @param options - Webhook payload, signature header, signing secret, and replay tolerance options.
35
+ * @throws {InvalidSignatureHeaderError} If payload, signature header, secret, or timestamp is missing or malformed.
36
+ * @throws {SignatureExpiredError} If the timestamp is outside the replay tolerance window.
37
+ * @throws {SignatureMismatchError} If the computed HMAC-SHA256 digest does not match the header.
38
+ *
39
+ * @example
40
+ * ```ts
41
+ * validateWebhookSignature({
42
+ * rawPayload: rawBody,
43
+ * signatureHeader: req.headers["x-trimlynk-signature"],
44
+ * secret: process.env.TRIMLYNK_WEBHOOK_SECRET!,
45
+ * });
46
+ * ```
47
+ */
48
+ function validateWebhookSignature(options) {
49
+ if (options.payload !== undefined && options.rawPayload !== undefined) {
50
+ throw new Error("Cannot specify both 'payload' and 'rawPayload'. Pass only one.");
51
+ }
52
+ const targetPayload = options.rawPayload ?? options.payload;
53
+ const rawBytes = resolvePayloadBytes(targetPayload);
54
+ const signatureHeader = options.signatureHeader;
55
+ if (!signatureHeader || typeof signatureHeader !== "string") {
56
+ throw new errors_js_1.InvalidSignatureHeaderError("X-TrimLynk-Signature header is missing or empty");
57
+ }
58
+ const secret = options.secret;
59
+ if (!secret || typeof secret !== "string") {
60
+ throw new errors_js_1.InvalidSignatureHeaderError("Webhook signing secret is missing or empty");
61
+ }
62
+ let timestamp = options.timestamp;
63
+ if (timestamp === undefined || timestamp === null || timestamp === "") {
64
+ for (const part of signatureHeader.split(",")) {
65
+ const p = part.trim();
66
+ if (p.startsWith("t=")) {
67
+ timestamp = p.slice(2).trim();
68
+ break;
69
+ }
70
+ }
71
+ }
72
+ if (timestamp === undefined || timestamp === null || timestamp === "") {
73
+ throw new errors_js_1.InvalidSignatureHeaderError("X-TrimLynk-Timestamp header (or 't=' component) is missing");
74
+ }
75
+ const tsNum = Number(timestamp);
76
+ if (!Number.isFinite(tsNum)) {
77
+ throw new errors_js_1.InvalidSignatureHeaderError(`Invalid timestamp value: ${JSON.stringify(timestamp)}`);
78
+ }
79
+ const toleranceSeconds = options.toleranceSeconds === undefined ? 300 : options.toleranceSeconds;
80
+ if (toleranceSeconds !== null && toleranceSeconds > 0) {
81
+ const tsSeconds = tsNum > 1e11 ? tsNum / 1000 : tsNum;
82
+ const nowSeconds = Date.now() / 1000;
83
+ const age = nowSeconds - tsSeconds;
84
+ if (Math.abs(age) > toleranceSeconds) {
85
+ throw new errors_js_1.SignatureExpiredError(`Webhook timestamp ${Math.round(tsSeconds)} is outside the ${toleranceSeconds}s tolerance window (current age: ${age.toFixed(1)}s)`);
86
+ }
87
+ }
88
+ const timestampStr = typeof timestamp === "string"
89
+ ? timestamp.trim()
90
+ : Number.isInteger(timestamp)
91
+ ? String(timestamp)
92
+ : String(timestamp);
93
+ const signedPayload = Buffer.concat([Buffer.from(`${timestampStr}.`, "utf8"), rawBytes]);
94
+ const expectedHex = (0, node_crypto_1.createHmac)("sha256", Buffer.from(secret, "utf8"))
95
+ .update(signedPayload)
96
+ .digest("hex");
97
+ const candidates = [];
98
+ for (const part of signatureHeader.split(",")) {
99
+ const p = part.trim();
100
+ if (!p)
101
+ continue;
102
+ if (p.startsWith("v1=")) {
103
+ const candidate = p.slice(3).trim();
104
+ if (candidate)
105
+ candidates.push(candidate);
106
+ }
107
+ else if (!p.includes("=")) {
108
+ candidates.push(p);
109
+ }
110
+ }
111
+ if (candidates.length === 0) {
112
+ throw new errors_js_1.InvalidSignatureHeaderError("No valid signature hashes found in signature header");
113
+ }
114
+ const expectedBuf = Buffer.from(expectedHex, "utf8");
115
+ for (const candidate of candidates) {
116
+ const candBuf = Buffer.from(candidate, "utf8");
117
+ if (candBuf.length === expectedBuf.length && (0, node_crypto_1.timingSafeEqual)(candBuf, expectedBuf)) {
118
+ return;
119
+ }
120
+ }
121
+ throw new errors_js_1.SignatureMismatchError("Computed HMAC-SHA256 digest does not match signature header");
122
+ }
123
+ /**
124
+ * Verify an incoming TrimLynk webhook HMAC-SHA256 signature using constant-time comparison.
125
+ *
126
+ * @param options - Webhook payload, signature header, signing secret, and replay tolerance options.
127
+ * @returns `true` if authentic and within replay tolerance, `false` otherwise.
128
+ *
129
+ * @example
130
+ * ```ts
131
+ * const ok = verifyWebhookSignature({
132
+ * rawPayload: rawBody,
133
+ * signatureHeader: req.headers["x-trimlynk-signature"],
134
+ * secret: process.env.TRIMLYNK_WEBHOOK_SECRET!,
135
+ * });
136
+ * ```
137
+ */
138
+ function verifyWebhookSignature(options) {
139
+ if (options.payload !== undefined && options.rawPayload !== undefined) {
140
+ throw new Error("Cannot specify both 'payload' and 'rawPayload'. Pass only one.");
141
+ }
142
+ const targetPayload = options.rawPayload ?? options.payload;
143
+ if (targetPayload === undefined || targetPayload === null) {
144
+ return false;
145
+ }
146
+ try {
147
+ validateWebhookSignature(options);
148
+ return true;
149
+ }
150
+ catch (err) {
151
+ if (err instanceof errors_js_1.SignatureVerificationError) {
152
+ return false;
153
+ }
154
+ throw err;
155
+ }
156
+ }