@loyaltte/node 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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 +205 -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 +199 -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,273 @@
|
|
|
1
|
+
import { LoyaltteError, invalidArgument } from "./errors.js";
|
|
2
|
+
import { signIdentity } from "./identity.js";
|
|
3
|
+
import { RETRY, Transport, newIdempotencyKey, } from "./transport.js";
|
|
4
|
+
import { webhooks } from "./webhooks.js";
|
|
5
|
+
/** `x-limits.maxEventsPerBatch` in the spec. */
|
|
6
|
+
export const MAX_EVENTS_PER_BATCH = 100;
|
|
7
|
+
/** `x-limits.maxBodyBytes` in the spec. */
|
|
8
|
+
export const MAX_BODY_BYTES = 65_536;
|
|
9
|
+
const EVENTS_ENVELOPE_BYTES = '{"events":[]}'.length;
|
|
10
|
+
const DECIMAL = /^\d+(\.\d+)?$/;
|
|
11
|
+
const op = (method, path, retry) => ({
|
|
12
|
+
method,
|
|
13
|
+
path,
|
|
14
|
+
retry,
|
|
15
|
+
});
|
|
16
|
+
const OPS = {
|
|
17
|
+
checkKey: op("GET", "/v1/key", "always"),
|
|
18
|
+
events: op("POST", "/v1/events", "refused-only"),
|
|
19
|
+
identify: op("POST", "/v1/identify", "refused-only"),
|
|
20
|
+
lookup: op("GET", "/v1/customers/lookup", "always"),
|
|
21
|
+
customer: (id) => op("GET", `/v1/customers/${encodeURIComponent(id)}`, "always"),
|
|
22
|
+
points: (id) => op("GET", `/v1/customers/${encodeURIComponent(id)}/points`, "always"),
|
|
23
|
+
preview: op("POST", "/v1/bills/preview", "refused-only"),
|
|
24
|
+
bill: op("POST", "/v1/bills", "idempotency-key"),
|
|
25
|
+
returns: op("POST", "/v1/returns", "idempotency-key"),
|
|
26
|
+
};
|
|
27
|
+
function requireId(id, what, inPath = false) {
|
|
28
|
+
if (typeof id !== "string" || id === "")
|
|
29
|
+
throw invalidArgument(`${what} is required.`, { [what]: "required" });
|
|
30
|
+
if (inPath && /^\.+$/.test(id))
|
|
31
|
+
throw invalidArgument(`${what} is not valid.`, { [what]: "invalid" });
|
|
32
|
+
return id;
|
|
33
|
+
}
|
|
34
|
+
/** Money is a decimal string: a number (a float) is refused before anything is sent. */
|
|
35
|
+
function requireMoney(value, field) {
|
|
36
|
+
if (typeof value !== "string" || !DECIMAL.test(value))
|
|
37
|
+
throw invalidArgument(`${field} must be a decimal string like "4200.00" (never a number: floats lose paise).`, { [field]: "must be a decimal string" });
|
|
38
|
+
}
|
|
39
|
+
function checkBill(body) {
|
|
40
|
+
if (body === null || typeof body !== "object")
|
|
41
|
+
throw invalidArgument("body is required.", { body: "required" });
|
|
42
|
+
requireMoney(body.amount, "amount");
|
|
43
|
+
if (body.items !== undefined) {
|
|
44
|
+
if (!Array.isArray(body.items))
|
|
45
|
+
throw invalidArgument("items must be a list.", { items: "invalid" });
|
|
46
|
+
body.items.forEach((line, i) => requireMoney(line?.amount, `items[${i}].amount`));
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
function idempotencyKeyFor(options) {
|
|
50
|
+
const given = options?.idempotencyKey;
|
|
51
|
+
if (given === undefined)
|
|
52
|
+
return newIdempotencyKey();
|
|
53
|
+
if (typeof given !== "string" || !/^[\x20-\x7e]{1,255}$/.test(given))
|
|
54
|
+
throw invalidArgument("idempotencyKey must be 1 to 255 printable ASCII characters.", {
|
|
55
|
+
idempotencyKey: "invalid",
|
|
56
|
+
});
|
|
57
|
+
return given;
|
|
58
|
+
}
|
|
59
|
+
/** `lyt_live_abcd…wxyz` -> `lyt_live_...wxyz`: enough to tell keys apart, never the key. */
|
|
60
|
+
export function maskKey(key) {
|
|
61
|
+
const prefix = /^lyt_(?:live|test)_/.exec(key)?.[0] ?? "";
|
|
62
|
+
return `${prefix}...${key.length >= 12 ? key.slice(-4) : ""}`;
|
|
63
|
+
}
|
|
64
|
+
class Resource {
|
|
65
|
+
#transport;
|
|
66
|
+
constructor(transport) {
|
|
67
|
+
this.#transport = transport;
|
|
68
|
+
}
|
|
69
|
+
call(operation, input) {
|
|
70
|
+
return this.#transport.request(operation, input);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
/** `GET /v1/key`. */
|
|
74
|
+
class KeyResource extends Resource {
|
|
75
|
+
/** Which account and mode the key is for, its permissions and stores. A good first call. */
|
|
76
|
+
retrieve() {
|
|
77
|
+
return this.call(OPS.checkKey);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
class EventsResource extends Resource {
|
|
81
|
+
/**
|
|
82
|
+
* Sends events (`POST /v1/events`). A longer list is sent in order as several requests of at most 100 events and
|
|
83
|
+
* 64 KiB each, and the answers are summed (`accepted`, `duplicates`; `rejected` entries keep the index the server gave,
|
|
84
|
+
* which is within their own batch). An empty list is a ValidationError before anything is sent. If a batch fails the error is raised and the
|
|
85
|
+
* earlier batches stay accepted: give every event an `id` and resend them all, a repeat is counted once.
|
|
86
|
+
*/
|
|
87
|
+
send(events) {
|
|
88
|
+
if (!Array.isArray(events) || events.length === 0)
|
|
89
|
+
throw invalidArgument("Send at least one event.", { events: "empty" });
|
|
90
|
+
const batches = [];
|
|
91
|
+
let current = [];
|
|
92
|
+
let size = EVENTS_ENVELOPE_BYTES;
|
|
93
|
+
events.forEach((event, i) => {
|
|
94
|
+
const bytes = Buffer.byteLength(JSON.stringify(event) ?? "null", "utf8") + 1; // + the comma
|
|
95
|
+
if (bytes + EVENTS_ENVELOPE_BYTES > MAX_BODY_BYTES)
|
|
96
|
+
throw invalidArgument(`Event ${i} is larger than ${MAX_BODY_BYTES} bytes.`, {
|
|
97
|
+
events: "too_large",
|
|
98
|
+
});
|
|
99
|
+
if (current.length > 0 &&
|
|
100
|
+
(current.length >= MAX_EVENTS_PER_BATCH || size + bytes > MAX_BODY_BYTES)) {
|
|
101
|
+
batches.push(current);
|
|
102
|
+
current = [];
|
|
103
|
+
size = EVENTS_ENVELOPE_BYTES;
|
|
104
|
+
}
|
|
105
|
+
current.push(event);
|
|
106
|
+
size += bytes;
|
|
107
|
+
});
|
|
108
|
+
batches.push(current);
|
|
109
|
+
return this.#sendAll(batches);
|
|
110
|
+
}
|
|
111
|
+
async #sendAll(batches) {
|
|
112
|
+
const total = {
|
|
113
|
+
accepted: 0,
|
|
114
|
+
duplicates: 0,
|
|
115
|
+
rejected: [],
|
|
116
|
+
dropped_properties: [],
|
|
117
|
+
};
|
|
118
|
+
for (const batch of batches) {
|
|
119
|
+
const answer = await this.call(OPS.events, { body: { events: batch } });
|
|
120
|
+
total.accepted += answer.accepted ?? 0;
|
|
121
|
+
total.duplicates += answer.duplicates ?? 0;
|
|
122
|
+
total.rejected.push(...(answer.rejected ?? []));
|
|
123
|
+
total.dropped_properties.push(...(answer.dropped_properties ?? []));
|
|
124
|
+
}
|
|
125
|
+
return total;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
class VisitorsResource extends Resource {
|
|
129
|
+
/** Ties a visitor's `anonymous_id` to a customer (`POST /v1/identify`); their earlier events become the customer's. */
|
|
130
|
+
identify(params) {
|
|
131
|
+
if (!params || typeof params.anonymous_id !== "string" || params.anonymous_id === "")
|
|
132
|
+
throw invalidArgument("anonymous_id is required.", { anonymous_id: "required" });
|
|
133
|
+
if (!params.phone && !params.email && !params.external_id)
|
|
134
|
+
throw invalidArgument("Give phone, email or external_id.", { customer: "required" });
|
|
135
|
+
return this.call(OPS.identify, { body: params });
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
class CustomersResource extends Resource {
|
|
139
|
+
/** Finds a customer by `phone`, `email` or `external_id` (`GET /v1/customers/lookup`). `found` is false when there is none. */
|
|
140
|
+
lookup(params) {
|
|
141
|
+
const { phone, email, external_id } = params ?? {};
|
|
142
|
+
if (!phone && !email && !external_id)
|
|
143
|
+
throw invalidArgument("Give phone, email or external_id.", { customer: "required" });
|
|
144
|
+
return this.call(OPS.lookup, { query: { phone, email, external_id } });
|
|
145
|
+
}
|
|
146
|
+
/** The profile summary (`GET /v1/customers/{id}`): membership, tier, points, lifetime spend, consent. */
|
|
147
|
+
retrieve(customerId) {
|
|
148
|
+
return this.call(OPS.customer(requireId(customerId, "customerId", true)));
|
|
149
|
+
}
|
|
150
|
+
/** The balance, lifetime earned and redeemed, and points expiring soon (`GET /v1/customers/{id}/points`). */
|
|
151
|
+
points(customerId) {
|
|
152
|
+
return this.call(OPS.points(requireId(customerId, "customerId", true)));
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
class BillsResource extends Resource {
|
|
156
|
+
/** Works a bill out without recording it (`POST /v1/bills/preview`). Amounts are decimal strings. */
|
|
157
|
+
preview(body) {
|
|
158
|
+
checkBill(body);
|
|
159
|
+
return this.call(OPS.preview, { body });
|
|
160
|
+
}
|
|
161
|
+
/**
|
|
162
|
+
* Records a bill (`POST /v1/bills`), exactly once: the call carries an Idempotency-Key (yours, or one the SDK
|
|
163
|
+
* makes) that every retry reuses, so a lost reply never records the bill twice. A repeat comes back with
|
|
164
|
+
* `replayed: true`.
|
|
165
|
+
*/
|
|
166
|
+
create(body, options) {
|
|
167
|
+
checkBill(body);
|
|
168
|
+
requireId(body.bill_number, "bill_number");
|
|
169
|
+
return this.call(OPS.bill, { body, idempotencyKey: idempotencyKeyFor(options) });
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
class ReturnsResource extends Resource {
|
|
173
|
+
/** Records a full or part return against an earlier bill (`POST /v1/returns`), exactly once like `bills.create`. */
|
|
174
|
+
create(body, options) {
|
|
175
|
+
if (body === null || typeof body !== "object")
|
|
176
|
+
throw invalidArgument("body is required.", { body: "required" });
|
|
177
|
+
requireId(body.bill_number, "bill_number");
|
|
178
|
+
requireId(body.return_number, "return_number");
|
|
179
|
+
requireMoney(body.amount, "amount");
|
|
180
|
+
return this.call(OPS.returns, { body, idempotencyKey: idempotencyKeyFor(options) });
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
const DEFAULT_BASE_URL = "https://api.loyaltte.com";
|
|
184
|
+
const LOOPBACK = new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
185
|
+
/** https only (the key travels in every request); plain http just for localhost, in tests. */
|
|
186
|
+
function checkBaseUrl(value) {
|
|
187
|
+
let url;
|
|
188
|
+
try {
|
|
189
|
+
url = new URL(value);
|
|
190
|
+
}
|
|
191
|
+
catch {
|
|
192
|
+
throw invalidArgument("baseUrl is not a URL.", { baseUrl: "invalid" });
|
|
193
|
+
}
|
|
194
|
+
const ok = url.protocol === "https:" || (url.protocol === "http:" && LOOPBACK.has(url.hostname));
|
|
195
|
+
if (!ok || url.username || url.password || url.search || url.hash)
|
|
196
|
+
throw invalidArgument("baseUrl must be an https:// address without credentials, query or fragment (plain http is only for localhost).", { baseUrl: "invalid" });
|
|
197
|
+
return `${url.origin}${url.pathname}`.replace(/\/+$/, "");
|
|
198
|
+
}
|
|
199
|
+
/**
|
|
200
|
+
* The Loyaltte server client. Use a SECRET key (`lyt_live_…` / `lyt_test_…`) and only on your server.
|
|
201
|
+
*
|
|
202
|
+
* ```ts
|
|
203
|
+
* const loyaltte = new Loyaltte(process.env.LOYALTTE_SECRET_KEY!);
|
|
204
|
+
* const key = await loyaltte.key.retrieve();
|
|
205
|
+
* ```
|
|
206
|
+
*/
|
|
207
|
+
export class Loyaltte {
|
|
208
|
+
/** Signs a customer in for the app SDK: see {@link signIdentity}. */
|
|
209
|
+
static signIdentity = signIdentity;
|
|
210
|
+
/** Checks and parses the webhooks Loyaltte sends. */
|
|
211
|
+
static webhooks = webhooks;
|
|
212
|
+
key;
|
|
213
|
+
events;
|
|
214
|
+
visitors;
|
|
215
|
+
customers;
|
|
216
|
+
bills;
|
|
217
|
+
returns;
|
|
218
|
+
/** The key, masked: `lyt_live_...wxyz`. The key itself is not kept anywhere you can read it. */
|
|
219
|
+
maskedKey;
|
|
220
|
+
constructor(secretKey, options = {}) {
|
|
221
|
+
if (typeof secretKey !== "string" || secretKey.trim() === "")
|
|
222
|
+
throw new LoyaltteError({
|
|
223
|
+
message: "Pass your secret key (lyt_live_… or lyt_test_…) from Settings › API keys.",
|
|
224
|
+
code: "INVALID_KEY",
|
|
225
|
+
});
|
|
226
|
+
if (secretKey.startsWith("lak_"))
|
|
227
|
+
throw new LoyaltteError({
|
|
228
|
+
message: "That is a publishable key (lak_…): it is for apps and web pages and cannot call the Server API. Use a secret key (lyt_live_… or lyt_test_…).",
|
|
229
|
+
code: "INVALID_KEY",
|
|
230
|
+
});
|
|
231
|
+
if (secretKey.startsWith("lps_"))
|
|
232
|
+
throw new LoyaltteError({
|
|
233
|
+
message: "That is an identify secret (lps_…): it signs sign-ins (Loyaltte.signIdentity) and is not an API key. Use a secret key (lyt_live_… or lyt_test_…).",
|
|
234
|
+
code: "INVALID_KEY",
|
|
235
|
+
});
|
|
236
|
+
const fetchImpl = options.fetch ?? globalThis.fetch;
|
|
237
|
+
if (!fetchImpl)
|
|
238
|
+
throw new LoyaltteError({
|
|
239
|
+
message: "This runtime has no global fetch (Node 18 or newer has it). Pass one as options.fetch.",
|
|
240
|
+
code: "NO_FETCH",
|
|
241
|
+
});
|
|
242
|
+
const maxRetries = options.maxRetries ?? RETRY.maxAttempts - 1;
|
|
243
|
+
const timeoutMs = options.timeoutMs ?? 30_000;
|
|
244
|
+
if (!Number.isInteger(maxRetries) || maxRetries < 0)
|
|
245
|
+
throw invalidArgument("maxRetries is a whole number, 0 or more.", { maxRetries: "invalid" });
|
|
246
|
+
if (!Number.isFinite(timeoutMs) || timeoutMs <= 0)
|
|
247
|
+
throw invalidArgument("timeoutMs is milliseconds, more than 0.", { timeoutMs: "invalid" });
|
|
248
|
+
const transport = new Transport({
|
|
249
|
+
secretKey,
|
|
250
|
+
baseUrl: checkBaseUrl(options.baseUrl ?? DEFAULT_BASE_URL),
|
|
251
|
+
timeoutMs,
|
|
252
|
+
maxRetries,
|
|
253
|
+
fetch: fetchImpl,
|
|
254
|
+
sleep: options.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms))),
|
|
255
|
+
});
|
|
256
|
+
this.maskedKey = maskKey(secretKey);
|
|
257
|
+
this.key = new KeyResource(transport);
|
|
258
|
+
this.events = new EventsResource(transport);
|
|
259
|
+
this.visitors = new VisitorsResource(transport);
|
|
260
|
+
this.customers = new CustomersResource(transport);
|
|
261
|
+
this.bills = new BillsResource(transport);
|
|
262
|
+
this.returns = new ReturnsResource(transport);
|
|
263
|
+
}
|
|
264
|
+
toString() {
|
|
265
|
+
return `Loyaltte(${this.maskedKey})`;
|
|
266
|
+
}
|
|
267
|
+
toJSON() {
|
|
268
|
+
return { key: this.maskedKey };
|
|
269
|
+
}
|
|
270
|
+
[Symbol.for("nodejs.util.inspect.custom")]() {
|
|
271
|
+
return this.toString();
|
|
272
|
+
}
|
|
273
|
+
}
|
|
@@ -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,81 @@
|
|
|
1
|
+
/** The base of every error this SDK throws. Messages never contain your secret key. */
|
|
2
|
+
export class LoyaltteError extends Error {
|
|
3
|
+
/** The HTTP status; null for a local refusal or when there was no answer. */
|
|
4
|
+
status;
|
|
5
|
+
/** The API's error code (`NOT_FOUND`, `VALIDATION_ERROR`, ...) or the SDK's own for a local refusal. */
|
|
6
|
+
code;
|
|
7
|
+
/** Per-field detail the API sent, e.g. `{ scope: "bills:write" }` on a 403. */
|
|
8
|
+
fields;
|
|
9
|
+
/** The id to quote to support (the answer's `requestId`, else its `X-Request-Id` header). */
|
|
10
|
+
requestId;
|
|
11
|
+
/** Seconds the server asked you to wait (`Retry-After`), when it did. */
|
|
12
|
+
retryAfter;
|
|
13
|
+
/**
|
|
14
|
+
* On a failed `bills.create` or `returns.create`: the Idempotency-Key the call used. The bill may have been
|
|
15
|
+
* recorded before the reply was lost; resend with THIS key (`{ idempotencyKey: error.idempotencyKey }`) to stay safe.
|
|
16
|
+
*/
|
|
17
|
+
idempotencyKey = null;
|
|
18
|
+
constructor(init) {
|
|
19
|
+
super(init.message, init.cause === undefined ? undefined : { cause: init.cause });
|
|
20
|
+
this.name = new.target.name;
|
|
21
|
+
this.status = init.status ?? null;
|
|
22
|
+
this.code = init.code ?? "ERROR";
|
|
23
|
+
this.fields = init.fields ?? null;
|
|
24
|
+
this.requestId = init.requestId ?? null;
|
|
25
|
+
this.retryAfter = init.retryAfter ?? null;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
/** 401: no key, or the key is revoked, expired or mistyped. */
|
|
29
|
+
export class AuthenticationError extends LoyaltteError {
|
|
30
|
+
}
|
|
31
|
+
/** 403: the key lacks a permission (`fields.scope` names it), or the feature isn't in the plan. */
|
|
32
|
+
export class PermissionError extends LoyaltteError {
|
|
33
|
+
}
|
|
34
|
+
/** 404: not found, or not in this key's account. */
|
|
35
|
+
export class NotFoundError extends LoyaltteError {
|
|
36
|
+
}
|
|
37
|
+
/** 409: an Idempotency-Key or a bill/return number used for a different request, or a state conflict. */
|
|
38
|
+
export class ConflictError extends LoyaltteError {
|
|
39
|
+
}
|
|
40
|
+
/** 400 or 422 from the API, or an argument the SDK refused before sending (`status` null, code `INVALID_ARGUMENT`). */
|
|
41
|
+
export class ValidationError extends LoyaltteError {
|
|
42
|
+
}
|
|
43
|
+
/** 429, once the retries are used up. `retryAfter` is the wait the server asked for. */
|
|
44
|
+
export class RateLimitError extends LoyaltteError {
|
|
45
|
+
}
|
|
46
|
+
/** Any other status (5xx, 413, 408, ...) once the retries are used up, or an answer that isn't JSON. */
|
|
47
|
+
export class ApiError extends LoyaltteError {
|
|
48
|
+
}
|
|
49
|
+
/** No answer: no connection, DNS failure, reset, timeout. `status` is null. */
|
|
50
|
+
export class ConnectionError extends LoyaltteError {
|
|
51
|
+
}
|
|
52
|
+
/** `Loyaltte.webhooks.constructEvent` could not verify the signature. */
|
|
53
|
+
export class WebhookSignatureError extends LoyaltteError {
|
|
54
|
+
constructor(message = "The webhook signature could not be verified.") {
|
|
55
|
+
super({ message, code: "WEBHOOK_SIGNATURE_INVALID" });
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
/** A refusal of an argument, before anything is sent. */
|
|
59
|
+
export function invalidArgument(message, fields) {
|
|
60
|
+
return new ValidationError({ message, code: "INVALID_ARGUMENT", fields: fields ?? null });
|
|
61
|
+
}
|
|
62
|
+
/** The typed error for an HTTP status (the mapping in contract/rules/server.json). */
|
|
63
|
+
export function errorForStatus(status) {
|
|
64
|
+
switch (status) {
|
|
65
|
+
case 401:
|
|
66
|
+
return AuthenticationError;
|
|
67
|
+
case 403:
|
|
68
|
+
return PermissionError;
|
|
69
|
+
case 404:
|
|
70
|
+
return NotFoundError;
|
|
71
|
+
case 409:
|
|
72
|
+
return ConflictError;
|
|
73
|
+
case 400:
|
|
74
|
+
case 422:
|
|
75
|
+
return ValidationError;
|
|
76
|
+
case 429:
|
|
77
|
+
return RateLimitError;
|
|
78
|
+
default:
|
|
79
|
+
return ApiError;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
@@ -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,24 @@
|
|
|
1
|
+
import { createHmac } from "node:crypto";
|
|
2
|
+
import { invalidArgument } from "./errors.js";
|
|
3
|
+
/**
|
|
4
|
+
* Signs a customer in: hex HMAC-SHA256, keyed with the identify secret, of `<customerId>:<timestamp>[:<installId>]`
|
|
5
|
+
* (UTF-8). Hand the result to your app, which passes it to the Loyaltte SDK's `identify`.
|
|
6
|
+
*/
|
|
7
|
+
export function signIdentity({ secret, customerId, installId, timestamp, }) {
|
|
8
|
+
if (typeof secret !== "string" || secret === "")
|
|
9
|
+
throw invalidArgument("secret is required.", { secret: "required" });
|
|
10
|
+
if (typeof customerId !== "string" || customerId === "")
|
|
11
|
+
throw invalidArgument("customerId is required.", { customerId: "required" });
|
|
12
|
+
if (installId !== undefined && (typeof installId !== "string" || installId === ""))
|
|
13
|
+
throw invalidArgument("installId must be a non-empty string.", { installId: "invalid" });
|
|
14
|
+
const ts = timestamp ?? Math.floor(Date.now() / 1000);
|
|
15
|
+
if (!Number.isSafeInteger(ts) || ts < 0)
|
|
16
|
+
throw invalidArgument("timestamp is whole unix seconds.", { timestamp: "invalid" });
|
|
17
|
+
const message = installId ? `${customerId}:${ts}:${installId}` : `${customerId}:${ts}`;
|
|
18
|
+
return {
|
|
19
|
+
customer_id: customerId,
|
|
20
|
+
timestamp: ts,
|
|
21
|
+
signature: createHmac("sha256", secret).update(message, "utf8").digest("hex"),
|
|
22
|
+
bind: installId ? "install" : null,
|
|
23
|
+
};
|
|
24
|
+
}
|
|
@@ -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,5 @@
|
|
|
1
|
+
export { Loyaltte, MAX_BODY_BYTES, MAX_EVENTS_PER_BATCH, maskKey } from "./client.js";
|
|
2
|
+
export { ApiError, AuthenticationError, ConflictError, ConnectionError, LoyaltteError, NotFoundError, PermissionError, RateLimitError, ValidationError, WebhookSignatureError, } from "./errors.js";
|
|
3
|
+
export { signIdentity } from "./identity.js";
|
|
4
|
+
export { constructEvent, verify, webhooks } from "./webhooks.js";
|
|
5
|
+
export { VERSION } from "./version.js";
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"type":"module"}
|
|
@@ -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;
|