@semics-tech/emdash-events 0.0.0-stage → 1.0.0-rc.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +82 -2
  3. package/dist/index.d.mts +5 -0
  4. package/dist/index.mjs +392 -0
  5. package/dist/manifest.json +401 -0
  6. package/dist/plugin.d.mts +11 -0
  7. package/dist/plugin.mjs +7 -0
  8. package/dist/ts/astro/lib/call.d.ts +54 -0
  9. package/dist/ts/astro/lib/call.js +121 -0
  10. package/dist/ts/integration/index.d.ts +48 -0
  11. package/dist/ts/integration/index.js +76 -0
  12. package/dist/ts/ui/index.d.ts +6 -0
  13. package/dist/ts/ui/index.js +46 -0
  14. package/emdash-plugin.jsonc +206 -0
  15. package/package.json +77 -3
  16. package/src/astro/AddToCalendar.astro +47 -0
  17. package/src/astro/BookingBlock.astro +30 -0
  18. package/src/astro/BookingPage.astro +193 -0
  19. package/src/astro/BookingStatus.astro +106 -0
  20. package/src/astro/BookingWidget.astro +581 -0
  21. package/src/astro/CheckIn.astro +186 -0
  22. package/src/astro/DoorSignPage.astro +62 -0
  23. package/src/astro/EventCard.astro +81 -0
  24. package/src/astro/EventList.astro +83 -0
  25. package/src/astro/OptOutPage.astro +58 -0
  26. package/src/astro/PaymentReturn.astro +96 -0
  27. package/src/astro/TicketPass.astro +95 -0
  28. package/src/astro/checkout-endpoint.ts +11 -0
  29. package/src/astro/index.js +18 -0
  30. package/src/astro/lib/call.ts +185 -0
  31. package/src/astro/lib/checkout-form.ts +271 -0
  32. package/src/astro/lib/list.ts +99 -0
  33. package/src/astro/lib/opt-out.ts +49 -0
  34. package/src/astro/lib/pass.ts +35 -0
  35. package/src/astro/lib/payment.ts +73 -0
  36. package/src/astro/lib/promo.ts +162 -0
  37. package/src/astro/lib/questions.ts +107 -0
  38. package/src/astro/lib/receipt.ts +132 -0
  39. package/src/astro/lib/waitlist.ts +72 -0
  40. package/src/astro/lib/widget.ts +278 -0
  41. package/src/astro/promo-endpoint.ts +11 -0
  42. package/src/astro/virtual.d.ts +16 -0
  43. package/src/astro/waitlist-endpoint.ts +12 -0
  44. package/src/client/booking.ts +188 -0
  45. package/src/client/checkin.ts +260 -0
  46. package/src/client/payment.ts +76 -0
  47. package/src/client/receipt.ts +75 -0
  48. package/src/i18n/ar.ts +213 -0
  49. package/src/i18n/en.ts +219 -0
  50. package/src/i18n/index.ts +121 -0
