create-nymbal-app 0.5.0 → 0.6.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 (35) hide show
  1. package/dist/index.js +7 -1
  2. package/dist/index.js.map +1 -1
  3. package/package.json +1 -1
  4. package/scaffold/templates/astro/package.json +25 -25
  5. package/scaffold/templates/astro/src/lib/api.ts +53 -21
  6. package/scaffold/templates/astro/src/pages/404.astro +3 -0
  7. package/scaffold/templates/astro/src/pages/account/orders/[orderNumber].astro +11 -3
  8. package/scaffold/templates/astro/src/pages/alerts/confirm.astro +59 -0
  9. package/scaffold/templates/astro/src/pages/alerts/unsubscribe.astro +53 -0
  10. package/scaffold/templates/astro/src/pages/category/[slug].astro +8 -6
  11. package/scaffold/templates/astro/src/pages/checkout.astro +2 -2
  12. package/scaffold/templates/astro/src/pages/index.astro +7 -0
  13. package/scaffold/templates/astro/src/pages/order/[orderNumber].astro +13 -2
  14. package/scaffold/templates/astro/src/pages/product/[slug].astro +20 -4
  15. package/scaffold/templates/astro/src/scripts/order-status.ts +3 -1
  16. package/scaffold/templates/astro/src/scripts/pdp.ts +5 -0
  17. package/scaffold/templates/astro/src/styles/pages/account.css +4 -0
  18. package/scaffold/templates/nextjs/app/(catalog)/home/[key]/page.tsx +6 -1
  19. package/scaffold/templates/nextjs/app/(catalog)/product/[slug]/page.tsx +22 -3
  20. package/scaffold/templates/nextjs/app/(shopper)/account/orders/[orderNumber]/page.tsx +10 -3
  21. package/scaffold/templates/nextjs/app/(shopper)/alerts/AlertLinkForm.tsx +90 -0
  22. package/scaffold/templates/nextjs/app/(shopper)/alerts/LinkInvalid.tsx +19 -0
  23. package/scaffold/templates/nextjs/app/(shopper)/alerts/actions.ts +33 -0
  24. package/scaffold/templates/nextjs/app/(shopper)/alerts/confirm/page.tsx +19 -0
  25. package/scaffold/templates/nextjs/app/(shopper)/alerts/unsubscribe/page.tsx +17 -0
  26. package/scaffold/templates/nextjs/app/(shopper)/checkout/CheckoutView.tsx +16 -9
  27. package/scaffold/templates/nextjs/app/(shopper)/not-found.tsx +6 -0
  28. package/scaffold/templates/nextjs/app/(shopper)/order/[orderNumber]/page.tsx +21 -5
  29. package/scaffold/templates/nextjs/app/not-found.tsx +1 -1
  30. package/scaffold/templates/nextjs/components/client/OrderStatusRefresh.tsx +8 -2
  31. package/scaffold/templates/nextjs/components/client/ProductInteractive.tsx +18 -1
  32. package/scaffold/templates/nextjs/components/client/elements.tsx +2 -0
  33. package/scaffold/templates/nextjs/lib/api.ts +55 -15
  34. package/scaffold/templates/nextjs/next.config.mjs +9 -0
  35. package/scaffold/templates/nextjs/package.json +26 -26
package/dist/index.js CHANGED
@@ -10,6 +10,10 @@ import pc from "picocolors";
10
10
  var HERE = dirname(fileURLToPath(import.meta.url));
11
11
  var SCAFFOLD_ROOT = resolve(HERE, "..", "scaffold");
12
12
  var API_PORT = 3001;
13
+ var STOREFRONT_ORIGIN = {
14
+ astro: "http://localhost:4321",
15
+ nextjs: "http://localhost:3000"
16
+ };
13
17
  function newAdminCredentials() {
14
18
  return { email: "admin@nymbal.local", password: randomBytes(16).toString("base64url") };
15
19
  }
@@ -325,7 +329,7 @@ async function renameDotFiles(dir) {
325
329
  }
326
330
  }
