n8n-nodes-lemonsqueezy 0.2.0 → 0.5.0

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.
@@ -1,28 +1,367 @@
1
+ /**
2
+ * Lemon Squeezy API Helper Functions
3
+ *
4
+ * This module provides utility functions for:
5
+ * - Input validation (email, URL, date, etc.)
6
+ * - API request handling with retry logic
7
+ * - Webhook signature verification
8
+ * - JSON:API body construction
9
+ * - Query parameter building
10
+ *
11
+ * @module helpers
12
+ */
1
13
  import type { IExecuteFunctions, IWebhookFunctions, IHookFunctions, IHttpRequestMethods, IDataObject } from 'n8n-workflow';
14
+ import type { PaginationOptions } from './types';
15
+ /**
16
+ * Validates email format using RFC 5322 compliant regex.
17
+ *
18
+ * The validation checks for:
19
+ * - Valid local part characters (alphanumeric and special chars)
20
+ * - Single @ symbol
21
+ * - Valid domain with proper TLD (at least one dot)
22
+ *
23
+ * @param email - The email address to validate
24
+ * @returns True if the email format is valid, false otherwise
25
+ *
26
+ * @example
27
+ * isValidEmail('user@example.com') // true
28
+ * isValidEmail('invalid') // false
29
+ * isValidEmail('user@localhost') // false (no TLD)
30
+ */
31
+ export declare function isValidEmail(email: string): boolean;
32
+ /**
33
+ * Validates URL format and ensures it's a safe external URL.
34
+ *
35
+ * Security features:
36
+ * - Only allows http:// and https:// protocols
37
+ * - Blocks localhost and loopback addresses (127.0.0.1, ::1, [::1])
38
+ * - Blocks private network ranges (10.x, 172.16-31.x, 192.168.x)
39
+ * - Blocks link-local addresses (169.254.x - AWS metadata endpoint)
40
+ *
41
+ * This prevents Server-Side Request Forgery (SSRF) attacks.
42
+ *
43
+ * @param url - The URL to validate
44
+ * @returns True if the URL is valid and safe, false otherwise
45
+ *
46
+ * @example
47
+ * isValidUrl('https://example.com') // true
48
+ * isValidUrl('http://localhost:3000') // false (internal)
49
+ * isValidUrl('ftp://files.example.com') // false (non-http protocol)
50
+ * isValidUrl('http://169.254.169.254') // false (AWS metadata)
51
+ */
52
+ export declare function isValidUrl(url: string): boolean;
53
+ /**
54
+ * Validates ISO 8601 date format.
55
+ *
56
+ * Accepts dates in formats like:
57
+ * - 2024-01-15
58
+ * - 2024-01-15T10:30:00Z
59
+ * - 2024-01-15T10:30:00.000Z
60
+ *
61
+ * @param dateString - The date string to validate
62
+ * @returns True if the date is valid ISO 8601 format, false otherwise
63
+ *
64
+ * @example
65
+ * isValidIsoDate('2024-01-15T10:30:00Z') // true
66
+ * isValidIsoDate('invalid') // false
67
+ * isValidIsoDate('01/15/2024') // false (no dash separator)
68
+ */
69
+ export declare function isValidIsoDate(dateString: string): boolean;
70
+ /**
71
+ * Validates that a value is a positive integer (greater than 0).
72
+ *
73
+ * @param value - The value to validate
74
+ * @returns True if the value is a positive integer, false otherwise
75
+ *
76
+ * @example
77
+ * isPositiveInteger(5) // true
78
+ * isPositiveInteger(0) // false
79
+ * isPositiveInteger(-1) // false
80
+ * isPositiveInteger(3.14) // false
81
+ * isPositiveInteger('5') // false (string, not number)
82
+ */
83
+ export declare function isPositiveInteger(value: unknown): boolean;
84
+ /**
85
+ * Validates a field value and throws a descriptive error if invalid.
86
+ *
87
+ * Supports multiple validation types:
88
+ * - 'required': Ensures value is not empty/null/undefined
89
+ * - 'email': RFC 5322 compliant email validation
90
+ * - 'url': Safe URL validation with SSRF protection
91
+ * - 'date': ISO 8601 date format validation
92
+ * - 'positiveInteger': Positive integer validation
93
+ *
94
+ * @param fieldName - The name of the field (used in error messages)
95
+ * @param value - The value to validate
96
+ * @param validationType - The type of validation to perform
97
+ * @throws Error with descriptive message if validation fails
98
+ *
99
+ * @example
100
+ * validateField('email', 'user@example.com', 'email') // passes
101
+ * validateField('email', 'invalid', 'email') // throws "email must be a valid email address"
102
+ */
103
+ export declare function validateField(fieldName: string, value: unknown, validationType: 'email' | 'url' | 'date' | 'positiveInteger' | 'required'): void;
104
+ /**
105
+ * Safely parses a JSON string with descriptive error handling.
106
+ *
107
+ * @template T - The expected type of the parsed JSON
108
+ * @param jsonString - The JSON string to parse
109
+ * @param fieldName - The name of the field (used in error messages)
110
+ * @returns The parsed JSON object
111
+ * @throws Error if the JSON is invalid
112
+ *
113
+ * @example
114
+ * const data = safeJsonParse<{name: string}>('{"name": "test"}', 'config')
115
+ * // Returns: {name: "test"}
116
+ *
117
+ * safeJsonParse('invalid json', 'config')
118
+ * // Throws: "config contains invalid JSON"
119
+ */
120
+ export declare function safeJsonParse<T = unknown>(jsonString: string, fieldName: string): T;
2
121
  /**
3
- * Make an authenticated request to the Lemon Squeezy API with retry logic
122
+ * Pauses execution for a specified duration.
123
+ *
124
+ * Used for implementing retry delays and rate limit backoff.
125
+ *
126
+ * @param ms - The number of milliseconds to sleep
127
+ * @returns A promise that resolves after the specified duration
128
+ *
129
+ * @example
130
+ * await sleep(1000) // Wait 1 second
131
+ */
132
+ export declare function sleep(ms: number): Promise<void>;
133
+ /**
134
+ * Checks if an error is a rate limit error (HTTP 429).
135
+ *
136
+ * Handles both direct statusCode and nested response.statusCode patterns.
137
+ *
138
+ * @param error - The error object to check
139
+ * @returns True if the error is a rate limit error, false otherwise
140
+ *
141
+ * @example
142
+ * isRateLimitError({ statusCode: 429 }) // true
143
+ * isRateLimitError({ response: { statusCode: 429 } }) // true
144
+ * isRateLimitError({ statusCode: 500 }) // false
145
+ */
146
+ export declare function isRateLimitError(error: unknown): boolean;
147
+ /**
148
+ * Checks if an error is retryable (5xx server errors or network errors).
149
+ *
150
+ * Retryable conditions:
151
+ * - HTTP 5xx status codes (500-599)
152
+ * - Network errors: ECONNRESET, ETIMEDOUT, ECONNREFUSED
153
+ *
154
+ * @param error - The error object to check
155
+ * @returns True if the error is retryable, false otherwise
156
+ *
157
+ * @example
158
+ * isRetryableError({ statusCode: 503 }) // true (server error)
159
+ * isRetryableError({ code: 'ECONNRESET' }) // true (network error)
160
+ * isRetryableError({ statusCode: 404 }) // false (client error)
161
+ */
162
+ export declare function isRetryableError(error: unknown): boolean;
163
+ /**
164
+ * Makes an authenticated request to the Lemon Squeezy API with retry logic.
165
+ *
166
+ * Features:
167
+ * - Automatic authentication using stored credentials
168
+ * - Rate limit handling with automatic retry after delay
169
+ * - Exponential backoff for server errors (5xx)
170
+ * - Detailed error messages using NodeApiError
171
+ *
172
+ * @param this - The n8n execution context
173
+ * @param method - HTTP method (GET, POST, PATCH, DELETE)
174
+ * @param endpoint - API endpoint path (e.g., '/v1/products')
175
+ * @param body - Optional request body for POST/PATCH requests
176
+ * @param qs - Optional query string parameters
177
+ * @returns The API response data
178
+ * @throws NodeApiError if the request fails after all retries
179
+ *
180
+ * @example
181
+ * // GET request
182
+ * const product = await lemonSqueezyApiRequest.call(this, 'GET', '/v1/products/123')
183
+ *
184
+ * // POST request with body
185
+ * const checkout = await lemonSqueezyApiRequest.call(this, 'POST', '/v1/checkouts', {
186
+ * data: { type: 'checkouts', attributes: { ... } }
187
+ * })
4
188
  */
