@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.
Files changed (114) hide show
  1. package/CHANGELOG.md +562 -0
  2. package/LICENSE +21 -0
  3. package/README.md +18 -2
  4. package/THIRD_PARTY_NOTICES.md +41 -0
  5. package/bin/booking-engine.mjs +575 -0
  6. package/bin/connect.mjs +408 -0
  7. package/bin/photos.mjs +82 -0
  8. package/dist/admin/BookingAdmin.d.ts +22 -0
  9. package/dist/admin/BookingAdmin.js +337 -0
  10. package/dist/admin/admin.css +1423 -0
  11. package/dist/admin/alerts.d.ts +10 -0
  12. package/dist/admin/alerts.js +11 -0
  13. package/dist/admin/booking-detail.d.ts +37 -0
  14. package/dist/admin/booking-detail.js +149 -0
  15. package/dist/admin/content-inputs.d.ts +15 -0
  16. package/dist/admin/content-inputs.js +105 -0
  17. package/dist/admin/context.d.ts +37 -0
  18. package/dist/admin/context.js +8 -0
  19. package/dist/admin/drawer.d.ts +14 -0
  20. package/dist/admin/drawer.js +56 -0
  21. package/dist/admin/feedback.d.ts +32 -0
  22. package/dist/admin/feedback.js +70 -0
  23. package/dist/admin/fields.d.ts +27 -0
  24. package/dist/admin/fields.js +146 -0
  25. package/dist/admin/fonts/OFL-Geist-Mono.txt +93 -0
  26. package/dist/admin/fonts/OFL-Geist.txt +93 -0
  27. package/dist/admin/fonts/geist-latin-wght-normal.woff2 +0 -0
  28. package/dist/admin/fonts/geist-mono-latin-wght-normal.woff2 +0 -0
  29. package/dist/admin/icons.d.ts +66 -0
  30. package/dist/admin/icons.js +72 -0
  31. package/dist/admin/image-upload.d.ts +58 -0
  32. package/dist/admin/image-upload.js +111 -0
  33. package/dist/admin/index.d.ts +6 -0
  34. package/dist/admin/index.js +6 -0
  35. package/dist/admin/lucide.generated.d.ts +521 -0
  36. package/dist/admin/lucide.generated.js +76 -0
  37. package/dist/admin/sections/BookingsSection.d.ts +1 -0
  38. package/dist/admin/sections/BookingsSection.js +137 -0
  39. package/dist/admin/sections/EmailSection.d.ts +8 -0
  40. package/dist/admin/sections/EmailSection.js +182 -0
  41. package/dist/admin/sections/HoursSection.d.ts +1 -0
  42. package/dist/admin/sections/HoursSection.js +110 -0
  43. package/dist/admin/sections/OverviewSection.d.ts +1 -0
  44. package/dist/admin/sections/OverviewSection.js +427 -0
  45. package/dist/admin/sections/ServicesSection.d.ts +1 -0
  46. package/dist/admin/sections/ServicesSection.js +236 -0
  47. package/dist/admin/sections/SettingsSection.d.ts +10 -0
  48. package/dist/admin/sections/SettingsSection.js +96 -0
  49. package/dist/admin/sections/WebsiteSection.d.ts +1 -0
  50. package/dist/admin/sections/WebsiteSection.js +228 -0
  51. package/dist/admin/sections.d.ts +22 -0
  52. package/dist/admin/sections.js +29 -0
  53. package/dist/admin/setup.d.ts +1 -0
  54. package/dist/admin/setup.js +45 -0
  55. package/dist/admin/today.d.ts +43 -0
  56. package/dist/admin/today.js +115 -0
  57. package/dist/admin/ui.d.ts +134 -0
  58. package/dist/admin/ui.js +220 -0
  59. package/dist/calendar.d.ts +64 -0
  60. package/dist/calendar.js +139 -0
  61. package/dist/client.d.ts +147 -0
  62. package/dist/client.js +507 -0
  63. package/dist/config.d.ts +25 -0
  64. package/dist/config.js +120 -0
  65. package/dist/content/image.d.ts +20 -0
  66. package/dist/content/image.js +90 -0
  67. package/dist/content/resolve.d.ts +12 -0
  68. package/dist/content/resolve.js +73 -0
  69. package/dist/content/schema.d.ts +119 -0
  70. package/dist/content/schema.js +53 -0
  71. package/dist/content/store.d.ts +48 -0
  72. package/dist/content/store.js +123 -0
  73. package/dist/content/validate.d.ts +33 -0
  74. package/dist/content/validate.js +177 -0
  75. package/dist/errors.d.ts +19 -0
  76. package/dist/errors.js +94 -0
  77. package/dist/generated/manifest.d.ts +6 -0
  78. package/dist/generated/manifest.js +7 -0
  79. package/dist/index.d.ts +20 -0
  80. package/dist/index.js +20 -0
  81. package/dist/presets/hair-salon.d.ts +8 -0
  82. package/dist/presets/hair-salon.js +94 -0
  83. package/dist/presets/index.d.ts +5 -0
  84. package/dist/presets/index.js +6 -0
  85. package/dist/preview.d.ts +18 -0
  86. package/dist/preview.js +134 -0
  87. package/dist/semver.d.ts +16 -0
  88. package/dist/semver.js +55 -0
  89. package/dist/time.d.ts +31 -0
  90. package/dist/time.js +138 -0
  91. package/dist/types.d.ts +477 -0
  92. package/dist/types.js +3 -0
  93. package/dist/vite.d.ts +52 -0
  94. package/dist/vite.js +150 -0
  95. package/docs/BUILD-A-SITE.md +203 -0
  96. package/docs/EMAIL-SETUP.md +224 -0
  97. package/docs/INTEGRATION.md +1109 -0
  98. package/engine.manifest.json +90 -0
  99. package/functions/booking-mailer/deno.json +6 -0
  100. package/functions/booking-mailer/index.ts +44 -0
  101. package/functions/booking-mailer/mailer.js +156 -0
  102. package/functions/booking-mailer/providers/index.js +42 -0
  103. package/functions/booking-mailer/providers/resend.js +75 -0
  104. package/functions/booking-mailer/templates.js +345 -0
  105. package/migrations/0001_core.sql +1673 -0
  106. package/migrations/0002_security_hardening.sql +711 -0
  107. package/migrations/0003_private_definers_and_holds.sql +808 -0
  108. package/migrations/0004_verified_requests.sql +1702 -0
  109. package/migrations/0005_scoped_mailer_credential.sql +347 -0
  110. package/migrations/0006_trusted_client_ip.sql +56 -0
  111. package/migrations/0007_site_content.sql +380 -0
  112. package/migrations/0008_service_images_opening_times.sql +328 -0
  113. package/package.json +85 -4
  114. package/templates/BOOKING_ENGINE.md +61 -0
