create-nymbal-app 0.7.0 → 0.8.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 (60) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +9 -0
  3. package/dist/index.d.ts +13 -2
  4. package/dist/index.js +40 -10
  5. package/dist/index.js.map +1 -1
  6. package/package.json +1 -1
  7. package/scaffold/templates/astro/README.md +49 -15
  8. package/scaffold/templates/astro/_dot.env.example +3 -1
  9. package/scaffold/templates/astro/package.json +25 -25
  10. package/scaffold/templates/astro/src/layouts/AccountLayout.astro +2 -6
  11. package/scaffold/templates/astro/src/layouts/BaseLayout.astro +2 -1
  12. package/scaffold/templates/astro/src/lib/api.ts +107 -11
  13. package/scaffold/templates/astro/src/lib/client.ts +5 -2
  14. package/scaffold/templates/astro/src/lib/page-policy.ts +24 -0
  15. package/scaffold/templates/astro/src/lib/reviews.ts +6 -0
  16. package/scaffold/templates/astro/src/lib/seo.ts +14 -1
  17. package/scaffold/templates/astro/src/lib/submit-once.ts +15 -2
  18. package/scaffold/templates/astro/src/middleware.ts +19 -10
  19. package/scaffold/templates/astro/src/pages/alerts/confirm.astro +3 -2
  20. package/scaffold/templates/astro/src/pages/alerts/unsubscribe.astro +3 -2
  21. package/scaffold/templates/astro/src/pages/cart.astro +15 -4
  22. package/scaffold/templates/astro/src/pages/order/[orderNumber].astro +41 -8
  23. package/scaffold/templates/astro/src/pages/product/[slug].astro +10 -4
  24. package/scaffold/templates/astro/src/pages/products/index.astro +2 -1
  25. package/scaffold/templates/astro/src/scripts/order-access.ts +28 -1
  26. package/scaffold/templates/astro/src/scripts/signed-in-redirect.ts +14 -1
  27. package/scaffold/templates/astro/src/styles/global.css +3 -0
  28. package/scaffold/templates/astro/src/styles/pages/pdp.css +7 -4
  29. package/scaffold/templates/nextjs/README.md +49 -15
  30. package/scaffold/templates/nextjs/_dot.env.example +3 -1
  31. package/scaffold/templates/nextjs/app/(catalog)/home/[key]/page.tsx +2 -2
  32. package/scaffold/templates/nextjs/app/(catalog)/product/[slug]/page.tsx +24 -20
  33. package/scaffold/templates/nextjs/app/(catalog)/products/page.tsx +8 -5
  34. package/scaffold/templates/nextjs/app/(catalog)/search/SearchView.tsx +1 -1
  35. package/scaffold/templates/nextjs/app/(shopper)/account/login/LoginView.tsx +4 -4
  36. package/scaffold/templates/nextjs/app/(shopper)/account/login/page.tsx +3 -1
  37. package/scaffold/templates/nextjs/app/(shopper)/alerts/actions.ts +6 -3
  38. package/scaffold/templates/nextjs/app/(shopper)/cart/page.tsx +21 -5
  39. package/scaffold/templates/nextjs/app/(shopper)/order/[orderNumber]/OrderEmailPrompt.tsx +27 -5
  40. package/scaffold/templates/nextjs/app/(shopper)/order/[orderNumber]/OrderLinkForm.tsx +20 -4
  41. package/scaffold/templates/nextjs/app/(shopper)/order/[orderNumber]/OrderNotFound.tsx +9 -4
  42. package/scaffold/templates/nextjs/app/(shopper)/order/[orderNumber]/OwnerRedirect.tsx +48 -0
  43. package/scaffold/templates/nextjs/app/(shopper)/order/[orderNumber]/actions.ts +56 -0
  44. package/scaffold/templates/nextjs/app/(shopper)/order/[orderNumber]/page.tsx +3 -3
  45. package/scaffold/templates/nextjs/app/error.tsx +9 -3
  46. package/scaffold/templates/nextjs/app/globals.css +3 -0
  47. package/scaffold/templates/nextjs/components/client/AuthGuard.tsx +2 -2
  48. package/scaffold/templates/nextjs/components/client/NymbalSetup.tsx +1 -2
  49. package/scaffold/templates/nextjs/components/server/Header.tsx +5 -2
  50. package/scaffold/templates/nextjs/lib/api.ts +109 -11
  51. package/scaffold/templates/nextjs/lib/chrome.ts +9 -5
  52. package/scaffold/templates/nextjs/lib/client.ts +5 -7
  53. package/scaffold/templates/nextjs/lib/header.ts +15 -0
  54. package/scaffold/templates/nextjs/lib/page-policy.mjs +24 -0
  55. package/scaffold/templates/nextjs/lib/reviews.ts +6 -0
  56. package/scaffold/templates/nextjs/lib/seo.ts +19 -15
  57. package/scaffold/templates/nextjs/lib/signed-in-target.ts +11 -0
  58. package/scaffold/templates/nextjs/next.config.mjs +10 -1
  59. package/scaffold/templates/nextjs/package.json +26 -26
  60. package/scaffold/templates/astro/src/scripts/account-guard.ts +0 -23