5
189
  export declare function lemonSqueezyApiRequest(this: IExecuteFunctions | IWebhookFunctions | IHookFunctions, method: IHttpRequestMethods, endpoint: string, body?: IDataObject, qs?: Record<string, string | number>): Promise<IDataObject>;
6
190
  /**
7
- * Make paginated requests to fetch all items
191
+ * Makes paginated requests to fetch all items from a Lemon Squeezy API endpoint.
192
+ *
193
+ * Automatically handles pagination by following 'next' links until all items
194
+ * are retrieved. Includes rate limit handling for long-running fetches.
195
+ *
196
+ * Features:
197
+ * - Optional maxItems limit to prevent memory issues with large datasets
198
+ * - Optional timeout to prevent long-running requests
199
+ * - Rate limit handling with automatic retry
200
+ *
201
+ * @param this - The n8n execution context
202
+ * @param method - HTTP method (typically 'GET')
203
+ * @param endpoint - API endpoint path (e.g., '/v1/products')
204
+ * @param qs - Optional query string parameters (filters, sorting, etc.)
205
+ * @param paginationOptions - Optional pagination configuration
206
+ * @returns Array of all items from all pages (up to maxItems if specified)
207
+ * @throws NodeApiError if any request fails or timeout is exceeded
208
+ *
209
+ * @example
210
+ * // Fetch all products with filtering
211
+ * const products = await lemonSqueezyApiRequestAllItems.call(
212
+ * this, 'GET', '/v1/products', { 'filter[store_id]': 123 }
213
+ * )
214
+ *
215
+ * // Fetch with limits
216
+ * const products = await lemonSqueezyApiRequestAllItems.call(
217
+ * this, 'GET', '/v1/products', {}, { maxItems: 1000, timeout: 60000 }
218
+ * )
8
219
  */
