@thorprovider/create-thor-app 4.1.2 → 4.1.4

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.
package/dist/index.js CHANGED
@@ -374,8 +374,7 @@ function readSource(sourceDir, relPath) {
374
374
  if (!existsSync5(abs)) return "";
375
375
  return readFileSync4(abs, "utf-8");
376
376
  }
377
- function buildAgentsMd(name) {
378
- return `# ${name} \u2014 Thor Commerce Storefront
377
+ var DEFAULT_AGENTS_MD = `# Thor Commerce Storefront
379
378
 
380
379
  ## CRITICAL
381
380
  ALWAYS import from @thorprovider/types \u2014 NEVER define Product, Cart, Collection, Money.
@@ -396,13 +395,28 @@ ALWAYS import from @thorprovider/types \u2014 NEVER define Product, Cart, Collec
396
395
  - useRegion() \u2014 @/components/providers/region-provider
397
396
  - useCommerce() \u2014 @/components/providers/commerce-provider
398
397
 
398
+ ## Runtime
399
+ - Default to mock mode when backend env is missing
400
+ - Real provider + URL + API key => live backend immediately
401
+ - Same commerce/useCart/useRegion APIs in both modes
402
+
399
403
  ## Stack
400
404
  Next.js 16, React 19, TS strict, Tailwind 4, shadcn/ui.
401
405
  Server Components default. 'use client' only for interactivity.
402
406
 
403
407
  ## Docs
404
- docs/types.md (types), docs/patterns.md (examples), docs/rules.md (constraints).
408
+ docs/types.md (types), docs/patterns.md (examples).
405
409
  `;
410
+ function applyProjectNameToAgentsMd(name, content) {
411
+ return content.replace(
412
+ /^#\s+Thor Commerce Storefront\s*$/m,
413
+ `# ${name} \u2014 Thor Commerce Storefront`
414
+ );
415
+ }
416
+ function buildAgentsMd(name, sourceDir) {
417
+ const sourceAgentsMd = readSource(sourceDir, ".agents/AGENTS.md").trim();
418
+ const baseAgentsMd = sourceAgentsMd || DEFAULT_AGENTS_MD.trim();
419
+ return applyProjectNameToAgentsMd(name, baseAgentsMd);
406
420
  }
407
421
  function buildArchitectureMd() {
408
422
  return `---
@@ -591,7 +605,7 @@ function generateAgentsDir(name, targetDir, sourceDir) {
591
605
  const skillsDir = join5(agentsDir, "skills");
592
606
  mkdirSync(contextDir, { recursive: true });
593
607
  mkdirSync(skillsDir, { recursive: true });
594
- write(join5(agentsDir, "AGENTS.md"), buildAgentsMd(name));
608
+ write(join5(agentsDir, "AGENTS.md"), buildAgentsMd(name, sourceDir));
595
609
  write(join5(contextDir, "architecture.md"), buildArchitectureMd());
596
610
  const docFiles = [
597
611
  "README.md",
@@ -821,10 +835,21 @@ function verifyValidatorConfig(targetDir) {
821
835
  log(" \u26A0\uFE0F ai-validator.json is missing required fields", c.yellow);
822
836
  return false;
823
837
  }
838
+ if (typeof config.postStreamDelayMs !== "number") {
839
+ log(" \u26A0\uFE0F ai-validator.json must define postStreamDelayMs", c.yellow);
840
+ return false;
841
+ }
824
842
  if (!Array.isArray(config.architecturalRules)) {
825
843
  log(" \u26A0\uFE0F ai-validator.json architecturalRules must be an array", c.yellow);
826
844
  return false;
827
845
  }
846
+ const hasInvalidRules = config.architecturalRules.some(
847
+ (rule) => !rule.id || !rule.filePattern || !rule.pattern || !rule.description || rule.severity !== void 0 && rule.severity !== "error" && rule.severity !== "warning"
848
+ );
849
+ if (hasInvalidRules) {
850
+ log(" \u26A0\uFE0F ai-validator.json contains invalid architecturalRules entries", c.yellow);
851
+ return false;
852
+ }
828
853
  log(" \u2713 ai-validator.json verified", c.green);
829
854
  return true;
830
855
  } catch (err) {
@@ -918,7 +943,7 @@ async function createApp(opts) {
918
943
  });
919
944
  log(" \u2713 package.json updated", c.green);
920
945
  const envOverrides = {
921
- ...commerceProvider && { NEXT_PUBLIC_COMMERCE_PROVIDER: commerceProvider },
946
+ NEXT_PUBLIC_COMMERCE_PROVIDER: commerceProvider ?? (commerceApiUrl && commerceApiKey ? "medusa" : "mock"),
922
947
  ...commerceApiUrl && { NEXT_PUBLIC_COMMERCE_API_URL: commerceApiUrl },
923
948
  ...commerceApiKey && { NEXT_PUBLIC_COMMERCE_API_KEY: commerceApiKey }
924
949
  };
@@ -1016,8 +1041,9 @@ async function createApp(opts) {
1016
1041
  ${step++}. Backend already configured (via CLI flags) \u2713`, c.green);
