@raylongsolutions/saaselixir 0.0.0-stage → 1.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.
@@ -0,0 +1,352 @@
1
+ var _a;
2
+ import { randomUUID } from 'node:crypto';
3
+ import { failureIn, SaasElixirError } from './errors.js';
4
+ export const VERSION = '1.0.0';
5
+ const DEFAULT_BASE = 'https://saaselixir.com';
6
+ const KEY_PATTERN = /^sxe_[A-Za-z0-9_-]{20,80}$/;
7
+ const MEMBERS_PER_CALL = 5000;
8
+ const memberBody = (m) => ({ phone: m.phone, ...(m.name ? { name: m.name } : {}), ...(m.fields ? { fields: Object.fromEntries(Object.entries(m.fields).map(([k, v]) => [k, String(v)])) } : {}) });
9
+ const valueBody = (v) => (typeof v === 'string' ? { text: v } : v);
10
+ function broadcastBody(i) {
11
+ const t = typeof i.template === 'string' ? { name: i.template, language: i.language } : { name: i.template.name, language: i.template.language ?? i.language };
12
+ return {
13
+ title: i.title, audienceId: i.audienceId, template: { name: t.name, language: t.language ?? 'en' },
14
+ ...(i.channelId ? { channelId: i.channelId } : {}), ...(i.trackClicks ? { trackClicks: true } : {}),
15
+ mapping: {
16
+ body: (i.body ?? []).map(valueBody),
17
+ ...(i.button !== undefined ? { button: valueBody(i.button) } : {}),
18
+ ...(i.header ? { header: 'link' in i.header ? { link: i.header.link } : { text: valueBody(i.header.text) } } : {}),
19
+ },
20
+ };
21
+ }
22
+ export class SaasElixir {
23
+ #key;
24
+ #base;
25
+ #timeoutMs;
26
+ #maxRetries;
27
+ #retryDelayMs;
28
+ constructor(options) {
29
+ const key = options?.apiKey?.trim() ?? '';
30
+ if (!KEY_PATTERN.test(key))
31
+ throw new Error('This is not a SaasElixir API key. Keys start with sxe_; make one on the API page of your account.');
32
+ this.#key = key;
33
+ this.#base = (options.baseUrl ?? DEFAULT_BASE).replace(/\/+$/, '');
34
+ this.#timeoutMs = options.timeoutMs ?? 30_000;
35
+ this.#maxRetries = Math.max(0, options.maxRetries ?? 2);
36
+ this.#retryDelayMs = options.retryDelayMs ?? 500;
37
+ }
38
+ // Keep the key out of console.log(client) and of error reports.
39
+ toJSON() { return { baseUrl: this.#base }; }
40
+ [Symbol.for('nodejs.util.inspect.custom')]() { return `SaasElixir { baseUrl: '${this.#base}' }`; }
41
+ // ------------------------------------------------------------ Messages
42
+ messages = {
43
+ /**
44
+ * Send a template message, or a text for a chat that is open. Safe to call again after a timeout: every message has a
45
+ * reference (yours, or one the SDK makes), and the same reference is never sent twice. If you retry yourself, pass the same one.
46
+ */
47
+ send: (message, o = {}) => this.#sendMessage('/api/v1/messages', message, o),
48
+ /** Where one message stands, by the `messageId` the send answered with. */
49
+ get: (messageId, o = {}) => this.#call('GET', `/api/v1/messages/${messageId}`, undefined, true, o),
50
+ /** Where one message stands, by the `reference` you sent it with. */
51
+ getByReference: (reference, o = {}) => this.#call('GET', `/api/v1/messages?reference=${encodeURIComponent(reference)}`, undefined, true, o),
52
+ /** Send to many people without a campaign. Same pace control, per-person results and early stop as campaigns.sendMany(). */
53
+ sendMany: (messages, o = {}) => this.#bulk('/api/v1/messages', messages, o),
54
+ /** Send words to someone whose chat is open (they wrote to you in the last 24 hours). */
55
+ sendText: (to, text, o = {}) => this.#sendMessage('/api/v1/messages', { to, text, reference: o.reference, channelId: o.channelId }, o),
56
+ };
57
+ // ------------------------------------------------------------ Templates and balance
58
+ /** Your number's templates, to see which are approved and how many values each needs. Pass `status: 'APPROVED'` to list only those you can send. */
59
+ templates = {
60
+ list: (q = {}, o = {}) => {
61
+ const params = new URLSearchParams();
62
+ if (q.channelId)
63
+ params.set('channelId', q.channelId);
64
+ if (q.status)
65
+ params.set('status', q.status);
66
+ const qs = params.toString();
67
+ return this.#call('GET', `/api/v1/templates${qs ? `?${qs}` : ''}`, undefined, true, o);
68
+ },
69
+ };
70
+ balance = {
71
+ /** What each of your numbers holds and whether it can send. Check before a big send. */
72
+ get: async (o = {}) => (await this.#call('GET', '/api/v1/balance', undefined, true, o)).numbers,
73
+ };
74
+ // ------------------------------------------------------------ Contacts and opt-outs
75
+ contacts = {
76
+ /** Add a person, or find the one already there; tags given are added either way. Safe to repeat. */
77
+ add: (input, o = {}) => this.#call('POST', '/api/v1/contacts', input, true, o),
78
+ /** Find a person by phone number, in any writing. Throws code "no_contact" when there is none. */
79
+ findByPhone: (phone, o = {}) => this.#call('GET', `/api/v1/contacts?phone=${encodeURIComponent(phone)}`, undefined, true, o),
80
+ get: (contactId, o = {}) => this.#call('GET', `/api/v1/contacts/${contactId}`, undefined, true, o),
81
+ /** One page of people, optionally those with a tag. */
82
+ list: (q = {}, o = {}) => {
83
+ const params = new URLSearchParams();
84
+ if (q.tag)
85
+ params.set('tag', q.tag);
86
+ if (q.limit)
87
+ params.set('limit', String(q.limit));
88
+ if (q.after)
89
+ params.set('after', String(q.after));
90
+ const qs = params.toString();
91
+ return this.#call('GET', `/api/v1/contacts${qs ? `?${qs}` : ''}`, undefined, true, o);
92
+ },
93
+ /** Every person, page after page: `for await (const c of wa.contacts.each({ tag: 'VIP' })) ...` */
94
+ each: (q = {}, o = {}) => this.#eachContact(q, o),
95
+ addTags: (contactId, tags, o = {}) => this.#call('POST', `/api/v1/contacts/${contactId}/tags`, { add: tags }, true, o),
96
+ removeTags: (contactId, tags, o = {}) => this.#call('POST', `/api/v1/contacts/${contactId}/tags`, { remove: tags }, true, o),
97
+ };
98
+ optouts = {
99
+ /** Record that someone does not want messages. Every send to them is refused from now on. Taking it back is done on the screens, by a person. */
100
+ add: (phone, o = {}) => this.#call('POST', '/api/v1/optouts', { phone }, true, o),
101
+ check: (phone, o = {}) => this.#call('GET', `/api/v1/optouts?phone=${encodeURIComponent(phone)}`, undefined, true, o),
102
+ };
103
+ // ------------------------------------------------------------ Lists of people
104
+ audiences = {
105
+ /**
106
+ * Save a list of people to send campaigns to. Any size: it is sent in pieces of 5000. Rows that are not phone numbers are not
107
+ * saved and come back in `rejected`, with their position in the list you gave. You must pass `consent: true`.
108
+ */
109
+ create: async (input, o = {}) => {
110
+ const { members, ...rest } = input;
111
+ const first = await this.#call('POST', '/api/v1/audiences', { ...rest, members: members.slice(0, MEMBERS_PER_CALL).map(memberBody) }, false, o);
112
+ const rejected = [...first.rejected];
113
+ let last = first;
114
+ for (let at = MEMBERS_PER_CALL; at < members.length; at += MEMBERS_PER_CALL) {
115
+ const more = await this.audiences.addMembers(first.id, members.slice(at, at + MEMBERS_PER_CALL), { consent: true, country: input.country, ...o });
116
+ rejected.push(...more.rejected.map((r) => ({ ...r, index: r.index + at })));
117
+ last = { ...first, members: more.members, fields: more.fields };
118
+ }
119
+ return { ...last, rejected };
120
+ },
121
+ /** Add people to a list. Someone already there is updated, not repeated. Safe to repeat. */
122
+ addMembers: (id, members, o) => this.#call('POST', `/api/v1/audiences/${id}/members`, { consent: o.consent, country: o.country, members: members.map(memberBody) }, true, o),
123
+ list: async (o = {}) => (await this.#call('GET', '/api/v1/audiences', undefined, true, o)).audiences,
124
+ get: (id, o = {}) => this.#call('GET', `/api/v1/audiences/${id}`, undefined, true, o),
125
+ };
126
+ // ------------------------------------------------------------ Campaigns to a list
127
+ /**
128
+ * Campaigns sent to a saved list, the same ones the Campaigns page makes, with the same rules (opt-outs, daily limit, wallet).
129
+ * Called "broadcasts" because "campaigns" in this API already means a label for single messages.
130
+ */
131
+ broadcasts = {
132
+ /** See who would get it, what it costs and how it reads, without making anything. */
133
+ preview: (input, o = {}) => this.#call('POST', '/api/v1/broadcasts/preview', broadcastBody(input), true, o),
134
+ /** Make a draft. Nothing is sent. */
135
+ create: (input, o = {}) => this.#call('POST', '/api/v1/broadcasts', broadcastBody(input), false, o),
136
+ /** Send a draft. `confirmCount` is the number of people you checked (`recipients` of the draft or preview): if the list changed since, it is not sent. Not retried: if it times out, look at get(). */
137
+ send: (id, confirmCount, o = {}) => this.#call('POST', `/api/v1/broadcasts/${id}/send`, { confirmCount }, false, o),
138
+ /** Send at a later time, between a minute and 60 days from now. */
139
+ schedule: (id, at, confirmCount, o = {}) => this.#call('POST', `/api/v1/broadcasts/${id}/schedule`, { at: at instanceof Date ? at.toISOString() : at, confirmCount }, false, o),
140
+ pause: (id, o = {}) => this.#call('POST', `/api/v1/broadcasts/${id}/pause`, {}, false, o),
141
+ resume: (id, o = {}) => this.#call('POST', `/api/v1/broadcasts/${id}/resume`, {}, false, o),
142
+ /** Stop for good: nobody not yet sent to will be. Messages already sent stay sent. */
143
+ cancel: (id, o = {}) => this.#call('POST', `/api/v1/broadcasts/${id}/cancel`, {}, false, o),
144
+ list: async (o = {}) => (await this.#call('GET', '/api/v1/broadcasts', undefined, true, o)).broadcasts,
145
+ /** How it is going: counts of sent, delivered, read and failed. */
146
+ get: (id, o = {}) => this.#call('GET', `/api/v1/broadcasts/${id}`, undefined, true, o),
147
+ /** One page of the people and what happened to each. Filter by `state`, for example "failed" to follow them up. */
148
+ recipients: (id, q = {}, o = {}) => {
149
+ const params = new URLSearchParams();
150
+ if (q.state)
151
+ params.set('state', q.state);
152
+ if (q.limit)
153
+ params.set('limit', String(q.limit));
154
+ if (q.after)
155
+ params.set('after', String(q.after));
156
+ const qs = params.toString();
157
+ return this.#call('GET', `/api/v1/broadcasts/${id}/recipients${qs ? `?${qs}` : ''}`, undefined, true, o);
158
+ },
159
+ /** Every person, page after page: `for await (const p of wa.broadcasts.eachRecipient(id, { state: 'failed' })) ...` */
160
+ eachRecipient: (id, q = {}, o = {}) => this.#eachRecipient(id, q, o),
161
+ /**
162
+ * Preview, make and send in one call, stopping before anything is sent when it cannot go well: a problem to fix (code "not_ready"),
163
+ * a number without enough balance ("no_balance"), or an estimate above `maxCost` ("too_costly"). Sending cannot be undone, so set `maxCost`.
164
+ */
165
+ sendNow: async (input, opts = {}) => {
166
+ const p = await this.broadcasts.preview(input, opts);
167
+ if (p.problems.length)
168
+ throw new SaasElixirError({ code: 'not_ready', httpStatus: 0, message: p.problems[0], problems: p.problems, response: p });
169
+ if (p.counts.send === 0)
170
+ throw new SaasElixirError({ code: 'nobody', httpStatus: 0, message: 'There is nobody to send to: everyone was left out.', response: p });
171
+ if (p.wallet !== null && p.cost.total > p.wallet)
172
+ throw new SaasElixirError({ code: 'no_balance', httpStatus: 0, message: `This needs about ₹${p.cost.total.toFixed(2)} and the number has ₹${p.wallet.toFixed(2)}.`, response: p });
173
+ if (opts.maxCost !== undefined && p.cost.total > opts.maxCost)
174
+ throw new SaasElixirError({ code: 'too_costly', httpStatus: 0, message: `The estimate is ₹${p.cost.total.toFixed(2)}, above your limit of ₹${opts.maxCost}.`, response: p });
175
+ const draft = await this.broadcasts.create(input, opts);
176
+ const started = await this.broadcasts.send(draft.id, draft.recipients, opts);
177
+ return { ...draft, status: started.status };
178
+ },
179
+ };
180
+ async *#eachRecipient(id, q, o) {
181
+ let after;
182
+ for (;;) {
183
+ const page = await this.broadcasts.recipients(id, { ...q, limit: 500, ...(after ? { after } : {}) }, o);
184
+ yield* page.recipients;
185
+ if (page.next === null)
186
+ return;
187
+ after = page.next;
188
+ }
189
+ }
190
+ // ------------------------------------------------------------ API campaigns
191
+ campaigns = {
192
+ /** Send under an API campaign, made on the API page. A paused campaign refuses with code "paused". */
193
+ send: (code, message, o = {}) => this.#sendMessage(`/api/v1/campaigns/${encodeURIComponent(code)}/send`, message, o),
194
+ /**
195
+ * Send under an API campaign to a whole list. Goes at a steady pace, reports each person, and stops by itself when every
196
+ * remaining message would fail the same way (no balance, plan ended, campaign paused, bad key). Never throws for one person's failure.
197
+ */
198
+ sendMany: (code, messages, o = {}) => this.#bulk(`/api/v1/campaigns/${encodeURIComponent(code)}/send`, messages, o),
199
+ };
200
+ // ------------------------------------------------------------ Chatbots
201
+ chatbots = {
202
+ list: async (o = {}) => (await this.#call('GET', '/api/v1/chatbots', undefined, true, o)).chatbots,
203
+ get: (id, o = {}) => this.#call('GET', `/api/v1/chatbots/${id}`, undefined, true, o),
204
+ /** Describe a chatbot in words. Charged to your AI wallet; never retried by the SDK. */
205
+ create: (input, o = {}) => this.#call('POST', '/api/v1/chatbots', input, false, o),
206
+ /** Change a chatbot in words. Charged to your AI wallet; never retried by the SDK. */
207
+ edit: (id, input, o = {}) => this.#call('POST', `/api/v1/chatbots/${id}/edit`, input, false, o),
208
+ /** Make the draft live. Refused with a list of problems (error.problems) when something is unfinished. */
209
+ publish: (id, o = {}) => this.#call('POST', `/api/v1/chatbots/${id}/publish`, {}, false, o),
210
+ };
211
+ // ------------------------------------------------------------ Automations
212
+ automations = {
213
+ list: async (o = {}) => (await this.#call('GET', '/api/v1/automations', undefined, true, o)).automations,
214
+ create: (input, o = {}) => this.#call('POST', '/api/v1/automations', input, false, o),
215
+ edit: (id, input, o = {}) => this.#call('POST', `/api/v1/automations/${id}/edit`, input, false, o),
216
+ publish: (id, o = {}) => this.#call('POST', `/api/v1/automations/${id}/publish`, {}, false, o),
217
+ };
218
+ /** Any other call, with the same key and error handling. Retried only when retrySafe is true. */
219
+ raw(method, path, p = {}) {
220
+ return this.#call(method, path, p.body, !!p.retrySafe, { timeoutMs: p.timeoutMs });
221
+ }
222
+ async *#eachContact(q, o) {
223
+ let after;
224
+ for (;;) {
225
+ const page = await this.contacts.list({ ...q, ...(after ? { after } : {}) }, o);
226
+ yield* page.contacts;
227
+ if (page.next === null)
228
+ return;
229
+ after = page.next;
230
+ }
231
+ }
232
+ // These refusals apply to every message that follows, so going on would only repeat them.
233
+ static #FATAL = new Set(['no_balance', 'plan_expired', 'plan_feature', 'unauthorized', 'paused', 'no_campaign', 'no_number']);
234
+ async #bulk(path, messages, o) {
235
+ const workers = Math.min(20, Math.max(1, Math.floor(o.concurrency ?? 5)));
236
+ const digits = (n) => String(n ?? '').replace(/\D/g, '');
237
+ const seen = new Set();
238
+ const items = [];
239
+ const todo = [];
240
+ messages.forEach((m, i) => {
241
+ const reference = m.reference ?? (o.referencePrefix ? `${o.referencePrefix}-${i}` : `sdk-${randomUUID()}`);
242
+ const dup = (o.dedupe ?? true) && digits(m?.to) !== '' && seen.has(digits(m.to));
243
+ if (m?.to)
244
+ seen.add(digits(m.to));
245
+ items[i] = { to: String(m?.to ?? ''), reference, outcome: 'skipped', ...(dup ? { error: { code: 'duplicate', message: 'This number is listed more than once.' } } : !m?.to ? { error: { code: 'bad_number', message: '"to" is missing.' } } : {}) };
246
+ if (!dup && m?.to)
247
+ todo.push({ at: i, m: { ...m, reference } });
248
+ });
249
+ const out = { total: messages.length, sent: 0, failed: 0, skipped: 0 };
250
+ let finished = items.length - todo.length;
251
+ let stopped;
252
+ let next = 0;
253
+ const report = (item) => { try {
254
+ o.onProgress?.(item, { total: out.total, finished, sent: out.sent, failed: out.failed });
255
+ }
256
+ catch { /* a progress callback must not stop the run */ } };
257
+ const work = async () => {
258
+ for (;;) {
259
+ if (stopped)
260
+ return;
261
+ const job = todo[next++];
262
+ if (!job)
263
+ return;
264
+ const item = items[job.at];
265
+ try {
266
+ item.result = await this.#sendMessage(path, job.m, { timeoutMs: o.timeoutMs });
267
+ item.outcome = 'sent';
268
+ out.sent += 1;
269
+ }
270
+ catch (e) {
271
+ const err = e instanceof SaasElixirError ? e : new SaasElixirError({ message: e?.message ?? 'Failed', code: 'error', httpStatus: 0 });
272
+ item.outcome = 'failed';
273
+ item.error = { code: err.code, message: err.message };
274
+ out.failed += 1;
275
+ if (_a.#FATAL.has(err.code) && !stopped)
276
+ stopped = err.code;
277
+ if (o.stopOnError && !stopped)
278
+ stopped = err.code;
279
+ }
280
+ finished += 1;
281
+ report(item);
282
+ }
283
+ };
284
+ await Promise.all(Array.from({ length: Math.min(workers, todo.length) }, work));
285
+ for (const item of items) {
286
+ if (item.outcome === 'skipped') {
287
+ if (!item.error)
288
+ item.error = { code: 'not_tried', message: `Not tried: the run stopped (${stopped}).` };
289
+ out.skipped += 1;
290
+ }
291
+ }
292
+ return { ...out, items, ...(stopped ? { stoppedBecause: stopped } : {}) };
293
+ }
294
+ #sendMessage(path, m, o) {
295
+ if (!m?.to)
296
+ throw new Error('"to" is required: the customer\'s number with its country code.');
297
+ // A reference makes a retry harmless, so sending is retried like a read.
298
+ const body = { ...m, reference: m.reference ?? `sdk-${randomUUID()}` };
299
+ return this.#call('POST', path, body, true, o);
300
+ }
301
+ async #call(method, path, body, retrySafe, o) {
302
+ const r = await this.#send(method, path, body, retrySafe, o.timeoutMs);
303
+ const failure = failureIn(r.json, r.status);
304
+ if (failure)
305
+ throw failure;
306
+ if (r.json === undefined)
307
+ throw new SaasElixirError({ message: 'SaasElixir answered with something that is not JSON.', code: 'bad_answer', httpStatus: r.status });
308
+ return r.json;
309
+ }
310
+ async #send(method, path, body, retrySafe, timeoutMs) {
311
+ const limit = timeoutMs ?? this.#timeoutMs;
312
+ const tries = retrySafe ? this.#maxRetries + 1 : 1;
313
+ for (let attempt = 1;; attempt++) {
314
+ let wait = this.#retryDelayMs * 2 ** (attempt - 1);
315
+ try {
316
+ const res = await fetch(this.#base + path, {
317
+ method,
318
+ headers: { Authorization: `Bearer ${this.#key}`, 'User-Agent': `raylong-saaselixir-node/${VERSION}`, Accept: 'application/json', ...(method === 'POST' ? { 'Content-Type': 'application/json' } : {}) },
319
+ body: method === 'POST' ? JSON.stringify(body ?? {}) : undefined,
320
+ signal: AbortSignal.timeout(limit),
321
+ });
322
+ let json;
323
+ try {
324
+ json = await res.json();
325
+ }
326
+ catch {
327
+ json = undefined;
328
+ }
329
+ const after = Number(res.headers.get('retry-after'));
330
+ const answer = { status: res.status, json, retryAfter: Number.isFinite(after) && after >= 0 ? after : null };
331
+ const busy = res.status === 429;
332
+ const down = res.status === 502 || res.status === 503 || res.status === 504;
333
+ if (!(busy || down) || attempt >= tries)
334
+ return answer;
335
+ if (busy && answer.retryAfter !== null)
336
+ wait = Math.min(answer.retryAfter * 1000, 10_000);
337
+ }
338
+ catch (e) {
339
+ const timedOut = e?.name === 'TimeoutError' || e?.name === 'AbortError';
340
+ if (attempt >= tries) {
341
+ const unsure = retrySafe ? 'Please try again.' : 'It may or may not have gone through: check before trying again.';
342
+ throw new SaasElixirError({
343
+ code: timedOut ? 'timeout' : 'network', httpStatus: 0,
344
+ message: timedOut ? `No answer from SaasElixir within ${Math.round(limit / 1000)} seconds. ${unsure}` : `Could not reach SaasElixir (${e?.message ?? 'network error'}). ${unsure}`,
345
+ });
346
+ }
347
+ }
348
+ await new Promise((ok) => setTimeout(ok, wait));
349
+ }
350
+ }
351
+ }
352
+ _a = SaasElixir;
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Every failure comes out as this one error.
3
+ *
4
+ * code: SaasElixir's own code when it refused the call (for example "no_balance", "opted_out", "template_not_found",
5
+ * "plan_expired", "plan_feature", "bad_number", "paused"), "unauthorized" for a missing, wrong or revoked key, or
6
+ * "timeout" / "network" when no answer came back.
7
+ *
8
+ * Sending a message is safe to try again after a timeout: the SDK gives every message a reference, and the same reference
9
+ * is never sent twice. Building a chatbot or automation is not retried by the SDK, because each build is charged.
10
+ */
11
+ export declare class SaasElixirError extends Error {
12
+ readonly name = "SaasElixirError";
13
+ readonly code: string;
14
+ /** HTTP status of the answer; 0 when none came back. */
15
+ readonly httpStatus: number;
16
+ /** The answer as received, for logging. */
17
+ readonly response: unknown;
18
+ /** For a refused publish: what to fix first. */
19
+ readonly problems: string[];
20
+ constructor(p: {
21
+ message: string;
22
+ code: string;
23
+ httpStatus: number;
24
+ response?: unknown;
25
+ problems?: string[];
26
+ });
27
+ }
28
+ export declare function failureIn(body: unknown, httpStatus: number): SaasElixirError | null;
@@ -0,0 +1,36 @@
1
+ /**
2
+ * Every failure comes out as this one error.
3
+ *
4
+ * code: SaasElixir's own code when it refused the call (for example "no_balance", "opted_out", "template_not_found",
5
+ * "plan_expired", "plan_feature", "bad_number", "paused"), "unauthorized" for a missing, wrong or revoked key, or
6
+ * "timeout" / "network" when no answer came back.
7
+ *
8
+ * Sending a message is safe to try again after a timeout: the SDK gives every message a reference, and the same reference
9
+ * is never sent twice. Building a chatbot or automation is not retried by the SDK, because each build is charged.
10
+ */
11
+ export class SaasElixirError extends Error {
12
+ name = 'SaasElixirError';
13
+ code;
14
+ /** HTTP status of the answer; 0 when none came back. */
15
+ httpStatus;
16
+ /** The answer as received, for logging. */
17
+ response;
18
+ /** For a refused publish: what to fix first. */
19
+ problems;
20
+ constructor(p) {
21
+ super(p.message);
22
+ this.code = p.code;
23
+ this.httpStatus = p.httpStatus;
24
+ this.response = p.response;
25
+ this.problems = p.problems ?? [];
26
+ }
27
+ }
28
+ export function failureIn(body, httpStatus) {
29
+ if (httpStatus < 400)
30
+ return null;
31
+ const b = (body && typeof body === 'object' ? body : {});
32
+ const message = typeof b.error === 'string' && b.error ? b.error : `SaasElixir answered HTTP ${httpStatus}`;
33
+ const code = typeof b.code === 'string' && b.code ? b.code : httpStatus === 401 ? 'unauthorized' : httpStatus === 404 ? 'not_found' : httpStatus === 429 ? 'rate_limited' : httpStatus >= 500 ? 'server_error' : 'refused';
34
+ const problems = Array.isArray(b.problems) ? b.problems.map(String) : [];
35
+ return new SaasElixirError({ message, code, httpStatus, response: body, problems });
36
+ }
@@ -0,0 +1,6 @@
1
+ export { SaasElixir, VERSION } from './client.js';
2
+ export type { SaasElixirOptions } from './client.js';
3
+ export { SaasElixirError } from './errors.js';
4
+ export { field, text } from './values.js';
5
+ export { constructEvent, verifySignature, signBody, SIGNATURE_HEADER } from './webhooks.js';
6
+ export type * from './types.js';
@@ -0,0 +1,4 @@
1
+ export { SaasElixir, VERSION } from './client.js';
2
+ export { SaasElixirError } from './errors.js';
3
+ export { field, text } from './values.js';
4
+ export { constructEvent, verifySignature, signBody, SIGNATURE_HEADER } from './webhooks.js';