@@ -0,0 +1,73 @@
1
+ /**
2
+ * What the booking page says about a paid booking (EU-FR-09). Pure: the state comes only from the
3
+ * core's `public/booking` answer. Stripe sends the buyer back to `/booking?ref=` on success and on
4
+ * cancel alike, with nothing in the URL to trust, so "paid", "abandoned" and "webhook still on its
5
+ * way" are told apart by asking the core, never by a query parameter.
6
+ */
7
+ import { type MessageKey, t } from "../../i18n/index";
8
+ import type { BookingView } from "./widget";
9
+
10
+ export type PaymentState = "confirmed" | "pending" | "expired" | "cancelled" | "refunded" | "refunded_unavailable";
11
+
12
+ export interface PaymentView {
13
+ state: PaymentState;
14
+ heading: string;
15
+ body: string;
16
+ /** The page re-reads the booking for a while (the webhook has not arrived yet). */
17
+ poll: boolean;
18
+ /** Offer "Pay now": the seats are still held and the payment has not been confirmed. */
19
+ resume: boolean;
20
+ }
21
+
22
+ const utc = (iso: string, locale: string) => {
23
+ try {
24
+ const at = new Intl.DateTimeFormat(locale, { dateStyle: "medium", timeStyle: "short", timeZone: "UTC" });
25
+ return t(locale, "time.utc", { time: at.format(new Date(iso)) });
26
+ } catch {
27
+ return iso;
28
+ }
29
+ };
30
+
31
+ /** The provider's payment page is followed only when it is an `https:` URL (never `javascript:` or `//host`). */
32
+ export function isPayUrl(value: unknown): value is string {
33
+ if (typeof value !== "string" || !value.startsWith("https://")) return false;
34
+ try {
35
+ return new URL(value).protocol === "https:";
36
+ } catch {
37
+ return false;
38
+ }
39
+ }
40
+
41
+ const final = (state: PaymentState, locale: string): PaymentView => ({
42
+ state,
43
+ heading: t(locale, `payment.${state}.heading` as MessageKey),
44
+ body: t(locale, `payment.${state}.body` as MessageKey),
45
+ poll: false,
46
+ resume: false,
47
+ });
48
+
49
+ /** The payment section for a booking, or `null` when there is nothing to say about money. */
50
+ export function paymentView(booking: BookingView, locale = "en-GB"): PaymentView | null {
51
+ const paid = booking.totals.totalMinor > 0;
52
+ switch (booking.status) {
53
+ case "awaiting_payment":
54
+ return {
55
+ state: "pending",
56
+ heading: t(locale, "payment.pending.heading"),
57
+ body: booking.holdExpiresAt
58
+ ? t(locale, "payment.pending.bodyUntil", { time: utc(booking.holdExpiresAt, locale) })
59
+ : t(locale, "payment.pending.body"),
60
+ poll: true,
61
+ resume: true,
62
+ };
63
+ case "confirmed":
64
+ case "expired":
65
+ case "cancelled":
66
+ return paid ? final(booking.status, locale) : null;
67
+ case "refunded":
68
+ case "refunded_unavailable":
69
+ return final(booking.status, locale);
70
+ default:
71
+ return null;
72
+ }
73
+ }
@@ -0,0 +1,162 @@
1
+ /**
2
+ * Promo codes in the booking widget (EV-FR-14, T078). The codes are Events Pro's: reserve takes
3
+ * `promoCode`, and `public/promo/check` says whether a code works for an event and, for an unlock
4
+ * code, which hidden ticket types it reveals. This module is the Free UI's side, and touches the core
5
+ * only through those public routes:
6
+ *
7
+ * - `POST /_events/promo` (the widget's "Apply" button, a plain form post that works without
8
+ * JavaScript): refuses cross-site posts, asks `public/promo/check`, keeps an accepted code in an
9
+ * HttpOnly cookie for this event and goes back to the widget. The code never goes into a URL (an
10
+ * unlock code is a credential for hidden tickets): refusals go back as an error code only.
11
+ * - `promoView`: what the widget shows for the cookie's code (the hidden types and a note), asked
12
+ * afresh on every render so a code that stopped working stops showing.
13
+ *
14
+ * The widget shows the field only when `public/event` says the core takes codes (`promoCodes`, set by
15
+ * Pro), so a Free site never offers one; and checkout sends `promoCode` only when a code was typed.
16
+ */
17
+ import { t } from "../../i18n/index";
18
+ import { callPublicRoute, type PublicRouteContext } from "./call";
19
+ import { type CheckoutEndpointContext, crossSiteResponse, isCrossSiteRequest } from "./checkout-form";
20
+ import { anchorId, formatMoney, promoRefusal, safeReturnTo, widgetErrorLocation } from "./widget";
21
+
22
+ export const PROMO_PATH = "/_events/promo";
23
+ /** How long an applied code is remembered for the event (it is checked again on every render). */
24
+ export const PROMO_COOKIE_SECONDS = 30 * 60;
25
+ const MAX_CODE = 60;
26
+
27
+ export interface PromoHiddenType {
28
+ id: string;
29
+ name: string;
30
+ priceMinor: number;
31
+ }
32
+
33
+ /** What `public/promo/check` answers for a code that works. */
34
+ export interface PromoCheck {
35
+ kind: "percent" | "fixed" | "unlock";
36
+ /** Basis points (`percent`) or minor units (`fixed`). */
37
+ value?: number;
38
+ currency?: string;
39
+ hiddenTypes: PromoHiddenType[];
40
+ }
41
+
42
+ export interface PromoView {
43
+ code: string;
44
+ note: string;
45
+ hiddenTypes: PromoHiddenType[];
46
+ }
47
+
48
+ export const promoCookieName = (eventId: string) => `semics_promo_${eventId.replace(/[^A-Za-z0-9_-]/g, "_")}`;
49
+
50
+ /** The applied-code cookie: HttpOnly, the whole site (the widget can be on any page), 30 minutes. */
51
+ export function promoCookieOptions(url: URL) {
52
+ return {
53
+ path: "/",
54
+ httpOnly: true,
55
+ sameSite: "lax" as const,
56
+ secure: url.protocol === "https:",
57
+ maxAge: PROMO_COOKIE_SECONDS,
58
+ };
59
+ }
60
+
61
+ /** A typed code, trimmed; "" when there is none or it is too long to be one. */
62
+ export function promoCodeOf(raw: unknown): string {
63
+ const code = typeof raw === "string" ? raw.trim() : "";
64
+ return code.length <= MAX_CODE ? code : "";
65
+ }
66
+
67
+ /** The refusal codes the widget has messages for; anything else (Free has no such route) is PROMO_INVALID. */
68
+ const KEPT = new Set(["PROMO_EXHAUSTED", "PROMO_UNAVAILABLE", "RATE_LIMITED"]);
69
+
70
+ async function checkCode(
71
+ ctx: PublicRouteContext,
72
+ input: { eventId: string; code: string },
73
+ pluginId: string | undefined,
74
+ ): Promise<{ ok: true; check: PromoCheck } | { ok: false; code: string }> {
75
+ const result = await callPublicRoute<PromoCheck>(ctx, {
76
+ method: "POST",
77
+ path: "public/promo/check",
78
+ pluginId,
79
+ body: { eventId: input.eventId, code: input.code },
80
+ });
81
+ if (!result.ok) {
82
+ const code = promoRefusal(result.error.code);
83
+ return { ok: false, code: KEPT.has(code) ? code : "PROMO_INVALID" };
84
+ }
85
+ const hiddenTypes = Array.isArray(result.data.hiddenTypes) ? result.data.hiddenTypes : [];
86
+ return { ok: true, check: { ...result.data, hiddenTypes } };
87
+ }
88
+
89
+ /** The line the widget shows under an applied code. */
90
+ export function promoNote(check: PromoCheck, currency: string, locale = "en-GB"): string {
91
+ const value = typeof check.value === "number" ? check.value : 0;
92
+ if (check.kind === "percent" && value > 0) {
93
+ const percent = new Intl.NumberFormat(locale, { style: "percent", maximumFractionDigits: 2 }).format(value / 10000);
94
+ return t(locale, "promo.percent", { percent });
95
+ }
96
+ if (check.kind === "fixed" && value > 0) {
97
+ return t(locale, "promo.fixed", { amount: formatMoney(value, check.currency ?? currency, locale) });
98
+ }
99
+ return t(locale, check.hiddenTypes.length > 0 ? "promo.unlocked" : "promo.applied");
100
+ }
101
+
102
+ /** The widget's view of the code in the cookie, or `null` (no code, Free, or it no longer works). */
103
+ export async function promoView(
104
+ ctx: PublicRouteContext,
105
+ input: { eventId: string; code: string; currency?: string; locale?: string },
106
+ options: { pluginId?: string },
107
+ ): Promise<PromoView | null> {
108
+ const code = promoCodeOf(input.code);
109
+ if (!code) return null;
110
+ const checked = await checkCode(ctx, { eventId: input.eventId, code }, options.pluginId);
111
+ if (!checked.ok) return null;
112
+ return {
113
+ code,
114
+ note: promoNote(checked.check, input.currency ?? "GBP", input.locale),
115
+ hiddenTypes: checked.check.hiddenTypes,
116
+ };
117
+ }
118
+
119
+ export interface PromoEndpointContext extends Omit<CheckoutEndpointContext, "cookies"> {
120
+ cookies: {
121
+ set(name: string, value: string, options: Record<string, unknown>): void;
122
+ delete(name: string, options: Record<string, unknown>): void;
123
+ };
124
+ }
125
+
126
+ const text = (form: FormData, key: string) => {
127
+ const value = form.get(key);
128
+ return typeof value === "string" ? value.trim() : "";
129
+ };
130
+
131
+ /** `POST /_events/promo`: refuse cross-site posts, check the code, remember or forget it, back to the widget (303). */
132
+ export async function handlePromoRequest(
133
+ { request, url, locals, redirect, cookies }: PromoEndpointContext,
134
+ options: { pluginId?: string },
135
+ ): Promise<Response> {
136
+ if (isCrossSiteRequest(request, url)) return crossSiteResponse();
137
+ const form = await request.formData().catch(() => new FormData());
138
+ const eventId = text(form, "eventId");
139
+ // Parsed once more and rebuilt from its path: `safeReturnTo` lets `/.//host` through as `//host`
140
+ // (phase 3 review F11), which as a Location would leave the site.
141
+ const parsed = new URL(safeReturnTo(text(form, "returnTo"), url.origin) ?? "/", "http://x");
142
+ const returnTo = `${parsed.pathname}${parsed.search}`;
143
+ const back = `${returnTo}#${anchorId(eventId)}`;
144
+ if (!eventId || eventId.length > 200) return redirect(returnTo, 303);
145
+ const cookie = promoCookieName(eventId);
146
+ const forget = () => cookies.delete(cookie, { path: "/" });
147
+ const raw = text(form, "promoCode");
148
+ if (!raw) {
149
+ forget();
150
+ return redirect(back, 303);
151
+ }
152
+ const code = promoCodeOf(raw);
153
+ const checked = code
154
+ ? await checkCode({ locals, url, request }, { eventId, code }, options.pluginId)
155
+ : { ok: false as const, code: "PROMO_INVALID" };
156
+ if (!checked.ok) {
157
+ forget();
158
+ return redirect(widgetErrorLocation(returnTo, eventId, checked.code, ["promo"]), 303);
159
+ }
160
+ cookies.set(cookie, code, promoCookieOptions(url));
161
+ return redirect(back, 303);
162
+ }
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Custom attendee questions in the booking widget (EV-FR-15, EU-FR-10, T080). Questions are Events
3
+ * Pro's: `public/event` lists them only on a Pro core, and Pro's reserve checks the answers (required
4
+ * ones, offered choices) and stores them on the booking. This module turns the listed questions into
5
+ * the widget's controls and reads the answers back from the posted form. Pure.
6
+ *
7
+ * The buyer answers once per booking. Each control is named `answer:<id>`; the form also carries a
8
+ * `questions` marker so the order sends `answers` (even `{}`) only when questions were shown: Free's
9
+ * reserve refuses unknown keys.
10
+ */
11
+ import { t } from "../../i18n/index";
12
+ import { type PublicQuestion, QUESTION_ID, type QuestionField, type WidgetField } from "./widget";
13
+
14
+ export const ANSWER_PREFIX = "answer:";
15
+ export const QUESTIONS_MARKER = "questions";
16
+ /** The longest text answer (Pro's reserve refuses longer ones). */
17
+ export const MAX_ANSWER = 500;
18
+
19
+ /** English messages by question type (the 1.0 API; `questionControls` translates). */
20
+ export const QUESTION_MESSAGES: Record<PublicQuestion["type"], string> = {
21
+ text: t("en", "question.error.text"),
22
+ select: t("en", "question.error.select"),
23
+ checkbox: t("en", "question.error.checkbox"),
24
+ };
25
+
26
+ export interface QuestionControl {
27
+ kind: PublicQuestion["type"];
28
+ /** The question's id. */
29
+ question: string;
30
+ /** The control's HTML id, unique on the page. */
31
+ id: string;
32
+ name: string;
33
+ field: QuestionField;
34
+ label: string;
35
+ required: boolean;
36
+ /** Shown after the label of an optional question ("(optional)"). */
37
+ hint: string | undefined;
38
+ errorId: string;
39
+ /** What the error says when the question needs an answer. */
40
+ message: string;
41
+ invalid: boolean;
42
+ /** A choice question's options, after an empty prompt. */
43
+ options?: Array<{ value: string; label: string }>;
44
+ maxLength?: number;
45
+ }
46
+
47
+ const KINDS = new Set<string>(["text", "select", "checkbox"]);
48
+
49
+ function wellFormed(q: PublicQuestion): boolean {
50
+ if (!q || typeof q !== "object" || typeof q.id !== "string" || !QUESTION_ID.test(q.id)) return false;
51
+ if (typeof q.label !== "string" || q.label.trim() === "" || !KINDS.has(q.type)) return false;
52
+ return q.type !== "select" || (Array.isArray(q.options) && q.options.some((o) => typeof o === "string" && o !== ""));
53
+ }
54
+
55
+ /** The widget's controls for `questions`, in order; `bad` are the fields a refusal named. */
56
+ export function questionControls(
57
+ questions: readonly PublicQuestion[] | undefined,
58
+ anchor: string,
59
+ bad: readonly WidgetField[] | readonly string[],
60
+ locale = "en-GB",
61
+ ): QuestionControl[] {
62
+ return (questions ?? []).filter(wellFormed).map((q) => {
63
+ const id = `${anchor}-q-${q.id}`;
64
+ const field: QuestionField = `q:${q.id}`;
65
+ const required = q.required === true;
66
+ return {
67
+ kind: q.type,
68
+ question: q.id,
69
+ id,
70
+ name: `${ANSWER_PREFIX}${q.id}`,
71
+ field,
72
+ label: q.label.trim(),
73
+ required,
74
+ hint: required ? undefined : t(locale, "question.optional"),
75
+ errorId: `${id}-error`,
76
+ message: t(locale, `question.error.${q.type}`),
77
+ invalid: (bad as readonly string[]).includes(field),
78
+ ...(q.type === "select"
79
+ ? {
80
+ options: [
81
+ { value: "", label: t(locale, "question.choose") },
82
+ ...(q.options ?? [])
83
+ .filter((o) => typeof o === "string" && o !== "")
84
+ .map((o) => ({ value: o, label: o })),
85
+ ],
86
+ }
87
+ : {}),
88
+ ...(q.type === "text" ? { maxLength: MAX_ANSWER } : {}),
89
+ };
90
+ });
91
+ }
92
+
93
+ /**
94
+ * The answers in a posted widget form, keyed by question id (text trimmed; a ticked box posts `yes`), or
95
+ * `undefined` when the widget showed no questions.
96
+ */
97
+ export function answersFromForm(form: FormData): Record<string, string> | undefined {
98
+ if (form.get(QUESTIONS_MARKER) === null) return undefined;
99
+ const answers: Record<string, string> = {};
100
+ for (const [key, value] of form.entries()) {
101
+ if (!key.startsWith(ANSWER_PREFIX) || typeof value !== "string") continue;
102
+ const id = key.slice(ANSWER_PREFIX.length);
103
+ if (!QUESTION_ID.test(id)) continue;
104
+ answers[id] = value.trim();
105
+ }
106
+ return answers;
107
+ }
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Server side of the waiver return page and door signing (EV-FR-12, SX-FR-04; esign-intent/1 §8.2,
3
+ * §8.3). Tokens arrive in POST bodies only (moved from the URL fragment by `src/client/receipt.ts`)
4
+ * and go to the cores in POST bodies; redirects never carry them.
5
+ *
6
+ * - `forwardReceipt`: POSTs a receipt to the Events core's `signatures/receipt`. When the receipt's
7
+ * `pdfSha256` was still null, the core adds a `lookup` request; with the e-sign core's plugin id
8
+ * configured, this asks e-sign's `public/receipts/lookup` once and forwards the full receipt.
9
+ * (Closed-tab reconciliation on later visits is the suite's job, T066.)
10
+ * - `startDoorSigning`: redeems a staff-issued intent (check-in's signing link) with e-sign's
11
+ * `public/envelopes/from-intent` in-process and sends the browser to e-sign's signing page. When the
12
+ * envelope is already completed (an emailed adult signed, but their return page never posted the
13
+ * receipt: no JavaScript, tab closed), the link's lookup request (Pro mints it with the intent) fetches
14
+ * the receipt from e-sign and records it, so check-in admits them (T119 F5).
15
+ *
16
+ * Web APIs only, no `@semics-tech/shared` (R35).
17
+ */
18
+ import { callPublicRoute, type PublicRouteContext } from "./call";
19
+ import { BOOKING_PATH } from "./checkout-form";
20
+
21
+ export interface ReceiptOptions {
22
+ /** The Events core's plugin id (defaults to the slug). */
23
+ pluginId?: string;
24
+ /** The e-sign core's plugin id, when e-sign runs on this site (`eventsIntegration({ esignPluginId })`). */
25
+ esignPluginId?: string | null;
26
+ }
27
+
28
+ /** `payloadB64 "." signature` (§4), within a type's maximum length. */
29
+ const tokenOk = (value: unknown, max: number): value is string =>
30
+ typeof value === "string" && value.length <= max && /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]{43}$/.test(value);
31
+
32
+ const BOOKING_REF = /^[0-9A-HJKMNP-TV-Z]{10}$/;
33
+ const RECEIPT_MAX = 2048;
34
+ const INTENT_MAX = 8192;
35
+
36
+ /** The notice the booking page shows for `?waiver=`. */
37
+ export type WaiverNotice = "signed" | "declined" | "voided" | "expired" | "failed";
38
+
39
+ interface ReceiptAnswer {
40
+ status?: string;
41
+ signature?: { status?: string };
42
+ lookup?: unknown;
43
+ }
44
+
45
+ function bookingLocation(ref: string, notice: WaiverNotice): string {
46
+ const query = new URLSearchParams();
47
+ if (BOOKING_REF.test(ref)) query.set("ref", ref);
48
+ query.set("waiver", notice);
49
+ return `${BOOKING_PATH}?${query}`;
50
+ }
51
+
52
+ const post = <T>(ctx: PublicRouteContext, pluginId: string | undefined, path: string, body: unknown) =>
53
+ callPublicRoute<T>(ctx, { method: "POST", path, body, ...(pluginId ? { pluginId } : {}) });
54
+
55
+ /** Forward a receipt from the return page; answers with where to send the browser. */
56
+ export async function forwardReceipt(
57
+ ctx: PublicRouteContext,
58
+ input: { ref: string; receipt: unknown },
59
+ options: ReceiptOptions,
60
+ ): Promise<{ location: string }> {
61
+ if (!tokenOk(input.receipt, RECEIPT_MAX)) return { location: bookingLocation(input.ref, "failed") };
62
+ const result = await post<ReceiptAnswer>(ctx, options.pluginId, "signatures/receipt", { receipt: input.receipt });
63
+ if (!result.ok) return { location: bookingLocation(input.ref, "failed") };
64
+ const answer = result.data;
65
+ if (typeof answer.lookup === "string" && options.esignPluginId) {
66
+ const lookup = await post<{ state?: string; receipt?: unknown }>(
67
+ ctx,
68
+ options.esignPluginId,
69
+ "public/receipts/lookup",
70
+ {
71
+ request: answer.lookup,
72
+ },
73
+ );
74
+ if (lookup.ok && lookup.data.state === "terminal" && tokenOk(lookup.data.receipt, RECEIPT_MAX)) {
75
+ await post(ctx, options.pluginId, "signatures/receipt", { receipt: lookup.data.receipt });
76
+ }
77
+ }
78
+ const status = answer.signature?.status;
79
+ const notice: WaiverNotice =
80
+ status === "completed"
81
+ ? "signed"
82
+ : status === "declined" || status === "voided" || status === "expired"
83
+ ? status
84
+ : "failed";
85
+ return { location: bookingLocation(input.ref, notice) };
86
+ }
87
+
88
+ /** The signing page e-sign's integration injects (`/sign/[token]`). */
89
+ export const SIGN_PATH = "/sign/";
90
+
91
+ /** Records a completed envelope's receipt, fetched with the door link's lookup request. */
92
+ async function recordSigned(ctx: PublicRouteContext, lookup: unknown, options: ReceiptOptions): Promise<boolean> {
93
+ if (!options.esignPluginId || !tokenOk(lookup, RECEIPT_MAX)) return false;
94
+ const found = await post<{ state?: string; receipt?: unknown }>(
95
+ ctx,
96
+ options.esignPluginId,
97
+ "public/receipts/lookup",
98
+ {
99
+ request: lookup,
100
+ },
101
+ );
102
+ if (!found.ok || found.data.state !== "terminal" || !tokenOk(found.data.receipt, RECEIPT_MAX)) return false;
103
+ const stored = await post<ReceiptAnswer>(ctx, options.pluginId, "signatures/receipt", {
104
+ receipt: found.data.receipt,
105
+ });
106
+ return stored.ok && stored.data.signature?.status === "completed";
107
+ }
108
+
109
+ /**
110
+ * Redeem a door-signing intent with e-sign and go to its signing page; `{ signed: true }` when the
111
+ * waiver was already signed and is now on record.
112
+ */
113
+ export async function startDoorSigning(
114
+ ctx: PublicRouteContext,
115
+ intent: unknown,
116
+ options: ReceiptOptions,
117
+ lookup?: unknown,
118
+ ): Promise<{ location: string } | { signed: true } | { error: string }> {
119
+ if (!options.esignPluginId) return { error: "ESIGN_NOT_CONFIGURED" };
120
+ if (!tokenOk(intent, INTENT_MAX)) return { error: "INTENT_INVALID" };
121
+ const result = await post<{ status?: unknown; signingToken?: unknown }>(
122
+ ctx,
123
+ options.esignPluginId,
124
+ "public/envelopes/from-intent",
125
+ { intent },
126
+ );
127
+ if (!result.ok) return { error: result.error.code };
128
+ const token = result.data.signingToken;
129
+ if (typeof token === "string" && /^[A-Za-z0-9_-]{1,256}$/.test(token)) return { location: `${SIGN_PATH}${token}` };
130
+ if (result.data.status === "completed" && (await recordSigned(ctx, lookup, options))) return { signed: true };
131
+ return { error: "SIGNING_UNAVAILABLE" };
132
+ }
@@ -0,0 +1,72 @@
1
+ /**
2
+ * The waitlist in the booking widget (EV-FR-16, EV-US-6, T081). A sold-out event whose core says it
3
+ * takes a waitlist (`public/event` answers `waitlist: true`) shows a "Join the waitlist" form that posts
4
+ * to the injected `POST /_events/waitlist` (no JavaScript needed). It refuses cross-site posts, asks
5
+ * `public/waitlist/join` and goes back to the widget with an outcome code only, never what was typed.
6
+ * Offers arrive by email; the booking page claims them (`claimOfferLink` in `./checkout-form`).
7
+ */
8
+ import { type MessageKey, t } from "../../i18n/index";
9
+ import { callPublicRoute } from "./call";
10
+ import { type CheckoutEndpointContext, crossSiteResponse, isCrossSiteRequest } from "./checkout-form";
11
+ import { anchorId, safeReturnTo, WIDGET_PARAMS } from "./widget";
12
+
13
+ export const WAITLIST_PATH = "/_events/waitlist";
14
+ const PARAM = "waitlist";
15
+
16
+ const OUTCOMES = ["joined", "BAD_REQUEST", "RATE_LIMITED", "TURNSTILE_FAILED", "NOT_FOUND", "INTERNAL"] as const;
17
+
18
+ /** What the widget says after a join, in English (the 1.0 API); anything else reads as `INTERNAL`. */
19
+ export const WAITLIST_MESSAGES: Record<string, string> = Object.fromEntries(
20
+ OUTCOMES.map((code) => [code, t("en", `waitlist.${code}`)]),
21
+ );
22
+
23
+ /** A join's outcome in the locale's language; an unknown one is `INTERNAL`'s. */
24
+ export const waitlistMessage = (code: string, locale?: string) =>
25
+ t(locale, `waitlist.${(OUTCOMES as readonly string[]).includes(code) ? code : "INTERNAL"}` as MessageKey);
26
+
27
+ /** The outcome a widget shows after a no-JS round trip; only for the widget of `eventId`. */
28
+ export function readWaitlistState(url: URL, eventId: string): string | undefined {
29
+ const raw = url.searchParams.get(PARAM);
30
+ if (!raw || url.searchParams.get(WIDGET_PARAMS.event) !== eventId) return undefined;
31
+ return Object.hasOwn(WAITLIST_MESSAGES, raw) ? raw : "INTERNAL";
32
+ }
33
+
34
+ const text = (form: FormData, key: string) => {
35
+ const value = form.get(key);
36
+ return typeof value === "string" ? value.trim() : "";
37
+ };
38
+
39
+ /** `POST /_events/waitlist`: refuse cross-site posts, join, back to the widget (303). */
40
+ export async function handleWaitlistRequest(
41
+ { request, url, locals, redirect }: CheckoutEndpointContext,
42
+ options: { pluginId?: string },
43
+ ): Promise<Response> {
44
+ if (isCrossSiteRequest(request, url)) return crossSiteResponse();
45
+ const form = await request.formData().catch(() => new FormData());
46
+ const eventId = text(form, "eventId");
47
+ // Rebuilt from its path, so the Location never leaves the site (as `/_events/promo`).
48
+ const back = new URL(safeReturnTo(text(form, "returnTo"), url.origin) ?? "/", "http://x");
49
+ const occurrenceId = text(form, "occurrenceId");
50
+ const ticketTypeId = text(form, "ticketTypeId");
51
+ const turnstileToken = text(form, "cf-turnstile-response");
52
+ const joined = await callPublicRoute(
53
+ { locals, url, request },
54
+ {
55
+ method: "POST",
56
+ path: "public/waitlist/join",
57
+ pluginId: options.pluginId,
58
+ body: {
59
+ eventId,
60
+ ...(occurrenceId ? { occurrenceId } : {}),
61
+ ...(ticketTypeId ? { ticketTypeId } : {}),
62
+ name: text(form, "name"),
63
+ email: text(form, "email"),
64
+ qty: Number.parseInt(text(form, "qty"), 10) || 1,
65
+ ...(turnstileToken ? { turnstileToken } : {}),
66
+ },
67
+ },
68
+ );
69
+ back.searchParams.set(PARAM, joined.ok ? "joined" : joined.error.code);
70
+ back.searchParams.set(WIDGET_PARAMS.event, eventId);
71
+ return redirect(`${back.pathname}${back.search}#${anchorId(eventId)}`, 303);
72
+ }