@msm-platform/customer-react 0.4.1 → 0.4.3

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.
@@ -0,0 +1,22 @@
1
+ /**
2
+ * The tab, opened at once on the customer's click so no popup blocker
3
+ * stops it, with `window` null when the browser refused one anyway; or
4
+ * undefined when this page itself may go to the provider.
5
+ */
6
+ export type PaymentTab = {
7
+ window: Window | null;
8
+ } | undefined;
9
+ export declare function openPaymentTab(basePath: string): PaymentTab;
10
+ /** Sends the tab, or without one this page, to the provider's page. */
11
+ export declare function goToProvider(tab: PaymentTab, redirect: string): void;
12
+ /** Closes a tab that will not go to a provider after all. */
13
+ export declare function closePaymentTab(tab: PaymentTab): void;
14
+ /** This page's URL with the return marker, for the provider to send the customer back to. */
15
+ export declare function returnUrl(param: string, outcome: string, tab: PaymentTab): string;
16
+ /** Whether this page is a payment tab the provider sent back. */
17
+ export declare function isPaymentTabReturn(): boolean;
18
+ /**
19
+ * Waits `ms`, or less when the page is shown again, as when the customer
20
+ * comes back from the payment tab to a page whose timers the browser slowed.
21
+ */
22
+ export declare function pause(ms: number): Promise<void>;
package/dist/portal.d.ts CHANGED
@@ -14,11 +14,15 @@ export declare function useCustomerPortal(options: {
14
14
  }): {
15
15
  basePath: string;
16
16
  sessionKey: import("./session").SessionState;
17
- notice: "app.loading" | "app.loadFailed" | "app.retry" | "app.signedOut" | "app.signedOutEverywhere" | "image.logo" | "nav.label" | "nav.book" | "nav.signIn" | "nav.bookings" | "nav.passes" | "nav.details" | "nav.signOut" | "signIn.heading" | "signIn.intro" | "register.intro" | "register.name" | "signIn.phone" | "signIn.codeSent" | "signIn.code" | "signIn.sendCode" | "signIn.submit" | "register.submit" | "signIn.wait" | "signIn.differentNumber" | "signIn.cancel" | "signIn.error.tooMany" | "signIn.error.tooManyLater" | "signIn.error.paused" | "signIn.error.pausedLater" | "signIn.error.destination" | "signIn.error.badCode" | "register.error.expired" | "register.error.name" | "signIn.error.invalid" | "signIn.error.refused" | "signIn.error.unreachable" | "signIn.error.failed" | "signIn.error.botCheck" | "signIn.error.botCheckUnavailable" | "signIn.error.notConfigured" | "wait.seconds.one" | "wait.seconds.other" | "wait.minutes.one" | "wait.minutes.other" | "wait.hours.one" | "wait.hours.other" | "bookings.heading" | "bookings.period" | "bookings.upcoming" | "bookings.past" | "bookings.emptyUpcoming" | "bookings.emptyPast" | "bookings.more" | "bookings.when" | "bookings.cancelled" | "bookings.cancelledLate" | "bookings.attended" | "bookings.noShow" | "bookings.lateFrom" | "bookings.started" | "bookings.cancel" | "bookings.confirmHeading" | "bookings.confirmLate" | "bookings.confirmCredit" | "bookings.confirm" | "bookings.keep" | "bookings.cancelling" | "bookings.doneOnTime" | "bookings.doneLate" | "bookings.cancelFailed" | "bookings.gone" | "businesses.heading" | "businesses.intro" | "businesses.empty" | "businesses.open" | "business.all" | "business.notFound" | "business.types" | "business.allTypes" | "business.resources" | "business.anyResource" | "business.typeMissing" | "business.minutes" | "business.week" | "business.previousWeek" | "business.nextWeek" | "business.weekOf" | "business.empty" | "business.seatsLeft.one" | "business.seatsLeft.other" | "business.full" | "business.openTime" | "business.with" | "business.instructor" | "business.room" | "business.guests" | "business.book" | "book.heading" | "book.signInFirst" | "book.back" | "book.reserving" | "book.heldUntil" | "book.confirm" | "book.confirming" | "book.booked" | "book.toBookings" | "book.done" | "book.close" | "book.chooseType" | "book.noTypes" | "book.seeAll" | "book.chooseResource" | "book.anyResource" | "book.anyResourceHint" | "book.toTypes" | "book.otherResource" | "book.reserveAgain" | "book.full" | "book.slotTaken" | "book.limit" | "book.expired" | "book.notAllowed" | "book.unavailable" | "book.refused" | "book.failed" | "passes.heading" | "passes.empty" | "passes.unlimited" | "passes.credits" | "passes.validFrom" | "passes.validRange" | "passes.expired" | "details.heading" | "details.name" | "details.phone" | "details.email" | "details.none" | "details.readOnly" | "details.save" | "details.saving" | "details.saved" | "details.saveFailed" | "details.signOutEverywhere" | "details.signOutEverywhereHint" | "details.signOutEverywhereFailed" | undefined;
17
+ notice: "app.loading" | "app.loadFailed" | "app.retry" | "app.signedOut" | "app.signedOutEverywhere" | "image.logo" | "nav.label" | "nav.book" | "nav.signIn" | "nav.bookings" | "nav.passes" | "nav.details" | "nav.signOut" | "signIn.heading" | "signIn.intro" | "register.intro" | "register.name" | "signIn.phone" | "signIn.codeSent" | "signIn.code" | "signIn.sendCode" | "signIn.submit" | "register.submit" | "signIn.wait" | "signIn.differentNumber" | "signIn.cancel" | "signIn.error.tooMany" | "signIn.error.tooManyLater" | "signIn.error.paused" | "signIn.error.pausedLater" | "signIn.error.destination" | "signIn.error.badCode" | "register.error.expired" | "register.error.name" | "signIn.error.invalid" | "signIn.error.refused" | "signIn.error.unreachable" | "signIn.error.failed" | "signIn.error.botCheck" | "signIn.error.botCheckUnavailable" | "signIn.error.notConfigured" | "wait.seconds.one" | "wait.seconds.other" | "wait.minutes.one" | "wait.minutes.other" | "wait.hours.one" | "wait.hours.other" | "bookings.heading" | "bookings.period" | "bookings.upcoming" | "bookings.past" | "bookings.emptyUpcoming" | "bookings.emptyPast" | "bookings.more" | "bookings.when" | "bookings.cancelled" | "bookings.cancelledLate" | "bookings.attended" | "bookings.noShow" | "bookings.lateFrom" | "bookings.started" | "bookings.cancel" | "bookings.confirmHeading" | "bookings.confirmLate" | "bookings.confirmCredit" | "bookings.confirm" | "bookings.keep" | "bookings.cancelling" | "bookings.doneOnTime" | "bookings.doneLate" | "bookings.cancelFailed" | "bookings.gone" | "businesses.heading" | "businesses.intro" | "businesses.empty" | "businesses.open" | "business.all" | "business.notFound" | "business.types" | "business.allTypes" | "business.resources" | "business.anyResource" | "business.typeMissing" | "business.minutes" | "business.week" | "business.previousWeek" | "business.nextWeek" | "business.weekOf" | "business.empty" | "business.seatsLeft.one" | "business.seatsLeft.other" | "business.full" | "business.openTime" | "business.with" | "business.book" | "book.heading" | "book.signInFirst" | "book.back" | "book.reserving" | "book.heldUntil" | "book.confirm" | "book.confirming" | "book.booked" | "book.toBookings" | "book.done" | "book.close" | "book.chooseType" | "book.noTypes" | "book.seeAll" | "book.chooseResource" | "book.anyResource" | "book.anyResourceHint" | "book.toTypes" | "book.toStep" | "book.otherResource" | "book.reserveAgain" | "book.full" | "book.slotTaken" | "book.limit" | "book.expired" | "book.notAllowed" | "book.unavailable" | "book.banned" | "book.banned.undated" | "book.refused" | "book.failed" | "pay.price" | "pay.advance" | "pay.whole" | "pay.later" | "pay.with" | "pay.none" | "pay.redirecting" | "pay.checking" | "pay.away" | "pay.awayBlocked" | "pay.open" | "pay.tabDone" | "pay.notFinished" | "pay.again" | "pay.released" | "pay.paidUnbooked" | "pay.slow" | "pay.unavailable" | "pay.notOffered" | "passes.heading" | "passes.empty" | "passes.unlimited" | "passes.credits" | "passes.validFrom" | "passes.validRange" | "passes.expired" | "shop.heading" | "shop.buy" | "shop.paid" | "shop.notPaid" | "shop.notFinished" | "shop.away" | "shop.slow" | "shop.outside" | "shop.gone" | "details.heading" | "details.name" | "details.phone" | "details.email" | "details.none" | "details.readOnly" | "details.save" | "details.saving" | "details.saved" | "details.saveFailed" | "details.signOutEverywhere" | "details.signOutEverywhereHint" | "details.signOutEverywhereFailed" | undefined;
18
18
  portal: Portal;
19
19
  signedInAs: (next: string) => void;
20
20
  };
