@genvoris/node 1.0.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.
- package/LICENSE +21 -0
- package/README.md +132 -0
- package/dist/index.d.mts +328 -0
- package/dist/index.d.ts +328 -0
- package/dist/index.js +384 -0
- package/dist/index.mjs +353 -0
- package/package.json +52 -0
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
interface GenvorisConfig {
|
|
2
|
+
/** Your store API key — starts with `gvk_live_` */
|
|
3
|
+
apiKey: string;
|
|
4
|
+
/** Override the base URL. Default: `https://genvoris.org/api/v1` */
|
|
5
|
+
baseUrl?: string;
|
|
6
|
+
/** Request timeout in milliseconds. Default: 30 000 */
|
|
7
|
+
timeoutMs?: number;
|
|
8
|
+
/** Maximum number of retries on 429/502/503/504. Default: 3 */
|
|
9
|
+
maxRetries?: number;
|
|
10
|
+
/** Additional headers to send on every request */
|
|
11
|
+
defaultHeaders?: Record<string, string>;
|
|
12
|
+
/** Custom fetch implementation. Default: `globalThis.fetch` */
|
|
13
|
+
fetch?: typeof globalThis.fetch;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
interface CustomerCreateParams {
|
|
17
|
+
/** Your stable external identifier. Re-POSTing with the same value upserts. */
|
|
18
|
+
externalId: string;
|
|
19
|
+
email?: string;
|
|
20
|
+
/** Plan to assign. No plan = every try-on returns 402. */
|
|
21
|
+
planId?: string;
|
|
22
|
+
/** Free-form metadata stored with the customer. */
|
|
23
|
+
metadata?: Record<string, unknown>;
|
|
24
|
+
}
|
|
25
|
+
interface CustomerUpdateParams {
|
|
26
|
+
email?: string | null;
|
|
27
|
+
/** Pass `null` to detach the plan. */
|
|
28
|
+
planId?: string | null;
|
|
29
|
+
status?: 'ACTIVE' | 'PAUSED' | 'CANCELLED';
|
|
30
|
+
metadata?: Record<string, unknown> | null;
|
|
31
|
+
/** When `true`, resets the period start to now and end to now + 30 days. */
|
|
32
|
+
resetPeriod?: boolean;
|
|
33
|
+
}
|
|
34
|
+
interface CustomerListParams {
|
|
35
|
+
status?: 'ACTIVE' | 'PAUSED' | 'CANCELLED';
|
|
36
|
+
/** 1–200. Default: 50. */
|
|
37
|
+
limit?: number;
|
|
38
|
+
/** Pagination cursor from the previous page's `next_cursor`. */
|
|
39
|
+
cursor?: string;
|
|
40
|
+
}
|
|
41
|
+
interface Customer {
|
|
42
|
+
id: string;
|
|
43
|
+
externalId: string;
|
|
44
|
+
email?: string | null;
|
|
45
|
+
planId?: string | null;
|
|
46
|
+
status: 'ACTIVE' | 'PAUSED' | 'CANCELLED';
|
|
47
|
+
createdAt: string;
|
|
48
|
+
updatedAt: string;
|
|
49
|
+
metadata?: Record<string, unknown> | null;
|
|
50
|
+
}
|
|
51
|
+
interface CustomerList {
|
|
52
|
+
data: Customer[];
|
|
53
|
+
next_cursor?: string | null;
|
|
54
|
+
}
|
|
55
|
+
interface CustomerUsage {
|
|
56
|
+
data: {
|
|
57
|
+
customer_id: string;
|
|
58
|
+
external_id: string;
|
|
59
|
+
plan: {
|
|
60
|
+
id: string;
|
|
61
|
+
name: string;
|
|
62
|
+
monthlyTryOns: number;
|
|
63
|
+
} | null;
|
|
64
|
+
status: string;
|
|
65
|
+
period_start: string;
|
|
66
|
+
period_end: string;
|
|
67
|
+
current: {
|
|
68
|
+
used: number;
|
|
69
|
+
limit: number;
|
|
70
|
+
remaining: number;
|
|
71
|
+
ok: boolean;
|
|
72
|
+
};
|
|
73
|
+
history: Array<{
|
|
74
|
+
period_start: string;
|
|
75
|
+
period_end: string;
|
|
76
|
+
used: number;
|
|
77
|
+
limit: number;
|
|
78
|
+
}>;
|
|
79
|
+
};
|
|
80
|
+
}
|
|
81
|
+
interface CustomerSession {
|
|
82
|
+
token: string;
|
|
83
|
+
expires_at: string;
|
|
84
|
+
}
|
|
85
|
+
interface CustomerSessionList {
|
|
86
|
+
data: CustomerSession[];
|
|
87
|
+
}
|
|
88
|
+
declare class CustomersResource {
|
|
89
|
+
private readonly config;
|
|
90
|
+
constructor(config: GenvorisConfig);
|
|
91
|
+
/** Create or upsert an end-customer. */
|
|
92
|
+
create(params: CustomerCreateParams): Promise<Customer>;
|
|
93
|
+
/** Retrieve a single customer by their Genvoris `id`. */
|
|
94
|
+
retrieve(id: string): Promise<Customer>;
|
|
95
|
+
/** Update a customer's email, plan, status, or metadata. */
|
|
96
|
+
update(id: string, params: CustomerUpdateParams): Promise<Customer>;
|
|
97
|
+
/** List customers with optional status filter and cursor pagination. */
|
|
98
|
+
list(params?: CustomerListParams): Promise<CustomerList>;
|
|
99
|
+
/** Soft-cancel a customer. Future try-ons return 402 `cancelled`. */
|
|
100
|
+
cancel(id: string): Promise<void>;
|
|
101
|
+
/** Return the customer's current-period quota state and usage history. */
|
|
102
|
+
usage(id: string): Promise<CustomerUsage>;
|
|
103
|
+
/** List active widget sessions for this customer. */
|
|
104
|
+
sessions(id: string): Promise<CustomerSessionList>;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
interface PlanCreateParams {
|
|
108
|
+
/** Display name. 1–80 characters. */
|
|
109
|
+
name: string;
|
|
110
|
+
/** Monthly try-on quota. 1–1 000 000. */
|
|
111
|
+
monthlyTryOns: number;
|
|
112
|
+
/** Map back to your billing price ID (e.g. Stripe price_xxx). */
|
|
113
|
+
externalPriceId?: string;
|
|
114
|
+
/** Defaults to `true`. */
|
|
115
|
+
active?: boolean;
|
|
116
|
+
}
|
|
117
|
+
interface PlanUpdateParams {
|
|
118
|
+
name?: string;
|
|
119
|
+
monthlyTryOns?: number;
|
|
120
|
+
externalPriceId?: string;
|
|
121
|
+
active?: boolean;
|
|
122
|
+
}
|
|
123
|
+
interface PlanListParams {
|
|
124
|
+
/** Include soft-disabled plans. Default: `false`. */
|
|
125
|
+
include_inactive?: boolean;
|
|
126
|
+
}
|
|
127
|
+
interface Plan {
|
|
128
|
+
id: string;
|
|
129
|
+
name: string;
|
|
130
|
+
monthlyTryOns: number;
|
|
131
|
+
externalPriceId?: string | null;
|
|
132
|
+
active: boolean;
|
|
133
|
+
createdAt: string;
|
|
134
|
+
updatedAt: string;
|
|
135
|
+
}
|
|
136
|
+
interface PlanList {
|
|
137
|
+
data: Plan[];
|
|
138
|
+
}
|
|
139
|
+
declare class PlansResource {
|
|
140
|
+
private readonly config;
|
|
141
|
+
constructor(config: GenvorisConfig);
|
|
142
|
+
/** List all plans. Pass `{ include_inactive: true }` to include disabled ones. */
|
|
143
|
+
list(params?: PlanListParams): Promise<PlanList>;
|
|
144
|
+
/** Create a new plan. Returns `201 Created`. */
|
|
145
|
+
create(params: PlanCreateParams): Promise<Plan>;
|
|
146
|
+
/** Retrieve a single plan. */
|
|
147
|
+
retrieve(id: string): Promise<Plan>;
|
|
148
|
+
/** Update any plan fields. */
|
|
149
|
+
update(id: string, params: PlanUpdateParams): Promise<Plan>;
|
|
150
|
+
/**
|
|
151
|
+
* Soft-disable a plan. Existing customers keep quota until cancelled or
|
|
152
|
+
* reassigned. The plan stops appearing in `list()` unless `include_inactive`
|
|
153
|
+
* is `true`.
|
|
154
|
+
*/
|
|
155
|
+
archive(id: string): Promise<void>;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
interface SessionMintParams {
|
|
159
|
+
/** Genvoris customer ID or your `externalId`. */
|
|
160
|
+
customerId: string;
|
|
161
|
+
/** JWT lifetime in seconds. Default: 900 (15 min). */
|
|
162
|
+
ttlSeconds?: number;
|
|
163
|
+
}
|
|
164
|
+
interface MintedSession {
|
|
165
|
+
token: string;
|
|
166
|
+
token_type: 'Bearer';
|
|
167
|
+
/** Remaining lifetime in seconds at issuance. */
|
|
168
|
+
expires_in: number;
|
|
169
|
+
/** ISO-8601 expiry timestamp. */
|
|
170
|
+
expires_at: string;
|
|
171
|
+
customer: {
|
|
172
|
+
id: string;
|
|
173
|
+
external_id: string;
|
|
174
|
+
plan_name: string | null;
|
|
175
|
+
monthly_try_ons: number | null;
|
|
176
|
+
period_end: string | null;
|
|
177
|
+
};
|
|
178
|
+
}
|
|
179
|
+
declare class SessionsResource {
|
|
180
|
+
private readonly config;
|
|
181
|
+
constructor(config: GenvorisConfig);
|
|
182
|
+
/**
|
|
183
|
+
* Mint a short-lived widget session token for a customer.
|
|
184
|
+
*
|
|
185
|
+
* The token should be sent to your frontend and passed to the
|
|
186
|
+
* Genvoris widget — never exposed in client-side code directly.
|
|
187
|
+
*/
|
|
188
|
+
mint({ customerId, ttlSeconds }: SessionMintParams): Promise<MintedSession>;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
interface WebhookCreateParams {
|
|
192
|
+
/** HTTPS endpoint URL Genvoris will POST events to. */
|
|
193
|
+
url: string;
|
|
194
|
+
/** Signing secret — store this securely; shown only once in the dashboard. */
|
|
195
|
+
secret: string;
|
|
196
|
+
/** Event types to subscribe to, e.g. `['end_customer.created']`. */
|
|
197
|
+
events: string[];
|
|
198
|
+
description?: string;
|
|
199
|
+
}
|
|
200
|
+
interface WebhookVerifyOptions {
|
|
201
|
+
/**
|
|
202
|
+
* The raw request body **as received over the wire** — do NOT parse and
|
|
203
|
+
* re-serialise, or the HMAC will mismatch.
|
|
204
|
+
*
|
|
205
|
+
* Pass a `string` or any `ArrayBufferView` (e.g. `Uint8Array`).
|
|
206
|
+
*/
|
|
207
|
+
payload: Uint8Array | string;
|
|
208
|
+
/** Value of the `X-Genvoris-Signature` header. */
|
|
209
|
+
header: string;
|
|
210
|
+
/** The endpoint signing secret from your dashboard. */
|
|
211
|
+
secret: string;
|
|
212
|
+
/**
|
|
213
|
+
* Maximum age of the timestamp in seconds before the signature is rejected.
|
|
214
|
+
* Default: 300 (5 minutes).
|
|
215
|
+
*/
|
|
216
|
+
toleranceSeconds?: number;
|
|
217
|
+
}
|
|
218
|
+
interface WebhookEndpoint {
|
|
219
|
+
id: string;
|
|
220
|
+
url: string;
|
|
221
|
+
events: string[];
|
|
222
|
+
description?: string | null;
|
|
223
|
+
active: boolean;
|
|
224
|
+
createdAt: string;
|
|
225
|
+
}
|
|
226
|
+
interface WebhookEndpointList {
|
|
227
|
+
data: WebhookEndpoint[];
|
|
228
|
+
}
|
|
229
|
+
/** Parsed, verified webhook event envelope. */
|
|
230
|
+
interface GenvorisEvent<T extends Record<string, unknown> = Record<string, unknown>> {
|
|
231
|
+
id: string;
|
|
232
|
+
type: string;
|
|
233
|
+
created: number;
|
|
234
|
+
data: T;
|
|
235
|
+
}
|
|
236
|
+
declare class WebhooksResource {
|
|
237
|
+
private readonly config;
|
|
238
|
+
constructor(config: GenvorisConfig);
|
|
239
|
+
/** List all webhook endpoints for your store. */
|
|
240
|
+
list(): Promise<WebhookEndpointList>;
|
|
241
|
+
/** Register a new webhook endpoint. */
|
|
242
|
+
create(params: WebhookCreateParams): Promise<WebhookEndpoint>;
|
|
243
|
+
/** Send a synthetic `webhook.test` ping to the endpoint. */
|
|
244
|
+
test(id: string): Promise<void>;
|
|
245
|
+
/** Delete a webhook endpoint. */
|
|
246
|
+
delete(id: string): Promise<void>;
|
|
247
|
+
/**
|
|
248
|
+
* Verify the `X-Genvoris-Signature` header and return the parsed event.
|
|
249
|
+
*
|
|
250
|
+
* Throws if the signature is invalid, the timestamp is too old, or the
|
|
251
|
+
* header is malformed. Uses `crypto.timingSafeEqual` to prevent
|
|
252
|
+
* timing attacks.
|
|
253
|
+
*
|
|
254
|
+
* @example
|
|
255
|
+
* ```ts
|
|
256
|
+
* import { WebhooksResource } from '@genvoris/node';
|
|
257
|
+
*
|
|
258
|
+
* const event = WebhooksResource.verify({
|
|
259
|
+
* payload: req.body, // raw Buffer — do NOT parse JSON first
|
|
260
|
+
* header: req.header('x-genvoris-signature') ?? '',
|
|
261
|
+
* secret: process.env.GENVORIS_WEBHOOK_SECRET!,
|
|
262
|
+
* });
|
|
263
|
+
* ```
|
|
264
|
+
*/
|
|
265
|
+
static verify<T extends Record<string, unknown> = Record<string, unknown>>({ payload, header, secret, toleranceSeconds, }: WebhookVerifyOptions): GenvorisEvent<T>;
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
declare class GenvorisAPIError extends Error {
|
|
269
|
+
readonly status: number;
|
|
270
|
+
readonly code: string;
|
|
271
|
+
readonly requestId: string | undefined;
|
|
272
|
+
constructor(args: {
|
|
273
|
+
status: number;
|
|
274
|
+
code: string;
|
|
275
|
+
message?: string;
|
|
276
|
+
requestId?: string;
|
|
277
|
+
});
|
|
278
|
+
}
|
|
279
|
+
declare class GenvorisAuthError extends GenvorisAPIError {
|
|
280
|
+
constructor(args: {
|
|
281
|
+
status: number;
|
|
282
|
+
code: string;
|
|
283
|
+
message?: string;
|
|
284
|
+
requestId?: string;
|
|
285
|
+
});
|
|
286
|
+
}
|
|
287
|
+
declare class GenvorisRateLimitError extends GenvorisAPIError {
|
|
288
|
+
readonly retryAfterSeconds: number;
|
|
289
|
+
constructor(args: {
|
|
290
|
+
status: number;
|
|
291
|
+
code: string;
|
|
292
|
+
message?: string;
|
|
293
|
+
requestId?: string;
|
|
294
|
+
retryAfterSeconds?: number;
|
|
295
|
+
});
|
|
296
|
+
}
|
|
297
|
+
declare class GenvorisValidationError extends GenvorisAPIError {
|
|
298
|
+
readonly fieldErrors: Record<string, string[]>;
|
|
299
|
+
constructor(args: {
|
|
300
|
+
status: number;
|
|
301
|
+
code: string;
|
|
302
|
+
message?: string;
|
|
303
|
+
requestId?: string;
|
|
304
|
+
fieldErrors?: Record<string, string[]>;
|
|
305
|
+
});
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
/**
|
|
309
|
+
* Official Genvoris Node.js SDK client.
|
|
310
|
+
*
|
|
311
|
+
* @example
|
|
312
|
+
* ```ts
|
|
313
|
+
* import Genvoris from '@genvoris/node';
|
|
314
|
+
*
|
|
315
|
+
* const gv = new Genvoris({ apiKey: process.env.GENVORIS_API_KEY! });
|
|
316
|
+
*
|
|
317
|
+
* const session = await gv.sessions.mint({ customerId: 'ec_abc' });
|
|
318
|
+
* ```
|
|
319
|
+
*/
|
|
320
|
+
declare class Genvoris {
|
|
321
|
+
readonly customers: CustomersResource;
|
|
322
|
+
readonly plans: PlansResource;
|
|
323
|
+
readonly sessions: SessionsResource;
|
|
324
|
+
readonly webhooks: WebhooksResource;
|
|
325
|
+
constructor(config: GenvorisConfig);
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
export { type Customer, type CustomerCreateParams, type CustomerList, type CustomerListParams, type CustomerSession, type CustomerSessionList, type CustomerUpdateParams, type CustomerUsage, GenvorisAPIError, GenvorisAuthError, type GenvorisConfig, type GenvorisEvent, GenvorisRateLimitError, GenvorisValidationError, type MintedSession, type Plan, type PlanCreateParams, type PlanList, type PlanListParams, type PlanUpdateParams, type SessionMintParams, type WebhookCreateParams, type WebhookEndpoint, type WebhookEndpointList, type WebhookVerifyOptions, WebhooksResource, Genvoris as default };
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,384 @@
|
|
|
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
|
+
GenvorisAPIError: () => GenvorisAPIError,
|
|
24
|
+
GenvorisAuthError: () => GenvorisAuthError,
|
|
25
|
+
GenvorisRateLimitError: () => GenvorisRateLimitError,
|
|
26
|
+
GenvorisValidationError: () => GenvorisValidationError,
|
|
27
|
+
WebhooksResource: () => WebhooksResource,
|
|
28
|
+
default: () => Genvoris
|
|
29
|
+
});
|
|
30
|
+
module.exports = __toCommonJS(index_exports);
|
|
31
|
+
|
|
32
|
+
// src/errors.ts
|
|
33
|
+
var GenvorisAPIError = class extends Error {
|
|
34
|
+
constructor(args) {
|
|
35
|
+
super(args.message ?? args.code);
|
|
36
|
+
this.name = "GenvorisAPIError";
|
|
37
|
+
this.status = args.status;
|
|
38
|
+
this.code = args.code;
|
|
39
|
+
this.requestId = args.requestId;
|
|
40
|
+
}
|
|
41
|
+
};
|
|
42
|
+
var GenvorisAuthError = class extends GenvorisAPIError {
|
|
43
|
+
constructor(args) {
|
|
44
|
+
super(args);
|
|
45
|
+
this.name = "GenvorisAuthError";
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
var GenvorisRateLimitError = class extends GenvorisAPIError {
|
|
49
|
+
constructor(args) {
|
|
50
|
+
super(args);
|
|
51
|
+
this.name = "GenvorisRateLimitError";
|
|
52
|
+
this.retryAfterSeconds = args.retryAfterSeconds ?? 60;
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
var GenvorisValidationError = class extends GenvorisAPIError {
|
|
56
|
+
constructor(args) {
|
|
57
|
+
super(args);
|
|
58
|
+
this.name = "GenvorisValidationError";
|
|
59
|
+
this.fieldErrors = args.fieldErrors ?? {};
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
// src/http.ts
|
|
64
|
+
var RETRY_STATUSES = /* @__PURE__ */ new Set([429, 502, 503, 504]);
|
|
65
|
+
var MAX_DELAY_MS = 8e3;
|
|
66
|
+
var DEFAULT_BASE_URL = "https://genvoris.org/api/v1";
|
|
67
|
+
var SDK_VERSION = "1.0.0";
|
|
68
|
+
function sleep(ms) {
|
|
69
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
70
|
+
}
|
|
71
|
+
async function request(config, path, opts = {}, attempt = 0) {
|
|
72
|
+
const { method = "GET", body, query } = opts;
|
|
73
|
+
const fetchFn = config.fetch ?? globalThis.fetch;
|
|
74
|
+
const baseUrl = (config.baseUrl ?? DEFAULT_BASE_URL).replace(/\/$/, "");
|
|
75
|
+
let url = `${baseUrl}${path}`;
|
|
76
|
+
if (query) {
|
|
77
|
+
const params = new URLSearchParams();
|
|
78
|
+
for (const [k, v] of Object.entries(query)) {
|
|
79
|
+
if (v !== void 0 && v !== null) params.set(k, String(v));
|
|
80
|
+
}
|
|
81
|
+
const qs = params.toString();
|
|
82
|
+
if (qs) url += `?${qs}`;
|
|
83
|
+
}
|
|
84
|
+
const controller = new AbortController();
|
|
85
|
+
const timerId = setTimeout(
|
|
86
|
+
() => controller.abort(),
|
|
87
|
+
config.timeoutMs ?? 3e4
|
|
88
|
+
);
|
|
89
|
+
let res;
|
|
90
|
+
try {
|
|
91
|
+
res = await fetchFn(url, {
|
|
92
|
+
method,
|
|
93
|
+
headers: {
|
|
94
|
+
Authorization: `Bearer ${config.apiKey}`,
|
|
95
|
+
"Content-Type": "application/json",
|
|
96
|
+
"User-Agent": `genvoris-node/${SDK_VERSION}`,
|
|
97
|
+
...config.defaultHeaders
|
|
98
|
+
},
|
|
99
|
+
body: body !== void 0 ? JSON.stringify(body) : void 0,
|
|
100
|
+
signal: controller.signal
|
|
101
|
+
});
|
|
102
|
+
} finally {
|
|
103
|
+
clearTimeout(timerId);
|
|
104
|
+
}
|
|
105
|
+
if (res.ok) {
|
|
106
|
+
if (res.status === 204) return void 0;
|
|
107
|
+
return res.json();
|
|
108
|
+
}
|
|
109
|
+
const requestId = res.headers.get("x-request-id") ?? void 0;
|
|
110
|
+
let errBody = {};
|
|
111
|
+
try {
|
|
112
|
+
errBody = await res.json();
|
|
113
|
+
} catch {
|
|
114
|
+
}
|
|
115
|
+
const code = errBody.error ?? "unknown_error";
|
|
116
|
+
const message = errBody.message ?? code;
|
|
117
|
+
if (RETRY_STATUSES.has(res.status)) {
|
|
118
|
+
const maxRetries = config.maxRetries ?? 3;
|
|
119
|
+
if (attempt < maxRetries) {
|
|
120
|
+
const base = Math.min(Math.pow(2, attempt) * 250, MAX_DELAY_MS);
|
|
121
|
+
const delay = Math.random() * base;
|
|
122
|
+
await sleep(delay);
|
|
123
|
+
return request(config, path, opts, attempt + 1);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
const errorBase = { status: res.status, code, message, requestId };
|
|
127
|
+
if (res.status === 401 || res.status === 403) {
|
|
128
|
+
throw new GenvorisAuthError(errorBase);
|
|
129
|
+
}
|
|
130
|
+
if (res.status === 429) {
|
|
131
|
+
const retryAfter = res.headers.get("retry-after");
|
|
132
|
+
throw new GenvorisRateLimitError({
|
|
133
|
+
...errorBase,
|
|
134
|
+
retryAfterSeconds: retryAfter ? Number(retryAfter) : 60
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
if (res.status === 400 || res.status === 422) {
|
|
138
|
+
throw new GenvorisValidationError({
|
|
139
|
+
...errorBase,
|
|
140
|
+
fieldErrors: errBody.fieldErrors ?? {}
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
throw new GenvorisAPIError(errorBase);
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// src/resources/customers.ts
|
|
147
|
+
var CustomersResource = class {
|
|
148
|
+
constructor(config) {
|
|
149
|
+
this.config = config;
|
|
150
|
+
}
|
|
151
|
+
/** Create or upsert an end-customer. */
|
|
152
|
+
create(params) {
|
|
153
|
+
return request(this.config, "/customers", {
|
|
154
|
+
method: "POST",
|
|
155
|
+
body: params
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
/** Retrieve a single customer by their Genvoris `id`. */
|
|
159
|
+
retrieve(id) {
|
|
160
|
+
return request(
|
|
161
|
+
this.config,
|
|
162
|
+
`/customers/${encodeURIComponent(id)}`
|
|
163
|
+
);
|
|
164
|
+
}
|
|
165
|
+
/** Update a customer's email, plan, status, or metadata. */
|
|
166
|
+
update(id, params) {
|
|
167
|
+
return request(
|
|
168
|
+
this.config,
|
|
169
|
+
`/customers/${encodeURIComponent(id)}`,
|
|
170
|
+
{ method: "PATCH", body: params }
|
|
171
|
+
);
|
|
172
|
+
}
|
|
173
|
+
/** List customers with optional status filter and cursor pagination. */
|
|
174
|
+
list(params = {}) {
|
|
175
|
+
return request(this.config, "/customers", {
|
|
176
|
+
query: params
|
|
177
|
+
});
|
|
178
|
+
}
|
|
179
|
+
/** Soft-cancel a customer. Future try-ons return 402 `cancelled`. */
|
|
180
|
+
cancel(id) {
|
|
181
|
+
return request(
|
|
182
|
+
this.config,
|
|
183
|
+
`/customers/${encodeURIComponent(id)}`,
|
|
184
|
+
{ method: "DELETE" }
|
|
185
|
+
);
|
|
186
|
+
}
|
|
187
|
+
/** Return the customer's current-period quota state and usage history. */
|
|
188
|
+
usage(id) {
|
|
189
|
+
return request(
|
|
190
|
+
this.config,
|
|
191
|
+
`/customers/${encodeURIComponent(id)}/usage`
|
|
192
|
+
);
|
|
193
|
+
}
|
|
194
|
+
/** List active widget sessions for this customer. */
|
|
195
|
+
sessions(id) {
|
|
196
|
+
return request(
|
|
197
|
+
this.config,
|
|
198
|
+
`/customers/${encodeURIComponent(id)}/sessions`
|
|
199
|
+
);
|
|
200
|
+
}
|
|
201
|
+
};
|
|
202
|
+
|
|
203
|
+
// src/resources/plans.ts
|
|
204
|
+
var PlansResource = class {
|
|
205
|
+
constructor(config) {
|
|
206
|
+
this.config = config;
|
|
207
|
+
}
|
|
208
|
+
/** List all plans. Pass `{ include_inactive: true }` to include disabled ones. */
|
|
209
|
+
list(params = {}) {
|
|
210
|
+
return request(this.config, "/plans", {
|
|
211
|
+
query: params
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
/** Create a new plan. Returns `201 Created`. */
|
|
215
|
+
create(params) {
|
|
216
|
+
return request(this.config, "/plans", {
|
|
217
|
+
method: "POST",
|
|
218
|
+
body: params
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
/** Retrieve a single plan. */
|
|
222
|
+
retrieve(id) {
|
|
223
|
+
return request(this.config, `/plans/${encodeURIComponent(id)}`);
|
|
224
|
+
}
|
|
225
|
+
/** Update any plan fields. */
|
|
226
|
+
update(id, params) {
|
|
227
|
+
return request(this.config, `/plans/${encodeURIComponent(id)}`, {
|
|
228
|
+
method: "PATCH",
|
|
229
|
+
body: params
|
|
230
|
+
});
|
|
231
|
+
}
|
|
232
|
+
/**
|
|
233
|
+
* Soft-disable a plan. Existing customers keep quota until cancelled or
|
|
234
|
+
* reassigned. The plan stops appearing in `list()` unless `include_inactive`
|
|
235
|
+
* is `true`.
|
|
236
|
+
*/
|
|
237
|
+
archive(id) {
|
|
238
|
+
return request(this.config, `/plans/${encodeURIComponent(id)}`, {
|
|
239
|
+
method: "DELETE"
|
|
240
|
+
});
|
|
241
|
+
}
|
|
242
|
+
};
|
|
243
|
+
|
|
244
|
+
// src/resources/sessions.ts
|
|
245
|
+
var SessionsResource = class {
|
|
246
|
+
constructor(config) {
|
|
247
|
+
this.config = config;
|
|
248
|
+
}
|
|
249
|
+
/**
|
|
250
|
+
* Mint a short-lived widget session token for a customer.
|
|
251
|
+
*
|
|
252
|
+
* The token should be sent to your frontend and passed to the
|
|
253
|
+
* Genvoris widget — never exposed in client-side code directly.
|
|
254
|
+
*/
|
|
255
|
+
mint({ customerId, ttlSeconds }) {
|
|
256
|
+
return request(
|
|
257
|
+
this.config,
|
|
258
|
+
`/customers/${encodeURIComponent(customerId)}/sessions`,
|
|
259
|
+
{
|
|
260
|
+
method: "POST",
|
|
261
|
+
body: ttlSeconds !== void 0 ? { expires_in: ttlSeconds } : void 0
|
|
262
|
+
}
|
|
263
|
+
);
|
|
264
|
+
}
|
|
265
|
+
};
|
|
266
|
+
|
|
267
|
+
// src/resources/webhooks.ts
|
|
268
|
+
var import_node_crypto = require("crypto");
|
|
269
|
+
function hexToBytes(hex) {
|
|
270
|
+
if (hex.length % 2 !== 0) throw new Error("genvoris: invalid hex string");
|
|
271
|
+
const bytes = new Uint8Array(hex.length / 2);
|
|
272
|
+
for (let i = 0; i < bytes.length; i++) {
|
|
273
|
+
bytes[i] = parseInt(hex.slice(i * 2, i * 2 + 2), 16);
|
|
274
|
+
}
|
|
275
|
+
return bytes;
|
|
276
|
+
}
|
|
277
|
+
var WebhooksResource = class {
|
|
278
|
+
constructor(config) {
|
|
279
|
+
this.config = config;
|
|
280
|
+
}
|
|
281
|
+
/** List all webhook endpoints for your store. */
|
|
282
|
+
list() {
|
|
283
|
+
return request(this.config, "/webhooks");
|
|
284
|
+
}
|
|
285
|
+
/** Register a new webhook endpoint. */
|
|
286
|
+
create(params) {
|
|
287
|
+
return request(this.config, "/webhooks", {
|
|
288
|
+
method: "POST",
|
|
289
|
+
body: params
|
|
290
|
+
});
|
|
291
|
+
}
|
|
292
|
+
/** Send a synthetic `webhook.test` ping to the endpoint. */
|
|
293
|
+
test(id) {
|
|
294
|
+
return request(
|
|
295
|
+
this.config,
|
|
296
|
+
`/webhooks/${encodeURIComponent(id)}/test`,
|
|
297
|
+
{ method: "POST" }
|
|
298
|
+
);
|
|
299
|
+
}
|
|
300
|
+
/** Delete a webhook endpoint. */
|
|
301
|
+
delete(id) {
|
|
302
|
+
return request(
|
|
303
|
+
this.config,
|
|
304
|
+
`/webhooks/${encodeURIComponent(id)}`,
|
|
305
|
+
{ method: "DELETE" }
|
|
306
|
+
);
|
|
307
|
+
}
|
|
308
|
+
// -------------------------------------------------------------------------
|
|
309
|
+
// Static helpers
|
|
310
|
+
// -------------------------------------------------------------------------
|
|
311
|
+
/**
|
|
312
|
+
* Verify the `X-Genvoris-Signature` header and return the parsed event.
|
|
313
|
+
*
|
|
314
|
+
* Throws if the signature is invalid, the timestamp is too old, or the
|
|
315
|
+
* header is malformed. Uses `crypto.timingSafeEqual` to prevent
|
|
316
|
+
* timing attacks.
|
|
317
|
+
*
|
|
318
|
+
* @example
|
|
319
|
+
* ```ts
|
|
320
|
+
* import { WebhooksResource } from '@genvoris/node';
|
|
321
|
+
*
|
|
322
|
+
* const event = WebhooksResource.verify({
|
|
323
|
+
* payload: req.body, // raw Buffer — do NOT parse JSON first
|
|
324
|
+
* header: req.header('x-genvoris-signature') ?? '',
|
|
325
|
+
* secret: process.env.GENVORIS_WEBHOOK_SECRET!,
|
|
326
|
+
* });
|
|
327
|
+
* ```
|
|
328
|
+
*/
|
|
329
|
+
static verify({
|
|
330
|
+
payload,
|
|
331
|
+
header,
|
|
332
|
+
secret,
|
|
333
|
+
toleranceSeconds = 300
|
|
334
|
+
}) {
|
|
335
|
+
const raw = typeof payload === "string" ? payload : new TextDecoder().decode(payload);
|
|
336
|
+
const parts = {};
|
|
337
|
+
for (const part of header.split(",")) {
|
|
338
|
+
const eq = part.indexOf("=");
|
|
339
|
+
if (eq !== -1) parts[part.slice(0, eq).trim()] = part.slice(eq + 1).trim();
|
|
340
|
+
}
|
|
341
|
+
const { t, v1 } = parts;
|
|
342
|
+
if (!t || !v1) {
|
|
343
|
+
throw new Error("genvoris: invalid signature header \u2014 expected t=...,v1=...");
|
|
344
|
+
}
|
|
345
|
+
const ts = parseInt(t, 10);
|
|
346
|
+
if (!Number.isFinite(ts)) {
|
|
347
|
+
throw new Error("genvoris: invalid signature timestamp");
|
|
348
|
+
}
|
|
349
|
+
const age = Math.abs(Date.now() / 1e3 - ts);
|
|
350
|
+
if (age > toleranceSeconds) {
|
|
351
|
+
throw new Error(
|
|
352
|
+
`genvoris: signature timestamp too old (${Math.round(age)}s > ${toleranceSeconds}s tolerance)`
|
|
353
|
+
);
|
|
354
|
+
}
|
|
355
|
+
const expectedHex = (0, import_node_crypto.createHmac)("sha256", secret).update(`${ts}.${raw}`).digest("hex");
|
|
356
|
+
const a = hexToBytes(expectedHex);
|
|
357
|
+
const b = hexToBytes(v1);
|
|
358
|
+
if (a.length !== b.length || !(0, import_node_crypto.timingSafeEqual)(a, b)) {
|
|
359
|
+
throw new Error("genvoris: signature mismatch");
|
|
360
|
+
}
|
|
361
|
+
return JSON.parse(raw);
|
|
362
|
+
}
|
|
363
|
+
};
|
|
364
|
+
|
|
365
|
+
// src/index.ts
|
|
366
|
+
var Genvoris = class {
|
|
367
|
+
constructor(config) {
|
|
368
|
+
if (!config?.apiKey) {
|
|
369
|
+
throw new Error("Genvoris: apiKey is required");
|
|
370
|
+
}
|
|
371
|
+
this.customers = new CustomersResource(config);
|
|
372
|
+
this.plans = new PlansResource(config);
|
|
373
|
+
this.sessions = new SessionsResource(config);
|
|
374
|
+
this.webhooks = new WebhooksResource(config);
|
|
375
|
+
}
|
|
376
|
+
};
|
|
377
|
+
// Annotate the CommonJS export names for ESM import in node:
|
|
378
|
+
0 && (module.exports = {
|
|
379
|
+
GenvorisAPIError,
|
|
380
|
+
GenvorisAuthError,
|
|
381
|
+
GenvorisRateLimitError,
|
|
382
|
+
GenvorisValidationError,
|
|
383
|
+
WebhooksResource
|
|
384
|
+
});
|