@loyaltte/node 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +238 -2
- package/dist/cjs/client.d.ts +105 -0
- package/dist/cjs/client.js +278 -0
- package/dist/cjs/errors.d.ts +61 -0
- package/dist/cjs/errors.js +96 -0
- package/dist/cjs/identity.d.ts +23 -0
- package/dist/cjs/identity.js +27 -0
- package/dist/cjs/index.d.ts +11 -0
- package/dist/cjs/index.js +27 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/transport.d.ts +50 -0
- package/dist/cjs/transport.js +212 -0
- package/dist/cjs/types.d.ts +195 -0
- package/dist/cjs/types.js +3 -0
- package/dist/cjs/version.d.ts +2 -0
- package/dist/cjs/version.js +5 -0
- package/dist/cjs/webhooks.d.ts +27 -0
- package/dist/cjs/webhooks.js +71 -0
- package/dist/esm/client.d.ts +105 -0
- package/dist/esm/client.js +273 -0
- package/dist/esm/errors.d.ts +61 -0
- package/dist/esm/errors.js +81 -0
- package/dist/esm/identity.d.ts +23 -0
- package/dist/esm/identity.js +24 -0
- package/dist/esm/index.d.ts +11 -0
- package/dist/esm/index.js +5 -0
- package/dist/esm/package.json +1 -0
- package/dist/esm/transport.d.ts +50 -0
- package/dist/esm/transport.js +206 -0
- package/dist/esm/types.d.ts +195 -0
- package/dist/esm/types.js +2 -0
- package/dist/esm/version.d.ts +2 -0
- package/dist/esm/version.js +2 -0
- package/dist/esm/webhooks.d.ts +27 -0
- package/dist/esm/webhooks.js +66 -0
- package/package.json +57 -3
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/** What every error from the SDK carries. `status` is null for errors that never got an answer. */
|
|
2
|
+
export interface LoyaltteErrorInit {
|
|
3
|
+
message: string;
|
|
4
|
+
status?: number | null;
|
|
5
|
+
code?: string;
|
|
6
|
+
fields?: Record<string, unknown> | null;
|
|
7
|
+
requestId?: string | null;
|
|
8
|
+
retryAfter?: number | null;
|
|
9
|
+
cause?: unknown;
|
|
10
|
+
}
|
|
11
|
+
/** The base of every error this SDK throws. Messages never contain your secret key. */
|
|
12
|
+
export declare class LoyaltteError extends Error {
|
|
13
|
+
/** The HTTP status; null for a local refusal or when there was no answer. */
|
|
14
|
+
readonly status: number | null;
|
|
15
|
+
/** The API's error code (`NOT_FOUND`, `VALIDATION_ERROR`, ...) or the SDK's own for a local refusal. */
|
|
16
|
+
readonly code: string;
|
|
17
|
+
/** Per-field detail the API sent, e.g. `{ scope: "bills:write" }` on a 403. */
|
|
18
|
+
readonly fields: Record<string, unknown> | null;
|
|
19
|
+
/** The id to quote to support (the answer's `requestId`, else its `X-Request-Id` header). */
|
|
20
|
+
readonly requestId: string | null;
|
|
21
|
+
/** Seconds the server asked you to wait (`Retry-After`), when it did. */
|
|
22
|
+
readonly retryAfter: number | null;
|
|
23
|
+
/**
|
|
24
|
+
* On a failed `bills.create` or `returns.create`: the Idempotency-Key the call used. The bill may have been
|
|
25
|
+
* recorded before the reply was lost; resend with THIS key (`{ idempotencyKey: error.idempotencyKey }`) to stay safe.
|
|
26
|
+
*/
|
|
27
|
+
idempotencyKey: string | null;
|
|
28
|
+
constructor(init: LoyaltteErrorInit);
|
|
29
|
+
}
|
|
30
|
+
/** 401: no key, or the key is revoked, expired or mistyped. */
|
|
31
|
+
export declare class AuthenticationError extends LoyaltteError {
|
|
32
|
+
}
|
|
33
|
+
/** 403: the key lacks a permission (`fields.scope` names it), or the feature isn't in the plan. */
|
|
34
|
+
export declare class PermissionError extends LoyaltteError {
|
|
35
|
+
}
|
|
36
|
+
/** 404: not found, or not in this key's account. */
|
|
37
|
+
export declare class NotFoundError extends LoyaltteError {
|
|
38
|
+
}
|
|
39
|
+
/** 409: an Idempotency-Key or a bill/return number used for a different request, or a state conflict. */
|
|
40
|
+
export declare class ConflictError extends LoyaltteError {
|
|
41
|
+
}
|
|
42
|
+
/** 400 or 422 from the API, or an argument the SDK refused before sending (`status` null, code `INVALID_ARGUMENT`). */
|
|
43
|
+
export declare class ValidationError extends LoyaltteError {
|
|
44
|
+
}
|
|
45
|
+
/** 429, once the retries are used up. `retryAfter` is the wait the server asked for. */
|
|
46
|
+
export declare class RateLimitError extends LoyaltteError {
|
|
47
|
+
}
|
|
48
|
+
/** Any other status (5xx, 413, 408, ...) once the retries are used up, or an answer that isn't JSON. */
|
|
49
|
+
export declare class ApiError extends LoyaltteError {
|
|
50
|
+
}
|
|
51
|
+
/** No answer: no connection, DNS failure, reset, timeout. `status` is null. */
|
|
52
|
+
export declare class ConnectionError extends LoyaltteError {
|
|
53
|
+
}
|
|
54
|
+
/** `Loyaltte.webhooks.constructEvent` could not verify the signature. */
|
|
55
|
+
export declare class WebhookSignatureError extends LoyaltteError {
|
|
56
|
+
constructor(message?: string);
|
|
57
|
+
}
|
|
58
|
+
/** A refusal of an argument, before anything is sent. */
|
|
59
|
+
export declare function invalidArgument(message: string, fields?: Record<string, unknown>): ValidationError;
|
|
60
|
+
/** The typed error for an HTTP status (the mapping in contract/rules/server.json). */
|
|
61
|
+
export declare function errorForStatus(status: number): typeof LoyaltteError;
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.WebhookSignatureError = exports.ConnectionError = exports.ApiError = exports.RateLimitError = exports.ValidationError = exports.ConflictError = exports.NotFoundError = exports.PermissionError = exports.AuthenticationError = exports.LoyaltteError = void 0;
|
|
4
|
+
exports.invalidArgument = invalidArgument;
|
|
5
|
+
exports.errorForStatus = errorForStatus;
|
|
6
|
+
/** The base of every error this SDK throws. Messages never contain your secret key. */
|
|
7
|
+
class LoyaltteError extends Error {
|
|
8
|
+
/** The HTTP status; null for a local refusal or when there was no answer. */
|
|
9
|
+
status;
|
|
10
|
+
/** The API's error code (`NOT_FOUND`, `VALIDATION_ERROR`, ...) or the SDK's own for a local refusal. */
|
|
11
|
+
code;
|
|
12
|
+
/** Per-field detail the API sent, e.g. `{ scope: "bills:write" }` on a 403. */
|
|
13
|
+
fields;
|
|
14
|
+
/** The id to quote to support (the answer's `requestId`, else its `X-Request-Id` header). */
|
|
15
|
+
requestId;
|
|
16
|
+
/** Seconds the server asked you to wait (`Retry-After`), when it did. */
|
|
17
|
+
retryAfter;
|
|
18
|
+
/**
|
|
19
|
+
* On a failed `bills.create` or `returns.create`: the Idempotency-Key the call used. The bill may have been
|
|
20
|
+
* recorded before the reply was lost; resend with THIS key (`{ idempotencyKey: error.idempotencyKey }`) to stay safe.
|
|
21
|
+
*/
|
|
22
|
+
idempotencyKey = null;
|
|
23
|
+
constructor(init) {
|
|
24
|
+
super(init.message, init.cause === undefined ? undefined : { cause: init.cause });
|
|
25
|
+
this.name = new.target.name;
|
|
26
|
+
this.status = init.status ?? null;
|
|
27
|
+
this.code = init.code ?? "ERROR";
|
|
28
|
+
this.fields = init.fields ?? null;
|
|
29
|
+
this.requestId = init.requestId ?? null;
|
|
30
|
+
this.retryAfter = init.retryAfter ?? null;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
exports.LoyaltteError = LoyaltteError;
|
|
34
|
+
/** 401: no key, or the key is revoked, expired or mistyped. */
|
|
35
|
+
class AuthenticationError extends LoyaltteError {
|
|
36
|
+
}
|
|
37
|
+
exports.AuthenticationError = AuthenticationError;
|
|
38
|
+
/** 403: the key lacks a permission (`fields.scope` names it), or the feature isn't in the plan. */
|
|
39
|
+
class PermissionError extends LoyaltteError {
|
|
40
|
+
}
|
|
41
|
+
exports.PermissionError = PermissionError;
|
|
42
|
+
/** 404: not found, or not in this key's account. */
|
|
43
|
+
class NotFoundError extends LoyaltteError {
|
|
44
|
+
}
|
|
45
|
+
exports.NotFoundError = NotFoundError;
|
|
46
|
+
/** 409: an Idempotency-Key or a bill/return number used for a different request, or a state conflict. */
|
|
47
|
+
class ConflictError extends LoyaltteError {
|
|
48
|
+
}
|
|
49
|
+
exports.ConflictError = ConflictError;
|
|
50
|
+
/** 400 or 422 from the API, or an argument the SDK refused before sending (`status` null, code `INVALID_ARGUMENT`). */
|
|
51
|
+
class ValidationError extends LoyaltteError {
|
|
52
|
+
}
|
|
53
|
+
exports.ValidationError = ValidationError;
|
|
54
|
+
/** 429, once the retries are used up. `retryAfter` is the wait the server asked for. */
|
|
55
|
+
class RateLimitError extends LoyaltteError {
|
|
56
|
+
}
|
|
57
|
+
exports.RateLimitError = RateLimitError;
|
|
58
|
+
/** Any other status (5xx, 413, 408, ...) once the retries are used up, or an answer that isn't JSON. */
|
|
59
|
+
class ApiError extends LoyaltteError {
|
|
60
|
+
}
|
|
61
|
+
exports.ApiError = ApiError;
|
|
62
|
+
/** No answer: no connection, DNS failure, reset, timeout. `status` is null. */
|
|
63
|
+
class ConnectionError extends LoyaltteError {
|
|
64
|
+
}
|
|
65
|
+
exports.ConnectionError = ConnectionError;
|
|
66
|
+
/** `Loyaltte.webhooks.constructEvent` could not verify the signature. */
|
|
67
|
+
class WebhookSignatureError extends LoyaltteError {
|
|
68
|
+
constructor(message = "The webhook signature could not be verified.") {
|
|
69
|
+
super({ message, code: "WEBHOOK_SIGNATURE_INVALID" });
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
exports.WebhookSignatureError = WebhookSignatureError;
|
|
73
|
+
/** A refusal of an argument, before anything is sent. */
|
|
74
|
+
function invalidArgument(message, fields) {
|
|
75
|
+
return new ValidationError({ message, code: "INVALID_ARGUMENT", fields: fields ?? null });
|
|
76
|
+
}
|
|
77
|
+
/** The typed error for an HTTP status (the mapping in contract/rules/server.json). */
|
|
78
|
+
function errorForStatus(status) {
|
|
79
|
+
switch (status) {
|
|
80
|
+
case 401:
|
|
81
|
+
return AuthenticationError;
|
|
82
|
+
case 403:
|
|
83
|
+
return PermissionError;
|
|
84
|
+
case 404:
|
|
85
|
+
return NotFoundError;
|
|
86
|
+
case 409:
|
|
87
|
+
return ConflictError;
|
|
88
|
+
case 400:
|
|
89
|
+
case 422:
|
|
90
|
+
return ValidationError;
|
|
91
|
+
case 429:
|
|
92
|
+
return RateLimitError;
|
|
93
|
+
default:
|
|
94
|
+
return ApiError;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
export interface SignIdentityParams {
|
|
2
|
+
/** Your identify secret (`lps_…`), from Settings › App push. Server only: never in an app. */
|
|
3
|
+
secret: string;
|
|
4
|
+
/** Your own id for the logged-in customer (or their mobile number). */
|
|
5
|
+
customerId: string;
|
|
6
|
+
/** The app's install id (SDK `installId`). With it the signature works for that install only (recommended). */
|
|
7
|
+
installId?: string;
|
|
8
|
+
/** Unix seconds when signed; defaults to now. Valid for 15 minutes. */
|
|
9
|
+
timestamp?: number;
|
|
10
|
+
}
|
|
11
|
+
export interface SignedIdentity {
|
|
12
|
+
customer_id: string;
|
|
13
|
+
timestamp: number;
|
|
14
|
+
/** 64 hex characters. */
|
|
15
|
+
signature: string;
|
|
16
|
+
/** `install` when the signature covers the install id; null for the older plain form. */
|
|
17
|
+
bind: "install" | null;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* Signs a customer in: hex HMAC-SHA256, keyed with the identify secret, of `<customerId>:<timestamp>[:<installId>]`
|
|
21
|
+
* (UTF-8). Hand the result to your app, which passes it to the Loyaltte SDK's `identify`.
|
|
22
|
+
*/
|
|
23
|
+
export declare function signIdentity({ secret, customerId, installId, timestamp, }: SignIdentityParams): SignedIdentity;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.signIdentity = signIdentity;
|
|
4
|
+
const node_crypto_1 = require("node:crypto");
|
|
5
|
+
const errors_js_1 = require("./errors.js");
|
|
6
|
+
/**
|
|
7
|
+
* Signs a customer in: hex HMAC-SHA256, keyed with the identify secret, of `<customerId>:<timestamp>[:<installId>]`
|
|
8
|
+
* (UTF-8). Hand the result to your app, which passes it to the Loyaltte SDK's `identify`.
|
|
9
|
+
*/
|
|
10
|
+
function signIdentity({ secret, customerId, installId, timestamp, }) {
|
|
11
|
+
if (typeof secret !== "string" || secret === "")
|
|
12
|
+
throw (0, errors_js_1.invalidArgument)("secret is required.", { secret: "required" });
|
|
13
|
+
if (typeof customerId !== "string" || customerId === "")
|
|
14
|
+
throw (0, errors_js_1.invalidArgument)("customerId is required.", { customerId: "required" });
|
|
15
|
+
if (installId !== undefined && (typeof installId !== "string" || installId === ""))
|
|
16
|
+
throw (0, errors_js_1.invalidArgument)("installId must be a non-empty string.", { installId: "invalid" });
|
|
17
|
+
const ts = timestamp ?? Math.floor(Date.now() / 1000);
|
|
18
|
+
if (!Number.isSafeInteger(ts) || ts < 0)
|
|
19
|
+
throw (0, errors_js_1.invalidArgument)("timestamp is whole unix seconds.", { timestamp: "invalid" });
|
|
20
|
+
const message = installId ? `${customerId}:${ts}:${installId}` : `${customerId}:${ts}`;
|
|
21
|
+
return {
|
|
22
|
+
customer_id: customerId,
|
|
23
|
+
timestamp: ts,
|
|
24
|
+
signature: (0, node_crypto_1.createHmac)("sha256", secret).update(message, "utf8").digest("hex"),
|
|
25
|
+
bind: installId ? "install" : null,
|
|
26
|
+
};
|
|
27
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export { Loyaltte, MAX_BODY_BYTES, MAX_EVENTS_PER_BATCH, maskKey } from "./client.js";
|
|
2
|
+
export type { IdempotencyOptions, LoyaltteOptions } from "./client.js";
|
|
3
|
+
export { ApiError, AuthenticationError, ConflictError, ConnectionError, LoyaltteError, NotFoundError, PermissionError, RateLimitError, ValidationError, WebhookSignatureError, } from "./errors.js";
|
|
4
|
+
export type { LoyaltteErrorInit } from "./errors.js";
|
|
5
|
+
export { signIdentity } from "./identity.js";
|
|
6
|
+
export type { SignIdentityParams, SignedIdentity } from "./identity.js";
|
|
7
|
+
export { constructEvent, verify, webhooks } from "./webhooks.js";
|
|
8
|
+
export type { VerifyParams } from "./webhooks.js";
|
|
9
|
+
export type { FetchLike } from "./transport.js";
|
|
10
|
+
export { VERSION } from "./version.js";
|
|
11
|
+
export type * from "./types.js";
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.VERSION = exports.webhooks = exports.verify = exports.constructEvent = exports.signIdentity = exports.WebhookSignatureError = exports.ValidationError = exports.RateLimitError = exports.PermissionError = exports.NotFoundError = exports.LoyaltteError = exports.ConnectionError = exports.ConflictError = exports.AuthenticationError = exports.ApiError = exports.maskKey = exports.MAX_EVENTS_PER_BATCH = exports.MAX_BODY_BYTES = exports.Loyaltte = void 0;
|
|
4
|
+
var client_js_1 = require("./client.js");
|
|
5
|
+
Object.defineProperty(exports, "Loyaltte", { enumerable: true, get: function () { return client_js_1.Loyaltte; } });
|
|
6
|
+
Object.defineProperty(exports, "MAX_BODY_BYTES", { enumerable: true, get: function () { return client_js_1.MAX_BODY_BYTES; } });
|
|
7
|
+
Object.defineProperty(exports, "MAX_EVENTS_PER_BATCH", { enumerable: true, get: function () { return client_js_1.MAX_EVENTS_PER_BATCH; } });
|
|
8
|
+
Object.defineProperty(exports, "maskKey", { enumerable: true, get: function () { return client_js_1.maskKey; } });
|
|
9
|
+
var errors_js_1 = require("./errors.js");
|
|
10
|
+
Object.defineProperty(exports, "ApiError", { enumerable: true, get: function () { return errors_js_1.ApiError; } });
|
|
11
|
+
Object.defineProperty(exports, "AuthenticationError", { enumerable: true, get: function () { return errors_js_1.AuthenticationError; } });
|
|
12
|
+
Object.defineProperty(exports, "ConflictError", { enumerable: true, get: function () { return errors_js_1.ConflictError; } });
|
|
13
|
+
Object.defineProperty(exports, "ConnectionError", { enumerable: true, get: function () { return errors_js_1.ConnectionError; } });
|
|
14
|
+
Object.defineProperty(exports, "LoyaltteError", { enumerable: true, get: function () { return errors_js_1.LoyaltteError; } });
|
|
15
|
+
Object.defineProperty(exports, "NotFoundError", { enumerable: true, get: function () { return errors_js_1.NotFoundError; } });
|
|
16
|
+
Object.defineProperty(exports, "PermissionError", { enumerable: true, get: function () { return errors_js_1.PermissionError; } });
|
|
17
|
+
Object.defineProperty(exports, "RateLimitError", { enumerable: true, get: function () { return errors_js_1.RateLimitError; } });
|
|
18
|
+
Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return errors_js_1.ValidationError; } });
|
|
19
|
+
Object.defineProperty(exports, "WebhookSignatureError", { enumerable: true, get: function () { return errors_js_1.WebhookSignatureError; } });
|
|
20
|
+
var identity_js_1 = require("./identity.js");
|
|
21
|
+
Object.defineProperty(exports, "signIdentity", { enumerable: true, get: function () { return identity_js_1.signIdentity; } });
|
|
22
|
+
var webhooks_js_1 = require("./webhooks.js");
|
|
23
|
+
Object.defineProperty(exports, "constructEvent", { enumerable: true, get: function () { return webhooks_js_1.constructEvent; } });
|
|
24
|
+
Object.defineProperty(exports, "verify", { enumerable: true, get: function () { return webhooks_js_1.verify; } });
|
|
25
|
+
Object.defineProperty(exports, "webhooks", { enumerable: true, get: function () { return webhooks_js_1.webhooks; } });
|
|
26
|
+
var version_js_1 = require("./version.js");
|
|
27
|
+
Object.defineProperty(exports, "VERSION", { enumerable: true, get: function () { return version_js_1.VERSION; } });
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"type":"commonjs"}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/** From `x-retry` in the OpenAPI spec (contract/rules/server.json). */
|
|
2
|
+
export declare const RETRY: {
|
|
3
|
+
baseMs: number;
|
|
4
|
+
maxMs: number;
|
|
5
|
+
multiplier: number;
|
|
6
|
+
maxAttempts: number;
|
|
7
|
+
statuses: Set<number>;
|
|
8
|
+
/** Across one call's retries: a bad Retry-After must not park a worker for hours. */
|
|
9
|
+
maxTotalSleepMs: number;
|
|
10
|
+
};
|
|
11
|
+
/**
|
|
12
|
+
* How an operation may be repeated:
|
|
13
|
+
* - `always`: a GET. Retried on every retry status and every network error.
|
|
14
|
+
* - `idempotency-key`: bills and returns. Retried the same way, always with the SAME Idempotency-Key.
|
|
15
|
+
* - `refused-only`: a POST the server can't tell from a new call. Retried only when the server certainly did
|
|
16
|
+
* nothing: a connection that was never made, or a 429 that says when (Retry-After). Not 503.
|
|
17
|
+
*/
|
|
18
|
+
export type RetryClass = "always" | "idempotency-key" | "refused-only";
|
|
19
|
+
export interface Operation {
|
|
20
|
+
method: "GET" | "POST";
|
|
21
|
+
/** Path, e.g. `/v1/bills`. */
|
|
22
|
+
path: string;
|
|
23
|
+
retry: RetryClass;
|
|
24
|
+
}
|
|
25
|
+
export interface RequestInput {
|
|
26
|
+
query?: Record<string, string | undefined>;
|
|
27
|
+
body?: unknown;
|
|
28
|
+
idempotencyKey?: string;
|
|
29
|
+
}
|
|
30
|
+
export type FetchLike = (input: string, init: RequestInit) => Promise<Response>;
|
|
31
|
+
export interface TransportConfig {
|
|
32
|
+
secretKey: string;
|
|
33
|
+
baseUrl: string;
|
|
34
|
+
timeoutMs: number;
|
|
35
|
+
maxRetries: number;
|
|
36
|
+
fetch: FetchLike;
|
|
37
|
+
sleep: (ms: number) => Promise<void>;
|
|
38
|
+
}
|
|
39
|
+
/** The jittered backoff before the next try; `attempt` is 1 for the first retry. */
|
|
40
|
+
export declare function backoffMs(attempt: number, random?: () => number): number;
|
|
41
|
+
/**
|
|
42
|
+
* Sends the requests. The secret key lives only in a private field: it is never a property, never printed, never
|
|
43
|
+
* in an error. Nothing here logs.
|
|
44
|
+
*/
|
|
45
|
+
export declare class Transport {
|
|
46
|
+
#private;
|
|
47
|
+
constructor({ secretKey, ...config }: TransportConfig);
|
|
48
|
+
request<T>(operation: Operation, input?: RequestInput): Promise<T>;
|
|
49
|
+
}
|
|
50
|
+
export declare const newIdempotencyKey: () => string;
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.newIdempotencyKey = exports.Transport = exports.RETRY = void 0;
|
|
4
|
+
exports.backoffMs = backoffMs;
|
|
5
|
+
const node_crypto_1 = require("node:crypto");
|
|
6
|
+
const errors_js_1 = require("./errors.js");
|
|
7
|
+
const version_js_1 = require("./version.js");
|
|
8
|
+
/** From `x-retry` in the OpenAPI spec (contract/rules/server.json). */
|
|
9
|
+
exports.RETRY = {
|
|
10
|
+
baseMs: 1000,
|
|
11
|
+
maxMs: 60_000,
|
|
12
|
+
multiplier: 2,
|
|
13
|
+
maxAttempts: 8,
|
|
14
|
+
statuses: new Set([408, 425, 429, 500, 502, 503, 504]),
|
|
15
|
+
/** Across one call's retries: a bad Retry-After must not park a worker for hours. */
|
|
16
|
+
maxTotalSleepMs: 300_000,
|
|
17
|
+
};
|
|
18
|
+
const NEVER_SENT = new Set([
|
|
19
|
+
"ECONNREFUSED",
|
|
20
|
+
"ENOTFOUND",
|
|
21
|
+
"EAI_AGAIN",
|
|
22
|
+
"ENETUNREACH",
|
|
23
|
+
"EHOSTUNREACH",
|
|
24
|
+
"UND_ERR_CONNECT_TIMEOUT",
|
|
25
|
+
]);
|
|
26
|
+
const errorCode = (error) => {
|
|
27
|
+
const code = error?.cause?.code;
|
|
28
|
+
return typeof code === "string" ? code : undefined;
|
|
29
|
+
};
|
|
30
|
+
/** The certificate was refused: never retried, however the operation is classed. */
|
|
31
|
+
function isCertificateFailure(error) {
|
|
32
|
+
const code = errorCode(error);
|
|
33
|
+
return (code !== undefined &&
|
|
34
|
+
(code.startsWith("ERR_TLS_") ||
|
|
35
|
+
/^(CERT_|DEPTH_ZERO_SELF_SIGNED|SELF_SIGNED_CERT|UNABLE_TO_(VERIFY_LEAF|GET_ISSUER|GET_LOCAL_ISSUER)|HOSTNAME_MISMATCH)/.test(code)));
|
|
36
|
+
}
|
|
37
|
+
/** The request certainly never reached the server (no connection was made). */
|
|
38
|
+
function neverSent(error) {
|
|
39
|
+
const code = error?.cause?.code;
|
|
40
|
+
return typeof code === "string" && NEVER_SENT.has(code);
|
|
41
|
+
}
|
|
42
|
+
function parseRetryAfter(value) {
|
|
43
|
+
if (value === null || !/^\s*\d+(\.\d+)?\s*$/.test(value))
|
|
44
|
+
return null;
|
|
45
|
+
return Number(value);
|
|
46
|
+
}
|
|
47
|
+
/** The jittered backoff before the next try; `attempt` is 1 for the first retry. */
|
|
48
|
+
function backoffMs(attempt, random = Math.random) {
|
|
49
|
+
const cap = Math.min(exports.RETRY.maxMs, exports.RETRY.baseMs * exports.RETRY.multiplier ** (attempt - 1));
|
|
50
|
+
return Math.floor(random() * cap);
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Sends the requests. The secret key lives only in a private field: it is never a property, never printed, never
|
|
54
|
+
* in an error. Nothing here logs.
|
|
55
|
+
*/
|
|
56
|
+
class Transport {
|
|
57
|
+
#secretKey;
|
|
58
|
+
#config;
|
|
59
|
+
constructor({ secretKey, ...config }) {
|
|
60
|
+
this.#secretKey = secretKey;
|
|
61
|
+
this.#config = config;
|
|
62
|
+
}
|
|
63
|
+
async request(operation, input = {}) {
|
|
64
|
+
try {
|
|
65
|
+
return await this.#attempts(operation, input);
|
|
66
|
+
}
|
|
67
|
+
catch (error) {
|
|
68
|
+
// After a raised error the caller can resend with this key and stay safe (a bill or return may have been
|
|
69
|
+
// recorded before the reply was lost).
|
|
70
|
+
if (error instanceof errors_js_1.LoyaltteError && input.idempotencyKey !== undefined)
|
|
71
|
+
error.idempotencyKey = input.idempotencyKey;
|
|
72
|
+
throw error;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
async #attempts(operation, input) {
|
|
76
|
+
const { baseUrl, timeoutMs, maxRetries, fetch, sleep } = this.#config;
|
|
77
|
+
const query = Object.entries(input.query ?? {}).filter(([, v]) => v !== undefined);
|
|
78
|
+
const url = `${baseUrl}${operation.path}${query.length ? `?${new URLSearchParams(query).toString()}` : ""}`;
|
|
79
|
+
const body = input.body === undefined ? undefined : JSON.stringify(input.body);
|
|
80
|
+
const headers = {
|
|
81
|
+
Authorization: `Bearer ${this.#secretKey}`,
|
|
82
|
+
"X-Loyaltte-SDK": `node/${version_js_1.VERSION}`,
|
|
83
|
+
Accept: "application/json",
|
|
84
|
+
};
|
|
85
|
+
if (body !== undefined)
|
|
86
|
+
headers["Content-Type"] = "application/json";
|
|
87
|
+
// One key per call, the same on every attempt: that is what makes a retry after a lost reply safe.
|
|
88
|
+
if (input.idempotencyKey !== undefined)
|
|
89
|
+
headers["Idempotency-Key"] = input.idempotencyKey;
|
|
90
|
+
let slept = 0; // ms waited so far in this call: capped at RETRY.maxTotalSleepMs
|
|
91
|
+
for (let attempt = 1;; attempt += 1) {
|
|
92
|
+
const retriesLeft = attempt <= maxRetries && slept < exports.RETRY.maxTotalSleepMs;
|
|
93
|
+
let response;
|
|
94
|
+
let text;
|
|
95
|
+
// A plain timer (not AbortSignal.timeout, whose timer is unref'd on Node 18) so the timeout always fires,
|
|
96
|
+
// covering the body read too; cleared as soon as the attempt ends.
|
|
97
|
+
const controller = new AbortController();
|
|
98
|
+
const timer = setTimeout(() => controller.abort(new DOMException("The request timed out.", "TimeoutError")), timeoutMs);
|
|
99
|
+
try {
|
|
100
|
+
response = await fetch(url, {
|
|
101
|
+
method: operation.method,
|
|
102
|
+
headers,
|
|
103
|
+
body,
|
|
104
|
+
redirect: "error", // never follow a redirect with the key attached
|
|
105
|
+
signal: controller.signal,
|
|
106
|
+
});
|
|
107
|
+
text = await response.text();
|
|
108
|
+
}
|
|
109
|
+
catch (error) {
|
|
110
|
+
if (isCertificateFailure(error))
|
|
111
|
+
throw new errors_js_1.ConnectionError({
|
|
112
|
+
message: "TLS certificate verification failed; refusing to send the request.",
|
|
113
|
+
code: "TLS_VERIFICATION_FAILED",
|
|
114
|
+
cause: { name: "TlsError", code: errorCode(error) },
|
|
115
|
+
});
|
|
116
|
+
const retryable = operation.retry === "refused-only" ? neverSent(error) : true;
|
|
117
|
+
if (retryable && retriesLeft) {
|
|
118
|
+
slept += await this.#wait(sleep, backoffMs(attempt), slept);
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
throw this.#connectionError(error);
|
|
122
|
+
}
|
|
123
|
+
finally {
|
|
124
|
+
clearTimeout(timer);
|
|
125
|
+
}
|
|
126
|
+
if (response.ok)
|
|
127
|
+
return this.#parse(response, text);
|
|
128
|
+
const failure = this.#failure(response, text);
|
|
129
|
+
const status = response.status;
|
|
130
|
+
const asked = status === 429 || status === 503 ? failure.retryAfter : null;
|
|
131
|
+
// Not safe to repeat unless the server certainly did nothing: for these POSTs that is a 429 that says when.
|
|
132
|
+
const retryable = exports.RETRY.statuses.has(status) &&
|
|
133
|
+
(operation.retry !== "refused-only" || (status === 429 && asked !== null));
|
|
134
|
+
if (retryable && retriesLeft) {
|
|
135
|
+
// A Retry-After longer than what is left of the budget ends the call with this error: no early retry.
|
|
136
|
+
if (asked !== null && asked * 1000 > exports.RETRY.maxTotalSleepMs - slept)
|
|
137
|
+
throw failure;
|
|
138
|
+
const jitter = backoffMs(attempt);
|
|
139
|
+
slept += await this.#wait(sleep, asked === null ? jitter : Math.max(asked * 1000, jitter), slept);
|
|
140
|
+
continue;
|
|
141
|
+
}
|
|
142
|
+
throw failure;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
/** Sleeps `ms` (at most what is left of the call's budget) and says how long that was. */
|
|
146
|
+
async #wait(sleep, ms, slept) {
|
|
147
|
+
const wait = Math.max(0, Math.min(ms, exports.RETRY.maxTotalSleepMs - slept));
|
|
148
|
+
await sleep(wait);
|
|
149
|
+
return wait;
|
|
150
|
+
}
|
|
151
|
+
#parse(response, text) {
|
|
152
|
+
try {
|
|
153
|
+
return JSON.parse(text);
|
|
154
|
+
}
|
|
155
|
+
catch {
|
|
156
|
+
throw new errors_js_1.ApiError({
|
|
157
|
+
message: "Loyaltte answered with something that isn't JSON.",
|
|
158
|
+
status: response.status,
|
|
159
|
+
code: "INVALID_RESPONSE",
|
|
160
|
+
requestId: response.headers.get("x-request-id"),
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
#failure(response, text) {
|
|
165
|
+
const status = response.status;
|
|
166
|
+
let detail = null;
|
|
167
|
+
try {
|
|
168
|
+
const parsed = JSON.parse(text);
|
|
169
|
+
if (parsed && typeof parsed === "object" && parsed.error && typeof parsed.error === "object")
|
|
170
|
+
detail = parsed.error;
|
|
171
|
+
}
|
|
172
|
+
catch {
|
|
173
|
+
// not JSON: use the status below
|
|
174
|
+
}
|
|
175
|
+
const text2 = (v) => (typeof v === "string" && v ? v : null);
|
|
176
|
+
const fields = detail?.fields && typeof detail.fields === "object" && !Array.isArray(detail.fields)
|
|
177
|
+
? detail.fields
|
|
178
|
+
: null;
|
|
179
|
+
const Type = (0, errors_js_1.errorForStatus)(status);
|
|
180
|
+
return new Type({
|
|
181
|
+
status,
|
|
182
|
+
code: this.#redact(text2(detail?.code) ?? `HTTP_${status}`),
|
|
183
|
+
message: this.#redact(text2(detail?.message) ?? (response.statusText || `HTTP ${status}`)),
|
|
184
|
+
fields: fields && JSON.parse(this.#redact(JSON.stringify(fields))),
|
|
185
|
+
requestId: this.#redactOrNull(text2(detail?.requestId) ?? response.headers.get("x-request-id")),
|
|
186
|
+
retryAfter: parseRetryAfter(response.headers.get("retry-after")),
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
/** Belt and braces: whatever text reaches an error, the key itself never does. */
|
|
190
|
+
#redact(text) {
|
|
191
|
+
return text.split(this.#secretKey).join("[redacted key]");
|
|
192
|
+
}
|
|
193
|
+
#redactOrNull(text) {
|
|
194
|
+
return text === null ? null : this.#redact(text);
|
|
195
|
+
}
|
|
196
|
+
#connectionError(error) {
|
|
197
|
+
const name = error?.name;
|
|
198
|
+
const code = error?.cause?.code;
|
|
199
|
+
const timedOut = name === "TimeoutError" || name === "AbortError";
|
|
200
|
+
return new errors_js_1.ConnectionError({
|
|
201
|
+
message: timedOut
|
|
202
|
+
? `Loyaltte did not answer within ${this.#config.timeoutMs} ms.`
|
|
203
|
+
: `Could not reach Loyaltte${typeof code === "string" ? ` (${code})` : ""}.`,
|
|
204
|
+
code: timedOut ? "TIMEOUT" : "CONNECTION_FAILED",
|
|
205
|
+
// Only what is safe to show: a custom fetch's error could carry the request, headers included.
|
|
206
|
+
cause: { name: String(name ?? "Error"), code: typeof code === "string" ? code : undefined },
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
exports.Transport = Transport;
|
|
211
|
+
const newIdempotencyKey = () => (0, node_crypto_1.randomUUID)();
|
|
212
|
+
exports.newIdempotencyKey = newIdempotencyKey;
|