@clikgate/node 2.0.1 → 2.1.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.
Files changed (74) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +116 -7
  3. package/SECURITY.md +2 -1
  4. package/dist/cjs/client.d.ts +38 -10
  5. package/dist/cjs/client.js +50 -16
  6. package/dist/cjs/currency.d.ts +7 -0
  7. package/dist/cjs/currency.js +75 -0
  8. package/dist/cjs/enums.js +1 -1
  9. package/dist/cjs/event-types.d.ts +108 -0
  10. package/dist/cjs/event-types.js +109 -0
  11. package/dist/cjs/express.d.ts +11 -2
  12. package/dist/cjs/express.js +3 -2
  13. package/dist/cjs/fastify.d.ts +4 -1
  14. package/dist/cjs/fastify.js +3 -2
  15. package/dist/cjs/generated/index.d.ts +1759 -86
  16. package/dist/cjs/generated/index.js +1 -1
  17. package/dist/cjs/identity.js +1 -1
  18. package/dist/cjs/index.d.ts +9 -1
  19. package/dist/cjs/index.js +15 -1
  20. package/dist/cjs/installation.d.ts +47 -0
  21. package/dist/cjs/installation.js +83 -0
  22. package/dist/cjs/lookups.d.ts +128 -0
  23. package/dist/cjs/lookups.js +149 -0
  24. package/dist/cjs/models.d.ts +342 -0
  25. package/dist/cjs/models.js +2 -0
  26. package/dist/cjs/next.d.ts +22 -0
  27. package/dist/cjs/next.js +20 -0
  28. package/dist/cjs/pager.d.ts +5 -0
  29. package/dist/cjs/pager.js +40 -0
  30. package/dist/cjs/referrals.d.ts +169 -0
  31. package/dist/cjs/referrals.js +208 -0
  32. package/dist/cjs/resources.d.ts +34 -5
  33. package/dist/cjs/resources.js +43 -42
  34. package/dist/cjs/types.d.ts +57 -10
  35. package/dist/cjs/version.d.ts +1 -1
  36. package/dist/cjs/version.js +1 -1
  37. package/dist/cjs/webhooks.d.ts +3 -2
  38. package/dist/cjs/webhooks.js +43 -2
  39. package/dist/esm/client.d.ts +38 -10
  40. package/dist/esm/client.js +50 -16
  41. package/dist/esm/currency.d.ts +7 -0
  42. package/dist/esm/currency.js +67 -0
  43. package/dist/esm/enums.js +1 -1
  44. package/dist/esm/event-types.d.ts +108 -0
  45. package/dist/esm/event-types.js +106 -0
  46. package/dist/esm/express.d.ts +11 -2
  47. package/dist/esm/express.js +3 -2
  48. package/dist/esm/fastify.d.ts +4 -1
  49. package/dist/esm/fastify.js +3 -2
  50. package/dist/esm/generated/index.d.ts +1759 -86
  51. package/dist/esm/generated/index.js +1 -1
  52. package/dist/esm/identity.js +1 -1
  53. package/dist/esm/index.d.ts +9 -1
  54. package/dist/esm/index.js +4 -0
  55. package/dist/esm/installation.d.ts +47 -0
  56. package/dist/esm/installation.js +77 -0
  57. package/dist/esm/lookups.d.ts +128 -0
  58. package/dist/esm/lookups.js +142 -0
  59. package/dist/esm/models.d.ts +342 -0
  60. package/dist/esm/models.js +1 -0
  61. package/dist/esm/next.d.ts +22 -0
  62. package/dist/esm/next.js +19 -0
  63. package/dist/esm/pager.d.ts +5 -0
  64. package/dist/esm/pager.js +36 -0
  65. package/dist/esm/referrals.d.ts +169 -0
  66. package/dist/esm/referrals.js +204 -0
  67. package/dist/esm/resources.d.ts +34 -5
  68. package/dist/esm/resources.js +43 -42
  69. package/dist/esm/types.d.ts +57 -10
  70. package/dist/esm/version.d.ts +1 -1
  71. package/dist/esm/version.js +1 -1
  72. package/dist/esm/webhooks.d.ts +3 -2
  73. package/dist/esm/webhooks.js +42 -2
  74. package/package.json +2 -2
