@clikgate/node 0.0.0-stage → 2.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (119) hide show
  1. package/CHANGELOG.md +136 -0
  2. package/LICENSE +21 -0
  3. package/README.md +311 -2
  4. package/SECURITY.md +34 -0
  5. package/dist/cjs/ads-hashing.d.ts +37 -0
  6. package/dist/cjs/ads-hashing.js +67 -0
  7. package/dist/cjs/click-ids.d.ts +184 -0
  8. package/dist/cjs/click-ids.js +535 -0
  9. package/dist/cjs/client.d.ts +191 -0
  10. package/dist/cjs/client.js +291 -0
  11. package/dist/cjs/config.d.ts +12 -0
  12. package/dist/cjs/config.js +87 -0
  13. package/dist/cjs/core.d.ts +15 -0
  14. package/dist/cjs/core.js +100 -0
  15. package/dist/cjs/customer-id.d.ts +26 -0
  16. package/dist/cjs/customer-id.js +52 -0
  17. package/dist/cjs/enums.d.ts +48 -0
  18. package/dist/cjs/enums.js +47 -0
  19. package/dist/cjs/errors.d.ts +117 -0
  20. package/dist/cjs/errors.js +257 -0
  21. package/dist/cjs/express.d.ts +49 -0
  22. package/dist/cjs/express.js +44 -0
  23. package/dist/cjs/fastify.d.ts +47 -0
  24. package/dist/cjs/fastify.js +35 -0
  25. package/dist/cjs/generated/index.d.ts +17793 -0
  26. package/dist/cjs/generated/index.js +8896 -0
  27. package/dist/cjs/goals.d.ts +116 -0
  28. package/dist/cjs/goals.js +381 -0
  29. package/dist/cjs/guard.d.ts +17 -0
  30. package/dist/cjs/guard.js +40 -0
  31. package/dist/cjs/http.d.ts +16 -0
  32. package/dist/cjs/http.js +148 -0
  33. package/dist/cjs/identity.d.ts +42 -0
  34. package/dist/cjs/identity.js +133 -0
  35. package/dist/cjs/index.d.ts +34 -0
  36. package/dist/cjs/index.js +70 -0
  37. package/dist/cjs/known-customers.d.ts +45 -0
  38. package/dist/cjs/known-customers.js +95 -0
  39. package/dist/cjs/logger.d.ts +9 -0
  40. package/dist/cjs/logger.js +8 -0
  41. package/dist/cjs/money.d.ts +16 -0
  42. package/dist/cjs/money.js +51 -0
  43. package/dist/cjs/next.d.ts +81 -0
  44. package/dist/cjs/next.js +103 -0
  45. package/dist/cjs/package.json +1 -0
  46. package/dist/cjs/payments.d.ts +174 -0
  47. package/dist/cjs/payments.js +485 -0
  48. package/dist/cjs/resources.d.ts +109 -0
  49. package/dist/cjs/resources.js +189 -0
  50. package/dist/cjs/shutdown.d.ts +2 -0
  51. package/dist/cjs/shutdown.js +51 -0
  52. package/dist/cjs/transport.d.ts +14 -0
  53. package/dist/cjs/transport.js +204 -0
  54. package/dist/cjs/types.d.ts +218 -0
  55. package/dist/cjs/types.js +2 -0
  56. package/dist/cjs/user-agent.d.ts +1 -0
  57. package/dist/cjs/user-agent.js +53 -0
  58. package/dist/cjs/version.d.ts +2 -0
  59. package/dist/cjs/version.js +5 -0
  60. package/dist/cjs/webhooks.d.ts +36 -0
  61. package/dist/cjs/webhooks.js +108 -0
  62. package/dist/esm/ads-hashing.d.ts +37 -0
  63. package/dist/esm/ads-hashing.js +62 -0
  64. package/dist/esm/click-ids.d.ts +184 -0
  65. package/dist/esm/click-ids.js +526 -0
  66. package/dist/esm/client.d.ts +191 -0
  67. package/dist/esm/client.js +287 -0
  68. package/dist/esm/config.d.ts +12 -0
  69. package/dist/esm/config.js +82 -0
  70. package/dist/esm/core.d.ts +15 -0
  71. package/dist/esm/core.js +96 -0
  72. package/dist/esm/customer-id.d.ts +26 -0
  73. package/dist/esm/customer-id.js +47 -0
  74. package/dist/esm/enums.d.ts +48 -0
  75. package/dist/esm/enums.js +44 -0
  76. package/dist/esm/errors.d.ts +117 -0
  77. package/dist/esm/errors.js +234 -0
  78. package/dist/esm/express.d.ts +49 -0
  79. package/dist/esm/express.js +40 -0
  80. package/dist/esm/fastify.d.ts +47 -0
  81. package/dist/esm/fastify.js +32 -0
  82. package/dist/esm/generated/index.d.ts +17793 -0
  83. package/dist/esm/generated/index.js +8833 -0
  84. package/dist/esm/goals.d.ts +116 -0
  85. package/dist/esm/goals.js +371 -0
  86. package/dist/esm/guard.d.ts +17 -0
  87. package/dist/esm/guard.js +36 -0
  88. package/dist/esm/http.d.ts +16 -0
  89. package/dist/esm/http.js +138 -0
  90. package/dist/esm/identity.d.ts +42 -0
  91. package/dist/esm/identity.js +125 -0
  92. package/dist/esm/index.d.ts +34 -0
  93. package/dist/esm/index.js +23 -0
  94. package/dist/esm/known-customers.d.ts +45 -0
  95. package/dist/esm/known-customers.js +90 -0
  96. package/dist/esm/logger.d.ts +9 -0
  97. package/dist/esm/logger.js +5 -0
  98. package/dist/esm/money.d.ts +16 -0
  99. package/dist/esm/money.js +48 -0
  100. package/dist/esm/next.d.ts +81 -0
  101. package/dist/esm/next.js +96 -0
  102. package/dist/esm/package.json +1 -0
  103. package/dist/esm/payments.d.ts +174 -0
  104. package/dist/esm/payments.js +476 -0
  105. package/dist/esm/resources.d.ts +109 -0
  106. package/dist/esm/resources.js +183 -0
  107. package/dist/esm/shutdown.d.ts +2 -0
  108. package/dist/esm/shutdown.js +47 -0
  109. package/dist/esm/transport.d.ts +14 -0
  110. package/dist/esm/transport.js +166 -0
  111. package/dist/esm/types.d.ts +218 -0
  112. package/dist/esm/types.js +1 -0
  113. package/dist/esm/user-agent.d.ts +1 -0
  114. package/dist/esm/user-agent.js +16 -0
  115. package/dist/esm/version.d.ts +2 -0
  116. package/dist/esm/version.js +2 -0
  117. package/dist/esm/webhooks.d.ts +36 -0
  118. package/dist/esm/webhooks.js +105 -0
  119. package/package.json +128 -4