327
331
  function renderConfig(answers) {
328
- return `import { defineConfig } from '@nymbalhq/config'
332
+ return `import { defineConfig, env } from '@nymbalhq/config'
329
333
 
330
334
  export default defineConfig({
331
335
  store: {
@@ -333,6 +337,8 @@ export default defineConfig({
333
337
  currency: '${answers.currency}',
334
338
  locale: '${defaultLocale(answers.currency)}',
335
339
  timezone: '${defaultTimezone(answers.currency)}',
340
+ // The storefront's public origin: the order email links to its order page. Set it for production.
341
+ url: env('NYMBAL_STOREFRONT_URL', '${STOREFRONT_ORIGIN[answers.template]}'),
336
342
  },
337
343
 
338
344
  template: '${answers.template}',
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { cp, readFile, mkdir, readdir, rm, writeFile } from 'node:fs/promises'\nimport { existsSync } from 'node:fs'\nimport { dirname, resolve } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { spawn, spawnSync } from 'node:child_process'\nimport { randomBytes } from 'node:crypto'\nimport { cancel, confirm, intro, isCancel, note, outro, select, text } from '@clack/prompts'\nimport pc from 'picocolors'\n\nconst HERE = dirname(fileURLToPath(import.meta.url))\nconst SCAFFOLD_ROOT = resolve(HERE, '..', 'scaffold')\n\nexport type PackageManager = 'npm' | 'pnpm' | 'yarn-classic' | 'yarn-berry' | 'bun'\n\ninterface Answers {\n name: string\n directory: string\n currency: 'GBP' | 'USD' | 'EUR'\n template: 'astro' | 'nextjs'\n seedDemo: boolean\n}\n\n/**\n * Runs a command in `cwd` (with `env` when given, else the process environment) and rejects on a non-zero exit.\n * Injected into `main` so tests do not shell out.\n */\nexport type Runner = (\n cmd: string,\n args: string[],\n cwd: string,\n env?: NodeJS.ProcessEnv,\n) => Promise<void>\n\n/** The port `renderConfig` gives the API, which serves the admin at /admin/. */\nconst API_PORT = 3001\n\ninterface AdminCredentials {\n email: string\n password: string\n}\n\n/** A fresh admin password per project (128 bits, base64url), so no two stores share the seed's default. */\nfunction newAdminCredentials(): AdminCredentials {\n return { email: 'admin@nymbal.local', password: randomBytes(16).toString('base64url') }\n}\n\n/**\n * `.env` holds the admin credentials the seed (and a first `nymbal dev`) creates the admin from, and the project's own\n * key for the values the admin's Settings encrypt (32 random bytes, base64).\n */\nasync function writeAdminEnv(dir: string, admin: AdminCredentials): Promise<void> {\n const lines = [\n '# The admin account the seed creates. Keep this file out of version control (.gitignore lists it).',\n `NYMBAL_ADMIN_EMAIL=${admin.email}`,\n `NYMBAL_ADMIN_PASSWORD=${admin.password}`,\n '',\n \"# Encrypts the keys saved in the admin's Settings. Losing it loses them: back it up with your deploy's secrets.\",\n `NYMBAL_SECRETS_KEY=${randomBytes(32).toString('base64')}`,\n '',\n ]\n await writeFile(resolve(dir, '.env'), lines.join('\\n'), { encoding: 'utf8', mode: 0o600 })\n}\n\nfunction adminSignIn(admin: AdminCredentials): string[] {\n return [\n `Admin: http://localhost:${API_PORT}/admin/`,\n ` email ${admin.email}`,\n ` password ${admin.password} (saved in .env)`,\n ]\n}\n\nexport interface MainDeps {\n run?: Runner\n}\n\n/**\n * The `packageManager` field for the package manager that launched us (`npm_config_user_agent`), read when called.\n * Without a usable user agent it is the installed npm; undefined when npm cannot be run either.\n */\nfunction packageManagerField(): string | undefined {\n const token = (process.env['npm_config_user_agent'] ?? '').split(' ')[0] ?? ''\n const match = /^(npm|pnpm|yarn|bun)\\/(\\d+\\.\\d+\\.\\d+\\S*)$/.exec(token)\n if (match) return `${match[1]}@${match[2]}`\n const npm = spawnSync('npm', ['-v'], { encoding: 'utf8', shell: process.platform === 'win32' })\n const version = npm.status === 0 ? npm.stdout.trim() : ''\n return version ? `npm@${version}` : undefined\n}\n\nexport function detectPackageManager(): PackageManager {\n const ua = process.env['npm_config_user_agent']\n if (!ua) return 'npm'\n const token = ua.split(' ')[0] ?? ''\n const slash = token.indexOf('/')\n const pm = slash >= 0 ? token.slice(0, slash) : token\n const version = slash >= 0 ? token.slice(slash + 1) : ''\n if (pm === 'pnpm') return 'pnpm'\n if (pm === 'bun') return 'bun'\n if (pm === 'yarn') {\n const major = parseInt(version.split('.')[0] ?? '1', 10)\n return major < 2 ? 'yarn-classic' : 'yarn-berry'\n }\n return 'npm'\n}\n\nfunction installCmd(pm: PackageManager): [string, string[]] {\n switch (pm) {\n case 'pnpm':\n return ['pnpm', ['install']]\n case 'bun':\n return ['bun', ['install']]\n case 'yarn-classic':\n case 'yarn-berry':\n return ['yarn', ['install']]\n default:\n return ['npm', ['install']]\n }\n}\n\nfunction seedCmd(pm: PackageManager): [string, string[]] {\n switch (pm) {\n case 'pnpm':\n return ['pnpm', ['exec', 'nymbal', 'seed']]\n case 'bun':\n return ['bunx', ['nymbal', 'seed']]\n case 'yarn-classic':\n return ['yarn', ['run', 'nymbal', 'seed']]\n case 'yarn-berry':\n return ['yarn', ['exec', 'nymbal', 'seed']]\n default:\n return ['npx', ['nymbal', 'seed']]\n }\n}\n\nfunction devCmd(pm: PackageManager): string {\n switch (pm) {\n case 'pnpm':\n return 'pnpm dev'\n case 'bun':\n return 'bun dev'\n case 'yarn-classic':\n case 'yarn-berry':\n return 'yarn dev'\n default:\n return 'npm run dev'\n }\n}\n\nconst TEMPLATES = ['astro', 'nextjs'] as const\nconst CURRENCIES = ['GBP', 'USD', 'EUR'] as const\n\nexport interface CliFlags {\n name?: string\n template?: (typeof TEMPLATES)[number]\n currency?: (typeof CURRENCIES)[number]\n yes: boolean\n /** Present (false) only with `--no-install`. */\n install?: boolean\n}\n\n/** A command-line flag that is missing its value or names a value outside the allowed set. */\nexport class CliFlagError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'CliFlagError'\n }\n}\n\nfunction oneOf<T extends string>(flag: string, value: string, allowed: readonly T[]): T {\n if ((allowed as readonly string[]).includes(value)) return value as T\n throw new CliFlagError(`Unknown ${flag} \"${value}\". Allowed: ${allowed.join(', ')}`)\n}\n\n/** Parses process.argv (node and script first): --name, --template and --currency take `--flag v` or `--flag=v`. */\nexport function parseCliFlags(argv: string[]): CliFlags {\n const flags: CliFlags = { yes: false }\n const args = argv.slice(2)\n let positional: string | undefined\n for (let i = 0; i < args.length; i++) {\n const arg = args[i]!\n if (arg === '--yes' || arg === '-y') {\n flags.yes = true\n continue\n }\n if (arg === '--no-install') {\n flags.install = false\n continue\n }\n const match = /^--(name|template|currency)(?:=(.*))?$/s.exec(arg)\n if (match) {\n const flag = match[1]!\n let value = match[2]\n if (value === undefined) {\n const next = args[i + 1]\n if (next === undefined || next.startsWith('-'))\n throw new CliFlagError(`--${flag} needs a value`)\n value = next\n i++\n }\n if (flag === 'name') flags.name = value\n else if (flag === 'template') flags.template = oneOf('--template', value, TEMPLATES)\n else flags.currency = oneOf('--currency', value, CURRENCIES)\n } else if (!arg.startsWith('-') && positional === undefined) {\n positional = arg\n }\n }\n if (flags.name === undefined && positional !== undefined) flags.name = positional\n return flags\n}\n\nexport async function main(argv: string[] = process.argv, deps: MainDeps = {}): Promise<void> {\n const run = deps.run ?? runCmd\n let flags: CliFlags\n try {\n flags = parseCliFlags(argv)\n } catch (err) {\n if (!(err instanceof CliFlagError)) throw err\n process.stderr.write(`Error: ${err.message}\\n`)\n process.exit(1)\n }\n\n const pm = detectPackageManager()\n\n if (flags.yes) {\n if (!flags.name) {\n process.stderr.write('Error: --yes requires --name or a positional name argument\\n')\n process.exit(1)\n }\n const name = flags.name.trim()\n const answers: Answers = {\n name,\n directory: toDirectoryName(name),\n currency: flags.currency ?? 'GBP',\n template: flags.template ?? 'astro',\n seedDemo: true,\n }\n const targetDir = resolve(process.cwd(), answers.directory)\n if (existsSync(targetDir)) {\n const entries = await readdir(targetDir)\n if (entries.length > 0) {\n process.stderr.write(\n `Error: Directory ${answers.directory} already exists and is not empty.\\n`,\n )\n process.exit(1)\n }\n } else {\n await mkdir(targetDir, { recursive: true })\n }\n await scaffold(targetDir, answers)\n const admin = newAdminCredentials()\n await writeAdminEnv(targetDir, admin)\n process.stdout.write(`Created ${answers.directory}\\n`)\n if (flags.install !== false) {\n await installAndSeed(targetDir, pm, answers.seedDemo, run, admin)\n } else {\n process.stdout.write(`Next: cd ${answers.directory} && ${installCmd(pm)[0]} install\\n`)\n }\n process.stdout.write(`${adminSignIn(admin).join('\\n')}\\n`)\n return\n }\n\n intro(pc.cyan(pc.bold('◆ create-nymbal-app')))\n\n const name = flags.name\n ? flags.name\n : ((await text({\n message: 'Store name',\n placeholder: 'My Store',\n validate: (v) => (!v || v.trim().length === 0 ? 'Required' : undefined),\n })) as string | symbol)\n\n if (isCancel(name)) return cancel('Cancelled')\n\n type Currency = 'GBP' | 'USD' | 'EUR'\n const currencyOptions: { value: Currency; label: string }[] = [\n { value: 'GBP', label: 'GBP — British Pound' },\n { value: 'USD', label: 'USD — US Dollar' },\n { value: 'EUR', label: 'EUR — Euro' },\n ]\n const currency = await select({\n message: 'Store currency',\n options: currencyOptions,\n initialValue: 'GBP' as Currency,\n })\n\n if (isCancel(currency)) return cancel('Cancelled')\n\n type Template = 'astro' | 'nextjs'\n const templateOptions: { value: Template; label: string }[] = [\n { value: 'astro', label: 'Astro (recommended — performance-first)' },\n { value: 'nextjs', label: 'Next.js (migration-friendly)' },\n ]\n const template = await select({\n message: 'Storefront template',\n options: templateOptions,\n initialValue: 'astro' as Template,\n })\n\n if (isCancel(template)) return cancel('Cancelled')\n\n const seedDemo = (await confirm({\n message: 'Generate demo content?',\n initialValue: true,\n })) as boolean | symbol\n\n if (isCancel(seedDemo)) return cancel('Cancelled')\n\n const shouldInstall =\n flags.install === false\n ? false\n : ((await confirm({\n message: 'Install dependencies now?',\n initialValue: true,\n })) as boolean | symbol)\n\n if (isCancel(shouldInstall)) return cancel('Cancelled')\n\n const answers: Answers = {\n name: String(name).trim(),\n directory: toDirectoryName(String(name).trim()),\n currency: currency as 'GBP' | 'USD' | 'EUR',\n template: template as 'astro' | 'nextjs',\n seedDemo: seedDemo as boolean,\n }\n\n const targetDir = resolve(process.cwd(), answers.directory)\n if (existsSync(targetDir)) {\n const entries = await readdir(targetDir)\n if (entries.length > 0) {\n cancel(`Directory ${answers.directory} already exists and is not empty.`)\n process.exit(1)\n }\n } else {\n await mkdir(targetDir, { recursive: true })\n }\n\n note(pc.dim(`Scaffolding into ${targetDir}`), 'Creating project')\n\n await scaffold(targetDir, answers)\n const admin = newAdminCredentials()\n await writeAdminEnv(targetDir, admin)\n\n if (shouldInstall) {\n await installAndSeed(targetDir, pm, answers.seedDemo, run, admin)\n }\n\n const cmd = devCmd(pm)\n const nextSteps = [` ${pc.cyan('cd')} ${answers.directory}`]\n if (!shouldInstall) {\n const [ic] = installCmd(pm)\n nextSteps.push(` ${pc.cyan(ic + ' install')}`)\n }\n nextSteps.push(` ${pc.cyan(cmd)}`)\n\n outro(\n [pc.green(`✓ Created ${answers.directory}`), '', ...nextSteps, '', ...adminSignIn(admin)].join(\n '\\n',\n ),\n )\n}\n\n/** Install with the detected package manager, then seed through the project's own `nymbal` bin. */\nasync function installAndSeed(\n dir: string,\n pm: PackageManager,\n seedDemo: boolean,\n run: Runner,\n admin: AdminCredentials,\n): Promise<void> {\n const [installBin, installArgs] = installCmd(pm)\n process.stdout.write(`Running ${installBin} install (this may take a moment)...\\n`)\n await run(installBin, installArgs, dir)\n if (seedDemo) {\n process.stdout.write('Seeding demo content...\\n')\n const [seedBin, seedArgs] = seedCmd(pm)\n // Explicit, so a value exported in the shell cannot replace the one in .env and the outro.\n await run(seedBin, seedArgs, dir, {\n ...process.env,\n NYMBAL_ADMIN_EMAIL: admin.email,\n NYMBAL_ADMIN_PASSWORD: admin.password,\n })\n }\n}\n\nexport async function scaffold(dir: string, answers: Answers): Promise<void> {\n // Copy the chosen template directly into dir (flat — no storefront/ subdirectory)\n await copyScaffoldDir(resolve(SCAFFOLD_ROOT, 'templates', answers.template), dir)\n\n // Overlay the project layer (scaffold/project/<template>) on top of the template\n // defaults. Project files WIN on path collision — this is the override model:\n // anything in the project layer shadows the template default at the same path.\n // scaffold/project/ lives outside scaffold/templates/, so sync-scaffold's\n // rm -rf of scaffold/templates/* never deletes it.\n const projectLayer = resolve(SCAFFOLD_ROOT, 'project', answers.template)\n if (existsSync(projectLayer)) {\n await copyScaffoldDir(projectLayer, dir)\n }\n\n // Write nymbal.config.ts (answers-dependent, so generated at runtime)\n await writeFile(resolve(dir, 'nymbal.config.ts'), renderConfig(answers), 'utf8')\n\n // Patch the copied package.json: set name to the project directory name\n await patchPackageJson(dir, answers.directory)\n}\n\nasync function patchPackageJson(dir: string, name: string): Promise<void> {\n const pkgPath = resolve(dir, 'package.json')\n const pkg = JSON.parse(await readFile(pkgPath, 'utf8')) as Record<string, unknown>\n pkg['name'] = name\n pkg['private'] = true\n const packageManager = packageManagerField()\n if (packageManager) pkg['packageManager'] = packageManager\n await writeFile(pkgPath, JSON.stringify(pkg, null, 2) + '\\n', 'utf8')\n}\n\nasync function copyScaffoldDir(src: string, dest: string): Promise<void> {\n if (!existsSync(src)) {\n throw new Error(`Scaffold directory not found: ${src}`)\n }\n await cp(src, dest, {\n recursive: true,\n filter: (source) => !source.endsWith('node_modules'),\n })\n await renameDotFiles(dest)\n}\n\nasync function renameDotFiles(dir: string): Promise<void> {\n // Non-recursive: only rename _dot.* files at the project root.\n // All shared dotfiles (_dot.gitignore, _dot.env.example) live at template root.\n const entries = await readdir(dir, { withFileTypes: true })\n for (const entry of entries) {\n if (!entry.isDirectory() && entry.name.startsWith('_dot.')) {\n const full = resolve(dir, entry.name)\n const renamed = resolve(dir, '.' + entry.name.slice(5))\n await writeFile(renamed, await readFile(full))\n await rm(full)\n }\n }\n}\n\nfunction renderConfig(answers: Answers): string {\n return `import { defineConfig } from '@nymbalhq/config'\n\nexport default defineConfig({\n store: {\n name: '${escape(answers.name)}',\n currency: '${answers.currency}',\n locale: '${defaultLocale(answers.currency)}',\n timezone: '${defaultTimezone(answers.currency)}',\n },\n\n template: '${answers.template}',\n\n infrastructure: {\n commandStore: 'sqlite',\n documentStore: 'in-memory',\n eventBus: 'in-process',\n },\n\n security: {\n adapter: 'middleware',\n rateLimit: {\n '/checkout': { requests: 10, window: '1m', action: 'block' },\n '/auth/*': { requests: 5, window: '1m', action: 'challenge' },\n '/api/*': { requests: 100, window: '1m', action: 'throttle' },\n '/webhooks/*': { requests: 200, window: '1m', action: 'throttle' },\n },\n botProtection: { mode: 'managed', allowList: ['googlebot', 'bingbot', 'stripe-webhooks'] },\n headers: {\n hsts: true,\n contentSecurityPolicy: 'strict',\n referrerPolicy: 'strict-origin-when-cross-origin',\n xFrameOptions: 'deny',\n },\n csrf: true,\n },\n\n commerce: {\n payments: { provider: 'native' },\n email: { provider: 'native' },\n reviews: { provider: 'native' },\n search: { provider: 'native' },\n analytics: { provider: 'native' },\n shipping: { provider: 'native' },\n tax: { provider: 'native' },\n ai: { provider: 'none' },\n },\n\n http: {\n adapter: 'fastify',\n port: ${API_PORT},\n },\n\n deployment: {\n strategy: 'standard',\n },\n\n features: {\n staging: false,\n heartbeat: false,\n autoUpdates: false,\n },\n})\n`\n}\n\nfunction defaultLocale(currency: Answers['currency']): string {\n return currency === 'USD' ? 'en-US' : 'en-GB'\n}\n\nfunction defaultTimezone(currency: Answers['currency']): string {\n return currency === 'USD' ? 'America/New_York' : 'Europe/London'\n}\n\nfunction escape(v: string): string {\n return v.replace(/'/g, \"\\\\'\")\n}\n\nfunction toDirectoryName(name: string): string {\n return name\n .toLowerCase()\n .replace(/[^a-z0-9-_ ]/g, '')\n .trim()\n .replace(/\\s+/g, '-')\n}\n\nconst runCmd: Runner = (cmd, args, cwd, env = process.env) => {\n return new Promise((resolve, reject) => {\n const child = spawn(cmd, args, { cwd, env, stdio: 'inherit', shell: false })\n child.on('error', reject)\n child.on('exit', (code) => {\n if (code === 0) return resolve()\n reject(new Error(`${cmd} ${args.join(' ')} exited with ${code}`))\n })\n })\n}\n"],"mappings":";AAAA,SAAS,IAAI,UAAU,OAAO,SAAS,IAAI,iBAAiB;AAC5D,SAAS,kBAAkB;AAC3B,SAAS,SAAS,eAAe;AACjC,SAAS,qBAAqB;AAC9B,SAAS,OAAO,iBAAiB;AACjC,SAAS,mBAAmB;AAC5B,SAAS,QAAQ,SAAS,OAAO,UAAU,MAAM,OAAO,QAAQ,YAAY;AAC5E,OAAO,QAAQ;AAEf,IAAM,OAAO,QAAQ,cAAc,YAAY,GAAG,CAAC;AACnD,IAAM,gBAAgB,QAAQ,MAAM,MAAM,UAAU;AAwBpD,IAAM,WAAW;AAQjB,SAAS,sBAAwC;AAC/C,SAAO,EAAE,OAAO,sBAAsB,UAAU,YAAY,EAAE,EAAE,SAAS,WAAW,EAAE;AACxF;AAMA,eAAe,cAAc,KAAa,OAAwC;AAChF,QAAM,QAAQ;AAAA,IACZ;AAAA,IACA,sBAAsB,MAAM,KAAK;AAAA,IACjC,yBAAyB,MAAM,QAAQ;AAAA,IACvC;AAAA,IACA;AAAA,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;AAC7C,SAAO,KACJ,YAAY,EACZ,QAAQ,iBAAiB,EAAE,EAC3B,KAAK,EACL,QAAQ,QAAQ,GAAG;AACxB;AAEA,IAAM,SAAiB,CAAC,KAAK,MAAM,KAAK,MAAM,QAAQ,QAAQ;AAC5D,SAAO,IAAI,QAAQ,CAACC,UAAS,WAAW;AACtC,UAAM,QAAQ,MAAM,KAAK,MAAM,EAAE,KAAK,KAAK,OAAO,WAAW,OAAO,MAAM,CAAC;AAC3E,UAAM,GAAG,SAAS,MAAM;AACxB,UAAM,GAAG,QAAQ,CAAC,SAAS;AACzB,UAAI,SAAS,EAAG,QAAOA,SAAQ;AAC/B,aAAO,IAAI,MAAM,GAAG,GAAG,IAAI,KAAK,KAAK,GAAG,CAAC,gBAAgB,IAAI,EAAE,CAAC;AAAA,IAClE,CAAC;AAAA,EACH,CAAC;AACH;","names":["name","answers","targetDir","admin","resolve"]}
1
+ {"version":3,"sources":["../src/index.ts"],"sourcesContent":["import { cp, readFile, mkdir, readdir, rm, writeFile } from 'node:fs/promises'\nimport { existsSync } from 'node:fs'\nimport { dirname, resolve } from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { spawn, spawnSync } from 'node:child_process'\nimport { randomBytes } from 'node:crypto'\nimport { cancel, confirm, intro, isCancel, note, outro, select, text } from '@clack/prompts'\nimport pc from 'picocolors'\n\nconst HERE = dirname(fileURLToPath(import.meta.url))\nconst SCAFFOLD_ROOT = resolve(HERE, '..', 'scaffold')\n\nexport type PackageManager = 'npm' | 'pnpm' | 'yarn-classic' | 'yarn-berry' | 'bun'\n\ninterface Answers {\n name: string\n directory: string\n currency: 'GBP' | 'USD' | 'EUR'\n template: 'astro' | 'nextjs'\n seedDemo: boolean\n}\n\n/**\n * Runs a command in `cwd` (with `env` when given, else the process environment) and rejects on a non-zero exit.\n * Injected into `main` so tests do not shell out.\n */\nexport type Runner = (\n cmd: string,\n args: string[],\n cwd: string,\n env?: NodeJS.ProcessEnv,\n) => Promise<void>\n\n/** The port `renderConfig` gives the API, which serves the admin at /admin/. */\nconst API_PORT = 3001\n\n/** Each template's dev server origin, the storefront URL a new store starts with. */\nconst STOREFRONT_ORIGIN: Record<Answers['template'], string> = {\n astro: 'http://localhost:4321',\n nextjs: 'http://localhost:3000',\n}\n\ninterface AdminCredentials {\n email: string\n password: string\n}\n\n/** A fresh admin password per project (128 bits, base64url), so no two stores share the seed's default. */\nfunction newAdminCredentials(): AdminCredentials {\n return { email: 'admin@nymbal.local', password: randomBytes(16).toString('base64url') }\n}\n\n/**\n * `.env` holds the admin credentials the seed (and a first `nymbal dev`) creates the admin from, and the project's own\n * key for the values the admin's Settings encrypt (32 random bytes, base64).\n */\nasync function writeAdminEnv(dir: string, admin: AdminCredentials): Promise<void> {\n const lines = [\n '# The admin account the seed creates. Keep this file out of version control (.gitignore lists it).',\n `NYMBAL_ADMIN_EMAIL=${admin.email}`,\n `NYMBAL_ADMIN_PASSWORD=${admin.password}`,\n '',\n \"# Encrypts the keys saved in the admin's Settings. Losing it loses them: back it up with your deploy's secrets.\",\n `NYMBAL_SECRETS_KEY=${randomBytes(32).toString('base64')}`,\n '',\n ]\n await writeFile(resolve(dir, '.env'), lines.join('\\n'), { encoding: 'utf8', mode: 0o600 })\n}\n\nfunction adminSignIn(admin: AdminCredentials): string[] {\n return [\n `Admin: http://localhost:${API_PORT}/admin/`,\n ` email ${admin.email}`,\n ` password ${admin.password} (saved in .env)`,\n ]\n}\n\nexport interface MainDeps {\n run?: Runner\n}\n\n/**\n * The `packageManager` field for the package manager that launched us (`npm_config_user_agent`), read when called.\n * Without a usable user agent it is the installed npm; undefined when npm cannot be run either.\n */\nfunction packageManagerField(): string | undefined {\n const token = (process.env['npm_config_user_agent'] ?? '').split(' ')[0] ?? ''\n const match = /^(npm|pnpm|yarn|bun)\\/(\\d+\\.\\d+\\.\\d+\\S*)$/.exec(token)\n if (match) return `${match[1]}@${match[2]}`\n const npm = spawnSync('npm', ['-v'], { encoding: 'utf8', shell: process.platform === 'win32' })\n const version = npm.status === 0 ? npm.stdout.trim() : ''\n return version ? `npm@${version}` : undefined\n}\n\nexport function detectPackageManager(): PackageManager {\n const ua = process.env['npm_config_user_agent']\n if (!ua) return 'npm'\n const token = ua.split(' ')[0] ?? ''\n const slash = token.indexOf('/')\n const pm = slash >= 0 ? token.slice(0, slash) : token\n const version = slash >= 0 ? token.slice(slash + 1) : ''\n if (pm === 'pnpm') return 'pnpm'\n if (pm === 'bun') return 'bun'\n if (pm === 'yarn') {\n const major = parseInt(version.split('.')[0] ?? '1', 10)\n return major < 2 ? 'yarn-classic' : 'yarn-berry'\n }\n return 'npm'\n}\n\nfunction installCmd(pm: PackageManager): [string, string[]] {\n switch (pm) {\n case 'pnpm':\n return ['pnpm', ['install']]\n case 'bun':\n return ['bun', ['install']]\n case 'yarn-classic':\n case 'yarn-berry':\n return ['yarn', ['install']]\n default:\n return ['npm', ['install']]\n }\n}\n\nfunction seedCmd(pm: PackageManager): [string, string[]] {\n switch (pm) {\n case 'pnpm':\n return ['pnpm', ['exec', 'nymbal', 'seed']]\n case 'bun':\n return ['bunx', ['nymbal', 'seed']]\n case 'yarn-classic':\n return ['yarn', ['run', 'nymbal', 'seed']]\n case 'yarn-berry':\n return ['yarn', ['exec', 'nymbal', 'seed']]\n default:\n return ['npx', ['nymbal', 'seed']]\n }\n}\n\nfunction devCmd(pm: PackageManager): string {\n switch (pm) {\n case 'pnpm':\n return 'pnpm dev'\n case 'bun':\n return 'bun dev'\n case 'yarn-classic':\n case 'yarn-berry':\n return 'yarn dev'\n default:\n return 'npm run dev'\n }\n}\n\nconst TEMPLATES = ['astro', 'nextjs'] as const\nconst CURRENCIES = ['GBP', 'USD', 'EUR'] as const\n\nexport interface CliFlags {\n name?: string\n template?: (typeof TEMPLATES)[number]\n currency?: (typeof CURRENCIES)[number]\n yes: boolean\n /** Present (false) only with `--no-install`. */\n install?: boolean\n}\n\n/** A command-line flag that is missing its value or names a value outside the allowed set. */\nexport class CliFlagError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'CliFlagError'\n }\n}\n\nfunction oneOf<T extends string>(flag: string, value: string, allowed: readonly T[]): T {\n if ((allowed as readonly string[]).includes(value)) return value as T\n throw new CliFlagError(`Unknown ${flag} \"${value}\". Allowed: ${allowed.join(', ')}`)\n}\n\n/** Parses process.argv (node and script first): --name, --template and --currency take `--flag v` or `--flag=v`. */\nexport function parseCliFlags(argv: string[]): CliFlags {\n const flags: CliFlags = { yes: false }\n const args = argv.slice(2)\n let positional: string | undefined\n for (let i = 0; i < args.length; i++) {\n const arg = args[i]!\n if (arg === '--yes' || arg === '-y') {\n flags.yes = true\n continue\n }\n if (arg === '--no-install') {\n flags.install = false\n continue\n }\n const match = /^--(name|template|currency)(?:=(.*))?$/s.exec(arg)\n if (match) {\n const flag = match[1]!\n let value = match[2]\n if (value === undefined) {\n const next = args[i + 1]\n if (next === undefined || next.startsWith('-'))\n throw new CliFlagError(`--${flag} needs a value`)\n value = next\n i++\n }\n if (flag === 'name') flags.name = value\n else if (flag === 'template') flags.template = oneOf('--template', value, TEMPLATES)\n else flags.currency = oneOf('--currency', value, CURRENCIES)\n } else if (!arg.startsWith('-') && positional === undefined) {\n positional = arg\n }\n }\n if (flags.name === undefined && positional !== undefined) flags.name = positional\n return flags\n}\n\nexport async function main(argv: string[] = process.argv, deps: MainDeps = {}): Promise<void> {\n const run = deps.run ?? runCmd\n let flags: CliFlags\n try {\n flags = parseCliFlags(argv)\n } catch (err) {\n if (!(err instanceof CliFlagError)) throw err\n process.stderr.write(`Error: ${err.message}\\n`)\n process.exit(1)\n }\n\n const pm = detectPackageManager()\n\n if (flags.yes) {\n if (!flags.name) {\n process.stderr.write('Error: --yes requires --name or a positional name argument\\n')\n process.exit(1)\n }\n const name = flags.name.trim()\n const answers: Answers = {\n name,\n directory: toDirectoryName(name),\n currency: flags.currency ?? 'GBP',\n template: flags.template ?? 'astro',\n seedDemo: true,\n }\n const targetDir = resolve(process.cwd(), answers.directory)\n if (existsSync(targetDir)) {\n const entries = await readdir(targetDir)\n if (entries.length > 0) {\n process.stderr.write(\n `Error: Directory ${answers.directory} already exists and is not empty.\\n`,\n )\n process.exit(1)\n }\n } else {\n await mkdir(targetDir, { recursive: true })\n }\n await scaffold(targetDir, answers)\n const admin = newAdminCredentials()\n await writeAdminEnv(targetDir, admin)\n process.stdout.write(`Created ${answers.directory}\\n`)\n if (flags.install !== false) {\n await installAndSeed(targetDir, pm, answers.seedDemo, run, admin)\n } else {\n process.stdout.write(`Next: cd ${answers.directory} && ${installCmd(pm)[0]} install\\n`)\n }\n process.stdout.write(`${adminSignIn(admin).join('\\n')}\\n`)\n return\n }\n\n intro(pc.cyan(pc.bold('◆ create-nymbal-app')))\n\n const name = flags.name\n ? flags.name\n : ((await text({\n message: 'Store name',\n placeholder: 'My Store',\n validate: (v) => (!v || v.trim().length === 0 ? 'Required' : undefined),\n })) as string | symbol)\n\n if (isCancel(name)) return cancel('Cancelled')\n\n type Currency = 'GBP' | 'USD' | 'EUR'\n const currencyOptions: { value: Currency; label: string }[] = [\n { value: 'GBP', label: 'GBP — British Pound' },\n { value: 'USD', label: 'USD — US Dollar' },\n { value: 'EUR', label: 'EUR — Euro' },\n ]\n const currency = await select({\n message: 'Store currency',\n options: currencyOptions,\n initialValue: 'GBP' as Currency,\n })\n\n if (isCancel(currency)) return cancel('Cancelled')\n\n type Template = 'astro' | 'nextjs'\n const templateOptions: { value: Template; label: string }[] = [\n { value: 'astro', label: 'Astro (recommended — performance-first)' },\n { value: 'nextjs', label: 'Next.js (migration-friendly)' },\n ]\n const template = await select({\n message: 'Storefront template',\n options: templateOptions,\n initialValue: 'astro' as Template,\n })\n\n if (isCancel(template)) return cancel('Cancelled')\n\n const seedDemo = (await confirm({\n message: 'Generate demo content?',\n initialValue: true,\n })) as boolean | symbol\n\n if (isCancel(seedDemo)) return cancel('Cancelled')\n\n const shouldInstall =\n flags.install === false\n ? false\n : ((await confirm({\n message: 'Install dependencies now?',\n initialValue: true,\n })) as boolean | symbol)\n\n if (isCancel(shouldInstall)) return cancel('Cancelled')\n\n const answers: Answers = {\n name: String(name).trim(),\n directory: toDirectoryName(String(name).trim()),\n currency: currency as 'GBP' | 'USD' | 'EUR',\n template: template as 'astro' | 'nextjs',\n seedDemo: seedDemo as boolean,\n }\n\n const targetDir = resolve(process.cwd(), answers.directory)\n if (existsSync(targetDir)) {\n const entries = await readdir(targetDir)\n if (entries.length > 0) {\n cancel(`Directory ${answers.directory} already exists and is not empty.`)\n process.exit(1)\n }\n } else {\n await mkdir(targetDir, { recursive: true })\n }\n\n note(pc.dim(`Scaffolding into ${targetDir}`), 'Creating project')\n\n await scaffold(targetDir, answers)\n const admin = newAdminCredentials()\n await writeAdminEnv(targetDir, admin)\n\n if (shouldInstall) {\n await installAndSeed(targetDir, pm, answers.seedDemo, run, admin)\n }\n\n const cmd = devCmd(pm)\n const nextSteps = [` ${pc.cyan('cd')} ${answers.directory}`]\n if (!shouldInstall) {\n const [ic] = installCmd(pm)\n nextSteps.push(` ${pc.cyan(ic + ' install')}`)\n }\n nextSteps.push(` ${pc.cyan(cmd)}`)\n\n outro(\n [pc.green(`✓ Created ${answers.directory}`), '', ...nextSteps, '', ...adminSignIn(admin)].join(\n '\\n',\n ),\n )\n}\n\n/** Install with the detected package manager, then seed through the project's own `nymbal` bin. */\nasync function installAndSeed(\n dir: string,\n pm: PackageManager,\n seedDemo: boolean,\n run: Runner,\n admin: AdminCredentials,\n): Promise<void> {\n const [installBin, installArgs] = installCmd(pm)\n process.stdout.write(`Running ${installBin} install (this may take a moment)...\\n`)\n await run(installBin, installArgs, dir)\n if (seedDemo) {\n process.stdout.write('Seeding demo content...\\n')\n const [seedBin, seedArgs] = seedCmd(pm)\n // Explicit, so a value exported in the shell cannot replace the one in .env and the outro.\n await run(seedBin, seedArgs, dir, {\n ...process.env,\n NYMBAL_ADMIN_EMAIL: admin.email,\n NYMBAL_ADMIN_PASSWORD: admin.password,\n })\n }\n}\n\nexport async function scaffold(dir: string, answers: Answers): Promise<void> {\n // Copy the chosen template directly into dir (flat — no storefront/ subdirectory)\n await copyScaffoldDir(resolve(SCAFFOLD_ROOT, 'templates', answers.template), dir)\n\n // Overlay the project layer (scaffold/project/<template>) on top of the template\n // defaults. Project files WIN on path collision — this is the override model:\n // anything in the project layer shadows the template default at the same path.\n // scaffold/project/ lives outside scaffold/templates/, so sync-scaffold's\n // rm -rf of scaffold/templates/* never deletes it.\n const projectLayer = resolve(SCAFFOLD_ROOT, 'project', answers.template)\n if (existsSync(projectLayer)) {\n await copyScaffoldDir(projectLayer, dir)\n }\n\n // Write nymbal.config.ts (answers-dependent, so generated at runtime)\n await writeFile(resolve(dir, 'nymbal.config.ts'), renderConfig(answers), 'utf8')\n\n // Patch the copied package.json: set name to the project directory name\n await patchPackageJson(dir, answers.directory)\n}\n\nasync function patchPackageJson(dir: string, name: string): Promise<void> {\n const pkgPath = resolve(dir, 'package.json')\n const pkg = JSON.parse(await readFile(pkgPath, 'utf8')) as Record<string, unknown>\n pkg['name'] = name\n pkg['private'] = true\n const packageManager = packageManagerField()\n if (packageManager) pkg['packageManager'] = packageManager\n await writeFile(pkgPath, JSON.stringify(pkg, null, 2) + '\\n', 'utf8')\n}\n\nasync function copyScaffoldDir(src: string, dest: string): Promise<void> {\n if (!existsSync(src)) {\n throw new Error(`Scaffold directory not found: ${src}`)\n }\n await cp(src, dest, {\n recursive: true,\n filter: (source) => !source.endsWith('node_modules'),\n })\n await renameDotFiles(dest)\n}\n\nasync function renameDotFiles(dir: string): Promise<void> {\n // Non-recursive: only rename _dot.* files at the project root.\n // All shared dotfiles (_dot.gitignore, _dot.env.example) live at template root.\n const entries = await readdir(dir, { withFileTypes: true })\n for (const entry of entries) {\n if (!entry.isDirectory() && entry.name.startsWith('_dot.')) {\n const full = resolve(dir, entry.name)\n const renamed = resolve(dir, '.' + entry.name.slice(5))\n await writeFile(renamed, await readFile(full))\n await rm(full)\n }\n }\n}\n\nfunction renderConfig(answers: Answers): string {\n return `import { defineConfig, env } from '@nymbalhq/config'\n\nexport default defineConfig({\n store: {\n name: '${escape(answers.name)}',\n currency: '${answers.currency}',\n locale: '${defaultLocale(answers.currency)}',\n timezone: '${defaultTimezone(answers.currency)}',\n // The storefront's public origin: the order email links to its order page. Set it for production.\n url: env('NYMBAL_STOREFRONT_URL', '${STOREFRONT_ORIGIN[answers.template]}'),\n },\n\n template: '${answers.template}',\n\n infrastructure: {\n commandStore: 'sqlite',\n documentStore: 'in-memory',\n eventBus: 'in-process',\n },\n\n security: {\n adapter: 'middleware',\n rateLimit: {\n '/checkout': { requests: 10, window: '1m', action: 'block' },\n '/auth/*': { requests: 5, window: '1m', action: 'challenge' },\n '/api/*': { requests: 100, window: '1m', action: 'throttle' },\n '/webhooks/*': { requests: 200, window: '1m', action: 'throttle' },\n },\n botProtection: { mode: 'managed', allowList: ['googlebot', 'bingbot', 'stripe-webhooks'] },\n headers: {\n hsts: true,\n contentSecurityPolicy: 'strict',\n referrerPolicy: 'strict-origin-when-cross-origin',\n xFrameOptions: 'deny',\n },\n csrf: true,\n },\n\n commerce: {\n payments: { provider: 'native' },\n email: { provider: 'native' },\n reviews: { provider: 'native' },\n search: { provider: 'native' },\n analytics: { provider: 'native' },\n shipping: { provider: 'native' },\n tax: { provider: 'native' },\n ai: { provider: 'none' },\n },\n\n http: {\n adapter: 'fastify',\n port: ${API_PORT},\n },\n\n deployment: {\n strategy: 'standard',\n },\n\n features: {\n staging: false,\n heartbeat: false,\n autoUpdates: false,\n },\n})\n`\n}\n\nfunction defaultLocale(currency: Answers['currency']): string {\n return currency === 'USD' ? 'en-US' : 'en-GB'\n}\n\nfunction defaultTimezone(currency: Answers['currency']): string {\n return currency === 'USD' ? 'America/New_York' : 'Europe/London'\n}\n\nfunction escape(v: string): string {\n return v.replace(/'/g, \"\\\\'\")\n}\n\nfunction toDirectoryName(name: string): string {\n return name\n .toLowerCase()\n .replace(/[^a-z0-9-_ ]/g, '')\n .trim()\n .replace(/\\s+/g, '-')\n}\n\nconst runCmd: Runner = (cmd, args, cwd, env = process.env) => {\n return new Promise((resolve, reject) => {\n const child = spawn(cmd, args, { cwd, env, stdio: 'inherit', shell: false })\n child.on('error', reject)\n child.on('exit', (code) => {\n if (code === 0) return resolve()\n reject(new Error(`${cmd} ${args.join(' ')} exited with ${code}`))\n })\n })\n}\n"],"mappings":";AAAA,SAAS,IAAI,UAAU,OAAO,SAAS,IAAI,iBAAiB;AAC5D,SAAS,kBAAkB;AAC3B,SAAS,SAAS,eAAe;AACjC,SAAS,qBAAqB;AAC9B,SAAS,OAAO,iBAAiB;AACjC,SAAS,mBAAmB;AAC5B,SAAS,QAAQ,SAAS,OAAO,UAAU,MAAM,OAAO,QAAQ,YAAY;AAC5E,OAAO,QAAQ;AAEf,IAAM,OAAO,QAAQ,cAAc,YAAY,GAAG,CAAC;AACnD,IAAM,gBAAgB,QAAQ,MAAM,MAAM,UAAU;AAwBpD,IAAM,WAAW;AAGjB,IAAM,oBAAyD;AAAA,EAC7D,OAAO;AAAA,EACP,QAAQ;AACV;AAQA,SAAS,sBAAwC;AAC/C,SAAO,EAAE,OAAO,sBAAsB,UAAU,YAAY,EAAE,EAAE,SAAS,WAAW,EAAE;AACxF;AAMA,eAAe,cAAc,KAAa,OAAwC;AAChF,QAAM,QAAQ;AAAA,IACZ;AAAA,IACA,sBAAsB,MAAM,KAAK;AAAA,IACjC,yBAAyB,MAAM,QAAQ;AAAA,IACvC;AAAA,IACA;AAAA,IACA,sBAAsB,YAAY,EAAE,EAAE,SAAS,QAAQ,CAAC;AAAA,IACxD;AAAA,EACF;AACA,QAAM,UAAU,QAAQ,KAAK,MAAM,GAAG,MAAM,KAAK,IAAI,GAAG,EAAE,UAAU,QAAQ,MAAM,IAAM,CAAC;AAC3F;AAEA,SAAS,YAAY,OAAmC;AACtD,SAAO;AAAA,IACL,2BAA2B,QAAQ;AAAA,IACnC,eAAe,MAAM,KAAK;AAAA,IAC1B,eAAe,MAAM,QAAQ;AAAA,EAC/B;AACF;AAUA,SAA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;AAC3E,UAAM,GAAG,SAAS,MAAM;AACxB,UAAM,GAAG,QAAQ,CAAC,SAAS;AACzB,UAAI,SAAS,EAAG,QAAOA,SAAQ;AAC/B,aAAO,IAAI,MAAM,GAAG,GAAG,IAAI,KAAK,KAAK,GAAG,CAAC,gBAAgB,IAAI,EAAE,CAAC;AAAA,IAClE,CAAC;AAAA,EACH,CAAC;AACH;","names":["name","answers","targetDir","admin","resolve"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-nymbal-app",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Scaffold a new Nymbal commerce project",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -17,14 +17,14 @@
17
17
  "seed": "nymbal seed"
18
18
  },
19
19
  "dependencies": {
20
- "nymbal": "1.2.0",
21
- "@nymbalhq/config": "1.2.0",
22
- "@nymbalhq/platform": "1.2.0",
23
- "@nymbalhq/stack": "1.2.0",
20
+ "nymbal": "1.4.0",
21
+ "@nymbalhq/config": "1.4.0",
22
+ "@nymbalhq/platform": "1.4.0",
23
+ "@nymbalhq/stack": "1.4.0",
24
24
  "@astrojs/node": "^11.1.8",
25
- "@nymbalhq/sdk": "1.2.0",
26
- "@nymbalhq/types": "1.2.0",
27
- "@nymbalhq/web-components": "1.2.0",
25
+ "@nymbalhq/sdk": "1.4.0",
26
+ "@nymbalhq/types": "1.4.0",
27
+ "@nymbalhq/web-components": "1.4.0",
28
28
  "astro": "^7.4.0"
29
29
  },
30
30
  "devDependencies": {
@@ -33,26 +33,26 @@
33
33
  },
34
34
  "pnpm": {
35
35
  "overrides": {
36
- "nymbal": "1.2.0",
37
- "@nymbalhq/config": "1.2.0",
38
- "@nymbalhq/http": "1.2.0",
39
- "@nymbalhq/platform": "1.2.0",
40
- "@nymbalhq/react": "1.2.0",
41
- "@nymbalhq/sdk": "1.2.0",
42
- "@nymbalhq/stack": "1.2.0",
43
- "@nymbalhq/types": "1.2.0",
44
- "@nymbalhq/web-components": "1.2.0"
36
+ "nymbal": "1.4.0",
37
+ "@nymbalhq/config": "1.4.0",
38
+ "@nymbalhq/http": "1.4.0",
39
+ "@nymbalhq/platform": "1.4.0",
40
+ "@nymbalhq/react": "1.4.0",
41
+ "@nymbalhq/sdk": "1.4.0",
42
+ "@nymbalhq/stack": "1.4.0",
43
+ "@nymbalhq/types": "1.4.0",
44
+ "@nymbalhq/web-components": "1.4.0"
45
45
  }
46
46
  },
47
47
  "overrides": {
48
- "nymbal": "1.2.0",
49
- "@nymbalhq/config": "1.2.0",
50
- "@nymbalhq/http": "1.2.0",
51
- "@nymbalhq/platform": "1.2.0",
52
- "@nymbalhq/react": "1.2.0",
53
- "@nymbalhq/sdk": "1.2.0",
54
- "@nymbalhq/stack": "1.2.0",
55
- "@nymbalhq/types": "1.2.0",
56
- "@nymbalhq/web-components": "1.2.0"
48
+ "nymbal": "1.4.0",
49
+ "@nymbalhq/config": "1.4.0",
50
+ "@nymbalhq/http": "1.4.0",
51
+ "@nymbalhq/platform": "1.4.0",
52
+ "@nymbalhq/react": "1.4.0",
53
+ "@nymbalhq/sdk": "1.4.0",
54
+ "@nymbalhq/stack": "1.4.0",
55
+ "@nymbalhq/types": "1.4.0",
56
+ "@nymbalhq/web-components": "1.4.0"
57
57
  }
58
58
  }
@@ -4,8 +4,15 @@ import type {
4
4
  ProductSearchResult,
5
5
  ReviewsListResult,
6
6
  } from '@nymbalhq/sdk'
7
- import { DEFAULT_PRODUCT_SORT, PRODUCT_SORT_KEYS } from '@nymbalhq/types'
8
- import type { Cart, Category, Order, ProductSortKey, StoreCapabilities } from '@nymbalhq/types'
7
+ import { DEFAULT_PRODUCT_SORT, ORDER_KEY_HEADER, PRODUCT_SORT_KEYS } from '@nymbalhq/types'
8
+ import type {
9
+ AlertKind,
10
+ Cart,
11
+ Category,
12
+ ProductSortKey,
13
+ ShopperOrder,
14
+ StoreCapabilities,
15
+ } from '@nymbalhq/types'
9
16
 
10
17
  const API_URL = import.meta.env.NYMBAL_API_URL ?? 'http://localhost:3001'
11
18
 
@@ -78,15 +85,6 @@ export async function loadProduct(slug: string): Promise<DenormalisedProduct | n
78
85
  return apiData<DenormalisedProduct>(`/api/products/${encodeURIComponent(slug)}`)
79
86
  }
80
87
 
81
- export async function fetchProduct(slug: string): Promise<DenormalisedProduct | null> {
82
- try {
83
- return await loadProduct(slug)
84
- } catch (err) {
85
- console.error('[api] fetchProduct failed', err)
86
- return null
87
- }
88
- }
89
-
90
88
  /** The store's categories as the API sent them; rejects when the API fails. */
91
89
  export async function loadCategories(): Promise<Category[]> {
92
90
  const categories = await apiData<Category[]>('/api/categories')
@@ -107,16 +105,21 @@ export async function fetchCategories(): Promise<Category[]> {
107
105
  }
108
106
  }
109
107
 
110
- export async function fetchOrder(orderNumber: string): Promise<Order | null> {
111
- try {
112
- const res = await fetch(`${API_URL}/api/orders/${encodeURIComponent(orderNumber)}`)
113
- if (!res.ok) return null
114
- const envelope = (await res.json()) as { data: Order }
115
- return envelope.data ?? null
116
- } catch (err) {
117
- console.error('[api] fetchOrder failed', err)
118
- return null
119
- }
108
+ /**
109
+ * The order its key opens, `key` being the confirmation URL's `?key=`. Null on a 404, which the API answers alike for
110
+ * an unknown number and for an order read without its key; rejects when the API fails, so a failed read is a 500 and
111
+ * never a not-found page for an order the shopper has. The key goes in a header, never in the API's URL.
112
+ */
113
+ export async function fetchOrder(orderNumber: string, key?: string): Promise<ShopperOrder | null> {
114
+ const path = `/api/orders/${encodeURIComponent(orderNumber)}`
115
+ const res = await fetch(`${API_URL}${path}`, {
116
+ headers: key ? { [ORDER_KEY_HEADER]: key } : {},
117
+ })
118
+ if (res.status === 404) return null
119
+ if (!res.ok) throw new ApiUnavailableError(`GET ${path} answered ${res.status}`)
120
+ const envelope = (await res.json()) as { data?: ShopperOrder | null }
121
+ if (!envelope.data) throw new ApiUnavailableError(`GET ${path} answered no data`)
122
+ return envelope.data
120
123
  }
121
124
 
122
125
  export async function fetchReviews(productId: string): Promise<ReviewsListResult> {
@@ -193,3 +196,32 @@ export async function fetchSearch(
193
196
  return null
194
197
  }
195
198
  }
199
+
200
+ /** An alert link's token posted to the API from this server; null when the API refuses the link (404, or 400). */
201
+ async function postAlertToken<T>(path: string, token: string): Promise<T | null> {
202
+ const res = await fetch(`${API_URL}${path}`, {
203
+ method: 'POST',
204
+ headers: { 'content-type': 'application/json', accept: 'application/json' },
205
+ body: JSON.stringify({ token }),
206
+ })
207
+ if (res.status === 404 || res.status === 400) return null
208
+ if (!res.ok) throw new ApiUnavailableError(`POST ${path} answered ${res.status}`)
209
+ return ((await res.json()) as { data: T }).data
210
+ }
211
+
212
+ export interface AlertConfirmation {
213
+ kind: AlertKind
214
+ product: { name: string; slug: string }
215
+ }
216
+
217
+ /** Confirms the alert a confirmation email's link names; null when the link is not valid; rejects when the API fails. */
218
+ export function confirmAlert(token: string): Promise<AlertConfirmation | null> {
219
+ return postAlertToken<AlertConfirmation>('/api/alerts/confirm', token)
220
+ }
221
+
222
+ /** Stops the alert an email's unsubscribe link names; false when the link is not valid; rejects when the API fails. */
223
+ export async function unsubscribeAlert(token: string): Promise<boolean> {
224
+ return (
225
+ (await postAlertToken<{ status: 'unsubscribed' }>('/api/alerts/unsubscribe', token)) !== null
226
+ )
227
+ }
@@ -1,6 +1,9 @@
1
1
  ---
2
2
  import '../styles/pages/error.css'
3
3
  import BaseLayout from '../layouts/BaseLayout.astro'
4
+
5
+ // An order page's not-found render, at a URL that may carry a key: the rewrite drops that page's own headers.
6
+ if (Astro.originPathname.startsWith('/order/')) Astro.response.headers.set('Referrer-Policy', 'no-referrer')
4
7
  ---
5
8
 
6
9
  <BaseLayout title="Page Not Found | Nymbal" description="The page you're looking for doesn't exist.">
@@ -13,8 +13,12 @@ import AccountLayout from '../../../layouts/AccountLayout.astro'
13
13
  </AccountLayout>
14
14
 
15
15
  <script>
16
+ import { NymbalApiError } from '@nymbalhq/sdk'
16
17
  import { client } from '../../../lib/client.js'
17
18
  import { escapeHtml, formatPrice, formatDate } from '../../../lib/format.js'
19
+ import { NymbalOrderTimeline } from '@nymbalhq/web-components/elements/nymbal-order-timeline'
20
+
21
+ NymbalOrderTimeline.define()
18
22
 
19
23
  const container = document.getElementById('order-detail-container')
20
24
  const orderNumber = container?.dataset.orderNumber
@@ -35,6 +39,8 @@ import AccountLayout from '../../../layouts/AccountLayout.astro'
35
39
  <span class="order-status status-${escapeHtml(order.status)}">${escapeHtml(order.status)}</span>
36
40
  </div>
37
41
 
42
+ ${order.timeline?.length ? `<nymbal-order-timeline style="display: block; margin-bottom: var(--nymbal-spacing-lg, 1.5rem);" entries="${escapeHtml(JSON.stringify(order.timeline))}"></nymbal-order-timeline>` : ''}
43
+
38
44
  <div class="confirmation-card">
39
45
  <h2 class="confirmation-card-title">Items</h2>
40
46
  <div class="confirmation-items" style="margin-top: 0; padding-top: 0; border-top: none;">
@@ -93,11 +99,13 @@ import AccountLayout from '../../../layouts/AccountLayout.astro'
93
99
 
94
100
  <a href="/account/orders" class="btn btn-secondary" style="margin-top: var(--nymbal-spacing-md, 1rem);">Back to Orders</a>
95
101
  `
96
- } catch {
102
+ } catch (err) {
103
+ // The API answers another shopper's order as it answers a number no order has: a 404 is not found, not a failure.
104
+ const notFound = err instanceof NymbalApiError && err.status === 404
97
105
  container.innerHTML = `
98
106
  <div class="account-empty">
99
- <h2 class="account-empty-title">Unable to load order</h2>
100
- <p class="account-empty-text">Please try again later.</p>
107
+ <h2 class="account-empty-title">${notFound ? 'Order Not Found' : 'Unable to load order'}</h2>
108
+ <p class="account-empty-text">${notFound ? 'This order could not be found.' : 'Please try again later.'}</p>
101
109
  <a href="/account/orders" class="btn btn-secondary">Back to Orders</a>
102
110
  </div>
103
111
  `
@@ -0,0 +1,59 @@
1
+ ---
2
+ import '../../styles/pages/error.css'
3
+ import BaseLayout from '../../layouts/BaseLayout.astro'
4
+ import { confirmAlert } from '../../lib/api'
5
+
6
+ // Opening the link only shows the button, so a mail scanner that fetches it confirms nothing. The press posts the
7
+ // token back here, and this server posts it on to the API, so the browser needs no CSRF cookie.
8
+ const pressed = Astro.request.method === 'POST'
9
+ const token = pressed
10
+ ? String((await Astro.request.formData()).get('token') ?? '')
11
+ : (Astro.url.searchParams.get('token') ?? '')
12
+ const confirmed = pressed && token !== '' ? await confirmAlert(token) : null
13
+ ---
14
+
15
+ <BaseLayout title="Email alert | Nymbal" description="Confirm your email alert.">
16
+ {!pressed && token !== '' ? (
17
+ <form method="post" class="error-page" data-testid="alert-confirm-form" id="alert-link-form">
18
+ <h1 class="error-title">Confirm your email alert</h1>
19
+ <p class="error-message">Press the button to start the alert this email asked for.</p>
20
+ <input type="hidden" name="token" value={token} />
21
+ <div class="error-actions">
22
+ <button type="submit" class="btn btn-primary" data-testid="alert-confirm-submit">Confirm alert</button>
23
+ </div>
24
+ </form>
25
+ ) : confirmed ? (
26
+ <div class="error-page" data-testid="alert-confirmed" data-kind={confirmed.kind}>
27
+ <h1 class="error-title">Your alert is on</h1>
28
+ {confirmed.kind === 'price_drop' ? (
29
+ <p class="error-message">
30
+ We'll email you when the price of <a href={`/product/${confirmed.product.slug}`}>{confirmed.product.name}</a> drops.
31
+ </p>
32
+ ) : (
33
+ <p class="error-message">
34
+ We'll email you once when <a href={`/product/${confirmed.product.slug}`}>{confirmed.product.name}</a> is back
35
+ in stock.
36
+ </p>
37
+ )}
38
+ </div>
39
+ ) : (
40
+ <div class="error-page" data-testid="alert-link-invalid">
41
+ <h1 class="error-title">This link is not valid</h1>
42
+ <p class="error-message">It may be from an older email, or the alert has been stopped.</p>
43
+ <div class="error-actions">
44
+ <a href="/products" class="btn btn-primary">Browse Products</a>
45
+ </div>
46
+ </div>
47
+ )}
48
+ </BaseLayout>
49
+
50
+ <script>
51
+ import { submitOnce } from '../../lib/submit-once'
52
+
53
+ // The native submit sends the form once; a second click or Enter while it is on its way is ignored.
54
+ const form = document.getElementById('alert-link-form') as HTMLFormElement | null
55
+ submitOnce(form, () => {
56
+ form?.submit()
57
+ return 'leaving'
58
+ })
59
+ </script>
@@ -0,0 +1,53 @@
1
+ ---
2
+ import '../../styles/pages/error.css'
3
+ import BaseLayout from '../../layouts/BaseLayout.astro'
4
+ import { unsubscribeAlert } from '../../lib/api'
5
+
6
+ // Opening the link only shows the button, so a mail scanner that fetches it stops nothing. The press posts the token
7
+ // back here, and this server posts it on to the API, which holds no CSRF cookie.
8
+ const pressed = Astro.request.method === 'POST'
9
+ const token = pressed
10
+ ? String((await Astro.request.formData()).get('token') ?? '')
11
+ : (Astro.url.searchParams.get('token') ?? '')
12
+ const stopped = pressed && token !== '' ? await unsubscribeAlert(token) : false
13
+ ---
14
+
15
+ <BaseLayout title="Back-in-stock alert | Nymbal" description="Stop a back-in-stock alert.">
16
+ {!pressed && token !== '' ? (
17
+ <form method="post" class="error-page" data-testid="alert-unsubscribe-form" id="alert-link-form">
18
+ <h1 class="error-title">Stop this email alert</h1>
19
+ <p class="error-message">Press the button and we won't email you about this product again.</p>
20
+ <input type="hidden" name="token" value={token} />
21
+ <div class="error-actions">
22
+ <button type="submit" class="btn btn-primary" data-testid="alert-unsubscribe-submit">Unsubscribe</button>
23
+ </div>
24
+ </form>
25
+ ) : stopped ? (
26
+ <div class="error-page" data-testid="alert-unsubscribed">
27
+ <h1 class="error-title">Your alert is off</h1>
28
+ <p class="error-message">We won't email you about this product again.</p>
29
+ <div class="error-actions">
30
+ <a href="/products" class="btn btn-primary">Browse Products</a>
31
+ </div>
32
+ </div>
33
+ ) : (
34
+ <div class="error-page" data-testid="alert-link-invalid">
35
+ <h1 class="error-title">This link is not valid</h1>
36
+ <p class="error-message">Check that the whole link from the email was opened.</p>
37
+ <div class="error-actions">
38
+ <a href="/products" class="btn btn-primary">Browse Products</a>
39
+ </div>
40
+ </div>
41
+ )}
42
+ </BaseLayout>
43
+
44
+ <script>
45
+ import { submitOnce } from '../../lib/submit-once'
46
+
47
+ // The native submit sends the form once; a second click or Enter while it is on its way is ignored.
48
+ const form = document.getElementById('alert-link-form') as HTMLFormElement | null
49
+ submitOnce(form, () => {
50
+ form?.submit()
51
+ return 'leaving'
52
+ })
53
+ </script>
@@ -4,7 +4,7 @@ import BaseLayout from '../../layouts/BaseLayout.astro'
4
4
  import NymbalElement from '@nymbalhq/web-components/astro'
5
5
  import { cardImageOf, cardProductOf } from '@nymbalhq/web-components/ssr'
6
6
  import { PRODUCT_SORT_LABELS } from '@nymbalhq/types'
7
- import { fetchProducts, fetchCategories, fetchCapabilities, sortFromUrl } from '../../lib/api'
7
+ import { fetchProducts, loadCategories, fetchCapabilities, sortFromUrl } from '../../lib/api'
8
8
 
9
9
  const { slug } = Astro.params
10
10
  const capabilities = await fetchCapabilities()
@@ -13,21 +13,23 @@ const sort = sortFromUrl(Astro.url, capabilities?.catalog)
13
13
 
14
14
  const [productResult, categories] = await Promise.all([
15
15
  fetchProducts({ limit: 24, category: slug, sort }),
16
- fetchCategories(),
16
+ // Rejects when the API fails, so a failed read is a 500 and never a 404 for a category the store has.
17
+ loadCategories(),
17
18
  ])
19
+ const category = categories.find((c) => c.slug === slug)
20
+ if (!category) return Astro.rewrite('/404')
18
21
 
19
22
  const products = productResult.items.map(cardProductOf)
20
23
  // The first card's image is the page's LCP, and the preload scanner never reaches it inside the grid's shadow root:
21
24
  // the head starts it.
22
25
  const firstImage = products[0] === undefined ? null : cardImageOf(products[0]).url
23
- const category = categories.find((c) => c.slug === slug)
24
- const categoryName = category?.name ?? slug ?? 'Category'
26
+ const categoryName = category.name
25
27
  const facets = productResult.facets ?? []
26
28
  ---
27
29
 
28
30
  <BaseLayout
29
31
  title={`${categoryName} | Nymbal`}
30
- description={category?.description ?? `Browse ${categoryName} products.`}
32
+ description={category.description ?? `Browse ${categoryName} products.`}
31
33
  >
32
34
  {firstImage && <link slot="head" rel="preload" as="image" href={firstImage} fetchpriority="high" />}
33
35
  <div class="container section">
@@ -35,7 +37,7 @@ const facets = productResult.facets ?? []
35
37
 
36
38
  <div class="plp-header">
37
39
  <h1 class="plp-title">{categoryName}</h1>
38
- {category?.description && (
40
+ {category.description && (
39
41
  <p style="font-size: var(--nymbal-font-size-sm, 0.875rem); color: var(--nymbal-color-text-muted, #71717a); margin-bottom: var(--nymbal-spacing-sm, 0.5rem);">
40
42
  {category.description}
41
43
  </p>
@@ -38,7 +38,7 @@ const paymentElement = `<nymbal-payment-element slot="payment" data-testid="paym
38
38
 
39
39
  // The element places the order; the page only goes to it.
40
40
  document.addEventListener('nymbal:checkout:placed', (event) => {
41
- const { orderNumber } = (event as CustomEvent<{ orderNumber: string }>).detail
42
- window.location.href = `/order/${encodeURIComponent(orderNumber)}`
41
+ const { orderNumber, orderKey } = (event as CustomEvent<{ orderNumber: string; orderKey?: string }>).detail
42
+ window.location.href = `/order/${encodeURIComponent(orderNumber)}${orderKey ? `?key=${encodeURIComponent(orderKey)}` : ''}`
43
43
  })
44
44
  </script>
@@ -40,13 +40,20 @@ const jsonLd = organizationJsonLd('Nymbal', Astro.url.origin)
40
40
  </section>
41
41
 
42
42
  <NewsletterSignup />
43
+
44
+ <!-- The shopper's own list, read in the browser: a bare tag, so no shopper's list is in the page's HTML. -->
45
+ <div class="container">
46
+ <nymbal-recently-viewed data-testid="recently-viewed"></nymbal-recently-viewed>
47
+ </div>
43
48
  </BaseLayout>
44
49
 
45
50
  <script>
46
51
  import '../lib/client.js'
47
52
  import { NymbalCategoryNav } from '@nymbalhq/web-components/elements/nymbal-category-nav'
48
53
  import { NymbalProductGrid } from '@nymbalhq/web-components/elements/nymbal-product-grid'
54
+ import { NymbalRecentlyViewed } from '@nymbalhq/web-components/elements/nymbal-recently-viewed'
49
55
 
50
56
  NymbalCategoryNav.define()
51
57
  NymbalProductGrid.define()
58
+ NymbalRecentlyViewed.define()
52
59
  </script>
@@ -5,10 +5,16 @@ import NymbalElement from '@nymbalhq/web-components/astro'
5
5
  import { fetchOrder } from '../../lib/api'
6
6
  import { isPaid, orderHeading } from '../../lib/order-status'
7
7
 
8
+ // The URL carries the order's key (`?key=`), so nothing this page links to or loads may be told the URL: a header
9
+ // and the meta tag below. The rewrite to /404 drops the header, so the not-found page sets its own.
10
+ Astro.response.headers.set('Referrer-Policy', 'no-referrer')
11
+
8
12
  const { orderNumber } = Astro.params
9
- const order = await fetchOrder(orderNumber!)
13
+ const key = Astro.url.searchParams.get('key') ?? undefined
14
+ // Rejects when the API fails, so a failed read is a 500 and never a 404 for an order the shopper has.
15
+ const order = await fetchOrder(orderNumber!, key)
10
16
 
11
- if (!order) return Astro.redirect('/404')
17
+ if (!order) return Astro.rewrite('/404')
12
18
 
13
19
  const summary = {
14
20
  items: JSON.stringify(
@@ -33,6 +39,7 @@ const paid = isPaid(order.status)
33
39
  ---
34
40
 
35
41
  <BaseLayout title={`${heading} | Nymbal`} description="Your order with Nymbal.">
42
+ <meta slot="head" name="referrer" content="no-referrer" />
36
43
  <div class="container section">
37
44
  <div class="confirmation-page" data-order-number={order.orderNumber} data-order-status={order.status}>
38
45
  {paid && (
@@ -75,6 +82,8 @@ const paid = isPaid(order.status)
75
82
  </dl>
76
83
  </div>
77
84
 
85
+ <NymbalElement tag="nymbal-order-timeline" attributes={{ class: 'confirmation-summary', entries: JSON.stringify(order.timeline ?? []) }} />
86
+
78
87
  <NymbalElement tag="nymbal-order-summary" attributes={{ class: 'confirmation-summary', ...summary }} />
79
88
 
80
89
  {shippingAddress && (
@@ -100,6 +109,8 @@ const paid = isPaid(order.status)
100
109
  <script>
101
110
  import '../../scripts/order-status.js'
102
111
  import { NymbalOrderSummary } from '@nymbalhq/web-components/elements/nymbal-order-summary'
112
+ import { NymbalOrderTimeline } from '@nymbalhq/web-components/elements/nymbal-order-timeline'
103
113
 
104
114
  NymbalOrderSummary.define()
115
+ NymbalOrderTimeline.define()
105
116
  </script>