@velastack/patterns 0.8.0 → 0.9.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 (26) hide show
  1. package/dist/chunks/{collections-BrEA7a62.js → collections-DZOuRpvS.js} +6 -1
  2. package/dist/chunks/collections-DZOuRpvS.js.map +1 -0
  3. package/dist/chunks/{generate-BZ741GPx.js → currency.server-Bb2Ndutg.js} +6 -3
  4. package/dist/chunks/{generate-BZ741GPx.js.map → currency.server-Bb2Ndutg.js.map} +1 -1
  5. package/dist/chunks/{generate-6JS05dWK.js → generate-B-cqjI-U.js} +62 -55
  6. package/dist/chunks/generate-B-cqjI-U.js.map +1 -0
  7. package/dist/chunks/{generate.runtime-BOl3LpPB.js → generate.runtime-BnqS_Zq8.js} +84 -158
  8. package/dist/chunks/generate.runtime-BnqS_Zq8.js.map +1 -0
  9. package/dist/chunks/{generate.runtime-KrQk7mqG.js → generate.runtime-DG9Lp3vR.js} +39 -37
  10. package/dist/chunks/generate.runtime-DG9Lp3vR.js.map +1 -0
  11. package/dist/chunks/{generate.runtime-Dt3Edp8-.js → generate.runtime-X-uAteso.js} +123 -104
  12. package/dist/chunks/generate.runtime-X-uAteso.js.map +1 -0
  13. package/dist/chunks/load-function-Dmkhg1pQ.js +79 -0
  14. package/dist/chunks/load-function-Dmkhg1pQ.js.map +1 -0
  15. package/dist/chunks/root-layout.svelte-CUVbnlX-.js +302 -0
  16. package/dist/chunks/root-layout.svelte-CUVbnlX-.js.map +1 -0
  17. package/dist/index.js +15 -15
  18. package/dist/index.js.map +1 -1
  19. package/package.json +1 -1
  20. package/dist/chunks/collections-BrEA7a62.js.map +0 -1
  21. package/dist/chunks/generate-6JS05dWK.js.map +0 -1
  22. package/dist/chunks/generate.runtime-BOl3LpPB.js.map +0 -1
  23. package/dist/chunks/generate.runtime-Dt3Edp8-.js.map +0 -1
  24. package/dist/chunks/generate.runtime-KrQk7mqG.js.map +0 -1
  25. package/dist/chunks/root-layout.svelte-CsJ2QJYi.js +0 -93
  26. package/dist/chunks/root-layout.svelte-CsJ2QJYi.js.map +0 -1