@@ -4,7 +4,13 @@ import type {
4
4
  ProductSearchResult,
5
5
  ReviewsListResult,
6
6
  } from '@nymbalhq/sdk'
7
- import { DEFAULT_PRODUCT_SORT, ORDER_KEY_HEADER, PRODUCT_SORT_KEYS } from '@nymbalhq/types'
7
+ import {
8
+ DEFAULT_PRODUCT_SORT,
9
+ ORDER_EMAIL_HEADER,
10
+ ORDER_KEY_HEADER,
11
+ PRODUCT_SORT_KEYS,
12
+ SHOPPER_ATTESTATION_HEADER,
13
+ } from '@nymbalhq/types'
8
14
  import type {
9
15
  AlertKind,
10
16
  Cart,
@@ -109,10 +115,9 @@ export async function fetchCategories(): Promise<Category[]> {
109
115
 
110
116
  /**
111
117
  * The order its key opens, `key` being the confirmation URL's `?key=`. `'expired'` when the API says the key has
112
- * expired, so the page can ask for the order's email, which the browser sends itself: a read from this server would
113
- * count every shopper's tries under the server's one address. Null on any other 404, which the API answers alike for
114
- * an unknown number and an order read without its key; rejects when the API fails, so a failed read is a 500 and
115
- * never a not-found page for an order the shopper has. The key goes in a header, never in the API's URL.
118
+ * expired, so the page can ask for the order's email. Null on any other 404, which the API answers alike for an
119
+ * unknown number and an order read without its key; rejects when the API fails, so a failed read is a 500 and never a
120
+ * not-found page for an order the shopper has. The key goes in a header, never in the API's URL.
116
121
  */
117
122
  export async function fetchOrder(
118
123
  orderNumber: string,
@@ -132,6 +137,69 @@ export async function fetchOrder(
132
137
  return envelope.data
133
138
  }
134
139
 
140
+ // The two calls below serve the order page's forms only when its script did not run. From this server they count
141
+ // against the shopper's address only when they echo the attestation the API sent with the page (`shopperHeaders`).
142
+
143
+ /** The page request's `x-nymbal-shopper`, set by the API that forwarded it; `{}` when no API forwarded it. */
144
+ export function shopperHeaders(headers: Headers): Record<string, string> {
145
+ const value = headers.get(SHOPPER_ATTESTATION_HEADER)
146
+ return value === null ? {} : { [SHOPPER_ATTESTATION_HEADER]: value }
147
+ }
148
+
149
+ /**
150
+ * The order its expired key opens beside the order's email; `'not-found'` when the email does not open it (the API's
151
+ * unknown-number 404), `'limited'` on the API's 429; rejects on any other failure. The email goes in a header.
152
+ */
153
+ export async function openExpiredOrder(
154
+ orderNumber: string,
155
+ key: string,
156
+ email: string,
157
+ forwarded: Record<string, string> = {},
158
+ ): Promise<ShopperOrder | 'not-found' | 'limited'> {
159
+ const path = `/api/orders/${encodeURIComponent(orderNumber)}`
160
+ const res = await fetch(`${API_URL}${path}`, {
161
+ headers: { ...forwarded, [ORDER_KEY_HEADER]: key, [ORDER_EMAIL_HEADER]: email },
162
+ })
163
+ if (res.status === 404) return 'not-found'
164
+ if (res.status === 429) return 'limited'
165
+ if (!res.ok) throw new ApiUnavailableError(`GET ${path} answered ${res.status}`)
166
+ const envelope = (await res.json()) as { data?: ShopperOrder | null }
167
+ if (!envelope.data) throw new ApiUnavailableError(`GET ${path} answered no data`)
168
+ return envelope.data
169
+ }
170
+
171
+ const CSRF_COOKIE = 'nymbal.csrf'
172
+ const CSRF_HEADER = 'x-csrf-token'
173
+
174
+ /**
175
+ * Asks the API to mail the order's link to the order's email; `'sent'` whatever matched (the API answers alike),
176
+ * `'limited'` on its 429; rejects on any other failure. The route is CSRF-checked, so the token `GET /api/csrf` gives
177
+ * goes back as both its cookie and its header.
178
+ */
179
+ export async function requestOrderLink(
180
+ orderNumber: string,
181
+ email: string,
182
+ forwarded: Record<string, string> = {},
183
+ ): Promise<'sent' | 'limited'> {
184
+ const issued = await fetch(`${API_URL}/api/csrf`, { headers: forwarded })
185
+ if (!issued.ok) throw new ApiUnavailableError(`GET /api/csrf answered ${issued.status}`)
186
+ const { token } = ((await issued.json()) as { data: { token: string } }).data
187
+ const res = await fetch(`${API_URL}/api/orders/link`, {
188
+ method: 'POST',
189
+ headers: {
190
+ ...forwarded,
191
+ 'content-type': 'application/json',
192
+ accept: 'application/json',
193
+ cookie: `${CSRF_COOKIE}=${token}`,
194
+ [CSRF_HEADER]: token,
195
+ },
196
+ body: JSON.stringify({ orderNumber, email }),
197
+ })
198
+ if (res.status === 202) return 'sent'
199
+ if (res.status === 429) return 'limited'
200
+ throw new ApiUnavailableError(`POST /api/orders/link answered ${res.status}`)
201
+ }
202
+
135
203
  export async function fetchReviews(productId: string): Promise<ReviewsListResult> {
136
204
  try {
137
205
  const res = await fetch(`${API_URL}/api/products/${encodeURIComponent(productId)}/reviews`)
@@ -189,6 +257,20 @@ export async function fetchCart(cookie: string | null): Promise<CartProjection |
189
257
  }
190
258
  }
191
259
 
260
+ /** Whether a request's Cookie header carries the shopper's `nymbal.cart` cookie. */
261
+ export function hasCartCookie(cookie: string | null): boolean {
262
+ return cartToken(cookie) !== null
263
+ }
264
+
265
+ /**
266
+ * The cart the cart page renders from: the empty cart without a `nymbal.cart` cookie, since the cart lives behind it,
267
+ * else `fetchCart`'s answer, where null (a failed read) is an unknown cart and never shown as empty.
268
+ */
269
+ export async function cartPageCart(cookie: string | null): Promise<CartProjection | null> {
270
+ if (!hasCartCookie(cookie)) return { items: [], subtotalMinor: 0, currency: '', itemCount: 0 }
271
+ return fetchCart(cookie)
272
+ }
273
+
192
274
  /** The search the search page shows for `q` (and its category), as the search store would hold it. */
193
275
  export async function fetchSearch(
194
276
  q: string,
@@ -208,10 +290,14 @@ export async function fetchSearch(
208
290
  }
209
291
 
210
292
  /** An alert link's token posted to the API from this server; null when the API refuses the link (404, or 400). */
211
- async function postAlertToken<T>(path: string, token: string): Promise<T | null> {
293
+ async function postAlertToken<T>(
294
+ path: string,
295
+ token: string,
296
+ forwarded: Record<string, string>,
297
+ ): Promise<T | null> {
212
298
  const res = await fetch(`${API_URL}${path}`, {
213
299
  method: 'POST',
214
- headers: { 'content-type': 'application/json', accept: 'application/json' },
300
+ headers: { ...forwarded, 'content-type': 'application/json', accept: 'application/json' },
215
301
  body: JSON.stringify({ token }),
216
302
  })
217
303
  if (res.status === 404 || res.status === 400) return null
@@ -225,13 +311,23 @@ export interface AlertConfirmation {
225
311
  }
226
312
 
227
313
  /** Confirms the alert a confirmation email's link names; null when the link is not valid; rejects when the API fails. */
228
- export function confirmAlert(token: string): Promise<AlertConfirmation | null> {
229
- return postAlertToken<AlertConfirmation>('/api/alerts/confirm', token)
314
+ export function confirmAlert(
315
+ token: string,
316
+ forwarded: Record<string, string> = {},
317
+ ): Promise<AlertConfirmation | null> {
318
+ return postAlertToken<AlertConfirmation>('/api/alerts/confirm', token, forwarded)
230
319
  }
231
320
 
232
321
  /** Stops the alert an email's unsubscribe link names; false when the link is not valid; rejects when the API fails. */
233
- export async function unsubscribeAlert(token: string): Promise<boolean> {
322
+ export async function unsubscribeAlert(
323
+ token: string,
324
+ forwarded: Record<string, string> = {},
325
+ ): Promise<boolean> {
234
326
  return (
235
- (await postAlertToken<{ status: 'unsubscribed' }>('/api/alerts/unsubscribe', token)) !== null
327
+ (await postAlertToken<{ status: 'unsubscribed' }>(
328
+ '/api/alerts/unsubscribe',
329
+ token,
330
+ forwarded,
331
+ )) !== null
236
332
  )
237
333
  }
@@ -1,5 +1,5 @@
1
1
  import '../elements/index.js'
2
- import { createNymbalClient } from '@nymbalhq/sdk/core'
2
+ import { createNymbalClient, resumeSession } from '@nymbalhq/sdk/core'
3
3
  import '@nymbalhq/sdk/ns/cart'
4
4
  // Every page's layout has the search bar: its store ships with the client, not in a chunk of its own.
5
5
  import '@nymbalhq/sdk/ns/search'
@@ -7,9 +7,12 @@ import { registerClient } from '@nymbalhq/web-components'
7
7
 
8
8
  const client = createNymbalClient({
9
9
  baseUrl: import.meta.env.PUBLIC_NYMBAL_API_URL ?? 'http://localhost:3001',
10
- tokenStorage: 'localStorage',
11
10
  })
12
11
 
12
+ // Before any element connects: every request the page sends while the session comes back waits for it, so none goes
13
+ // as a guest's. The auth store is not loaded for it: what reads the profile (the account pages, the review form)
14
+ // calls client.auth.restore(), which shares this refresh.
15
+ void resumeSession(client)
13
16
  registerClient(client)
14
17
  // A payment driver of the project's own goes here, before any element is defined: registerPaymentDriver(name, driver)
15
18
  // from @nymbalhq/sdk/core, named by the driver of the payments adapter's client half.
@@ -0,0 +1,24 @@
1
+ import { PAYMENT_SOURCES as PAY } from '@nymbalhq/web-components/payment-sources'
2
+
3
+ /**
4
+ * The content security policy every page answers. A script, style, font, frame or browser-side call from anywhere
5
+ * else (analytics, chat, a web font) is refused until it is named here; the payment step's come with its drivers.
6
+ * Scripts stay 'unsafe-inline': escaping is the defence against an injected inline script. `apiUrl` empty is the API
7
+ * on the page's own origin. `dev` adds nothing: the dev server loads nothing this refuses.
8
+ */
9
+ export function pagePolicy({ apiUrl }: { apiUrl: string; dev: boolean }): string {
10
+ const api = apiUrl === '' ? '' : ` ${new URL(apiUrl).origin}`
11
+ return [
12
+ "default-src 'self'",
13
+ `script-src 'self' 'unsafe-inline' ${PAY.script.join(' ')}`,
14
+ "style-src 'self' 'unsafe-inline'",
15
+ `img-src 'self'${api} data: blob: https:`,
16
+ "font-src 'self' data:",
17
+ `connect-src 'self'${api} ${PAY.connect.join(' ')}`,
18
+ `frame-src ${PAY.frame.join(' ')}`,
19
+ "frame-ancestors 'none'",
20
+ "base-uri 'self'",
21
+ "form-action 'self'",
22
+ "object-src 'none'",
23
+ ].join('; ')
24
+ }
@@ -0,0 +1,6 @@
1
+ import type { StoreCapabilities } from '@nymbalhq/sdk'
2
+
3
+ /** The review form only where the store's reviews adapter takes reviews on the site (`submit`). */
4
+ export function acceptsReviews(capabilities: StoreCapabilities | null | undefined): boolean {
5
+ return capabilities?.reviews?.capabilities.includes('submit') === true
6
+ }
@@ -1,4 +1,7 @@
1
1
  import type { DenormalisedProduct } from '@nymbalhq/sdk'
2
+ import { descriptionText } from '@nymbalhq/web-components/ssr'
3
+
4
+ export { descriptionText, serializeJsonLd } from '@nymbalhq/web-components/ssr'
2
5
 
3
6
  export function productJsonLd(product: DenormalisedProduct, baseUrl: string) {
4
7
  // The SDK types `media` as unknown: the projection stores either URLs or `{ url }` objects.
@@ -22,7 +25,7 @@ export function productJsonLd(product: DenormalisedProduct, baseUrl: string) {
22
25
  '@context': 'https://schema.org',
23
26
  '@type': 'Product',
24
27
  name: product.name,
25
- description: product.description,
28
+ description: descriptionText(product.description),
26
29
  image: images,
27
30
  sku,
28
31
  url: `${baseUrl}/product/${product.slug}`,
@@ -36,6 +39,16 @@ export function productJsonLd(product: DenormalisedProduct, baseUrl: string) {
36
39
  : 'https://schema.org/OutOfStock',
37
40
  offerCount: product.variants?.length ?? 1,
38
41
  },
42
+ // None without an approved review: a zero-count aggregateRating is invalid structured data.
43
+ ...(product.rating?.count && {
44
+ aggregateRating: {
45
+ '@type': 'AggregateRating',
46
+ ratingValue: product.rating.average,
47
+ reviewCount: product.rating.count,
48
+ bestRating: 5,
49
+ worstRating: 1,
50
+ },
51
+ }),
39
52
  }
40
53
  }
41
54
 
@@ -1,4 +1,7 @@
1
- /** What a handler resolves when it has sent the browser elsewhere (`location.href = …`): the form stays locked. */
1
+ /**
2
+ * What a handler resolves when it has sent the browser elsewhere (`location.href = …`): the form stays locked until the
3
+ * browser restores the page from its back/forward cache.
4
+ */
2
5
  export type SubmitOutcome = void | 'leaving'
3
6
 
4
7
  export type SubmitHandler = (event: SubmitEvent) => Promise<SubmitOutcome> | SubmitOutcome
@@ -15,6 +18,15 @@ function submitButtonOf(event: SubmitEvent, form: HTMLFormElement): HTMLButtonEl
15
18
  export function submitOnce(form: HTMLFormElement | null, handler: SubmitHandler): void {
16
19
  if (form === null) return
17
20
  let inFlight = false
21
+ /** Releases the lock a `'leaving'` resolve left; null while no such lock is held. */
22
+ let releaseLeaving: (() => void) | null = null
23
+
24
+ // Back to a page the browser kept in its back/forward cache: the navigation that locked the form left that page.
25
+ window.addEventListener('pageshow', (event) => {
26
+ if ((event as PageTransitionEvent).persisted !== true || releaseLeaving === null) return
27
+ releaseLeaving()
28
+ releaseLeaving = null
29
+ })
18
30
 
19
31
  form.addEventListener('submit', (event) => {
20
32
  event.preventDefault()
@@ -33,7 +45,8 @@ export function submitOnce(form: HTMLFormElement | null, handler: SubmitHandler)
33
45
  .then(() => handler(event as SubmitEvent))
34
46
  .then(
35
47
  (outcome) => {
36
- if (outcome !== 'leaving') release()
48
+ if (outcome === 'leaving') releaseLeaving = release
49
+ else release()
37
50
  },
38
51
  (reason: unknown) => {
39
52
  release()
@@ -1,4 +1,10 @@
1
1
  import { defineMiddleware } from 'astro:middleware'
2
+ import { pagePolicy } from './lib/page-policy'
3
+
4
+ const POLICY = pagePolicy({
5
+ apiUrl: import.meta.env.PUBLIC_NYMBAL_API_URL ?? 'http://localhost:3001',
6
+ dev: import.meta.env.DEV,
7
+ })
2
8
 
3
9
  /** Whether an `Accept-Encoding` value accepts gzip: a `gzip` entry (or, without one, `*`) with a q-value above 0. */
4
10
  function acceptsGzip(header: string): boolean {
@@ -13,21 +19,24 @@ function acceptsGzip(header: string): boolean {
13
19
  return star
14
20
  }
15
21
 
16
- // The standalone Node adapter compresses nothing, so a page's HTML (its styles inlined) went over the wire whole.
17
- // An HTML response is gzipped as a stream when the client accepts it; everything else passes through unchanged, and a
18
- // proxy that compresses sees the encoding and passes it on. Every HTML response varies on Accept-Encoding, the
19
- // uncompressed one included, so a cache keeps both forms apart.
22
+ // Every HTML response carries the page policy. The standalone Node adapter compresses nothing, so a page's HTML (its
23
+ // styles inlined) went over the wire whole. An HTML response is gzipped as a stream when the client accepts it;
24
+ // everything else passes through unchanged, and a proxy that compresses sees the encoding and passes it on. Every HTML
25
+ // response varies on Accept-Encoding, the uncompressed one included, so a cache keeps both forms apart.
20
26
  export const onRequest = defineMiddleware(async (context, next) => {
21
27
  const response = await next()
22
28
  const type = response.headers.get('content-type') ?? ''
23
- if (!type.startsWith('text/html') || response.headers.has('content-encoding')) return response
29
+ if (!type.startsWith('text/html')) return response
24
30
  const headers = new Headers(response.headers)
25
- headers.append('vary', 'Accept-Encoding')
31
+ headers.set('content-security-policy', POLICY)
26
32
  let body = response.body
27
- if (body !== null && acceptsGzip(context.request.headers.get('accept-encoding') ?? '')) {
28
- headers.set('content-encoding', 'gzip')
29
- headers.delete('content-length')
30
- body = body.pipeThrough(new CompressionStream('gzip'))
33
+ if (!response.headers.has('content-encoding')) {
34
+ headers.append('vary', 'Accept-Encoding')
35
+ if (body !== null && acceptsGzip(context.request.headers.get('accept-encoding') ?? '')) {
36
+ headers.set('content-encoding', 'gzip')
37
+ headers.delete('content-length')
38
+ body = body.pipeThrough(new CompressionStream('gzip'))
39
+ }
31
40
  }
32
41
  return new Response(body, {
33
42
  status: response.status,
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  import '../../styles/pages/error.css'
3
3
  import BaseLayout from '../../layouts/BaseLayout.astro'
4
- import { confirmAlert } from '../../lib/api'
4
+ import { confirmAlert, shopperHeaders } from '../../lib/api'
5
5
 
6
6
  // Opening the link only shows the button, so a mail scanner that fetches it confirms nothing. The press posts the
7
7
  // token back here, and this server posts it on to the API, so the browser needs no CSRF cookie.
@@ -9,7 +9,8 @@ const pressed = Astro.request.method === 'POST'
9
9
  const token = pressed
10
10
  ? String((await Astro.request.formData()).get('token') ?? '')
11
11
  : (Astro.url.searchParams.get('token') ?? '')
12
- const confirmed = pressed && token !== '' ? await confirmAlert(token) : null
12
+ const confirmed =
13
+ pressed && token !== '' ? await confirmAlert(token, shopperHeaders(Astro.request.headers)) : null
13
14
  ---
14
15
 
15
16
  <BaseLayout title="Email alert | Nymbal" description="Confirm your email alert.">
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  import '../../styles/pages/error.css'
3
3
  import BaseLayout from '../../layouts/BaseLayout.astro'
4
- import { unsubscribeAlert } from '../../lib/api'
4
+ import { shopperHeaders, unsubscribeAlert } from '../../lib/api'
5
5
 
6
6
  // Opening the link only shows the button, so a mail scanner that fetches it stops nothing. The press posts the token
7
7
  // back here, and this server posts it on to the API, which holds no CSRF cookie.
@@ -9,7 +9,8 @@ const pressed = Astro.request.method === 'POST'
9
9
  const token = pressed
10
10
  ? String((await Astro.request.formData()).get('token') ?? '')
11
11
  : (Astro.url.searchParams.get('token') ?? '')
12
- const stopped = pressed && token !== '' ? await unsubscribeAlert(token) : false
12
+ const stopped =
13
+ pressed && token !== '' ? await unsubscribeAlert(token, shopperHeaders(Astro.request.headers)) : false
13
14
  ---
14
15
 
15
16
  <BaseLayout title="Back-in-stock alert | Nymbal" description="Stop a back-in-stock alert.">
@@ -1,20 +1,31 @@
1
1
  ---
2
2
  import NymbalElement from '@nymbalhq/web-components/astro'
3
3
  import BaseLayout from '../layouts/BaseLayout.astro'
4
- import { fetchCart } from '../lib/api'
4
+ import { cartPageCart, hasCartCookie } from '../lib/api'
5
5
 
6
6
  // The shopper's own cart: no shared cache may keep it for the next visitor.
7
7
  Astro.response.headers.set('Cache-Control', 'no-store')
8
8
 
9
- const cart = await fetchCart(Astro.request.headers.get('cookie'))
9
+ const cookie = Astro.request.headers.get('cookie')
10
+ const cart = await cartPageCart(cookie)
11
+ // Without the cookie this server cannot tell an empty cart from one the browser holds for an API on another host, so
12
+ // the empty cart is for a browser without JavaScript; with it, the element's own read decides.
13
+ const noCookie = !hasCartCookie(cookie)
14
+ const shown = noCookie ? null : cart
10
15
  ---
11
16
 
12
- <BaseLayout title="Your Cart | Nymbal" description="Review the items in your cart." cart={cart}>
17
+ <BaseLayout title="Your Cart | Nymbal" description="Review the items in your cart." cart={shown}>
13
18
  <div class="container section" data-testid="cart-page">
14
19
  <NymbalElement
15
20
  tag="nymbal-cart-page"
16
- attributes={cart === null ? {} : { cart: JSON.stringify(cart) }}
21
+ attributes={shown === null ? {} : { cart: JSON.stringify(shown) }}
17
22
  />
23
+ {noCookie && (
24
+ <noscript>
25
+ <style is:inline>nymbal-cart-page:not([cart]) { display: none; }</style>
26
+ <NymbalElement tag="nymbal-cart-page" attributes={{ cart: JSON.stringify(cart) }} />
27
+ </noscript>
28
+ )}
18
29
  </div>
19
30
  </BaseLayout>
20
31
 
@@ -3,7 +3,8 @@ import '../../styles/pages/confirmation.css'
3
3
  import '../../styles/pages/error.css'
4
4
  import BaseLayout from '../../layouts/BaseLayout.astro'
5
5
  import NymbalElement from '@nymbalhq/web-components/astro'
6
- import { fetchOrder } from '../../lib/api'
6
+ import type { ShopperOrder } from '@nymbalhq/types'
7
+ import { fetchOrder, openExpiredOrder, requestOrderLink, shopperHeaders } from '../../lib/api'
7
8
  import { isPaid, orderHeading } from '../../lib/order-status'
8
9
 
9
10
  // The URL carries the order's key (`?key=`), so nothing this page links to or loads may be told the URL: a header,
@@ -13,14 +14,43 @@ Astro.response.headers.set('Cache-Control', 'no-store')
13
14
 
14
15
  const { orderNumber } = Astro.params
15
16
  const key = Astro.url.searchParams.get('key') ?? undefined
16
- // Rejects when the API fails, so a failed read is a 500 and never a not-found page for an order the shopper has. A POST
17
- // here (a form sent before its script ran) is answered as the plain page: its body is never read.
18
- const read = await fetchOrder(orderNumber!, key)
17
+
18
+ // A POST is one of the page's two forms sent without its script (the script sends both from the browser): this server
19
+ // answers it, the email in the form's body, never in a URL.
20
+ const form = Astro.request.method === 'POST' ? await Astro.request.formData() : null
21
+ const posted = (name: string): string => String(form?.get(name) ?? '').trim()
22
+ const intent = posted('intent')
23
+
24
+ // Every read rejects when the API fails, so a failed read is a 500 and never a not-found page for an order the shopper
25
+ // has.
26
+ let read: ShopperOrder | 'expired' | null
27
+ let emailLimited = false
28
+ let link: 'idle' | 'sent' | 'limited' = 'idle'
29
+ if (intent === 'link') {
30
+ link = await requestOrderLink(
31
+ posted('orderNumber'),
32
+ posted('email'),
33
+ shopperHeaders(Astro.request.headers),
34
+ )
35
+ read = null
36
+ } else if (intent === 'open' && key !== undefined) {
37
+ const opened = await openExpiredOrder(
38
+ orderNumber!,
39
+ key,
40
+ posted('email'),
41
+ shopperHeaders(Astro.request.headers),
42
+ )
43
+ emailLimited = opened === 'limited'
44
+ read = opened === 'limited' ? 'expired' : opened === 'not-found' ? null : opened
45
+ } else {
46
+ read = await fetchOrder(orderNumber!, key)
47
+ }
19
48
  const order = read === 'expired' ? null : read
20
49
  const canonical = new URL(Astro.url.pathname, Astro.url).href
21
50
 
22
51
  // The order page's own not-found state, which offers a fresh link; the site-wide 404 would drop the headers above.
23
52
  if (read === null) Astro.response.status = 404
53
+ if (emailLimited || link === 'limited') Astro.response.status = 429
24
54
 
25
55
  const summary = order && {
26
56
  items: JSON.stringify(
@@ -49,13 +79,14 @@ const paid = order ? isPaid(order.status) : false
49
79
  {read === 'expired' && (
50
80
  <div class="container section" id="order-email-prompt">
51
81
  <form method="post" class="error-page" id="order-email-form" data-order-number={orderNumber}>
82
+ <input type="hidden" name="intent" value="open" />
52
83
  <h1 class="error-title">Open your order</h1>
53
84
  <p class="error-message">This order link has expired. Enter the email you gave at checkout to open the order.</p>
54
85
  <div class="form-group">
55
86
  <label for="order-email">Email</label>
56
87
  <input id="order-email" type="email" name="email" autocomplete="email" required data-testid="order-email-input" />
57
88
  </div>
58
- <p class="error-message" data-testid="order-email-limited" hidden>
89
+ <p class="error-message" data-testid="order-email-limited" hidden={!emailLimited}>
59
90
  Too many tries for now. Please try again in a while.
60
91
  </p>
61
92
  <p class="error-message" id="order-email-failed" hidden>We could not open the order just now. Please try again.</p>
@@ -102,7 +133,7 @@ const paid = order ? isPaid(order.status) : false
102
133
  </div>
103
134
  )}
104
135
  {(read === 'expired' || read === null) && (
105
- <div class="container section" id="order-not-found" hidden={read === 'expired'}>
136
+ <div class="container section" id="order-not-found" data-order-number={orderNumber} hidden={read === 'expired'}>
106
137
  <div class="error-page">
107
138
  <span class="error-code">404</span>
108
139
  <h1 class="error-title">Order not found</h1>
@@ -110,7 +141,8 @@ const paid = order ? isPaid(order.status) : false
110
141
  This link does not open an order. Give its order number and the email you gave at checkout, and we'll email
111
142
  you a fresh link if they match.
112
143
  </p>
113
- <form method="post" id="order-link-form">
144
+ <form method="post" id="order-link-form" hidden={link === 'sent'}>
145
+ <input type="hidden" name="intent" value="link" />
114
146
  <div class="form-group">
115
147
  <label for="order-link-number">Order number</label>
116
148
  <input id="order-link-number" name="orderNumber" required data-testid="order-link-number" />
@@ -119,11 +151,12 @@ const paid = order ? isPaid(order.status) : false
119
151
  <label for="order-link-email">Email</label>
120
152
  <input id="order-link-email" type="email" name="email" autocomplete="email" required data-testid="order-link-email" />
121
153
  </div>
154
+ {link === 'limited' && <p class="error-message">Too many tries for now. Please try again in a while.</p>}
122
155
  <div class="error-actions">
123
156
  <button type="submit" class="btn btn-primary" data-testid="order-link-submit">Send me my order link</button>
124
157
  </div>
125
158
  </form>
126
- <p class="error-message" data-testid="order-link-sent" hidden>
159
+ <p class="error-message" data-testid="order-link-sent" hidden={link !== 'sent'}>
127
160
  If that number and email match an order, its link is on its way to that email.
128
161
  </p>
129
162
  <p class="error-message" id="order-link-failed" hidden>We could not send the link just now. Please try again.</p>
@@ -4,7 +4,8 @@ import BaseLayout from '../../layouts/BaseLayout.astro'
4
4
  import NymbalElement from '@nymbalhq/web-components/astro'
5
5
  import { cardProductOf } from '@nymbalhq/web-components/ssr'
6
6
  import { loadProduct, fetchReviews, fetchProducts, fetchCapabilities } from '../../lib/api'
7
- import { productJsonLd, breadcrumbJsonLd } from '../../lib/seo'
7
+ import { productJsonLd, breadcrumbJsonLd, descriptionText } from '../../lib/seo'
8
+ import { acceptsReviews } from '../../lib/reviews'
8
9
 
9
10
  const { slug } = Astro.params
10
11
 
@@ -50,7 +51,7 @@ const offersAlerts = capabilities?.email?.delivers === true && defaultVariant !=
50
51
  const hasVariantChoice = (product.variants?.length ?? 0) > 1
51
52
  ---
52
53
 
53
- <BaseLayout title={`${product.name} | Nymbal`} description={product.shortDescription ?? product.description ?? ''} jsonLd={jsonLd}>
54
+ <BaseLayout title={`${product.name} | Nymbal`} description={descriptionText(product.shortDescription || product.description)} jsonLd={jsonLd}>
54
55
  <!-- The gallery's main image is the page's LCP: the browser starts it before it parses the body. -->
55
56
  <link slot="head" rel="preload" as="image" href={images[0]!.url} fetchpriority="high" />
56
57
  <div class="container section" data-product-slug={product.slug}>
@@ -116,8 +117,13 @@ const hasVariantChoice = (product.variants?.length ?? 0) > 1
116
117
 
117
118
  <section class="pdp-reviews">
118
119
  <h2 class="pdp-reviews-title">Customer Reviews</h2>
119
- <NymbalElement tag="nymbal-review-list" attributes={{ reviews: JSON.stringify(reviews) }} />
120
- <NymbalElement tag="nymbal-review-form" attributes={{ class: 'pdp-review-form', 'product-id': product.id }} />
120
+ <NymbalElement
121
+ tag="nymbal-review-list"
122
+ attributes={{ reviews: JSON.stringify(reviews), rating: JSON.stringify(product.rating ?? null) }}
123
+ />
124
+ {acceptsReviews(capabilities) && (
125
+ <NymbalElement tag="nymbal-review-form" attributes={{ class: 'pdp-review-form', 'product-id': product.id }} />
126
+ )}
121
127
  </section>
122
128
 
123
129
  {relatedProducts.length > 0 && (
@@ -9,9 +9,10 @@ import { fetchProducts, fetchCategories, fetchCapabilities, sortFromUrl } from '
9
9
  const capabilities = await fetchCapabilities()
10
10
  const sortKeys = capabilities?.catalog.sortKeys ?? []
11
11
  const sort = sortFromUrl(Astro.url, capabilities?.catalog)
12
+ const category = Astro.url.searchParams.get('category') || undefined
12
13
 
13
14
  const [productResult, categories] = await Promise.all([
14
- fetchProducts({ limit: 24, sort }),
15
+ fetchProducts({ limit: 24, category, sort }),
15
16
  fetchCategories(),
16
17
  ])
17
18
 
@@ -1,4 +1,5 @@
1
1
  import { NymbalApiError } from '@nymbalhq/sdk/core'
2
+ import '@nymbalhq/sdk/ns/auth'
2
3
  import type { ShopperAddress, ShopperOrder } from '@nymbalhq/types'
3
4
  import { client } from '../lib/client.js'
4
5
  import { isPaid, orderHeading } from '../lib/order-status.js'
@@ -7,7 +8,7 @@ import { submitOnce } from '../lib/submit-once.js'
7
8
  // The order page's two forms, each sent once per click from the browser. The expired key's email prompt reads the
8
9
  // order with the email in a header and shows it on this page: read by the storefront's server instead, every shopper's
9
10
  // tries would count against the API's per-address limit as one. "Send me my order link" asks the API, which answers
10
- // the same whatever matched.
11
+ // the same whatever matched. Without this script the forms post to the page, whose server answers them.
11
12
 
12
13
  const byId = (id: string): HTMLElement | null => document.getElementById(id)
13
14
 
@@ -152,3 +153,29 @@ submitOnce(linkForm, async () => {
152
153
  const sent = document.querySelector<HTMLElement>('[data-testid="order-link-sent"]')
153
154
  if (sent) sent.hidden = false
154
155
  })
156
+
157
+ /**
158
+ * A signed-in shopper who opens their own order here without a working key is sent to it in their account. The
159
+ * session is restored first, which refreshes a lapsed token: the API reads a lapsed bearer as a guest's. Only the
160
+ * owner's read answering moves the page, so anyone else's order stays this page's not-found state and the page says
161
+ * nothing about whether it exists. Replacing the entry keeps Back from returning here.
162
+ */
163
+ async function sendOwnerToAccount(orderNumber: string): Promise<void> {
164
+ await client.auth.restore()
165
+ if (!client.auth.getState().isAuthenticated) return
166
+ try {
167
+ await client.customer.orders.get(orderNumber)
168
+ } catch (err) {
169
+ if (err instanceof NymbalApiError && err.status === 404) return
170
+ throw err
171
+ }
172
+ window.location.replace(`/account/orders/${encodeURIComponent(orderNumber)}`)
173
+ }
174
+
175
+ // The not-found state is on the page, shown or behind the expired key's prompt: the key did not open the order.
176
+ const notFound = byId('order-not-found')
177
+ if (notFound?.dataset.orderNumber) {
178
+ sendOwnerToAccount(notFound.dataset.orderNumber).catch((err: unknown) => {
179
+ console.error('The signed-in order check failed', err)
180
+ })
181
+ }
@@ -1,4 +1,17 @@
1
+ /**
2
+ * Where to go once signed in: the decoded `redirect` as the URL parser reads it against `origin`, if both are a path
3
+ * on `origin` (one leading `/`, and `/.//host` reads as `//host`) with no control character; else /account.
4
+ */
5
+ export function signedInTarget(redirect: string | null, origin: string): string {
6
+ if (redirect === null || !/^\/(?![/\\])/.test(redirect)) return '/account'
7
+ if ([...redirect].some((c) => c < ' ' || c === '\x7f')) return '/account'
8
+ const url = new URL(redirect, origin)
9
+ const target = url.pathname + url.search + url.hash
10
+ return /^\/(?![/\\])/.test(target) && url.origin === new URL(origin).origin ? target : '/account'
11
+ }
12
+
1
13
  // Signed in or registered: on to the page that sent the shopper here (`?redirect`), or the account.
2
14
  document.addEventListener('nymbal:auth:signed-in', () => {
3
- window.location.href = new URLSearchParams(window.location.search).get('redirect') ?? '/account'
15
+ const redirect = new URLSearchParams(window.location.search).get('redirect')
16
+ window.location.href = signedInTarget(redirect, window.location.origin)
4
17
  })
@@ -20,6 +20,9 @@ html {
20
20
  -moz-text-size-adjust: 100%;
21
21
  text-size-adjust: 100%;
22
22
  scroll-behavior: smooth;
23
+ /* What is scrolled to the top edge (a fragment, scrollIntoView, keyboard focus) lands below the sticky site header:
24
+ at least its height at every width, with room for a phone header that also holds the mini-cart. */
25
+ scroll-padding-top: 5.5rem;
23
26
  }
24
27
 
25
28
  body {