@@ -0,0 +1,177 @@
1
+ import { allFields } from './schema.js';
2
+ export const TEXT_MAX = 160;
3
+ export const LONG_TEXT_MAX = 2000;
4
+ export const LIST_MAX = 12;
5
+ export const ALT_MAX = 300;
6
+ // eslint-disable-next-line no-control-regex
7
+ const CONTROL_ANY = /[\u0000-\u001f\u007f]/;
8
+ // eslint-disable-next-line no-control-regex
9
+ const CONTROL_EXCEPT_BREAKS = /[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/;
10
+ const IMAGE_PATH_RE = /^site\/[a-z0-9][a-z0-9._-]{0,120}$/;
11
+ const HEX_RE = /^#[0-9a-fA-F]{6}$/;
12
+ const good = (value) => ({ ok: true, value });
13
+ const bad = (problem) => ({ ok: false, problem });
14
+ /**
15
+ * A link a website may put in href: https:/http:, mailto:, tel:, #anchor or a
16
+ * /path on the same site. Anything else (javascript:, data:, //host) → null.
17
+ */
18
+ export function safeHref(value) {
19
+ const v = value.trim();
20
+ if (!v || CONTROL_ANY.test(v) || v.length > 2000)
21
+ return null;
22
+ if (/^#[A-Za-z][\w:.-]*$/.test(v))
23
+ return v;
24
+ if (/^\/(?!\/)[^\s\\]*$/.test(v))
25
+ return v;
26
+ if (/^mailto:[^\s<>()@]+@[^\s<>()@]+\.[^\s<>()@]{2,}$/i.test(v))
27
+ return v;
28
+ if (/^tel:\+?[0-9() .-]{5,30}$/i.test(v))
29
+ return v;
30
+ try {
31
+ const url = new URL(v);
32
+ return url.protocol === 'https:' || url.protocol === 'http:' ? url.href : null;
33
+ }
34
+ catch {
35
+ return null;
36
+ }
37
+ }
38
+ export function isHexColor(value) {
39
+ return typeof value === 'string' && HEX_RE.test(value);
40
+ }
41
+ function luminance(hex) {
42
+ const channel = (i) => {
43
+ const c = parseInt(hex.slice(i, i + 2), 16) / 255;
44
+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
45
+ };
46
+ return 0.2126 * channel(1) + 0.7152 * channel(3) + 0.0722 * channel(5);
47
+ }
48
+ /** WCAG contrast ratio between two #rrggbb colours (1–21). */
49
+ export function contrastRatio(a, b) {
50
+ const [hi, lo] = [luminance(a), luminance(b)].sort((x, y) => y - x);
51
+ return (hi + 0.05) / (lo + 0.05);
52
+ }
53
+ export function isStoredImage(value) {
54
+ if (!value || typeof value !== 'object' || Array.isArray(value))
55
+ return false;
56
+ const v = value;
57
+ if (Object.keys(v).some((k) => !['path', 'alt', 'width', 'height'].includes(k)))
58
+ return false;
59
+ return (typeof v.path === 'string' &&
60
+ IMAGE_PATH_RE.test(v.path) &&
61
+ !v.path.includes('..') &&
62
+ (v.alt === undefined || (typeof v.alt === 'string' && v.alt.length <= ALT_MAX && !CONTROL_ANY.test(v.alt))) &&
63
+ (v.width === undefined || (Number.isInteger(v.width) && v.width > 0)) &&
64
+ (v.height === undefined || (Number.isInteger(v.height) && v.height > 0)));
65
+ }
66
+ function checkText(field, value, max, multiline) {
67
+ if (typeof value !== 'string')
68
+ return bad('Enter text.');
69
+ const v = multiline ? value.replace(/\r\n?/g, '\n').trim() : value.trim();
70
+ if ((multiline ? CONTROL_EXCEPT_BREAKS : CONTROL_ANY).test(v))
71
+ return bad('Remove the special characters.');
72
+ const limit = Math.min(field.maxLength ?? max, 5000);
73
+ if (v.length > limit)
74
+ return bad(`Keep it to ${limit} characters (now ${v.length}).`);
75
+ if (field.required && !v)
76
+ return bad('This cannot be empty.');
77
+ return good(v);
78
+ }
79
+ /** Checks one value against its field. Images must be uploaded ones (StoredImage) or null. */
80
+ export function checkFieldValue(field, value) {
81
+ switch (field.type) {
82
+ case 'text':
83
+ return checkText(field, value, TEXT_MAX, false);
84
+ case 'longText':
85
+ return checkText(field, value, LONG_TEXT_MAX, true);
86
+ case 'link': {
87
+ if (typeof value !== 'string')
88
+ return bad('Enter a link.');
89
+ const v = value.trim();
90
+ if (!v)
91
+ return field.required ? bad('Enter a link.') : good('');
92
+ const href = safeHref(v);
93
+ return href ? good(href) : bad('Use a full https:// address, mailto:, tel:, #section or /page.');
94
+ }
95
+ case 'image':
96
+ if (value === null)
97
+ return good(null);
98
+ if (!isStoredImage(value))
99
+ return bad('Upload the image again.');
100
+ return good({ ...value, alt: (value.alt ?? '').trim() });
101
+ case 'color': {
102
+ if (!isHexColor(value))
103
+ return bad('Use a colour like #b8743c.');
104
+ const color = value.toLowerCase();
105
+ if (field.contrastWith && field.minContrast) {
106
+ const ratio = contrastRatio(color, field.contrastWith);
107
+ if (ratio < field.minContrast) {
108
+ return bad(`Too little contrast (${ratio.toFixed(1)}:1, needs ${field.minContrast}:1) — text would be hard to read.`);
109
+ }
110
+ }
111
+ return good(color);
112
+ }
113
+ case 'choice':
114
+ return typeof value === 'string' && field.options.some((o) => o.value === value) ? good(value) : bad('Choose one of the options.');
115
+ case 'toggle':
116
+ return typeof value === 'boolean' ? good(value) : bad('Choose on or off.');
117
+ case 'list': {
118
+ if (!Array.isArray(value))
119
+ return bad('Not a list.');
120
+ const max = Math.min(field.maxItems ?? LIST_MAX, 50);
121
+ if (value.length > max)
122
+ return bad(`At most ${max} items.`);
123
+ if (field.minItems && value.length < field.minItems)
124
+ return bad(`At least ${field.minItems} item${field.minItems === 1 ? '' : 's'}.`);
125
+ const items = [];
126
+ for (let i = 0; i < value.length; i++) {
127
+ const item = value[i];
128
+ if (!item || typeof item !== 'object' || Array.isArray(item))
129
+ return bad(`Item ${i + 1} is not valid.`);
130
+ const out = {};
131
+ for (const sub of field.fields) {
132
+ const raw = item[sub.id];
133
+ const checked = checkFieldValue(sub, raw === undefined ? emptyValue(sub) : raw);
134
+ if (!checked.ok)
135
+ return bad(`${field.itemLabel} ${i + 1}, ${sub.label}: ${checked.problem}`);
136
+ out[sub.id] = checked.value;
137
+ }
138
+ items.push(out);
139
+ }
140
+ return good(items);
141
+ }
142
+ }
143
+ }
144
+ /** The value an empty input stands for. */
145
+ export function emptyValue(field) {
146
+ switch (field.type) {
147
+ case 'toggle':
148
+ return false;
149
+ case 'image':
150
+ return null;
151
+ case 'list':
152
+ return [];
153
+ case 'color':
154
+ case 'choice':
155
+ return field.default;
156
+ default:
157
+ return '';
158
+ }
159
+ }
160
+ /**
161
+ * Checks a whole document against a website's schema: known fields only
162
+ * (unknown keys are dropped), each normalised. Problems are by field id.
163
+ */
164
+ export function checkSiteContent(schema, values) {
165
+ const out = {};
166
+ const problems = {};
167
+ for (const field of allFields(schema)) {
168
+ if (!(field.id in values))
169
+ continue;
170
+ const checked = checkFieldValue(field, values[field.id]);
171
+ if (checked.ok)
172
+ out[field.id] = checked.value;
173
+ else
174
+ problems[field.id] = checked.problem;
175
+ }
176
+ return { values: out, problems };
177
+ }
@@ -0,0 +1,19 @@
1
+ import type { EngineError, EngineErrorCode, Result } from './types.js';
2
+ export declare function engineError(code: EngineErrorCode, field?: string, message?: string): EngineError;
3
+ export declare function fail<T>(code: EngineErrorCode, field?: string, message?: string): Result<T>;
4
+ export declare function ok<T>(data: T): Result<T>;
5
+ /** Default English message for a code; sites can use their own copy instead. */
6
+ export declare function defaultMessage(code: EngineErrorCode): string;
7
+ /** Shape of supabase-js PostgrestError (kept structural to avoid a type dependency). */
8
+ interface PostgrestLikeError {
9
+ message?: string;
10
+ details?: string | null;
11
+ hint?: string | null;
12
+ code?: string;
13
+ }
14
+ /**
15
+ * Map a PostgREST / network error to the engine's error contract.
16
+ * Raw database messages are never shown to visitors.
17
+ */
18
+ export declare function mapRemoteError(error: PostgrestLikeError | null | undefined): EngineError;
19
+ export {};
package/dist/errors.js ADDED
@@ -0,0 +1,94 @@
1
+ const MESSAGES = {
2
+ INVALID_INPUT: 'Please check the information you entered.',
3
+ SERVICE_UNAVAILABLE: 'This service cannot be booked online right now.',
4
+ SLOT_UNAVAILABLE: 'That time is no longer available. Please choose another time.',
5
+ RATE_LIMITED: 'Too many booking requests. Please try again later or contact us directly.',
6
+ NOT_AUTHORIZED: 'You do not have access to this.',
7
+ NOT_FOUND: 'This item no longer exists.',
8
+ INVALID_TRANSITION: 'This change is not possible for this booking.',
9
+ CONFLICT: 'This change conflicts with existing data.',
10
+ PREVIEW_MODE: 'Preview mode: no booking was saved. Connect the backend to accept real bookings.',
11
+ NOT_CONFIGURED: 'The booking system is not connected yet.',
12
+ SCHEMA_MISSING: 'The booking database is not set up yet. Apply the Booking Engine migrations.',
13
+ SCHEMA_INCOMPATIBLE: 'The booking database version does not match this website. Apply the latest Booking Engine migrations.',
14
+ NETWORK: 'Could not reach the booking system. Check your connection and try again.',
15
+ UNKNOWN: 'Something went wrong. Please try again.',
16
+ BOOKING_DISABLED: 'Online booking is not available right now. Please contact us to book.',
17
+ VERIFICATION_REQUIRED: 'This website needs an update to accept bookings: bookings now require an email code.',
18
+ INVALID_CODE: 'That code is not right. Please check the email and try again.',
19
+ CODE_EXPIRED: 'This code has expired. Please choose your time again to get a new code.',
20
+ TOO_MANY_ATTEMPTS: 'Too many incorrect codes. Please choose your time again to get a new code.',
21
+ TOO_MANY_BOOKINGS: 'You already have the maximum number of upcoming bookings. Please contact us to book more.',
22
+ RESEND_TOO_SOON: 'Please wait a moment before asking for a new code.',
23
+ RESEND_LIMIT: 'No more codes can be sent for this request. Please choose your time again.',
24
+ };
25
+ const FIELD_MESSAGES = {
26
+ 'customer.name': 'Please enter your name.',
27
+ 'customer.email': 'Please enter a valid email address.',
28
+ 'customer.phone': 'Please enter a valid phone number.',
29
+ notes: 'Notes can be up to 1,000 characters.',
30
+ startsAt: 'Please choose a time.',
31
+ serviceId: 'Please choose a service.',
32
+ timezone: 'Please choose a valid time zone.',
33
+ currency: 'Use a 3-letter currency code, e.g. USD or EUR.',
34
+ locale: 'Use a language code such as en-US or fr-FR.',
35
+ publicEmail: 'Please enter a valid email address.',
36
+ durationMinutes: 'Duration must be between 5 and 720 minutes.',
37
+ 'hours.overlap': 'Opening hours on the same day overlap.',
38
+ 'hours.order': 'Each opening time must be before its closing time.',
39
+ services_exist: 'Starter services can only be added to an empty service list.',
40
+ service_has_bookings: 'This service has bookings. Deactivate it instead of deleting it.',
41
+ slot_taken: 'Someone else has booked this time since the request expired. Contact the client to choose another time.',
42
+ pendingHoldMinutes: 'Choose a hold between 15 minutes and 7 days.',
43
+ code: 'Enter the 6-digit code from the email.',
44
+ requestId: 'This booking request is no longer open. Please choose your time again.',
45
+ recipient: 'Please enter a valid email address.',
46
+ ownerNotificationEmail: 'Please enter a valid email address.',
47
+ verificationWindowMinutes: 'Choose between 5 and 30 minutes.',
48
+ maxVerificationEmailsPerDay: 'Choose between 1 and 5,000 code emails per day.',
49
+ maxWebsiteBookingsPerHour: 'Choose between 1 and 1,000 requests per hour.',
50
+ onlineBookingEnabled: 'Send a test email and check that it arrives before switching online booking on.',
51
+ already_verified: 'This request is already verified: enter the same code again to see the confirmation.',
52
+ not_started: 'You can mark an appointment completed or no-show once it has started.',
53
+ };
54
+ export function engineError(code, field, message) {
55
+ const fieldMessage = field ? FIELD_MESSAGES[field] : undefined;
56
+ const error = { code, message: message ?? fieldMessage ?? MESSAGES[code] };
57
+ if (field)
58
+ error.field = field;
59
+ return error;
60
+ }
61
+ export function fail(code, field, message) {
62
+ return { ok: false, error: engineError(code, field, message) };
63
+ }
64
+ export function ok(data) {
65
+ return { ok: true, data };
66
+ }
67
+ /** Default English message for a code; sites can use their own copy instead. */
68
+ export function defaultMessage(code) {
69
+ return MESSAGES[code];
70
+ }
71
+ const KNOWN_CODES = new Set(Object.keys(MESSAGES));
72
+ /**
73
+ * Map a PostgREST / network error to the engine's error contract.
74
+ * Raw database messages are never shown to visitors.
75
+ */
76
+ export function mapRemoteError(error) {
77
+ const message = error?.message ?? '';
78
+ const engine = /^booking_engine:([A-Z_]+)$/.exec(message);
79
+ if (engine && engine[1] && KNOWN_CODES.has(engine[1])) {
80
+ const field = error?.details ? String(error.details) : undefined;
81
+ return engineError(engine[1], field || undefined);
82
+ }
83
+ const code = error?.code ?? '';
84
+ if (code === '42501' || code === 'PGRST301' || code === 'PGRST302' || code === 'PGRST303') {
85
+ return engineError('NOT_AUTHORIZED');
86
+ }
87
+ if (code === 'PGRST202' || code === '42883' || code === '3F000') {
88
+ return engineError('SCHEMA_MISSING');
89
+ }
90
+ if (/fetch|network|Failed to fetch|NetworkError|ECONNREFUSED|ENOTFOUND/i.test(message) || code === '') {
91
+ return engineError('NETWORK');
92
+ }
93
+ return engineError('UNKNOWN');
94
+ }
@@ -0,0 +1,6 @@
1
+ export declare const ENGINE_PACKAGE = "@profitstudio/booking-engine";
2
+ export declare const ENGINE_VERSION = "2.0.0-beta.1";
3
+ /** Schema version this package's migrations produce. */
4
+ export declare const SCHEMA_VERSION = "2.0.0-alpha.10";
5
+ /** Oldest database schema this package can talk to (same major). */
6
+ export declare const REQUIRED_SCHEMA_VERSION = "2.0.0-alpha.5";
@@ -0,0 +1,7 @@
1
+ // GENERATED by scripts/build.mjs from package.json — do not edit.
2
+ export const ENGINE_PACKAGE = "@profitstudio/booking-engine";
3
+ export const ENGINE_VERSION = "2.0.0-beta.1";
4
+ /** Schema version this package's migrations produce. */
5
+ export const SCHEMA_VERSION = "2.0.0-alpha.10";
6
+ /** Oldest database schema this package can talk to (same major). */
7
+ export const REQUIRED_SCHEMA_VERSION = "2.0.0-alpha.5";
@@ -0,0 +1,20 @@
1
+ export { createBookingEngine, assertPublishableKey, SERVICE_MEDIA_SCHEMA, SITE_CONTENT_SCHEMA, SITE_MEDIA_BUCKET } from './client.js';
2
+ export type { AdminApi, AuthApi, BookingEngine, BookingEngineOptions, PreviewOptions } from './client.js';
3
+ export { BACKEND_ENV, BACKEND_ENV_ALIASES, checkBackendEnv } from './config.js';
4
+ export type { BackendEnvCheck } from './config.js';
5
+ export type { AdminBooking, AdminIdentity, AdminService, AdminSettings, AdminSiteContent, Availability, AvailabilityDay, AvailabilityException, AvailabilityQuery, BookingConfirmation, BookingListQuery, BookingPolicies, BookingRequest, BookingStatus, Business, CodeResent, DayStatus, EmailDeliveryStatus, EmailKind, EmailStatus, EngineError, EngineErrorCode, EngineInfo, EngineMode, ExceptionInput, OpeningHoursInterval, OpeningTimes, OpeningTimesDay, OpeningTimesQuery, PendingVerification, Preset, PresetService, PublishedSiteContent, RequestDiagnostics, RequestReleased, Result, Service, ServiceImage, ServiceImageInput, ServiceInput, SettingsPatch, Slot, UploadedSiteImage, VerifyBookingInput, Weekday, } from './types.js';
6
+ export { addDays, deviceTimeZone, formatDate, formatClockTime, formatDateTime, formatMoney, formatTime, isDifferentTimeZone, localTimeLabel, timeZoneLabel, todayInTimeZone, weekdayOf, } from './time.js';
7
+ export { FEW_LEFT_MAX, PARTS_OF_DAY, addMonths, daysInMonth, firstDayOfWeek, groupSlotsByPartOfDay, isFewLeft, monthGrid, monthOf, nextAvailableDay, partOfDay, startOfWeek, weekDates, } from './calendar.js';
8
+ export type { MonthGrid, PartOfDay } from './calendar.js';
9
+ export { defaultMessage, mapRemoteError } from './errors.js';
10
+ export { compareVersions, isSchemaCompatible } from './semver.js';
11
+ export { ENGINE_PACKAGE, ENGINE_VERSION, REQUIRED_SCHEMA_VERSION, SCHEMA_VERSION } from './generated/manifest.js';
12
+ export { hairSalonPreset, presets } from './presets/index.js';
13
+ export { defineSiteContent, allFields, FIELD_ID_RE, ITEM_FIELD_ID_RE } from './content/schema.js';
14
+ export type { ChoiceField, ColorField, ContentField, ContentSection, ImageField, LinkField, ListField, ListItemField, ListItemValue, LongTextField, SiteContentSchema, SiteContentValues, SiteImage, StoredContentValues, StoredImage, TextField, ToggleField, } from './content/schema.js';
15
+ export { checkFieldValue, checkSiteContent, contrastRatio, emptyValue, isHexColor, isStoredImage, safeHref } from './content/validate.js';
16
+ export { defaultSiteContent, ownerFieldIds, resolveSiteContent } from './content/resolve.js';
17
+ export type { MediaUrl } from './content/resolve.js';
18
+ export { createSiteContentStore, previewRequested, readSiteContentSnapshot, siteContentSnapshotTag } from './content/store.js';
19
+ export type { PublishedSnapshot, SiteContentState, SiteContentStore, SiteContentStoreOptions } from './content/store.js';
20
+ export { SITE_IMAGE_MAX_BYTES, SITE_IMAGE_MAX_DIMENSION, SITE_IMAGE_TYPES } from './content/image.js';
package/dist/index.js ADDED
@@ -0,0 +1,20 @@
1
+ // @profitstudio/booking-engine — public entry point.
2
+ // Everything exported here is the stable integration contract (see docs/INTEGRATION.md).
3
+ export { createBookingEngine, assertPublishableKey, SERVICE_MEDIA_SCHEMA, SITE_CONTENT_SCHEMA, SITE_MEDIA_BUCKET } from './client.js';
4
+ export { BACKEND_ENV, BACKEND_ENV_ALIASES, checkBackendEnv } from './config.js';
5
+ export { addDays, deviceTimeZone, formatDate, formatClockTime, formatDateTime, formatMoney, formatTime, isDifferentTimeZone, localTimeLabel, timeZoneLabel, todayInTimeZone, weekdayOf, } from './time.js';
6
+ // Calendar view helpers for a booking UI (month grid, week strip, parts of the
7
+ // day, "few left", next available day): they only reshape getAvailability()
8
+ // data — see docs/INTEGRATION.md §8–§9.
9
+ export { FEW_LEFT_MAX, PARTS_OF_DAY, addMonths, daysInMonth, firstDayOfWeek, groupSlotsByPartOfDay, isFewLeft, monthGrid, monthOf, nextAvailableDay, partOfDay, startOfWeek, weekDates, } from './calendar.js';
10
+ export { defaultMessage, mapRemoteError } from './errors.js';
11
+ export { compareVersions, isSchemaCompatible } from './semver.js';
12
+ export { ENGINE_PACKAGE, ENGINE_VERSION, REQUIRED_SCHEMA_VERSION, SCHEMA_VERSION } from './generated/manifest.js';
13
+ export { hairSalonPreset, presets } from './presets/index.js';
14
+ // Website content (owner customization): the typed contract between a website
15
+ // and the dashboard — see docs/INTEGRATION.md, "Website content".
16
+ export { defineSiteContent, allFields, FIELD_ID_RE, ITEM_FIELD_ID_RE } from './content/schema.js';
17
+ export { checkFieldValue, checkSiteContent, contrastRatio, emptyValue, isHexColor, isStoredImage, safeHref } from './content/validate.js';
18
+ export { defaultSiteContent, ownerFieldIds, resolveSiteContent } from './content/resolve.js';
19
+ export { createSiteContentStore, previewRequested, readSiteContentSnapshot, siteContentSnapshotTag } from './content/store.js';
20
+ export { SITE_IMAGE_MAX_BYTES, SITE_IMAGE_MAX_DIMENSION, SITE_IMAGE_TYPES } from './content/image.js';
@@ -0,0 +1,8 @@
1
+ import type { Preset } from '../types.js';
2
+ /**
3
+ * Hair Salon — appointment model, one chair/calendar.
4
+ * Operational starter data only: services, durations, cleanup buffers, hours
5
+ * and policies. Prices and the preview business are fictional examples that
6
+ * the owner replaces in the admin dashboard.
7
+ */
8
+ export declare const hairSalonPreset: Preset;
@@ -0,0 +1,94 @@
1
+ /**
2
+ * Hair Salon — appointment model, one chair/calendar.
3
+ * Operational starter data only: services, durations, cleanup buffers, hours
4
+ * and policies. Prices and the preview business are fictional examples that
5
+ * the owner replaces in the admin dashboard.
6
+ */
7
+ export const hairSalonPreset = {
8
+ id: 'hair-salon',
9
+ label: 'Hair Salon',
10
+ terminology: { customer: 'client', customers: 'clients', booking: 'appointment', bookings: 'appointments' },
11
+ previewBusiness: {
12
+ name: 'Sample Hair Studio',
13
+ currency: 'USD',
14
+ locale: 'en-US',
15
+ contact: { email: 'hello@example.com', phone: '+1 555 0100', address: '123 Example Street, Springfield' },
16
+ },
17
+ policies: {
18
+ slotIntervalMinutes: 15,
19
+ minNoticeMinutes: 120,
20
+ maxAdvanceDays: 60,
21
+ autoConfirm: false,
22
+ requirePhone: true,
23
+ pendingHoldMinutes: 1440,
24
+ verificationWindowMinutes: 15,
25
+ },
26
+ workingHours: [
27
+ { weekday: 2, start: '09:00', end: '18:00' },
28
+ { weekday: 3, start: '09:00', end: '18:00' },
29
+ { weekday: 4, start: '10:00', end: '20:00' },
30
+ { weekday: 5, start: '09:00', end: '18:00' },
31
+ { weekday: 6, start: '09:00', end: '16:00' },
32
+ ],
33
+ services: [
34
+ {
35
+ name: 'Cut & Style',
36
+ description: 'Consultation, wash, precision cut and finish.',
37
+ durationMinutes: 60,
38
+ bufferAfterMinutes: 15,
39
+ priceCents: 6500,
40
+ },
41
+ {
42
+ name: 'Short Cut',
43
+ description: 'Clipper or scissor cut for short hair, with wash and finish.',
44
+ durationMinutes: 30,
45
+ bufferAfterMinutes: 10,
46
+ priceCents: 3500,
47
+ },
48
+ {
49
+ name: 'Blow-Dry & Style',
50
+ description: 'Wash and blow-dry styled smooth, voluminous or curled.',
51
+ durationMinutes: 45,
52
+ bufferAfterMinutes: 10,
53
+ priceCents: 4500,
54
+ },
55
+ {
56
+ name: 'Root Color',
57
+ description: 'Single-process color on regrowth, with gloss and blow-dry.',
58
+ durationMinutes: 90,
59
+ bufferAfterMinutes: 15,
60
+ priceCents: 8500,
61
+ priceFrom: true,
62
+ },
63
+ {
64
+ name: 'Full Color',
65
+ description: 'All-over color, gloss and blow-dry. Final price depends on length.',
66
+ durationMinutes: 120,
67
+ bufferAfterMinutes: 15,
68
+ priceCents: 12000,
69
+ priceFrom: true,
70
+ },
71
+ {
72
+ name: 'Balayage',
73
+ description: 'Hand-painted highlights with toner, treatment and style.',
74
+ durationMinutes: 180,
75
+ bufferAfterMinutes: 15,
76
+ priceCents: 18000,
77
+ priceFrom: true,
78
+ },
79
+ {
80
+ name: "Children's Cut",
81
+ description: 'For children under 12.',
82
+ durationMinutes: 30,
83
+ bufferAfterMinutes: 10,
84
+ priceCents: 2500,
85
+ },
86
+ {
87
+ name: 'Deep Conditioning Treatment',
88
+ description: 'Restorative mask and scalp massage. Can be added to any service.',
89
+ durationMinutes: 30,
90
+ bufferAfterMinutes: 10,
91
+ priceCents: 3000,
92
+ },
93
+ ],
94
+ };
@@ -0,0 +1,5 @@
1
+ import type { Preset } from '../types.js';
2
+ import { hairSalonPreset } from './hair-salon.js';
3
+ export { hairSalonPreset };
4
+ /** Presets shipped with this engine version, by id. */
5
+ export declare const presets: Readonly<Record<string, Preset>>;
@@ -0,0 +1,6 @@
1
+ import { hairSalonPreset } from './hair-salon.js';
2
+ export { hairSalonPreset };
3
+ /** Presets shipped with this engine version, by id. */
4
+ export const presets = Object.freeze({
5
+ [hairSalonPreset.id]: hairSalonPreset,
6
+ });
@@ -0,0 +1,18 @@
1
+ import type { Availability, AvailabilityQuery, Business, CodeResent, OpeningTimes, PendingVerification, Preset, RequestReleased, Result, Service } from './types.js';
2
+ export interface PreviewOptions {
3
+ preset: Preset;
4
+ /** Override the fictional business shown in preview (e.g. the name the AI designed). */
5
+ business?: Partial<Pick<Business, 'name' | 'timezone' | 'currency' | 'locale'>> & {
6
+ contact?: Partial<Business['contact']>;
7
+ };
8
+ }
9
+ export declare function createPreviewData(options: PreviewOptions): {
10
+ business: Business;
11
+ services: Service[];
12
+ availability: (query: AvailabilityQuery, now?: Date) => Result<Availability>;
13
+ openingTimes: (from: string, to: string) => Result<OpeningTimes>;
14
+ requestBooking: (email: string, now?: Date) => Result<PendingVerification>;
15
+ verifyBooking: (requestId: string, now?: Date) => Result<never>;
16
+ resendCode: (requestId: string, now?: Date) => Result<CodeResent>;
17
+ cancelRequest: (requestId: string, now?: Date) => Result<RequestReleased>;
18
+ };
@@ -0,0 +1,134 @@
1
+ // Preview mode: fictional preset data so a website can be designed before a
2
+ // backend exists. It must never pretend a booking was saved or an email sent:
3
+ // requestBooking answers with delivery 'preview' (no email; any 6 digits are
4
+ // accepted as the code) and verifyBooking always returns PREVIEW_MODE.
5
+ import { engineError, fail, ok } from './errors.js';
6
+ import { addDays, deviceTimeZone, localTimeLabel, todayInTimeZone, weekdayOf, zonedTimeToUtc } from './time.js';
7
+ const MAX_DAYS = 42;
8
+ export function createPreviewData(options) {
9
+ const { preset } = options;
10
+ const timezone = options.business?.timezone ?? deviceTimeZone() ?? 'UTC';
11
+ const business = {
12
+ name: options.business?.name ?? preset.previewBusiness.name,
13
+ timezone,
14
+ currency: options.business?.currency ?? preset.previewBusiness.currency,
15
+ locale: options.business?.locale ?? preset.previewBusiness.locale,
16
+ contact: { ...preset.previewBusiness.contact, ...options.business?.contact },
17
+ // Preview shows the booking form; nothing is saved or emailed.
18
+ policies: { ...preset.policies, onlineBookingEnabled: true },
19
+ openingHours: preset.workingHours.map((h) => ({ ...h })),
20
+ };
21
+ const services = preset.services.map((s, i) => ({
22
+ id: `preview-${preset.id}-${i + 1}`,
23
+ name: s.name,
24
+ description: s.description ?? null,
25
+ durationMinutes: s.durationMinutes,
26
+ priceCents: s.priceCents ?? null,
27
+ priceFrom: s.priceFrom ?? false,
28
+ currency: business.currency,
29
+ // Preview has no uploaded photos: a website shows its no-photo design.
30
+ image: null,
31
+ }));
32
+ /** The weekly hours per date (preview knows no closures). */
33
+ function openingTimes(from, to) {
34
+ const days = [];
35
+ for (let date = from, n = 0; date <= to; date = addDays(date, 1), n++) {
36
+ if (n >= MAX_DAYS)
37
+ return fail('INVALID_INPUT', 'to');
38
+ const hours = business.openingHours
39
+ .filter((h) => h.weekday === weekdayOf(date))
40
+ .map((h) => ({ start: h.start, end: h.end }))
41
+ .sort((a, b) => a.start.localeCompare(b.start));
42
+ days.push({ date, hours });
43
+ }
44
+ return ok({ timezone, from, to, days });
45
+ }
46
+ function availability(query, now = new Date()) {
47
+ const service = services.find((s) => s.id === query.serviceId);
48
+ if (!service)
49
+ return fail('SERVICE_UNAVAILABLE');
50
+ const to = query.to ?? query.from;
51
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(query.from))
52
+ return fail('INVALID_INPUT', 'from');
53
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(to) || to < query.from)
54
+ return fail('INVALID_INPUT', 'to');
55
+ const { slotIntervalMinutes, minNoticeMinutes, maxAdvanceDays } = business.policies;
56
+ const today = todayInTimeZone(timezone, now);
57
+ const last = addDays(today, maxAdvanceDays);
58
+ const earliest = now.getTime() + minNoticeMinutes * 60000;
59
+ const days = [];
60
+ for (let date = query.from, n = 0; date <= to; date = addDays(date, 1), n++) {
61
+ if (n >= MAX_DAYS)
62
+ return fail('INVALID_INPUT', 'to');
63
+ const hours = business.openingHours.filter((h) => h.weekday === weekdayOf(date));
64
+ if (date < today || date > last) {
65
+ days.push({ date, status: 'unavailable', slots: [] });
66
+ continue;
67
+ }
68
+ if (!hours.length) {
69
+ days.push({ date, status: 'closed', slots: [] });
70
+ continue;
71
+ }
72
+ const slots = [];
73
+ for (const h of hours) {
74
+ const open = zonedTimeToUtc(date, h.start, timezone);
75
+ const close = zonedTimeToUtc(date, h.end, timezone);
76
+ for (let t = open; t + service.durationMinutes * 60000 <= close; t += slotIntervalMinutes * 60000) {
77
+ if (t < earliest)
78
+ continue;
79
+ slots.push({
80
+ startsAt: new Date(t).toISOString().replace('.000Z', 'Z'),
81
+ endsAt: new Date(t + service.durationMinutes * 60000).toISOString().replace('.000Z', 'Z'),
82
+ time: localTimeLabel(t, timezone),
83
+ });
84
+ }
85
+ }
86
+ slots.sort((a, b) => a.startsAt.localeCompare(b.startsAt));
87
+ days.push({ date, status: slots.length ? 'available' : 'full', slots });
88
+ }
89
+ return ok({ serviceId: service.id, timezone, from: query.from, to, days });
90
+ }
91
+ const requests = new Map();
92
+ const iso = (t) => new Date(t).toISOString().replace(/\.\d{3}Z$/, 'Z');
93
+ /** A held time in preview: no email is sent, nothing is stored outside this page. */
94
+ function requestBooking(email, now = new Date()) {
95
+ const requestId = `preview-${Math.random().toString(36).slice(2, 10)}`;
96
+ const expiresAt = now.getTime() + business.policies.verificationWindowMinutes * 60000;
97
+ requests.set(requestId, { expiresAt, sends: 1, lastSent: now.getTime() });
98
+ const at = email.indexOf('@');
99
+ return ok({
100
+ requestId,
101
+ expiresAt: iso(expiresAt),
102
+ email: at > 0 ? `${email[0]}***${email.slice(at)}` : '***',
103
+ codeLength: 6,
104
+ resendAfterSeconds: 60,
105
+ resendsLeft: 3,
106
+ delivery: 'preview',
107
+ });
108
+ }
109
+ function cancelRequest(requestId, now = new Date()) {
110
+ const r = requests.get(requestId);
111
+ requests.delete(requestId);
112
+ return ok({ released: Boolean(r && r.expiresAt > now.getTime()) });
113
+ }
114
+ function verifyBooking(requestId, now = new Date()) {
115
+ const r = requests.get(requestId);
116
+ if (!r || r.expiresAt <= now.getTime())
117
+ return fail('CODE_EXPIRED');
118
+ return fail('PREVIEW_MODE');
119
+ }
120
+ function resendCode(requestId, now = new Date()) {
121
+ const r = requests.get(requestId);
122
+ if (!r || r.expiresAt <= now.getTime())
123
+ return fail('CODE_EXPIRED');
124
+ if (r.sends >= 4)
125
+ return fail('RESEND_LIMIT');
126
+ const wait = Math.ceil((r.lastSent + 60000 - now.getTime()) / 1000);
127
+ if (wait > 0)
128
+ return { ok: false, error: { ...engineError('RESEND_TOO_SOON'), retryAfterSeconds: wait } };
129
+ r.sends += 1;
130
+ r.lastSent = now.getTime();
131
+ return ok({ expiresAt: iso(r.expiresAt), resendsLeft: 4 - r.sends, resendAfterSeconds: 60, delivery: 'preview' });
132
+ }
133
+ return { business, services, availability, openingTimes, requestBooking, verifyBooking, resendCode, cancelRequest };
134
+ }
@@ -0,0 +1,16 @@
1
+ interface Parsed {
2
+ major: number;
3
+ minor: number;
4
+ patch: number;
5
+ pre: Array<string | number>;
6
+ }
7
+ export declare function parseVersion(version: string): Parsed | null;
8
+ /** -1, 0 or 1. Throws on an invalid version. */
9
+ export declare function compareVersions(a: string, b: string): number;
10
+ /**
11
+ * A database at `schemaVersion` can serve a client that requires `required`
12
+ * when the MAJOR matches and the database is not older. Newer minor versions
13
+ * only add, so older clients keep working.
14
+ */
15
+ export declare function isSchemaCompatible(schemaVersion: string, required: string): boolean;
16
+ export {};