usebecky 0.0.0-stage → 0.2.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 (135) hide show
  1. package/README.md +701 -2
  2. package/dist/analytics/client.d.ts +219 -0
  3. package/dist/analytics/client.js +923 -0
  4. package/dist/analytics/cmp.d.ts +20 -0
  5. package/dist/analytics/cmp.js +166 -0
  6. package/dist/analytics/context.d.ts +29 -0
  7. package/dist/analytics/context.js +97 -0
  8. package/dist/auth/client.d.ts +401 -0
  9. package/dist/auth/client.js +1081 -0
  10. package/dist/auth/webauthn.d.ts +18 -0
  11. package/dist/auth/webauthn.js +138 -0
  12. package/dist/cli/ai.d.ts +54 -0
  13. package/dist/cli/ai.js +202 -0
  14. package/dist/cli/analytics.d.ts +53 -0
  15. package/dist/cli/analytics.js +357 -0
  16. package/dist/cli/config.d.ts +75 -0
  17. package/dist/cli/config.js +718 -0
  18. package/dist/cli/db.d.ts +48 -0
  19. package/dist/cli/db.js +215 -0
  20. package/dist/cli/deploy-api.d.ts +168 -0
  21. package/dist/cli/deploy-api.js +177 -0
  22. package/dist/cli/deploy-ci.d.ts +15 -0
  23. package/dist/cli/deploy-ci.js +54 -0
  24. package/dist/cli/deploy-detect.d.ts +64 -0
  25. package/dist/cli/deploy-detect.js +249 -0
  26. package/dist/cli/deploy-files.d.ts +112 -0
  27. package/dist/cli/deploy-files.js +778 -0
  28. package/dist/cli/deploy.d.ts +10 -0
  29. package/dist/cli/deploy.js +430 -0
  30. package/dist/cli/emails.d.ts +29 -0
  31. package/dist/cli/emails.js +122 -0
  32. package/dist/cli/framework.d.ts +135 -0
  33. package/dist/cli/framework.js +459 -0
  34. package/dist/cli/functions.d.ts +59 -0
  35. package/dist/cli/functions.js +426 -0
  36. package/dist/cli/hosting.d.ts +4 -0
  37. package/dist/cli/hosting.js +532 -0
  38. package/dist/cli/index.d.ts +2 -0
  39. package/dist/cli/index.js +9 -0
  40. package/dist/cli/payments.d.ts +35 -0
  41. package/dist/cli/payments.js +176 -0
  42. package/dist/cli/push.d.ts +36 -0
  43. package/dist/cli/push.js +172 -0
  44. package/dist/cli/run.d.ts +65 -0
  45. package/dist/cli/run.js +850 -0
  46. package/dist/cli/social.d.ts +52 -0
  47. package/dist/cli/social.js +532 -0
  48. package/dist/cli/tokens.d.ts +28 -0
  49. package/dist/cli/tokens.js +114 -0
  50. package/dist/cli/ui.d.ts +38 -0
  51. package/dist/cli/ui.js +140 -0
  52. package/dist/client.d.ts +94 -0
  53. package/dist/client.js +156 -0
  54. package/dist/db/query.d.ts +162 -0
  55. package/dist/db/query.js +336 -0
  56. package/dist/db/types.d.ts +93 -0
  57. package/dist/db/types.js +4 -0
  58. package/dist/forms/client.d.ts +65 -0
  59. package/dist/forms/client.js +106 -0
  60. package/dist/functions/client.d.ts +37 -0
  61. package/dist/functions/client.js +76 -0
  62. package/dist/index.d.ts +17 -0
  63. package/dist/index.js +16 -0
  64. package/dist/lib/dashboard-paths.d.ts +4 -0
  65. package/dist/lib/dashboard-paths.js +8 -0
  66. package/dist/lib/env.d.ts +9 -0
  67. package/dist/lib/env.js +55 -0
  68. package/dist/lib/errors.d.ts +22 -0
  69. package/dist/lib/errors.js +90 -0
  70. package/dist/lib/hosted.d.ts +2 -0
  71. package/dist/lib/hosted.js +7 -0
  72. package/dist/lib/http.d.ts +59 -0
  73. package/dist/lib/http.js +172 -0
  74. package/dist/lib/jwt.d.ts +1 -0
  75. package/dist/lib/jwt.js +31 -0
  76. package/dist/lib/locale.d.ts +12 -0
  77. package/dist/lib/locale.js +51 -0
  78. package/dist/lib/pkce.d.ts +20 -0
  79. package/dist/lib/pkce.js +124 -0
  80. package/dist/lib/storage-adapter.d.ts +15 -0
  81. package/dist/lib/storage-adapter.js +91 -0
  82. package/dist/lib/types.d.ts +339 -0
  83. package/dist/lib/types.js +1 -0
  84. package/dist/newsletter/client.d.ts +140 -0
  85. package/dist/newsletter/client.js +85 -0
  86. package/dist/payments/client.d.ts +352 -0
  87. package/dist/payments/client.js +323 -0
  88. package/dist/push/client.d.ts +110 -0
  89. package/dist/push/client.js +179 -0
  90. package/dist/realtime/client.d.ts +131 -0
  91. package/dist/realtime/client.js +513 -0
  92. package/dist/server/analytics.d.ts +176 -0
  93. package/dist/server/analytics.js +49 -0
  94. package/dist/server/cache.d.ts +74 -0
  95. package/dist/server/cache.js +154 -0
  96. package/dist/server/emails.d.ts +142 -0
  97. package/dist/server/emails.js +123 -0
  98. package/dist/server/events.d.ts +357 -0
  99. package/dist/server/events.js +219 -0
  100. package/dist/server/functions.d.ts +40 -0
  101. package/dist/server/functions.js +1 -0
  102. package/dist/server/http-utils.d.ts +10 -0
  103. package/dist/server/http-utils.js +115 -0
  104. package/dist/server/index.d.ts +195 -0
  105. package/dist/server/index.js +314 -0
  106. package/dist/server/payments.d.ts +218 -0
  107. package/dist/server/payments.js +150 -0
  108. package/dist/server/push.d.ts +85 -0
  109. package/dist/server/push.js +37 -0
  110. package/dist/server/usage.d.ts +43 -0
  111. package/dist/server/usage.js +8 -0
  112. package/dist/storage/client.d.ts +143 -0
  113. package/dist/storage/client.js +224 -0
  114. package/package.json +52 -4
  115. package/skill/usebecky/SKILL.md +339 -0
  116. package/skill/usebecky/references/access-rules.md +307 -0
  117. package/skill/usebecky/references/addons.md +68 -0
  118. package/skill/usebecky/references/analytics.md +166 -0
  119. package/skill/usebecky/references/android.md +434 -0
  120. package/skill/usebecky/references/auth.md +379 -0
  121. package/skill/usebecky/references/cache.md +51 -0
  122. package/skill/usebecky/references/components.md +127 -0
  123. package/skill/usebecky/references/emails.md +105 -0
  124. package/skill/usebecky/references/expo.md +147 -0
  125. package/skill/usebecky/references/functions.md +99 -0
  126. package/skill/usebecky/references/hosting.md +119 -0
  127. package/skill/usebecky/references/http-api.md +233 -0
  128. package/skill/usebecky/references/ios.md +355 -0
  129. package/skill/usebecky/references/payments.md +493 -0
  130. package/skill/usebecky/references/realtime.md +143 -0
  131. package/skill/usebecky/references/scheduled-jobs.md +82 -0
  132. package/skill/usebecky/references/sdk.md +838 -0
  133. package/skill/usebecky/references/storage.md +210 -0
  134. package/skill/usebecky/references/templates.md +191 -0
  135. package/skill/usebecky/references/wordpress.md +87 -0
