@profitstudio/booking-engine 0.0.0-stage → 2.0.0-beta.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/CHANGELOG.md +562 -0
- package/LICENSE +21 -0
- package/README.md +18 -2
- package/THIRD_PARTY_NOTICES.md +41 -0
- package/bin/booking-engine.mjs +575 -0
- package/bin/connect.mjs +408 -0
- package/bin/photos.mjs +82 -0
- package/dist/admin/BookingAdmin.d.ts +22 -0
- package/dist/admin/BookingAdmin.js +337 -0
- package/dist/admin/admin.css +1423 -0
- package/dist/admin/alerts.d.ts +10 -0
- package/dist/admin/alerts.js +11 -0
- package/dist/admin/booking-detail.d.ts +37 -0
- package/dist/admin/booking-detail.js +149 -0
- package/dist/admin/content-inputs.d.ts +15 -0
- package/dist/admin/content-inputs.js +105 -0
- package/dist/admin/context.d.ts +37 -0
- package/dist/admin/context.js +8 -0
- package/dist/admin/drawer.d.ts +14 -0
- package/dist/admin/drawer.js +56 -0
- package/dist/admin/feedback.d.ts +32 -0
- package/dist/admin/feedback.js +70 -0
- package/dist/admin/fields.d.ts +27 -0
- package/dist/admin/fields.js +146 -0
- package/dist/admin/fonts/OFL-Geist-Mono.txt +93 -0
- package/dist/admin/fonts/OFL-Geist.txt +93 -0
- package/dist/admin/fonts/geist-latin-wght-normal.woff2 +0 -0
- package/dist/admin/fonts/geist-mono-latin-wght-normal.woff2 +0 -0
- package/dist/admin/icons.d.ts +66 -0
- package/dist/admin/icons.js +72 -0
- package/dist/admin/image-upload.d.ts +58 -0
- package/dist/admin/image-upload.js +111 -0
- package/dist/admin/index.d.ts +6 -0
- package/dist/admin/index.js +6 -0
- package/dist/admin/lucide.generated.d.ts +521 -0
- package/dist/admin/lucide.generated.js +76 -0
- package/dist/admin/sections/BookingsSection.d.ts +1 -0
- package/dist/admin/sections/BookingsSection.js +137 -0
- package/dist/admin/sections/EmailSection.d.ts +8 -0
- package/dist/admin/sections/EmailSection.js +182 -0
- package/dist/admin/sections/HoursSection.d.ts +1 -0
- package/dist/admin/sections/HoursSection.js +110 -0
- package/dist/admin/sections/OverviewSection.d.ts +1 -0
- package/dist/admin/sections/OverviewSection.js +427 -0
- package/dist/admin/sections/ServicesSection.d.ts +1 -0
- package/dist/admin/sections/ServicesSection.js +236 -0
- package/dist/admin/sections/SettingsSection.d.ts +10 -0
- package/dist/admin/sections/SettingsSection.js +96 -0
- package/dist/admin/sections/WebsiteSection.d.ts +1 -0
- package/dist/admin/sections/WebsiteSection.js +228 -0
- package/dist/admin/sections.d.ts +22 -0
- package/dist/admin/sections.js +29 -0
- package/dist/admin/setup.d.ts +1 -0
- package/dist/admin/setup.js +45 -0
- package/dist/admin/today.d.ts +43 -0
- package/dist/admin/today.js +115 -0
- package/dist/admin/ui.d.ts +134 -0
- package/dist/admin/ui.js +220 -0
- package/dist/calendar.d.ts +64 -0
- package/dist/calendar.js +139 -0
- package/dist/client.d.ts +147 -0
- package/dist/client.js +507 -0
- package/dist/config.d.ts +25 -0
- package/dist/config.js +120 -0
- package/dist/content/image.d.ts +20 -0
- package/dist/content/image.js +90 -0
- package/dist/content/resolve.d.ts +12 -0
- package/dist/content/resolve.js +73 -0
- package/dist/content/schema.d.ts +119 -0
- package/dist/content/schema.js +53 -0
- package/dist/content/store.d.ts +48 -0
- package/dist/content/store.js +123 -0
- package/dist/content/validate.d.ts +33 -0
- package/dist/content/validate.js +177 -0
- package/dist/errors.d.ts +19 -0
- package/dist/errors.js +94 -0
- package/dist/generated/manifest.d.ts +6 -0
- package/dist/generated/manifest.js +7 -0
- package/dist/index.d.ts +20 -0
- package/dist/index.js +20 -0
- package/dist/presets/hair-salon.d.ts +8 -0
- package/dist/presets/hair-salon.js +94 -0
- package/dist/presets/index.d.ts +5 -0
- package/dist/presets/index.js +6 -0
- package/dist/preview.d.ts +18 -0
- package/dist/preview.js +134 -0
- package/dist/semver.d.ts +16 -0
- package/dist/semver.js +55 -0
- package/dist/time.d.ts +31 -0
- package/dist/time.js +138 -0
- package/dist/types.d.ts +477 -0
- package/dist/types.js +3 -0
- package/dist/vite.d.ts +52 -0
- package/dist/vite.js +150 -0
- package/docs/BUILD-A-SITE.md +203 -0
- package/docs/EMAIL-SETUP.md +224 -0
- package/docs/INTEGRATION.md +1109 -0
- package/engine.manifest.json +90 -0
- package/functions/booking-mailer/deno.json +6 -0
- package/functions/booking-mailer/index.ts +44 -0
- package/functions/booking-mailer/mailer.js +156 -0
- package/functions/booking-mailer/providers/index.js +42 -0
- package/functions/booking-mailer/providers/resend.js +75 -0
- package/functions/booking-mailer/templates.js +345 -0
- package/migrations/0001_core.sql +1673 -0
- package/migrations/0002_security_hardening.sql +711 -0
- package/migrations/0003_private_definers_and_holds.sql +808 -0
- package/migrations/0004_verified_requests.sql +1702 -0
- package/migrations/0005_scoped_mailer_credential.sql +347 -0
- package/migrations/0006_trusted_client_ip.sql +56 -0
- package/migrations/0007_site_content.sql +380 -0
- package/migrations/0008_service_images_opening_times.sql +328 -0
- package/package.json +85 -4
- package/templates/BOOKING_ENGINE.md +61 -0
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
{
|
|
2
|
+
"package": "@profitstudio/booking-engine",
|
|
3
|
+
"version": "2.0.0-beta.1",
|
|
4
|
+
"schemaVersion": "2.0.0-alpha.10",
|
|
5
|
+
"requiredSchemaVersion": "2.0.0-alpha.5",
|
|
6
|
+
"migrations": [
|
|
7
|
+
{
|
|
8
|
+
"id": "0001_core",
|
|
9
|
+
"file": "migrations/0001_core.sql",
|
|
10
|
+
"schemaVersion": "2.0.0-alpha.1",
|
|
11
|
+
"sha256": "6a7f3da20ba39b4dc1ae68014bc7feb1b5d9ef0542062d1c9c6322d5b979a793"
|
|
12
|
+
},
|
|
13
|
+
{
|
|
14
|
+
"id": "0002_security_hardening",
|
|
15
|
+
"file": "migrations/0002_security_hardening.sql",
|
|
16
|
+
"schemaVersion": "2.0.0-alpha.2",
|
|
17
|
+
"sha256": "8ab0dca712ecf7a668b3843077194e2094fe9cfed189159a29e10edbbc77bacf"
|
|
18
|
+
},
|
|
19
|
+
{
|
|
20
|
+
"id": "0003_private_definers_and_holds",
|
|
21
|
+
"file": "migrations/0003_private_definers_and_holds.sql",
|
|
22
|
+
"schemaVersion": "2.0.0-alpha.3",
|
|
23
|
+
"sha256": "1f3c76419f637a9e73757bdc5af24ff125639a0b61387433a6dde9c5cc473f63"
|
|
24
|
+
},
|
|
25
|
+
{
|
|
26
|
+
"id": "0004_verified_requests",
|
|
27
|
+
"file": "migrations/0004_verified_requests.sql",
|
|
28
|
+
"schemaVersion": "2.0.0-alpha.4",
|
|
29
|
+
"sha256": "aeb84aa8d363b3a48cfaa7735ef5edbaea7983bba6daf9f9682beecdcf591eae"
|
|
30
|
+
},
|
|
31
|
+
{
|
|
32
|
+
"id": "0005_scoped_mailer_credential",
|
|
33
|
+
"file": "migrations/0005_scoped_mailer_credential.sql",
|
|
34
|
+
"schemaVersion": "2.0.0-alpha.5",
|
|
35
|
+
"sha256": "de5d252b0d0c91e1d48f5e7089a67e2eaa11adc52323012d68329cf4c0f6721d"
|
|
36
|
+
},
|
|
37
|
+
{
|
|
38
|
+
"id": "0006_trusted_client_ip",
|
|
39
|
+
"file": "migrations/0006_trusted_client_ip.sql",
|
|
40
|
+
"schemaVersion": "2.0.0-alpha.6",
|
|
41
|
+
"sha256": "78b5cb79baf432d1d25c7327db641b5c47e372be558d9448ae49044151d0b02b"
|
|
42
|
+
},
|
|
43
|
+
{
|
|
44
|
+
"id": "0007_site_content",
|
|
45
|
+
"file": "migrations/0007_site_content.sql",
|
|
46
|
+
"schemaVersion": "2.0.0-alpha.7",
|
|
47
|
+
"sha256": "ad40fa3bc6d361bc4869501a40e441e4a700e6ca16c6e5219245d3f259429e1b"
|
|
48
|
+
},
|
|
49
|
+
{
|
|
50
|
+
"id": "0008_service_images_opening_times",
|
|
51
|
+
"file": "migrations/0008_service_images_opening_times.sql",
|
|
52
|
+
"schemaVersion": "2.0.0-alpha.10",
|
|
53
|
+
"sha256": "7bd73c7a71cf11cfcf1c20c00072f2bd163f6656af6314186e95a107b26ff6b8"
|
|
54
|
+
}
|
|
55
|
+
],
|
|
56
|
+
"functions": [
|
|
57
|
+
{
|
|
58
|
+
"name": "booking-mailer",
|
|
59
|
+
"files": [
|
|
60
|
+
{
|
|
61
|
+
"path": "deno.json",
|
|
62
|
+
"sha256": "c25c8af2f700c9c4cfb5a196599bfeb99c854a0569f44c12a2e25d41bda27363"
|
|
63
|
+
},
|
|
64
|
+
{
|
|
65
|
+
"path": "index.ts",
|
|
66
|
+
"sha256": "1423dd378fcb992bb68946e5e21d65feacdb22b69402d8e573c06b5b6d4c5f2c"
|
|
67
|
+
},
|
|
68
|
+
{
|
|
69
|
+
"path": "mailer.js",
|
|
70
|
+
"sha256": "11c53e03288c9e757dc994a0e9505fd6f46dbb131d23af20782b683073c361ac"
|
|
71
|
+
},
|
|
72
|
+
{
|
|
73
|
+
"path": "providers/index.js",
|
|
74
|
+
"sha256": "ee8198ff49270aeb2b5a7b25a6dafc9238c4f4efcd48a4e3f478f94540d1a37f"
|
|
75
|
+
},
|
|
76
|
+
{
|
|
77
|
+
"path": "providers/resend.js",
|
|
78
|
+
"sha256": "2c27d90fbfb1f905f2ec607eabea9ef8f64f8d8b337be8aba54011ecccbdb783"
|
|
79
|
+
},
|
|
80
|
+
{
|
|
81
|
+
"path": "templates.js",
|
|
82
|
+
"sha256": "f045094490f3f86ddd2939ac3de965f3a64b1b161225dc7f9655a65f44d42de9"
|
|
83
|
+
}
|
|
84
|
+
]
|
|
85
|
+
}
|
|
86
|
+
],
|
|
87
|
+
"presets": [
|
|
88
|
+
"hair-salon"
|
|
89
|
+
]
|
|
90
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// booking-mailer — Supabase Edge Function that sends the Booking Engine's emails.
|
|
2
|
+
// ENGINE-OWNED FILE (installed by `booking-engine init` / `sync`). Do not edit.
|
|
3
|
+
//
|
|
4
|
+
// Called by the project's own database, never by the website: pg_net (after
|
|
5
|
+
// each queued email) and pg_cron (every minute, for retries and expiry
|
|
6
|
+
// notices), with the mailer-only token in the `x-booking-mailer-token` header.
|
|
7
|
+
// It takes no input — it can only send what the database already queued.
|
|
8
|
+
//
|
|
9
|
+
// Deploy: npx supabase functions deploy booking-mailer --no-verify-jwt
|
|
10
|
+
// Secrets: BOOKING_MAILER_TOKEN, RESEND_API_KEY, BOOKING_EMAIL_FROM (see mailer.js)
|
|
11
|
+
//
|
|
12
|
+
// Authentication: the platform JWT check is off (`verify_jwt = false`) and the
|
|
13
|
+
// function authenticates every call itself — the pattern @supabase/server
|
|
14
|
+
// documents for its `none` mode. Only the mailer token is accepted (compared in
|
|
15
|
+
// constant time; fails closed when the secret is missing), so the database
|
|
16
|
+
// never needs a Supabase secret key. The function's own database access uses
|
|
17
|
+
// the project's default secret key, which never leaves the function runtime.
|
|
18
|
+
// No browser calls this function, so CORS is disabled.
|
|
19
|
+
import { withSupabase } from '@supabase/server'; // exact version pinned in deno.json
|
|
20
|
+
import { authorizeMailerRequest, runMailer } from './mailer.js';
|
|
21
|
+
|
|
22
|
+
export default {
|
|
23
|
+
fetch: withSupabase({ auth: 'none', cors: 'disabled' }, async (req, ctx) => {
|
|
24
|
+
const auth = await authorizeMailerRequest(req, (name: string) => Deno.env.get(name));
|
|
25
|
+
if (!auth.ok) {
|
|
26
|
+
if (auth.status === 503) console.error(JSON.stringify({ event: 'booking-mailer', error: 'BOOKING_MAILER_TOKEN is not set (Edge Function secret)' }));
|
|
27
|
+
return Response.json({ error: auth.error }, { status: auth.status });
|
|
28
|
+
}
|
|
29
|
+
if (req.method !== 'POST') {
|
|
30
|
+
return new Response('Method Not Allowed', { status: 405, headers: { Allow: 'POST' } });
|
|
31
|
+
}
|
|
32
|
+
try {
|
|
33
|
+
const result = await runMailer({
|
|
34
|
+
db: ctx.supabaseAdmin,
|
|
35
|
+
env: (name: string) => Deno.env.get(name),
|
|
36
|
+
log: (entry: object) => console.log(JSON.stringify(entry)),
|
|
37
|
+
});
|
|
38
|
+
return Response.json(result);
|
|
39
|
+
} catch (error) {
|
|
40
|
+
console.error(JSON.stringify({ event: 'booking-mailer', error: String((error as Error)?.message ?? error).slice(0, 300) }));
|
|
41
|
+
return Response.json({ error: 'The mailer could not finish; queued emails are retried.' }, { status: 500 });
|
|
42
|
+
}
|
|
43
|
+
}),
|
|
44
|
+
};
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
// booking-mailer — sends the Booking Engine's queued emails.
|
|
2
|
+
// ENGINE-OWNED FILE (installed by `booking-engine init` / `sync`). Do not edit.
|
|
3
|
+
//
|
|
4
|
+
// Runtime-neutral core (Supabase Edge Functions / Deno, and Node for tests).
|
|
5
|
+
// One run: lease due emails from the database (booking_mailer_claim), render
|
|
6
|
+
// each from its stored payload, send it through the provider with the outbox
|
|
7
|
+
// id as idempotency key, and report the result (booking_mailer_report). The
|
|
8
|
+
// database decides what is sent, to whom and when; this code only delivers.
|
|
9
|
+
// Nothing here logs addresses, names, codes or keys.
|
|
10
|
+
//
|
|
11
|
+
// Function secrets:
|
|
12
|
+
// BOOKING_MAILER_TOKEN the mailer-only token from `select * from booking.configure_mailer(…)`
|
|
13
|
+
// (the database sends it as x-booking-mailer-token; nothing else is accepted)
|
|
14
|
+
// RESEND_API_KEY provider key (server only)
|
|
15
|
+
// BOOKING_EMAIL_FROM sender on a verified domain, e.g. "Copper & Comb <bookings@mail.example.com>"
|
|
16
|
+
// (an address alone uses the business name as display name)
|
|
17
|
+
// BOOKING_EMAIL_PROVIDER optional, default "resend"
|
|
18
|
+
// BOOKING_ADMIN_URL optional dashboard link in owner alerts (https)
|
|
19
|
+
import { providerFromEnv } from './providers/index.js';
|
|
20
|
+
import { renderEmail } from './templates.js';
|
|
21
|
+
|
|
22
|
+
const BATCH_SIZE = 10;
|
|
23
|
+
const MAX_BATCHES = 5;
|
|
24
|
+
const SEND_GAP_MS = 120; // stays below Resend's default of 10 requests per second
|
|
25
|
+
|
|
26
|
+
const ADDRESS = /^[^@\s<>"]+@[^@\s<>"]+\.[^@\s<>"]{2,}$/;
|
|
27
|
+
const TOKEN_HEADER = 'x-booking-mailer-token';
|
|
28
|
+
|
|
29
|
+
/**
|
|
30
|
+
* The only credential the mailer accepts: the mailer token the database holds
|
|
31
|
+
* (booking.mailer_config), compared in constant time. Fails closed when the
|
|
32
|
+
* secret is missing. A Supabase key — publishable or secret — is NOT accepted:
|
|
33
|
+
* starting the mailer needs no more than this narrow token.
|
|
34
|
+
* @param {Request} request
|
|
35
|
+
* @param {(name: string) => string | undefined} env
|
|
36
|
+
* @returns {Promise<{ ok: true } | { ok: false, status: 401 | 503, error: string }>}
|
|
37
|
+
*/
|
|
38
|
+
export async function authorizeMailerRequest(request, env) {
|
|
39
|
+
const expected = (env('BOOKING_MAILER_TOKEN') || '').trim();
|
|
40
|
+
if (expected.length < 32) return { ok: false, status: 503, error: 'Mailer not configured' };
|
|
41
|
+
const given = request.headers.get(TOKEN_HEADER) ?? '';
|
|
42
|
+
return (await sameSecret(given, expected)) ? { ok: true } : { ok: false, status: 401, error: 'Unauthorized' };
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
async function sameSecret(a, b) {
|
|
46
|
+
const encoder = new TextEncoder();
|
|
47
|
+
const [x, y] = await Promise.all([
|
|
48
|
+
crypto.subtle.digest('SHA-256', encoder.encode(a)),
|
|
49
|
+
crypto.subtle.digest('SHA-256', encoder.encode(b)),
|
|
50
|
+
]);
|
|
51
|
+
const u = new Uint8Array(x);
|
|
52
|
+
const v = new Uint8Array(y);
|
|
53
|
+
let diff = 0;
|
|
54
|
+
for (let i = 0; i < u.length; i++) diff |= u[i] ^ v[i];
|
|
55
|
+
return diff === 0;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* @param {object} options
|
|
60
|
+
* @param {{ rpc: (fn: string, args: Record<string, unknown>) => PromiseLike<{ data: any, error: any }> }} options.db
|
|
61
|
+
* A Supabase client with the secret key (service_role).
|
|
62
|
+
* @param {(name: string) => string | undefined} options.env
|
|
63
|
+
* @param {typeof fetch} [options.fetch]
|
|
64
|
+
* @param {(ms: number) => Promise<void>} [options.sleep]
|
|
65
|
+
* @param {(entry: object) => void} [options.log]
|
|
66
|
+
*/
|
|
67
|
+
export async function runMailer({ db, env, fetch: fetchImpl = globalThis.fetch, sleep = defaultSleep, log = () => {} }) {
|
|
68
|
+
const from = parseFrom(env('BOOKING_EMAIL_FROM'));
|
|
69
|
+
const selected = providerFromEnv(env, fetchImpl);
|
|
70
|
+
const problem = selected.error ?? from.error;
|
|
71
|
+
if (problem) {
|
|
72
|
+
await call(db, 'booking_mailer_report_unconfigured', { p_error: problem });
|
|
73
|
+
log({ event: 'booking-mailer', configured: false });
|
|
74
|
+
return { configured: false, error: problem };
|
|
75
|
+
}
|
|
76
|
+
const { provider } = selected;
|
|
77
|
+
const adminUrl = env('BOOKING_ADMIN_URL') || undefined;
|
|
78
|
+
const totals = { sent: 0, retrying: 0, failed: 0 };
|
|
79
|
+
|
|
80
|
+
for (let batch = 0; batch < MAX_BATCHES; batch++) {
|
|
81
|
+
const claimed = (await call(db, 'booking_mailer_claim', { p_limit: BATCH_SIZE })) ?? [];
|
|
82
|
+
for (const mail of claimed) {
|
|
83
|
+
const result = await deliver(provider, mail, { from, adminUrl });
|
|
84
|
+
await call(db, 'booking_mailer_report', {
|
|
85
|
+
p_id: mail.id,
|
|
86
|
+
p_attempt: mail.attempt,
|
|
87
|
+
p_ok: result.ok,
|
|
88
|
+
p_provider_id: result.ok ? result.id : null,
|
|
89
|
+
p_error: result.ok ? null : result.error,
|
|
90
|
+
p_permanent: result.ok ? false : result.permanent,
|
|
91
|
+
});
|
|
92
|
+
if (result.ok) totals.sent++;
|
|
93
|
+
else if (result.permanent || mail.attempt >= 5) totals.failed++;
|
|
94
|
+
else totals.retrying++;
|
|
95
|
+
await sleep(SEND_GAP_MS);
|
|
96
|
+
}
|
|
97
|
+
if (claimed.length < BATCH_SIZE) break;
|
|
98
|
+
}
|
|
99
|
+
log({ event: 'booking-mailer', configured: true, provider: provider.name, ...totals });
|
|
100
|
+
return { configured: true, ...totals };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
async function deliver(provider, mail, { from, adminUrl }) {
|
|
104
|
+
let email;
|
|
105
|
+
try {
|
|
106
|
+
email = renderEmail(mail, { adminUrl });
|
|
107
|
+
} catch (error) {
|
|
108
|
+
return { ok: false, permanent: true, error: `Could not render the email: ${String(error?.message ?? error).slice(0, 200)}` };
|
|
109
|
+
}
|
|
110
|
+
if (!ADDRESS.test(mail.to ?? '')) return { ok: false, permanent: true, error: 'Invalid recipient address.' };
|
|
111
|
+
try {
|
|
112
|
+
return await provider.send({
|
|
113
|
+
idempotencyKey: `booking-engine-${mail.id}`,
|
|
114
|
+
from: from.address ? sender(from, mail.payload?.businessName) : from.full,
|
|
115
|
+
to: mail.to,
|
|
116
|
+
replyTo: email.replyTo && ADDRESS.test(email.replyTo) ? email.replyTo : undefined,
|
|
117
|
+
subject: email.subject,
|
|
118
|
+
html: email.html,
|
|
119
|
+
text: email.text,
|
|
120
|
+
});
|
|
121
|
+
} catch (error) {
|
|
122
|
+
return { ok: false, permanent: false, error: `Provider error: ${String(error?.message ?? error).slice(0, 200)}` };
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** BOOKING_EMAIL_FROM: "Name <address>" (used as is) or an address (named after the business). */
|
|
127
|
+
export function parseFrom(value) {
|
|
128
|
+
const v = (value ?? '').trim();
|
|
129
|
+
if (!v) return { error: 'BOOKING_EMAIL_FROM is not set (Edge Function secret), e.g. "Your Business <bookings@mail.yourdomain.com>".' };
|
|
130
|
+
const named = /^(.*)<([^<>]+)>$/.exec(v);
|
|
131
|
+
if (named) {
|
|
132
|
+
const address = named[2].trim();
|
|
133
|
+
if (!ADDRESS.test(address)) return { error: 'BOOKING_EMAIL_FROM does not contain a valid email address.' };
|
|
134
|
+
return { full: `${quoteName(named[1])} <${address}>`.trim() };
|
|
135
|
+
}
|
|
136
|
+
if (!ADDRESS.test(v)) return { error: 'BOOKING_EMAIL_FROM is not a valid email address.' };
|
|
137
|
+
return { address: v };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function sender(from, businessName) {
|
|
141
|
+
const name = quoteName(businessName ?? '');
|
|
142
|
+
return name ? `${name} <${from.address}>` : from.address;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function quoteName(name) {
|
|
146
|
+
const n = String(name).replace(/["\\<>\r\n\t]/g, '').replace(/\s+/g, ' ').trim().slice(0, 70);
|
|
147
|
+
return n ? `"${n}"` : '';
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
async function call(db, fn, args) {
|
|
151
|
+
const { data, error } = await db.rpc(fn, args);
|
|
152
|
+
if (error) throw new Error(`${fn} failed: ${error.message ?? error}`);
|
|
153
|
+
return data;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
const defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// booking-mailer — the email provider boundary.
|
|
2
|
+
// ENGINE-OWNED FILE (installed by `booking-engine init` / `sync`). Do not edit.
|
|
3
|
+
//
|
|
4
|
+
// A provider is one object with one method. Everything else — what to send,
|
|
5
|
+
// when, to whom, retries, de-duplication, the booking rules — stays in the
|
|
6
|
+
// engine. Adding a provider means adding a factory here; nothing else changes.
|
|
7
|
+
//
|
|
8
|
+
// @typedef {object} OutgoingEmail
|
|
9
|
+
// @property {string} idempotencyKey Stable per queued email: a retry is never a second email.
|
|
10
|
+
// @property {string} from "Display Name <address@domain>"
|
|
11
|
+
// @property {string} to
|
|
12
|
+
// @property {string} [replyTo]
|
|
13
|
+
// @property {string} subject
|
|
14
|
+
// @property {string} html
|
|
15
|
+
// @property {string} text
|
|
16
|
+
//
|
|
17
|
+
// @typedef {{ ok: true, id: string } | { ok: false, permanent: boolean, error: string }} SendResult
|
|
18
|
+
// permanent: retrying the same email cannot succeed (bad address, rejected content).
|
|
19
|
+
// error: a short, human-readable reason shown to the owner. Never include secrets.
|
|
20
|
+
//
|
|
21
|
+
// @typedef {object} EmailProvider
|
|
22
|
+
// @property {string} name
|
|
23
|
+
// @property {(email: OutgoingEmail) => Promise<SendResult>} send
|
|
24
|
+
import { createResendProvider } from './resend.js';
|
|
25
|
+
|
|
26
|
+
/** Provider factories by name: (env, fetch) → { provider } | { error }. */
|
|
27
|
+
export const PROVIDERS = {
|
|
28
|
+
resend: createResendProvider,
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* The provider the function secrets select (BOOKING_EMAIL_PROVIDER, default "resend").
|
|
33
|
+
* @param {(name: string) => string | undefined} env
|
|
34
|
+
* @param {typeof fetch} fetchImpl
|
|
35
|
+
* @returns {{ provider: EmailProvider } | { error: string }}
|
|
36
|
+
*/
|
|
37
|
+
export function providerFromEnv(env, fetchImpl) {
|
|
38
|
+
const name = (env('BOOKING_EMAIL_PROVIDER') || 'resend').trim().toLowerCase();
|
|
39
|
+
const factory = PROVIDERS[name];
|
|
40
|
+
if (!factory) return { error: `Unknown BOOKING_EMAIL_PROVIDER "${name}". Supported: ${Object.keys(PROVIDERS).join(', ')}.` };
|
|
41
|
+
return factory(env, fetchImpl);
|
|
42
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// booking-mailer — Resend (https://resend.com) through its HTTP API.
|
|
2
|
+
// ENGINE-OWNED FILE (installed by `booking-engine init` / `sync`). Do not edit.
|
|
3
|
+
//
|
|
4
|
+
// Function secrets: RESEND_API_KEY (required; a "Sending access" key is enough).
|
|
5
|
+
// RESEND_API_URL is for local tests only (a fake Resend server).
|
|
6
|
+
//
|
|
7
|
+
// Resend keeps an Idempotency-Key for 24 hours: the same key with the same
|
|
8
|
+
// content returns the first result without sending again; the same key with
|
|
9
|
+
// different content is refused (409). The outbox id is the key, and emails are
|
|
10
|
+
// rendered from the stored payload only, so a retry is always identical.
|
|
11
|
+
|
|
12
|
+
const DEFAULT_API_URL = 'https://api.resend.com';
|
|
13
|
+
const TIMEOUT_MS = 15_000;
|
|
14
|
+
// Retrying cannot fix these: the request itself is wrong.
|
|
15
|
+
const PERMANENT_STATUS = new Set([400, 404, 405, 413, 422]);
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* @param {(name: string) => string | undefined} env
|
|
19
|
+
* @param {typeof fetch} fetchImpl
|
|
20
|
+
*/
|
|
21
|
+
export function createResendProvider(env, fetchImpl) {
|
|
22
|
+
const apiKey = (env('RESEND_API_KEY') || '').trim();
|
|
23
|
+
if (!apiKey) return { error: 'RESEND_API_KEY is not set (Edge Function secret).' };
|
|
24
|
+
const base = (env('RESEND_API_URL') || DEFAULT_API_URL).trim().replace(/\/+$/, '');
|
|
25
|
+
return {
|
|
26
|
+
provider: {
|
|
27
|
+
name: 'resend',
|
|
28
|
+
send: (email) => send({ apiKey, base, fetchImpl }, email),
|
|
29
|
+
},
|
|
30
|
+
};
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async function send({ apiKey, base, fetchImpl }, email) {
|
|
34
|
+
let response;
|
|
35
|
+
try {
|
|
36
|
+
response = await fetchImpl(`${base}/emails`, {
|
|
37
|
+
method: 'POST',
|
|
38
|
+
headers: {
|
|
39
|
+
Authorization: `Bearer ${apiKey}`,
|
|
40
|
+
'Content-Type': 'application/json',
|
|
41
|
+
'Idempotency-Key': email.idempotencyKey,
|
|
42
|
+
'User-Agent': 'profitstudio-booking-engine',
|
|
43
|
+
},
|
|
44
|
+
body: JSON.stringify({
|
|
45
|
+
from: email.from,
|
|
46
|
+
to: [email.to],
|
|
47
|
+
subject: email.subject,
|
|
48
|
+
html: email.html,
|
|
49
|
+
text: email.text,
|
|
50
|
+
...(email.replyTo ? { reply_to: email.replyTo } : {}),
|
|
51
|
+
}),
|
|
52
|
+
signal: AbortSignal.timeout(TIMEOUT_MS),
|
|
53
|
+
});
|
|
54
|
+
} catch (error) {
|
|
55
|
+
const reason = error?.name === 'TimeoutError' ? 'timed out' : 'network error';
|
|
56
|
+
return { ok: false, permanent: false, error: `Resend could not be reached (${reason}).` };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
let body = null;
|
|
60
|
+
try {
|
|
61
|
+
body = await response.json();
|
|
62
|
+
} catch {
|
|
63
|
+
body = null;
|
|
64
|
+
}
|
|
65
|
+
if (response.ok && body && typeof body.id === 'string') return { ok: true, id: body.id };
|
|
66
|
+
|
|
67
|
+
const name = typeof body?.name === 'string' ? body.name : 'error';
|
|
68
|
+
const message = typeof body?.message === 'string' ? body.message : '';
|
|
69
|
+
const permanent = PERMANENT_STATUS.has(response.status) || name === 'invalid_idempotent_request';
|
|
70
|
+
return {
|
|
71
|
+
ok: false,
|
|
72
|
+
permanent,
|
|
73
|
+
error: `Resend ${response.status} ${name}${message ? `: ${message}` : ''}`.slice(0, 300),
|
|
74
|
+
};
|
|
75
|
+
}
|