package/dist/index.js CHANGED
@@ -16,8 +16,8 @@ import { $ as Ae, $t as je, A as Me, At as Ne, B as Pe, Bt as Fe, C as Ie, Ct as
16
16
  import { t as Xn } from "./chunks/env-vars-mnRA0hOe.js";
17
17
  import { t as Zn } from "./chunks/generate-DoHn_xJZ.js";
18
18
  import { t as Qn } from "./chunks/pocketbase-DpudAAmd.js";
19
- import { i as $n, n as er, r as tr, t as nr } from "./chunks/generate-BZ741GPx.js";
20
- import { a as rr, n as ir, t as ar } from "./chunks/collections-BrEA7a62.js";
19
+ import { a as $n, i as er, o as tr, r as nr } from "./chunks/currency.server-Bb2Ndutg.js";
20
+ import { a as rr, n as ir, t as ar } from "./chunks/collections-DZOuRpvS.js";
21
21
  import { o as or } from "./chunks/site-VrqOvuiU.js";
22
22
  import { a as sr, i as cr, n as lr, o as ur, r as dr, s as fr, t as pr } from "./chunks/dispatch-BIvOwbKN.js";
23
23
  import { t as mr } from "./chunks/pocketbase-C5GS-Dh5.js";
@@ -25,10 +25,10 @@ import { t as hr } from "./chunks/env-vars-Cr4lbMD_.js";
25
25
  import { n as N, t as gr } from "./chunks/shared-BbxLil4g.js";
26
26
  import { i as _r } from "./chunks/generate-Df7t5Nbk.js";
27
27
  import { r as vr } from "./chunks/generate-CNabcEBx.js";
28
- import { n as yr, t as br } from "./chunks/generate-6JS05dWK.js";
28
+ import { n as yr, t as br } from "./chunks/generate-B-cqjI-U.js";
29
29
  var xr = {
30
30
  name: "@velastack/patterns",
31
- version: "0.8.0",
31
+ version: "0.9.0",
32
32
  description: "Registry of VelaStack patterns: generators and modifications applied to SvelteKit projects by the VelaStack CLI.",
33
33
  type: "module",
34
34
  private: !1,
@@ -4128,7 +4128,7 @@ var Qs = {
4128
4128
  tests: 0,
4129
4129
  baseline: "velastack",
4130
4130
  generate: Zs
4131
- }, $s = "<script lang=\"ts\">\n import { formatMoney } from '#lib/cart.svelte.js';\n\n let { data } = $props();\n<\/script>\n\n<section data-role=\"content\">\n <h1 class=\"mb-6 text-2xl font-semibold\">Shop</h1>\n\n {#if data.products.length === 0}\n <p class=\"text-muted-foreground\">\n Nothing for sale yet. Products live in Shopify admin; publish them to the Headless channel\n the Storefront token belongs to.\n </p>\n {:else}\n <ul class=\"grid gap-6 sm:grid-cols-2 lg:grid-cols-3\">\n {#each data.products as product (product.id)}\n <li class=\"rounded-lg border p-4\">\n <a href=\"/shop/{product.handle}\" class=\"flex flex-col gap-3\">\n {#if product.featuredImage}\n <img\n src={product.featuredImage.url}\n alt={product.featuredImage.altText ?? ''}\n class=\"aspect-square w-full rounded object-cover\"\n />\n {/if}\n <div>\n <h2 class=\"font-medium\">{product.title}</h2>\n <p class=\"text-muted-foreground text-sm\">\n From {formatMoney(product.priceRange.minVariantPrice)}\n </p>\n </div>\n </a>\n </li>\n {/each}\n </ul>\n {/if}\n</section>\n", ec = "import { error } from '@sveltejs/kit';\nimport { storefront } from '#lib/shopify.js';\n\nexport interface Money {\n amount: string;\n currencyCode: string;\n}\n\nexport interface ProductCard {\n id: string;\n handle: string;\n title: string;\n featuredImage: { url: string; altText: string | null } | null;\n priceRange: { minVariantPrice: Money };\n}\n\nconst PRODUCTS = `#graphql\n query Products {\n products(first: 100, sortKey: TITLE) {\n nodes {\n id\n handle\n title\n featuredImage {\n url\n altText\n }\n priceRange {\n minVariantPrice {\n amount\n currencyCode\n }\n }\n }\n }\n }\n`;\n\n// The Storefront token is public, so the same load runs on the server and in\n// the browser. It is not prerendered: the catalog changes without a rebuild.\nexport const prerender = false;\n\nexport const load = async () => {\n const { data, errors } = await storefront().request(PRODUCTS);\n if (errors) error(502, errors.message ?? 'Shopify did not answer.');\n return { products: (data?.products.nodes ?? []) as ProductCard[] };\n};\n", tc = "<script lang=\"ts\">\n import { Button } from '#lib/components/ui/button/index.js';\n import AddToCart from '#lib/components/cart/add-to-cart.svelte';\n import { formatMoney } from '#lib/cart.svelte.js';\n\n let { data } = $props();\n\n // One value per option, starting from the first variant that can be bought.\n // The variant for sale is the one whose options all match.\n const first = data.product.variants.nodes.find((v) => v.availableForSale) ??\n data.product.variants.nodes[0];\n let chosen = $state<Record<string, string>>(\n Object.fromEntries(first.selectedOptions.map((option) => [option.name, option.value]))\n );\n const variant = $derived(\n data.product.variants.nodes.find((candidate) =>\n candidate.selectedOptions.every((option) => chosen[option.name] === option.value)\n )\n );\n // A product with one variant has a single option Shopify calls \"Title\".\n const options = $derived(\n data.product.options.filter((option) => option.optionValues.length > 1)\n );\n<\/script>\n\n<section data-role=\"content\" class=\"grid gap-8 md:grid-cols-2\">\n <div class=\"flex flex-col gap-3\">\n {#each data.product.images.nodes.slice(0, 1) as image (image.url)}\n <img src={image.url} alt={image.altText ?? ''} class=\"aspect-square w-full rounded-lg object-cover\" />\n {/each}\n </div>\n\n <div class=\"flex flex-col gap-6\">\n <div>\n <p class=\"text-muted-foreground mb-2 text-sm\"><a href=\"/shop\">Shop</a></p>\n <h1 class=\"text-2xl font-semibold\">{data.product.title}</h1>\n {#if variant}\n <p class=\"mt-2 text-lg\">{formatMoney(variant.price)}</p>\n {/if}\n </div>\n\n {#each options as option (option.name)}\n <div class=\"flex flex-col gap-2\">\n <p class=\"text-sm font-medium\">{option.name}</p>\n <div class=\"flex flex-wrap gap-2\" role=\"radiogroup\" aria-label={option.name}>\n {#each option.optionValues as value (value.name)}\n <Button\n variant={chosen[option.name] === value.name ? 'default' : 'outline'}\n size=\"sm\"\n role=\"radio\"\n aria-checked={chosen[option.name] === value.name}\n onclick={() => (chosen = { ...chosen, [option.name]: value.name })}\n >\n {value.name}\n </Button>\n {/each}\n </div>\n </div>\n {/each}\n\n {#if variant}\n <AddToCart\n merchandiseId={variant.id}\n size=\"lg\"\n disabled={!variant.availableForSale}\n label={variant.availableForSale ? 'Add to cart' : 'Sold out'}\n />\n {:else}\n <p class=\"text-muted-foreground text-sm\">That combination is not available.</p>\n {/if}\n\n {#if data.product.descriptionHtml}\n <!-- The description as written in Shopify admin, which is HTML. -->\n <div class=\"prose prose-sm text-muted-foreground\">{@html data.product.descriptionHtml}</div>\n {/if}\n </div>\n</section>\n", nc = "import { error } from '@sveltejs/kit';\nimport { storefront } from '#lib/shopify.js';\nimport type { Money } from '../+page.js';\n\nexport interface Variant {\n id: string;\n title: string;\n availableForSale: boolean;\n price: Money;\n selectedOptions: { name: string; value: string }[];\n}\n\nexport interface Product {\n id: string;\n title: string;\n descriptionHtml: string;\n images: { nodes: { url: string; altText: string | null }[] };\n options: { name: string; optionValues: { name: string }[] }[];\n variants: { nodes: Variant[] };\n}\n\nconst PRODUCT = `#graphql\n query Product($handle: String!) {\n product(handle: $handle) {\n id\n title\n descriptionHtml\n images(first: 4) {\n nodes {\n url\n altText\n }\n }\n options {\n name\n optionValues {\n name\n }\n }\n variants(first: 100) {\n nodes {\n id\n title\n availableForSale\n price {\n amount\n currencyCode\n }\n selectedOptions {\n name\n value\n }\n }\n }\n }\n }\n`;\n\nexport const prerender = false;\n\nexport const load = async ({ params }) => {\n const { data, errors } = await storefront().request(PRODUCT, {\n variables: { handle: params.handle }\n });\n if (errors) error(502, errors.message ?? 'Shopify did not answer.');\n const product = data?.product as Product | null | undefined;\n if (!product) error(404, 'Not found');\n return { product };\n};\n", rc = "/** The fields of the synced catalog this page reads. */\ninterface ProductRecord {\n id: string;\n name?: string;\n /** Stripe's boolean, stored by the sync in a text field. */\n active?: unknown;\n default_price?: string;\n description?: string;\n images?: unknown;\n metadata?: unknown;\n}\n\ninterface PriceRecord {\n id: string;\n product?: string;\n unit_amount?: number;\n currency?: string;\n}\n\nconst isActive = (product: ProductRecord) => String(product.active) !== 'false';\n\nconst slugOf = (product: ProductRecord): string => {\n const metadata = product.metadata as { slug?: unknown } | null | undefined;\n return typeof metadata?.slug === 'string' && metadata.slug ? metadata.slug : product.id;\n};\n\nconst firstImage = (product: ProductRecord): string | null =>\n Array.isArray(product.images) && typeof product.images[0] === 'string'\n ? product.images[0]\n : null;\n\n/**\n * The catalog, as the sync copied it from Stripe: every active product with\n * its default one-time price (or its first active one). A product's\n * `metadata.slug`, when set in the Stripe dashboard, names its page.\n */\nexport const load = async ({ locals }) => {\n const [products, prices] = await Promise.all([\n locals.admin.collection('stripe_products').getFullList<ProductRecord>({ sort: 'name' }),\n locals.admin\n .collection('stripe_prices')\n .getFullList<PriceRecord>({ filter: 'active = true && type = \"one_time\"' })\n ]);\n\n return {\n products: products.filter(isActive).flatMap((product) => {\n const price =\n prices.find((candidate) => candidate.id === product.default_price) ??\n prices.find((candidate) => candidate.product === product.id);\n if (!price?.currency) return [];\n const name = product.name ?? product.id;\n return [\n {\n id: product.id,\n slug: slugOf(product),\n name,\n description: product.description ?? null,\n image: firstImage(product),\n price: {\n price: price.id,\n name,\n unitAmount: price.unit_amount ?? 0,\n currency: price.currency\n }\n }\n ];\n })\n };\n};\n", ic = "<script lang=\"ts\">\n import AddToCart from '#lib/components/cart/add-to-cart.svelte';\n import { formatAmount } from '#lib/cart.svelte.js';\n\n let { data } = $props();\n<\/script>\n\n<section data-role=\"content\">\n <h1 class=\"mb-6 text-2xl font-semibold\">Shop</h1>\n\n {#if data.products.length === 0}\n <p class=\"text-muted-foreground\">\n Nothing for sale yet. Products and prices come from your Stripe dashboard; the catalog syncs\n every ten minutes.\n </p>\n {:else}\n <ul class=\"grid gap-6 sm:grid-cols-2 lg:grid-cols-3\">\n {#each data.products as product (product.id)}\n <li class=\"flex flex-col gap-3 rounded-lg border p-4\">\n <a href=\"/shop/{product.slug}\" class=\"flex flex-col gap-3\">\n {#if product.image}\n <img src={product.image} alt=\"\" class=\"aspect-square w-full rounded object-cover\" />\n {/if}\n <div>\n <h2 class=\"font-medium\">{product.name}</h2>\n <p class=\"text-muted-foreground text-sm\">\n {formatAmount(product.price.unitAmount, product.price.currency)}\n </p>\n </div>\n </a>\n <AddToCart price={product.price} class=\"mt-auto\" />\n </li>\n {/each}\n </ul>\n {/if}\n</section>\n", ac = "import { error } from '@sveltejs/kit';\n\n/** The fields of the synced catalog this page reads. */\ninterface ProductRecord {\n id: string;\n name?: string;\n /** Stripe's boolean, stored by the sync in a text field. */\n active?: unknown;\n default_price?: string;\n description?: string;\n images?: unknown;\n}\n\ninterface PriceRecord {\n id: string;\n nickname?: string;\n unit_amount?: number;\n currency?: string;\n}\n\nconst isActive = (product: ProductRecord) => String(product.active) !== 'false';\n\nconst images = (product: ProductRecord): string[] =>\n Array.isArray(product.images)\n ? product.images.filter((image): image is string => typeof image === 'string')\n : [];\n\n/**\n * One product and its active one-time prices (sizes, say), by its\n * `metadata.slug` from the Stripe dashboard or its id.\n */\nexport const load = async ({ locals, params }) => {\n const products = locals.admin.collection('stripe_products');\n const product = await products\n .getFirstListItem<ProductRecord>(\n locals.admin.filter('metadata.slug = {:slug}', { slug: params.product })\n )\n .catch(() => products.getOne<ProductRecord>(params.product))\n .catch(() => null);\n if (!product || !isActive(product)) error(404, 'Not found');\n\n const prices = await locals.admin.collection('stripe_prices').getFullList<PriceRecord>({\n filter: locals.admin.filter('product = {:product} && active = true && type = \"one_time\"', {\n product: product.id\n }),\n sort: 'unit_amount'\n });\n const priced = prices.filter((price): price is PriceRecord & { currency: string } =>\n Boolean(price.currency)\n );\n if (priced.length === 0) error(404, 'Not found');\n\n const name = product.name ?? product.id;\n return {\n product: {\n id: product.id,\n name,\n description: product.description ?? null,\n images: images(product),\n defaultPrice: product.default_price ?? null\n },\n prices: priced.map((price) => ({\n price: price.id,\n name,\n // What the dashboard calls this price, when there is more than one.\n nickname: price.nickname ?? null,\n unitAmount: price.unit_amount ?? 0,\n currency: price.currency\n }))\n };\n};\n", oc = "<script lang=\"ts\">\n import { Button } from '#lib/components/ui/button/index.js';\n import AddToCart from '#lib/components/cart/add-to-cart.svelte';\n import { formatAmount } from '#lib/cart.svelte.js';\n\n let { data } = $props();\n\n // The default price first, or the cheapest; with one price there is nothing to pick.\n let selectedId = $state(\n data.prices.find((price) => price.price === data.product.defaultPrice)?.price ??\n data.prices[0].price\n );\n const selected = $derived(data.prices.find((price) => price.price === selectedId) ?? data.prices[0]);\n<\/script>\n\n<section data-role=\"content\" class=\"grid gap-8 md:grid-cols-2\">\n <div class=\"flex flex-col gap-3\">\n {#each data.product.images.slice(0, 1) as image (image)}\n <img src={image} alt=\"\" class=\"aspect-square w-full rounded-lg object-cover\" />\n {/each}\n </div>\n\n <div class=\"flex flex-col gap-6\">\n <div>\n <p class=\"text-muted-foreground mb-2 text-sm\"><a href=\"/shop\">Shop</a></p>\n <h1 class=\"text-2xl font-semibold\">{data.product.name}</h1>\n <p class=\"mt-2 text-lg\">{formatAmount(selected.unitAmount, selected.currency)}</p>\n </div>\n\n {#if data.product.description}\n <p class=\"text-muted-foreground\">{data.product.description}</p>\n {/if}\n\n {#if data.prices.length > 1}\n <div class=\"flex flex-wrap gap-2\" role=\"radiogroup\" aria-label=\"Option\">\n {#each data.prices as price (price.price)}\n <Button\n variant={price.price === selectedId ? 'default' : 'outline'}\n size=\"sm\"\n role=\"radio\"\n aria-checked={price.price === selectedId}\n onclick={() => (selectedId = price.price)}\n >\n {price.nickname ?? formatAmount(price.unitAmount, price.currency)}\n </Button>\n {/each}\n </div>\n {/if}\n\n <AddToCart price={selected} size=\"lg\" />\n </div>\n</section>\n", sc = "/**\n * What the shop sells. Edit this list: it is the catalog the `/shop` pages\n * read. Prices are in `site.currency` (src/lib/site.ts), written as you would\n * write them (`4.5`); leave one out to quote in the chat instead.\n */\nexport interface Product {\n /** Your own id for the item (a slug or SKU); it is the item's URL and its cart line. */\n id: string;\n name: string;\n description?: string;\n price?: number;\n /** A URL, or a path under `static/`. */\n image?: string;\n}\n\nexport const catalog: Product[] = [\n {\n id: 'concha',\n name: 'Concha',\n description: 'A sweet bun with a vanilla or cocoa shell.',\n price: 12\n },\n {\n id: 'birthday-cake',\n name: 'Birthday cake',\n description: 'Say the size and the day you need it in the chat.'\n }\n];\n\nexport const product = (id: string): Product | undefined => catalog.find((item) => item.id === id);\n", cc = "<script lang=\"ts\">\n import AddToCart from '#lib/components/cart/add-to-cart.svelte';\n import { catalog } from '#lib/catalog.js';\n import { formatPrice } from '#lib/currency.svelte.js';\n<\/script>\n\n<section data-role=\"content\">\n <h1 class=\"mb-6 text-2xl font-semibold\">Shop</h1>\n\n <ul class=\"grid gap-6 sm:grid-cols-2 lg:grid-cols-3\">\n {#each catalog as item (item.id)}\n <li class=\"flex flex-col gap-3 rounded-lg border p-4\">\n <a href=\"/shop/{item.id}\" class=\"flex flex-col gap-3\">\n {#if item.image}\n <img src={item.image} alt=\"\" class=\"aspect-square w-full rounded object-cover\" />\n {/if}\n <div>\n <h2 class=\"font-medium\">{item.name}</h2>\n <p class=\"text-muted-foreground text-sm\">\n {#if item.price !== undefined}\n {formatPrice(item.price)}\n {:else}\n Price on request\n {/if}\n </p>\n </div>\n </a>\n <AddToCart id={item.id} name={item.name} price={item.price} class=\"mt-auto\" />\n </li>\n {/each}\n </ul>\n</section>\n", lc = "<script lang=\"ts\">\n import AddToCart from '#lib/components/cart/add-to-cart.svelte';\n import { formatPrice } from '#lib/currency.svelte.js';\n\n let { data } = $props();\n<\/script>\n\n<section data-role=\"content\" class=\"grid gap-8 md:grid-cols-2\">\n <div>\n {#if data.item.image}\n <img src={data.item.image} alt=\"\" class=\"aspect-square w-full rounded-lg object-cover\" />\n {/if}\n </div>\n\n <div class=\"flex flex-col gap-6\">\n <div>\n <p class=\"text-muted-foreground mb-2 text-sm\"><a href=\"/shop\">Shop</a></p>\n <h1 class=\"text-2xl font-semibold\">{data.item.name}</h1>\n <p class=\"mt-2 text-lg\">\n {#if data.item.price !== undefined}\n {formatPrice(data.item.price)}\n {:else}\n <span class=\"text-muted-foreground\">We'll confirm the price in WhatsApp.</span>\n {/if}\n </p>\n </div>\n\n {#if data.item.description}\n <p class=\"text-muted-foreground\">{data.item.description}</p>\n {/if}\n\n <AddToCart id={data.item.id} name={data.item.name} price={data.item.price} size=\"lg\" />\n </div>\n</section>\n", uc = "import { error } from '@sveltejs/kit';\nimport { catalog, product } from '#lib/catalog.js';\n\n// The catalog is a module, so every item's page can be prerendered.\nexport const entries = () => catalog.map(({ id }) => ({ id }));\n\nexport const load = ({ params }) => {\n const item = product(params.id);\n if (!item) error(404, 'Not found');\n return { item };\n};\n", dc = "<script lang=\"ts\">\n import { CmsCollection, CmsText, type CollectionItem } from '@velastack/cms';\n import AddToCart from '#lib/components/cart/add-to-cart.svelte';\n import { formatPrice } from '#lib/currency.svelte.js';\n\n // The catalog is edited in place: open the page with `?edit` to add items.\n // It lives in the root layout scope, so the product pages read the same\n // list. Prices are in `site.currency` (src/lib/site.ts); an item without\n // one is quoted in the chat.\n const sample: Partial<CollectionItem>[] = [\n {\n id: 'concha',\n title: 'Concha',\n summary: 'A sweet bun with a vanilla or cocoa shell.',\n price: { amount: 12, currency: '', period: '', prefix: '' }\n },\n {\n id: 'birthday-cake',\n title: 'Birthday cake',\n summary: 'Say the size and the day you need it in the chat.'\n }\n ];\n<\/script>\n\n<section data-role=\"content\">\n <h1 class=\"mb-6 text-2xl font-semibold\"><CmsText name=\"title\" fallback=\"Shop\" /></h1>\n\n <CmsCollection name=\"catalog\" scope=\"root\" fallback={sample}>\n {#snippet children(items)}\n <ul class=\"grid gap-6 sm:grid-cols-2 lg:grid-cols-3\">\n {#each items as item (item.id)}\n <li class=\"flex flex-col gap-3 rounded-lg border p-4\">\n <a href=\"/shop/{item.id}\" class=\"flex flex-col gap-3\">\n {#if item.image?.url}\n <img src={item.image.url} alt={item.image.alt ?? ''} class=\"aspect-square w-full rounded object-cover\" />\n {/if}\n <div>\n <h2 class=\"font-medium\">{item.title}</h2>\n <p class=\"text-muted-foreground text-sm\">\n {#if item.price.amount !== null}\n {formatPrice(item.price.amount)}\n {:else}\n Price on request\n {/if}\n </p>\n </div>\n </a>\n <AddToCart\n id={item.id}\n name={item.title}\n price={item.price.amount ?? undefined}\n class=\"mt-auto\"\n />\n </li>\n {/each}\n </ul>\n {/snippet}\n </CmsCollection>\n</section>\n", fc = "<script lang=\"ts\">\n import { page } from '$app/state';\n import { CmsCollection } from '@velastack/cms';\n import AddToCart from '#lib/components/cart/add-to-cart.svelte';\n import { formatPrice } from '#lib/currency.svelte.js';\n<\/script>\n\n<!-- The same catalog the shop page edits, from the root layout scope. -->\n<CmsCollection name=\"catalog\" scope=\"root\">\n {#snippet children(items)}\n {@const item = items.find((candidate) => candidate.id === page.params.id)}\n <section data-role=\"content\" class=\"grid gap-8 md:grid-cols-2\">\n {#if item}\n <div>\n {#if item.image?.url}\n <img src={item.image.url} alt={item.image.alt ?? ''} class=\"aspect-square w-full rounded-lg object-cover\" />\n {/if}\n </div>\n\n <div class=\"flex flex-col gap-6\">\n <div>\n <p class=\"text-muted-foreground mb-2 text-sm\"><a href=\"/shop\">Shop</a></p>\n <h1 class=\"text-2xl font-semibold\">{item.title}</h1>\n <p class=\"mt-2 text-lg\">\n {#if item.price.amount !== null}\n {formatPrice(item.price.amount)}\n {:else}\n <span class=\"text-muted-foreground\">We'll confirm the price in WhatsApp.</span>\n {/if}\n </p>\n </div>\n\n {#if item.summary}\n <p class=\"text-muted-foreground\">{item.summary}</p>\n {/if}\n\n <AddToCart id={item.id} name={item.title} price={item.price.amount ?? undefined} size=\"lg\" />\n </div>\n {:else}\n <div>\n <h1 class=\"text-2xl font-semibold\">Not found</h1>\n <p class=\"text-muted-foreground mt-2\"><a href=\"/shop\">Back to the shop</a></p>\n </div>\n {/if}\n </section>\n {/snippet}\n</CmsCollection>\n", pc = "// The items are CMS content, so there is no list of ids to prerender from;\n// the page renders from the catalog the shop page holds.\nexport const prerender = false;\n", mc = [
4131
+ }, $s = "<script lang=\"ts\">\n import { formatMoney } from '#lib/cart.svelte.js';\n\n let { data } = $props();\n<\/script>\n\n<section data-role=\"content\">\n <h1 class=\"mb-6 text-2xl font-semibold\">Shop</h1>\n\n {#if data.products.length === 0}\n <p class=\"text-muted-foreground\">\n Nothing for sale yet. Products live in Shopify admin; publish them to the Headless channel\n the Storefront token belongs to.\n </p>\n {:else}\n <ul class=\"grid gap-6 sm:grid-cols-2 lg:grid-cols-3\">\n {#each data.products as product (product.id)}\n <li class=\"rounded-lg border p-4\">\n <a href=\"/shop/{product.handle}\" class=\"flex flex-col gap-3\">\n {#if product.featuredImage}\n <img\n src={product.featuredImage.url}\n alt={product.featuredImage.altText ?? ''}\n class=\"aspect-square w-full rounded object-cover\"\n />\n {/if}\n <div>\n <h2 class=\"font-medium\">{product.title}</h2>\n <p class=\"text-muted-foreground text-sm\">\n From {formatMoney(product.priceRange.minVariantPrice)}\n </p>\n </div>\n </a>\n </li>\n {/each}\n </ul>\n {/if}\n</section>\n", ec = "import { error } from '@sveltejs/kit';\nimport { currencyFrom } from '#lib/currency.svelte.js';\nimport { marketCountry, storefront } from '#lib/shopify.js';\n\nexport interface Money {\n amount: string;\n currencyCode: string;\n}\n\nexport interface ProductCard {\n id: string;\n handle: string;\n title: string;\n featuredImage: { url: string; altText: string | null } | null;\n priceRange: { minVariantPrice: Money };\n}\n\nconst PRODUCTS = `#graphql\n query Products($country: CountryCode) @inContext(country: $country) {\n products(first: 100, sortKey: TITLE) {\n nodes {\n id\n handle\n title\n featuredImage {\n url\n altText\n }\n priceRange {\n minVariantPrice {\n amount\n currencyCode\n }\n }\n }\n }\n }\n`;\n\n// The Storefront token is public, so the same load runs on the server and in\n// the browser. It is not prerendered: the catalog changes without a rebuild.\nexport const prerender = false;\n\nexport const load = async ({ parent }) => {\n // Priced by Shopify in the visitor's currency, when the store has a market in it.\n const country = await marketCountry(currencyFrom(await parent()));\n const { data, errors } = await storefront().request(PRODUCTS, { variables: { country } });\n if (errors) error(502, errors.message ?? 'Shopify did not answer.');\n return { products: (data?.products.nodes ?? []) as ProductCard[] };\n};\n", tc = "<script lang=\"ts\">\n import { Button } from '#lib/components/ui/button/index.js';\n import AddToCart from '#lib/components/cart/add-to-cart.svelte';\n import { formatMoney } from '#lib/cart.svelte.js';\n\n let { data } = $props();\n\n // One value per option, starting from the first variant that can be bought.\n // The variant for sale is the one whose options all match.\n const first = data.product.variants.nodes.find((v) => v.availableForSale) ??\n data.product.variants.nodes[0];\n let chosen = $state<Record<string, string>>(\n Object.fromEntries(first.selectedOptions.map((option) => [option.name, option.value]))\n );\n const variant = $derived(\n data.product.variants.nodes.find((candidate) =>\n candidate.selectedOptions.every((option) => chosen[option.name] === option.value)\n )\n );\n // A product with one variant has a single option Shopify calls \"Title\".\n const options = $derived(\n data.product.options.filter((option) => option.optionValues.length > 1)\n );\n<\/script>\n\n<section data-role=\"content\" class=\"grid gap-8 md:grid-cols-2\">\n <div class=\"flex flex-col gap-3\">\n {#each data.product.images.nodes.slice(0, 1) as image (image.url)}\n <img src={image.url} alt={image.altText ?? ''} class=\"aspect-square w-full rounded-lg object-cover\" />\n {/each}\n </div>\n\n <div class=\"flex flex-col gap-6\">\n <div>\n <p class=\"text-muted-foreground mb-2 text-sm\"><a href=\"/shop\">Shop</a></p>\n <h1 class=\"text-2xl font-semibold\">{data.product.title}</h1>\n {#if variant}\n <p class=\"mt-2 text-lg\">{formatMoney(variant.price)}</p>\n {/if}\n </div>\n\n {#each options as option (option.name)}\n <div class=\"flex flex-col gap-2\">\n <p class=\"text-sm font-medium\">{option.name}</p>\n <div class=\"flex flex-wrap gap-2\" role=\"radiogroup\" aria-label={option.name}>\n {#each option.optionValues as value (value.name)}\n <Button\n variant={chosen[option.name] === value.name ? 'default' : 'outline'}\n size=\"sm\"\n role=\"radio\"\n aria-checked={chosen[option.name] === value.name}\n onclick={() => (chosen = { ...chosen, [option.name]: value.name })}\n >\n {value.name}\n </Button>\n {/each}\n </div>\n </div>\n {/each}\n\n {#if variant}\n <AddToCart\n merchandiseId={variant.id}\n size=\"lg\"\n disabled={!variant.availableForSale}\n label={variant.availableForSale ? 'Add to cart' : 'Sold out'}\n />\n {:else}\n <p class=\"text-muted-foreground text-sm\">That combination is not available.</p>\n {/if}\n\n {#if data.product.descriptionHtml}\n <!-- The description as written in Shopify admin, which is HTML. -->\n <div class=\"prose prose-sm text-muted-foreground\">{@html data.product.descriptionHtml}</div>\n {/if}\n </div>\n</section>\n", nc = "import { error } from '@sveltejs/kit';\nimport { currencyFrom } from '#lib/currency.svelte.js';\nimport { marketCountry, storefront } from '#lib/shopify.js';\nimport type { Money } from '../+page.js';\n\nexport interface Variant {\n id: string;\n title: string;\n availableForSale: boolean;\n price: Money;\n selectedOptions: { name: string; value: string }[];\n}\n\nexport interface Product {\n id: string;\n title: string;\n descriptionHtml: string;\n images: { nodes: { url: string; altText: string | null }[] };\n options: { name: string; optionValues: { name: string }[] }[];\n variants: { nodes: Variant[] };\n}\n\nconst PRODUCT = `#graphql\n query Product($handle: String!, $country: CountryCode) @inContext(country: $country) {\n product(handle: $handle) {\n id\n title\n descriptionHtml\n images(first: 4) {\n nodes {\n url\n altText\n }\n }\n options {\n name\n optionValues {\n name\n }\n }\n variants(first: 100) {\n nodes {\n id\n title\n availableForSale\n price {\n amount\n currencyCode\n }\n selectedOptions {\n name\n value\n }\n }\n }\n }\n }\n`;\n\nexport const prerender = false;\n\nexport const load = async ({ params, parent }) => {\n const country = await marketCountry(currencyFrom(await parent()));\n const { data, errors } = await storefront().request(PRODUCT, {\n variables: { handle: params.handle, country }\n });\n if (errors) error(502, errors.message ?? 'Shopify did not answer.');\n const product = data?.product as Product | null | undefined;\n if (!product) error(404, 'Not found');\n return { product };\n};\n", rc = "import { priceOptions } from '#lib/cart.svelte.js';\n\n/** The fields of the synced catalog this page reads. */\ninterface ProductRecord {\n id: string;\n name?: string;\n /** Stripe's boolean, stored by the sync in a text field. */\n active?: unknown;\n default_price?: string;\n description?: string;\n images?: unknown;\n metadata?: unknown;\n}\n\ninterface PriceRecord {\n id: string;\n product?: string;\n unit_amount?: number;\n currency?: string;\n currency_options?: unknown;\n}\n\nconst isActive = (product: ProductRecord) => String(product.active) !== 'false';\n\nconst slugOf = (product: ProductRecord): string => {\n const metadata = product.metadata as { slug?: unknown } | null | undefined;\n return typeof metadata?.slug === 'string' && metadata.slug ? metadata.slug : product.id;\n};\n\nconst firstImage = (product: ProductRecord): string | null =>\n Array.isArray(product.images) && typeof product.images[0] === 'string'\n ? product.images[0]\n : null;\n\n/**\n * The catalog, as the sync copied it from Stripe: every active product with\n * its default one-time price (or its first active one). A product's\n * `metadata.slug`, when set in the Stripe dashboard, names its page.\n */\nexport const load = async ({ locals }) => {\n const [products, prices] = await Promise.all([\n locals.admin.collection('stripe_products').getFullList<ProductRecord>({ sort: 'name' }),\n locals.admin\n .collection('stripe_prices')\n .getFullList<PriceRecord>({ filter: 'active = true && type = \"one_time\"' })\n ]);\n\n return {\n products: products.filter(isActive).flatMap((product) => {\n const price =\n prices.find((candidate) => candidate.id === product.default_price) ??\n prices.find((candidate) => candidate.product === product.id);\n if (!price?.currency) return [];\n const name = product.name ?? product.id;\n return [\n {\n id: product.id,\n slug: slugOf(product),\n name,\n description: product.description ?? null,\n image: firstImage(product),\n price: {\n price: price.id,\n name,\n unitAmount: price.unit_amount ?? 0,\n currency: price.currency,\n options: priceOptions(price.currency_options)\n }\n }\n ];\n })\n };\n};\n", ic = "<script lang=\"ts\">\n import AddToCart from '#lib/components/cart/add-to-cart.svelte';\n import { formatAmount } from '#lib/cart.svelte.js';\n\n let { data } = $props();\n<\/script>\n\n<section data-role=\"content\">\n <h1 class=\"mb-6 text-2xl font-semibold\">Shop</h1>\n\n {#if data.products.length === 0}\n <p class=\"text-muted-foreground\">\n Nothing for sale yet. Products and prices come from your Stripe dashboard; the catalog syncs\n every ten minutes.\n </p>\n {:else}\n <ul class=\"grid gap-6 sm:grid-cols-2 lg:grid-cols-3\">\n {#each data.products as product (product.id)}\n <li class=\"flex flex-col gap-3 rounded-lg border p-4\">\n <a href=\"/shop/{product.slug}\" class=\"flex flex-col gap-3\">\n {#if product.image}\n <img src={product.image} alt=\"\" class=\"aspect-square w-full rounded object-cover\" />\n {/if}\n <div>\n <h2 class=\"font-medium\">{product.name}</h2>\n <p class=\"text-muted-foreground text-sm\">\n {formatAmount(\n product.price.unitAmount,\n product.price.currency,\n product.price.options\n )}\n </p>\n </div>\n </a>\n <AddToCart price={product.price} class=\"mt-auto\" />\n </li>\n {/each}\n </ul>\n {/if}\n</section>\n", ac = "import { error } from '@sveltejs/kit';\nimport { priceOptions } from '#lib/cart.svelte.js';\n\n/** The fields of the synced catalog this page reads. */\ninterface ProductRecord {\n id: string;\n name?: string;\n /** Stripe's boolean, stored by the sync in a text field. */\n active?: unknown;\n default_price?: string;\n description?: string;\n images?: unknown;\n}\n\ninterface PriceRecord {\n id: string;\n nickname?: string;\n unit_amount?: number;\n currency?: string;\n currency_options?: unknown;\n}\n\nconst isActive = (product: ProductRecord) => String(product.active) !== 'false';\n\nconst images = (product: ProductRecord): string[] =>\n Array.isArray(product.images)\n ? product.images.filter((image): image is string => typeof image === 'string')\n : [];\n\n/**\n * One product and its active one-time prices (sizes, say), by its\n * `metadata.slug` from the Stripe dashboard or its id.\n */\nexport const load = async ({ locals, params }) => {\n const products = locals.admin.collection('stripe_products');\n const product = await products\n .getFirstListItem<ProductRecord>(\n locals.admin.filter('metadata.slug = {:slug}', { slug: params.product })\n )\n .catch(() => products.getOne<ProductRecord>(params.product))\n .catch(() => null);\n if (!product || !isActive(product)) error(404, 'Not found');\n\n const prices = await locals.admin.collection('stripe_prices').getFullList<PriceRecord>({\n filter: locals.admin.filter('product = {:product} && active = true && type = \"one_time\"', {\n product: product.id\n }),\n sort: 'unit_amount'\n });\n const priced = prices.filter((price): price is PriceRecord & { currency: string } =>\n Boolean(price.currency)\n );\n if (priced.length === 0) error(404, 'Not found');\n\n const name = product.name ?? product.id;\n return {\n product: {\n id: product.id,\n name,\n description: product.description ?? null,\n images: images(product),\n defaultPrice: product.default_price ?? null\n },\n prices: priced.map((price) => ({\n price: price.id,\n name,\n // What the dashboard calls this price, when there is more than one.\n nickname: price.nickname ?? null,\n unitAmount: price.unit_amount ?? 0,\n currency: price.currency,\n options: priceOptions(price.currency_options)\n }))\n };\n};\n", oc = "<script lang=\"ts\">\n import { Button } from '#lib/components/ui/button/index.js';\n import AddToCart from '#lib/components/cart/add-to-cart.svelte';\n import { formatAmount } from '#lib/cart.svelte.js';\n\n let { data } = $props();\n\n // The default price first, or the cheapest; with one price there is nothing to pick.\n let selectedId = $state(\n data.prices.find((price) => price.price === data.product.defaultPrice)?.price ??\n data.prices[0].price\n );\n const selected = $derived(data.prices.find((price) => price.price === selectedId) ?? data.prices[0]);\n<\/script>\n\n<section data-role=\"content\" class=\"grid gap-8 md:grid-cols-2\">\n <div class=\"flex flex-col gap-3\">\n {#each data.product.images.slice(0, 1) as image (image)}\n <img src={image} alt=\"\" class=\"aspect-square w-full rounded-lg object-cover\" />\n {/each}\n </div>\n\n <div class=\"flex flex-col gap-6\">\n <div>\n <p class=\"text-muted-foreground mb-2 text-sm\"><a href=\"/shop\">Shop</a></p>\n <h1 class=\"text-2xl font-semibold\">{data.product.name}</h1>\n <p class=\"mt-2 text-lg\">\n {formatAmount(selected.unitAmount, selected.currency, selected.options)}\n </p>\n </div>\n\n {#if data.product.description}\n <p class=\"text-muted-foreground\">{data.product.description}</p>\n {/if}\n\n {#if data.prices.length > 1}\n <div class=\"flex flex-wrap gap-2\" role=\"radiogroup\" aria-label=\"Option\">\n {#each data.prices as price (price.price)}\n <Button\n variant={price.price === selectedId ? 'default' : 'outline'}\n size=\"sm\"\n role=\"radio\"\n aria-checked={price.price === selectedId}\n onclick={() => (selectedId = price.price)}\n >\n {price.nickname ?? formatAmount(price.unitAmount, price.currency, price.options)}\n </Button>\n {/each}\n </div>\n {/if}\n\n <AddToCart price={selected} size=\"lg\" />\n </div>\n</section>\n", sc = "/**\n * What the shop sells. Edit this list: it is the catalog the `/shop` pages\n * read. Prices are in `site.currency` (src/lib/site.ts), written as you would\n * write them (`4.5`); leave one out to quote in the chat instead.\n */\nexport interface Product {\n /** Your own id for the item (a slug or SKU); it is the item's URL and its cart line. */\n id: string;\n name: string;\n description?: string;\n price?: number;\n /** A URL, or a path under `static/`. */\n image?: string;\n}\n\nexport const catalog: Product[] = [\n {\n id: 'concha',\n name: 'Concha',\n description: 'A sweet bun with a vanilla or cocoa shell.',\n price: 12\n },\n {\n id: 'birthday-cake',\n name: 'Birthday cake',\n description: 'Say the size and the day you need it in the chat.'\n }\n];\n\nexport const product = (id: string): Product | undefined => catalog.find((item) => item.id === id);\n", cc = "<script lang=\"ts\">\n import AddToCart from '#lib/components/cart/add-to-cart.svelte';\n import { catalog } from '#lib/catalog.js';\n import { formatPrice } from '#lib/currency.svelte.js';\n<\/script>\n\n<section data-role=\"content\">\n <h1 class=\"mb-6 text-2xl font-semibold\">Shop</h1>\n\n <ul class=\"grid gap-6 sm:grid-cols-2 lg:grid-cols-3\">\n {#each catalog as item (item.id)}\n <li class=\"flex flex-col gap-3 rounded-lg border p-4\">\n <a href=\"/shop/{item.id}\" class=\"flex flex-col gap-3\">\n {#if item.image}\n <img src={item.image} alt=\"\" class=\"aspect-square w-full rounded object-cover\" />\n {/if}\n <div>\n <h2 class=\"font-medium\">{item.name}</h2>\n <p class=\"text-muted-foreground text-sm\">\n {#if item.price !== undefined}\n {formatPrice(item.price)}\n {:else}\n Price on request\n {/if}\n </p>\n </div>\n </a>\n <AddToCart id={item.id} name={item.name} price={item.price} class=\"mt-auto\" />\n </li>\n {/each}\n </ul>\n</section>\n", lc = "<script lang=\"ts\">\n import AddToCart from '#lib/components/cart/add-to-cart.svelte';\n import { formatPrice } from '#lib/currency.svelte.js';\n\n let { data } = $props();\n<\/script>\n\n<section data-role=\"content\" class=\"grid gap-8 md:grid-cols-2\">\n <div>\n {#if data.item.image}\n <img src={data.item.image} alt=\"\" class=\"aspect-square w-full rounded-lg object-cover\" />\n {/if}\n </div>\n\n <div class=\"flex flex-col gap-6\">\n <div>\n <p class=\"text-muted-foreground mb-2 text-sm\"><a href=\"/shop\">Shop</a></p>\n <h1 class=\"text-2xl font-semibold\">{data.item.name}</h1>\n <p class=\"mt-2 text-lg\">\n {#if data.item.price !== undefined}\n {formatPrice(data.item.price)}\n {:else}\n <span class=\"text-muted-foreground\">We'll confirm the price in WhatsApp.</span>\n {/if}\n </p>\n </div>\n\n {#if data.item.description}\n <p class=\"text-muted-foreground\">{data.item.description}</p>\n {/if}\n\n <AddToCart id={data.item.id} name={data.item.name} price={data.item.price} size=\"lg\" />\n </div>\n</section>\n", uc = "import { error } from '@sveltejs/kit';\nimport { catalog, product } from '#lib/catalog.js';\n\n// The catalog is a module, so every item's page can be prerendered.\nexport const entries = () => catalog.map(({ id }) => ({ id }));\n\nexport const load = ({ params }) => {\n const item = product(params.id);\n if (!item) error(404, 'Not found');\n return { item };\n};\n", dc = "<script lang=\"ts\">\n import { CmsCollection, CmsText, type CollectionItem } from '@velastack/cms';\n import AddToCart from '#lib/components/cart/add-to-cart.svelte';\n import { formatPrice } from '#lib/currency.svelte.js';\n\n // The catalog is edited in place: open the page with `?edit` to add items.\n // It lives in the root layout scope, so the product pages read the same\n // list. Prices are in `site.currency` (src/lib/site.ts); an item without\n // one is quoted in the chat.\n const sample: Partial<CollectionItem>[] = [\n {\n id: 'concha',\n title: 'Concha',\n summary: 'A sweet bun with a vanilla or cocoa shell.',\n price: { amount: 12, currency: '', period: '', prefix: '' }\n },\n {\n id: 'birthday-cake',\n title: 'Birthday cake',\n summary: 'Say the size and the day you need it in the chat.'\n }\n ];\n<\/script>\n\n<section data-role=\"content\">\n <h1 class=\"mb-6 text-2xl font-semibold\"><CmsText name=\"title\" fallback=\"Shop\" /></h1>\n\n <CmsCollection name=\"catalog\" scope=\"root\" fallback={sample}>\n {#snippet children(items)}\n <ul class=\"grid gap-6 sm:grid-cols-2 lg:grid-cols-3\">\n {#each items as item (item.id)}\n <li class=\"flex flex-col gap-3 rounded-lg border p-4\">\n <a href=\"/shop/{item.id}\" class=\"flex flex-col gap-3\">\n {#if item.image?.url}\n <img src={item.image.url} alt={item.image.alt ?? ''} class=\"aspect-square w-full rounded object-cover\" />\n {/if}\n <div>\n <h2 class=\"font-medium\">{item.title}</h2>\n <p class=\"text-muted-foreground text-sm\">\n {#if item.price.amount !== null}\n {formatPrice(item.price.amount)}\n {:else}\n Price on request\n {/if}\n </p>\n </div>\n </a>\n <AddToCart\n id={item.id}\n name={item.title}\n price={item.price.amount ?? undefined}\n class=\"mt-auto\"\n />\n </li>\n {/each}\n </ul>\n {/snippet}\n </CmsCollection>\n</section>\n", fc = "<script lang=\"ts\">\n import { page } from '$app/state';\n import { CmsCollection } from '@velastack/cms';\n import AddToCart from '#lib/components/cart/add-to-cart.svelte';\n import { formatPrice } from '#lib/currency.svelte.js';\n<\/script>\n\n<!-- The same catalog the shop page edits, from the root layout scope. -->\n<CmsCollection name=\"catalog\" scope=\"root\">\n {#snippet children(items)}\n {@const item = items.find((candidate) => candidate.id === page.params.id)}\n <section data-role=\"content\" class=\"grid gap-8 md:grid-cols-2\">\n {#if item}\n <div>\n {#if item.image?.url}\n <img src={item.image.url} alt={item.image.alt ?? ''} class=\"aspect-square w-full rounded-lg object-cover\" />\n {/if}\n </div>\n\n <div class=\"flex flex-col gap-6\">\n <div>\n <p class=\"text-muted-foreground mb-2 text-sm\"><a href=\"/shop\">Shop</a></p>\n <h1 class=\"text-2xl font-semibold\">{item.title}</h1>\n <p class=\"mt-2 text-lg\">\n {#if item.price.amount !== null}\n {formatPrice(item.price.amount)}\n {:else}\n <span class=\"text-muted-foreground\">We'll confirm the price in WhatsApp.</span>\n {/if}\n </p>\n </div>\n\n {#if item.summary}\n <p class=\"text-muted-foreground\">{item.summary}</p>\n {/if}\n\n <AddToCart id={item.id} name={item.title} price={item.price.amount ?? undefined} size=\"lg\" />\n </div>\n {:else}\n <div>\n <h1 class=\"text-2xl font-semibold\">Not found</h1>\n <p class=\"text-muted-foreground mt-2\"><a href=\"/shop\">Back to the shop</a></p>\n </div>\n {/if}\n </section>\n {/snippet}\n</CmsCollection>\n", pc = "// The items are CMS content, so there is no list of ids to prerender from;\n// the page renders from the catalog the shop page holds.\nexport const prerender = false;\n", mc = [
4132
4132
  {
4133
4133
  id: "stripe",
4134
4134
  label: "Stripe",
@@ -4190,7 +4190,7 @@ async function yc(e) {
4190
4190
  }
4191
4191
  //#endregion
4192
4192
  //#region src/patterns/generate/shop/index.ts
4193
- var bc = "generate-shop", xc = "1.1.0", Sc = "src/patterns/generate/shop", Cc = "/generate/shop";
4193
+ var bc = "generate-shop", xc = "1.2.0", Sc = "src/patterns/generate/shop", Cc = "/generate/shop";
4194
4194
  async function wc(e) {
4195
4195
  let t = await yc(e);
4196
4196
  if (e.env !== "runtime") return D(t, e);
@@ -5623,7 +5623,7 @@ async function vd(e) {
5623
5623
  let n = await pd(e);
5624
5624
  return D(C([t, n]), e);
5625
5625
  }
5626
- let { generate: n } = await import("./chunks/generate.runtime-BOl3LpPB.js"), { keepMissing: r } = await import("./chunks/modify-file-B4uJzOEj.js").then((e) => e.i), i = await n(e), { writeResult: a } = await import("./chunks/write-result-DcqMefuP.js").then((e) => e.l);
5626
+ let { generate: n } = await import("./chunks/generate.runtime-BnqS_Zq8.js"), { keepMissing: r } = await import("./chunks/modify-file-B4uJzOEj.js").then((e) => e.i), i = await n(e), { writeResult: a } = await import("./chunks/write-result-DcqMefuP.js").then((e) => e.l);
5627
5627
  return a(await D(C([{
5628
5628
  ...t,
5629
5629
  creates: r(t.creates, e.root)
@@ -6069,7 +6069,7 @@ async function zf(e) {
6069
6069
  i.push({
6070
6070
  path: ".env",
6071
6071
  language: "text",
6072
- content: tr(t).map((e) => e.type === "comment" ? `# ${e.key}` : `${e.key}=${e.value}`).join("\n") + "\n",
6072
+ content: $n(t).map((e) => e.type === "comment" ? `# ${e.key}` : `${e.key}=${e.value}`).join("\n") + "\n",
6073
6073
  status: "success"
6074
6074
  }), i.push({
6075
6075
  path: "src/lib/site.ts",
@@ -6100,13 +6100,13 @@ async function zf(e) {
6100
6100
  }
6101
6101
  //#endregion
6102
6102
  //#region src/patterns/enable/payments/index.ts
6103
- var Bf = "enable-payments", Vf = "2.3.0", Hf = "src/patterns/enable/payments", Uf = "/enable/payments";
6103
+ var Bf = "enable-payments", Vf = "2.4.0", Hf = "src/patterns/enable/payments", Uf = "/enable/payments";
6104
6104
  async function Wf(e) {
6105
6105
  if (e.env === "preview") {
6106
- let t = await $n(e), n = await zf(e);
6106
+ let t = await tr(e), n = await zf(e);
6107
6107
  return D(C([t, n]), e);
6108
6108
  }
6109
- let { generate: t, hasVitest: n } = await import("./chunks/generate.runtime-Dt3Edp8-.js"), r = await $n(e, { unitTests: n(e.root) }), i = await t(e), { writeResult: a } = await import("./chunks/write-result-DcqMefuP.js").then((e) => e.l);
6109
+ let { generate: t, hasVitest: n } = await import("./chunks/generate.runtime-X-uAteso.js"), r = await tr(e, { unitTests: n(e.root) }), i = await t(e), { writeResult: a } = await import("./chunks/write-result-DcqMefuP.js").then((e) => e.l);
6110
6110
  return a(await D(C([r, i]), e), e);
6111
6111
  }
6112
6112
  var Gf = {
@@ -6164,7 +6164,7 @@ var Gf = {
6164
6164
  baseline: "velastack",
6165
6165
  providers: er,
6166
6166
  generate: Wf
6167
- }, Kf = "<script lang=\"ts\">\n import { onMount } from 'svelte';\n import ShoppingCartIcon from '@lucide/svelte/icons/shopping-cart';\n import { Badge } from '#lib/components/ui/badge/index.js';\n import { Button } from '#lib/components/ui/button/index.js';\n import { cart } from '#lib/cart.svelte.js';\n import CartSheet from './cart-sheet.svelte';\n\n // The cart lives in the browser, so the server renders it empty and it\n // fills in here.\n onMount(() => cart.load());\n<\/script>\n\n<Button\n variant=\"ghost\"\n size=\"icon\"\n class=\"relative\"\n aria-label=\"Cart, {cart.count} items\"\n onclick={() => (cart.open = true)}\n>\n <ShoppingCartIcon />\n {#if cart.count > 0}\n <Badge class=\"absolute -top-1 -right-1 h-5 min-w-5 rounded-full px-1 tabular-nums\">\n {cart.count}\n </Badge>\n {/if}\n</Button>\n\n<CartSheet />\n", qf = "import { browser } from '$app/env';\nimport { money } from '#lib/currency.svelte.js';\nimport { storefront } from '#lib/shopify.js';\n\nexport interface Money {\n amount: string;\n currencyCode: string;\n}\n\nexport interface CartLine {\n id: string;\n quantity: number;\n attributes: { key: string; value: string }[];\n cost: { totalAmount: Money };\n merchandise: {\n id: string;\n title: string;\n image: { url: string; altText: string | null } | null;\n price: Money;\n product: { title: string; handle: string };\n };\n}\n\ninterface ShopifyCart {\n id: string;\n checkoutUrl: string;\n totalQuantity: number;\n cost: { subtotalAmount: Money };\n lines: { nodes: CartLine[] };\n}\n\ninterface CartPayload {\n cart: ShopifyCart | null;\n userErrors: { message: string }[];\n}\n\nconst CART_FRAGMENT = `#graphql\n fragment CartFields on Cart {\n id\n checkoutUrl\n totalQuantity\n cost {\n subtotalAmount {\n amount\n currencyCode\n }\n }\n lines(first: 100) {\n nodes {\n id\n quantity\n attributes {\n key\n value\n }\n cost {\n totalAmount {\n amount\n currencyCode\n }\n }\n merchandise {\n ... on ProductVariant {\n id\n title\n image {\n url\n altText\n }\n price {\n amount\n currencyCode\n }\n product {\n title\n handle\n }\n }\n }\n }\n }\n }\n`;\n\nconst CART_QUERY = `#graphql\n query Cart($id: ID!) {\n cart(id: $id) {\n ...CartFields\n }\n }\n ${CART_FRAGMENT}\n`;\n\nconst CART_CREATE = `#graphql\n mutation CartCreate($lines: [CartLineInput!]!) {\n cartCreate(input: { lines: $lines }) {\n cart {\n ...CartFields\n }\n userErrors {\n message\n }\n }\n }\n ${CART_FRAGMENT}\n`;\n\nconst CART_LINES_ADD = `#graphql\n mutation CartLinesAdd($cartId: ID!, $lines: [CartLineInput!]!) {\n cartLinesAdd(cartId: $cartId, lines: $lines) {\n cart {\n ...CartFields\n }\n userErrors {\n message\n }\n }\n }\n ${CART_FRAGMENT}\n`;\n\nconst CART_LINES_UPDATE = `#graphql\n mutation CartLinesUpdate($cartId: ID!, $lines: [CartLineUpdateInput!]!) {\n cartLinesUpdate(cartId: $cartId, lines: $lines) {\n cart {\n ...CartFields\n }\n userErrors {\n message\n }\n }\n }\n ${CART_FRAGMENT}\n`;\n\nconst CART_LINES_REMOVE = `#graphql\n mutation CartLinesRemove($cartId: ID!, $lineIds: [ID!]!) {\n cartLinesRemove(cartId: $cartId, lineIds: $lineIds) {\n cart {\n ...CartFields\n }\n userErrors {\n message\n }\n }\n }\n ${CART_FRAGMENT}\n`;\n\nconst CART_ID_KEY = 'shopify_cart_id';\n\n/**\n * The cart lives at Shopify; the browser keeps only its id. Each change sends\n * one Storefront API request and shows the cart Shopify sends back.\n */\nclass Cart {\n lines = $state<CartLine[]>([]);\n subtotal = $state<Money | null>(null);\n checkoutUrl = $state<string | null>(null);\n count = $state(0);\n /** Whether the cart sheet is open. */\n open = $state(false);\n /** True while a request is in flight; the cart's controls wait for it. */\n pending = $state(false);\n error = $state<string | null>(null);\n\n #id: string | null = null;\n #loaded = false;\n\n /** Fetches the saved cart, once, in the browser. */\n async load() {\n if (!browser || this.#loaded) return;\n this.#loaded = true;\n const id = readCartId();\n if (!id) return;\n\n this.pending = true;\n try {\n const { data, errors } = await storefront().request(CART_QUERY, { variables: { id } });\n if (errors) throw new Error(errors.message);\n // A cart that expired or was checked out comes back as null.\n if (data?.cart) this.#show(data.cart);\n else this.clear();\n } catch (error) {\n console.error('Could not load the Shopify cart:', error);\n } finally {\n this.pending = false;\n }\n }\n\n async add(merchandiseId: string, quantity = 1, attributes?: { key: string; value: string }[]) {\n await this.load();\n const lines = [{ merchandiseId, quantity, attributes }];\n if (this.#id) {\n await this.#mutate(CART_LINES_ADD, 'cartLinesAdd', { cartId: this.#id, lines });\n } else {\n await this.#mutate(CART_CREATE, 'cartCreate', { lines });\n }\n }\n\n /** A quantity of 0 removes the line. */\n async setQuantity(lineId: string, quantity: number) {\n if (quantity <= 0) return this.remove(lineId);\n await this.#mutate(CART_LINES_UPDATE, 'cartLinesUpdate', {\n cartId: this.#id,\n lines: [{ id: lineId, quantity }]\n });\n }\n\n async remove(lineId: string) {\n await this.#mutate(CART_LINES_REMOVE, 'cartLinesRemove', {\n cartId: this.#id,\n lineIds: [lineId]\n });\n }\n\n clear() {\n this.#id = null;\n this.lines = [];\n this.subtotal = null;\n this.checkoutUrl = null;\n this.count = 0;\n try {\n localStorage.removeItem(CART_ID_KEY);\n } catch {\n // Blocked storage: nothing was saved either.\n }\n }\n\n async #mutate(operation: string, field: string, variables: Record<string, unknown>) {\n this.pending = true;\n this.error = null;\n try {\n const { data, errors } = await storefront().request(operation, { variables });\n if (errors) throw new Error(errors.message);\n const payload: CartPayload | undefined = data?.[field];\n if (!payload) throw new Error(`No ${field} in the response`);\n if (payload.userErrors.length > 0) this.error = payload.userErrors[0].message;\n if (payload.cart) this.#show(payload.cart);\n } catch (error) {\n console.error('Shopify cart request failed:', error);\n this.error = 'The cart could not be updated. Try again.';\n } finally {\n this.pending = false;\n }\n }\n\n #show(cart: ShopifyCart) {\n this.#id = cart.id;\n this.lines = cart.lines.nodes;\n this.subtotal = cart.cost.subtotalAmount;\n this.checkoutUrl = cart.checkoutUrl;\n this.count = cart.totalQuantity;\n try {\n localStorage.setItem(CART_ID_KEY, cart.id);\n } catch {\n // The cart still works for this visit.\n }\n }\n}\n\nfunction readCartId(): string | null {\n try {\n return localStorage.getItem(CART_ID_KEY);\n } catch {\n return null;\n }\n}\n\nexport const cart = new Cart();\n\n/** Shopify's money, as it priced it, formatted for the page's language in the business's country. */\nexport function formatMoney({ amount, currencyCode }: Money): string {\n return money(Number(amount), currencyCode);\n}\n", Jf = "<script lang=\"ts\">\n import { Button } from '#lib/components/ui/button/index.js';\n import type { ButtonProps } from '#lib/components/ui/button/index.js';\n import { cart } from '#lib/cart.svelte.js';\n\n interface Props {\n /** The product variant: `gid://shopify/ProductVariant/...`. */\n merchandiseId: string;\n quantity?: number;\n /** Line item properties Shopify keeps with the line, such as an engraving. */\n attributes?: { key: string; value: string }[];\n label?: string;\n }\n\n let {\n merchandiseId,\n quantity = 1,\n attributes,\n label = 'Add to cart',\n disabled,\n ...rest\n }: Props & ButtonProps = $props();\n\n let added = $state(false);\n\n async function add() {\n await cart.add(merchandiseId, quantity, attributes);\n if (cart.error) return;\n added = true;\n cart.open = true;\n setTimeout(() => (added = false), 1500);\n }\n<\/script>\n\n<Button onclick={add} disabled={disabled || cart.pending} {...rest}>\n {added ? 'Added' : label}\n</Button>\n", Yf = "<script lang=\"ts\">\n import MinusIcon from '@lucide/svelte/icons/minus';\n import PlusIcon from '@lucide/svelte/icons/plus';\n import XIcon from '@lucide/svelte/icons/x';\n import * as Sheet from '#lib/components/ui/sheet/index.js';\n import { Button } from '#lib/components/ui/button/index.js';\n import { Separator } from '#lib/components/ui/separator/index.js';\n import { cart, formatMoney } from '#lib/cart.svelte.js';\n<\/script>\n\n<Sheet.Root bind:open={cart.open}>\n <Sheet.Content side=\"right\" class=\"flex flex-col\">\n <Sheet.Header>\n <Sheet.Title>Cart</Sheet.Title>\n </Sheet.Header>\n\n <div class=\"flex flex-1 flex-col gap-4 overflow-y-auto px-4 pb-4\">\n {#if cart.error}\n <p class=\"text-destructive text-sm\">{cart.error}</p>\n {/if}\n\n {#if cart.lines.length === 0}\n <p class=\"text-muted-foreground text-sm\">Your cart is empty.</p>\n {:else}\n <ul class=\"divide-y\">\n {#each cart.lines as line (line.id)}\n <li class=\"flex items-center gap-3 py-3\">\n {#if line.merchandise.image}\n <img\n src={line.merchandise.image.url}\n alt={line.merchandise.image.altText ?? line.merchandise.product.title}\n class=\"size-12 rounded object-cover\"\n />\n {/if}\n <div class=\"min-w-0 flex-1\">\n <p class=\"truncate text-sm font-medium\">{line.merchandise.product.title}</p>\n {#if line.merchandise.title !== 'Default Title'}\n <p class=\"text-muted-foreground truncate text-xs\">{line.merchandise.title}</p>\n {/if}\n <p class=\"text-muted-foreground text-sm\">\n {formatMoney(line.cost.totalAmount)}\n </p>\n </div>\n <div class=\"flex items-center gap-1\">\n <Button\n variant=\"outline\"\n size=\"icon\"\n class=\"size-7\"\n aria-label=\"One fewer {line.merchandise.product.title}\"\n disabled={cart.pending}\n onclick={() => cart.setQuantity(line.id, line.quantity - 1)}\n >\n <MinusIcon />\n </Button>\n <span class=\"w-6 text-center text-sm tabular-nums\">{line.quantity}</span>\n <Button\n variant=\"outline\"\n size=\"icon\"\n class=\"size-7\"\n aria-label=\"One more {line.merchandise.product.title}\"\n disabled={cart.pending}\n onclick={() => cart.setQuantity(line.id, line.quantity + 1)}\n >\n <PlusIcon />\n </Button>\n </div>\n <Button\n variant=\"ghost\"\n size=\"icon\"\n class=\"size-7\"\n aria-label=\"Remove {line.merchandise.product.title}\"\n disabled={cart.pending}\n onclick={() => cart.remove(line.id)}\n >\n <XIcon />\n </Button>\n </li>\n {/each}\n </ul>\n\n <Separator />\n\n {#if cart.subtotal}\n <div class=\"flex justify-between text-sm font-medium\">\n <span>Subtotal</span>\n <span>{formatMoney(cart.subtotal)}</span>\n </div>\n {/if}\n\n <!-- Shopify's checkout takes it from here. -->\n <Button href={cart.checkoutUrl ?? undefined} class=\"w-full\" disabled={cart.pending}>\n Check out\n </Button>\n {/if}\n </div>\n </Sheet.Content>\n</Sheet.Root>\n", Xf = "import { browser } from '$app/env';\nimport { currency } from '#lib/currency.svelte.js';\n\nexport interface CartItem {\n /** The Stripe price (`price_...`). */\n price: string;\n name: string;\n /** Stripe's `unit_amount`: the price in the currency's smallest unit. */\n unitAmount: number;\n currency: string;\n quantity: number;\n}\n\nconst STORAGE_KEY = 'cart';\n\n/**\n * The cart is a list of Stripe prices kept in the browser. Stripe sees it only\n * at checkout, where it prices the session itself, so what is stored here is\n * for display and nothing in it can change what is charged.\n */\nclass Cart {\n items = $state<CartItem[]>([]);\n /** Whether the cart sheet is open. */\n open = $state(false);\n count = $derived(this.items.reduce((total, item) => total + item.quantity, 0));\n subtotal = $derived(\n this.items.reduce((total, item) => total + item.unitAmount * item.quantity, 0)\n );\n /** The cart's currency: Stripe refuses a mixed cart, so the first item's. `null` while empty. */\n currency = $derived<string | null>(this.items[0]?.currency ?? null);\n\n #loaded = false;\n\n /** Reads the saved cart, once, in the browser. */\n load() {\n if (!browser || this.#loaded) return;\n this.#loaded = true;\n try {\n const saved = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? '[]');\n if (Array.isArray(saved)) this.items = saved;\n } catch {\n // Unreadable or blocked storage starts an empty cart.\n }\n }\n\n add(item: Omit<CartItem, 'quantity'>, quantity = 1) {\n this.load();\n const line = this.items.find((line) => line.price === item.price);\n if (line) line.quantity += quantity;\n else this.items.push({ ...item, quantity });\n this.#save();\n }\n\n /** A quantity of 0 removes the item. */\n setQuantity(price: string, quantity: number) {\n if (quantity <= 0) return this.remove(price);\n const line = this.items.find((line) => line.price === price);\n if (!line) return;\n line.quantity = quantity;\n this.#save();\n }\n\n remove(price: string) {\n this.items = this.items.filter((line) => line.price !== price);\n this.#save();\n }\n\n clear() {\n this.items = [];\n this.#save();\n }\n\n #save() {\n try {\n localStorage.setItem(STORAGE_KEY, JSON.stringify($state.snapshot(this.items)));\n } catch {\n // Storage can be full or blocked; the cart still works for this visit.\n }\n }\n}\n\nexport const cart = new Cart();\n\n/**\n * Formats a Stripe amount: Intl knows how many decimals the currency has\n * (none for JPY). Shown the way the visitor reads prices: in the currency they\n * picked, as an estimate, when it isn't the price's own.\n */\nexport function formatAmount(amount: number, code: string): string {\n const digits =\n new Intl.NumberFormat('en', { style: 'currency', currency: code }).resolvedOptions()\n .maximumFractionDigits ?? 2;\n return currency.format(amount / 10 ** digits, code);\n}\n", Zf = "<script lang=\"ts\">\n import { Button } from '#lib/components/ui/button/index.js';\n import type { ButtonProps } from '#lib/components/ui/button/index.js';\n import { cart, type CartItem } from '#lib/cart.svelte.js';\n\n interface Props {\n /** The Stripe price, as the page selling it loaded it. */\n price: Omit<CartItem, 'quantity'>;\n quantity?: number;\n label?: string;\n }\n\n let { price, quantity = 1, label = 'Add to cart', ...rest }: Props & ButtonProps = $props();\n\n let added = $state(false);\n\n function add() {\n cart.add(price, quantity);\n added = true;\n cart.open = true;\n setTimeout(() => (added = false), 1500);\n }\n<\/script>\n\n<Button onclick={add} {...rest}>\n {added ? 'Added' : label}\n</Button>\n", Qf = "<script lang=\"ts\">\n import MinusIcon from '@lucide/svelte/icons/minus';\n import PlusIcon from '@lucide/svelte/icons/plus';\n import XIcon from '@lucide/svelte/icons/x';\n import { Button } from '#lib/components/ui/button/index.js';\n import { Separator } from '#lib/components/ui/separator/index.js';\n import { cart, formatAmount } from '#lib/cart.svelte.js';\n\n let { class: className = '' }: { class?: string } = $props();\n\n // What the checkout action reads: the prices and quantities, nothing the\n // browser could misstate.\n const items = $derived(\n JSON.stringify(cart.items.map(({ price, quantity }) => ({ price, quantity })))\n );\n<\/script>\n\n<div class=\"flex flex-col gap-4 {className}\">\n {#if cart.items.length === 0}\n <p class=\"text-muted-foreground text-sm\">Your cart is empty.</p>\n {:else}\n <ul class=\"divide-y\">\n {#each cart.items as item (item.price)}\n <li class=\"flex items-center gap-3 py-3\">\n <div class=\"min-w-0 flex-1\">\n <p class=\"truncate text-sm font-medium\">{item.name}</p>\n <p class=\"text-muted-foreground text-sm\">\n {formatAmount(item.unitAmount, item.currency)}\n </p>\n </div>\n <div class=\"flex items-center gap-1\">\n <Button\n variant=\"outline\"\n size=\"icon\"\n class=\"size-7\"\n aria-label=\"One fewer {item.name}\"\n onclick={() => cart.setQuantity(item.price, item.quantity - 1)}\n >\n <MinusIcon />\n </Button>\n <span class=\"w-6 text-center text-sm tabular-nums\">{item.quantity}</span>\n <Button\n variant=\"outline\"\n size=\"icon\"\n class=\"size-7\"\n aria-label=\"One more {item.name}\"\n onclick={() => cart.setQuantity(item.price, item.quantity + 1)}\n >\n <PlusIcon />\n </Button>\n </div>\n <Button\n variant=\"ghost\"\n size=\"icon\"\n class=\"size-7\"\n aria-label=\"Remove {item.name}\"\n onclick={() => cart.remove(item.price)}\n >\n <XIcon />\n </Button>\n </li>\n {/each}\n </ul>\n\n <Separator />\n\n {#if cart.currency}\n <div class=\"flex justify-between text-sm font-medium\">\n <span>Subtotal</span>\n <span>{formatAmount(cart.subtotal, cart.currency)}</span>\n </div>\n {/if}\n\n <!-- A plain form post: checkout works before the page has hydrated. -->\n <form method=\"POST\" action=\"/cart?/checkout\">\n <input type=\"hidden\" name=\"items\" value={items} />\n <Button type=\"submit\" class=\"w-full\">Check out</Button>\n </form>\n {/if}\n</div>\n", $f = "<script lang=\"ts\">\n import * as Sheet from '#lib/components/ui/sheet/index.js';\n import CartItems from './cart-items.svelte';\n import { cart } from '#lib/cart.svelte.js';\n<\/script>\n\n<Sheet.Root bind:open={cart.open}>\n <Sheet.Content side=\"right\" class=\"flex flex-col\">\n <Sheet.Header>\n <Sheet.Title>Cart</Sheet.Title>\n </Sheet.Header>\n <CartItems class=\"flex-1 overflow-y-auto px-4 pb-4\" />\n </Sheet.Content>\n</Sheet.Root>\n", ep = "import { fail, redirect } from '@sveltejs/kit';\nimport Stripe from 'stripe';\nimport stripe from '#lib/stripe.js';\n\n/** What the cart posts: prices and quantities. Stripe supplies everything else. */\nfunction readItems(raw: FormDataEntryValue | null): { price: string; quantity: number }[] | null {\n try {\n const items: unknown = JSON.parse(typeof raw === 'string' ? raw : '');\n if (!Array.isArray(items) || items.length === 0 || items.length > 100) return null;\n const valid = items.every(\n (item) =>\n typeof item?.price === 'string' &&\n Number.isInteger(item?.quantity) &&\n item.quantity >= 1 &&\n item.quantity <= 99\n );\n return valid ? items : null;\n } catch {\n return null;\n }\n}\n\nexport const actions = {\n checkout: async ({ request, url }) => {\n const items = readItems((await request.formData()).get('items'));\n if (!items) return fail(400, { message: 'Your cart could not be read.' });\n\n let session: Stripe.Checkout.Session;\n try {\n session = await stripe.checkout.sessions.create({\n mode: 'payment',\n line_items: items,\n allow_promotion_codes: true,\n success_url: `${url.origin}/checkout/success?session_id={CHECKOUT_SESSION_ID}`,\n cancel_url: `${url.origin}/cart`\n });\n } catch (error) {\n // An inactive or recurring price, or mixed currencies: Stripe says which.\n if (error instanceof Stripe.errors.StripeError) {\n return fail(400, { message: error.message });\n }\n throw error;\n }\n\n // SvelteKit 3 redirects off-site only when told to.\n redirect(303, session.url!, { external: true });\n }\n};\n", tp = "<script lang=\"ts\">\n import CartItems from '#lib/components/cart/cart-items.svelte';\n\n let { form } = $props();\n<\/script>\n\n<section data-role=\"content\" class=\"max-w-xl\">\n <h1 class=\"mb-6 text-2xl font-semibold\">Cart</h1>\n {#if form?.message}\n <p class=\"text-destructive mb-4 text-sm\">{form.message}</p>\n {/if}\n <CartItems />\n</section>\n", np = "import { describe, it, expect, beforeAll, type TestContext } from 'vitest';\nimport * as devalue from 'devalue';\nimport type { Match } from '@velastack/kit';\nimport type { RouteId } from './$types';\nimport stripe from '#lib/stripe.js';\nimport type Stripe from 'stripe';\n\ndescribe('POST /cart?/checkout', () => {\n let price: Stripe.Price;\n let inactivePrice: Stripe.Price;\n\n beforeAll(async () => {\n const name = 'Test Product - Cart';\n const found = await stripe.products.search({\n query: `name:\"${name}\" AND metadata[\"test\"]:\"true\"`,\n limit: 1\n });\n const product =\n found.data[0] ?? (await stripe.products.create({ name, metadata: { test: 'true' } }));\n\n const prices = async (active: boolean) =>\n (await stripe.prices.list({ product: product.id, active, limit: 1 })).data[0];\n price =\n (await prices(true)) ??\n (await stripe.prices.create({ product: product.id, unit_amount: 1500, currency: 'usd' }));\n inactivePrice =\n (await prices(false)) ??\n (await stripe.prices.create({\n product: product.id,\n unit_amount: 2500,\n currency: 'usd',\n active: false\n }));\n });\n\n const checkout = (context: TestContext, items: unknown) =>\n context.request\n .post(`${'/cart' satisfies Match<RouteId>}?/checkout`)\n .type('form')\n .send({ items: typeof items === 'string' ? items : JSON.stringify(items) });\n\n it('redirects to a Stripe Checkout Session', async (context) => {\n const response = await checkout(context, [{ price: price.id, quantity: 2 }]);\n expect(response.body.status).toBe(303);\n expect(response.body.location).toMatch(/^https:\\/\\/checkout\\.stripe\\.com\\//);\n });\n\n it('refuses a cart it cannot read', async (context) => {\n for (const items of ['not json', [], [{ price: price.id }], [{ quantity: 1 }]]) {\n const response = await checkout(context, items);\n expect(response.body.status).toBe(400);\n }\n });\n\n it('refuses quantities outside 1 to 99', async (context) => {\n for (const quantity of [0, 100, 1.5]) {\n const response = await checkout(context, [{ price: price.id, quantity }]);\n expect(response.body.status).toBe(400);\n }\n });\n\n it(\"passes on Stripe's reason for a price it won't sell\", async (context) => {\n const response = await checkout(context, [{ price: inactivePrice.id, quantity: 1 }]);\n expect(response.body.status).toBe(400);\n expect(devalue.parse(response.body.data).message).toMatch(/inactive|not active/i);\n });\n});\n", rp = "import { error } from '@sveltejs/kit';\nimport stripe from '#lib/stripe.js';\n\nexport const load = async ({ url }) => {\n const id = url.searchParams.get('session_id');\n if (!id) error(404, 'Not found');\n\n try {\n const session = await stripe.checkout.sessions.retrieve(id);\n return {\n amountTotal: session.amount_total,\n currency: session.currency,\n paid: session.payment_status === 'paid'\n };\n } catch {\n error(404, 'Not found');\n }\n};\n", ip = "<script lang=\"ts\">\n import { onMount } from 'svelte';\n import { cart, formatAmount } from '#lib/cart.svelte.js';\n\n let { data } = $props();\n\n onMount(() => {\n cart.load();\n if (data.paid) cart.clear();\n });\n<\/script>\n\n<section data-role=\"content\" class=\"max-w-xl\">\n {#if data.paid}\n <h1 class=\"mb-2 text-2xl font-semibold\">Thank you</h1>\n <p class=\"text-muted-foreground\">\n {#if data.amountTotal !== null && data.currency}\n Your payment of {formatAmount(data.amountTotal, data.currency)} went through.\n {:else}\n Your payment went through.\n {/if}\n </p>\n {:else}\n <h1 class=\"mb-2 text-2xl font-semibold\">Payment pending</h1>\n <p class=\"text-muted-foreground\">Your order is placed; the payment has not cleared yet.</p>\n {/if}\n</section>\n", ap = "import { browser } from '$app/env';\nimport { orderSubtotal, type OrderLine } from '@velastack/whatsapp';\nimport { site } from '#lib/site.js';\n\nexport interface CartItem extends OrderLine {\n /** Your own id for the item (a slug or SKU); lines with the same id merge. */\n id: string;\n}\n\n/** An order sent to WhatsApp, kept until the customer says they're done. */\nexport interface PlacedOrder {\n ref: string;\n /** The chat link, to open it again. */\n href: string;\n}\n\nconst STORAGE_KEY = 'cart';\n\n/**\n * The cart is a list of items kept in the browser. Checkout turns it into a\n * WhatsApp message to the business, where the order is confirmed and paid,\n * so what is stored here is what the customer asked for, not what they pay.\n */\nclass Cart {\n items = $state<CartItem[]>([]);\n /** Whether the cart sheet is open. */\n open = $state(false);\n placed = $state<PlacedOrder | null>(null);\n count = $derived(this.items.reduce((total, item) => total + item.quantity, 0));\n /** In `site.currency`, only when every item has a price; otherwise the business quotes. */\n subtotal = $derived(orderSubtotal(this.items, site.currency));\n\n #loaded = false;\n\n /** Reads the saved cart, once, in the browser. */\n load() {\n if (!browser || this.#loaded) return;\n this.#loaded = true;\n try {\n const saved = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? '{}');\n if (Array.isArray(saved?.items)) this.items = saved.items;\n if (saved?.placed) this.placed = saved.placed;\n } catch {\n // Unreadable or blocked storage starts an empty cart.\n }\n }\n\n add(item: Omit<CartItem, 'quantity'>, quantity = 1) {\n this.load();\n // Adding after an order was sent starts the next one.\n if (this.placed) this.clear();\n const line = this.items.find((line) => line.id === item.id);\n if (line) line.quantity += quantity;\n else this.items.push({ ...item, quantity });\n this.#save();\n }\n\n /** A quantity of 0 removes the item. */\n setQuantity(id: string, quantity: number) {\n if (quantity <= 0) return this.remove(id);\n const line = this.items.find((line) => line.id === id);\n if (!line) return;\n line.quantity = quantity;\n this.#save();\n }\n\n remove(id: string) {\n this.items = this.items.filter((line) => line.id !== id);\n this.#save();\n }\n\n /** Records that the order went to WhatsApp; the sheet shows it until `clear()`. */\n place(order: PlacedOrder) {\n this.placed = order;\n this.#save();\n }\n\n clear() {\n this.items = [];\n this.placed = null;\n this.#save();\n }\n\n #save() {\n try {\n localStorage.setItem(\n STORAGE_KEY,\n JSON.stringify({ items: $state.snapshot(this.items), placed: this.placed })\n );\n } catch {\n // Storage can be full or blocked; the cart still works for this visit.\n }\n }\n}\n\nexport const cart = new Cart();\n", op = "<script lang=\"ts\">\n import { Button } from '#lib/components/ui/button/index.js';\n import type { ButtonProps } from '#lib/components/ui/button/index.js';\n import { cart } from '#lib/cart.svelte.js';\n\n interface Props {\n /** Your own id for the item (a slug or SKU); adding it again raises the quantity. */\n id: string;\n /** What the business will read in the order. */\n name: string;\n /** The unit price in `site.currency`, written as you would (`4.5`). Leave it out to quote in the chat. */\n price?: number;\n quantity?: number;\n label?: string;\n }\n\n let {\n id,\n name,\n price,\n quantity = 1,\n label = 'Add to cart',\n ...rest\n }: Props & ButtonProps = $props();\n\n let added = $state(false);\n\n function add() {\n cart.add({ id, name, price }, quantity);\n added = true;\n cart.open = true;\n setTimeout(() => (added = false), 1500);\n }\n<\/script>\n\n<Button onclick={add} {...rest}>\n {added ? 'Added' : label}\n</Button>\n", sp = "<script lang=\"ts\">\n import MinusIcon from '@lucide/svelte/icons/minus';\n import PlusIcon from '@lucide/svelte/icons/plus';\n import XIcon from '@lucide/svelte/icons/x';\n import { toast } from 'svelte-sonner';\n import { formToken, lineTotal, orderRef } from '@velastack/whatsapp';\n import { Button, buttonVariants } from '#lib/components/ui/button/index.js';\n import { Separator } from '#lib/components/ui/separator/index.js';\n import * as Sheet from '#lib/components/ui/sheet/index.js';\n import CustomerFields from '#lib/components/payments/customer-fields.svelte';\n import { cart } from '#lib/cart.svelte.js';\n import { formatPrice } from '#lib/currency.svelte.js';\n import { ORDER_FORM, placeOrder } from '#lib/order.js';\n import { site } from '#lib/site.js';\n\n // Fetched once, the first time the cart opens: the hosted form refuses a\n // token younger than two seconds, and filling the form in takes longer.\n let token: string | null = null;\n\n $effect(() => {\n if (!cart.open || !ORDER_FORM || token) return;\n formToken(ORDER_FORM).then((value) => (token = value));\n });\n\n function checkout(event: SubmitEvent) {\n event.preventDefault();\n const data = new FormData(event.currentTarget as HTMLFormElement);\n const order = {\n ref: orderRef(),\n name: String(data.get('name') ?? ''),\n phone: String(data.get('phone') ?? ''),\n note: String(data.get('note') ?? '') || undefined,\n currency: site.currency,\n lines: cart.items.map(({ name, quantity, price }) => ({ name, quantity, price })),\n subtotal: cart.subtotal\n };\n const href = placeOrder(order, { token, gotcha: String(data.get('_gotcha') ?? '') });\n if (!href) {\n toast.error('WhatsApp ordering is not set up yet');\n return;\n }\n cart.place({ ref: order.ref, href });\n }\n\n function done() {\n cart.clear();\n cart.open = false;\n }\n<\/script>\n\n<Sheet.Root bind:open={cart.open}>\n <Sheet.Content side=\"right\" class=\"flex flex-col\">\n <Sheet.Header>\n <Sheet.Title>Cart</Sheet.Title>\n </Sheet.Header>\n <div class=\"flex flex-1 flex-col gap-4 overflow-y-auto px-4 pb-4\">\n {#if cart.placed}\n <div class=\"flex flex-col gap-2\">\n <p class=\"font-medium\">Order {cart.placed.ref} opened in WhatsApp</p>\n <p class=\"text-muted-foreground text-sm\">\n Send the message in WhatsApp to place your order. We'll reply there.\n </p>\n </div>\n <a\n href={cart.placed.href}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n class={buttonVariants({ variant: 'outline' })}\n >\n Open WhatsApp again\n </a>\n <Button onclick={done}>Done</Button>\n {:else if cart.items.length === 0}\n <p class=\"text-muted-foreground text-sm\">Your cart is empty.</p>\n {:else}\n <ul class=\"divide-y\">\n {#each cart.items as item (item.id)}\n {@const total = lineTotal(item, site.currency)}\n <li class=\"flex items-center gap-3 py-3\">\n <div class=\"min-w-0 flex-1\">\n <p class=\"truncate text-sm font-medium\">{item.name}</p>\n {#if total !== undefined}\n <p class=\"text-muted-foreground text-sm\">{formatPrice(total)}</p>\n {/if}\n </div>\n <div class=\"flex items-center gap-1\">\n <Button\n variant=\"outline\"\n size=\"icon\"\n class=\"size-7\"\n aria-label=\"One fewer {item.name}\"\n onclick={() => cart.setQuantity(item.id, item.quantity - 1)}\n >\n <MinusIcon />\n </Button>\n <span class=\"w-6 text-center text-sm tabular-nums\">{item.quantity}</span>\n <Button\n variant=\"outline\"\n size=\"icon\"\n class=\"size-7\"\n aria-label=\"One more {item.name}\"\n onclick={() => cart.setQuantity(item.id, item.quantity + 1)}\n >\n <PlusIcon />\n </Button>\n </div>\n <Button\n variant=\"ghost\"\n size=\"icon\"\n class=\"size-7\"\n aria-label=\"Remove {item.name}\"\n onclick={() => cart.remove(item.id)}\n >\n <XIcon />\n </Button>\n </li>\n {/each}\n </ul>\n\n <Separator />\n\n {#if cart.subtotal !== undefined}\n <div class=\"flex justify-between text-sm font-medium\">\n <span>Subtotal</span>\n <span>{formatPrice(cart.subtotal)}</span>\n </div>\n {:else}\n <p class=\"text-muted-foreground text-sm\">We'll confirm the total in WhatsApp.</p>\n {/if}\n\n <form class=\"flex flex-col gap-4\" onsubmit={checkout}>\n <CustomerFields />\n <Button type=\"submit\" class=\"w-full\">Order on WhatsApp</Button>\n </form>\n {/if}\n </div>\n </Sheet.Content>\n</Sheet.Root>\n", cp = "import { fail, redirect } from '@sveltejs/kit';\nimport Stripe from 'stripe';\nimport stripe from '#lib/stripe.js';\nimport { getStripeCustomerId } from '#lib/server/stripe-customer.js';\n\n/** What the cart posts: prices and quantities. Stripe supplies everything else. */\nfunction readItems(raw: FormDataEntryValue | null): { price: string; quantity: number }[] | null {\n try {\n const items: unknown = JSON.parse(typeof raw === 'string' ? raw : '');\n if (!Array.isArray(items) || items.length === 0 || items.length > 100) return null;\n const valid = items.every(\n (item) =>\n typeof item?.price === 'string' &&\n Number.isInteger(item?.quantity) &&\n item.quantity >= 1 &&\n item.quantity <= 99\n );\n return valid ? items : null;\n } catch {\n return null;\n }\n}\n\nexport const actions = {\n checkout: async ({ request, url, locals }) => {\n const items = readItems((await request.formData()).get('items'));\n if (!items) return fail(400, { message: 'Your cart could not be read.' });\n\n // A signed-in buyer checks out as their Stripe customer, so their saved\n // cards are offered and the payment shows up on their billing page. If\n // the customer isn't linked yet, they check out as a guest.\n const user = locals.pb.authStore.record;\n const customer = user\n ? await getStripeCustomerId(locals.admin, user).catch(() => undefined)\n : undefined;\n\n let session: Stripe.Checkout.Session;\n try {\n session = await stripe.checkout.sessions.create({\n mode: 'payment',\n customer,\n line_items: items,\n allow_promotion_codes: true,\n success_url: `${url.origin}/checkout/success?session_id={CHECKOUT_SESSION_ID}`,\n cancel_url: `${url.origin}/cart`\n });\n } catch (error) {\n // An inactive or recurring price, or mixed currencies: Stripe says which.\n if (error instanceof Stripe.errors.StripeError) {\n return fail(400, { message: error.message });\n }\n throw error;\n }\n\n // SvelteKit 3 redirects off-site only when told to.\n redirect(303, session.url!, { external: true });\n }\n};\n", lp = [
6167
+ }, Kf = "<script lang=\"ts\">\n import { onMount } from 'svelte';\n import ShoppingCartIcon from '@lucide/svelte/icons/shopping-cart';\n import { Badge } from '#lib/components/ui/badge/index.js';\n import { Button } from '#lib/components/ui/button/index.js';\n import { cart } from '#lib/cart.svelte.js';\n import CartSheet from './cart-sheet.svelte';\n\n // The cart lives in the browser, so the server renders it empty and it\n // fills in here.\n onMount(() => cart.load());\n<\/script>\n\n<Button\n variant=\"ghost\"\n size=\"icon\"\n class=\"relative\"\n aria-label=\"Cart, {cart.count} items\"\n onclick={() => (cart.open = true)}\n>\n <ShoppingCartIcon />\n {#if cart.count > 0}\n <Badge class=\"absolute -top-1 -right-1 h-5 min-w-5 rounded-full px-1 tabular-nums\">\n {cart.count}\n </Badge>\n {/if}\n</Button>\n\n<CartSheet />\n", qf = "import { browser } from '$app/env';\nimport { currency, money } from '#lib/currency.svelte.js';\nimport { marketCountry, storefront } from '#lib/shopify.js';\n\nexport interface Money {\n amount: string;\n currencyCode: string;\n}\n\nexport interface CartLine {\n id: string;\n quantity: number;\n attributes: { key: string; value: string }[];\n cost: { totalAmount: Money };\n merchandise: {\n id: string;\n title: string;\n image: { url: string; altText: string | null } | null;\n price: Money;\n product: { title: string; handle: string };\n };\n}\n\ninterface ShopifyCart {\n id: string;\n checkoutUrl: string;\n totalQuantity: number;\n cost: { subtotalAmount: Money };\n lines: { nodes: CartLine[] };\n}\n\ninterface CartPayload {\n cart: ShopifyCart | null;\n userErrors: { message: string }[];\n}\n\nconst CART_FRAGMENT = `#graphql\n fragment CartFields on Cart {\n id\n checkoutUrl\n totalQuantity\n cost {\n subtotalAmount {\n amount\n currencyCode\n }\n }\n lines(first: 100) {\n nodes {\n id\n quantity\n attributes {\n key\n value\n }\n cost {\n totalAmount {\n amount\n currencyCode\n }\n }\n merchandise {\n ... on ProductVariant {\n id\n title\n image {\n url\n altText\n }\n price {\n amount\n currencyCode\n }\n product {\n title\n handle\n }\n }\n }\n }\n }\n }\n`;\n\nconst CART_QUERY = `#graphql\n query Cart($id: ID!, $country: CountryCode) @inContext(country: $country) {\n cart(id: $id) {\n ...CartFields\n }\n }\n ${CART_FRAGMENT}\n`;\n\nconst CART_CREATE = `#graphql\n mutation CartCreate($lines: [CartLineInput!]!, $country: CountryCode) @inContext(country: $country) {\n cartCreate(input: { lines: $lines, buyerIdentity: { countryCode: $country } }) {\n cart {\n ...CartFields\n }\n userErrors {\n message\n }\n }\n }\n ${CART_FRAGMENT}\n`;\n\nconst CART_LINES_ADD = `#graphql\n mutation CartLinesAdd($cartId: ID!, $lines: [CartLineInput!]!, $country: CountryCode)\n @inContext(country: $country) {\n cartLinesAdd(cartId: $cartId, lines: $lines) {\n cart {\n ...CartFields\n }\n userErrors {\n message\n }\n }\n }\n ${CART_FRAGMENT}\n`;\n\nconst CART_LINES_UPDATE = `#graphql\n mutation CartLinesUpdate($cartId: ID!, $lines: [CartLineUpdateInput!]!, $country: CountryCode)\n @inContext(country: $country) {\n cartLinesUpdate(cartId: $cartId, lines: $lines) {\n cart {\n ...CartFields\n }\n userErrors {\n message\n }\n }\n }\n ${CART_FRAGMENT}\n`;\n\nconst CART_LINES_REMOVE = `#graphql\n mutation CartLinesRemove($cartId: ID!, $lineIds: [ID!]!, $country: CountryCode)\n @inContext(country: $country) {\n cartLinesRemove(cartId: $cartId, lineIds: $lineIds) {\n cart {\n ...CartFields\n }\n userErrors {\n message\n }\n }\n }\n ${CART_FRAGMENT}\n`;\n\nconst CART_BUYER_IDENTITY_UPDATE = `#graphql\n mutation CartBuyerIdentityUpdate($cartId: ID!, $country: CountryCode)\n @inContext(country: $country) {\n cartBuyerIdentityUpdate(cartId: $cartId, buyerIdentity: { countryCode: $country }) {\n cart {\n ...CartFields\n }\n userErrors {\n message\n }\n }\n }\n ${CART_FRAGMENT}\n`;\n\nconst CART_ID_KEY = 'shopify_cart_id';\n\n/**\n * The cart lives at Shopify; the browser keeps only its id. Each change sends\n * one Storefront API request and shows the cart Shopify sends back.\n */\nclass Cart {\n lines = $state<CartLine[]>([]);\n subtotal = $state<Money | null>(null);\n checkoutUrl = $state<string | null>(null);\n count = $state(0);\n /** Whether the cart sheet is open. */\n open = $state(false);\n /** True while a request is in flight; the cart's controls wait for it. */\n pending = $state(false);\n error = $state<string | null>(null);\n\n #id: string | null = null;\n #loaded = false;\n /** The market the cart is priced in: the one for the visitor's currency, else the store's default. */\n #country: string | null = null;\n\n /** Fetches the saved cart, once, in the browser. */\n async load() {\n if (!browser || this.#loaded) return;\n this.#loaded = true;\n const id = readCartId();\n if (!id) return;\n\n this.pending = true;\n try {\n this.#country = await marketCountry(currency.current);\n const { data, errors } = await storefront().request(CART_QUERY, {\n variables: { id, country: this.#country }\n });\n if (errors) throw new Error(errors.message);\n // A cart that expired or was checked out comes back as null.\n if (data?.cart) this.#show(data.cart);\n else this.clear();\n } catch (error) {\n console.error('Could not load the Shopify cart:', error);\n } finally {\n this.pending = false;\n }\n }\n\n /**\n * Prices the cart in the market for `code`, the currency the visitor now\n * reads prices in, when the store has one. Shopify reprices the lines and\n * the checkout; nothing is estimated.\n */\n async market(code: string) {\n const country = await marketCountry(code);\n if (country === this.#country) return;\n this.#country = country;\n if (this.#id) {\n await this.#mutate(CART_BUYER_IDENTITY_UPDATE, 'cartBuyerIdentityUpdate', {\n cartId: this.#id\n });\n }\n }\n\n async add(merchandiseId: string, quantity = 1, attributes?: { key: string; value: string }[]) {\n await this.load();\n // A new cart starts in the visitor's market; a saved one was loaded in it.\n if (!this.#id) this.#country = await marketCountry(currency.current);\n const lines = [{ merchandiseId, quantity, attributes }];\n if (this.#id) {\n await this.#mutate(CART_LINES_ADD, 'cartLinesAdd', { cartId: this.#id, lines });\n } else {\n await this.#mutate(CART_CREATE, 'cartCreate', { lines });\n }\n }\n\n /** A quantity of 0 removes the line. */\n async setQuantity(lineId: string, quantity: number) {\n if (quantity <= 0) return this.remove(lineId);\n await this.#mutate(CART_LINES_UPDATE, 'cartLinesUpdate', {\n cartId: this.#id,\n lines: [{ id: lineId, quantity }]\n });\n }\n\n async remove(lineId: string) {\n await this.#mutate(CART_LINES_REMOVE, 'cartLinesRemove', {\n cartId: this.#id,\n lineIds: [lineId]\n });\n }\n\n clear() {\n this.#id = null;\n this.lines = [];\n this.subtotal = null;\n this.checkoutUrl = null;\n this.count = 0;\n try {\n localStorage.removeItem(CART_ID_KEY);\n } catch {\n // Blocked storage: nothing was saved either.\n }\n }\n\n async #mutate(operation: string, field: string, variables: Record<string, unknown>) {\n this.pending = true;\n this.error = null;\n try {\n const { data, errors } = await storefront().request(operation, {\n variables: { ...variables, country: this.#country }\n });\n if (errors) throw new Error(errors.message);\n const payload: CartPayload | undefined = data?.[field];\n if (!payload) throw new Error(`No ${field} in the response`);\n if (payload.userErrors.length > 0) this.error = payload.userErrors[0].message;\n if (payload.cart) this.#show(payload.cart);\n } catch (error) {\n console.error('Shopify cart request failed:', error);\n this.error = 'The cart could not be updated. Try again.';\n } finally {\n this.pending = false;\n }\n }\n\n #show(cart: ShopifyCart) {\n this.#id = cart.id;\n this.lines = cart.lines.nodes;\n this.subtotal = cart.cost.subtotalAmount;\n this.checkoutUrl = cart.checkoutUrl;\n this.count = cart.totalQuantity;\n try {\n localStorage.setItem(CART_ID_KEY, cart.id);\n } catch {\n // The cart still works for this visit.\n }\n }\n}\n\nfunction readCartId(): string | null {\n try {\n return localStorage.getItem(CART_ID_KEY);\n } catch {\n return null;\n }\n}\n\nexport const cart = new Cart();\n\n/** Shopify's money, as it priced it, formatted for the page's language in the business's country. */\nexport function formatMoney({ amount, currencyCode }: Money): string {\n return money(Number(amount), currencyCode);\n}\n", Jf = "<script lang=\"ts\">\n import { Button } from '#lib/components/ui/button/index.js';\n import type { ButtonProps } from '#lib/components/ui/button/index.js';\n import { cart } from '#lib/cart.svelte.js';\n\n interface Props {\n /** The product variant: `gid://shopify/ProductVariant/...`. */\n merchandiseId: string;\n quantity?: number;\n /** Line item properties Shopify keeps with the line, such as an engraving. */\n attributes?: { key: string; value: string }[];\n label?: string;\n }\n\n let {\n merchandiseId,\n quantity = 1,\n attributes,\n label = 'Add to cart',\n disabled,\n ...rest\n }: Props & ButtonProps = $props();\n\n let added = $state(false);\n\n async function add() {\n await cart.add(merchandiseId, quantity, attributes);\n if (cart.error) return;\n added = true;\n cart.open = true;\n setTimeout(() => (added = false), 1500);\n }\n<\/script>\n\n<Button onclick={add} disabled={disabled || cart.pending} {...rest}>\n {added ? 'Added' : label}\n</Button>\n", Yf = "<script lang=\"ts\">\n import MinusIcon from '@lucide/svelte/icons/minus';\n import PlusIcon from '@lucide/svelte/icons/plus';\n import XIcon from '@lucide/svelte/icons/x';\n import * as Sheet from '#lib/components/ui/sheet/index.js';\n import { Button } from '#lib/components/ui/button/index.js';\n import { Separator } from '#lib/components/ui/separator/index.js';\n import { cart, formatMoney } from '#lib/cart.svelte.js';\n import { currency } from '#lib/currency.svelte.js';\n\n // A cart is priced in the market for the currency the visitor reads prices in.\n $effect(() => {\n void cart.market(currency.current);\n });\n<\/script>\n\n<Sheet.Root bind:open={cart.open}>\n <Sheet.Content side=\"right\" class=\"flex flex-col\">\n <Sheet.Header>\n <Sheet.Title>Cart</Sheet.Title>\n </Sheet.Header>\n\n <div class=\"flex flex-1 flex-col gap-4 overflow-y-auto px-4 pb-4\">\n {#if cart.error}\n <p class=\"text-destructive text-sm\">{cart.error}</p>\n {/if}\n\n {#if cart.lines.length === 0}\n <p class=\"text-muted-foreground text-sm\">Your cart is empty.</p>\n {:else}\n <ul class=\"divide-y\">\n {#each cart.lines as line (line.id)}\n <li class=\"flex items-center gap-3 py-3\">\n {#if line.merchandise.image}\n <img\n src={line.merchandise.image.url}\n alt={line.merchandise.image.altText ?? line.merchandise.product.title}\n class=\"size-12 rounded object-cover\"\n />\n {/if}\n <div class=\"min-w-0 flex-1\">\n <p class=\"truncate text-sm font-medium\">{line.merchandise.product.title}</p>\n {#if line.merchandise.title !== 'Default Title'}\n <p class=\"text-muted-foreground truncate text-xs\">{line.merchandise.title}</p>\n {/if}\n <p class=\"text-muted-foreground text-sm\">\n {formatMoney(line.cost.totalAmount)}\n </p>\n </div>\n <div class=\"flex items-center gap-1\">\n <Button\n variant=\"outline\"\n size=\"icon\"\n class=\"size-7\"\n aria-label=\"One fewer {line.merchandise.product.title}\"\n disabled={cart.pending}\n onclick={() => cart.setQuantity(line.id, line.quantity - 1)}\n >\n <MinusIcon />\n </Button>\n <span class=\"w-6 text-center text-sm tabular-nums\">{line.quantity}</span>\n <Button\n variant=\"outline\"\n size=\"icon\"\n class=\"size-7\"\n aria-label=\"One more {line.merchandise.product.title}\"\n disabled={cart.pending}\n onclick={() => cart.setQuantity(line.id, line.quantity + 1)}\n >\n <PlusIcon />\n </Button>\n </div>\n <Button\n variant=\"ghost\"\n size=\"icon\"\n class=\"size-7\"\n aria-label=\"Remove {line.merchandise.product.title}\"\n disabled={cart.pending}\n onclick={() => cart.remove(line.id)}\n >\n <XIcon />\n </Button>\n </li>\n {/each}\n </ul>\n\n <Separator />\n\n {#if cart.subtotal}\n <div class=\"flex justify-between text-sm font-medium\">\n <span>Subtotal</span>\n <span>{formatMoney(cart.subtotal)}</span>\n </div>\n {/if}\n\n <!-- Shopify's checkout takes it from here. -->\n <Button href={cart.checkoutUrl ?? undefined} class=\"w-full\" disabled={cart.pending}>\n Check out\n </Button>\n {/if}\n </div>\n </Sheet.Content>\n</Sheet.Root>\n", Xf = "import { browser } from '$app/env';\nimport { currency, money } from '#lib/currency.svelte.js';\n\nexport interface CartItem {\n /** The Stripe price (`price_...`). */\n price: string;\n name: string;\n /** Stripe's `unit_amount`: the price in the currency's smallest unit. */\n unitAmount: number;\n currency: string;\n /**\n * Fixed amounts in other currencies, from the price's `currency_options` in\n * the dashboard, by upper-cased code: `{ EUR: 1800 }`. A visitor reading\n * prices in one of them sees and pays that amount, not an estimate.\n */\n options?: Record<string, number>;\n quantity: number;\n}\n\nconst STORAGE_KEY = 'cart';\n\n/**\n * The cart is a list of Stripe prices kept in the browser. Stripe sees it only\n * at checkout, where it prices the session itself, so what is stored here is\n * for display and nothing in it can change what is charged.\n */\nclass Cart {\n items = $state<CartItem[]>([]);\n /** Whether the cart sheet is open. */\n open = $state(false);\n count = $derived(this.items.reduce((total, item) => total + item.quantity, 0));\n subtotal = $derived(\n this.items.reduce((total, item) => total + item.unitAmount * item.quantity, 0)\n );\n /** The cart's currency: Stripe refuses a mixed cart, so the first item's. `null` while empty. */\n currency = $derived<string | null>(this.items[0]?.currency ?? null);\n /** Fixed subtotals in the currencies every item has a dashboard amount in. */\n options = $derived.by<Record<string, number>>(() => {\n const [first, ...rest] = this.items;\n if (!first?.options) return {};\n const totals: Record<string, number> = {};\n for (const code of Object.keys(first.options)) {\n if (rest.every((item) => item.options?.[code] !== undefined)) {\n totals[code] = this.items.reduce(\n (total, item) => total + item.options![code] * item.quantity,\n 0\n );\n }\n }\n return totals;\n });\n\n #loaded = false;\n\n /** Reads the saved cart, once, in the browser. */\n load() {\n if (!browser || this.#loaded) return;\n this.#loaded = true;\n try {\n const saved = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? '[]');\n if (Array.isArray(saved)) this.items = saved;\n } catch {\n // Unreadable or blocked storage starts an empty cart.\n }\n }\n\n add(item: Omit<CartItem, 'quantity'>, quantity = 1) {\n this.load();\n const line = this.items.find((line) => line.price === item.price);\n if (line) line.quantity += quantity;\n else this.items.push({ ...item, quantity });\n this.#save();\n }\n\n /** A quantity of 0 removes the item. */\n setQuantity(price: string, quantity: number) {\n if (quantity <= 0) return this.remove(price);\n const line = this.items.find((line) => line.price === price);\n if (!line) return;\n line.quantity = quantity;\n this.#save();\n }\n\n remove(price: string) {\n this.items = this.items.filter((line) => line.price !== price);\n this.#save();\n }\n\n clear() {\n this.items = [];\n this.#save();\n }\n\n #save() {\n try {\n localStorage.setItem(STORAGE_KEY, JSON.stringify($state.snapshot(this.items)));\n } catch {\n // Storage can be full or blocked; the cart still works for this visit.\n }\n }\n}\n\nexport const cart = new Cart();\n\n/** Stripe amounts are in the currency's smallest unit; Intl knows how many digits that is (none for JPY). */\nfunction major(amount: number, code: string): number {\n const digits =\n new Intl.NumberFormat('en', { style: 'currency', currency: code }).resolvedOptions()\n .maximumFractionDigits ?? 2;\n return amount / 10 ** digits;\n}\n\n/**\n * Formats a Stripe amount the way the visitor reads prices: the fixed amount\n * in the currency they picked when the dashboard set one (`options`), else\n * the price's own, converted and marked as an estimate when they picked another.\n */\nexport function formatAmount(amount: number, code: string, options?: Record<string, number>): string {\n const fixed = options?.[currency.current];\n if (fixed !== undefined && currency.current !== code) {\n return money(major(fixed, currency.current), currency.current);\n }\n return currency.format(major(amount, code), code);\n}\n\n/**\n * A synced price's `currency_options` as the cart keeps them: upper-cased\n * code to `unit_amount`, leaving out options priced another way (tiers, a\n * customer-chosen amount).\n */\nexport function priceOptions(raw: unknown): Record<string, number> | undefined {\n if (!raw || typeof raw !== 'object') return undefined;\n const options: Record<string, number> = {};\n for (const [code, option] of Object.entries(raw as Record<string, { unit_amount?: unknown }>)) {\n if (typeof option?.unit_amount === 'number') options[code.toUpperCase()] = option.unit_amount;\n }\n return Object.keys(options).length > 0 ? options : undefined;\n}\n", Zf = "<script lang=\"ts\">\n import { Button } from '#lib/components/ui/button/index.js';\n import type { ButtonProps } from '#lib/components/ui/button/index.js';\n import { cart, type CartItem } from '#lib/cart.svelte.js';\n\n interface Props {\n /** The Stripe price, as the page selling it loaded it. */\n price: Omit<CartItem, 'quantity'>;\n quantity?: number;\n label?: string;\n }\n\n let { price, quantity = 1, label = 'Add to cart', ...rest }: Props & ButtonProps = $props();\n\n let added = $state(false);\n\n function add() {\n cart.add(price, quantity);\n added = true;\n cart.open = true;\n setTimeout(() => (added = false), 1500);\n }\n<\/script>\n\n<Button onclick={add} {...rest}>\n {added ? 'Added' : label}\n</Button>\n", Qf = "<script lang=\"ts\">\n import MinusIcon from '@lucide/svelte/icons/minus';\n import PlusIcon from '@lucide/svelte/icons/plus';\n import XIcon from '@lucide/svelte/icons/x';\n import { Button } from '#lib/components/ui/button/index.js';\n import { Separator } from '#lib/components/ui/separator/index.js';\n import { cart, formatAmount } from '#lib/cart.svelte.js';\n\n let { class: className = '' }: { class?: string } = $props();\n\n // What the checkout action reads: the prices and quantities, nothing the\n // browser could misstate.\n const items = $derived(\n JSON.stringify(cart.items.map(({ price, quantity }) => ({ price, quantity })))\n );\n<\/script>\n\n<div class=\"flex flex-col gap-4 {className}\">\n {#if cart.items.length === 0}\n <p class=\"text-muted-foreground text-sm\">Your cart is empty.</p>\n {:else}\n <ul class=\"divide-y\">\n {#each cart.items as item (item.price)}\n <li class=\"flex items-center gap-3 py-3\">\n <div class=\"min-w-0 flex-1\">\n <p class=\"truncate text-sm font-medium\">{item.name}</p>\n <p class=\"text-muted-foreground text-sm\">\n {formatAmount(item.unitAmount, item.currency, item.options)}\n </p>\n </div>\n <div class=\"flex items-center gap-1\">\n <Button\n variant=\"outline\"\n size=\"icon\"\n class=\"size-7\"\n aria-label=\"One fewer {item.name}\"\n onclick={() => cart.setQuantity(item.price, item.quantity - 1)}\n >\n <MinusIcon />\n </Button>\n <span class=\"w-6 text-center text-sm tabular-nums\">{item.quantity}</span>\n <Button\n variant=\"outline\"\n size=\"icon\"\n class=\"size-7\"\n aria-label=\"One more {item.name}\"\n onclick={() => cart.setQuantity(item.price, item.quantity + 1)}\n >\n <PlusIcon />\n </Button>\n </div>\n <Button\n variant=\"ghost\"\n size=\"icon\"\n class=\"size-7\"\n aria-label=\"Remove {item.name}\"\n onclick={() => cart.remove(item.price)}\n >\n <XIcon />\n </Button>\n </li>\n {/each}\n </ul>\n\n <Separator />\n\n {#if cart.currency}\n <div class=\"flex justify-between text-sm font-medium\">\n <span>Subtotal</span>\n <span>{formatAmount(cart.subtotal, cart.currency, cart.options)}</span>\n </div>\n {/if}\n\n <!-- A plain form post: checkout works before the page has hydrated. -->\n <form method=\"POST\" action=\"/cart?/checkout\">\n <input type=\"hidden\" name=\"items\" value={items} />\n <Button type=\"submit\" class=\"w-full\">Check out</Button>\n </form>\n {/if}\n</div>\n", $f = "<script lang=\"ts\">\n import * as Sheet from '#lib/components/ui/sheet/index.js';\n import CartItems from './cart-items.svelte';\n import { cart } from '#lib/cart.svelte.js';\n<\/script>\n\n<Sheet.Root bind:open={cart.open}>\n <Sheet.Content side=\"right\" class=\"flex flex-col\">\n <Sheet.Header>\n <Sheet.Title>Cart</Sheet.Title>\n </Sheet.Header>\n <CartItems class=\"flex-1 overflow-y-auto px-4 pb-4\" />\n </Sheet.Content>\n</Sheet.Root>\n", ep = "import { fail, redirect } from '@sveltejs/kit';\nimport Stripe from 'stripe';\nimport stripe from '#lib/stripe.js';\nimport { priceOptions } from '#lib/cart.svelte.js';\n\n/** What the cart posts: prices and quantities. Stripe supplies everything else. */\nfunction readItems(raw: FormDataEntryValue | null): { price: string; quantity: number }[] | null {\n try {\n const items: unknown = JSON.parse(typeof raw === 'string' ? raw : '');\n if (!Array.isArray(items) || items.length === 0 || items.length > 100) return null;\n const valid = items.every(\n (item) =>\n typeof item?.price === 'string' &&\n Number.isInteger(item?.quantity) &&\n item.quantity >= 1 &&\n item.quantity <= 99\n );\n return valid ? items : null;\n } catch {\n return null;\n }\n}\n\n/**\n * The currency to charge in: the one the visitor read prices in, when every\n * price has a fixed amount in it (`currency_options`, set in the dashboard);\n * else the prices' own, and nothing is converted at checkout.\n */\nasync function chargeCurrency(\n locals: App.Locals,\n items: { price: string }[]\n): Promise<string | undefined> {\n const wanted = locals.currency?.toLowerCase();\n if (!wanted) return undefined;\n const prices = await Promise.all(\n items.map((item) =>\n locals.admin\n .collection('stripe_prices')\n .getOne<{ currency?: string; currency_options?: unknown }>(item.price)\n .catch(() => null)\n )\n );\n const priced = prices.every(\n (price) =>\n price &&\n (price.currency === wanted ||\n priceOptions(price.currency_options)?.[wanted.toUpperCase()] !== undefined)\n );\n // Prices already in that currency are charged in it without being told.\n const needed = prices.some((price) => price && price.currency !== wanted);\n return priced && needed ? wanted : undefined;\n}\n\nexport const actions = {\n checkout: async ({ request, url, locals }) => {\n const items = readItems((await request.formData()).get('items'));\n if (!items) return fail(400, { message: 'Your cart could not be read.' });\n\n const currency = await chargeCurrency(locals, items);\n\n let session: Stripe.Checkout.Session;\n try {\n session = await stripe.checkout.sessions.create({\n mode: 'payment',\n currency,\n line_items: items,\n allow_promotion_codes: true,\n success_url: `${url.origin}/checkout/success?session_id={CHECKOUT_SESSION_ID}`,\n cancel_url: `${url.origin}/cart`\n });\n } catch (error) {\n // An inactive or recurring price, or mixed currencies: Stripe says which.\n if (error instanceof Stripe.errors.StripeError) {\n return fail(400, { message: error.message });\n }\n throw error;\n }\n\n // SvelteKit 3 redirects off-site only when told to.\n redirect(303, session.url!, { external: true });\n }\n};\n", tp = "<script lang=\"ts\">\n import CartItems from '#lib/components/cart/cart-items.svelte';\n\n let { form } = $props();\n<\/script>\n\n<section data-role=\"content\" class=\"max-w-xl\">\n <h1 class=\"mb-6 text-2xl font-semibold\">Cart</h1>\n {#if form?.message}\n <p class=\"text-destructive mb-4 text-sm\">{form.message}</p>\n {/if}\n <CartItems />\n</section>\n", np = "import { describe, it, expect, beforeAll, type TestContext } from 'vitest';\nimport * as devalue from 'devalue';\nimport type { Match } from '@velastack/kit';\nimport type { RouteId } from './$types';\nimport stripe from '#lib/stripe.js';\nimport type Stripe from 'stripe';\n\ndescribe('POST /cart?/checkout', () => {\n let price: Stripe.Price;\n let inactivePrice: Stripe.Price;\n\n beforeAll(async () => {\n const name = 'Test Product - Cart';\n const found = await stripe.products.search({\n query: `name:\"${name}\" AND metadata[\"test\"]:\"true\"`,\n limit: 1\n });\n const product =\n found.data[0] ?? (await stripe.products.create({ name, metadata: { test: 'true' } }));\n\n const prices = async (active: boolean) =>\n (await stripe.prices.list({ product: product.id, active, limit: 1 })).data[0];\n price =\n (await prices(true)) ??\n (await stripe.prices.create({ product: product.id, unit_amount: 1500, currency: 'usd' }));\n inactivePrice =\n (await prices(false)) ??\n (await stripe.prices.create({\n product: product.id,\n unit_amount: 2500,\n currency: 'usd',\n active: false\n }));\n });\n\n const checkout = (context: TestContext, items: unknown) =>\n context.request\n .post(`${'/cart' satisfies Match<RouteId>}?/checkout`)\n .type('form')\n .send({ items: typeof items === 'string' ? items : JSON.stringify(items) });\n\n it('redirects to a Stripe Checkout Session', async (context) => {\n const response = await checkout(context, [{ price: price.id, quantity: 2 }]);\n expect(response.body.status).toBe(303);\n expect(response.body.location).toMatch(/^https:\\/\\/checkout\\.stripe\\.com\\//);\n });\n\n it('refuses a cart it cannot read', async (context) => {\n for (const items of ['not json', [], [{ price: price.id }], [{ quantity: 1 }]]) {\n const response = await checkout(context, items);\n expect(response.body.status).toBe(400);\n }\n });\n\n it('refuses quantities outside 1 to 99', async (context) => {\n for (const quantity of [0, 100, 1.5]) {\n const response = await checkout(context, [{ price: price.id, quantity }]);\n expect(response.body.status).toBe(400);\n }\n });\n\n it(\"passes on Stripe's reason for a price it won't sell\", async (context) => {\n const response = await checkout(context, [{ price: inactivePrice.id, quantity: 1 }]);\n expect(response.body.status).toBe(400);\n expect(devalue.parse(response.body.data).message).toMatch(/inactive|not active/i);\n });\n});\n", rp = "import { error } from '@sveltejs/kit';\nimport stripe from '#lib/stripe.js';\n\nexport const load = async ({ url }) => {\n const id = url.searchParams.get('session_id');\n if (!id) error(404, 'Not found');\n\n try {\n const session = await stripe.checkout.sessions.retrieve(id);\n return {\n amountTotal: session.amount_total,\n currency: session.currency,\n paid: session.payment_status === 'paid'\n };\n } catch {\n error(404, 'Not found');\n }\n};\n", ip = "<script lang=\"ts\">\n import { onMount } from 'svelte';\n import { cart, formatAmount } from '#lib/cart.svelte.js';\n\n let { data } = $props();\n\n onMount(() => {\n cart.load();\n if (data.paid) cart.clear();\n });\n<\/script>\n\n<section data-role=\"content\" class=\"max-w-xl\">\n {#if data.paid}\n <h1 class=\"mb-2 text-2xl font-semibold\">Thank you</h1>\n <p class=\"text-muted-foreground\">\n {#if data.amountTotal !== null && data.currency}\n Your payment of {formatAmount(data.amountTotal, data.currency)} went through.\n {:else}\n Your payment went through.\n {/if}\n </p>\n {:else}\n <h1 class=\"mb-2 text-2xl font-semibold\">Payment pending</h1>\n <p class=\"text-muted-foreground\">Your order is placed; the payment has not cleared yet.</p>\n {/if}\n</section>\n", ap = "import { browser } from '$app/env';\nimport { orderSubtotal, type OrderLine } from '@velastack/whatsapp';\nimport { site } from '#lib/site.js';\n\nexport interface CartItem extends OrderLine {\n /** Your own id for the item (a slug or SKU); lines with the same id merge. */\n id: string;\n}\n\n/** An order sent to WhatsApp, kept until the customer says they're done. */\nexport interface PlacedOrder {\n ref: string;\n /** The chat link, to open it again. */\n href: string;\n}\n\nconst STORAGE_KEY = 'cart';\n\n/**\n * The cart is a list of items kept in the browser. Checkout turns it into a\n * WhatsApp message to the business, where the order is confirmed and paid,\n * so what is stored here is what the customer asked for, not what they pay.\n */\nclass Cart {\n items = $state<CartItem[]>([]);\n /** Whether the cart sheet is open. */\n open = $state(false);\n placed = $state<PlacedOrder | null>(null);\n count = $derived(this.items.reduce((total, item) => total + item.quantity, 0));\n /** In `site.currency`, only when every item has a price; otherwise the business quotes. */\n subtotal = $derived(orderSubtotal(this.items, site.currency));\n\n #loaded = false;\n\n /** Reads the saved cart, once, in the browser. */\n load() {\n if (!browser || this.#loaded) return;\n this.#loaded = true;\n try {\n const saved = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? '{}');\n if (Array.isArray(saved?.items)) this.items = saved.items;\n if (saved?.placed) this.placed = saved.placed;\n } catch {\n // Unreadable or blocked storage starts an empty cart.\n }\n }\n\n add(item: Omit<CartItem, 'quantity'>, quantity = 1) {\n this.load();\n // Adding after an order was sent starts the next one.\n if (this.placed) this.clear();\n const line = this.items.find((line) => line.id === item.id);\n if (line) line.quantity += quantity;\n else this.items.push({ ...item, quantity });\n this.#save();\n }\n\n /** A quantity of 0 removes the item. */\n setQuantity(id: string, quantity: number) {\n if (quantity <= 0) return this.remove(id);\n const line = this.items.find((line) => line.id === id);\n if (!line) return;\n line.quantity = quantity;\n this.#save();\n }\n\n remove(id: string) {\n this.items = this.items.filter((line) => line.id !== id);\n this.#save();\n }\n\n /** Records that the order went to WhatsApp; the sheet shows it until `clear()`. */\n place(order: PlacedOrder) {\n this.placed = order;\n this.#save();\n }\n\n clear() {\n this.items = [];\n this.placed = null;\n this.#save();\n }\n\n #save() {\n try {\n localStorage.setItem(\n STORAGE_KEY,\n JSON.stringify({ items: $state.snapshot(this.items), placed: this.placed })\n );\n } catch {\n // Storage can be full or blocked; the cart still works for this visit.\n }\n }\n}\n\nexport const cart = new Cart();\n", op = "<script lang=\"ts\">\n import { Button } from '#lib/components/ui/button/index.js';\n import type { ButtonProps } from '#lib/components/ui/button/index.js';\n import { cart } from '#lib/cart.svelte.js';\n\n interface Props {\n /** Your own id for the item (a slug or SKU); adding it again raises the quantity. */\n id: string;\n /** What the business will read in the order. */\n name: string;\n /** The unit price in `site.currency`, written as you would (`4.5`). Leave it out to quote in the chat. */\n price?: number;\n quantity?: number;\n label?: string;\n }\n\n let {\n id,\n name,\n price,\n quantity = 1,\n label = 'Add to cart',\n ...rest\n }: Props & ButtonProps = $props();\n\n let added = $state(false);\n\n function add() {\n cart.add({ id, name, price }, quantity);\n added = true;\n cart.open = true;\n setTimeout(() => (added = false), 1500);\n }\n<\/script>\n\n<Button onclick={add} {...rest}>\n {added ? 'Added' : label}\n</Button>\n", sp = "<script lang=\"ts\">\n import MinusIcon from '@lucide/svelte/icons/minus';\n import PlusIcon from '@lucide/svelte/icons/plus';\n import XIcon from '@lucide/svelte/icons/x';\n import { toast } from 'svelte-sonner';\n import { formToken, lineTotal, orderRef } from '@velastack/whatsapp';\n import { Button, buttonVariants } from '#lib/components/ui/button/index.js';\n import { Separator } from '#lib/components/ui/separator/index.js';\n import * as Sheet from '#lib/components/ui/sheet/index.js';\n import CustomerFields from '#lib/components/payments/customer-fields.svelte';\n import { cart } from '#lib/cart.svelte.js';\n import { formatPrice } from '#lib/currency.svelte.js';\n import { ORDER_FORM, placeOrder } from '#lib/order.js';\n import { site } from '#lib/site.js';\n\n // Fetched once, the first time the cart opens: the hosted form refuses a\n // token younger than two seconds, and filling the form in takes longer.\n let token: string | null = null;\n\n $effect(() => {\n if (!cart.open || !ORDER_FORM || token) return;\n formToken(ORDER_FORM).then((value) => (token = value));\n });\n\n function checkout(event: SubmitEvent) {\n event.preventDefault();\n const data = new FormData(event.currentTarget as HTMLFormElement);\n const order = {\n ref: orderRef(),\n name: String(data.get('name') ?? ''),\n phone: String(data.get('phone') ?? ''),\n note: String(data.get('note') ?? '') || undefined,\n currency: site.currency,\n lines: cart.items.map(({ name, quantity, price }) => ({ name, quantity, price })),\n subtotal: cart.subtotal\n };\n const href = placeOrder(order, { token, gotcha: String(data.get('_gotcha') ?? '') });\n if (!href) {\n toast.error('WhatsApp ordering is not set up yet');\n return;\n }\n cart.place({ ref: order.ref, href });\n }\n\n function done() {\n cart.clear();\n cart.open = false;\n }\n<\/script>\n\n<Sheet.Root bind:open={cart.open}>\n <Sheet.Content side=\"right\" class=\"flex flex-col\">\n <Sheet.Header>\n <Sheet.Title>Cart</Sheet.Title>\n </Sheet.Header>\n <div class=\"flex flex-1 flex-col gap-4 overflow-y-auto px-4 pb-4\">\n {#if cart.placed}\n <div class=\"flex flex-col gap-2\">\n <p class=\"font-medium\">Order {cart.placed.ref} opened in WhatsApp</p>\n <p class=\"text-muted-foreground text-sm\">\n Send the message in WhatsApp to place your order. We'll reply there.\n </p>\n </div>\n <a\n href={cart.placed.href}\n target=\"_blank\"\n rel=\"noopener noreferrer\"\n class={buttonVariants({ variant: 'outline' })}\n >\n Open WhatsApp again\n </a>\n <Button onclick={done}>Done</Button>\n {:else if cart.items.length === 0}\n <p class=\"text-muted-foreground text-sm\">Your cart is empty.</p>\n {:else}\n <ul class=\"divide-y\">\n {#each cart.items as item (item.id)}\n {@const total = lineTotal(item, site.currency)}\n <li class=\"flex items-center gap-3 py-3\">\n <div class=\"min-w-0 flex-1\">\n <p class=\"truncate text-sm font-medium\">{item.name}</p>\n {#if total !== undefined}\n <p class=\"text-muted-foreground text-sm\">{formatPrice(total)}</p>\n {/if}\n </div>\n <div class=\"flex items-center gap-1\">\n <Button\n variant=\"outline\"\n size=\"icon\"\n class=\"size-7\"\n aria-label=\"One fewer {item.name}\"\n onclick={() => cart.setQuantity(item.id, item.quantity - 1)}\n >\n <MinusIcon />\n </Button>\n <span class=\"w-6 text-center text-sm tabular-nums\">{item.quantity}</span>\n <Button\n variant=\"outline\"\n size=\"icon\"\n class=\"size-7\"\n aria-label=\"One more {item.name}\"\n onclick={() => cart.setQuantity(item.id, item.quantity + 1)}\n >\n <PlusIcon />\n </Button>\n </div>\n <Button\n variant=\"ghost\"\n size=\"icon\"\n class=\"size-7\"\n aria-label=\"Remove {item.name}\"\n onclick={() => cart.remove(item.id)}\n >\n <XIcon />\n </Button>\n </li>\n {/each}\n </ul>\n\n <Separator />\n\n {#if cart.subtotal !== undefined}\n <div class=\"flex justify-between text-sm font-medium\">\n <span>Subtotal</span>\n <span>{formatPrice(cart.subtotal)}</span>\n </div>\n {:else}\n <p class=\"text-muted-foreground text-sm\">We'll confirm the total in WhatsApp.</p>\n {/if}\n\n <form class=\"flex flex-col gap-4\" onsubmit={checkout}>\n <CustomerFields />\n <Button type=\"submit\" class=\"w-full\">Order on WhatsApp</Button>\n </form>\n {/if}\n </div>\n </Sheet.Content>\n</Sheet.Root>\n", cp = "import { fail, redirect } from '@sveltejs/kit';\nimport Stripe from 'stripe';\nimport stripe from '#lib/stripe.js';\nimport { priceOptions } from '#lib/cart.svelte.js';\nimport { getStripeCustomerId } from '#lib/server/stripe-customer.js';\n\n/** What the cart posts: prices and quantities. Stripe supplies everything else. */\nfunction readItems(raw: FormDataEntryValue | null): { price: string; quantity: number }[] | null {\n try {\n const items: unknown = JSON.parse(typeof raw === 'string' ? raw : '');\n if (!Array.isArray(items) || items.length === 0 || items.length > 100) return null;\n const valid = items.every(\n (item) =>\n typeof item?.price === 'string' &&\n Number.isInteger(item?.quantity) &&\n item.quantity >= 1 &&\n item.quantity <= 99\n );\n return valid ? items : null;\n } catch {\n return null;\n }\n}\n\n/**\n * The currency to charge in: the one the visitor read prices in, when every\n * price has a fixed amount in it (`currency_options`, set in the dashboard);\n * else the prices' own, and nothing is converted at checkout.\n */\nasync function chargeCurrency(\n locals: App.Locals,\n items: { price: string }[]\n): Promise<string | undefined> {\n const wanted = locals.currency?.toLowerCase();\n if (!wanted) return undefined;\n const prices = await Promise.all(\n items.map((item) =>\n locals.admin\n .collection('stripe_prices')\n .getOne<{ currency?: string; currency_options?: unknown }>(item.price)\n .catch(() => null)\n )\n );\n const priced = prices.every(\n (price) =>\n price &&\n (price.currency === wanted ||\n priceOptions(price.currency_options)?.[wanted.toUpperCase()] !== undefined)\n );\n // Prices already in that currency are charged in it without being told.\n const needed = prices.some((price) => price && price.currency !== wanted);\n return priced && needed ? wanted : undefined;\n}\n\nexport const actions = {\n checkout: async ({ request, url, locals }) => {\n const items = readItems((await request.formData()).get('items'));\n if (!items) return fail(400, { message: 'Your cart could not be read.' });\n\n // A signed-in buyer checks out as their Stripe customer, so their saved\n // cards are offered and the payment shows up on their billing page. If\n // the customer isn't linked yet, they check out as a guest.\n const user = locals.pb.authStore.record;\n const customer = user\n ? await getStripeCustomerId(locals.admin, user).catch(() => undefined)\n : undefined;\n\n const currency = await chargeCurrency(locals, items);\n\n let session: Stripe.Checkout.Session;\n try {\n session = await stripe.checkout.sessions.create({\n mode: 'payment',\n currency,\n customer,\n line_items: items,\n allow_promotion_codes: true,\n success_url: `${url.origin}/checkout/success?session_id={CHECKOUT_SESSION_ID}`,\n cancel_url: `${url.origin}/cart`\n });\n } catch (error) {\n // An inactive or recurring price, or mixed currencies: Stripe says which.\n if (error instanceof Stripe.errors.StripeError) {\n return fail(400, { message: error.message });\n }\n throw error;\n }\n\n // SvelteKit 3 redirects off-site only when told to.\n redirect(303, session.url!, { external: true });\n }\n};\n", lp = [
6168
6168
  {
6169
6169
  id: "stripe",
6170
6170
  label: "Stripe",
@@ -6236,7 +6236,7 @@ async function gp(e) {
6236
6236
  }
6237
6237
  //#endregion
6238
6238
  //#region src/patterns/enable/ecommerce/index.ts
6239
- var _p = "enable-ecommerce", vp = "2.1.0", yp = "src/patterns/enable/ecommerce", bp = "/enable/ecommerce";
6239
+ var _p = "enable-ecommerce", vp = "2.2.0", yp = "src/patterns/enable/ecommerce", bp = "/enable/ecommerce";
6240
6240
  async function xp(e) {
6241
6241
  if (e.env === "preview") {
6242
6242
  let t = await mp(e), n = await gp(e);
@@ -8275,11 +8275,11 @@ var H_ = {
8275
8275
  tests: 0,
8276
8276
  baseline: "velastack-auth",
8277
8277
  generate: V_
8278
- }, U_ = "disable-payments", W_ = "2.3.0", G_ = "src/patterns/disable/payments", K_ = "/disable/payments";
8278
+ }, U_ = "disable-payments", W_ = "2.4.0", G_ = "src/patterns/disable/payments", K_ = "/disable/payments";
8279
8279
  async function q_(e) {
8280
8280
  let t = await br(e);
8281
8281
  if (e.env !== "runtime") return D(t, e);
8282
- let { generate: n } = await import("./chunks/generate.runtime-KrQk7mqG.js"), r = await n(e), i = await D(C([t, r]), e);
8282
+ let { generate: n } = await import("./chunks/generate.runtime-DG9Lp3vR.js"), r = await n(e), i = await D(C([t, r]), e);
8283
8283
  if (e.input.destructive !== !0) return i;
8284
8284
  let a = yr(e).some((e) => e.id === "stripe") && e.features.backend ? await J_(e) : [], o = {
8285
8285
  ...i,