@@ -0,0 +1,208 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Referrals = exports.REFERRER_IMPORT_BATCH = void 0;
4
+ const errors_js_1 = require("./errors.js");
5
+ const http_js_1 = require("./http.js");
6
+ const money_js_1 = require("./money.js");
7
+ const currency_js_1 = require("./currency.js");
8
+ const pager_js_1 = require("./pager.js");
9
+ /** The API's limit of referrers per import request. */
10
+ exports.REFERRER_IMPORT_BATCH = 1000;
11
+ /** Referrals: referrers, referrals, manual overrides, qualification steps and imports. */
12
+ class Referrals {
13
+ core;
14
+ /** @internal */
15
+ constructor(core) {
16
+ this.core = core;
17
+ }
18
+ async call(method, path, init, requestOptions) {
19
+ const { status, data } = await this.core.requester.request({ method, path, ...init, ...requestOptions });
20
+ return { status, data };
21
+ }
22
+ /**
23
+ * Get the referrer for one of your customers in a program, creating it (with its code and link) the first time.
24
+ * `created` is true when it was just created.
25
+ *
26
+ * @example
27
+ * const referrer = await clikgate.referrals.getOrCreateReferrer('rpg_01J…', { customerId: user.id, displayName: user.firstName });
28
+ * console.log(referrer.code, referrer.url, referrer.created);
29
+ */
30
+ async getOrCreateReferrer(programId, params, requestOptions = {}) {
31
+ const program = (0, http_js_1.encodePathSegment)((0, http_js_1.requireId)(programId, 'program_id'));
32
+ const body = (0, pager_js_1.defined)({ customer_user_id: (0, http_js_1.requireId)(params?.customerId, 'customer_id'), display_name: params.displayName, external_code: params.externalCode });
33
+ const { status, data } = await this.call('POST', `/v1/referral-programs/${program}/referrers`, { body }, requestOptions);
34
+ return (0, currency_js_1.toReferrerResult)(data, status);
35
+ }
36
+ /**
37
+ * Fetch a referrer by ID.
38
+ *
39
+ * @example
40
+ * const referrer = await clikgate.referrals.getReferrer('rfr_01J…');
41
+ */
42
+ async getReferrer(referrerId, requestOptions = {}) {
43
+ const { data } = await this.call('GET', `/v1/referrers/${(0, http_js_1.encodePathSegment)((0, http_js_1.requireId)(referrerId, 'referrer_id'))}`, {}, requestOptions);
44
+ return (0, currency_js_1.toReferrer)(data);
45
+ }
46
+ /**
47
+ * Find a referrer by your customer ID or by code. Returns `null` when there is none (404); other errors throw.
48
+ *
49
+ * @example
50
+ * const referrer = await clikgate.referrals.findReferrer('rpg_01J…', { customerId: user.id });
51
+ * if (!referrer) { … }
52
+ */
53
+ async findReferrer(programId, lookup, requestOptions = {}) {
54
+ const program = (0, http_js_1.encodePathSegment)((0, http_js_1.requireId)(programId, 'program_id'));
55
+ const hasCustomer = lookup?.customerId !== undefined && lookup?.customerId !== null;
56
+ const hasCode = lookup?.code !== undefined && lookup?.code !== null;
57
+ if (hasCustomer === hasCode)
58
+ throw (0, errors_js_1.localError)('invalid_argument', 'Pass exactly one of customerId and code.', 'customer_id');
59
+ const path = hasCustomer
60
+ ? `/v1/referral-programs/${program}/referrers/by-user/${(0, http_js_1.encodePathSegment)((0, http_js_1.requireId)(lookup.customerId, 'customer_id'))}`
61
+ : `/v1/referral-programs/${program}/referrers/by-code/${(0, http_js_1.encodePathSegment)((0, http_js_1.requireId)(lookup.code, 'code'))}`;
62
+ try {
63
+ const { data } = await this.call('GET', path, {}, requestOptions);
64
+ return (0, currency_js_1.toReferrer)(data);
65
+ }
66
+ catch (err) {
67
+ if (err instanceof errors_js_1.NotFoundError)
68
+ return null;
69
+ throw err;
70
+ }
71
+ }
72
+ /**
73
+ * Fetch a referral by ID. Reward sides carry `amount` (normal units) next to `amount_minor`.
74
+ *
75
+ * @example
76
+ * const referral = await clikgate.referrals.get('ref_01J…');
77
+ * console.log(referral.status, referral.reward_snapshot?.referrer?.amount);
78
+ */
79
+ async get(referralId, requestOptions = {}) {
80
+ const { data } = await this.call('GET', `/v1/referrals/${(0, http_js_1.encodePathSegment)((0, http_js_1.requireId)(referralId, 'referral_id'))}`, {}, requestOptions);
81
+ return (0, currency_js_1.toReferral)(data);
82
+ }
83
+ /**
84
+ * Fetch one page of referrals.
85
+ *
86
+ * @example
87
+ * const page = await clikgate.referrals.listPage({ programId: 'rpg_01J…', status: 'qualified', limit: 100 });
88
+ */
89
+ async listPage(params = {}, requestOptions = {}) {
90
+ const query = (0, pager_js_1.defined)({
91
+ program_id: params.programId,
92
+ referrer_id: params.referrerId,
93
+ referee_customer_user_id: params.refereeCustomerId,
94
+ status: params.status,
95
+ from: params.from,
96
+ to: params.to,
97
+ limit: params.limit,
98
+ starting_after: params.startingAfter,
99
+ ending_before: params.endingBefore,
100
+ });
101
+ const { data } = await this.call('GET', '/v1/referrals', { query }, requestOptions);
102
+ return { ...data, data: (data?.data ?? []).map(currency_js_1.toReferral) };
103
+ }
104
+ /**
105
+ * Iterate over every referral, fetching pages lazily.
106
+ *
107
+ * @example
108
+ * for await (const referral of clikgate.referrals.list({ programId: 'rpg_01J…', status: 'qualified' })) {
109
+ * console.log(referral.id, referral.referee.customer_user_id);
110
+ * }
111
+ */
112
+ list(params = {}, requestOptions = {}) {
113
+ return (0, pager_js_1.paginate)((cursor) => this.listPage(cursor ? { ...params, startingAfter: cursor } : params, requestOptions));
114
+ }
115
+ /**
116
+ * Qualify a referral by hand (a manual override), with your reason.
117
+ *
118
+ * @example
119
+ * await clikgate.referrals.qualify('ref_01J…', { reason: 'Checked by support' });
120
+ */
121
+ async qualify(referralId, params, requestOptions = {}) {
122
+ return this.override(referralId, 'qualify', params?.reason, requestOptions);
123
+ }
124
+ /**
125
+ * Disqualify a referral by hand (a manual override), with your reason.
126
+ *
127
+ * @example
128
+ * await clikgate.referrals.disqualify('ref_01J…', { reason: 'Same household' });
129
+ */
130
+ async disqualify(referralId, params, requestOptions = {}) {
131
+ return this.override(referralId, 'disqualify', params?.reason, requestOptions);
132
+ }
133
+ async override(referralId, action, reason, requestOptions) {
134
+ const path = `/v1/referrals/${(0, http_js_1.encodePathSegment)((0, http_js_1.requireId)(referralId, 'referral_id'))}/override`;
135
+ const { data } = await this.call('POST', path, { body: { action, reason } }, requestOptions);
136
+ return (0, currency_js_1.toReferral)(data);
137
+ }
138
+ /**
139
+ * Complete the referral's current qualification step from your server (a goal it can't see otherwise).
140
+ *
141
+ * @example
142
+ * await clikgate.referrals.completeStep('ref_01J…', { goal: 'first_order', occurredAt: order.paidAt, value: '1500.50', currency: 'NGN' });
143
+ */
144
+ async completeStep(referralId, params, requestOptions = {}) {
145
+ const path = `/v1/referrals/${(0, http_js_1.encodePathSegment)((0, http_js_1.requireId)(referralId, 'referral_id'))}/steps`;
146
+ if (params?.occurredAt === undefined || params.occurredAt === null || params.occurredAt === '')
147
+ throw (0, errors_js_1.localError)('invalid_argument', 'occurredAt is required: when the step happened.', 'occurred_at');
148
+ const value = params.value === undefined || params.value === null ? undefined : (0, money_js_1.formatValue)(params.value, (m) => this.core.warn('inexact_number', m));
149
+ const body = (0, pager_js_1.defined)({ goal: params.goal, occurred_at: (0, http_js_1.formatDate)(params.occurredAt), value, currency: params.currency });
150
+ const { data } = await this.call('POST', path, { body }, requestOptions);
151
+ return (0, currency_js_1.toReferral)(data);
152
+ }
153
+ /**
154
+ * Import referrers (customers who already refer others, with their old codes). Rows are sent in batches of 1000;
155
+ * the result is one job per batch.
156
+ *
157
+ * @example
158
+ * const jobs = await clikgate.referrals.importReferrers('rpg_01J…', [{ customerId: 'user-42', externalCode: 'ADA-OLD' }]);
159
+ */
160
+ async importReferrers(programId, rows, requestOptions = {}) {
161
+ const program = (0, http_js_1.encodePathSegment)((0, http_js_1.requireId)(programId, 'program_id'));
162
+ if (!Array.isArray(rows))
163
+ throw (0, errors_js_1.localError)('invalid_argument', 'rows must be a list.', 'rows');
164
+ const wire = rows.map((r, i) => (0, pager_js_1.defined)({ customer_user_id: (0, http_js_1.requireId)(r?.customerId, `rows[${i}].customer_id`), external_code: r.externalCode, display_name: r.displayName }));
165
+ const jobs = [];
166
+ const batches = Math.ceil(wire.length / exports.REFERRER_IMPORT_BATCH);
167
+ for (let b = 0; b < batches; b++) {
168
+ const key = requestOptions.idempotencyKey && batches > 1 ? `${requestOptions.idempotencyKey}-${b}` : requestOptions.idempotencyKey;
169
+ const body = { referrers: wire.slice(b * exports.REFERRER_IMPORT_BATCH, (b + 1) * exports.REFERRER_IMPORT_BATCH) };
170
+ const { data } = await this.call('POST', `/v1/referral-programs/${program}/referrers/import`, { body }, { ...requestOptions, idempotencyKey: key });
171
+ jobs.push(data);
172
+ }
173
+ return jobs;
174
+ }
175
+ /**
176
+ * Block a referrer: their code and link stop creating referrals.
177
+ *
178
+ * @example
179
+ * await clikgate.referrals.blockReferrer('rfr_01J…', { reason: 'Fake installs' });
180
+ */
181
+ async blockReferrer(referrerId, params = {}, requestOptions = {}) {
182
+ const path = `/v1/referrers/${(0, http_js_1.encodePathSegment)((0, http_js_1.requireId)(referrerId, 'referrer_id'))}/block`;
183
+ const { data } = await this.call('POST', path, { body: (0, pager_js_1.defined)({ reason: params?.reason }) }, requestOptions);
184
+ return (0, currency_js_1.toReferrer)(data);
185
+ }
186
+ /**
187
+ * Unblock a referrer.
188
+ *
189
+ * @example
190
+ * await clikgate.referrals.unblockReferrer('rfr_01J…');
191
+ */
192
+ async unblockReferrer(referrerId, requestOptions = {}) {
193
+ const { data } = await this.call('POST', `/v1/referrers/${(0, http_js_1.encodePathSegment)((0, http_js_1.requireId)(referrerId, 'referrer_id'))}/unblock`, {}, requestOptions);
194
+ return (0, currency_js_1.toReferrer)(data);
195
+ }
196
+ /**
197
+ * Update a referrer's display name or your own attributes (`null` clears).
198
+ *
199
+ * @example
200
+ * await clikgate.referrals.updateReferrer('rfr_01J…', { displayName: 'Ada O.', attributes: { tier: 'gold' } });
201
+ */
202
+ async updateReferrer(referrerId, params, requestOptions = {}) {
203
+ const body = (0, pager_js_1.defined)({ display_name: params?.displayName, attributes: params?.attributes });
204
+ const { data } = await this.call('PATCH', `/v1/referrers/${(0, http_js_1.encodePathSegment)((0, http_js_1.requireId)(referrerId, 'referrer_id'))}`, { body }, requestOptions);
205
+ return (0, currency_js_1.toReferrer)(data);
206
+ }
207
+ }
208
+ exports.Referrals = Referrals;
@@ -1,5 +1,7 @@
1
1
  import { type RequestOptions } from './http.js';