@@ -0,0 +1,96 @@
1
+ import { REDACTED } from './guard.js';
2
+ /** @internal The API's reason (and error code) for a goal name that isn't set up, in strict mode. */
3
+ export const UNKNOWN_GOAL = 'unknown_goal';
4
+ /** @internal State shared by the resources of one client. */
5
+ export class Core {
6
+ requester;
7
+ logger;
8
+ clock;
9
+ privateMode;
10
+ configCache;
11
+ onErrorFn;
12
+ warned = new Set();
13
+ constructor(requester, logger, clock, privateMode, configCache, onErrorFn) {
14
+ this.requester = requester;
15
+ this.logger = logger;
16
+ this.clock = clock;
17
+ this.privateMode = privateMode;
18
+ this.configCache = configCache;
19
+ this.onErrorFn = onErrorFn;
20
+ }
21
+ /** Warn with a stable code. With `onceKey`, at most once per client for that key. */
22
+ warn(code, message, onceKey) {
23
+ if (onceKey !== undefined) {
24
+ const k = `${code}:${onceKey}`;
25
+ if (this.warned.has(k))
26
+ return;
27
+ this.warned.add(k);
28
+ }
29
+ this.logger.warn(message, { code });
30
+ }
31
+ /** Whether the guard is (or may be) on right now, without fetching: used for redaction. */
32
+ mayBePrivate() {
33
+ if (this.privateMode === true)
34
+ return true;
35
+ if (this.privateMode === false)
36
+ return false;
37
+ const cfg = this.configCache.peek();
38
+ return cfg === null || cfg.private_mode;
39
+ }
40
+ /** Resolve the guard state, fetching config in `auto` mode. */
41
+ async guardState() {
42
+ if (this.privateMode === true)
43
+ return { guard: true, config: null };
44
+ if (this.privateMode === false)
45
+ return { guard: false, config: null };
46
+ const config = await this.configCache.get();
47
+ return { guard: config === null || config.private_mode, config };
48
+ }
49
+ /** The reference as it may appear in logs and on_error. */
50
+ shownReference(reference) {
51
+ if (this.mayBePrivate())
52
+ return REDACTED;
53
+ return typeof reference === 'string' ? reference : String(reference ?? '');
54
+ }
55
+ /**
56
+ * A goal the API refused because the organisation accepts only goals it has set up (`unknown_goal`): one line at
57
+ * debug level, only when the logger has `debug`. The goal name only: never the reference, customer ID, values or
58
+ * labels. The SDK never checks names itself and never remembers the refusal. Never throws.
59
+ */
60
+ noteRefusedGoal(goal, codeOrReason) {
61
+ if (codeOrReason !== UNKNOWN_GOAL || typeof goal !== 'string' || !this.logger.debug)
62
+ return;
63
+ try {
64
+ this.logger.debug(`Goal \`${goal}\` isn't set up in Clikgate`, { code: UNKNOWN_GOAL });
65
+ }
66
+ catch {
67
+ // a broken logger must not break the caller
68
+ }
69
+ }
70
+ /** Report a failure that can't be thrown: log at error level and call onError. Never throws. */
71
+ report(error, context) {
72
+ try {
73
+ const who = context.events.map((e) => `${e.goal}:${e.reference}`).join(', ');
74
+ this.logger.error(`Clikgate ${context.operation} failed (${error.name} ${error.code}${error.requestId ? `, request ${error.requestId}` : ''}) for ${who || 'no events'}${context.dropped ? '; dropped' : ''}.`, {
75
+ code: error.code,
76
+ requestId: error.requestId,
77
+ });
78
+ }
79
+ catch {
80
+ // a broken logger must not break the caller
81
+ }
82
+ if (!this.onErrorFn)
83
+ return;
84
+ try {
85
+ this.onErrorFn(error, context);
86
+ }
87
+ catch (err) {
88
+ try {
89
+ this.logger.error(`onError threw: ${err instanceof Error ? err.message : String(err)}`);
90
+ }
91
+ catch {
92
+ // ignore
93
+ }
94
+ }
95
+ }
96
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Your customer IDs, in one canonical form: the same form the API stores and checks, so an ID
3
+ * sent from your server, an import and an identity token always match.
4
+ *
5
+ * - canonical form: Unicode NFC, trimmed of Unicode whitespace (and U+FEFF) at both ends, case kept;
6
+ * - warnings (first match wins): `empty`, `too_long` (more than 128 characters), `looks_like_email`,
7
+ * `looks_like_national_id` (exactly 11 digits, unless `allow11DigitIds`), `looks_like_phone`.
8
+ *
9
+ * Use your own stable user ID (for example `u_10482`), never an email, phone number, BVN or NIN.
10
+ */
11
+ /** The longest customer ID kept as a known customer, in Unicode code points. */
12
+ export declare const CUSTOMER_ID_MAX_LENGTH = 128;
13
+ /** Why a customer ID can't be used as a known customer (the API's refusal reasons for the same checks). */
14
+ export type CustomerIdWarning = 'empty' | 'too_long' | 'looks_like_email' | 'looks_like_national_id' | 'looks_like_phone';
15
+ /** The canonical form of a customer ID: NFC, trimmed, case kept. */
16
+ export declare function canonicalCustomerId(customerId: string): string;
17
+ /**
18
+ * Why Clikgate wouldn't keep this ID as a known customer, or `null` when it's fine.
19
+ *
20
+ * @example
21
+ * customerIdWarning('ada@example.com'); // 'looks_like_email'
22
+ * customerIdWarning('u_10482'); // null
23
+ */
24
+ export declare function customerIdWarning(customerId: string, options?: {
25
+ allow11DigitIds?: boolean;
26
+ }): CustomerIdWarning | null;
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Your customer IDs, in one canonical form: the same form the API stores and checks, so an ID
3
+ * sent from your server, an import and an identity token always match.
4
+ *
5
+ * - canonical form: Unicode NFC, trimmed of Unicode whitespace (and U+FEFF) at both ends, case kept;
6
+ * - warnings (first match wins): `empty`, `too_long` (more than 128 characters), `looks_like_email`,
7
+ * `looks_like_national_id` (exactly 11 digits, unless `allow11DigitIds`), `looks_like_phone`.
8
+ *
9
+ * Use your own stable user ID (for example `u_10482`), never an email, phone number, BVN or NIN.
10
+ */
11
+ /** Unicode White_Space characters plus U+FEFF (the byte-order mark). */
12
+ const TRIM = '\t\n\u000b\u000c\r \u0085\u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\ufeff';
13
+ /** The longest customer ID kept as a known customer, in Unicode code points. */
14
+ export const CUSTOMER_ID_MAX_LENGTH = 128;
15
+ /** The canonical form of a customer ID: NFC, trimmed, case kept. */
16
+ export function canonicalCustomerId(customerId) {
17
+ const s = customerId.normalize('NFC');
18
+ let start = 0;
19
+ let end = s.length;
20
+ while (start < end && TRIM.includes(s[start]))
21
+ start++;
22
+ while (end > start && TRIM.includes(s[end - 1]))
23
+ end--;
24
+ return s.slice(start, end);
25
+ }
26
+ /**
27
+ * Why Clikgate wouldn't keep this ID as a known customer, or `null` when it's fine.
28
+ *
29
+ * @example
30
+ * customerIdWarning('ada@example.com'); // 'looks_like_email'
31
+ * customerIdWarning('u_10482'); // null
32
+ */
33
+ export function customerIdWarning(customerId, options = {}) {
34
+ const cid = canonicalCustomerId(customerId);
35
+ if (cid === '')
36
+ return 'empty';
37
+ if ([...cid].length > CUSTOMER_ID_MAX_LENGTH)
38
+ return 'too_long';
39
+ const at = cid.indexOf('@');
40
+ if (at >= 0 && cid.slice(at + 1).includes('.'))
41
+ return 'looks_like_email';
42
+ if (/^[0-9]{11}$/.test(cid))
43
+ return options.allow11DigitIds ? null : 'looks_like_national_id';
44
+ if (/^\+?[0-9]{10,15}$/.test(cid.replace(/[ -]/g, '')))
45
+ return 'looks_like_phone';
46
+ return null;
47
+ }
@@ -0,0 +1,48 @@
1
+ /** A goal's kind, set in the goal's settings (never in a goal call): `standard` or `payment`. */
2
+ export declare const GoalKind: {
3
+ readonly Standard: "standard";
4
+ readonly Payment: "payment";
5
+ };
6
+ /** A goal's kind, set in the goal's settings (never in a goal call): `standard` or `payment`. */
7
+ export type GoalKind = (typeof GoalKind)[keyof typeof GoalKind];
8
+ /** A goal call's outcome: `counted`, `waiting` (a Payment goal awaiting confirmation), `received` (not counted) or `refused`. */
9
+ export declare const GoalStatus: {
10
+ readonly Counted: "counted";
11
+ readonly Waiting: "waiting";
12
+ readonly Refused: "refused";
13
+ readonly Received: "received";
14
+ };
15
+ /** A goal call's outcome: `counted`, `waiting` (a Payment goal awaiting confirmation), `received` (not counted) or `refused`. */
16
+ export type GoalStatus = (typeof GoalStatus)[keyof typeof GoalStatus];
17
+ /** A payment provider: every gateway in `GET /v1/payment-gateways`, plus `shopify`, `woocommerce` and `custom`. */
18
+ export declare const Provider: {
19
+ readonly Paystack: "paystack";
20
+ readonly Flutterwave: "flutterwave";
21
+ readonly Monnify: "monnify";
22
+ readonly Squad: "squad";
23
+ readonly Opay: "opay";
24
+ readonly Interswitch: "interswitch";
25
+ readonly Remita: "remita";
26
+ readonly Korapay: "korapay";
27
+ readonly Paga: "paga";
28
+ readonly Moniepoint: "moniepoint";
29
+ readonly Hubtel: "hubtel";
30
+ readonly Mpesa: "mpesa";
31
+ readonly Pesapal: "pesapal";
32
+ readonly MtnMomo: "mtn_momo";
33
+ readonly AirtelMoney: "airtel_money";
34
+ readonly Yoco: "yoco";
35
+ readonly Payfast: "payfast";
36
+ readonly PeachPayments: "peach_payments";
37
+ readonly DpoPay: "dpo_pay";
38
+ readonly Stripe: "stripe";
39
+ readonly Paypal: "paypal";
40
+ readonly Adyen: "adyen";
41
+ readonly Square: "square";
42
+ readonly CheckoutCom: "checkout_com";
43
+ readonly Shopify: "shopify";
44
+ readonly Woocommerce: "woocommerce";
45
+ readonly Custom: "custom";
46
+ };
47
+ /** A payment provider: every gateway in `GET /v1/payment-gateways`, plus `shopify`, `woocommerce` and `custom`. */
48
+ export type Provider = (typeof Provider)[keyof typeof Provider];
@@ -0,0 +1,44 @@
1
+ // Generated by server/codegen/generate.mjs from openapi.json (GoalKind, GoalStatus, Provider). Do not edit by hand.
2
+ // Source sha256 86cb28d5c8c70cb6793d1c9145f99790d749cc09b447fa0f702d4c9cbbeeabd8.
3
+ /** A goal's kind, set in the goal's settings (never in a goal call): `standard` or `payment`. */
4
+ export const GoalKind = {
5
+ Standard: 'standard',
6
+ Payment: 'payment',
7
+ };
8
+ /** A goal call's outcome: `counted`, `waiting` (a Payment goal awaiting confirmation), `received` (not counted) or `refused`. */
9
+ export const GoalStatus = {
10
+ Counted: 'counted',
11
+ Waiting: 'waiting',
12
+ Refused: 'refused',
13
+ Received: 'received',
14
+ };
15
+ /** A payment provider: every gateway in `GET /v1/payment-gateways`, plus `shopify`, `woocommerce` and `custom`. */
16
+ export const Provider = {
17
+ Paystack: 'paystack',
18
+ Flutterwave: 'flutterwave',
19
+ Monnify: 'monnify',
20
+ Squad: 'squad',
21
+ Opay: 'opay',
22
+ Interswitch: 'interswitch',
23
+ Remita: 'remita',
24
+ Korapay: 'korapay',
25
+ Paga: 'paga',
26
+ Moniepoint: 'moniepoint',
27
+ Hubtel: 'hubtel',
28
+ Mpesa: 'mpesa',
29
+ Pesapal: 'pesapal',
30
+ MtnMomo: 'mtn_momo',
31
+ AirtelMoney: 'airtel_money',
32
+ Yoco: 'yoco',
33
+ Payfast: 'payfast',
34
+ PeachPayments: 'peach_payments',
35
+ DpoPay: 'dpo_pay',
36
+ Stripe: 'stripe',
37
+ Paypal: 'paypal',
38
+ Adyen: 'adyen',
39
+ Square: 'square',
40
+ CheckoutCom: 'checkout_com',
41
+ Shopify: 'shopify',
42
+ Woocommerce: 'woocommerce',
43
+ Custom: 'custom',
44
+ };
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Typed errors (SPEC section 5). Every error extends {@link ClikgateError}.
3
+ *
4
+ * @example
5
+ * import { Clikgate, RateLimitError, InvalidRequestError } from '@clikgate/node';
6
+ * try {
7
+ * await clikgate.goals.send('account_opened', { reference: 'APP-55231', value: '2000000' });
8
+ * } catch (err) {
9
+ * if (err instanceof RateLimitError) console.log('retry in', err.retryAfter, 's');
10
+ * else if (err instanceof InvalidRequestError) console.log(err.code, err.param);
11
+ * else throw err;
12
+ * }
13
+ */
14
+ /** Error codes with documented meaning (SPEC section 5). Other codes can appear; `code` is a plain string. */
15
+ export type KnownErrorCode = 'invalid_goal_key' | 'invalid_reference' | 'invalid_value' | 'click_id_and_code' | 'batch_too_large' | 'batch_empty' | 'invalid_argument' | 'invalid_click_id' | 'queue_full' | 'client_closed' | 'missing_api_key' | 'invalid_api_key' | 'invalid_option' | 'network_error' | 'timeout' | 'unexpected_status' | 'rate_limit_exceeded' | 'private_mode_field_rejected' | 'private_mode_conflict' | 'link_locked' | 'idempotency_key_reused' | 'idempotency_request_in_progress' | 'goal_archived' | 'goal_not_found' | 'value_required' | 'value_not_allowed' | 'domain_mode_mismatch' | 'https_required' | 'destination_not_allowlisted' | 'test_destination_not_allowed' | 'test_link_limit_reached' | 'plan_limit_reached' | 'plan_upgrade_required' | 'plan_feature_unavailable' | 'feature_disabled' | 'invalid_provider' | 'unknown_provider' | 'code_not_supported' | 'payment_goal_needs_confirmation' | 'unknown_goal' | 'cli_scope' | 'missing_signature' | 'malformed_signature' | 'timestamp_outside_tolerance' | 'no_matching_signature' | 'invalid_payload' | 'server_only' | 'invalid_customer_id' | 'missing_identity_secret' | 'invalid_identity_secrets';
16
+ /** Fields every Clikgate error carries. */
17
+ export interface ClikgateErrorInit {
18
+ message: string;
19
+ code: string;
20
+ httpStatus?: number | null;
21
+ requestId?: string | null;
22
+ param?: string | null;
23
+ type?: string | null;
24
+ raw?: unknown;
25
+ }
26
+ /** Base class of every error the SDK throws. */
27
+ export declare class ClikgateError extends Error {
28
+ /** Stable machine-readable code, e.g. `invalid_value`, `link_locked`, `network_error`. */
29
+ readonly code: string;
30
+ /** HTTP status, or `null` for local, network and timeout errors. */
31
+ readonly httpStatus: number | null;
32
+ /** The request ID (`req_…`) to quote to Clikgate support, when the API answered. */
33
+ readonly requestId: string | null;
34
+ /** The request field the error is about, when there is one. */
35
+ readonly param: string | null;
36
+ /** The envelope `type` (`invalid_request`, `conflict`, …), or `null` for local errors. */
37
+ readonly type: string | null;
38
+ /** The raw `error` object from the API, including extra keys such as `required_plan`. */
39
+ readonly raw: unknown;
40
+ constructor(init: ClikgateErrorInit);
41
+ }
42
+ /** Invalid client options. Thrown by the constructor, never later. */
43
+ export declare class ConfigurationError extends ClikgateError {
44
+ }
45
+ /** 401: the API key is missing, invalid, expired or revoked. */
46
+ export declare class AuthenticationError extends ClikgateError {
47
+ }
48
+ /**
49
+ * 403: missing scope, role, feature or plan (`insufficient_scope`, `plan_limit_reached`, `plan_upgrade_required`,
50
+ * `feature_disabled`, `test_link_limit_reached`, `cli_scope`, …).
51
+ */
52
+ export declare class PermissionError extends ClikgateError {
53
+ /** On `plan_limit_reached` / `plan_upgrade_required`: the lowest plan that allows it. */
54
+ get requiredPlan(): string | null;
55
+ /** On `test_link_limit_reached`: the number of active test links allowed. */
56
+ get limit(): number | null;
57
+ }
58
+ /** 400, 410, 422 and other 4xx (`invalid_value`, `domain_mode_mismatch`, `test_destination_not_allowed`, …); also local validation (`httpStatus` null). */
59
+ export declare class InvalidRequestError extends ClikgateError {
60
+ /** For batch calls: the index of the event that failed local validation. */
61
+ index: number | null;
62
+ /** On `test_destination_not_allowed`: the allowed destination kinds. */
63
+ get allowed(): string[] | null;
64
+ /** On `test_destination_not_allowed`: the docs page explaining test-link destinations. */
65
+ get docUrl(): string | null;
66
+ }
67
+ /** Private mode refused a field (locally, before sending, or by the API). Carries the field **name** only. */
68
+ export declare class PrivateModeFieldRejectedError extends InvalidRequestError {
69
+ /** The refused field name, e.g. `metadata`. Never its value. */
70
+ readonly field: string;
71
+ constructor(init: ClikgateErrorInit & {
72
+ field: string;
73
+ });
74
+ }
75
+ /** 404. */
76
+ export declare class NotFoundError extends ClikgateError {
77
+ }
78
+ /** 409. */
79
+ export declare class ConflictError extends ClikgateError {
80
+ }
81
+ /** 409 `link_locked`: the link is locked; destination, fallback and deep-link changes are refused. */
82
+ export declare class LinkLockedError extends ConflictError {
83
+ }
84
+ /** 409 `idempotency_*`: the key was used with a different request, or the first request is still running. */
85
+ export declare class IdempotencyError extends ClikgateError {
86
+ }
87
+ /** 429. */
88
+ export declare class RateLimitError extends ClikgateError {
89
+ /** Seconds from `Retry-After`, or `null`. */
90
+ readonly retryAfter: number | null;
91
+ constructor(init: ClikgateErrorInit & {
92
+ retryAfter?: number | null;
93
+ });
94
+ }
95
+ /** 5xx, or an unexpected status (redirects are never followed). */
96
+ export declare class ServerError extends ClikgateError {
97
+ /** Seconds from `Retry-After` on a 503, or `null`. */
98
+ readonly retryAfter: number | null;
99
+ constructor(init: ClikgateErrorInit & {
100
+ retryAfter?: number | null;
101
+ });
102
+ }
103
+ /** The connection failed (DNS, refused, reset, TLS). */
104
+ export declare class NetworkError extends ClikgateError {
105
+ }
106
+ /** The per-attempt timeout elapsed. */
107
+ export declare class TimeoutError extends ClikgateError {
108
+ }
109
+ /** A webhook signature didn't verify. `code`: `missing_signature`, `malformed_signature`, `timestamp_outside_tolerance`, `no_matching_signature` or `invalid_payload`. */
110
+ export declare class SignatureVerificationError extends ClikgateError {
111
+ }
112
+ /**
113
+ * `createIdentityToken()` ran in a browser or a React Native app. Identity tokens are signed with
114
+ * your identity secret, which must stay on your server. `code`: `server_only`.
115
+ */
116
+ export declare class ClikgateServerOnlyError extends ClikgateError {
117
+ }
@@ -0,0 +1,234 @@
1
+ /**
2
+ * Typed errors (SPEC section 5). Every error extends {@link ClikgateError}.
3
+ *
4
+ * @example
5
+ * import { Clikgate, RateLimitError, InvalidRequestError } from '@clikgate/node';
6
+ * try {
7
+ * await clikgate.goals.send('account_opened', { reference: 'APP-55231', value: '2000000' });
8
+ * } catch (err) {
9
+ * if (err instanceof RateLimitError) console.log('retry in', err.retryAfter, 's');
10
+ * else if (err instanceof InvalidRequestError) console.log(err.code, err.param);
11
+ * else throw err;
12
+ * }
13
+ */
14
+ /** Base class of every error the SDK throws. */
15
+ export class ClikgateError extends Error {
16
+ /** Stable machine-readable code, e.g. `invalid_value`, `link_locked`, `network_error`. */
17
+ code;
18
+ /** HTTP status, or `null` for local, network and timeout errors. */
19
+ httpStatus;
20
+ /** The request ID (`req_…`) to quote to Clikgate support, when the API answered. */
21
+ requestId;
22
+ /** The request field the error is about, when there is one. */
23
+ param;
24
+ /** The envelope `type` (`invalid_request`, `conflict`, …), or `null` for local errors. */
25
+ type;
26
+ /** The raw `error` object from the API, including extra keys such as `required_plan`. */
27
+ raw;
28
+ constructor(init) {
29
+ super(init.message);
30
+ this.name = new.target.name;
31
+ this.code = init.code;
32
+ this.httpStatus = init.httpStatus ?? null;
33
+ this.requestId = init.requestId ?? null;
34
+ this.param = init.param ?? null;
35
+ this.type = init.type ?? null;
36
+ this.raw = init.raw ?? null;
37
+ Object.setPrototypeOf(this, new.target.prototype);
38
+ }
39
+ }
40
+ /** Invalid client options. Thrown by the constructor, never later. */
41
+ export class ConfigurationError extends ClikgateError {
42
+ }
43
+ /** 401: the API key is missing, invalid, expired or revoked. */
44
+ export class AuthenticationError extends ClikgateError {
45
+ }
46
+ const rawField = (raw, key) => (raw && typeof raw === 'object' ? raw[key] : undefined);
47
+ /**
48
+ * 403: missing scope, role, feature or plan (`insufficient_scope`, `plan_limit_reached`, `plan_upgrade_required`,
49
+ * `feature_disabled`, `test_link_limit_reached`, `cli_scope`, …).
50
+ */
51
+ export class PermissionError extends ClikgateError {
52
+ /** On `plan_limit_reached` / `plan_upgrade_required`: the lowest plan that allows it. */
53
+ get requiredPlan() {
54
+ const v = rawField(this.raw, 'required_plan');
55
+ return typeof v === 'string' ? v : null;
56
+ }
57
+ /** On `test_link_limit_reached`: the number of active test links allowed. */
58
+ get limit() {
59
+ const v = rawField(this.raw, 'limit');
60
+ return typeof v === 'number' ? v : null;
61
+ }
62
+ }
63
+ /** 400, 410, 422 and other 4xx (`invalid_value`, `domain_mode_mismatch`, `test_destination_not_allowed`, …); also local validation (`httpStatus` null). */
64
+ export class InvalidRequestError extends ClikgateError {
65
+ /** For batch calls: the index of the event that failed local validation. */
66
+ index = null;
67
+ /** On `test_destination_not_allowed`: the allowed destination kinds. */
68
+ get allowed() {
69
+ const v = rawField(this.raw, 'allowed');
70
+ return Array.isArray(v) ? v.map(String) : null;
71
+ }
72
+ /** On `test_destination_not_allowed`: the docs page explaining test-link destinations. */
73
+ get docUrl() {
74
+ const v = rawField(this.raw, 'doc_url');
75
+ return typeof v === 'string' ? v : null;
76
+ }
77
+ }
78
+ /** Private mode refused a field (locally, before sending, or by the API). Carries the field **name** only. */
79
+ export class PrivateModeFieldRejectedError extends InvalidRequestError {
80
+ /** The refused field name, e.g. `metadata`. Never its value. */
81
+ field;
82
+ constructor(init) {
83
+ super(init);
84
+ this.field = init.field;
85
+ }
86
+ }
87
+ /** 404. */
88
+ export class NotFoundError extends ClikgateError {
89
+ }
90
+ /** 409. */
91
+ export class ConflictError extends ClikgateError {
92
+ }
93
+ /** 409 `link_locked`: the link is locked; destination, fallback and deep-link changes are refused. */
94
+ export class LinkLockedError extends ConflictError {
95
+ }
96
+ /** 409 `idempotency_*`: the key was used with a different request, or the first request is still running. */
97
+ export class IdempotencyError extends ClikgateError {
98
+ }
99
+ /** 429. */
100
+ export class RateLimitError extends ClikgateError {
101
+ /** Seconds from `Retry-After`, or `null`. */
102
+ retryAfter;
103
+ constructor(init) {
104
+ super(init);
105
+ this.retryAfter = init.retryAfter ?? null;
106
+ }
107
+ }
108
+ /** 5xx, or an unexpected status (redirects are never followed). */
109
+ export class ServerError extends ClikgateError {
110
+ /** Seconds from `Retry-After` on a 503, or `null`. */
111
+ retryAfter;
112
+ constructor(init) {
113
+ super(init);
114
+ this.retryAfter = init.retryAfter ?? null;
115
+ }
116
+ }
117
+ /** The connection failed (DNS, refused, reset, TLS). */
118
+ export class NetworkError extends ClikgateError {
119
+ }
120
+ /** The per-attempt timeout elapsed. */
121
+ export class TimeoutError extends ClikgateError {
122
+ }
123
+ /** A webhook signature didn't verify. `code`: `missing_signature`, `malformed_signature`, `timestamp_outside_tolerance`, `no_matching_signature` or `invalid_payload`. */
124
+ export class SignatureVerificationError extends ClikgateError {
125
+ }
126
+ /**
127
+ * `createIdentityToken()` ran in a browser or a React Native app. Identity tokens are signed with
128
+ * your identity secret, which must stay on your server. `code`: `server_only`.
129
+ */
130
+ export class ClikgateServerOnlyError extends ClikgateError {
131
+ }
132
+ const SNIPPET = 200;
133
+ // eslint-disable-next-line no-control-regex
134
+ const CONTROL = /[\u0000-\u001f\u007f]/g;
135
+ const stripControl = (t) => t.replace(CONTROL, ' ');
136
+ function retryAfterSeconds(headers, nowMs) {
137
+ const v = headers['retry-after'];
138
+ if (v === undefined)
139
+ return null;
140
+ const s = v.trim();
141
+ if (/^\d+$/.test(s))
142
+ return Number(s);
143
+ const t = Date.parse(s);
144
+ if (Number.isNaN(t))
145
+ return null;
146
+ return Math.max(0, Math.ceil((t - nowMs) / 1000));
147
+ }
148
+ /** @internal Parse `Retry-After` in milliseconds, or null when absent or unparseable. */
149
+ export function retryAfterMs(headers, nowMs) {
150
+ const v = headers['retry-after'];
151
+ if (v === undefined)
152
+ return null;
153
+ const s = v.trim();
154
+ if (/^\d+$/.test(s))
155
+ return Number(s) * 1000;
156
+ const t = Date.parse(s);
157
+ if (Number.isNaN(t))
158
+ return null;
159
+ return Math.max(0, t - nowMs);
160
+ }
161
+ const str = (v) => (typeof v === 'string' ? v : null);
162
+ /** @internal Map an HTTP response to a typed error (SPEC 5, rules 3-13). */
163
+ export function errorFromResponse(status, headers, body, nowMs) {
164
+ const text = new TextDecoder().decode(body);
165
+ let envelope = null;
166
+ let refusal = null;
167
+ try {
168
+ const parsed = JSON.parse(text);
169
+ if (parsed && typeof parsed === 'object' && 'error' in parsed) {
170
+ const e = parsed.error;
171
+ if (e && typeof e === 'object')
172
+ envelope = e;
173
+ }
174
+ else if (isRefusalBody(parsed)) {
175
+ refusal = parsed;
176
+ }
177
+ }
178
+ catch {
179
+ envelope = null;
180
+ }
181
+ const requestId = str(envelope?.request_id) ?? headers['x-request-id'] ?? null;
182
+ const code = str(envelope?.code) ?? str(refusal?.reason) ?? (status >= 300 && status < 400 ? 'unexpected_status' : `http_${status}`);
183
+ const message = str(envelope?.message) ?? `HTTP ${status}${text ? `: ${stripControl(text.slice(0, SNIPPET))}` : ''}`;
184
+ const init = {
185
+ message,
186
+ code: status >= 300 && status < 400 ? 'unexpected_status' : code,
187
+ httpStatus: status,
188
+ requestId,
189
+ param: str(envelope?.param),
190
+ type: str(envelope?.type),
191
+ raw: envelope ?? refusal,
192
+ };
193
+ const retryAfter = retryAfterSeconds(headers, nowMs);
194
+ if (status === 429)
195
+ return new RateLimitError({ ...init, code: str(envelope?.code) ?? 'rate_limit_exceeded', retryAfter });
196
+ if (status >= 500)
197
+ return new ServerError({ ...init, retryAfter });
198
+ if (init.code === 'private_mode_field_rejected')
199
+ return new PrivateModeFieldRejectedError({ ...init, field: init.param ?? 'unknown' });
200
+ if (status === 401)
201
+ return new AuthenticationError(init);
202
+ if (status === 403)
203
+ return new PermissionError(init);
204
+ if (status === 404)
205
+ return new NotFoundError(init);
206
+ if (status === 409 && (init.type === 'idempotency' || init.code.startsWith('idempotency_')))
207
+ return new IdempotencyError(init);
208
+ if (status === 409 && init.code === 'link_locked')
209
+ return new LinkLockedError(init);
210
+ if (status === 409)
211
+ return new ConflictError(init);
212
+ if (status >= 400)
213
+ return new InvalidRequestError(init);
214
+ return new ServerError({ ...init, retryAfter: null });
215
+ }
216
+ /**
217
+ * A goal refusal answered as a result body instead of an error envelope (`422 {status: "refused", reason:
218
+ * "unknown_goal", ...}`): the reason is the error code.
219
+ */
220
+ function isRefusalBody(v) {
221
+ if (!v || typeof v !== 'object' || Array.isArray(v))
222
+ return false;
223
+ const o = v;
224
+ return o.status === 'refused' && typeof o.reason === 'string' && o.reason !== '';
225
+ }
226
+ /** @internal Map a batch item's `{status, error}` to a typed error. */
227
+ export function errorFromBatchItem(status, error) {
228
+ const body = new TextEncoder().encode(JSON.stringify({ error: error ?? {} }));
229
+ return errorFromResponse(status, {}, body, Date.now());
230
+ }
231
+ /** @internal A local validation error (no HTTP request was made). */
232
+ export function localError(code, message, param = null) {
233
+ return new InvalidRequestError({ message, code, param, httpStatus: null });
234
+ }
@@ -0,0 +1,49 @@
1
+ /**
2
+ * Express / Connect middleware: keeps the click ID (SPEC section 17).
3
+ *
4
+ * @example
5
+ * import express from 'express';
6
+ * import { Clikgate } from '@clikgate/node';
7
+ * import { clikgateMiddleware } from '@clikgate/node/express';
8
+ *
9
+ * const clikgate = new Clikgate();
10
+ * const app = express();
11
+ * app.use(clikgateMiddleware(clikgate));
12
+ * app.post('/signup', (req, res) => {
13
+ * const clickId = req.clikgate.clickId; // save it with the application
14
+ * });
15
+ *
16
+ * @packageDocumentation
17
+ */
18
+ import type { IncomingMessage, ServerResponse } from 'node:http';
19
+ import { type PersistOptions } from './click-ids.js';
20
+ import type { Clikgate } from './client.js';
21
+ /** What the middleware puts on the request. */
22
+ export interface ClikgateRequestContext {
23
+ /** The click ID from the query, the `_cg_<param>` cookie or the `Clikgate-Click-Id` header; `null` when there is none. */
24
+ clickId: string | null;
25
+ }
26
+ declare global {
27
+ namespace Express {
28
+ interface Request {
29
+ /** Set by `clikgateMiddleware` from `@clikgate/node/express`. */
30
+ clikgate: ClikgateRequestContext;
31
+ }
32
+ }
33
+ }
34
+ /** Middleware options. */
35
+ export interface ClikgateMiddlewareOptions extends PersistOptions {
36
+ /** Write the cookie when the click ID arrives in the query string (default true; last click wins, like the web script). */
37
+ persist?: boolean;
38
+ }
39
+ type Next = (err?: unknown) => void;
40
+ /**
41
+ * Express/Connect middleware: sets `req.clikgate.clickId`, and stores a click ID that arrives in
42
+ * the query string in the first-party `_cg_<param>` cookie. Pass the client so the organisation's
43
+ * click-ID parameter is used; without it, `cgid`.
44
+ *
45
+ * @example
46
+ * app.use(clikgateMiddleware(clikgate, { days: 30 }));
47
+ */
48
+ export declare function clikgateMiddleware(client?: Clikgate | null, options?: ClikgateMiddlewareOptions): (req: IncomingMessage, res: ServerResponse, next: Next) => void;
49
+ export {};