1017
1042
  } else {
1018
1043
  log(`
1019
- ${step++}. Configure your backend:`, c.cyan);
1020
- log(` Edit ${relPath}/.env with your commerce backend URL and API key`, c.yellow);
1044
+ ${step++}. Optional: connect a real backend later`, c.cyan);
1045
+ log(" The scaffold starts in mock mode so you can design immediately.", c.yellow);
1046
+ log(` When ready, edit ${relPath}/.env and set NEXT_PUBLIC_COMMERCE_PROVIDER, NEXT_PUBLIC_COMMERCE_API_URL, and NEXT_PUBLIC_COMMERCE_API_KEY`, c.yellow);
1021
1047
  }
1022
1048
  if (!remoteCreated && !skipRemote) {
1023
1049
  const vis = process.env.GITHUB_REPO_VISIBILITY === "public" ? "--public" : "--private";
@@ -1092,7 +1118,7 @@ if (nodeMajor < NODE_MIN_MAJOR || nodeMajor === NODE_MIN_MAJOR && nodeMinor < NO
1092
1118
  );
1093
1119
  process.exit(1);
1094
1120
  }
1095
- program.name("create-thor-app").description("Create a new Thor Commerce application").argument("[name]", "Project name (kebab-case)").option("--name <name>", "Project name (alternative to positional arg)").option("-o, --output <dir>", "Output directory (default: ./<name>)").option("--skip-git", "Skip git init").option("--skip-install", "Skip yarn install").option("--skip-remote", "Skip GitHub remote repo creation").option("--skip-vercel", "Skip Vercel project linking").option("--no-context", "Skip .agents/ directory generation").option("--no-validator", "Skip ai-validator.json injection (V0 Stop Hooks)").option("--commerce-provider <provider>", "Commerce backend provider (e.g., medusa, shopify)").option("--commerce-api-url <url>", "Commerce backend API URL").option("--commerce-api-key <key>", "Commerce publishable API key").action(async (positionalName, opts) => {
1121
+ program.name("create-thor-app").description("Create a new Thor Commerce application").argument("[name]", "Project name (kebab-case)").option("--name <name>", "Project name (alternative to positional arg)").option("-o, --output <dir>", "Output directory (default: ./<name>)").option("--skip-git", "Skip git init").option("--skip-install", "Skip yarn install").option("--skip-remote", "Skip GitHub remote repo creation").option("--skip-vercel", "Skip Vercel project linking").option("--no-context", "Skip .agents/ directory generation").option("--no-validator", "Skip ai-validator.json injection (V0 Stop Hooks)").option("--commerce-provider <provider>", "Commerce backend provider (e.g., mock, medusa, shopify)").option("--commerce-api-url <url>", "Commerce backend API URL").option("--commerce-api-key <key>", "Commerce publishable API key").action(async (positionalName, opts) => {
1096
1122
  let rawName = positionalName || opts.name || "";
1097
1123
  if (!rawName) {
1098
1124
  rawName = await promptForName();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thorprovider/create-thor-app",
3
- "version": "4.1.2",
3
+ "version": "4.1.4",
4
4
  "description": "CLI to scaffold a new Thor Commerce V0-native application",
5
5
  "type": "module",
6
6
  "bin": "./dist/index.js",
@@ -46,6 +46,7 @@ NEXT_PUBLIC_COMMERCE_API_KEY=pk_live_xxx
46
46
  - `mock` or missing live-backend env vars → storefront uses fixture-backed mock commerce data
47
47
  - real provider + API URL + API key → storefront uses the live backend immediately
48
48
  - switching config later should not require rewriting app code that calls `commerce.*`, `useCart()`, or `useRegion()`
49
+ - if a configured live backend becomes unreachable, surface unavailable/error UX instead of masking the failure with fake catalog data
49
50
 
50
51
  ## Development with V0
51
52
 
@@ -32,9 +32,9 @@
32
32
  {
33
33
  "id": "no-frozen-lib-modifications",
34
34
  "filePattern": "lib/commerce.ts",
35
- "pattern": "createProvider\\(",
36
- "description": "lib/commerce.ts is frozen — createProvider() must only be called once in this file",
37
- "required": false
35
+ "pattern": "(?:^|\\n)\\s*(?:const\\s+[_$a-zA-Z][\\w$]*\\s*=\\s*|let\\s+[_$a-zA-Z][\\w$]*\\s*=\\s*|[_$a-zA-Z][\\w$]*\\s*=\\s*|return\\s+)createProvider\\([^]*?(?:^|\\n)\\s*(?:const\\s+[_$a-zA-Z][\\w$]*\\s*=\\s*|let\\s+[_$a-zA-Z][\\w$]*\\s*=\\s*|[_$a-zA-Z][\\w$]*\\s*=\\s*|return\\s+)createProvider\\(",
36
+ "description": "lib/commerce.ts is frozen — do not add a second createProvider() invocation in this file",
37
+ "severity": "warning"
38
38
  },
39
39
  {
40
40
  "id": "no-any-type",
@@ -45,8 +45,8 @@
45
45
  {
46
46
  "id": "no-var-declaration",
47
47
  "filePattern": "**/*.{ts,tsx}",
48
- "pattern": "\\bvar\\s+",
49
- "description": "Use const/let instead of var"
48
+ "pattern": "(?:^|[;({]\\s*)var\\s+[A-Za-z_$][\\w$]*\\s*(?:=|[;,\\n])",
49
+ "description": "Use const/let instead of var declarations"
50
50
  },
51
51
  {
52
52
  "id": "use-product-handle-in-urls",
@@ -57,8 +57,8 @@
57
57
  {
58
58
  "id": "no-client-env-vars",
59
59
  "filePattern": "components/**/*.tsx",
60
- "pattern": "process\\.env\\.[A-Z_]*(?!NEXT_PUBLIC)",
61
- "description": "Client components cannot access non-NEXT_PUBLIC env vars — they are only available server-side"
60
+ "pattern": "process\\.env\\.(?!NEXT_PUBLIC_)[A-Z][A-Z0-9_]*",
61
+ "description": "Client components cannot access non-NEXT_PUBLIC env vars — only NEXT_PUBLIC_* keys are allowed client-side"
62
62
  },
63
63
  {
64
64
  "id": "use-cn-utility",
@@ -117,8 +117,22 @@
117
117
  {
118
118
  "id": "no-provider-branching-in-app",
119
119
  "filePattern": "app/**/*.{ts,tsx}",
120
- "pattern": "NEXT_PUBLIC_COMMERCE_PROVIDER|commerce\\.isMock\\s*\\?|commerce\\.isMock\\s*&&|isMockMode\\s*\\?",
121
- "description": "Do not create separate app-level provider branches for mock vs live — keep one storefront architecture using commerce.*"
120
+ "pattern": "NEXT_PUBLIC_COMMERCE_PROVIDER|process\\.env\\.NEXT_PUBLIC_COMMERCE_PROVIDER|shouldUseMockProvider\\(|isEnvConfigured\\(",
121
+ "description": "Do not create app-level provider/env branches for mock vs live — keep one storefront architecture using commerce.* and infrastructure-resolved runtime mode"
122
+ },
123
+ {
124
+ "id": "mock-first-provider-default",
125
+ "filePattern": "lib/env.ts",
126
+ "pattern": "\\.default\\('medusa'\\)",
127
+ "description": "The runtime must default to mock mode when backend config is absent — lib/env.ts must not default the provider to medusa",
128
+ "severity": "error"
129
+ },
130
+ {
131
+ "id": "no-undefined-commerce-when-env-missing",
132
+ "filePattern": "lib/commerce.ts",
133
+ "pattern": "if \\(!isEnvConfigured\\(\\)\\) return undefined",
134
+ "description": "The commerce singleton must resolve to mock mode instead of returning undefined when backend env vars are missing",
135
+ "severity": "error"
122
136
  },
123
137
  {
124
138
  "id": "no-direct-backend-fetch",
@@ -1,14 +1,67 @@
1
1
  // V0 replaces this with the actual storefront homepage
2
2
  import { commerce } from '@/lib/commerce'
3
+ import { formatPrice } from '@/lib/utils'
4
+ import { redirect } from 'next/navigation'
3
5
  import type { Product } from '@thorprovider/types'
4
6
 
5
7
  export default async function HomePage() {
6
- const products: Product[] = await commerce.getProducts({ first: 8 })
8
+ let products: Product[]
9
+
10
+ try {
11
+ products = await commerce.getProducts({ first: 8 })
12
+ } catch (error) {
13
+ if (commerce.isMock !== true) {
14
+ redirect('/backend-unavailable?returnTo=/')
15
+ }
16
+
17
+ throw error
18
+ }
19
+
20
+ const isMockMode = commerce.isMock === true
7
21
 
8
22
  return (
9
23
  <main className="container mx-auto px-4 py-8">
10
- <h1 className="text-3xl font-bold">Store</h1>
11
- <p className="text-muted-foreground">{products.length} products available</p>
24
+ <div className="flex flex-col gap-3 md:flex-row md:items-end md:justify-between">
25
+ <div>
26
+ <h1 className="text-3xl font-bold">Store</h1>
27
+ <p className="text-muted-foreground">{products.length} products available</p>
28
+ </div>
29
+
30
+ <div className="rounded-full border px-4 py-2 text-sm text-muted-foreground">
31
+ {isMockMode
32
+ ? 'Using mock catalog — connect a backend to switch to live commerce data.'
33
+ : 'Connected to live commerce data.'}
34
+ </div>
35
+ </div>
36
+
37
+ <div className="mt-8 grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
38
+ {products.slice(0, 4).map((product) => {
39
+ const previewPrice = product.variants[0]?.price
40
+
41
+ return (
42
+ <article key={product.id} className="rounded-xl border bg-card p-4 text-card-foreground">
43
+ <div className="aspect-square overflow-hidden rounded-lg bg-muted">
44
+ {product.featuredImage ? (
45
+ <img
46
+ alt={product.featuredImage.altText || product.title}
47
+ className="h-full w-full object-cover"
48
+ src={product.featuredImage.url}
49
+ />
50
+ ) : null}
51
+ </div>
52
+
53
+ <div className="mt-4 space-y-1">
54
+ <h2 className="font-semibold">{product.title}</h2>
55
+ <p className="line-clamp-2 text-sm text-muted-foreground">{product.description}</p>
56
+ {previewPrice ? (
57
+ <p className="text-sm font-medium">{formatPrice(previewPrice)}</p>
58
+ ) : null}
59
+ </div>
60
+ </article>
61
+ )
62
+ })}
63
+ </div>
64
+
12
65
  {/* V0: Generate the actual storefront homepage here */}
13
66
  </main>
14
67
  )
@@ -37,6 +37,7 @@ export interface CartContextValue {
37
37
  const CartContext = createContext<CartContextValue | null>(null)
38
38
 
39
39
  const CART_ID_KEY = 'thor-cart-id'
40
+ const CART_PROVIDER_KEY = 'thor-cart-provider'
40
41
 
41
42
  export function CartProvider({ children }: { children: ReactNode }) {
42
43
  const [cart, setCart] = useState<Cart | null>(null)
@@ -52,6 +53,15 @@ export function CartProvider({ children }: { children: ReactNode }) {
52
53
  ;(async () => {
53
54
  try {
54
55
  setIsLoading(true)
56
+ const currentProvider = commerce.isMock ? 'mock' : 'live'
57
+ const storedProvider = localStorage.getItem(CART_PROVIDER_KEY)
58
+
59
+ if (storedProvider && storedProvider !== currentProvider) {
60
+ localStorage.removeItem(CART_ID_KEY)
61
+ }
62
+
63
+ localStorage.setItem(CART_PROVIDER_KEY, currentProvider)
64
+
55
65
  const cartId = localStorage.getItem(CART_ID_KEY)
56
66
  if (cartId) {
57
67
  const loaded = await commerce.getCart(cartId)
@@ -74,6 +84,7 @@ export function CartProvider({ children }: { children: ReactNode }) {
74
84
  const newCart = await commerce.createCart()
75
85
  setCart(newCart)
76
86
  if (newCart.id) localStorage.setItem(CART_ID_KEY, newCart.id)
87
+ localStorage.setItem(CART_PROVIDER_KEY, commerce.isMock ? 'mock' : 'live')
77
88
  return newCart
78
89
  }, [cart])
79
90
 
@@ -127,6 +138,7 @@ export function CartProvider({ children }: { children: ReactNode }) {
127
138
  const clearCart = useCallback(() => {
128
139
  setCart(null)
129
140
  localStorage.removeItem(CART_ID_KEY)
141
+ localStorage.removeItem(CART_PROVIDER_KEY)
130
142
  }, [])
131
143
 
132
144
  return (
@@ -14,13 +14,14 @@ import type { ReactNode } from 'react'
14
14
  export interface CommerceContextValue {
15
15
  /** The commerce adapter instance (same as `@/lib/commerce` export) */
16
16
  commerce: typeof commerce
17
+ isMock: boolean
17
18
  }
18
19
 
19
20
  const CommerceContext = createContext<CommerceContextValue | null>(null)
20
21
 
21
22
  export function CommerceProvider({ children }: { children: ReactNode }) {
22
23
  return (
23
- <CommerceContext.Provider value={{ commerce }}>
24
+ <CommerceContext.Provider value={{ commerce, isMock: commerce.isMock === true }}>
24
25
  {children}
25
26
  </CommerceContext.Provider>
26
27
  )
@@ -30,6 +30,7 @@ export interface RegionContextValue {
30
30
  const RegionContext = createContext<RegionContextValue | null>(null)
31
31
 
32
32
  const REGION_KEY = 'thor-region-id'
33
+ const REGION_PROVIDER_KEY = 'thor-region-provider'
33
34
 
34
35
  /**
35
36
  * Normalize adapter response to Region type.
@@ -64,6 +65,15 @@ export function RegionProvider({ children }: { children: ReactNode }) {
64
65
  setIsLoading(true)
65
66
  if (!commerce.getRegions) return
66
67
 
68
+ const currentProvider = commerce.isMock ? 'mock' : 'live'
69
+ const storedProvider = localStorage.getItem(REGION_PROVIDER_KEY)
70
+
71
+ if (storedProvider && storedProvider !== currentProvider) {
72
+ localStorage.removeItem(REGION_KEY)
73
+ }
74
+
75
+ localStorage.setItem(REGION_PROVIDER_KEY, currentProvider)
76
+
67
77
  const raw = await commerce.getRegions()
68
78
  if (cancelled || !raw) return
69
79
 
@@ -32,22 +32,6 @@ V0 generates feature code (pages, components) on top of this frozen infrastructu
32
32
  | `patterns.md` | Code templates for pages, components, cart, auth, styling |
33
33
  | `rules.md` | Non-negotiable constraints (read before generating) |
34
34
  | `project-structure.md` | Folder map + where to put new files |
35
- | `decision-matrix.md` | Fast decisions when prompts pressure V0 to leave ThorCommerce architecture |
36
-
37
- ## Guardrail Maintenance
38
-
39
- V0 is guided by multiple aligned layers, not a single prompt.
40
-
41
- - `.agents/AGENTS.md` — mission, runtime, conflict resolution
42
- - `docs/*.md` — types, methods, patterns, rules, structure, decisions
43
- - `ai-validator.json` — regex-based architectural checks
44
- - ThorBuilder prompt injection — project/runtime-specific guardrails at chat time
45
-
46
- If the architecture changes, these layers must be reviewed together.
47
-
48
- See maintainer documentation in `packages/create-thor-app/`:
49
- - `V0_GUARDRAILS_MAINTENANCE.md`
50
- - `AI_GUARDRAILS_AGENTS.md`
51
35
 
52
36
  ## Quick Import Reference
53
37
 
@@ -12,13 +12,6 @@ All backend access goes through the `commerce` singleton from `@/lib/commerce`.
12
12
  import { commerce } from '@/lib/commerce';
13
13
  ```
14
14
 
15
- ## Runtime Modes
16
-
17
- - `mock` provider, or missing real-backend env vars → `commerce` uses a fixture-backed mock provider for layout/preview work.
18
- - Real provider + `NEXT_PUBLIC_COMMERCE_API_URL` + `NEXT_PUBLIC_COMMERCE_API_KEY` → `commerce` uses the live backend immediately.
19
- - The `commerce.*` API stays the same in both modes. Write app code against the shared interface instead of branching on provider.
20
- - If backend config is added later, products, categories, region, cart, checkout, and auth flows switch to the live provider without changing call sites.
21
-
22
15
  ---
23
16
 
24
17
  ## Products
@@ -178,8 +171,6 @@ try {
178
171
  }
179
172
  ```
180
173
 
181
- In `mock` mode there is no backend network dependency, so preview/design work should continue without live-backend health checks.
182
-
183
174
  ---
184
175
 
185
176
  ## Optional Methods
@@ -98,7 +98,6 @@ export function AddToCartButton({ variantId }: { variantId: string }) {
98
98
 
99
99
  - Import `useCart` from `@/components/providers/cart-provider`.
100
100
  - Cart methods: `addItem(variantId, quantity)`, `removeItem(lineItemId)`, `updateQuantity(lineItemId, qty)`, `clearCart()`.
101
- - When the storefront switches from mock to live backend, `CartProvider` resets incompatible persisted cart state automatically.
102
101
 
103
102
  ---
104
103
 
@@ -126,7 +125,6 @@ export function CurrencySelector() {
126
125
  ```
127
126
 
128
127
  - Import `useRegion` from `@/components/providers/region-provider`.
129
- - When the provider changes between mock and live, `RegionProvider` clears stale persisted region state automatically.
130
128
 
131
129
  ---
132
130
 
@@ -264,6 +262,9 @@ export default async function HomePage() {
264
262
  - Keep demo fixtures isolated in `lib/demo-data/*` or `lib/demo-catalog.ts`.
265
263
  - Do not replace normal product listings, collections, cart, or region flows with demo fixtures.
266
264
 
265
+ - Minor runtime-aware UX such as mock/live badges is allowed when it reads the already-resolved adapter state (`commerce.isMock`).
266
+ - Do not use environment variables or helper functions like `isEnvConfigured()`/`shouldUseMockProvider()` inside app code to branch storefront rendering.
267
+
267
268
  ---
268
269
 
269
270
  ## 10. What NOT to Do in Backend-Optional Mode
@@ -12,30 +12,47 @@
12
12
  import { createProvider } from '@thorprovider/adapters'
13
13
  import type { ProviderTypeString } from '@thorprovider/types'
14
14
  import { isSupportedProviderType } from '@thorprovider/types'
15
- import { isEnvConfigured } from './env'
15
+ import { getConfiguredProvider, isRealBackendProvider, shouldUseMockProvider } from './env'
16
16
 
17
17
  let _commerce: ReturnType<typeof createProvider> | undefined
18
18
 
19
19
  function createCommerceInstance(): ReturnType<typeof createProvider> {
20
20
  if (_commerce) return _commerce
21
21
 
22
- const rawProviderType = process.env.NEXT_PUBLIC_COMMERCE_PROVIDER || 'medusa'
23
- if (!isSupportedProviderType(rawProviderType)) {
22
+ const rawProviderType = getConfiguredProvider()
23
+
24
+ if (rawProviderType === 'custom') {
25
+ throw new Error(
26
+ '[commerce] The "custom" provider is not supported by the V0-native template runtime. Configure a supported real backend or use mock mode.'
27
+ )
28
+ }
29
+
30
+ const resolvedProviderType: ProviderTypeString = shouldUseMockProvider()
31
+ ? 'mock'
32
+ : rawProviderType
33
+
34
+ if (!isSupportedProviderType(resolvedProviderType)) {
24
35
  throw new Error(
25
- `[commerce] Unsupported provider: "${rawProviderType}". Set NEXT_PUBLIC_COMMERCE_PROVIDER to a supported value.`
36
+ `[commerce] Unsupported provider: "${resolvedProviderType}". Set NEXT_PUBLIC_COMMERCE_PROVIDER to a supported value.`
26
37
  )
27
38
  }
28
39
 
29
- const providerType: ProviderTypeString = rawProviderType
30
40
  const baseUrl = (process.env.NEXT_PUBLIC_COMMERCE_API_URL ?? '').replace(/\/+$/, '')
31
41
  const apiKey = process.env.NEXT_PUBLIC_COMMERCE_API_KEY ?? ''
42
+ const currencyCode = process.env.NEXT_PUBLIC_DEFAULT_CURRENCY || 'USD'
43
+ const isRealProvider = isRealBackendProvider(resolvedProviderType)
32
44
 
33
45
  _commerce = createProvider({
34
- provider: providerType,
46
+ provider: resolvedProviderType,
35
47
  config: {
36
- baseUrl,
37
- publishableKey: apiKey,
38
- currencyCode: process.env.NEXT_PUBLIC_DEFAULT_CURRENCY || 'USD',
48
+ ...(isRealProvider
49
+ ? {
50
+ baseUrl,
51
+ publishableKey: apiKey,
52
+ }
53
+ : {}),
54
+ currencyCode,
55
+ siteUrl: process.env.NEXT_PUBLIC_SITE_URL,
39
56
  debug: process.env.NODE_ENV === 'development',
40
57
  retry: {
41
58
  maxRetries: 3,
@@ -60,7 +77,6 @@ function createCommerceInstance(): ReturnType<typeof createProvider> {
60
77
  */
61
78
  export const commerce = new Proxy({} as ReturnType<typeof createProvider>, {
62
79
  get(_target, prop: string | symbol) {
63
- if (!isEnvConfigured()) return undefined
64
80
  return createCommerceInstance()[prop as keyof ReturnType<typeof createProvider>]
65
81
  },
66
82
  })
@@ -7,11 +7,27 @@
7
7
 
8
8
  import { z } from 'zod'
9
9
 
10
- export const EnvSchema = z.object({
10
+ const realProviderSchema = z.enum(['medusa', 'shopify', 'bigcommerce'])
11
+
12
+ const BaseEnvSchema = z.object({
11
13
  NEXT_PUBLIC_COMMERCE_PROVIDER: z
12
- .enum(['medusa', 'shopify', 'bigcommerce', 'custom'])
13
- .default('medusa'),
14
+ .enum(['mock', 'medusa', 'shopify', 'bigcommerce', 'custom'])
15
+ .default('mock'),
16
+
17
+ NEXT_PUBLIC_DEFAULT_CURRENCY: z
18
+ .string()
19
+ .default('USD'),
14
20
 
21
+ NEXT_PUBLIC_SALES_CHANNEL_ID: z
22
+ .string()
23
+ .optional(),
24
+
25
+ FRONTEND_WEBHOOK_SECRET: z
26
+ .string()
27
+ .optional(),
28
+ })
29
+
30
+ const RealBackendEnvSchema = BaseEnvSchema.extend({
15
31
  NEXT_PUBLIC_COMMERCE_API_URL: z
16
32
  .string()
17
33
  .url(),
@@ -19,22 +35,44 @@ export const EnvSchema = z.object({
19
35
  NEXT_PUBLIC_COMMERCE_API_KEY: z
20
36
  .string()
21
37
  .min(1),
38
+ })
22
39
 
23
- NEXT_PUBLIC_DEFAULT_CURRENCY: z
24
- .string()
25
- .default('USD'),
26
-
27
- NEXT_PUBLIC_SALES_CHANNEL_ID: z
40
+ const MockEnvSchema = BaseEnvSchema.extend({
41
+ NEXT_PUBLIC_COMMERCE_API_URL: z
28
42
  .string()
29
43
  .optional(),
30
44
 
31
- FRONTEND_WEBHOOK_SECRET: z
45
+ NEXT_PUBLIC_COMMERCE_API_KEY: z
32
46
  .string()
33
47
  .optional(),
34
48
  })
35
49
 
50
+ export const EnvSchema = MockEnvSchema
51
+
36
52
  export type Env = z.infer<typeof EnvSchema>
37
53
 
54
+ export function getConfiguredProvider(): Env['NEXT_PUBLIC_COMMERCE_PROVIDER'] {
55
+ return BaseEnvSchema.shape.NEXT_PUBLIC_COMMERCE_PROVIDER.parse(
56
+ process.env.NEXT_PUBLIC_COMMERCE_PROVIDER
57
+ )
58
+ }
59
+
60
+ export function isRealBackendProvider(
61
+ provider: string | undefined
62
+ ): provider is z.infer<typeof realProviderSchema> {
63
+ return realProviderSchema.safeParse(provider).success
64
+ }
65
+
66
+ export function shouldUseMockProvider(): boolean {
67
+ const provider = getConfiguredProvider()
68
+
69
+ if (provider === 'mock') {
70
+ return true
71
+ }
72
+
73
+ return !isRealBackendProvider(provider) || !isEnvConfigured()
74
+ }
75
+
38
76
  /**
39
77
  * Check whether required commerce env vars are present.
40
78
  * Used to bail out gracefully during build/SSG.
@@ -55,14 +93,20 @@ export function isEnvConfigured(): boolean {
55
93
  */
56
94
  export function getEnv(): Env {
57
95
  try {
58
- return EnvSchema.parse({
96
+ const rawEnv = {
59
97
  NEXT_PUBLIC_COMMERCE_PROVIDER: process.env.NEXT_PUBLIC_COMMERCE_PROVIDER,
60
98
  NEXT_PUBLIC_COMMERCE_API_URL: process.env.NEXT_PUBLIC_COMMERCE_API_URL,
61
99
  NEXT_PUBLIC_COMMERCE_API_KEY: process.env.NEXT_PUBLIC_COMMERCE_API_KEY,
62
100
  NEXT_PUBLIC_DEFAULT_CURRENCY: process.env.NEXT_PUBLIC_DEFAULT_CURRENCY,
63
101
  NEXT_PUBLIC_SALES_CHANNEL_ID: process.env.NEXT_PUBLIC_SALES_CHANNEL_ID,
64
102
  FRONTEND_WEBHOOK_SECRET: process.env.FRONTEND_WEBHOOK_SECRET,
65
- })
103
+ }
104
+
105
+ if (shouldUseMockProvider()) {
106
+ return MockEnvSchema.parse(rawEnv)
107
+ }
108
+
109
+ return RealBackendEnvSchema.parse(rawEnv)
66
110
  } catch (error) {
67
111
  if (error instanceof z.ZodError) {
68
112
  const issues = error.issues
@@ -1,6 +1,6 @@
1
1
  /// <reference types="next" />
2
2
  /// <reference types="next/image-types/global" />
3
- import "./.next/dev/types/routes.d.ts";
3
+ import "./.next/types/routes.d.ts";
4
4
 
5
5
  // NOTE: This file should not be edited
6
6
  // see https://nextjs.org/docs/app/api-reference/config/typescript for more information.