9
- export declare function lemonSqueezyApiRequestAllItems(this: IExecuteFunctions, method: IHttpRequestMethods, endpoint: string, qs?: Record<string, string | number>): Promise<IDataObject[]>;
220
+ export declare function lemonSqueezyApiRequestAllItems(this: IExecuteFunctions, method: IHttpRequestMethods, endpoint: string, qs?: Record<string, string | number>, paginationOptions?: PaginationOptions): Promise<IDataObject[]>;
10
221
  /**
11
- * Validate required fields before making API request
222
+ * Validates that all required fields are present and non-empty.
223
+ *
224
+ * @param fields - Object containing field values to validate
225
+ * @param requiredFields - Array of field names that are required
226
+ * @throws Error listing all missing fields if any are empty
227
+ *
228
+ * @example
229
+ * validateRequiredFields({ name: 'Test', email: '' }, ['name', 'email'])
230
+ * // Throws: "Missing required fields: email"
12
231
  */
13
232
  export declare function validateRequiredFields(fields: Record<string, unknown>, requiredFields: string[]): void;
14
233
  /**
15
- * Build filter query string parameters
234
+ * Builds filter query string parameters for Lemon Squeezy API.
235
+ *
236
+ * Converts camelCase field names to snake_case and wraps them in
237
+ * filter[] syntax as required by the API.
238
+ *
239
+ * @param filters - Object containing filter key-value pairs
240
+ * @returns Query string parameters object for API request
241
+ *
242
+ * @example
243
+ * buildFilterParams({ storeId: 123, status: 'active' })
244
+ * // Returns: { 'filter[store_id]': 123, 'filter[status]': 'active' }
16
245
  */
17
246
  export declare function buildFilterParams(filters: IDataObject): Record<string, string | number>;
18
247
  /**
19
- * Build JSON:API request body
248
+ * Builds a JSON:API compliant request body for create/update operations.
249
+ *
250
+ * Constructs the proper structure expected by Lemon Squeezy API:
251
+ * - data.type: Resource type (e.g., 'checkouts', 'customers')
252
+ * - data.attributes: Resource attributes
253
+ * - data.relationships: Optional related resource references
254
+ * - data.id: Optional resource ID (for updates)
255
+ *
256
+ * @param type - The JSON:API resource type
257
+ * @param attributes - Resource attributes to include
258
+ * @param relationships - Optional relationships to other resources
259
+ * @param id - Optional resource ID (required for updates)
260
+ * @returns Properly structured JSON:API request body
261
+ *
262
+ * @example
263
+ * buildJsonApiBody('customers', { name: 'John', email: 'john@example.com' },
264
+ * { store: { type: 'stores', id: '123' } })
265
+ * // Returns: { data: { type: 'customers', attributes: {...}, relationships: {...} } }
20
266
  */
21
267
  export declare function buildJsonApiBody(type: string, attributes: IDataObject, relationships?: Record<string, {
22
268
  type: string;
23
269
  id: string;
24
270
  }>, id?: string): IDataObject;
