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
@@ -26,10 +26,13 @@
26
26
 
27
27
  /* ---- Image gallery (nymbal-image-gallery) ---- */
28
28
 
29
- .pdp-gallery {
30
- position: sticky;
31
- top: 80px;
32
- align-self: start;
29
+ /* Sticky only beside the info column: in one column it would paint over the actions scrolling under it. */
30
+ @media (min-width: 769px) {
31
+ .pdp-gallery {
32
+ position: sticky;
33
+ top: 80px;
34
+ align-self: start;
35
+ }
33
36
  }
34
37
 
35
38
  /* ---- Product info ---- */
@@ -1,26 +1,60 @@
1
- # Your Nymbal Store
1
+ # Your Nymbal store
2
2
 
3
- A commerce project scaffolded with [create-nymbal-app](https://github.com/nymbal/nymbal).
3
+ A commerce store made with [create-nymbal-app](https://github.com/nymbalhq/nymbal). Everything in this project is
4
+ yours to edit: `nymbal.config.ts`, and the pages, layouts and components under `src/`.
4
5
 
5
- ## Scripts
6
+ ## Develop
6
7
 
8
+ ```sh
9
+ npx nymbal dev
7
10
  ```
8
- pnpm dev # start Next.js dev server
9
- pnpm build # production build
10
- pnpm start # start production server
11
- pnpm migrate # run database migrations
12
- pnpm seed # re-seed demo content
11
+
12
+ This serves the storefront at `http://localhost:3000`, the API on port 3001 and the admin at
13
+ `http://localhost:3001/admin/` (its email and password are in `.env`). It runs on SQLite with stub payments, and seeds
14
+ demo products on the first run.
15
+
16
+ ## Production
17
+
18
+ Production runs on Postgres and takes payments through Stripe. Add both, then build the store's image:
19
+
20
+ ```sh
21
+ npx nymbal add postgres
22
+ npx nymbal add stripe
23
+ npx nymbal build --image
13
24
  ```
14
25
 
26
+ The image runs `nymbal start`: the API, the admin and the storefront on one port. `npx nymbal deploy fly` and
27
+ `npx nymbal deploy railway` deploy it (`--dry-run` shows the steps first). The
28
+ [quickstart](https://github.com/nymbalhq/nymbal/blob/main/apps/docs/src/content/docs/quickstart.md) runs it locally with
29
+ an AI agent connected, and [Deploying](https://github.com/nymbalhq/nymbal/blob/main/apps/docs/src/content/docs/deploying.md)
30
+ covers the environment it needs.
31
+
32
+ ## Scripts
33
+
34
+ | Script | Runs |
35
+ | ----------- | ------------------------------------------------------------------------------------------ |
36
+ | `dev` | `next dev -p 3000`: the storefront alone, without the API (use `npx nymbal dev`) |
37
+ | `build` | `next build`: the storefront's production build |
38
+ | `start` | `next start -p 3000`: the built storefront alone (`npx nymbal start` runs the whole store) |
39
+ | `typecheck` | `tsc --noEmit` |
40
+ | `migrate` | `nymbal migrate`: apply database migrations |
41
+ | `seed` | `nymbal seed`: seed the demo content again |
42
+
43
+ Run them with your package manager (`npm run dev`, `pnpm dev`, …). `npx nymbal --help` lists every CLI command.
44
+
15
45
  ## Configuration
16
46
 
17
- All configuration lives in `nymbal.config.ts`. Adapters, template, security, and deployment
18
- settings are centralized there — the CLI and every package reads from the same source of truth.
47
+ All configuration lives in `nymbal.config.ts`: the CLI, the API and the storefront read it. `npx nymbal doctor`
48
+ checks the project without changing anything, and `npx nymbal add` lists the providers and services you can add.
49
+
50
+ ## Running behind a proxy
19
51
 
20
- ## Swapping the command store
52
+ The API believes a forwarded client address (`X-Forwarded-For`) only from the proxies listed in
53
+ `NYMBAL_TRUSTED_PROXIES`: `loopback` by default, for a web server on the same machine. On your own server,
54
+ `npx nymbal deploy nginx` (or `apache`, `caddy`) writes a web server config with TLS that sets the header itself.
55
+ Behind a platform proxy, list its range (`NYMBAL_TRUSTED_PROXIES=uniquelocal` on Fly and Railway); otherwise every shopper
56
+ shares one rate-limit bucket, and `nymbal doctor` warns when the list is the default and `NYMBAL_PUBLIC_URL` is public.
21
57
 
22
- For local development you get SQLite out of the box. To move to Postgres:
58
+ ## Help
23
59
 
24
- 1. Set `DATABASE_URL=postgres://…` in `.env`.
25
- 2. Change `infrastructure.commandStore` to `'postgres'` in `nymbal.config.ts`.
26
- 3. Run `pnpm migrate`.
60
+ Report a problem or ask a question at [github.com/nymbalhq/nymbal/issues](https://github.com/nymbalhq/nymbal/issues).
@@ -3,4 +3,6 @@ NYMBAL_API_URL=http://localhost:3001
3
3
  # DATABASE_URL=postgres://user:pass@localhost:5432/nymbal
4
4
  # STRIPE_SECRET_KEY=
5
5
  # STRIPE_WEBHOOK_SECRET=
6
- # ANTHROPIC_API_KEY=
6
+ # The proxies whose X-Forwarded-For the API believes: loopback for a web server on this machine,
7
+ # uniquelocal behind Fly's or Railway's proxy.
8
+ # NYMBAL_TRUSTED_PROXIES=loopback
@@ -3,7 +3,7 @@ import { notFound } from 'next/navigation'
3
3
  import { preload } from 'react-dom'
4
4
  import { fetchProducts, fetchCategories } from '@/lib/api'
5
5
  import { cardImageOf, cardProductOf, renderNymbal } from '@/lib/render'
6
- import { organizationJsonLd } from '@/lib/seo'
6
+ import { organizationJsonLd, serializeJsonLd } from '@/lib/seo'
7
7
  import { HeroSection } from '@/components/server/HeroSection'
8
8
  import { CategoryNav, ProductGrid, RecentlyViewed } from '@/components/client/elements'
9
9
  import { NewsletterSignup } from '@/components/client/NewsletterSignup'
@@ -44,7 +44,7 @@ export default async function HomePage({ params }: HomePageProps) {
44
44
  <>
45
45
  <script
46
46
  type="application/ld+json"
47
- dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
47
+ dangerouslySetInnerHTML={{ __html: serializeJsonLd(jsonLd) }}
48
48
  />
49
49
 
50
50
  <HeroSection />
@@ -3,7 +3,8 @@ import { notFound } from 'next/navigation'
3
3
  import { preload } from 'react-dom'
4
4
  import { fetchCapabilities, fetchProduct, fetchProducts, fetchReviews } from '@/lib/api'
5
5
  import { cardProductOf, renderNymbal } from '@/lib/render'
6
- import { productJsonLd } from '@/lib/seo'
6
+ import { acceptsReviews } from '@/lib/reviews'
7
+ import { descriptionText, productJsonLd, serializeJsonLd } from '@/lib/seo'
7
8
  import {
8
9
  Breadcrumb,
9
10
  ImageGallery,
@@ -37,7 +38,8 @@ export async function generateMetadata({ params }: ProductPageProps): Promise<Me
37
38
 
38
39
  return {
39
40
  title: product.name,
40
- description: product.shortDescription ?? product.description ?? `Buy ${product.name}.`,
41
+ description:
42
+ descriptionText(product.shortDescription || product.description) || `Buy ${product.name}.`,
41
43
  }
42
44
  }
43
45
 
@@ -88,10 +90,15 @@ export default async function ProductPage({ params }: ProductPageProps) {
88
90
  stock: String(variant.stock ?? 0),
89
91
  }).__html
90
92
  : undefined,
93
+ reviews: renderNymbal('nymbal-review-list', {
94
+ reviews: JSON.stringify(reviews),
95
+ rating: JSON.stringify(product.rating ?? null),
96
+ }).__html,
91
97
  }
92
98
 
93
99
  const baseUrl = process.env.NEXT_PUBLIC_SITE_URL ?? 'http://localhost:3000'
94
100
  const jsonLd = productJsonLd(product, baseUrl)
101
+ const descriptionHtml = { __html: product.description || 'No additional details available.' }
95
102
 
96
103
  const mediaArray = Array.isArray(product.media) ? product.media : []
97
104
  const images =
@@ -115,7 +122,7 @@ export default async function ProductPage({ params }: ProductPageProps) {
115
122
  <>
116
123
  <script
117
124
  type="application/ld+json"
118
- dangerouslySetInnerHTML={{ __html: JSON.stringify(jsonLd) }}
125
+ dangerouslySetInnerHTML={{ __html: serializeJsonLd(jsonLd) }}
119
126
  />
120
127
 
121
128
  <div className={`container ${styles.page}`}>
@@ -141,17 +148,17 @@ export default async function ProductPage({ params }: ProductPageProps) {
141
148
  />
142
149
 
143
150
  {product.description && (
144
- <div className={styles.description}>
145
- <p>{product.description}</p>
146
- </div>
151
+ <div
152
+ className={styles.description}
153
+ data-testid="product-description"
154
+ dangerouslySetInnerHTML={descriptionHtml}
155
+ />
147
156
  )}
148
157
 
149
158
  <div className={styles.detailsSection}>
150
159
  <details className={styles.detailsItem}>
151
160
  <summary className={styles.detailsSummary}>Details</summary>
152
- <div className={styles.detailsContent}>
153
- {product.description ?? 'No additional details available.'}
154
- </div>
161
+ <div className={styles.detailsContent} dangerouslySetInnerHTML={descriptionHtml} />
155
162
  </details>
156
163
  <details className={styles.detailsItem}>
157
164
  <summary className={styles.detailsSummary}>Shipping & Returns</summary>
@@ -166,17 +173,14 @@ export default async function ProductPage({ params }: ProductPageProps) {
166
173
 
167
174
  <section className={styles.reviewsSection}>
168
175
  <h2 className={styles.reviewsTitle}>Customer Reviews</h2>
169
- <ReviewList
170
- reviews={reviews}
171
- serverHtml={
172
- renderNymbal('nymbal-review-list', { reviews: JSON.stringify(reviews) }).__html
173
- }
174
- />
175
- <ReviewForm
176
- className={styles.reviewForm}
177
- productId={product.id}
178
- serverHtml={renderNymbal('nymbal-review-form', { 'product-id': product.id }).__html}
179
- />
176
+ <ReviewList reviews={reviews} rating={product.rating} serverHtml={serverHtml.reviews} />
177
+ {acceptsReviews(capabilities) && (
178
+ <ReviewForm
179
+ className={styles.reviewForm}
180
+ productId={product.id}
181
+ serverHtml={renderNymbal('nymbal-review-form', { 'product-id': product.id }).__html}
182
+ />
183
+ )}
180
184
  </section>
181
185
 
182
186
  {related.length > 0 && (
@@ -10,20 +10,22 @@ export const metadata: Metadata = {
10
10
  description: 'Browse our full collection of products.',
11
11
  }
12
12
 
13
- // The page reads `?sort=`, so it renders per request; said here, the build does not render it with the API down. Its
14
- // catalog reads still go through Next's data cache.
13
+ // The page reads `?sort=` and `?category=`, so it renders per request; said here, the build does not render it with
14
+ // the API down. Its catalog reads still go through Next's data cache.
15
15
  export const dynamic = 'force-dynamic'
16
16
 
17
17
  interface ProductsPageProps {
18
- searchParams: Promise<{ sort?: string | string[] }>
18
+ searchParams: Promise<{ sort?: string | string[]; category?: string | string[] }>
19
19
  }
20
20
 
21
21
  const CRUMBS = [{ label: 'Home', href: '/' }, { label: 'Products' }]
22
22
 
23
23
  export default async function ProductsPage({ searchParams }: ProductsPageProps) {
24
24
  const capabilities = await fetchCapabilities()
25
- const sort = sortFromSearchParams(await searchParams, capabilities?.catalog)
26
- const { items, nextCursor, facets } = await fetchProducts({ limit: 24, sort })
25
+ const params = await searchParams
26
+ const sort = sortFromSearchParams(params, capabilities?.catalog)
27
+ const category = (Array.isArray(params.category) ? params.category[0] : params.category) || undefined
28
+ const { items, nextCursor, facets } = await fetchProducts({ limit: 24, category, sort })
27
29
  const cards = items.map(cardProductOf)
28
30
  // The first card's image is the page's LCP, and the preload scanner never reaches it inside the grid's shadow root:
29
31
  // a preload link, which React hoists into the head, starts it.
@@ -46,6 +48,7 @@ export default async function ProductsPage({ searchParams }: ProductsPageProps)
46
48
  <h1 className={styles.pageTitle}>All Products</h1>
47
49
  <ListingControls
48
50
  sort={sort}
51
+ category={category}
49
52
  facets={facets ?? []}
50
53
  sortKeys={capabilities?.catalog.sortKeys ?? []}
51
54
  defaultSort={capabilities?.catalog.defaultSort}
@@ -49,7 +49,7 @@ export function SearchView({
49
49
  window.history.replaceState(null, '', url.toString())
50
50
  }, [])
51
51
 
52
- const filtered = facets.length > 0 && results.length > 0
52
+ const filtered = results.length > 0 && facets.some((facet) => facet.values.length > 0)
53
53
 
54
54
  return (
55
55
  <div className={`container ${styles.page}`}>
@@ -6,12 +6,12 @@ import Link from 'next/link'
6
6
  import { LoginForm } from '@nymbalhq/react'
7
7
  import styles from '@/styles/pages/account.module.css'
8
8
 
9
- /** `serverHtml` is the form as the server rendered it, `redirect` where to go once signed in (page.tsx). */
10
- export function LoginView({ serverHtml, redirect }: { serverHtml: string; redirect?: string }) {
9
+ /** `serverHtml` is the form as the server rendered it, `target` the store path to go to once signed in (page.tsx). */
10
+ export function LoginView({ serverHtml, target }: { serverHtml: string; target: string }) {
11
11
  const router = useRouter()
12
12
  const onSignedIn = useCallback(() => {
13
- router.push(redirect ?? '/account')
14
- }, [router, redirect])
13
+ router.push(target)
14
+ }, [router, target])
15
15
 
16
16
  return (
17
17
  <div className={styles.authPage}>
@@ -1,5 +1,6 @@
1
1
  import type { Metadata } from 'next'
2
2
  import { renderNymbal } from '@/lib/render'
3
+ import { signedInTarget } from '@/lib/signed-in-target'
3
4
  import { LoginView } from './LoginView'
4
5
 
5
6
  export const metadata: Metadata = {
@@ -14,9 +15,10 @@ interface LoginPageProps {
14
15
  // boundary, which React may stream after the shell, and without JavaScript a streamed boundary is never shown.
15
16
  export default async function LoginPage({ searchParams }: LoginPageProps) {
16
17
  const { redirect } = await searchParams
18
+ const origin = process.env.NEXT_PUBLIC_SITE_URL ?? 'http://localhost:3000'
17
19
  return (
18
20
  <LoginView
19
- redirect={typeof redirect === 'string' ? redirect : undefined}
21
+ target={signedInTarget(typeof redirect === 'string' ? redirect : null, origin)}
20
22
  serverHtml={renderNymbal('nymbal-login-form').__html}
21
23
  />
22
24
  )
@@ -1,6 +1,7 @@
1
1
  'use server'
2
2
 
3
- import { confirmAlert, unsubscribeAlert, type AlertConfirmation } from '@/lib/api'
3
+ import { headers } from 'next/headers'
4
+ import { confirmAlert, shopperHeaders, unsubscribeAlert, type AlertConfirmation } from '@/lib/api'
4
5
 
5
6
  /** What a press of an alert page's button shows. */
6
7
  export type AlertLinkResult =
@@ -19,7 +20,8 @@ export async function confirmAlertAction(
19
20
  form: FormData,
20
21
  ): Promise<AlertLinkResult> {
21
22
  const token = tokenOf(form)
22
- const confirmation = token === '' ? null : await confirmAlert(token)
23
+ const confirmation =
24
+ token === '' ? null : await confirmAlert(token, shopperHeaders(await headers()))
23
25
  return confirmation ? { result: 'confirmed', confirmation } : { result: 'invalid' }
24
26
  }
25
27
 
@@ -28,6 +30,7 @@ export async function unsubscribeAlertAction(
28
30
  form: FormData,
29
31
  ): Promise<AlertLinkResult> {
30
32
  const token = tokenOf(form)
31
- const stopped = token === '' ? false : await unsubscribeAlert(token)
33
+ const stopped =
34
+ token === '' ? false : await unsubscribeAlert(token, shopperHeaders(await headers()))
32
35
  return stopped ? { result: 'unsubscribed' } : { result: 'invalid' }
33
36
  }
@@ -1,22 +1,38 @@
1
1
  import type { Metadata } from 'next'
2
2
  import { headers } from 'next/headers'
3
- import { fetchCart } from '@/lib/api'
4
- import { renderNymbal } from '@/lib/render'
3
+ import { cartPageCart, hasCartCookie, type CartProjection } from '@/lib/api'
4
+ import { renderElement, renderNymbal } from '@/lib/render'
5
5
  import CartPage from './CartView'
6
6
 
7
7
  export const metadata: Metadata = {
8
8
  title: 'Shopping Cart',
9
9
  }
10
10
 
11
+ /** With JavaScript off: the empty cart, with the element's loading shell hidden. */
12
+ function noScriptEmptyCart(cart: CartProjection): string {
13
+ return (
14
+ '<style>nymbal-cart-page:not([cart]) { display: none; }</style>' +
15
+ renderElement('nymbal-cart-page', { attributes: { cart: JSON.stringify(cart) } })
16
+ )
17
+ }
18
+
11
19
  export default async function CartRoute() {
12
- const cart = await fetchCart((await headers()).get('cookie'))
20
+ const cookie = (await headers()).get('cookie')
21
+ const cart = await cartPageCart(cookie)
22
+ // Without the cookie this server cannot tell an empty cart from one the browser holds for an API on another host, so
23
+ // the empty cart is for a browser without JavaScript; with it, the element's own read decides.
24
+ const noCookie = !hasCartCookie(cookie)
25
+ const shown = noCookie ? null : cart
13
26
  const serverHtml = renderNymbal(
14
27
  'nymbal-cart-page',
15
- cart === null ? {} : { cart: JSON.stringify(cart) },
28
+ shown === null ? {} : { cart: JSON.stringify(shown) },
16
29
  ).__html
17
30
  return (
18
31
  <div className="container section" data-testid="cart-page">
19
- <CartPage cart={cart ?? undefined} serverHtml={serverHtml} />
32
+ <CartPage cart={shown ?? undefined} serverHtml={serverHtml} />
33
+ {noCookie && cart !== null && (
34
+ <noscript dangerouslySetInnerHTML={{ __html: noScriptEmptyCart(cart) }} />
35
+ )}
20
36
  </div>
21
37
  )
22
38
  }
@@ -1,12 +1,14 @@
1
1
  'use client'
2
2
 
3
- import { useRef, useState, type FormEvent } from 'react'
3
+ import { useActionState, useRef, useState, type FormEvent } from 'react'
4
4
  import { NymbalApiError } from '@nymbalhq/sdk'
5
5
  import type { ShopperOrder } from '@nymbalhq/types'
6
6
  import { getNymbalClient } from '@/lib/client'
7
7
  import styles from '@/styles/pages/error.module.css'
8
+ import { orderPageAction } from './actions'
8
9
  import { OrderNotFound } from './OrderNotFound'
9
10
  import { OrderView } from './OrderView'
11
+ import { OwnerRedirect } from './OwnerRedirect'
10
12
 
11
13
  type State =
12
14
  | { kind: 'idle' | 'sending' | 'limited' | 'failed' | 'not-found' }
@@ -15,7 +17,8 @@ type State =
15
17
  /**
16
18
  * The order's key has expired: the shopper gives the order's email to open it. The browser reads the order with the
17
19
  * email in a header, so it never lands in a page URL and each shopper's tries count against their own address, not
18
- * the storefront server's. One request per click: a second submit while one is out is ignored.
20
+ * the storefront server's. One request per click: a second submit while one is out is ignored. Without the script,
21
+ * this form and the not-found state's link form post to one action state, whose answer picks what the page shows.
19
22
  */
20
23
  export function OrderEmailPrompt({
21
24
  orderNumber,
@@ -25,6 +28,7 @@ export function OrderEmailPrompt({
25
28
  orderKey: string
26
29
  }) {
27
30
  const [state, setState] = useState<State>({ kind: 'idle' })
31
+ const [served, formAction] = useActionState(orderPageAction, null)
28
32
  const inFlight = useRef(false)
29
33
 
30
34
  async function onSubmit(event: FormEvent<HTMLFormElement>) {
@@ -47,10 +51,28 @@ export function OrderEmailPrompt({
47
51
  }
48
52
 
49
53
  if (state.kind === 'opened') return <OrderView order={state.order} />
50
- if (state.kind === 'not-found') return <OrderNotFound />
54
+ if (served?.kind === 'opened') {
55
+ return (
56
+ <OrderView
57
+ order={served.order}
58
+ timelineHtml={served.timelineHtml}
59
+ summaryHtml={served.summaryHtml}
60
+ />
61
+ )
62
+ }
63
+ const notFound =
64
+ state.kind === 'not-found' ||
65
+ served?.kind === 'not-found' ||
66
+ served?.kind === 'link-sent' ||
67
+ served?.kind === 'link-limited'
68
+ if (notFound) return <OrderNotFound link={[served, formAction]} />
51
69
  return (
52
70
  <div className={styles.page}>
53
- <form method="post" onSubmit={onSubmit} className={styles.wrapper}>
71
+ <OwnerRedirect />
72
+ <form action={formAction} onSubmit={onSubmit} className={styles.wrapper}>
73
+ <input type="hidden" name="intent" value="open" />
74
+ <input type="hidden" name="orderNumber" value={orderNumber} />
75
+ <input type="hidden" name="key" value={orderKey} />
54
76
  <h1 className={styles.title}>Open your order</h1>
55
77
  <p className={styles.message}>
56
78
  This order link has expired. Enter the email you gave at checkout to open the order.
@@ -66,7 +88,7 @@ export function OrderEmailPrompt({
66
88
  data-testid="order-email-input"
67
89
  />
68
90
  </div>
69
- {state.kind === 'limited' && (
91
+ {(state.kind === 'limited' || served?.kind === 'open-limited') && (
70
92
  <p className={styles.message} data-testid="order-email-limited">
71
93
  Too many tries for now. Please try again in a while.
72
94
  </p>
@@ -1,16 +1,22 @@
1
1
  'use client'
2
2
 
3
- import { useRef, useState, type FormEvent } from 'react'
3
+ import { useActionState, useRef, useState, type FormEvent } from 'react'
4
4
  import { getNymbalClient } from '@/lib/client'
5
5
  import styles from '@/styles/pages/error.module.css'
6
+ import { orderPageAction, type OrderPageState } from './actions'
6
7
 
7
8
  type State = 'idle' | 'sending' | 'sent' | 'failed'
8
9
 
10
+ /** The action state a link form posts to without the page's script, and the action that answers it. */
11
+ export type LinkFormBinding = readonly [OrderPageState | null, (form: FormData) => void]
12
+
9
13
  /**
10
14
  * "Send me my order link": the store emails the order's link to the order's own email, and answers the same whatever
11
15
  * matched, so the page says the same either way. One request per click: a second submit while one is out is ignored.
16
+ * Without the script the form posts to `orderPageAction` through `binding`, the expired page's own when it is there.
12
17
  */
13
- export function OrderLinkForm() {
18
+ export function OrderLinkForm({ binding }: { binding: LinkFormBinding }) {
19
+ const [served, formAction] = binding
14
20
  const [state, setState] = useState<State>('idle')
15
21
  const inFlight = useRef(false)
16
22
 
@@ -33,7 +39,7 @@ export function OrderLinkForm() {
33
39
  }
34
40
  }
35
41
 
36
- if (state === 'sent') {
42
+ if (state === 'sent' || served?.kind === 'link-sent') {
37
43
  return (
38
44
  <p className={styles.message} data-testid="order-link-sent">
39
45
  If that number and email match an order, its link is on its way to that email.
@@ -41,7 +47,8 @@ export function OrderLinkForm() {
41
47
  )
42
48
  }
43
49
  return (
44
- <form method="post" className={styles.searchPrompt} onSubmit={onSubmit}>
50
+ <form action={formAction} className={styles.searchPrompt} onSubmit={onSubmit}>
51
+ <input type="hidden" name="intent" value="link" />
45
52
  <div className={styles.searchPromptInput}>
46
53
  <label htmlFor="order-link-number">Order number</label>
47
54
  <input id="order-link-number" name="orderNumber" required data-testid="order-link-number" />
@@ -55,6 +62,9 @@ export function OrderLinkForm() {
55
62
  data-testid="order-link-email"
56
63
  />
57
64
  </div>
65
+ {served?.kind === 'link-limited' && (
66
+ <p className={styles.message}>Too many tries for now. Please try again in a while.</p>
67
+ )}
58
68
  {state === 'failed' && (
59
69
  <p className={styles.message}>We could not send the link just now. Please try again.</p>
60
70
  )}
@@ -71,3 +81,9 @@ export function OrderLinkForm() {
71
81
  </form>
72
82
  )
73
83
  }
84
+
85
+ /** The bare not-found page's link form, with an action state of its own. */
86
+ export function OwnOrderLinkForm() {
87
+ const [served, formAction] = useActionState(orderPageAction, null)
88
+ return <OrderLinkForm binding={[served, formAction]} />
89
+ }
@@ -1,11 +1,16 @@
1
1
  import Link from 'next/link'
2
2
  import styles from '@/styles/pages/error.module.css'
3
- import { OrderLinkForm } from './OrderLinkForm'
3
+ import { OrderLinkForm, OwnOrderLinkForm, type LinkFormBinding } from './OrderLinkForm'
4
+ import { OwnerRedirect } from './OwnerRedirect'
4
5
 
5
- /** The order page's not-found state: what the site's 404 says, and a way to ask for a fresh order link. */
6
- export function OrderNotFound() {
6
+ /**
7
+ * The order page's not-found state: what the site's 404 says, and a way to ask for a fresh order link. `link` is the
8
+ * expired page's action state, which its link form shares; the bare not-found page's form has its own.
9
+ */
10
+ export function OrderNotFound({ link }: { link?: LinkFormBinding }) {
7
11
  return (
8
12
  <div className={styles.page}>
13
+ <OwnerRedirect />
9
14
  <div className={styles.wrapper}>
10
15
  <p className={styles.statusCode}>404</p>
11
16
  <h1 className={styles.title}>Order not found</h1>
@@ -13,7 +18,7 @@ export function OrderNotFound() {
13
18
  This link does not open an order. Give its order number and the email you gave at
14
19
  checkout, and we&apos;ll email you a fresh link if they match.
15
20
  </p>
16
- <OrderLinkForm />
21
+ {link ? <OrderLinkForm binding={link} /> : <OwnOrderLinkForm />}
17
22
  <div className={styles.actions}>
18
23
  <Link href="/products" className={styles.retryButton}>
19
24
  Browse Products
@@ -0,0 +1,48 @@
1
+ 'use client'
2
+
3
+ import { useEffect } from 'react'
4
+ import { useParams, useRouter } from 'next/navigation'
5
+ import { NymbalApiError } from '@nymbalhq/sdk'
6
+ import { getNymbalClient, restoreSession } from '@/lib/client'
7
+
8
+ /**
9
+ * Where a signed-in shopper who opened their own order here without a working key belongs: the order in their
10
+ * account. The session is restored first, which refreshes a lapsed token: the API reads a lapsed bearer as a guest's.
11
+ * Only the owner's read answering gives a path, so anyone else's order stays this page's not-found state and the page
12
+ * says nothing about whether it exists. Null with no session, so a guest's visit sends nothing.
13
+ */
14
+ async function ownersAccountPath(orderNumber: string): Promise<string | null> {
15
+ await restoreSession()
16
+ const client = getNymbalClient()
17
+ if (!client.auth.getState().isAuthenticated) return null
18
+ try {
19
+ await client.customer.orders.get(orderNumber)
20
+ } catch (err) {
21
+ if (err instanceof NymbalApiError && err.status === 404) return null
22
+ throw err
23
+ }
24
+ return `/account/orders/${encodeURIComponent(orderNumber)}`
25
+ }
26
+
27
+ /** Sends the order's signed-in owner on to it in their account; replacing the entry keeps Back from returning here. */
28
+ export function OwnerRedirect() {
29
+ const params = useParams<{ orderNumber?: string }>()
30
+ const orderNumber = decodeURIComponent(params.orderNumber ?? '')
31
+ const router = useRouter()
32
+
33
+ useEffect(() => {
34
+ if (!orderNumber) return
35
+ let active = true
36
+ ownersAccountPath(orderNumber).then(
37
+ (path) => {
38
+ if (active && path !== null) router.replace(path)
39
+ },
40
+ (err: unknown) => console.error('The signed-in order check failed', err),
41
+ )
42
+ return () => {
43
+ active = false
44
+ }
45
+ }, [orderNumber, router])
46
+
47
+ return null
48
+ }
@@ -0,0 +1,56 @@
1
+ 'use server'
2
+
3
+ import { headers } from 'next/headers'
4
+ import type { ShopperOrder } from '@nymbalhq/types'
5
+ import { openExpiredOrder, requestOrderLink, shopperHeaders } from '@/lib/api'
6
+ import { renderNymbal } from '@/lib/render'
7
+ import { summaryAttributes } from './OrderView'
8
+
9
+ /** What the order page shows once this server answered one of its forms. */
10
+ export type OrderPageState =
11
+ | { kind: 'opened'; order: ShopperOrder; timelineHtml: string; summaryHtml: string }
12
+ | { kind: 'not-found' }
13
+ | { kind: 'link-sent' }
14
+ | { kind: 'open-limited' }
15
+ | { kind: 'link-limited' }
16
+
17
+ function field(form: FormData, name: string): string {
18
+ const value = form.get(name)
19
+ return typeof value === 'string' ? value.trim() : ''
20
+ }
21
+
22
+ /**
23
+ * The order page's two forms sent without the page's script, which sends both from the browser: `intent=open` reads
24
+ * the expired key's order with the typed email, `intent=link` asks for a fresh link. The email stays in the body. An
25
+ * opened order carries the elements' server HTML, so its summary and timeline show without a script.
26
+ */
27
+ export async function orderPageAction(
28
+ _previous: OrderPageState | null,
29
+ form: FormData,
30
+ ): Promise<OrderPageState> {
31
+ const forwarded = shopperHeaders(await headers())
32
+ if (field(form, 'intent') === 'link') {
33
+ const answer = await requestOrderLink(
34
+ field(form, 'orderNumber'),
35
+ field(form, 'email'),
36
+ forwarded,
37
+ )
38
+ return { kind: answer === 'sent' ? 'link-sent' : 'link-limited' }
39
+ }
40
+ const read = await openExpiredOrder(
41
+ field(form, 'orderNumber'),
42
+ field(form, 'key'),
43
+ field(form, 'email'),
44
+ forwarded,
45
+ )
46
+ if (read === 'not-found') return { kind: 'not-found' }
47
+ if (read === 'limited') return { kind: 'open-limited' }
48
+ return {
49
+ kind: 'opened',
50
+ order: read,
51
+ timelineHtml: renderNymbal('nymbal-order-timeline', {
52
+ entries: JSON.stringify(read.timeline ?? []),
53
+ }).__html,
54
+ summaryHtml: renderNymbal('nymbal-order-summary', summaryAttributes(read)).__html,
55
+ }
56
+ }