21
- /** The scoped root every screen component renders, "Loading…" until the session is known. */
21
+ /**
22
+ * The scoped root every screen component renders, "Loading…" until the
23
+ * session is known. #333: a payment tab the provider sent back
24
+ * (`payment-tab.ts`) closes, or says the page it came from has the result.
25
+ */
22
26
  export declare function CustomerRoot(props: {
23
27
  portal: Portal;
24
28
  loading: boolean;
@@ -24,6 +24,7 @@ export declare function useCatalog(businessId: string): {
24
24
  displayName: string;
25
25
  email: string | null;
26
26
  id: string;
27
+ kind: "organization" | "contractor";
27
28
  latitude: number | null;
28
29
  logo: {
29
30
  height: number;
@@ -41,7 +42,6 @@ export declare function useCatalog(businessId: string): {
41
42
  } | null | undefined;
42
43
  types: {
43
44
  cancellationCutoffMinutes: number | null;
44
- categoryId: string | null;
45
45
  description: string | null;
46
46
  displayName: string;
47
47
  durationMinutes: number;
@@ -56,6 +56,17 @@ export declare function useCatalog(businessId: string): {
56
56
  url: string;
57
57
  width: number;
58
58
  } | null;
59
+ noShowFee: {
60
+ amount: number;
61
+ currency: string;
62
+ vatRateBp: number;
63
+ } | null;
64
+ price: {
65
+ advanceAmount: number;
66
+ amount: number;
67
+ currency: string;
68
+ vatRateBp: number;
69
+ } | null;
59
70
  requiresAccess: boolean;
60
71
  resources: {
61
72
  description: string | null;
@@ -72,6 +83,12 @@ export declare function useCatalog(businessId: string): {
72
83
  width: number;
73
84
  } | null;
74
85
  }[];
86
+ tags: {
87
+ colour: "red" | "orange" | "amber" | "lime" | "green" | "teal" | "cyan" | "blue" | "indigo" | "purple" | "pink" | "slate";
88
+ id: string;
89
+ name: string;
90
+ slug: string;
91
+ }[];
75
92
  timeSlotBooking: boolean;
76
93
  }[] | undefined;
77
94
  failed: boolean;
@@ -133,8 +150,8 @@ export declare function Availability(props: {
133
150
  }): import("react").JSX.Element;
134
151
  /**
135
152
  * Who and where: a slot's resource when the customer chose it; an event's
136
- * first person as its instructor, its places as the room and its other people
137
- * as guest instructors, each in the event's order (#404).
153
+ * resources in its order, each as staff present it (#462): its label before
154
+ * its name, or its name alone. Neighbours with the same label share it.
138
155
  */
139
156
  export declare function CandidateResources({ candidate }: {
140
157
  candidate: Candidate;
@@ -0,0 +1,14 @@
1
+ import type { CustomerScreen } from "../context";
2
+ /**
3
+ * #520: back from the provider's page on another screen, such as the
4
+ * business list a package that switches screens itself opens on, the
5
+ * customer is shown the passes screen, which reads the purchase.
6
+ */
7
+ export declare function useReturnToPasses(screen: CustomerScreen, navigate: (screen: "passes") => void): void;
8
+ /**
9
+ * #520: the products of the partner's businesses that take payments
10
+ * online, each bought through one of the business's payment methods: the
11
+ * customer pays on the provider's page and comes back here to the result.
12
+ * The provider's receipt is theirs; the package shows none.
13
+ */
14
+ export declare function Shop(): import("react").JSX.Element | null;
@@ -21,6 +21,21 @@ export interface CustomerHandlerOptions {
21
21
  * when it is unknown, which refuses code requests.
22
22
  */
23
23
  clientIp: (request: Request) => string | null | undefined | Promise<string | null | undefined>;
24
+ /**
25
+ * Keeps sessions without cookies, for screens in a cross-site iframe, where
26
+ * browsers block or partition cookies; mount a handler with it on its own
27
+ * `basePath` for those screens, which need no setting of their own.
28
+ * Instead of the two cookies, the screens get the encrypted session and a
29
+ * pending registration's ticket in the `X-MSM-Session` and
30
+ * `X-MSM-Registration` response headers, keep them in the page's memory
31
+ * only, and send them back in the same request headers, so a reload signs
32
+ * the customer out. Each opens only on requests from the page origin it
33
+ * was issued to, as the browser's `Origin` and `Sec-Fetch-Site` headers
34
+ * say; a request the browser marks as another origin's, or a write
35
+ * without `Origin`, is refused. The engine token stays on this server
36
+ * either way. The default is cookies, unchanged.
37
+ */
38
+ cookieless?: boolean;
24
39
  fetch?: typeof globalThis.fetch;
25
40
  }
26
41
  /**
@@ -23,6 +23,18 @@ export interface PendingRegistration {
23
23
  /** When the engine stops accepting the ticket (ISO 8601). */
24
24
  expiresAt: string;
25
25
  }
26
+ /**
27
+ * Cookieless, for screens in a cross-site iframe: the headers that hand the
28
+ * page its session and pending registration and bring them back, in place of
29
+ * the two cookies. Each carries the same kind of ciphertext as its cookie,
30
+ * with the origin it was issued to.
31
+ */
32
+ export declare const customerSessionHeader = "x-msm-session";
33
+ export declare const customerRegistrationHeader = "x-msm-registration";
34
+ /** A cookieless handle's value: what its cookie would hold, and the page's origin. */
35
+ export type Bound<T> = T & {
36
+ origin: string;
37
+ };
26
38
  /** The session cookie's cipher. */
27
39
  export declare function sessionCipher(keys: readonly string[]): {
28
40
  seal(value: CustomerSession): Promise<string>;
@@ -35,6 +47,18 @@ export declare function registrationCipher(keys: readonly string[]): {
35
47
  /** The cookie's value, or null when no key opens it or it has expired. */
36
48
  open(cookie: string | undefined): Promise<PendingRegistration | null>;
37
49
  };
50
+ /** The cookieless session header's cipher. */
51
+ export declare function sessionHeaderCipher(keys: readonly string[]): {
52
+ seal(value: Bound<CustomerSession>): Promise<string>;
53
+ /** The cookie's value, or null when no key opens it or it has expired. */
54
+ open(cookie: string | undefined): Promise<Bound<CustomerSession> | null>;
55
+ };
56
+ /** The cookieless pending registration header's cipher. */
57
+ export declare function registrationHeaderCipher(keys: readonly string[]): {
58
+ seal(value: Bound<PendingRegistration>): Promise<string>;
59
+ /** The cookie's value, or null when no key opens it or it has expired. */
60
+ open(cookie: string | undefined): Promise<Bound<PendingRegistration> | null>;
61
+ };
38
62
  /**
39
63
  * The signed-in customer's session for the partner's own server code, such as
40
64
  * a page that books through the customer SDK with `sessionHeaders`. It shares
package/dist/server.js CHANGED
@@ -7,8 +7,8 @@ function a(e) {
7
7
  for (let e of t) if (r.encode(e).length < 32) throw Error("customer-react/server: each session key must be at least 32 bytes, such as `openssl rand -base64 32`.");
8
8
  return t;
9
9
  }
10
- var o = "__Host-msm_customer_registration";
11
- function s(e, t, n) {
10
+ var o = "__Host-msm_customer_registration", s = "x-msm-session", c = "x-msm-registration";
11
+ function l(e, t, n) {
12
12
  let a, o = () => a ??= Promise.all(e.map(async (e) => {
13
13
  let t = await crypto.subtle.importKey("raw", r.encode(e), "HKDF", !1, ["deriveKey"]);
14
14
  return crypto.subtle.deriveKey({
@@ -28,10 +28,10 @@ function s(e, t, n) {
28
28
  iv: a,
29
29
  additionalData: s
30
30
  }, t, r.encode(JSON.stringify(n(e)))), l = new Uint8Array(i + c.byteLength);
31
- return l.set(a), l.set(new Uint8Array(c), i), m(l);
31
+ return l.set(a), l.set(new Uint8Array(c), i), y(l);
32
32
  },
33
33
  async open(e) {
34
- let t = e ? h(e) : null;
34
+ let t = e ? b(e) : null;
35
35
  if (!t || t.length <= i) return null;
36
36
  let r = t.subarray(0, i), a = t.subarray(i);
37
37
  for (let e of await o()) {
@@ -45,23 +45,29 @@ function s(e, t, n) {
45
45
  } catch {
46
46
  continue;
47
47
  }
48
- let i = d(new TextDecoder().decode(t), n);
48
+ let i = h(new TextDecoder().decode(t), n);
49
49
  return i && Date.parse(i.expiresAt) > Date.now() ? i : null;
50
50
  }
51
51
  return null;
52
52
  }
53
53
  };
54
54
  }
55
- function c(e) {
56
- return s(e, n, f);
55
+ function u(e) {
56
+ return l(e, n, g);
57
57
  }
58
- function l(e) {
59
- return s(e, o, p);
58
+ function d(e) {
59
+ return l(e, o, _);
60
60
  }
61
- function u(e, t) {
62
- return c(a(t.sessionKeys)).open(e);
61
+ function f(e) {
62
+ return l(e, s, v(g));
63
+ }
64
+ function p(e) {
65
+ return l(e, c, v(_));
66
+ }
67
+ function m(e, t) {
68
+ return u(a(t.sessionKeys)).open(e);
63
69
  }
64
- function d(e, t) {
70
+ function h(e, t) {
65
71
  try {
66
72
  let n = JSON.parse(e);
67
73
  return typeof n == "object" && n ? t(n) : null;
@@ -69,25 +75,34 @@ function d(e, t) {
69
75
  return null;
70
76
  }
71
77
  }
72
- function f(e) {
78
+ function g(e) {
73
79
  return typeof e.sessionId == "string" && typeof e.sessionToken == "string" && typeof e.expiresAt == "string" ? {
74
80
  sessionId: e.sessionId,
75
81
  sessionToken: e.sessionToken,
76
82
  expiresAt: e.expiresAt
77
83
  } : null;
78
84
  }
79
- function p(e) {
85
+ function _(e) {
80
86
  return typeof e.registrationTicket == "string" && typeof e.expiresAt == "string" ? {
81
87
  registrationTicket: e.registrationTicket,
82
88
  expiresAt: e.expiresAt
83
89
  } : null;
84
90
  }
85
- function m(e) {
91
+ function v(e) {
92
+ return (t) => {
93
+ let n = e(t);
94
+ return n && typeof t.origin == "string" ? {
95
+ ...n,
96
+ origin: t.origin
97
+ } : null;
98
+ };
99
+ }
100
+ function y(e) {
86
101
  let t = "";
87
102
  for (let n of e) t += String.fromCharCode(n);
88
103
  return btoa(t).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
89
104
  }
90
- function h(e) {
105
+ function b(e) {
91
106
  if (!/^[A-Za-z0-9_-]+$/.test(e)) return null;
92
107
  try {
93
108
  let t = atob(e.replace(/-/g, "+").replace(/_/g, "/"));
@@ -97,18 +112,18 @@ function h(e) {
97
112
  }
98
113
  }
99
114
  // src/server/index.ts
100
- var g = 1e4, _ = 3e4, v = 1048576, y = /* @__PURE__ */ new Set([
115
+ var x = 1e4, S = 3e4, C = 1048576, w = /* @__PURE__ */ new Set([
101
116
  "GET",
102
117
  "HEAD",
103
118
  "POST",
104
119
  "PUT",
105
120
  "PATCH",
106
121
  "DELETE"
107
- ]), b = [
122
+ ]), T = [
108
123
  "accept",
109
124
  "content-type",
110
125
  "accept-language"
111
- ], x = "Path=/; HttpOnly; Secure; SameSite=Lax", S = class extends Error {
126
+ ], E = "Path=/; HttpOnly; Secure; SameSite=Lax", D = class extends Error {
112
127
  status;
113
128
  code;
114
129
  retryAfterSeconds;
@@ -116,87 +131,86 @@ var g = 1e4, _ = 3e4, v = 1048576, y = /* @__PURE__ */ new Set([
116
131
  super(n), this.status = e, this.code = t, this.retryAfterSeconds = r;
117
132
  }
118
133
  };
119
- function C(r) {
134
+ function O(r) {
120
135
  if (typeof r.clientIp != "function") throw Error("customer-react/server: clientIp is required.");
121
136
  let i = r.basePath.replace(/\/$/, "");
122
137
  if (!i.startsWith("/") || i.startsWith("//")) throw Error("customer-react/server: basePath must be a path, such as /msm.");
123
- let s = a(r.sessionKeys), u = c(s), d = l(s), f = t({
138
+ let l = a(r.sessionKeys), m = r.cookieless === !0, h = P(m, n, u(l), s, f(l)), g = P(m, o, d(l), c, p(l)), _ = t({
124
139
  baseUrl: r.engineUrl,
125
140
  clientId: r.clientId,
126
141
  clientSecret: r.clientSecret,
127
142
  ...r.fetch && { fetch: r.fetch }
128
- }), p = () => AbortSignal.timeout(g), m = `${n}=; ${x}; Max-Age=0`, h = `${o}=; ${x}; Max-Age=0`;
129
- async function v(e) {
143
+ }), v = () => AbortSignal.timeout(x);
144
+ async function y(e) {
130
145
  let t = new URL(e.url);
131
- if (t.pathname !== i && !t.pathname.startsWith(`${i}/`)) throw new S(404, "NotFound", "Not found.");
132
- let r = t.pathname.slice(i.length);
133
- if (e.headers.get("x-msm-bff") !== "1") throw new S(403, "BffHeaderRequired", "Missing X-MSM-BFF header.");
134
- let a = await u.open(O(e, n));
135
- if (r.startsWith("/engine/")) return N(e, t, r, a);
136
- let s = `${e.method} ${r}`;
137
- if (s === "POST /auth/initiate") {
138
- let t = await j(e, ["phone", "botCheckToken"]), n = await M(e, t);
139
- return E(200, await f.POST("/web/identity/initiateLogin", {
146
+ if (t.pathname !== i && !t.pathname.startsWith(`${i}/`)) throw new D(404, "NotFound", "Not found.");
147
+ let n = t.pathname.slice(i.length);
148
+ if (e.headers.get("x-msm-bff") !== "1") throw new D(403, "BffHeaderRequired", "Missing X-MSM-BFF header.");
149
+ m && F(e);
150
+ let r = await h.read(e);
151
+ if (n.startsWith("/engine/")) return O(e, t, n, r);
152
+ let a = `${e.method} ${n}`;
153
+ if (a === "POST /auth/initiate") {
154
+ let t = await R(e, ["phone", "botCheckToken"]), n = await E(e, t);
155
+ return j(200, await _.POST("/web/identity/initiateLogin", {
140
156
  body: {
141
157
  phone: t.phone,
142
158
  ...n
143
159
  },
144
- signal: p()
145
- }).then(T));
160
+ signal: v()
161
+ }).then(A));
146
162
  }
147
- if (s === "POST /auth/login") {
148
- let { challenge: t, code: n } = await j(e, ["challenge", "code"]), r = await f.POST("/web/identity/customerLogin", {
163
+ if (a === "POST /auth/login") {
164
+ let { challenge: t, code: n } = await R(e, ["challenge", "code"]), i = await _.POST("/web/identity/customerLogin", {
149
165
  body: {
150
166
  challenge: t,
151
167
  code: n
152
168
  },
153
- signal: p()
154
- }).then(T);
155
- if (r.result === "session") return C(a, r);
156
- let { registrationTicket: i } = r;
157
- return r.nameRequired ? E(200, { result: "nameRequired" }, { "set-cookie": `${o}=${await d.seal({
158
- registrationTicket: i,
159
- expiresAt: r.registrationExpiresAt
160
- })}; ${x}; Max-Age=${D(r.registrationExpiresAt)}` }) : C(a, await A({ registrationTicket: i }));
169
+ signal: v()
170
+ }).then(A);
171
+ if (i.result === "session") return b(e, r, i);
172
+ let { registrationTicket: a } = i;
173
+ return i.nameRequired ? j(200, { result: "nameRequired" }, [await g.write(e, {
174
+ registrationTicket: a,
175
+ expiresAt: i.registrationExpiresAt
176
+ })]) : b(e, r, await C({ registrationTicket: a }));
161
177
  }
162
- if (s === "POST /auth/register") {
163
- let t = await d.open(O(e, o));
164
- if (!t) return E(401, {
178
+ if (a === "POST /auth/register") {
179
+ let t = await g.read(e);
180
+ if (!t) return j(401, {
165
181
  code: "NotAuthenticated",
166
182
  message: "No registration is pending."
167
- }, { "set-cookie": h });
168
- let { name: n } = await j(e, ["name"]);
169
- return C(a, await A({
183
+ }, [await g.write(e, null)]);
184
+ let { name: n } = await R(e, ["name"]);
185
+ return b(e, r, await C({
170
186
  registrationTicket: t.registrationTicket,
171
187
  name: n
172
188
  }));
173
189
  }
174
- if (s === "GET /auth/session") return a ? E(200, { sessionKey: a.sessionId }) : F();
175
- if (s === "POST /auth/logout") return a && await P(a), new Response(null, {
190
+ if (a === "GET /auth/session") return r ? j(200, { sessionKey: r.sessionId }) : N(e);
191
+ if (a === "POST /auth/logout") return r && await M(r), new Response(null, {
176
192
  status: 204,
177
193
  headers: [
178
- ["set-cookie", m],
179
- ["set-cookie", h],
194
+ await h.write(e, null),
195
+ await g.write(e, null),
180
196
  ["cache-control", "no-store"]
181
197
  ]
182
198
  });
183
- throw new S(404, "NotFound", "Not found.");
199
+ throw new D(404, "NotFound", "Not found.");
184
200
  }
185
- async function C(e, t) {
186
- e && await P(e);
187
- let r = await u.seal(t);
188
- return E(200, {
201
+ async function b(e, t, n) {
202
+ return t && await M(t), j(200, {
189
203
  result: "session",
190
- sessionKey: t.sessionId
191
- }, [["set-cookie", `${n}=${r}; ${x}; Max-Age=${D(t.expiresAt)}`], ["set-cookie", h]]);
204
+ sessionKey: n.sessionId
205
+ }, [await h.write(e, n), await g.write(e, null)]);
192
206
  }
193
- function A(e) {
194
- return f.POST("/web/identity/completeRegistration", {
207
+ function C(e) {
208
+ return _.POST("/web/identity/completeRegistration", {
195
209
  body: e,
196
- signal: p()
197
- }).then(T);
210
+ signal: v()
211
+ }).then(A);
198
212
  }
199
- async function M(e, t) {
213
+ async function E(e, t) {
200
214
  let n;
201
215
  try {
202
216
  n = await r.clientIp(e);
@@ -204,30 +218,30 @@ function C(r) {
204
218
  n = null;
205
219
  }
206
220
  let i = n?.trim().replace(/^\[|\]$/g, "").replace(/%.*$/, "");
207
- if (!i) throw new S(503, "ClientIpUnavailable", "The client's address is unknown.");
221
+ if (!i) throw new D(503, "ClientIpUnavailable", "The client's address is unknown.");
208
222
  return {
209
223
  botCheckToken: t.botCheckToken,
210
224
  clientIp: i
211
225
  };
212
226
  }
213
- async function N(t, n, r, i) {
227
+ async function O(t, n, r, i) {
214
228
  let a = r.slice(7);
215
- if (!w(a) || !y.has(t.method)) throw new S(404, "NotFound", "Not found.");
229
+ if (!k(a) || !w.has(t.method)) throw new D(404, "NotFound", "Not found.");
216
230
  let o = new Headers();
217
- for (let e of b) {
231
+ for (let e of T) {
218
232
  let n = t.headers.get(e);
219
233
  n && o.set(e, n);
220
234
  }
221
235
  i && o.set("x-session-token", i.sessionToken);
222
- let s = t.method !== "GET" && t.method !== "HEAD" ? await k(t) : void 0, c;
236
+ let s = t.method !== "GET" && t.method !== "HEAD" ? await I(t) : void 0, c;
223
237
  try {
224
- c = (await f.request(t.method.toLowerCase(), `${a}${n.search}`, {
238
+ c = (await _.request(t.method.toLowerCase(), `${a}${n.search}`, {
225
239
  headers: o,
226
240
  ...s && s.byteLength > 0 && { body: s },
227
241
  bodySerializer: (e) => e,
228
242
  parseAs: "stream",
229
243
  redirect: "manual",
230
- signal: AbortSignal.timeout(_)
244
+ signal: AbortSignal.timeout(S)
231
245
  })).response;
232
246
  } catch (t) {
233
247
  if (!(t instanceof e)) throw t;
@@ -238,7 +252,7 @@ function C(r) {
238
252
  let t = c.headers.get(e);
239
253
  t && u.set(e, t);
240
254
  }
241
- l && u.set("set-cookie", m);
255
+ l && u.set(...await h.write(t, null));
242
256
  let d = t.method === "HEAD" || [
243
257
  204,
244
258
  205,
@@ -249,41 +263,41 @@ function C(r) {
249
263
  headers: u
250
264
  });
251
265
  }
252
- async function P(e) {
253
- await f.POST("/web/identity/logout", {
266
+ async function M(e) {
267
+ await _.POST("/web/identity/logout", {
254
268
  body: { sessionToken: e.sessionToken },
255
- signal: p()
269
+ signal: v()
256
270
  }).catch(() => {});
257
271
  }
258
- function F() {
259
- return E(401, {
272
+ async function N(e) {
273
+ return j(401, {
260
274
  code: "NotAuthenticated",
261
275
  message: "Sign in again."
262
- }, { "set-cookie": m });
276
+ }, [await h.write(e, null)]);
263
277
  }
264
278
  return async function(t) {
265
279
  try {
266
- return await v(t);
267
- } catch (t) {
268
- if (t instanceof S) return E(t.status, {
269
- code: t.code,
270
- message: t.message
271
- }, t.retryAfterSeconds ? { "retry-after": String(t.retryAfterSeconds) } : {});
272
- if (t instanceof e && (t.status >= 400 && t.status < 500 || t.status === 503 && t.code)) {
273
- let e = new Headers(), n = t.response.headers.get("retry-after");
274
- return n && e.set("retry-after", n), t.status === 401 && e.set("set-cookie", h), E(t.status, {
275
- code: t.code ?? "EngineRejected",
276
- message: t.message
280
+ return await y(t);
281
+ } catch (n) {
282
+ if (n instanceof D) return j(n.status, {
283
+ code: n.code,
284
+ message: n.message
285
+ }, n.retryAfterSeconds ? { "retry-after": String(n.retryAfterSeconds) } : {});
286
+ if (n instanceof e && (n.status >= 400 && n.status < 500 || n.status === 503 && n.code)) {
287
+ let e = new Headers(), r = n.response.headers.get("retry-after");
288
+ return r && e.set("retry-after", r), n.status === 401 && e.set(...await g.write(t, null)), j(n.status, {
289
+ code: n.code ?? "EngineRejected",
290
+ message: n.message
277
291
  }, e);
278
292
  }
279
- return E(502, {
293
+ return j(502, {
280
294
  code: "EngineUnavailable",
281
295
  message: "The engine could not complete the request."
282
296
  });
283
297
  }
284
298
  };
285
299
  }
286
- function w(e) {
300
+ function k(e) {
287
301
  if (/%2f|%5c|\/\//i.test(e)) return !1;
288
302
  let t;
289
303
  try {
@@ -293,49 +307,68 @@ function w(e) {
293
307
  }
294
308
  return !/(^|\/)\.\.?(\/|$)|\\/.test(t) && /^\/web\//.test(t) && !/^\/web\/identity(\/|$)/i.test(t);
295
309
  }
296
- var T = ({ data: e }) => {
310
+ var A = ({ data: e }) => {
297
311
  if (e === void 0) throw Error("Engine returned no body.");
298
312
  return e;
299
313
  };
300
- function E(e, t, n = {}) {
314
+ function j(e, t, n = {}) {
301
315
  let r = new Headers(n);
302
316
  return r.set("content-type", "application/json"), r.set("cache-control", "no-store"), new Response(JSON.stringify(t), {
303
317
  status: e,
304
318
  headers: r
305
319
  });
306
320
  }
307
- var D = (e) => Math.max(0, Math.floor((Date.parse(e) - Date.now()) / 1e3));
308
- function O(e, t) {
321
+ var M = (e) => Math.max(0, Math.floor((Date.parse(e) - Date.now()) / 1e3));
322
+ function N(e, t) {
309
323
  for (let n of e.headers.get("cookie")?.split(";") ?? []) {
310
324
  let e = n.indexOf("=");
311
325
  if (e > 0 && n.slice(0, e).trim() === t) return n.slice(e + 1).trim() || void 0;
312
326
  }
313
327
  }
314
- async function k(e) {
315
- if (Number(e.headers.get("content-length")) > v) throw A();
328
+ function P(e, t, n, r, i) {
329
+ return {
330
+ async read(a) {
331
+ if (!e) return n.open(N(a, t));
332
+ let o = await i.open(a.headers.get(r) ?? void 0), s = a.headers.get("origin"), c = s ? s === o?.origin : a.headers.get("sec-fetch-site") === "same-origin";
333
+ return o && c ? o : null;
334
+ },
335
+ async write(a, o) {
336
+ return e ? [r, o ? await i.seal({
337
+ ...o,
338
+ origin: a.headers.get("origin") ?? ""
339
+ }) : ""] : ["set-cookie", o ? `${t}=${await n.seal(o)}; ${E}; Max-Age=${M(o.expiresAt)}` : `${t}=; ${E}; Max-Age=0`];
340
+ }
341
+ };
342
+ }
343
+ function F(e) {
344
+ let t = e.headers.get("sec-fetch-site"), n = e.method !== "GET" && e.method !== "HEAD";
345
+ if (t && t !== "same-origin" || n && !e.headers.get("origin")) throw new D(403, "CrossOriginRefused", "Only this origin's pages may call it.");
346
+ }
347
+ async function I(e) {
348
+ if (Number(e.headers.get("content-length")) > C) throw L();
316
349
  if (!e.body) return /* @__PURE__ */ new Uint8Array();
317
350
  let t = e.body.getReader(), n = [], r = 0;
318
351
  for (;;) {
319
352
  let { done: e, value: i } = await t.read();
320
353
  if (e) break;
321
- if (r += i.byteLength, r > v) throw await t.cancel().catch(() => {}), A();
354
+ if (r += i.byteLength, r > C) throw await t.cancel().catch(() => {}), L();
322
355
  n.push(i);
323
356
  }
324
357
  let i = new Uint8Array(r), a = 0;
325
358
  for (let e of n) i.set(e, a), a += e.byteLength;
326
359
  return i;
327
360
  }
328
- var A = () => new S(413, "PayloadTooLarge", "Request body is too large.");
329
- async function j(e, t) {
361
+ var L = () => new D(413, "PayloadTooLarge", "Request body is too large.");
362
+ async function R(e, t) {
330
363
  let n;
331
364
  try {
332
- n = JSON.parse(new TextDecoder().decode(await k(e)));
365
+ n = JSON.parse(new TextDecoder().decode(await I(e)));
333
366
  } catch (e) {
334
- if (e instanceof S) throw e;
367
+ if (e instanceof D) throw e;
335
368
  n = void 0;
336
369
  }
337
370
  let r = typeof n == "object" && n;
338
- if (!r || t.some((e) => typeof r[e] != "string")) throw new S(400, "InvalidRequest", `Expected ${t.join(", ")}.`);
371
+ if (!r || t.some((e) => typeof r[e] != "string")) throw new D(400, "InvalidRequest", `Expected ${t.join(", ")}.`);
339
372
  return r;
340
373
  }
341
- export { C as createCustomerHandler, n as customerSessionCookie, u as readCustomerSession };
374
+ export { O as createCustomerHandler, n as customerSessionCookie, m as readCustomerSession };