@profitstudio/booking-engine 0.0.0-stage → 2.0.0-beta.2

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 +578 -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 +29 -0
  9. package/dist/admin/BookingAdmin.js +338 -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 +47 -0
  14. package/dist/admin/booking-detail.js +159 -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 +41 -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 +7 -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 +184 -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 +1112 -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,90 @@
1
+ // Preparing an owner's photo for the website, in the browser, before upload:
2
+ // images only (no SVG: it can carry scripts); camera photos (JPEG) are always
3
+ // redrawn, so their hidden EXIF data — often the GPS position where they were
4
+ // taken — is never published; other images are re-encoded only when larger
5
+ // than needed. The storage bucket enforces type and size again on the server.
6
+ export const SITE_IMAGE_TYPES = ['image/jpeg', 'image/png', 'image/webp', 'image/avif'];
7
+ /** The bucket's limit. */
8
+ export const SITE_IMAGE_MAX_BYTES = 5 * 1024 * 1024;
9
+ /** Longest side after scaling. */
10
+ export const SITE_IMAGE_MAX_DIMENSION = 2400;
11
+ const EXTENSIONS = { 'image/jpeg': 'jpg', 'image/png': 'png', 'image/webp': 'webp', 'image/avif': 'avif' };
12
+ export class ImageProblem extends Error {
13
+ }
14
+ /** Redraws the pixels (nothing else survives) as `type`; null when this browser cannot write that type. */
15
+ async function encode(source, width, height, type) {
16
+ const quality = type === 'image/webp' ? 0.85 : 0.88;
17
+ const draw = (ctx) => {
18
+ if (!ctx)
19
+ return false;
20
+ ctx.drawImage(source, 0, 0, width, height);
21
+ return true;
22
+ };
23
+ let blob = null;
24
+ if (typeof OffscreenCanvas !== 'undefined') {
25
+ const canvas = new OffscreenCanvas(width, height);
26
+ if (!draw(canvas.getContext('2d')))
27
+ return null;
28
+ try {
29
+ blob = await canvas.convertToBlob({ type, quality });
30
+ }
31
+ catch {
32
+ return null;
33
+ }
34
+ }
35
+ else if (typeof document !== 'undefined') {
36
+ const canvas = document.createElement('canvas');
37
+ canvas.width = width;
38
+ canvas.height = height;
39
+ if (!draw(canvas.getContext('2d')))
40
+ return null;
41
+ blob = await new Promise((resolve) => canvas.toBlob((b) => resolve(b), type, quality));
42
+ }
43
+ // A browser that cannot write the type silently returns PNG instead.
44
+ return blob && blob.type === type ? blob : null;
45
+ }
46
+ /**
47
+ * Checks the file, redraws camera photos (dropping their metadata) and scales
48
+ * down anything larger than needed. Throws ImageProblem with a message for the
49
+ * owner.
50
+ */
51
+ export async function prepareSiteImage(file) {
52
+ if (!SITE_IMAGE_TYPES.includes(file.type)) {
53
+ throw new ImageProblem('Use a JPEG, PNG, WebP or AVIF image.');
54
+ }
55
+ if (file.size > 25 * 1024 * 1024)
56
+ throw new ImageProblem('That file is too large (more than 25 MB).');
57
+ let bitmap;
58
+ try {
59
+ bitmap = await createImageBitmap(file);
60
+ }
61
+ catch {
62
+ throw new ImageProblem('This image could not be read. Try another file.');
63
+ }
64
+ try {
65
+ const scale = Math.min(1, SITE_IMAGE_MAX_DIMENSION / Math.max(bitmap.width, bitmap.height));
66
+ const width = Math.round(bitmap.width * scale);
67
+ const height = Math.round(bitmap.height * scale);
68
+ const photo = file.type === 'image/jpeg';
69
+ let prepared = null;
70
+ if (photo || scale < 1 || file.size > 1.5 * 1024 * 1024) {
71
+ const webp = await encode(bitmap, width, height, 'image/webp');
72
+ if (webp && (photo || webp.size < file.size))
73
+ prepared = { blob: webp, type: 'image/webp', extension: 'webp', width, height };
74
+ else if (photo) {
75
+ // No WebP writer (older Safari): JPEG, which every browser writes (a photo has no transparency to lose).
76
+ const jpeg = await encode(bitmap, width, height, 'image/jpeg');
77
+ if (!jpeg)
78
+ throw new ImageProblem('This photo could not be prepared for the website. Try another file.');
79
+ prepared = { blob: jpeg, type: 'image/jpeg', extension: 'jpg', width, height };
80
+ }
81
+ }
82
+ prepared ??= { blob: file, type: file.type, extension: EXTENSIONS[file.type] ?? 'jpg', width: bitmap.width, height: bitmap.height };
83
+ if (prepared.blob.size > SITE_IMAGE_MAX_BYTES)
84
+ throw new ImageProblem('Images can be up to 5 MB. Try a smaller photo.');
85
+ return prepared;
86
+ }
87
+ finally {
88
+ bitmap.close();
89
+ }
90
+ }
@@ -0,0 +1,12 @@
1
+ import type { SiteContentSchema, SiteContentValues, StoredContentValues } from './schema.js';
2
+ /** Turns a media-bucket path into a public URL (null when there is no backend). */
3
+ export type MediaUrl = (path: string) => string | null;
4
+ /** Ids of the fields whose stored value is valid — what the owner has set (the rest show defaults). */
5
+ export declare function ownerFieldIds(schema: SiteContentSchema, stored: StoredContentValues | null | undefined): string[];
6
+ /** The website's defaults for every field. */
7
+ export declare function defaultSiteContent<S extends SiteContentSchema>(schema: S): SiteContentValues<S>;
8
+ /**
9
+ * Merges stored values over the defaults. Invalid or unknown stored values are
10
+ * ignored (the default shows), so nothing unexpected ever reaches the page.
11
+ */
12
+ export declare function resolveSiteContent<S extends SiteContentSchema>(schema: S, stored: StoredContentValues | null | undefined, mediaUrl: MediaUrl): SiteContentValues<S>;
@@ -0,0 +1,73 @@
1
+ import { allFields } from './schema.js';
2
+ import { checkFieldValue } from './validate.js';
3
+ function toSiteImage(image, mediaUrl) {
4
+ const src = mediaUrl(image.path);
5
+ if (!src)
6
+ return null;
7
+ return {
8
+ src,
9
+ alt: image.alt ?? '',
10
+ ...(image.width ? { width: image.width } : {}),
11
+ ...(image.height ? { height: image.height } : {}),
12
+ };
13
+ }
14
+ function resolveValue(field, stored, mediaUrl) {
15
+ if (field.type === 'image') {
16
+ if (stored === null)
17
+ return null; // the owner removed the image
18
+ return toSiteImage(stored, mediaUrl) ?? field.default;
19
+ }
20
+ if (field.type === 'list') {
21
+ return stored.map((item) => {
22
+ const out = {};
23
+ for (const sub of field.fields) {
24
+ out[sub.id] = sub.type === 'image' ? (item[sub.id] ? toSiteImage(item[sub.id], mediaUrl) : null) : item[sub.id];
25
+ }
26
+ return out;
27
+ });
28
+ }
29
+ return stored;
30
+ }
31
+ /** Ids of the fields whose stored value is valid — what the owner has set (the rest show defaults). */
32
+ export function ownerFieldIds(schema, stored) {
33
+ if (!stored)
34
+ return [];
35
+ return allFields(schema)
36
+ .filter((field) => field.id in stored && checkFieldValue(field, stored[field.id]).ok)
37
+ .map((field) => field.id);
38
+ }
39
+ /** The website's defaults for every field. */
40
+ export function defaultSiteContent(schema) {
41
+ const out = {};
42
+ for (const field of allFields(schema)) {
43
+ out[field.id] =
44
+ field.type === 'list'
45
+ ? field.default.map((item) => {
46
+ // Default items hold text only: their images are null, as typed (and as stored items resolve).
47
+ const copy = { ...item };
48
+ for (const sub of field.fields)
49
+ if (sub.type === 'image' && copy[sub.id] == null)
50
+ copy[sub.id] = null;
51
+ return copy;
52
+ })
53
+ : field.default;
54
+ }
55
+ return out;
56
+ }
57
+ /**
58
+ * Merges stored values over the defaults. Invalid or unknown stored values are
59
+ * ignored (the default shows), so nothing unexpected ever reaches the page.
60
+ */
61
+ export function resolveSiteContent(schema, stored, mediaUrl) {
62
+ const out = defaultSiteContent(schema);
63
+ if (!stored)
64
+ return out;
65
+ for (const field of allFields(schema)) {
66
+ if (!(field.id in stored))
67
+ continue;
68
+ const checked = checkFieldValue(field, stored[field.id]);
69
+ if (checked.ok)
70
+ out[field.id] = resolveValue(field, checked.value, mediaUrl);
71
+ }
72
+ return out;
73
+ }
@@ -0,0 +1,119 @@
1
+ /** An image the owner uploaded: a file in the media bucket. */
2
+ export interface StoredImage {
3
+ /** Path inside the media bucket, e.g. "site/3f1c….webp". */
4
+ path: string;
5
+ /** Text alternative for screen readers; empty only for decorative images. */
6
+ alt: string;
7
+ width?: number;
8
+ height?: number;
9
+ }
10
+ /** An image ready to render: from the owner's upload or the website's default. */
11
+ export interface SiteImage {
12
+ src: string;
13
+ alt: string;
14
+ width?: number;
15
+ height?: number;
16
+ }
17
+ interface FieldBase<T extends string> {
18
+ type: T;
19
+ /** Stable id: `section.name` style for top-level fields, `name` inside lists. */
20
+ id: string;
21
+ label: string;
22
+ /** One sentence under the input. */
23
+ help?: string;
24
+ }
25
+ /** One line of plain text (no markup). */
26
+ export interface TextField extends FieldBase<'text'> {
27
+ default: string;
28
+ /** Characters; default 160. */
29
+ maxLength?: number;
30
+ required?: boolean;
31
+ placeholder?: string;
32
+ }
33
+ /** Paragraphs of plain text: line breaks are kept, no markup. */
34
+ export interface LongTextField extends FieldBase<'longText'> {
35
+ default: string;
36
+ /** Characters; default 2000. */
37
+ maxLength?: number;
38
+ required?: boolean;
39
+ rows?: number;
40
+ }
41
+ /** A link: https:, mailto:, tel:, an in-page #anchor or a /path on this website. */
42
+ export interface LinkField extends FieldBase<'link'> {
43
+ default: string;
44
+ required?: boolean;
45
+ }
46
+ /** An image with its text alternative. `default: null` = optional image. */
47
+ export interface ImageField extends FieldBase<'image'> {
48
+ default: SiteImage | null;
49
+ /** Width ÷ height the design expects (the editor shows it; the site crops). */
50
+ aspectRatio?: number;
51
+ }
52
+ /** A brand colour, #rrggbb. */
53
+ export interface ColorField extends FieldBase<'color'> {
54
+ default: string;
55
+ /** Colour the brand colour sits on or next to; with minContrast, a WCAG check. */
56
+ contrastWith?: string;
57
+ /** Minimum contrast ratio against contrastWith (3 for large text, 4.5 for body text). */
58
+ minContrast?: number;
59
+ }
60
+ /** One of a few options the website offers (e.g. a heading style). */
61
+ export interface ChoiceField extends FieldBase<'choice'> {
62
+ default: string;
63
+ options: ReadonlyArray<{
64
+ value: string;
65
+ label: string;
66
+ description?: string;
67
+ }>;
68
+ }
69
+ /** On or off. */
70
+ export interface ToggleField extends FieldBase<'toggle'> {
71
+ default: boolean;
72
+ }
73
+ /** Fields allowed inside list items. */
74
+ export type ListItemField = TextField | LongTextField | LinkField | ImageField | ToggleField;
75
+ /** A list of items with the same fields (FAQ entries, team members, testimonials…). */
76
+ export interface ListField extends FieldBase<'list'> {
77
+ default: ReadonlyArray<Readonly<Record<string, string | boolean | SiteImage | null>>>;
78
+ fields: ReadonlyArray<ListItemField>;
79
+ /** What one item is called in the editor: "Question", "Team member". */
80
+ itemLabel: string;
81
+ /** Default 12, at most 50. */
82
+ maxItems?: number;
83
+ minItems?: number;
84
+ }
85
+ export type ContentField = TextField | LongTextField | LinkField | ImageField | ColorField | ChoiceField | ToggleField | ListField;
86
+ export interface ContentSection {
87
+ id: string;
88
+ label: string;
89
+ description?: string;
90
+ fields: ReadonlyArray<ContentField>;
91
+ }
92
+ export interface SiteContentSchema {
93
+ sections: ReadonlyArray<ContentSection>;
94
+ }
95
+ type FieldsOf<S extends SiteContentSchema> = S['sections'][number]['fields'][number];
96
+ type ItemValue<F> = F extends ImageField ? SiteImage | null : F extends ToggleField ? boolean : string;
97
+ export type ListItemValue<L extends ListField> = {
98
+ [F in L['fields'][number] as F['id']]: ItemValue<F>;
99
+ };
100
+ type FieldValue<F> = F extends ChoiceField ? F['options'][number]['value'] : F extends TextField | LongTextField | LinkField | ColorField ? string : F extends ToggleField ? boolean : F extends ImageField ? SiteImage | null : F extends ListField ? Array<ListItemValue<F>> : never;
101
+ /** The resolved content a website renders: every declared field, by id. */
102
+ export type SiteContentValues<S extends SiteContentSchema> = {
103
+ [F in FieldsOf<S> as F['id']]: FieldValue<F>;
104
+ };
105
+ /** What the database stores: field id → value (strings, booleans, images, lists). */
106
+ export type StoredContentValues = Record<string, unknown>;
107
+ /** Field ids at the top level, as the database accepts them. */
108
+ export declare const FIELD_ID_RE: RegExp;
109
+ /** Field ids inside list items. */
110
+ export declare const ITEM_FIELD_ID_RE: RegExp;
111
+ /**
112
+ * Declare the content a website's owner can edit. Returns the schema as given
113
+ * (typed), after checking it: unique valid ids, defaults that pass their own
114
+ * field's rules. Mistakes throw at start-up, never at an owner.
115
+ */
116
+ export declare function defineSiteContent<const S extends SiteContentSchema>(schema: S): S;
117
+ /** Every field, in declaration order. */
118
+ export declare function allFields(schema: SiteContentSchema): ContentField[];
119
+ export {};
@@ -0,0 +1,53 @@
1
+ // Website content contract: each website DECLARES the content its owner may
2
+ // edit (fields, types, defaults); the engine stores the owner's values and
3
+ // the dashboard renders an editor for whatever the website declared. The
4
+ // engine never decides how anything looks.
5
+ // ------------------------------------------------------------ definition ----
6
+ /** Field ids at the top level, as the database accepts them. */
7
+ export const FIELD_ID_RE = /^[a-z][a-zA-Z0-9]*(\.[a-zA-Z0-9_-]+){0,4}$/;
8
+ /** Field ids inside list items. */
9
+ export const ITEM_FIELD_ID_RE = /^[a-zA-Z][a-zA-Z0-9_]{0,31}$/;
10
+ /**
11
+ * Declare the content a website's owner can edit. Returns the schema as given
12
+ * (typed), after checking it: unique valid ids, defaults that pass their own
13
+ * field's rules. Mistakes throw at start-up, never at an owner.
14
+ */
15
+ export function defineSiteContent(schema) {
16
+ const problems = [];
17
+ const ids = new Set();
18
+ const sections = new Set();
19
+ for (const section of schema.sections) {
20
+ if (!section.id || sections.has(section.id))
21
+ problems.push(`section id "${section.id}" is missing or repeated`);
22
+ sections.add(section.id);
23
+ for (const field of section.fields) {
24
+ if (!FIELD_ID_RE.test(field.id) || field.id.length > 64)
25
+ problems.push(`field id "${field.id}" is not valid (e.g. "hero.title")`);
26
+ if (ids.has(field.id))
27
+ problems.push(`field id "${field.id}" is used twice`);
28
+ ids.add(field.id);
29
+ if (field.type === 'list') {
30
+ const itemIds = new Set();
31
+ for (const sub of field.fields) {
32
+ if (!ITEM_FIELD_ID_RE.test(sub.id) || itemIds.has(sub.id))
33
+ problems.push(`list "${field.id}": item field id "${sub.id}" is not valid or repeated`);
34
+ itemIds.add(sub.id);
35
+ // Images inside list items come from uploads only: a default item has none.
36
+ if (sub.type === 'image' && field.default.some((item) => item[sub.id] != null)) {
37
+ problems.push(`list "${field.id}": default items cannot have an image in "${sub.id}" (use null)`);
38
+ }
39
+ }
40
+ }
41
+ if (field.type === 'choice' && !field.options.some((o) => o.value === field.default)) {
42
+ problems.push(`choice "${field.id}": the default is not one of its options`);
43
+ }
44
+ }
45
+ }
46
+ if (problems.length)
47
+ throw new Error(`Booking Engine: invalid website content schema — ${problems.join('; ')}.`);
48
+ return schema;
49
+ }
50
+ /** Every field, in declaration order. */
51
+ export function allFields(schema) {
52
+ return schema.sections.flatMap((s) => [...s.fields]);
53
+ }
@@ -0,0 +1,48 @@
1
+ import type { BookingEngine } from '../client.js';
2
+ import type { SiteContentSchema, SiteContentValues, StoredContentValues } from './schema.js';
3
+ export interface SiteContentState<S extends SiteContentSchema> {
4
+ values: SiteContentValues<S>;
5
+ /** Where the values came from. */
6
+ source: 'defaults' | 'snapshot' | 'cache' | 'published' | 'draft';
7
+ /** Published version (0 = never published). */
8
+ version: number;
9
+ publishedAt: string | null;
10
+ /** True while showing an unpublished draft. */
11
+ preview: boolean;
12
+ /** Fields the owner has set (the others show the website's defaults) — e.g. to drop "placeholder" labels. */
13
+ ownerFields: string[];
14
+ /** ?preview=draft was asked for, but this visitor is not a signed-in admin. */
15
+ previewDenied?: boolean;
16
+ }
17
+ export interface SiteContentStore<S extends SiteContentSchema> {
18
+ /** Synchronous: for the first render (cached published copy, else defaults). */
19
+ initial(): SiteContentState<S>;
20
+ /** The current content (published, or the draft in an admin preview). */
21
+ load(): Promise<SiteContentState<S>>;
22
+ }
23
+ export interface SiteContentStoreOptions {
24
+ /** Show the draft to signed-in admins: true/false, or 'auto' (= ?preview=draft in the address). Default 'auto'. */
25
+ preview?: boolean | 'auto';
26
+ /** localStorage key for the last published copy; false = no cache. Default 'pbe-site-content'. */
27
+ cacheKey?: string | false;
28
+ /** The published copy at build time (see readSiteContentSnapshot): visitors see it on the first paint. */
29
+ snapshot?: PublishedSnapshot | null;
30
+ }
31
+ /** Published content as embedded in a page: { version, publishedAt, values }. */
32
+ export interface PublishedSnapshot {
33
+ version: number;
34
+ publishedAt: string | null;
35
+ values: StoredContentValues;
36
+ }
37
+ /**
38
+ * Reads the snapshot a build step embedded as
39
+ * <script type="application/json" id="site-content">{…}</script>.
40
+ */
41
+ export declare function readSiteContentSnapshot(id?: string): PublishedSnapshot | null;
42
+ /**
43
+ * The script tag a build step puts in the page for readSiteContentSnapshot.
44
+ * Escapes "<" so content can never close the tag (no HTML injection).
45
+ */
46
+ export declare function siteContentSnapshotTag(snapshot: PublishedSnapshot, id?: string): string;
47
+ export declare function previewRequested(): boolean;
48
+ export declare function createSiteContentStore<S extends SiteContentSchema>(engine: BookingEngine, schema: S, options?: SiteContentStoreOptions): SiteContentStore<S>;
@@ -0,0 +1,123 @@
1
+ import { ownerFieldIds, resolveSiteContent } from './resolve.js';
2
+ function isSnapshot(value) {
3
+ const v = value;
4
+ return Boolean(v && typeof v.version === 'number' && v.values && typeof v.values === 'object' && !Array.isArray(v.values));
5
+ }
6
+ /**
7
+ * Reads the snapshot a build step embedded as
8
+ * <script type="application/json" id="site-content">{…}</script>.
9
+ */
10
+ export function readSiteContentSnapshot(id = 'site-content') {
11
+ if (typeof document === 'undefined')
12
+ return null;
13
+ try {
14
+ const parsed = JSON.parse(document.getElementById(id)?.textContent ?? 'null');
15
+ return isSnapshot(parsed) ? parsed : null;
16
+ }
17
+ catch {
18
+ return null;
19
+ }
20
+ }
21
+ /**
22
+ * The script tag a build step puts in the page for readSiteContentSnapshot.
23
+ * Escapes "<" so content can never close the tag (no HTML injection).
24
+ */
25
+ export function siteContentSnapshotTag(snapshot, id = 'site-content') {
26
+ const json = JSON.stringify({ version: snapshot.version, publishedAt: snapshot.publishedAt, values: snapshot.values })
27
+ .replace(/</g, '\\u003c')
28
+ .replace(/\u2028/g, '\\u2028')
29
+ .replace(/\u2029/g, '\\u2029');
30
+ return `<script type="application/json" id="${id.replace(/[^\w-]/g, '')}">${json}</script>`;
31
+ }
32
+ function storage() {
33
+ try {
34
+ return typeof window !== 'undefined' ? window.localStorage : null;
35
+ }
36
+ catch {
37
+ return null;
38
+ }
39
+ }
40
+ export function previewRequested() {
41
+ if (typeof window === 'undefined')
42
+ return false;
43
+ return new URLSearchParams(window.location.search).get('preview') === 'draft';
44
+ }
45
+ export function createSiteContentStore(engine, schema, options = {}) {
46
+ const key = options.cacheKey === false ? null : (options.cacheKey ?? 'pbe-site-content');
47
+ const wantsPreview = options.preview === 'auto' || options.preview === undefined ? previewRequested() : options.preview;
48
+ const resolve = (values) => resolveSiteContent(schema, values, (path) => engine.mediaUrl(path));
49
+ function readCache() {
50
+ if (!key)
51
+ return null;
52
+ try {
53
+ const raw = storage()?.getItem(key);
54
+ const parsed = raw ? JSON.parse(raw) : null;
55
+ return isSnapshot(parsed) ? parsed : null;
56
+ }
57
+ catch {
58
+ return null;
59
+ }
60
+ }
61
+ const snapshot = options.snapshot && isSnapshot(options.snapshot) ? options.snapshot : null;
62
+ function writeCache(content) {
63
+ if (!key)
64
+ return;
65
+ try {
66
+ storage()?.setItem(key, JSON.stringify(content));
67
+ }
68
+ catch {
69
+ // Storage full or blocked: the next visit simply starts from the defaults.
70
+ }
71
+ }
72
+ return {
73
+ initial() {
74
+ const cached = wantsPreview ? null : readCache();
75
+ // The newer of the build-time snapshot and this browser's cache.
76
+ const best = cached && (!snapshot || cached.version >= snapshot.version) ? { from: 'cache', copy: cached } : snapshot ? { from: 'snapshot', copy: snapshot } : null;
77
+ return best
78
+ ? {
79
+ values: resolve(best.copy.values),
80
+ source: best.from,
81
+ version: best.copy.version,
82
+ publishedAt: best.copy.publishedAt,
83
+ preview: false,
84
+ ownerFields: ownerFieldIds(schema, best.copy.values),
85
+ }
86
+ : { values: resolve(null), source: 'defaults', version: 0, publishedAt: null, preview: false, ownerFields: [] };
87
+ },
88
+ async load() {
89
+ let previewDenied = false;
90
+ if (wantsPreview) {
91
+ // Only a signed-in visitor can be an admin: nobody else is sent to the admin API.
92
+ const draft = (await engine.auth.getUserEmail()) ? await engine.admin.getSiteContent() : null;
93
+ if (draft?.ok) {
94
+ return {
95
+ values: resolve(draft.data.draft),
96
+ source: 'draft',
97
+ version: draft.data.version,
98
+ publishedAt: draft.data.publishedAt,
99
+ preview: true,
100
+ ownerFields: ownerFieldIds(schema, draft.data.draft),
101
+ };
102
+ }
103
+ previewDenied = true;
104
+ }
105
+ const published = await engine.getSiteContent();
106
+ if (!published.ok) {
107
+ // Offline, no backend yet, or an older database: keep what we have.
108
+ return { ...this.initial(), ...(previewDenied ? { previewDenied } : {}) };
109
+ }
110
+ const { version, publishedAt, values } = published.data;
111
+ writeCache({ version, publishedAt, values });
112
+ return {
113
+ values: resolve(values),
114
+ source: 'published',
115
+ version,
116
+ publishedAt,
117
+ preview: false,
118
+ ownerFields: ownerFieldIds(schema, values),
119
+ ...(previewDenied ? { previewDenied } : {}),
120
+ };
121
+ },
122
+ };
123
+ }
@@ -0,0 +1,33 @@
1
+ import type { ContentField, ListItemField, SiteContentSchema, StoredContentValues, StoredImage } from './schema.js';
2
+ export declare const TEXT_MAX = 160;
3
+ export declare const LONG_TEXT_MAX = 2000;
4
+ export declare const LIST_MAX = 12;
5
+ export declare const ALT_MAX = 300;
6
+ export type Check<T> = {
7
+ ok: true;
8
+ value: T;
9
+ } | {
10
+ ok: false;
11
+ problem: string;
12
+ };
13
+ /**
14
+ * A link a website may put in href: https:/http:, mailto:, tel:, #anchor or a
15
+ * /path on the same site. Anything else (javascript:, data:, //host) → null.
16
+ */
17
+ export declare function safeHref(value: string): string | null;
18
+ export declare function isHexColor(value: unknown): value is string;
19
+ /** WCAG contrast ratio between two #rrggbb colours (1–21). */
20
+ export declare function contrastRatio(a: string, b: string): number;
21
+ export declare function isStoredImage(value: unknown): value is StoredImage;
22
+ /** Checks one value against its field. Images must be uploaded ones (StoredImage) or null. */
23
+ export declare function checkFieldValue(field: ContentField | ListItemField, value: unknown): Check<unknown>;
24
+ /** The value an empty input stands for. */
25
+ export declare function emptyValue(field: ContentField | ListItemField): unknown;
26
+ /**
27
+ * Checks a whole document against a website's schema: known fields only
28
+ * (unknown keys are dropped), each normalised. Problems are by field id.
29
+ */
30
+ export declare function checkSiteContent(schema: SiteContentSchema, values: StoredContentValues): {
31
+ values: StoredContentValues;
32
+ problems: Record<string, string>;
33
+ };