@clikgate/node 0.0.0-stage → 2.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.
Files changed (111) hide show
  1. package/CHANGELOG.md +126 -0
  2. package/LICENSE +21 -0
  3. package/README.md +300 -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 +175 -0
  10. package/dist/cjs/client.js +266 -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/enums.d.ts +48 -0
  16. package/dist/cjs/enums.js +47 -0
  17. package/dist/cjs/errors.d.ts +117 -0
  18. package/dist/cjs/errors.js +257 -0
  19. package/dist/cjs/express.d.ts +49 -0
  20. package/dist/cjs/express.js +44 -0
  21. package/dist/cjs/fastify.d.ts +47 -0
  22. package/dist/cjs/fastify.js +35 -0
  23. package/dist/cjs/generated/index.d.ts +17534 -0
  24. package/dist/cjs/generated/index.js +8816 -0
  25. package/dist/cjs/goals.d.ts +116 -0
  26. package/dist/cjs/goals.js +381 -0
  27. package/dist/cjs/guard.d.ts +17 -0
  28. package/dist/cjs/guard.js +40 -0
  29. package/dist/cjs/http.d.ts +16 -0
  30. package/dist/cjs/http.js +148 -0
  31. package/dist/cjs/identity.d.ts +32 -0
  32. package/dist/cjs/identity.js +99 -0
  33. package/dist/cjs/index.d.ts +32 -0
  34. package/dist/cjs/index.js +64 -0
  35. package/dist/cjs/logger.d.ts +9 -0
  36. package/dist/cjs/logger.js +8 -0
  37. package/dist/cjs/money.d.ts +16 -0
  38. package/dist/cjs/money.js +51 -0
  39. package/dist/cjs/next.d.ts +81 -0
  40. package/dist/cjs/next.js +103 -0
  41. package/dist/cjs/package.json +1 -0
  42. package/dist/cjs/payments.d.ts +174 -0
  43. package/dist/cjs/payments.js +485 -0
  44. package/dist/cjs/resources.d.ts +109 -0
  45. package/dist/cjs/resources.js +189 -0
  46. package/dist/cjs/shutdown.d.ts +2 -0
  47. package/dist/cjs/shutdown.js +51 -0
  48. package/dist/cjs/transport.d.ts +14 -0
  49. package/dist/cjs/transport.js +204 -0
  50. package/dist/cjs/types.d.ts +218 -0
  51. package/dist/cjs/types.js +2 -0
  52. package/dist/cjs/user-agent.d.ts +1 -0
  53. package/dist/cjs/user-agent.js +53 -0
  54. package/dist/cjs/version.d.ts +2 -0
  55. package/dist/cjs/version.js +5 -0
  56. package/dist/cjs/webhooks.d.ts +36 -0
  57. package/dist/cjs/webhooks.js +108 -0
  58. package/dist/esm/ads-hashing.d.ts +37 -0
  59. package/dist/esm/ads-hashing.js +62 -0
  60. package/dist/esm/click-ids.d.ts +184 -0
  61. package/dist/esm/click-ids.js +526 -0
  62. package/dist/esm/client.d.ts +175 -0
  63. package/dist/esm/client.js +262 -0
  64. package/dist/esm/config.d.ts +12 -0
  65. package/dist/esm/config.js +82 -0
  66. package/dist/esm/core.d.ts +15 -0
  67. package/dist/esm/core.js +96 -0
  68. package/dist/esm/enums.d.ts +48 -0
  69. package/dist/esm/enums.js +44 -0
  70. package/dist/esm/errors.d.ts +117 -0
  71. package/dist/esm/errors.js +234 -0
  72. package/dist/esm/express.d.ts +49 -0
  73. package/dist/esm/express.js +40 -0
  74. package/dist/esm/fastify.d.ts +47 -0
  75. package/dist/esm/fastify.js +32 -0
  76. package/dist/esm/generated/index.d.ts +17534 -0
  77. package/dist/esm/generated/index.js +8754 -0
  78. package/dist/esm/goals.d.ts +116 -0
  79. package/dist/esm/goals.js +371 -0
  80. package/dist/esm/guard.d.ts +17 -0
  81. package/dist/esm/guard.js +36 -0
  82. package/dist/esm/http.d.ts +16 -0
  83. package/dist/esm/http.js +138 -0
  84. package/dist/esm/identity.d.ts +32 -0
  85. package/dist/esm/identity.js +92 -0
  86. package/dist/esm/index.d.ts +32 -0
  87. package/dist/esm/index.js +21 -0
  88. package/dist/esm/logger.d.ts +9 -0
  89. package/dist/esm/logger.js +5 -0
  90. package/dist/esm/money.d.ts +16 -0
  91. package/dist/esm/money.js +48 -0
  92. package/dist/esm/next.d.ts +81 -0
  93. package/dist/esm/next.js +96 -0
  94. package/dist/esm/package.json +1 -0
  95. package/dist/esm/payments.d.ts +174 -0
  96. package/dist/esm/payments.js +476 -0
  97. package/dist/esm/resources.d.ts +109 -0
  98. package/dist/esm/resources.js +183 -0
  99. package/dist/esm/shutdown.d.ts +2 -0
  100. package/dist/esm/shutdown.js +47 -0
  101. package/dist/esm/transport.d.ts +14 -0
  102. package/dist/esm/transport.js +166 -0
  103. package/dist/esm/types.d.ts +218 -0
  104. package/dist/esm/types.js +1 -0
  105. package/dist/esm/user-agent.d.ts +1 -0
  106. package/dist/esm/user-agent.js +16 -0
  107. package/dist/esm/version.d.ts +2 -0
  108. package/dist/esm/version.js +2 -0
  109. package/dist/esm/webhooks.d.ts +36 -0
  110. package/dist/esm/webhooks.js +105 -0
  111. package/package.json +128 -4