@@ -0,0 +1,49 @@
1
+ // Visitor analytics reports from your server (secret key): the dashboard's numbers, for one site or the whole project.
2
+ //
3
+ // await baas.analytics.overview({ range: '30d', filters: { hostname: 'shop.example.com' } }) // KPIs + daily chart
4
+ // await baas.analytics.report('pages', { range: '7d', filters: { hostname: 'shop.example.com' } }) // top pages
5
+ // await baas.analytics.timeseries({ metric: 'visitors', dimension: 'channels' }) // one line per channel
6
+ //
7
+ // A platform that hosts a site per customer shows each customer their own numbers with `filters: { hostname }`.
8
+ // Never in a browser: the secret key reads every site's numbers. Endpoints: GET /analytics/v1/overview, /reports,
9
+ // /timeseries (docs/API.md "Analytics").
10
+ import { UseBeckyError } from "../lib/errors.js";
11
+ const day = (v) => (v instanceof Date ? v.toISOString().slice(0, 10) : v);
12
+ /** Query parameters without the empty ones (a filter with several values repeats: `country=DE&country=AT`). */
13
+ function query(values) {
14
+ const out = [];
15
+ for (const [k, v] of Object.entries(values)) {
16
+ if (v === undefined || v === null || v === '')
17
+ continue;
18
+ for (const one of Array.isArray(v) ? v : [v])
19
+ out.push([k, String(one)]);
20
+ }
21
+ return out;
22
+ }
23
+ /** The period and filters as query parameters. */
24
+ function periodQuery(o = {}) {
25
+ return query({ range: o.range, from: day(o.from), to: day(o.to), tz: o.tz, compare: o.compare ? 'previous' : undefined, ...(o.filters ?? {}) });
26
+ }
27
+ export function createServerAnalytics(http) {
28
+ const get = async (path, query) => {
29
+ const res = await http.request(path, { token: null, query });
30
+ return res.error ? { data: null, error: res.error } : { data: res.data, error: null };
31
+ };
32
+ return {
33
+ overview: (options) => get('/analytics/v1/overview', periodQuery(options)),
34
+ async report(dimension, options = {}) {
35
+ if (!dimension)
36
+ return { data: null, error: new UseBeckyError({ code: 'invalid_input', message: "Say which report, like 'pages' or 'countries'.", status: 0 }) };
37
+ const res = await get('/analytics/v1/reports', [
38
+ ...periodQuery(options),
39
+ ...query({ dimension, limit: options.limit, sort: options.sort, dir: options.dir, q: options.search, cursor: options.cursor }),
40
+ ]);
41
+ if (res.error)
42
+ return res;
43
+ // The server names the rows after the report ({ pages: [...] }); `rows` is the same list under a fixed name.
44
+ const body = res.data;
45
+ return { data: { ...body, rows: body[dimension] ?? [] }, error: null };
46
+ },
47
+ timeseries: (options = {}) => get('/analytics/v1/timeseries', [...periodQuery(options), ...query({ metric: options.metric, dimension: options.dimension, limit: options.limit })]),
48
+ };
49
+ }
@@ -0,0 +1,74 @@
1
+ import { UseBeckyError } from '../lib/errors.ts';
2
+ import type { HttpClient } from '../lib/http.ts';
3
+ /** Seconds (600) or text like `'30s'`, `'10m'`, `'2h'`, `'7d'`. */
4
+ export type Duration = number | string;
5
+ export interface CacheSetOptions {
6
+ /** How long the value is kept: seconds or text like `'10m'`, `'1h'`, `'7d'` (at most 30 days). Default `'1h'`. */
7
+ ttl?: Duration;
8
+ }
9
+ export interface RateLimitResult {
10
+ /** This try may go ahead. */
11
+ allowed: boolean;
12
+ /** The `max` you passed. */
13
+ limit: number;
14
+ /** Tries left in this window (0 when refused). */
15
+ remaining: number;
16
+ /** When the window ends and the count starts again. */
17
+ resetAt: Date;
18
+ /** Seconds until a refused caller may try again (0 when allowed). Handy for a `Retry-After` header. */
19
+ retryAfter: number;
20
+ /** Set when the cache couldn't be asked. The try was then refused (`allowed: false`) or let through, following
21
+ * `onError` (see LimitOptions). */
22
+ error?: UseBeckyError;
23
+ }
24
+ export interface LimitOptions {
25
+ /** What to do when the cache can't be asked. Left out: let the try through only when the cache is down or
26
+ * unreachable (a 5xx other than 507, or the network: an outage never locks users out); refuse on everything else
27
+ * (requests or cache memory used up, a wrong or publishable key). `'refuse'`: refuse on every error. `'allow'`: let
28
+ * every try through. A project that isn't on Business is always let through. */
29
+ onError?: 'refuse' | 'allow';
30
+ }
31
+ export interface ServerCache {
32
+ /**
33
+ * The value saved under `key`, or `null` when there is none (never saved, expired or deleted).
34
+ *
35
+ * ```ts
36
+ * const weather = await baas.cache.get<Weather>('weather:berlin')
37
+ * ```
38
+ */
39
+ get<T = unknown>(key: string): Promise<T | null>;
40
+ /**
41
+ * Save any JSON value (up to 1 MB) under `key` for `ttl` (default 1 hour). Answers `true` when it was saved.
42
+ *
43
+ * ```ts
44
+ * await baas.cache.set('weather:berlin', data, { ttl: '10m' })
45
+ * ```
46
+ */
47
+ set(key: string, value: unknown, options?: CacheSetOptions): Promise<boolean>;
48
+ /** Remove `key`. Answers `true` when something was removed. */
49
+ delete(key: string): Promise<boolean>;
50
+ /**
51
+ * The cached value, or else run `compute`, save its result for `ttl` and return it. The usual way to cache:
52
+ *
53
+ * ```ts
54
+ * const weather = await baas.cache.getOrSet('weather:berlin', () => fetchWeather('Berlin'), { ttl: '10m' })
55
+ * ```
56
+ * A result of `null` or `undefined` is returned but not saved.
57
+ */
58
+ getOrSet<T>(key: string, compute: () => T | Promise<T>, options?: CacheSetOptions): Promise<T>;
59
+ /**
60
+ * Count a try and say whether it is allowed: at most `max` tries (1 to 1,000,000) per `window` for each `key`. The
61
+ * window starts with the first try; refused tries don't count. When the cache can't be asked, the answer has an
62
+ * `error` and follows `onError` (by default: let through only when the cache is down or unreachable, refused
63
+ * otherwise).
64
+ *
65
+ * ```ts
66
+ * const { allowed, retryAfter } = await baas.cache.limit(`signup:${ip}`, 5, '1h')
67
+ * if (!allowed) return res.status(429).set('Retry-After', String(retryAfter)).send('Too many tries. Try again later.')
68
+ * ```
69
+ */
70
+ limit(key: string, max: number, window: Duration, options?: LimitOptions): Promise<RateLimitResult>;
71
+ }
72
+ /** Seconds from a duration, or null. */
73
+ export declare function durationSeconds(v: unknown): number | null;
74
+ export declare function createCache(http: HttpClient): ServerCache;
@@ -0,0 +1,154 @@
1
+ // The built-in cache, from your server or a Function (secret key; Business plan):
2
+ // baas.cache.set(key, value, { ttl }) → PUT /cache/v1/keys/:key
3
+ // baas.cache.get(key) → GET /cache/v1/keys/:key
4
+ // baas.cache.delete(key) → DELETE /cache/v1/keys/:key
5
+ // baas.cache.getOrSet(key, compute) → get, and on a miss compute + set
6
+ // baas.cache.limit(key, max, window) → POST /cache/v1/limit
7
+ //
8
+ // A cache must never take your app down: when the cache can't be reached (or the project isn't on Business), get()
9
+ // answers null and set() and delete() answer false, each with a console warning (at most once a minute per problem).
10
+ // limit() is a security check. When the cache is simply down or unreachable (a 5xx like 503, or the network), the try
11
+ // goes through, so an outage never locks your users out. Every other error REFUSES the try: reasons someone could cause
12
+ // on purpose (the project's requests used up: 429, the cache memory full: 507), so an attacker never gets unlimited
13
+ // tries that way, and configuration mistakes (400, 401, 403: a wrong key, a publishable key), so someone notices.
14
+ // { onError: 'refuse' } or { onError: 'allow' } picks one behaviour for every error. A project that isn't on Business
15
+ // (plan_required) is always let through, so a downgrade never locks people out. Only wrong arguments throw, so you find
16
+ // them while you build.
17
+ import { UseBeckyError } from "../lib/errors.js";
18
+ const MAX_KEY_BYTES = 512;
19
+ const MAX_LIMIT = 1_000_000;
20
+ const UNITS = { s: 1, sec: 1, second: 1, seconds: 1, m: 60, min: 60, minute: 60, minutes: 60, h: 3600, hour: 3600, hours: 3600, d: 86400, day: 86400, days: 86400 };
21
+ function invalid(message) {
22
+ return new UseBeckyError({ code: 'invalid_input', message, status: 0 });
23
+ }
24
+ /** Seconds from a duration, or null. */
25
+ export function durationSeconds(v) {
26
+ if (typeof v === 'number')
27
+ return Number.isFinite(v) && v > 0 ? Math.ceil(v) : null;
28
+ if (typeof v !== 'string')
29
+ return null;
30
+ const m = /^\s*(\d+(?:\.\d+)?)\s*([a-z]*)\s*$/i.exec(v);
31
+ const mult = m ? UNITS[m[2].toLowerCase() || 's'] : undefined;
32
+ if (!m || !mult)
33
+ return null;
34
+ const n = Number(m[1]) * mult;
35
+ return n > 0 ? Math.ceil(n) : null;
36
+ }
37
+ function checkKey(method, key) {
38
+ if (typeof key !== 'string' || key === '')
39
+ throw invalid(`baas.cache.${method}() needs a key: a short text like 'weather:berlin'.`);
40
+ if (new TextEncoder().encode(key).length > MAX_KEY_BYTES)
41
+ throw invalid(`baas.cache.${method}(): the key is longer than ${MAX_KEY_BYTES} bytes. Use a shorter one.`);
42
+ // eslint-disable-next-line no-control-regex
43
+ if (/[\u0000-\u001f\u007f]/.test(key))
44
+ throw invalid(`baas.cache.${method}(): the key contains a control character (like a line break).`);
45
+ return key;
46
+ }
47
+ function checkDuration(method, what, v) {
48
+ const s = durationSeconds(v);
49
+ if (s === null)
50
+ throw invalid(`baas.cache.${method}(): "${String(v)}" is not a duration. Use seconds (600) or text like '10m', '1h' or '7d'.`);
51
+ if (s > 30 * 86400)
52
+ throw invalid(`baas.cache.${method}(): the ${what} can be at most 30 days.`);
53
+ return s;
54
+ }
55
+ const lastWarn = new Map();
56
+ function warn(method, err) {
57
+ const now = Date.now();
58
+ if (now - (lastWarn.get(err.code) ?? 0) < 60_000)
59
+ return;
60
+ lastWarn.set(err.code, now);
61
+ try {
62
+ console.warn(`[usebecky] baas.cache.${method}() did not work, so your code carried on without the cache: ${err.message}${err.hint ? ` ${err.hint}` : ''}`);
63
+ }
64
+ catch { }
65
+ }
66
+ export function createCache(http) {
67
+ const path = (key) => `/cache/v1/keys/${encodeURIComponent(key)}`;
68
+ const cache = {
69
+ async get(key) {
70
+ checkKey('get', key);
71
+ const res = await http.request(path(key), { token: null });
72
+ if (res.error) {
73
+ warn('get', res.error);
74
+ return null;
75
+ }
76
+ return res.data?.found ? (res.data.value ?? null) : null;
77
+ },
78
+ async set(key, value, options = {}) {
79
+ checkKey('set', key);
80
+ if (value === undefined)
81
+ throw invalid('baas.cache.set() needs a value to save. To remove a key, use baas.cache.delete(key).');
82
+ if (typeof value === 'function' || typeof value === 'symbol')
83
+ throw invalid('baas.cache.set() saves JSON values (text, numbers, true/false, objects, lists), not functions.');
84
+ let body;
85
+ try {
86
+ body = JSON.stringify({ value, ttl: options.ttl === undefined ? undefined : checkDuration('set', 'ttl', options.ttl) });
87
+ }
88
+ catch (err) {
89
+ if (err instanceof UseBeckyError)
90
+ throw err;
91
+ throw invalid(`baas.cache.set() can't turn this value into JSON (${err.message}). Save plain objects, lists, text and numbers.`);
92
+ }
93
+ const res = await http.request(path(key), { method: 'PUT', token: null, body, headers: { 'content-type': 'application/json' } });
94
+ if (res.error) {
95
+ warn('set', res.error);
96
+ return false;
97
+ }
98
+ return true;
99
+ },
100
+ async delete(key) {
101
+ checkKey('delete', key);
102
+ const res = await http.request(path(key), { method: 'DELETE', token: null });
103
+ if (res.error) {
104
+ warn('delete', res.error);
105
+ return false;
106
+ }
107
+ return !!res.data?.deleted;
108
+ },
109
+ async getOrSet(key, compute, options = {}) {
110
+ checkKey('getOrSet', key);
111
+ if (typeof compute !== 'function')
112
+ throw invalid('baas.cache.getOrSet() needs a function that makes the value, like () => fetchWeather().');
113
+ if (options.ttl !== undefined)
114
+ checkDuration('getOrSet', 'ttl', options.ttl);
115
+ const hit = await cache.get(key);
116
+ if (hit !== null)
117
+ return hit;
118
+ const fresh = await compute();
119
+ if (fresh !== undefined && fresh !== null)
120
+ await cache.set(key, fresh, options);
121
+ return fresh;
122
+ },
123
+ async limit(key, max, window, options = {}) {
124
+ checkKey('limit', key);
125
+ if (typeof max !== 'number' || !Number.isInteger(max) || max < 1 || max > MAX_LIMIT)
126
+ throw invalid('baas.cache.limit() needs the number of tries as a whole number from 1 to 1,000,000, like limit(key, 5, \'1h\').');
127
+ const seconds = checkDuration('limit', 'window', window);
128
+ const onError = options.onError;
129
+ if (onError !== undefined && onError !== 'refuse' && onError !== 'allow')
130
+ throw invalid("baas.cache.limit(): onError must be 'refuse' or 'allow'.");
131
+ const res = await http.request('/cache/v1/limit', {
132
+ method: 'POST',
133
+ token: null,
134
+ body: { key, limit: max, window: seconds },
135
+ });
136
+ if (res.error || !res.data) {
137
+ const error = res.error ?? new UseBeckyError({ code: 'invalid_response', message: 'The cache sent an empty answer.', status: res.status });
138
+ warn('limit', error);
139
+ // Not on Business: never lock anyone out because of a plan change. The cache down or unreachable (a 5xx other
140
+ // than 507 "full", or no answer at all): let the try through. Anything else (429/507 someone could cause on
141
+ // purpose, 400/401/403 configuration mistakes someone must notice): refuse.
142
+ const outage = error.status === 0 || (error.status >= 500 && error.status !== 507);
143
+ const allow = error.code === 'plan_required' || (onError === undefined ? outage : onError === 'allow');
144
+ const retryAfter = Math.min(seconds, 60);
145
+ return allow
146
+ ? { allowed: true, limit: max, remaining: max, resetAt: new Date(Date.now() + seconds * 1000), retryAfter: 0, error }
147
+ : { allowed: false, limit: max, remaining: 0, resetAt: new Date(Date.now() + retryAfter * 1000), retryAfter, error };
148
+ }
149
+ const d = res.data;
150
+ return { allowed: d.allowed, limit: d.limit, remaining: d.remaining, resetAt: new Date(d.reset_at), retryAfter: d.retry_after_seconds };
151
+ },
152
+ };
153
+ return cache;
154
+ }
@@ -0,0 +1,142 @@
1
+ import { UseBeckyError } from '../lib/errors.ts';
2
+ import type { HttpClient } from '../lib/http.ts';
3
+ import type { Result } from '../lib/types.ts';
4
+ /** A file to attach. Up to 10 files per email, 5 MB in total on Free and 10 MB on paid plans. */
5
+ export interface EmailAttachment {
6
+ /** The file name people see, like `'invoice-1042.pdf'`. Programs and scripts (.exe, .js, .sh, ...) are refused. */
7
+ filename: string;
8
+ /** The file: a Buffer / Uint8Array / ArrayBuffer, or text that is already base64. */
9
+ content: Uint8Array | ArrayBuffer | string;
10
+ /** The file type, like `'application/pdf'`. Default: guessed from the file name. */
11
+ contentType?: string;
12
+ }
13
+ /** A label you put on an email, like `{ name: 'category', value: 'receipt' }`. Shown in Emails → Sent and sent with email events. */
14
+ export interface EmailTag {
15
+ name: string;
16
+ value: string;
17
+ }
18
+ export interface SendEmailOptions {
19
+ /** One recipient address. Call `send` once per person (or use `batch`), so nobody sees the other addresses. */
20
+ to: string;
21
+ /**
22
+ * The id of an email you made in Dashboard → Emails → New email, like `'order-shipped'`. It brings its own
23
+ * subject and text (in the person's language, if you translated it); fill its blanks with `data`.
24
+ */
25
+ template?: string;
26
+ /** Values for the template's blanks: `{ order_id: '1042' }` fills `{{order_id}}`. Every blank the template uses must get a value. */
27
+ data?: Record<string, string | number | boolean | null>;
28
+ /** Subject line (one line, up to 300 characters). Needed unless you use `template`. */
29
+ subject?: string;
30
+ /** Plain text. Without `html`, it becomes the body of your branded layout: blank lines start new paragraphs, links become clickable. */
31
+ text?: string;
32
+ /** Your own HTML, sent exactly as it is (no logo, no footer: add your own). Leave it out to use your branded layout. */
33
+ html?: string;
34
+ /** Big title above the text (branded layout only). */
35
+ heading?: string;
36
+ /** Text of a button below the text (branded layout only). Needs `buttonUrl`. */
37
+ buttonText?: string;
38
+ /** Where the button goes: a full https:// address. Needs `buttonText`. */
39
+ buttonUrl?: string;
40
+ /** Where replies go. Default: the reply-to address in Dashboard → Emails → Sender, if set. */
41
+ replyTo?: string;
42
+ /**
43
+ * The email's language, like `'de'` or `'pt-BR'`. With `template`, it picks that language's text. Without one,
44
+ * it picks the language of the words usebecky adds around your text (like "Button not working? Copy this link
45
+ * into your browser:" and the footer links); your own `subject`, `text` and `html` are sent as you wrote them.
46
+ * Default: your project's default language.
47
+ */
48
+ locale?: string;
49
+ /** Files to attach (see EmailAttachment for the limits). */
50
+ attachments?: EmailAttachment[];
51
+ /** Send it later: a Date or an ISO time, up to 7 days ahead. Until then its status is `'scheduled'` and `cancel(id)` stops it. */
52
+ sendAt?: Date | string;
53
+ /** Up to 10 labels, like `[{ name: 'category', value: 'receipt' }]`. */
54
+ tags?: EmailTag[];
55
+ /**
56
+ * A unique key for this email, like `'order-1042-shipped'` (up to 200 characters), sent as the
57
+ * `Idempotency-Key` header. Sending again with the same key within 24 hours sends nothing new and answers
58
+ * like the first time, so a retry after a timeout never emails someone twice.
59
+ */
60
+ idempotencyKey?: string;
61
+ }
62
+ /** Where an email is now. `'sent'` = handed to the email provider; the rest come from the receiving side. */
63
+ export type EmailStatus = 'scheduled' | 'sent' | 'delivered' | 'delayed' | 'bounced' | 'complained' | 'suppressed' | 'failed' | 'cancelled' | (string & {});
64
+ export interface SentEmail {
65
+ /** The email's id: use it with `get(id)` / `cancel(id)`; it is also the entry in Dashboard → Emails → Sent. */
66
+ id: string;
67
+ /** Short code like `'UB-7F3A9C2K'`, printed in the email's footer. Search for it in Dashboard → Emails → Sent. */
68
+ reference?: string;
69
+ /** `'scheduled'` with `sendAt`, else usually `'sent'`. Present when the server says it. */
70
+ status?: EmailStatus;
71
+ }
72
+ /** One email in a `batch` answer: `id` when it was accepted, `error` when it wasn't. Same order as you sent them. */
73
+ export interface BatchEmailResult {
74
+ id: string | null;
75
+ /** The email's short code (see SentEmail.reference). */
76
+ reference?: string;
77
+ status?: EmailStatus;
78
+ error: UseBeckyError | null;
79
+ }
80
+ /** Something that happened to an email, like `{ type: 'delivered', at: '2026-11-15T10:00:02Z' }`. */
81
+ export interface EmailEvent {
82
+ type: string;
83
+ at: string;
84
+ /** A plain-English reason for bounces, complaints and failures. */
85
+ reason?: string | null;
86
+ }
87
+ /** What `get(id)` returns. */
88
+ export interface EmailDetails {
89
+ id: string;
90
+ /** Short code like `'UB-7F3A9C2K'`, printed in the email's footer. */
91
+ reference?: string;
92
+ status: EmailStatus;
93
+ /** The recipient, shortened for privacy, like `'a***@example.com'`. */
94
+ to: string;
95
+ subject: string | null;
96
+ /** Your template's id, or null. */
97
+ template: string | null;
98
+ locale: string | null;
99
+ tags: EmailTag[];
100
+ /** A plain-English reason when it bounced, was suppressed or failed. */
101
+ reason: string | null;
102
+ created_at: string;
103
+ /** When a scheduled email goes out. */
104
+ send_at: string | null;
105
+ /** Everything that happened to it, oldest first. */
106
+ events: EmailEvent[];
107
+ [key: string]: unknown;
108
+ }
109
+ export interface ServerEmails {
110
+ /**
111
+ * Send an email to one person from your server: your own words, or a template you made in the dashboard.
112
+ *
113
+ * ```ts
114
+ * const { data, error } = await baas.emails.send({ to: 'ada@example.com', subject: 'Your order shipped', text: 'It is on its way!' })
115
+ * const sent = await baas.emails.send({ to: 'ada@example.com', template: 'order-shipped', data: { order_id: '1042' } })
116
+ * // data: { id: '…' } (the id of the entry in Dashboard → Emails → Sent)
117
+ * ```
118
+ */
119
+ send(options: SendEmailOptions): Promise<Result<SentEmail>>;
120
+ /**
121
+ * Send up to 100 emails in one request (each counts toward your limits). The answer has one result per email,
122
+ * in the same order: an `id`, or an `error` for that email only.
123
+ *
124
+ * ```ts
125
+ * const { data } = await baas.emails.batch(users.map((u) => ({ to: u.email, template: 'weekly-report', data: { name: u.name } })))
126
+ * // data.results: [{ id: '…', error: null }, { id: null, error: UseBeckyError }]
127
+ * ```
128
+ */
129
+ batch(emails: SendEmailOptions[], options?: {
130
+ idempotencyKey?: string;
131
+ }): Promise<Result<{
132
+ results: BatchEmailResult[];
133
+ }>>;
134
+ /** Where an email is now (`status`) and everything that happened to it (`events`). */
135
+ get(id: string): Promise<Result<EmailDetails>>;
136
+ /** Stop a scheduled email (one sent with `sendAt`) before it goes out. */
137
+ cancel(id: string): Promise<Result<{
138
+ id: string;
139
+ status: EmailStatus;
140
+ }>>;
141
+ }
142
+ export declare function createEmails(http: HttpClient): ServerEmails;
@@ -0,0 +1,123 @@
1
+ // Transactional email from your server (secret key only):
2
+ // baas.emails.send({...}) → POST /email/v1/send
3
+ // baas.emails.batch([...]) → POST /email/v1/batch (up to 100 at once)
4
+ // baas.emails.get(id) → GET /email/v1/emails/:id (status + delivery events)
5
+ // baas.emails.cancel(id) → DELETE /email/v1/emails/:id (only while scheduled)
6
+ // Emails use your project's brand, footer and sender (Dashboard → Emails) and show up in Emails → Sent.
7
+ import { UseBeckyError, errorFromResponse } from "../lib/errors.js";
8
+ import { localeField } from "../lib/locale.js";
9
+ function notAnObject() {
10
+ return new UseBeckyError({ code: 'invalid_email', message: 'Pass the email as an object, like { to, subject, text }.', status: 0 });
11
+ }
12
+ function base64(content) {
13
+ if (typeof content === 'string')
14
+ return content;
15
+ if (content instanceof ArrayBuffer)
16
+ return Buffer.from(content).toString('base64');
17
+ return Buffer.from(content.buffer, content.byteOffset, content.byteLength).toString('base64');
18
+ }
19
+ /** The email as the API wants it (snake_case; `idempotencyKey` is a header, not part of the body). */
20
+ function wire(o, where) {
21
+ return {
22
+ to: o.to,
23
+ template: o.template,
24
+ data: o.data,
25
+ subject: o.subject,
26
+ text: o.text,
27
+ html: o.html,
28
+ heading: o.heading,
29
+ button_text: o.buttonText,
30
+ button_url: o.buttonUrl,
31
+ reply_to: o.replyTo,
32
+ ...localeField(o.locale, where),
33
+ attachments: o.attachments?.map((a) => ({ filename: a?.filename, content: a?.content == null ? a?.content : base64(a.content), content_type: a?.contentType })),
34
+ send_at: o.sendAt instanceof Date ? o.sendAt.toISOString() : o.sendAt,
35
+ tags: o.tags,
36
+ };
37
+ }
38
+ function idempotencyHeader(key) {
39
+ return typeof key === 'string' && key.trim() ? { 'idempotency-key': key.trim() } : undefined;
40
+ }
41
+ function sentEmail(d) {
42
+ const out = { id: typeof d?.id === 'string' ? d.id : '' };
43
+ if (typeof d?.reference === 'string')
44
+ out.reference = d.reference;
45
+ if (typeof d?.status === 'string')
46
+ out.status = d.status;
47
+ return out;
48
+ }
49
+ function badId(id) {
50
+ return typeof id === 'string' && id.trim()
51
+ ? null
52
+ : new UseBeckyError({ code: 'invalid_email_id', message: 'Pass the email id you got back from send(), like get(data.id).', status: 0 });
53
+ }
54
+ export function createEmails(http) {
55
+ return {
56
+ async send(o) {
57
+ if (!o || typeof o !== 'object')
58
+ return { data: null, error: notAnObject() };
59
+ let body;
60
+ try {
61
+ body = wire(o, 'emails.send({ locale })');
62
+ }
63
+ catch {
64
+ return { data: null, error: new UseBeckyError({ code: 'invalid_attachment', message: 'An attachment\'s content must be a Buffer, Uint8Array, ArrayBuffer or base64 text.', status: 0 }) };
65
+ }
66
+ const res = await http.request('/email/v1/send', { method: 'POST', token: null, headers: idempotencyHeader(o.idempotencyKey), body });
67
+ if (res.error)
68
+ return { data: null, error: res.error };
69
+ return { data: sentEmail(res.data), error: null };
70
+ },
71
+ async batch(emails, options = {}) {
72
+ if (!Array.isArray(emails)) {
73
+ return { data: null, error: new UseBeckyError({ code: 'invalid_email', message: 'Pass a list of emails, like batch([{ to, subject, text }, ...]).', status: 0 }) };
74
+ }
75
+ const list = [];
76
+ for (const [i, o] of emails.entries()) {
77
+ if (!o || typeof o !== 'object') {
78
+ return { data: null, error: new UseBeckyError({ code: 'invalid_email', message: `Email ${i + 1} in the list is not an object, like { to, subject, text }.`, status: 0 }) };
79
+ }
80
+ try {
81
+ list.push(wire(o, 'emails.batch([{ locale }])'));
82
+ }
83
+ catch {
84
+ return { data: null, error: new UseBeckyError({ code: 'invalid_attachment', message: `An attachment of email ${i + 1} must be a Buffer, Uint8Array, ArrayBuffer or base64 text.`, status: 0 }) };
85
+ }
86
+ }
87
+ const res = await http.request('/email/v1/batch', { method: 'POST', token: null, headers: idempotencyHeader(options.idempotencyKey), body: { emails: list } });
88
+ if (res.error)
89
+ return { data: null, error: res.error };
90
+ const raw = Array.isArray(res.data) ? res.data : Array.isArray(res.data?.results) ? res.data.results : Array.isArray(res.data?.data) ? res.data.data : [];
91
+ const results = raw.map((r) => {
92
+ if (r && r.error)
93
+ return { id: null, error: errorFromResponse(typeof r.status === 'number' ? r.status : 400, { error: r.error }) };
94
+ const out = { id: typeof r?.id === 'string' ? r.id : null, error: null };
95
+ if (typeof r?.reference === 'string')
96
+ out.reference = r.reference;
97
+ if (typeof r?.status === 'string')
98
+ out.status = r.status;
99
+ return out;
100
+ });
101
+ return { data: { results }, error: null };
102
+ },
103
+ async get(id) {
104
+ const bad = badId(id);
105
+ if (bad)
106
+ return { data: null, error: bad };
107
+ const res = await http.request(`/email/v1/emails/${encodeURIComponent(id.trim())}`, { token: null });
108
+ if (res.error)
109
+ return { data: null, error: res.error };
110
+ const d = res.data ?? {};
111
+ return { data: { ...d, tags: Array.isArray(d.tags) ? d.tags : [], events: Array.isArray(d.events) ? d.events : [] }, error: null };
112
+ },
113
+ async cancel(id) {
114
+ const bad = badId(id);
115
+ if (bad)
116
+ return { data: null, error: bad };
117
+ const res = await http.request(`/email/v1/emails/${encodeURIComponent(id.trim())}`, { method: 'DELETE', token: null });
118
+ if (res.error)
119
+ return { data: null, error: res.error };
120
+ return { data: { id: res.data?.id ?? id.trim(), status: res.data?.status ?? 'cancelled' }, error: null };
121
+ },
122
+ };
123
+ }