2
2
  import type { Click, Conversion, GoalEvent, Link, LinkUpdateResult, ListPage, QrCode } from './types.js';
3
+ import type { LinkCreateParams, LinkUpdateParams } from './models.js';
4
+ import { type PageIterator } from './pager.js';
3
5
  type Params = Record<string, unknown>;
4
6
  /** Conversions: the older API. New integrations should use goals. */
5
7
  export declare class Conversions {
@@ -36,11 +38,8 @@ export interface QrOptions {
36
38
  dark?: string;
37
39
  light?: string;
38
40
  }
39
- /** An async iterator over every link that also exposes the first page. */
40
- export interface LinkIterator extends AsyncIterable<Link> {
41
- /** Collect up to `max` links (default: all). */
42
- toArray(max?: number): Promise<Link[]>;
43
- }
41
+ /** An async iterator over every link. */
42
+ export type LinkIterator = PageIterator<Link>;
44
43
  /** Links: create, read, update (with approvals and locks), list and QR codes. */
45
44
  export declare class Links {
46
45
  private readonly core;
@@ -51,6 +50,7 @@ export declare class Links {
51
50
  * const link = await clikgate.links.create({ destination_url: 'https://example.com/spring', og_title: 'Spring sale', og_image_url: 'https://example.com/og.png' });
52
51
  * console.log(link.short_url, link.warnings);
53
52
  */
53
+ create(params: LinkCreateParams, requestOptions?: RequestOptions): Promise<Link>;
54
54
  create(params: Params, requestOptions?: RequestOptions): Promise<Link>;
55
55
  /**
56
56
  * Fetch a link by ID.
@@ -68,6 +68,7 @@ export declare class Links {
68
68
  * const result = await clikgate.links.update('lnk_01J…', { destination_url: 'https://example.com/summer' });
69
69
  * if (!result.applied) console.log('waiting for approval:', result.change_request.id);
70
70
  */
71
+ update(id: string, params: LinkUpdateParams, requestOptions?: RequestOptions): Promise<LinkUpdateResult>;
71
72
  update(id: string, params: Params, requestOptions?: RequestOptions): Promise<LinkUpdateResult>;
72
73
  /**
73
74
  * Fetch one page of links (`limit` 1–100, `starting_after`, `ending_before`, filters such as `status`, `tag`, `campaign_id`).
@@ -85,6 +86,34 @@ export declare class Links {
85
86
  * }
86
87
  */
87
88
  list(params?: Params, requestOptions?: RequestOptions): LinkIterator;
89
+ /**
90
+ * Archive a link (`DELETE /v1/links/{id}`): it stops redirecting. Returns the archived link.
91
+ *
92
+ * @example
93
+ * const link = await clikgate.links.archive('lnk_01J…');
94
+ */
95
+ archive(id: string, requestOptions?: RequestOptions): Promise<Link>;
96
+ /**
97
+ * Fetch a link by your own external reference (`external_reference`).
98
+ *
99
+ * @example
100
+ * const link = await clikgate.links.getByReference('order-1001');
101
+ */
102
+ getByReference(reference: string, requestOptions?: RequestOptions): Promise<Link>;
103
+ /**
104
+ * Pause a link: visitors see the paused page until you resume it.
105
+ *
106
+ * @example
107
+ * const link = await clikgate.links.pause('lnk_01J…');
108
+ */
109
+ pause(id: string, requestOptions?: RequestOptions): Promise<Link>;
110
+ /**
111
+ * Resume a paused link.
112
+ *
113
+ * @example
114
+ * const link = await clikgate.links.resume('lnk_01J…');
115
+ */
116
+ resume(id: string, requestOptions?: RequestOptions): Promise<Link>;
88
117
  /**
89
118
  * Download the link's QR code.
90
119
  *
@@ -5,6 +5,7 @@ const guard_js_1 = require("./guard.js");
5
5
  const http_js_1 = require("./http.js");
6
6
  const money_js_1 = require("./money.js");
7
7
  const ads_hashing_js_1 = require("./ads-hashing.js");
8
+ const pager_js_1 = require("./pager.js");
8
9
  function withFormattedValue(core, params) {
9
10
  const out = {};
10
11
  for (const [k, v] of Object.entries(params))
@@ -66,13 +67,6 @@ class Links {
66
67
  constructor(core) {
67
68
  this.core = core;
68
69
  }
69
- /**
70
- * Create a link. The result's `warnings` include `no_preview` when there is no preview title and image.
71
- *
72
- * @example
73
- * const link = await clikgate.links.create({ destination_url: 'https://example.com/spring', og_title: 'Spring sale', og_image_url: 'https://example.com/og.png' });
74
- * console.log(link.short_url, link.warnings);
75
- */
76
70
  async create(params, requestOptions = {}) {
77
71
  const { data } = await this.core.requester.request({ method: 'POST', path: '/v1/links', body: params, ...requestOptions });
78
72
  return data;
@@ -87,15 +81,6 @@ class Links {
87
81
  const { data } = await this.core.requester.request({ method: 'GET', path: `/v1/links/${(0, http_js_1.encodePathSegment)((0, http_js_1.requireId)(id))}`, ...requestOptions });
88
82
  return data;
89
83
  }
90
- /**
91
- * Update a link. With two-person approval on, a destination change answers `202` and waits for a
92
- * second person: the result is `{ applied: false, change_request }`. A locked link throws {@link LinkLockedError}.
93
- * An explicit `null` clears a field.
94
- *
95
- * @example
96
- * const result = await clikgate.links.update('lnk_01J…', { destination_url: 'https://example.com/summer' });
97
- * if (!result.applied) console.log('waiting for approval:', result.change_request.id);
98
- */
99
84
  async update(id, params, requestOptions = {}) {
100
85
  const { status, data } = await this.core.requester.request({
101
86
  method: 'PATCH',
@@ -127,32 +112,48 @@ class Links {
127
112
  * }
128
113
  */
129
114
  list(params = {}, requestOptions = {}) {
130
- const listPage = (p) => this.listPage(p, requestOptions);
131
- async function* iterate() {
132
- let cursor = null;
133
- for (;;) {
134
- const page = await listPage(cursor ? { ...params, starting_after: cursor } : params);
135
- for (const item of page.data ?? [])
136
- yield item;
137
- if (!page.has_more || !page.next_cursor)
138
- return;
139
- cursor = page.next_cursor;
140
- }
141
- }
142
- return {
143
- [Symbol.asyncIterator]: iterate,
144
- async toArray(max = Number.POSITIVE_INFINITY) {
145
- const out = [];
146
- if (max <= 0)
147
- return out;
148
- for await (const l of iterate()) {
149
- out.push(l);
150
- if (out.length >= max)
151
- break;
152
- }
153
- return out;
154
- },
155
- };
115
+ return (0, pager_js_1.paginate)((cursor) => this.listPage(cursor ? { ...params, starting_after: cursor } : params, requestOptions));
116
+ }
117
+ /**
118
+ * Archive a link (`DELETE /v1/links/{id}`): it stops redirecting. Returns the archived link.
119
+ *
120
+ * @example
121
+ * const link = await clikgate.links.archive('lnk_01J…');
122
+ */
123
+ async archive(id, requestOptions = {}) {
124
+ const { data } = await this.core.requester.request({ method: 'DELETE', path: `/v1/links/${(0, http_js_1.encodePathSegment)((0, http_js_1.requireId)(id))}`, ...requestOptions });
125
+ return data;
126
+ }
127
+ /**
128
+ * Fetch a link by your own external reference (`external_reference`).
129
+ *
130
+ * @example
131
+ * const link = await clikgate.links.getByReference('order-1001');
132
+ */
133
+ async getByReference(reference, requestOptions = {}) {
134
+ const path = `/v1/links/by-reference/${(0, http_js_1.encodePathSegment)((0, http_js_1.requireId)(reference, 'reference'))}`;
135
+ const { data } = await this.core.requester.request({ method: 'GET', path, ...requestOptions });
136
+ return data;
137
+ }
138
+ /**
139
+ * Pause a link: visitors see the paused page until you resume it.
140
+ *
141
+ * @example
142
+ * const link = await clikgate.links.pause('lnk_01J…');
143
+ */
144
+ async pause(id, requestOptions = {}) {
145
+ const { data } = await this.core.requester.request({ method: 'POST', path: `/v1/links/${(0, http_js_1.encodePathSegment)((0, http_js_1.requireId)(id))}/pause`, ...requestOptions });
146
+ return data;
147
+ }
148
+ /**
149
+ * Resume a paused link.
150
+ *
151
+ * @example
152
+ * const link = await clikgate.links.resume('lnk_01J…');
153
+ */
154
+ async resume(id, requestOptions = {}) {
155
+ const { data } = await this.core.requester.request({ method: 'POST', path: `/v1/links/${(0, http_js_1.encodePathSegment)((0, http_js_1.requireId)(id))}/resume`, ...requestOptions });
156
+ return data;
156
157
  }
157
158
  /**
158
159
  * Download the link's QR code.
@@ -1,4 +1,7 @@
1
1
  import type { GoalKind, GoalStatus, Provider } from './enums.js';
2
+ import type { LinkInfoResponse } from './generated/index.js';
3
+ import type { EventTypeValue } from './event-types.js';
4
+ import type { ConversionObject, DeviceChange, Install, PaymentReport, Referral, Referrer, WebhookGoalEvent } from './models.js';
2
5
  /** Wire objects returned by the hand-written resources. Keys are as the API sends them (snake_case). */
3
6
  /** Where a goal event was attributed. */
4
7
  export interface GoalAttribution {
@@ -86,8 +89,8 @@ export interface LinkWarning {
86
89
  message: string;
87
90
  param?: string | null;
88
91
  }
89
- /** A link (`/v1/links`). Only the most used fields are typed; the rest are kept. */
90
- export interface Link {
92
+ /** A link (`/v1/links`): every field of the API's link, plus any newer field (kept as is). */
93
+ export interface Link extends Omit<LinkInfoResponse, 'object' | 'warnings' | 'metadata' | 'domain_badge' | 'locked'> {
91
94
  object: 'link';
92
95
  id: string;
93
96
  short_url: string;
@@ -194,25 +197,69 @@ export interface ServerSdkConfig {
194
197
  minimum_sdk_versions: Partial<Record<'node' | 'python' | 'php' | 'java' | 'dotnet', string>>;
195
198
  [key: string]: unknown;
196
199
  }
197
- /** A webhook event. */
198
- export interface WebhookEvent<T = Record<string, unknown>> {
200
+ /** Typed accessors of a verified webhook event (SPEC 29). Each gives `null` for an event of another family. */
201
+ export interface WebhookEventAccessors {
202
+ /** `referral.*`: the referral, with reward amounts. */
203
+ asReferral(): Referral | null;
204
+ /** `referrer.*`: the referrer. */
205
+ asReferrer(): Referrer | null;
206
+ /** `goal.completed` / `goal.reversed`: the goal event as webhooks show it. */
207
+ asGoalEvent(): WebhookGoalEvent | null;
208
+ /** `install.*`: the install. */
209
+ asInstall(): Install | null;
210
+ /** `payment.*`: the payment report. */
211
+ asPayment(): PaymentReport | null;
212
+ /** `conversion.*`: the conversion. */
213
+ asConversion(): ConversionObject | null;
214
+ /** `person.device_changed`: the device change. */
215
+ asDeviceChange(): DeviceChange | null;
216
+ /** The same event, typed as the union discriminated by `type`. */
217
+ typed(): TypedWebhookEvent;
218
+ }
219
+ /** A webhook event's `data`. */
220
+ export interface WebhookEventData<T> {
221
+ object: T;
222
+ previous_attributes?: Record<string, unknown> | null;
223
+ [key: string]: unknown;
224
+ }
225
+ /** A webhook event. `data` is the raw payload; the `as…()` accessors give typed objects. */
226
+ export interface WebhookEvent<T = Record<string, unknown>> extends WebhookEventAccessors {
199
227
  id: string;
200
228
  object: 'event';
201
- /** e.g. `goal.completed`, `link.destination_changed`, `subscription.updated`. */
229
+ /** e.g. `referral.qualified`, `goal.completed`, `link.destination_changed`. Compare with `EventType`. */
202
230
  type: string;
203
231
  api_version: string;
204
232
  created_at: string;
205
233
  organization_id: string;
206
234
  livemode: boolean;
207
- data: {
208
- object: T;
209
- previous_attributes?: Record<string, unknown> | null;
210
- [key: string]: unknown;
211
- };
235
+ data: WebhookEventData<T>;
236
+ [key: string]: unknown;
237
+ }
238
+ /** One member of {@link TypedWebhookEvent}. */
239
+ export interface WebhookEventOf<Type extends string, T> extends WebhookEventAccessors {
240
+ id: string;
241
+ object: 'event';
242
+ type: Type;
243
+ api_version: string;
244
+ created_at: string;
245
+ organization_id: string;
246
+ livemode: boolean;
247
+ data: WebhookEventData<T>;
212
248
  [key: string]: unknown;
213
249
  }
250
+ type Family<P extends string> = Extract<EventTypeValue, `${P}.${string}`>;
251
+ type Typed = Family<'referral'> | Family<'referrer'> | Family<'goal'> | Family<'install'> | Family<'payment'> | Family<'conversion'> | 'person.device_changed';
252
+ /**
253
+ * Every webhook event this SDK release knows, discriminated by `type` (`event.typed()`):
254
+ *
255
+ * @example
256
+ * const e = event.typed();
257
+ * if (e.type === EventType.ReferralQualified) console.log(e.data.object.referrer.customer_user_id);
258
+ */
259
+ export type TypedWebhookEvent = WebhookEventOf<Family<'referral'>, Referral> | WebhookEventOf<Family<'referrer'>, Referrer> | WebhookEventOf<Family<'goal'>, WebhookGoalEvent> | WebhookEventOf<Family<'install'>, Install> | WebhookEventOf<Family<'payment'>, PaymentReport> | WebhookEventOf<Family<'conversion'>, ConversionObject> | WebhookEventOf<'person.device_changed', DeviceChange> | WebhookEventOf<Exclude<EventTypeValue, Typed>, Record<string, unknown>>;
214
260
  /** QR code bytes. */
215
261
  export interface QrCode {
216
262
  contentType: string;
217
263
  data: Uint8Array;
218
264
  }
265
+ export {};
@@ -1,2 +1,2 @@
1
1
  /** The SDK version (kept equal to package.json by `npm run check:version`). */
2
- export declare const VERSION = "2.0.1";
2
+ export declare const VERSION = "2.1.0";
@@ -2,4 +2,4 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.VERSION = void 0;
4
4
  /** The SDK version (kept equal to package.json by `npm run check:version`). */
5
- exports.VERSION = '2.0.1';
5
+ exports.VERSION = '2.1.0';
@@ -18,10 +18,11 @@ export declare const webhooks: {
18
18
  *
19
19
  * @example
20
20
  * import express from 'express';
21
- * import { webhooks } from '@clikgate/node';
21
+ * import { webhooks, EventType } from '@clikgate/node';
22
22
  * app.post('/webhooks/clikgate', express.raw({ type: 'application/json' }), (req, res) => {
23
23
  * const event = webhooks.verify(req.body, req.get('Clikgate-Signature'), process.env.CLIKGATE_WEBHOOK_SECRET!);
24
- * if (event.type === 'goal.completed') { … } // dedupe on event.id: delivery is at-least-once
24
+ * const referral = event.asReferral(); // null for other event types
25
+ * if (referral && event.type === EventType.ReferralQualified) { … } // dedupe on event.id: delivery is at-least-once
25
26
  * res.sendStatus(200);
26
27
  * });
27
28
  */
@@ -1,8 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.webhooks = void 0;
4
+ exports.withAccessors = withAccessors;
4
5
  const node_crypto_1 = require("node:crypto");
5
6
  const errors_js_1 = require("./errors.js");
7
+ const currency_js_1 = require("./currency.js");
6
8
  const fail = (code, message) => new errors_js_1.SignatureVerificationError({ message, code });
7
9
  function toBytes(raw) {
8
10
  if (typeof raw === 'string')
@@ -69,6 +71,44 @@ function verifyWith(rawBody, signatureHeader, secrets, options) {
69
71
  }
70
72
  if (!event || typeof event !== 'object' || Array.isArray(event))
71
73
  throw fail('invalid_payload', 'The body is not an event object.');
74
+ return withAccessors(event);
75
+ }
76
+ function objectOf(event, family) {
77
+ const type = event.type;
78
+ if (typeof type !== 'string' || !type.startsWith(`${family}.`))
79
+ return null;
80
+ const data = event.data;
81
+ if (!data || typeof data !== 'object' || Array.isArray(data))
82
+ return null;
83
+ const object = data.object;
84
+ return object && typeof object === 'object' && !Array.isArray(object) ? object : null;
85
+ }
86
+ /** @internal Add the typed accessors as non-enumerable methods (JSON.stringify(event) is unchanged). */
87
+ function withAccessors(event) {
88
+ const accessors = {
89
+ asReferral: () => {
90
+ const o = objectOf(event, 'referral');
91
+ return o ? (0, currency_js_1.toReferral)(o) : null;
92
+ },
93
+ asReferrer: () => {
94
+ const o = objectOf(event, 'referrer');
95
+ return o ? (0, currency_js_1.toReferrer)(o) : null;
96
+ },
97
+ asGoalEvent: () => objectOf(event, 'goal'),
98
+ asInstall: () => objectOf(event, 'install'),
99
+ asPayment: () => objectOf(event, 'payment'),
100
+ asConversion: () => objectOf(event, 'conversion'),
101
+ asDeviceChange: () => {
102
+ if (event.type !== 'person.device_changed')
103
+ return null;
104
+ const data = event.data;
105
+ const object = data && typeof data === 'object' ? data.object : null;
106
+ return object && typeof object === 'object' && !Array.isArray(object) ? object : null;
107
+ },
108
+ typed: () => event,
109
+ };
110
+ for (const [name, fn] of Object.entries(accessors))
111
+ Object.defineProperty(event, name, { value: fn, enumerable: false, writable: true, configurable: true });
72
112
  return event;
73
113
  }
74
114
  /**
@@ -81,10 +121,11 @@ exports.webhooks = {
81
121
  *
82
122
  * @example
83
123
  * import express from 'express';
84
- * import { webhooks } from '@clikgate/node';
124
+ * import { webhooks, EventType } from '@clikgate/node';
85
125
  * app.post('/webhooks/clikgate', express.raw({ type: 'application/json' }), (req, res) => {
86
126
  * const event = webhooks.verify(req.body, req.get('Clikgate-Signature'), process.env.CLIKGATE_WEBHOOK_SECRET!);
87
- * if (event.type === 'goal.completed') { … } // dedupe on event.id: delivery is at-least-once
127
+ * const referral = event.asReferral(); // null for other event types
128
+ * if (referral && event.type === EventType.ReferralQualified) { … } // dedupe on event.id: delivery is at-least-once
88
129
  * res.sendStatus(200);
89
130
  * });
90
131
  */