@@ -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 d39834b71974ddd58b7ba177f00c450738a641f18add17189a2f707bf724c796.
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' | '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 {};
@@ -0,0 +1,40 @@
1
+ import { clickIds as defaultClickIds } from './click-ids.js';
2
+ /** @internal Shared by the add-ons: read, expose and (optionally) persist the click ID. */
3
+ export function captureClickId(helpers, req, res, options) {
4
+ const clickId = helpers.fromRequest(req);
5
+ if (clickId && options.persist !== false) {
6
+ const url = new URL(req.originalUrl ?? req.url ?? '/', 'http://localhost');
7
+ if (url.searchParams.getAll(helpers.paramName).includes(clickId)) {
8
+ const { persist: _p, ...cookie } = options;
9
+ helpers.persist(res, clickId, cookie);
10
+ }
11
+ }
12
+ return clickId;
13
+ }
14
+ /**
15
+ * Express/Connect middleware: sets `req.clikgate.clickId`, and stores a click ID that arrives in
16
+ * the query string in the first-party `_cg_<param>` cookie. Pass the client so the organisation's
17
+ * click-ID parameter is used; without it, `cgid`.
18
+ *
19
+ * @example
20
+ * app.use(clikgateMiddleware(clikgate, { days: 30 }));
21
+ */
22
+ export function clikgateMiddleware(client, options = {}) {
23
+ const helpers = client ? client.clickIds : defaultClickIds;
24
+ let warmed = false;
25
+ return (req, res, next) => {
26
+ try {
27
+ if (client && !warmed) {
28
+ warmed = true;
29
+ // learn the organisation's click_id_param in the background; never blocks a request
30
+ void client.config().catch(() => undefined);
31
+ }
32
+ const clickId = captureClickId(helpers, req, res, options);
33
+ req.clikgate = { clickId };
34
+ next();
35
+ }
36
+ catch (err) {
37
+ next(err);
38
+ }
39
+ };
40
+ }
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Fastify plugin: keeps the click ID (SPEC section 17). Works with Fastify 5 (Node 20+).
3
+ *
4
+ * @example
5
+ * import Fastify from 'fastify';
6
+ * import { Clikgate } from '@clikgate/node';
7
+ * import { clikgatePlugin } from '@clikgate/node/fastify';
8
+ *
9
+ * const clikgate = new Clikgate();
10
+ * const app = Fastify();
11
+ * await app.register(clikgatePlugin, { client: clikgate });
12
+ * app.post('/signup', async (request) => {
13
+ * const clickId = request.clikgate.clickId;
14
+ * });
15
+ *
16
+ * @packageDocumentation
17
+ */
18
+ import type { FastifyPluginAsync } from 'fastify';
19
+ import { type PersistOptions } from './click-ids.js';
20
+ import type { Clikgate } from './client.js';
21
+ /** What the plugin puts on the request. */
22
+ export interface ClikgateRequestContext {
23
+ /** The click ID, or `null`. */
24
+ clickId: string | null;
25
+ }
26
+ declare module 'fastify' {
27
+ interface FastifyRequest {
28
+ /** Set by `clikgatePlugin` from `@clikgate/node/fastify`. */
29
+ clikgate: ClikgateRequestContext;
30
+ }
31
+ }
32
+ /** Plugin options. */
33
+ export interface ClikgatePluginOptions extends PersistOptions {
34
+ /** The client (for the organisation's click-ID parameter). Optional: without it, `cgid`. */
35
+ client?: Clikgate;
36
+ /** Write the cookie when the click ID arrives in the query string (default true). */
37
+ persist?: boolean;
38
+ }
39
+ /**
40
+ * Fastify plugin: sets `request.clikgate.clickId` and keeps a click ID from the query string in the
41
+ * `_cg_<param>` cookie.
42
+ *
43
+ * @example
44
+ * await app.register(clikgatePlugin, { client: clikgate, days: 30 });
45
+ */
46
+ export declare const clikgatePlugin: FastifyPluginAsync<ClikgatePluginOptions>;
47
+ export default clikgatePlugin;
@@ -0,0 +1,32 @@
1
+ import { clickIds as defaultClickIds } from './click-ids.js';
2
+ const plugin = async (fastify, options) => {
3
+ const { client, persist, ...cookie } = options;
4
+ const helpers = client ? client.clickIds : defaultClickIds;
5
+ if (client)
6
+ void client.config().catch(() => undefined);
7
+ // v5: reference-type decorators must start as null and be set per request
8
+ fastify.decorateRequest('clikgate', null);
9
+ fastify.addHook('onRequest', async (request, reply) => {
10
+ const clickId = helpers.fromRequest({ url: request.url, headers: request.headers });
11
+ request.clikgate = { clickId };
12
+ if (clickId && persist !== false) {
13
+ const url = new URL(request.url, 'http://localhost');
14
+ if (url.searchParams.getAll(helpers.paramName).includes(clickId))
15
+ helpers.persist(reply, clickId, cookie);
16
+ }
17
+ });
18
+ };
19
+ // What fastify-plugin does, without the dependency: share decorators and hooks with the parent scope.
20
+ const meta = plugin;
21
+ meta[Symbol.for('skip-override')] = true;
22
+ meta[Symbol.for('fastify.display-name')] = '@clikgate/node/fastify';
23
+ meta[Symbol.for('plugin-meta')] = { name: '@clikgate/node/fastify', fastify: '>=5' };
24
+ /**
25
+ * Fastify plugin: sets `request.clikgate.clickId` and keeps a click ID from the query string in the
26
+ * `_cg_<param>` cookie.
27
+ *
28
+ * @example
29
+ * await app.register(clikgatePlugin, { client: clikgate, days: 30 });
30
+ */
31
+ export const clikgatePlugin = plugin;
32
+ export default clikgatePlugin;