25
271
  /**
26
- * Parse webhook signature for validation
272
+ * Verifies a webhook signature using HMAC-SHA256.
273
+ *
274
+ * Uses timing-safe comparison to prevent timing attacks.
275
+ *
276
+ * @param payload - The raw webhook payload string
277
+ * @param signature - The signature from X-Signature header
278
+ * @param secret - The webhook signing secret
279
+ * @returns True if signature is valid, false otherwise
280
+ *
281
+ * @example
282
+ * const isValid = verifyWebhookSignature(
283
+ * '{"data": {...}}',
284
+ * 'abc123signature',
285
+ * 'webhook_secret_key'
286
+ * )
27
287
  */
28
288
  export declare function verifyWebhookSignature(payload: string, signature: string, secret: string): boolean;
289
+ /**
290
+ * Builds query parameters for including related resources in API responses.
291
+ *
292
+ * Uses the JSON:API include parameter to fetch related resources in a single
293
+ * request, reducing the number of API calls needed.
294
+ *
295
+ * @param includes - Array of relationship names to include
296
+ * @returns Query string parameters object with 'include' key
297
+ *
298
+ * @example
299
+ * buildIncludeParams(['store', 'customer', 'order-items'])
300
+ * // Returns: { include: 'store,customer,order-items' }
301
+ *
302
+ * buildIncludeParams([])
303
+ * // Returns: {}
304
+ */
305
+ export declare function buildIncludeParams(includes: string[]): Record<string, string>;
306
+ /**
307
+ * Builds advanced filter parameters with support for date ranges and sorting.
308
+ *
309
+ * Features:
310
+ * - Converts camelCase to snake_case for API compatibility
311
+ * - Handles date range filters with _after/_before suffixes
312
+ * - Adds sorting with ascending/descending direction
313
+ *
314
+ * @param filters - Object containing filter key-value pairs
315
+ * @param options - Optional configuration for date fields and sorting
316
+ * @param options.dateFields - Array of field names that are date ranges
317
+ * @param options.sortField - Field name to sort by
318
+ * @param options.sortDirection - Sort direction ('asc' or 'desc')
319
+ * @returns Query string parameters object for API request
320
+ *
321
+ * @example
322
+ * buildAdvancedFilterParams(
323
+ * { status: 'active', createdAt: { from: '2024-01-01', to: '2024-12-31' } },
324
+ * { dateFields: ['createdAt'], sortField: 'created_at', sortDirection: 'desc' }
325
+ * )
326
+ * // Returns: { 'filter[status]': 'active', 'filter[created_at_after]': '2024-01-01',
327
+ * // 'filter[created_at_before]': '2024-12-31', sort: '-created_at' }
328
+ */
329
+ export declare function buildAdvancedFilterParams(filters: IDataObject, options?: {
330
+ dateFields?: string[];
331
+ sortField?: string;
332
+ sortDirection?: 'asc' | 'desc';
333
+ }): Record<string, string | number>;
334
+ /**
335
+ * Extracts the 'data' field from a JSON:API response with proper typing.
336
+ *
337
+ * JSON:API responses wrap the actual resource data in a 'data' field.
338
+ * This helper extracts it while preserving type information.
339
+ *
340
+ * @template T - The expected type of the extracted data
341
+ * @param response - The full JSON:API response object
342
+ * @returns The extracted data, or undefined if not present
343
+ *
344
+ * @example
345
+ * const response = { data: { id: '1', type: 'products', attributes: {...} } }
346
+ * const product = extractResponseData<Product>(response)
347
+ * // Returns: { id: '1', type: 'products', attributes: {...} }
348
+ */
349
+ export declare function extractResponseData<T = IDataObject>(response: IDataObject): T | T[] | undefined;
350
+ /**
351
+ * Extracts included related resources from a JSON:API response.
352
+ *
353
+ * When using the 'include' query parameter, related resources are returned
354
+ * in the 'included' array of the response. This helper extracts them.
355
+ *
356
+ * @param response - The full JSON:API response object
357
+ * @returns Array of included resources, or empty array if none
358
+ *
359
+ * @example
360
+ * const response = {
361
+ * data: {...},
362
+ * included: [{ id: '1', type: 'stores', attributes: {...} }]
363
+ * }
364
+ * const stores = extractIncludedResources(response)
365
+ * // Returns: [{ id: '1', type: 'stores', attributes: {...} }]
366
+ */
367
+ export declare function extractIncludedResources(response: IDataObject): IDataObject[];