@stackverify/ui 0.0.0-stage → 0.1.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 (3) hide show
  1. package/README.md +416 -2
  2. package/dist/bin.js +2187 -0
  3. package/package.json +47 -4
package/dist/bin.js ADDED
@@ -0,0 +1,2187 @@
1
+ #!/usr/bin/env node
2
+
3
+ // packages/cli/src/index.ts
4
+ import { spawn } from "child_process";
5
+ import { mkdir as mkdir2, readFile as readFile2 } from "fs/promises";
6
+ import { resolve } from "path";
7
+
8
+ // packages/adapters/dist/index.js
9
+ var TARGETS = ["vite-react", "next", "node"];
10
+ var TARGET_COMMANDS = {
11
+ "vite-react": {
12
+ dev: ["npm", ["run", "dev"]],
13
+ build: ["npm", ["run", "build"]],
14
+ start: ["npm", ["run", "start"]]
15
+ },
16
+ next: {
17
+ dev: ["npm", ["run", "dev"]],
18
+ build: ["npm", ["run", "build"]],
19
+ start: ["npm", ["run", "start"]]
20
+ },
21
+ node: {
22
+ dev: ["npm", ["run", "dev"]],
23
+ build: ["npm", ["run", "build"]],
24
+ start: ["npm", ["run", "start"]]
25
+ }
26
+ };
27
+ function isTarget(value) {
28
+ return TARGETS.some((target) => target === value);
29
+ }
30
+ function packageJson(name, target) {
31
+ if (target === "next") {
32
+ return `${JSON.stringify(
33
+ {
34
+ name,
35
+ private: true,
36
+ scripts: {
37
+ dev: "next dev",
38
+ build: "next build",
39
+ start: "next start"
40
+ },
41
+ dependencies: {
42
+ next: "16.4.2",
43
+ react: "19.2.0",
44
+ "react-dom": "19.2.0"
45
+ },
46
+ devDependencies: {
47
+ "@types/node": "22.18.6",
48
+ "@types/react": "19.2.2",
49
+ "@types/react-dom": "19.2.2",
50
+ typescript: "5.9.3"
51
+ }
52
+ },
53
+ null,
54
+ 2
55
+ )}
56
+ `;
57
+ }
58
+ return `${JSON.stringify(
59
+ {
60
+ name,
61
+ private: true,
62
+ type: "module",
63
+ scripts: {
64
+ dev: "vite --host 0.0.0.0",
65
+ build: "vite build",
66
+ start: "node server/index.mjs"
67
+ },
68
+ dependencies: {
69
+ react: "19.2.0",
70
+ "react-dom": "19.2.0"
71
+ },
72
+ devDependencies: {
73
+ "@types/react": "19.2.2",
74
+ "@types/react-dom": "19.2.2",
75
+ "@vitejs/plugin-react": "5.0.4",
76
+ typescript: "5.9.3",
77
+ vite: "7.1.12"
78
+ }
79
+ },
80
+ null,
81
+ 2
82
+ )}
83
+ `;
84
+ }
85
+ var serverPlatformFiles = {
86
+ "src/generated/server/platform.mjs": `import { randomUUID } from "node:crypto";
87
+ import { readFile } from "node:fs/promises";
88
+ import { join } from "node:path";
89
+
90
+ const API_ROOT = "/api/sdk/v1";
91
+ const TIMEOUT_MS = 10000;
92
+
93
+ function truthy(value) {
94
+ return ["on", "true", "1"].includes(String(value ?? "").trim().toLowerCase());
95
+ }
96
+
97
+ async function readEnv(root) {
98
+ let local = {};
99
+ try {
100
+ const text = await readFile(join(root, ".env.local"), "utf8");
101
+ for (const line of text.split("\\n")) {
102
+ const trimmed = line.trim();
103
+ if (!trimmed || trimmed.startsWith("#")) continue;
104
+ const at = trimmed.indexOf("=");
105
+ if (at < 1) continue;
106
+ local[trimmed.slice(0, at).trim()] = trimmed.slice(at + 1).trim().replace(/^["']|["']$/g, "");
107
+ }
108
+ } catch {
109
+ local = {};
110
+ }
111
+ const value = (name) => {
112
+ const fromProcess = process.env[name];
113
+ return fromProcess && fromProcess.trim() ? fromProcess.trim() : local[name] ?? "";
114
+ };
115
+ return {
116
+ root,
117
+ fixtures: truthy(value("STACKVERIFY_FIXTURES")),
118
+ apiUrl: value("STACKVERIFY_API_URL") || "https://stack-verify.com",
119
+ publishableKey: value("STACKVERIFY_PUBLISHABLE_KEY"),
120
+ secretKey: value("STACKVERIFY_SECRET_KEY"),
121
+ apiKey: value("STACKVERIFY_API_KEY"),
122
+ };
123
+ }
124
+
125
+ function buildUrl(baseUrl, segments, params = {}) {
126
+ let url;
127
+ try {
128
+ url = new URL(baseUrl);
129
+ } catch {
130
+ throw new Error("STACKVERIFY_API_URL is invalid.");
131
+ }
132
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
133
+ throw new Error("STACKVERIFY_API_URL is invalid.");
134
+ }
135
+ const prefix = url.pathname.replace(/\\/$/, "");
136
+ url.pathname = prefix + API_ROOT + "/" + segments.map(encodeURIComponent).join("/");
137
+ url.search = "";
138
+ url.hash = "";
139
+ for (const [key, value] of Object.entries(params)) {
140
+ if (value) url.searchParams.set(key, value);
141
+ }
142
+ return url.toString();
143
+ }
144
+
145
+ async function fetchJson(url, key, init = {}) {
146
+ let response;
147
+ try {
148
+ response = await fetch(url, {
149
+ ...init,
150
+ headers: {
151
+ accept: "application/json",
152
+ authorization: "Bearer " + key,
153
+ ...init.headers,
154
+ },
155
+ signal: AbortSignal.timeout(TIMEOUT_MS),
156
+ });
157
+ } catch (error) {
158
+ if (error && error.name === "TimeoutError") {
159
+ throw new Error("The platform API timed out.");
160
+ }
161
+ throw new Error("The platform API request failed.");
162
+ }
163
+ let value;
164
+ try {
165
+ value = await response.json();
166
+ } catch {
167
+ throw new Error("The platform API returned an invalid response.");
168
+ }
169
+ return { response, value };
170
+ }
171
+
172
+ export async function loadServerConfig(root = process.cwd()) {
173
+ const env = await readEnv(root);
174
+ let manifest;
175
+ try {
176
+ manifest = JSON.parse(await readFile(join(root, "store.json"), "utf8"));
177
+ } catch {
178
+ throw new Error("store.json could not be read.");
179
+ }
180
+ const slug = manifest && manifest.store && manifest.store.slug;
181
+ if (typeof slug !== "string" || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug)) {
182
+ throw new Error("store.json does not have a valid store slug.");
183
+ }
184
+ return {
185
+ ...env,
186
+ slug,
187
+ mode: env.fixtures || !env.publishableKey ? "fixtures" : "platform",
188
+ };
189
+ }
190
+
191
+ async function fixtureContext(config) {
192
+ return JSON.parse(await readFile(join(config.root, "src", "generated", "context.json"), "utf8"));
193
+ }
194
+
195
+ function fixtureCheckout() {
196
+ return {
197
+ ok: true,
198
+ orderId: "sdk-demo-order",
199
+ token: "sdk-demo-token",
200
+ orderNumber: "SDK-DEMO-1",
201
+ totalMinor: 0,
202
+ depositMinor: 0,
203
+ scheduledFor: null,
204
+ whatsappUrl: "",
205
+ message: "Demo checkout accepted.",
206
+ };
207
+ }
208
+
209
+ export async function getStoreContext(options = {}) {
210
+ const config = await loadServerConfig(options.root ?? process.cwd());
211
+ if (config.mode === "fixtures") return fixtureContext(config);
212
+ const query = typeof options.query === "string" ? options.query.trim() : "";
213
+ const result = await fetchJson(
214
+ buildUrl(
215
+ config.apiUrl,
216
+ ["storefronts", config.slug, "context"],
217
+ query ? { q: query } : {},
218
+ ),
219
+ config.publishableKey,
220
+ );
221
+ if (!result.response.ok) throw new Error("Store context is not available.");
222
+ return result.value;
223
+ }
224
+
225
+ export async function submitCheckout(input, options = {}) {
226
+ const config = await loadServerConfig(options.root ?? process.cwd());
227
+ const idempotencyKey = input && input.idempotencyKey ? input.idempotencyKey : randomUUID();
228
+ if (config.fixtures || !config.publishableKey || (!config.secretKey && !config.apiKey)) {
229
+ return fixtureCheckout();
230
+ }
231
+ const body = { ...input };
232
+ delete body.idempotencyKey;
233
+ const result = await fetchJson(
234
+ buildUrl(config.apiUrl, ["storefronts", config.slug, "checkout"]),
235
+ config.secretKey || config.apiKey,
236
+ {
237
+ method: "POST",
238
+ body: JSON.stringify(body),
239
+ headers: {
240
+ "content-type": "application/json",
241
+ "Idempotency-Key": idempotencyKey,
242
+ },
243
+ },
244
+ );
245
+ if (result.value && typeof result.value === "object") return result.value;
246
+ if (!result.response.ok) return { ok: false, message: "Checkout could not be completed." };
247
+ throw new Error("The platform API returned an invalid checkout response.");
248
+ }
249
+ `,
250
+ "src/generated/server/platform.d.mts": `export type StoreContext = {
251
+ store: {
252
+ name: string;
253
+ slug: string;
254
+ tagline: string;
255
+ about: string;
256
+ themeColor: string;
257
+ logo: string;
258
+ cover: string;
259
+ acceptingOrders: boolean;
260
+ pickupEnabled: boolean;
261
+ deliveryEnabled: boolean;
262
+ payment: { payOnDelivery: boolean; mpesa: boolean };
263
+ };
264
+ categories: Array<{ id: string; name: string; image: string }>;
265
+ products: Array<{
266
+ id: string;
267
+ name: string;
268
+ description: string;
269
+ priceMinor: number;
270
+ currency: string;
271
+ image: string;
272
+ categoryId: string;
273
+ isFeatured: boolean;
274
+ }>;
275
+ search: { query: string; results: Array<{ id: string; name: string; description: string; priceMinor: number; currency: string; image: string; categoryId: string; isFeatured: boolean }> };
276
+ };
277
+
278
+ export type CheckoutInput = {
279
+ items: Array<{ productId: string; quantity: number }>;
280
+ name: string;
281
+ phone: string;
282
+ fulfillment: "pickup" | "delivery";
283
+ paymentChoice: "pay_now" | "on_delivery";
284
+ address?: string;
285
+ note?: string;
286
+ bookingAt?: string;
287
+ visitorId?: string;
288
+ sessionId?: string;
289
+ source?: string;
290
+ idempotencyKey?: string;
291
+ };
292
+
293
+ export type CheckoutResult =
294
+ | {
295
+ ok: true;
296
+ orderId: string;
297
+ token: string;
298
+ orderNumber: string;
299
+ totalMinor: number;
300
+ depositMinor: number;
301
+ scheduledFor: string | null;
302
+ whatsappUrl: string;
303
+ message: string;
304
+ }
305
+ | {
306
+ ok: false;
307
+ message: string;
308
+ fieldErrors?: Record<string, string | string[]>;
309
+ };
310
+
311
+ export type ServerConfig = {
312
+ root: string;
313
+ fixtures: boolean;
314
+ apiUrl: string;
315
+ publishableKey: string;
316
+ secretKey: string;
317
+ apiKey: string;
318
+ slug: string;
319
+ mode: "fixtures" | "platform";
320
+ };
321
+
322
+ export type ServerOptions = { root?: string };
323
+ export type ContextOptions = ServerOptions & { query?: string };
324
+
325
+ export function loadServerConfig(root?: string): Promise<ServerConfig>;
326
+ export function getStoreContext(options?: ContextOptions): Promise<StoreContext>;
327
+ export function submitCheckout(input: CheckoutInput, options?: ServerOptions): Promise<CheckoutResult>;
328
+ `
329
+ };
330
+ var viteFiles = {
331
+ "index.html": `<!doctype html>
332
+ <html lang="en">
333
+ <head>
334
+ <meta charset="UTF-8" />
335
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
336
+ <title>Store</title>
337
+ </head>
338
+ <body>
339
+ <div id="root"></div>
340
+ <script type="module" src="/src/main.tsx"></script>
341
+ </body>
342
+ </html>
343
+ `,
344
+ "vite.config.ts": `import react from "@vitejs/plugin-react";
345
+ import { defineConfig } from "vite";
346
+
347
+ export default defineConfig({
348
+ plugins: [react()],
349
+ });
350
+ `,
351
+ "tsconfig.json": `${JSON.stringify(
352
+ {
353
+ compilerOptions: {
354
+ target: "ES2022",
355
+ lib: ["ES2022", "DOM", "DOM.Iterable"],
356
+ module: "ESNext",
357
+ moduleResolution: "Bundler",
358
+ jsx: "react-jsx",
359
+ strict: true,
360
+ skipLibCheck: true,
361
+ resolveJsonModule: true,
362
+ noEmit: true
363
+ },
364
+ include: ["src", "vite.config.ts"]
365
+ },
366
+ null,
367
+ 2
368
+ )}
369
+ `,
370
+ "src/main.tsx": `import { StrictMode } from "react";
371
+ import { createRoot } from "react-dom/client";
372
+ import App from "./generated/App";
373
+ import "./generated/tokens.css";
374
+
375
+ const root = document.getElementById("root");
376
+ if (!root) throw new Error("Root element not found.");
377
+
378
+ createRoot(root).render(
379
+ <StrictMode>
380
+ <App />
381
+ </StrictMode>,
382
+ );
383
+ `,
384
+ "server/index.mjs": `import { createServer } from "node:http";
385
+ import { readFile } from "node:fs/promises";
386
+ import { extname, join, normalize } from "node:path";
387
+ import { getStoreContext, submitCheckout } from "../src/generated/server/platform.mjs";
388
+
389
+ const port = Number(process.env.PORT ?? "3000");
390
+ const root = process.cwd();
391
+ const dist = join(root, "dist");
392
+
393
+ const types = {
394
+ ".css": "text/css; charset=utf-8",
395
+ ".html": "text/html; charset=utf-8",
396
+ ".js": "text/javascript; charset=utf-8",
397
+ ".json": "application/json; charset=utf-8",
398
+ ".svg": "image/svg+xml",
399
+ ".png": "image/png",
400
+ ".jpg": "image/jpeg",
401
+ ".webp": "image/webp",
402
+ };
403
+
404
+ function sendJson(response, status, value) {
405
+ response.writeHead(status, { "content-type": "application/json; charset=utf-8" });
406
+ response.end(JSON.stringify(value));
407
+ }
408
+
409
+ async function readJsonBody(request) {
410
+ const chunks = [];
411
+ let size = 0;
412
+ for await (const chunk of request) {
413
+ size += chunk.length;
414
+ if (size > 64 * 1024) throw new Error("Request too large.");
415
+ chunks.push(chunk);
416
+ }
417
+ return JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
418
+ }
419
+
420
+ async function serveStatic(pathname, response) {
421
+ const clean = normalize(decodeURIComponent(pathname)).replace(/^(\\.\\.[/\\\\])+/, "");
422
+ const target = join(dist, clean === "/" ? "index.html" : clean);
423
+ if (!target.startsWith(dist)) {
424
+ response.writeHead(403);
425
+ response.end();
426
+ return;
427
+ }
428
+ try {
429
+ const content = await readFile(target);
430
+ response.writeHead(200, {
431
+ "content-type": types[extname(target)] ?? "application/octet-stream",
432
+ });
433
+ response.end(content);
434
+ } catch {
435
+ try {
436
+ const fallback = await readFile(join(dist, "index.html"));
437
+ response.writeHead(200, { "content-type": "text/html; charset=utf-8" });
438
+ response.end(fallback);
439
+ } catch {
440
+ response.writeHead(404, { "content-type": "text/plain; charset=utf-8" });
441
+ response.end("Not found.");
442
+ }
443
+ }
444
+ }
445
+
446
+ createServer(async (request, response) => {
447
+ const url = new URL(request.url ?? "/", "http://localhost");
448
+ if (url.pathname === "/api/stackverify/context" && request.method === "GET") {
449
+ try {
450
+ const query = url.searchParams.get("q") ?? undefined;
451
+ sendJson(response, 200, await getStoreContext({ query }));
452
+ } catch {
453
+ sendJson(response, 500, { error: "Store context is not available." });
454
+ }
455
+ return;
456
+ }
457
+ if (url.pathname === "/api/stackverify/checkout" && request.method === "POST") {
458
+ try {
459
+ const input = await readJsonBody(request);
460
+ if (!input || !Array.isArray(input.items) || input.items.length === 0) {
461
+ sendJson(response, 400, { ok: false, message: "Add an item before checkout." });
462
+ return;
463
+ }
464
+ const result = await submitCheckout(input);
465
+ sendJson(response, result.ok ? 200 : 400, result);
466
+ } catch {
467
+ sendJson(response, 400, { ok: false, message: "Checkout could not be read." });
468
+ }
469
+ return;
470
+ }
471
+ await serveStatic(url.pathname, response);
472
+ }).listen(port, () => {
473
+ console.log("StackVerify store listening on http://localhost:" + port);
474
+ });
475
+ `,
476
+ "api/context.mjs": `import { getStoreContext } from "../src/generated/server/platform.mjs";
477
+
478
+ export default async function handler(request, response) {
479
+ if (request.method !== "GET") {
480
+ response.status(405).json({ error: "Method not allowed." });
481
+ return;
482
+ }
483
+ try {
484
+ response.status(200).json(await getStoreContext({ query: request.query?.q }));
485
+ } catch {
486
+ response.status(500).json({ error: "Store context is not available." });
487
+ }
488
+ }
489
+ `,
490
+ "api/checkout.mjs": `import { submitCheckout } from "../src/generated/server/platform.mjs";
491
+
492
+ async function readBody(request) {
493
+ const chunks = [];
494
+ let size = 0;
495
+ for await (const chunk of request) {
496
+ size += chunk.length;
497
+ if (size > 64 * 1024) throw new Error("Request too large.");
498
+ chunks.push(chunk);
499
+ }
500
+ return JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}");
501
+ }
502
+
503
+ export default async function handler(request, response) {
504
+ if (request.method !== "POST") {
505
+ response.status(405).json({ error: "Method not allowed." });
506
+ return;
507
+ }
508
+ try {
509
+ const input = await readBody(request);
510
+ if (!input || !Array.isArray(input.items) || input.items.length === 0) {
511
+ response.status(400).json({ ok: false, message: "Add an item before checkout." });
512
+ return;
513
+ }
514
+ const result = await submitCheckout(input);
515
+ response.status(result.ok ? 200 : 400).json(result);
516
+ } catch {
517
+ response.status(400).json({ ok: false, message: "Checkout could not be read." });
518
+ }
519
+ }
520
+ `,
521
+ "vercel.json": `${JSON.stringify(
522
+ {
523
+ framework: "vite",
524
+ rewrites: [{ source: "/((?!api/).*)", destination: "/index.html" }]
525
+ },
526
+ null,
527
+ 2
528
+ )}
529
+ `,
530
+ "render.yaml": `services:
531
+ - type: web
532
+ name: stackverify-store
533
+ runtime: node
534
+ buildCommand: npm install && npm run build
535
+ startCommand: npm start
536
+ envVars:
537
+ - key: STACKVERIFY_API_URL
538
+ sync: false
539
+ - key: STACKVERIFY_PUBLISHABLE_KEY
540
+ sync: false
541
+ - key: STACKVERIFY_SECRET_KEY
542
+ sync: false
543
+ `
544
+ };
545
+ var nextFiles = {
546
+ "next.config.mjs": `const nextConfig = {};
547
+
548
+ export default nextConfig;
549
+ `,
550
+ "tsconfig.json": `${JSON.stringify(
551
+ {
552
+ compilerOptions: {
553
+ target: "ES2022",
554
+ lib: ["dom", "dom.iterable", "esnext"],
555
+ allowJs: true,
556
+ skipLibCheck: true,
557
+ strict: true,
558
+ noEmit: true,
559
+ esModuleInterop: true,
560
+ module: "esnext",
561
+ moduleResolution: "bundler",
562
+ resolveJsonModule: true,
563
+ isolatedModules: true,
564
+ jsx: "react-jsx",
565
+ incremental: true
566
+ },
567
+ include: ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
568
+ exclude: ["node_modules"]
569
+ },
570
+ null,
571
+ 2
572
+ )}
573
+ `,
574
+ "app/globals.css": `html,
575
+ body {
576
+ margin: 0;
577
+ padding: 0;
578
+ }
579
+ `,
580
+ "app/layout.tsx": `import type { ReactNode } from "react";
581
+ import "./globals.css";
582
+ import "../src/generated/tokens.css";
583
+
584
+ export default function RootLayout({ children }: { children: ReactNode }) {
585
+ return (
586
+ <html lang="en">
587
+ <body>{children}</body>
588
+ </html>
589
+ );
590
+ }
591
+ `,
592
+ "app/page.tsx": `import App from "../src/generated/App";
593
+
594
+ export default function Page() {
595
+ return <App />;
596
+ }
597
+ `,
598
+ "app/api/stackverify/context/route.ts": `import { NextResponse } from "next/server";
599
+ import { getStoreContext } from "../../../../src/generated/server/platform.mjs";
600
+
601
+ export const dynamic = "force-dynamic";
602
+
603
+ export async function GET(request: Request) {
604
+ const query = new URL(request.url).searchParams.get("q") ?? undefined;
605
+ try {
606
+ return NextResponse.json(await getStoreContext({ query }));
607
+ } catch {
608
+ return NextResponse.json({ error: "Store context is not available." }, { status: 500 });
609
+ }
610
+ }
611
+ `,
612
+ "app/api/stackverify/checkout/route.ts": `import { NextResponse } from "next/server";
613
+ import {
614
+ submitCheckout,
615
+ type CheckoutInput,
616
+ } from "../../../../src/generated/server/platform.mjs";
617
+
618
+ export async function POST(request: Request) {
619
+ let input: unknown;
620
+ try {
621
+ input = await request.json();
622
+ } catch {
623
+ return NextResponse.json({ ok: false, message: "Checkout could not be read." }, { status: 400 });
624
+ }
625
+ const value = input as { items?: unknown };
626
+ if (!Array.isArray(value.items) || value.items.length === 0) {
627
+ return NextResponse.json({ ok: false, message: "Add an item before checkout." }, { status: 400 });
628
+ }
629
+ try {
630
+ const result = await submitCheckout(input as CheckoutInput);
631
+ return NextResponse.json(result, { status: result.ok ? 200 : 400 });
632
+ } catch {
633
+ return NextResponse.json({ ok: false, message: "Checkout could not be completed." }, { status: 400 });
634
+ }
635
+ }
636
+ `,
637
+ "render.yaml": `services:
638
+ - type: web
639
+ name: stackverify-store
640
+ runtime: node
641
+ buildCommand: npm install && npm run build
642
+ startCommand: npm start
643
+ envVars:
644
+ - key: STACKVERIFY_API_URL
645
+ sync: false
646
+ - key: STACKVERIFY_PUBLISHABLE_KEY
647
+ sync: false
648
+ - key: STACKVERIFY_SECRET_KEY
649
+ sync: false
650
+ `
651
+ };
652
+ function targetPackageJson(name, target) {
653
+ return packageJson(name, target);
654
+ }
655
+ function targetFiles(target) {
656
+ if (target === "next") return { ...serverPlatformFiles, ...nextFiles };
657
+ if (target === "node") {
658
+ const files = { ...serverPlatformFiles, ...viteFiles };
659
+ delete files["api/context.mjs"];
660
+ delete files["api/checkout.mjs"];
661
+ delete files["vercel.json"];
662
+ return files;
663
+ }
664
+ return { ...serverPlatformFiles, ...viteFiles };
665
+ }
666
+
667
+ // packages/cli/src/config/env.ts
668
+ import { readFile } from "fs/promises";
669
+ import { join } from "path";
670
+ function parseApiUrl(value) {
671
+ try {
672
+ const url = new URL(value);
673
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
674
+ throw new Error("Invalid protocol.");
675
+ }
676
+ return url.toString();
677
+ } catch {
678
+ throw new Error("STACKVERIFY_API_URL must be a valid http or https URL.");
679
+ }
680
+ }
681
+ function parseFixtures(value) {
682
+ return ["on", "true", "1"].includes((value ?? "").trim().toLowerCase());
683
+ }
684
+ function parseEnv(text) {
685
+ const values = {};
686
+ for (const line of text.split("\n")) {
687
+ const trimmed = line.trim();
688
+ if (!trimmed || trimmed.startsWith("#")) continue;
689
+ const separator = trimmed.indexOf("=");
690
+ if (separator < 1) continue;
691
+ const key = trimmed.slice(0, separator).trim();
692
+ const raw = trimmed.slice(separator + 1).trim();
693
+ values[key] = raw.replace(/^["']|["']$/g, "");
694
+ }
695
+ return values;
696
+ }
697
+ async function loadEnv(root) {
698
+ let local = {};
699
+ try {
700
+ local = parseEnv(await readFile(join(root, ".env.local"), "utf8"));
701
+ } catch {
702
+ local = {};
703
+ }
704
+ for (const [key, value] of Object.entries(local)) process.env[key] = value;
705
+ const values = { ...process.env, ...local };
706
+ return {
707
+ apiUrl: parseApiUrl(values.STACKVERIFY_API_URL ?? "https://stack-verify.com"),
708
+ fixtures: parseFixtures(values.STACKVERIFY_FIXTURES),
709
+ publishableKey: values.STACKVERIFY_PUBLISHABLE_KEY,
710
+ secretKey: values.STACKVERIFY_SECRET_KEY,
711
+ apiKey: values.STACKVERIFY_API_KEY
712
+ };
713
+ }
714
+ var ENV_EXAMPLE = `STACKVERIFY_API_URL=https://stack-verify.com
715
+ STACKVERIFY_FIXTURES=off
716
+ STACKVERIFY_PUBLISHABLE_KEY=
717
+ STACKVERIFY_SECRET_KEY=
718
+ `;
719
+ var PROJECT_GITIGNORE = `node_modules
720
+ dist
721
+ .next
722
+ .env
723
+ .env.*
724
+ !.env.example
725
+ *.log
726
+ `;
727
+
728
+ // packages/cli/src/config/lock.ts
729
+ import { createHash } from "crypto";
730
+ import { z } from "zod";
731
+ var LOCK_VERSION = 1;
732
+ var GENERATOR_VERSION = "0.2.0";
733
+ var lockSchema = z.object({
734
+ version: z.literal(LOCK_VERSION),
735
+ target: z.enum(["vite-react", "next", "node"]),
736
+ generatorVersion: z.literal(GENERATOR_VERSION),
737
+ contractVersion: z.number().int().positive(),
738
+ manifestSha256: z.string().length(64),
739
+ blocks: z.array(
740
+ z.object({
741
+ id: z.string(),
742
+ version: z.string(),
743
+ entry: z.string(),
744
+ sha256: z.string().length(64)
745
+ }).strict()
746
+ ).min(1)
747
+ }).strict();
748
+ function stableStringify(value) {
749
+ if (Array.isArray(value)) return `[${value.map(stableStringify).join(",")}]`;
750
+ if (value && typeof value === "object") {
751
+ const entries = Object.entries(value).sort(([left], [right]) => left.localeCompare(right));
752
+ return `{${entries.map(([key, item]) => `${JSON.stringify(key)}:${stableStringify(item)}`).join(",")}}`;
753
+ }
754
+ return JSON.stringify(value);
755
+ }
756
+ function sha256(value) {
757
+ return createHash("sha256").update(stableStringify(value)).digest("hex");
758
+ }
759
+ function createLock(manifest, target, contractVersion, blocks) {
760
+ return {
761
+ version: LOCK_VERSION,
762
+ target,
763
+ generatorVersion: GENERATOR_VERSION,
764
+ contractVersion,
765
+ manifestSha256: sha256(manifest),
766
+ blocks: blocks.map((block2) => ({
767
+ id: block2.id,
768
+ version: block2.version,
769
+ entry: block2.entry,
770
+ sha256: block2.sha256
771
+ }))
772
+ };
773
+ }
774
+ function parseLock(value) {
775
+ return lockSchema.parse(value);
776
+ }
777
+ function verifyLock(lock, manifest, target, contractVersion, blocks) {
778
+ const expected = createLock(manifest, target, contractVersion, blocks);
779
+ return sha256(lock) === sha256(expected);
780
+ }
781
+
782
+ // packages/cli/src/config/manifest.ts
783
+ import { z as z2 } from "zod";
784
+ var slug = z2.string().min(1).max(40).regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "Use a lowercase store link.");
785
+ var semver = z2.string().regex(/^\d+\.\d+\.\d+$/, "Use a block version like 1.0.0.");
786
+ var hex = z2.string().regex(/^#[0-9a-fA-F]{6}$/, "Use a six digit hex colour.");
787
+ var safePath = z2.string().regex(/^\/[A-Za-z0-9/:_.-]*$/, "Use an internal path.");
788
+ var unsafeKeys = /* @__PURE__ */ new Set([
789
+ "html",
790
+ "css",
791
+ "script",
792
+ "iframe",
793
+ "dangerouslySetInnerHTML",
794
+ "innerHTML",
795
+ "outerHTML",
796
+ "srcDoc"
797
+ ]);
798
+ function unsafeValue(value) {
799
+ if (typeof value === "string") {
800
+ const lower = value.toLowerCase();
801
+ if (lower.includes("<script") || lower.includes("</script") || lower.includes("<iframe") || lower.includes("javascript:") || lower.includes("data:text/html") || lower.includes("onerror=") || lower.includes("onload=") || lower.includes("url(") || lower.includes("{") || lower.includes("}")) {
802
+ return "Raw code, style strings and scripts are not allowed.";
803
+ }
804
+ if (lower.startsWith("http://") || lower.startsWith("https://") || lower.startsWith("//")) {
805
+ return "External URLs are not allowed in the design JSON.";
806
+ }
807
+ return null;
808
+ }
809
+ if (Array.isArray(value)) {
810
+ for (const item of value) {
811
+ const found = unsafeValue(item);
812
+ if (found) return found;
813
+ }
814
+ return null;
815
+ }
816
+ if (value && typeof value === "object") {
817
+ for (const [key, item] of Object.entries(value)) {
818
+ if (unsafeKeys.has(key) || key.startsWith("on")) {
819
+ return "Raw code, style strings and scripts are not allowed.";
820
+ }
821
+ const found = unsafeValue(item);
822
+ if (found) return found;
823
+ }
824
+ }
825
+ return null;
826
+ }
827
+ var propsSchema = z2.record(z2.string(), z2.unknown()).superRefine((value, context) => {
828
+ const found = unsafeValue(value);
829
+ if (found) context.addIssue({ code: z2.ZodIssueCode.custom, message: found });
830
+ });
831
+ var manifestSchema = z2.object({
832
+ version: z2.literal(1),
833
+ store: z2.object({ slug }).strict(),
834
+ skin: z2.object({
835
+ version: z2.literal(1),
836
+ tokens: z2.object({
837
+ background: hex,
838
+ surface: hex,
839
+ text: hex,
840
+ mutedText: hex,
841
+ accent: hex,
842
+ headingFont: z2.enum(["inter", "newsreader"]),
843
+ bodyFont: z2.literal("inter"),
844
+ radius: z2.enum(["none", "sm", "md", "lg"]),
845
+ density: z2.enum(["compact", "comfortable"])
846
+ }).strict(),
847
+ layout: z2.object({
848
+ sections: z2.array(z2.string()).min(1).max(12),
849
+ header: z2.string(),
850
+ hero: z2.string(),
851
+ categories: z2.string(),
852
+ catalogue: z2.string(),
853
+ productCard: z2.string(),
854
+ checkout: z2.string()
855
+ }).strict(),
856
+ composition: z2.object({
857
+ sections: z2.array(
858
+ z2.object({ section: z2.string(), variant: z2.string(), source: z2.string() }).strict()
859
+ )
860
+ }).strict().optional(),
861
+ media: z2.object({
862
+ heroImage: z2.object({
863
+ ref: z2.string(),
864
+ fit: z2.enum(["cover", "contain"]),
865
+ focus: z2.object({
866
+ x: z2.number().int().min(0).max(100),
867
+ y: z2.number().int().min(0).max(100)
868
+ }).strict()
869
+ }).strict().optional(),
870
+ logo: z2.object({ ref: z2.string(), size: z2.enum(["sm", "md", "lg"]) }).strict().optional()
871
+ }).strict().optional(),
872
+ visibility: z2.object({
873
+ search: z2.boolean(),
874
+ categories: z2.boolean(),
875
+ featured: z2.boolean(),
876
+ about: z2.boolean(),
877
+ reportLink: z2.literal(true)
878
+ }).strict()
879
+ }).strict(),
880
+ blocks: z2.array(
881
+ z2.object({
882
+ id: z2.string().regex(/^[a-z][a-z0-9.-]*$/, "Use a block id like header.simple."),
883
+ version: semver,
884
+ slot: z2.enum(["top", "main", "aside", "footer", "overlay"]),
885
+ props: propsSchema.default({}),
886
+ data: propsSchema.default({})
887
+ }).strict()
888
+ ).min(1).max(20),
889
+ routing: z2.object({
890
+ home: safePath,
891
+ product: safePath.optional(),
892
+ search: safePath.optional()
893
+ }).strict().optional()
894
+ }).strict();
895
+ function parseManifest(value) {
896
+ return manifestSchema.parse(value);
897
+ }
898
+ var DEFAULT_MANIFEST = {
899
+ version: 1,
900
+ store: { slug: "demo" },
901
+ skin: {
902
+ version: 1,
903
+ tokens: {
904
+ background: "#fff5f7",
905
+ surface: "#ffffff",
906
+ text: "#2a121c",
907
+ mutedText: "#704255",
908
+ accent: "#db2777",
909
+ headingFont: "newsreader",
910
+ bodyFont: "inter",
911
+ radius: "md",
912
+ density: "comfortable"
913
+ },
914
+ layout: {
915
+ sections: [
916
+ "header",
917
+ "search",
918
+ "hero",
919
+ "categories",
920
+ "featured",
921
+ "catalogue",
922
+ "about",
923
+ "footer"
924
+ ],
925
+ header: "simple",
926
+ hero: "cover",
927
+ categories: "circles",
928
+ catalogue: "grid",
929
+ productCard: "photoFirst",
930
+ checkout: "sheet"
931
+ },
932
+ visibility: {
933
+ search: true,
934
+ categories: true,
935
+ featured: true,
936
+ about: true,
937
+ reportLink: true
938
+ }
939
+ },
940
+ blocks: [
941
+ { id: "header.simple", version: "1.0.0", slot: "top", props: {}, data: {} },
942
+ { id: "search.bar", version: "1.0.0", slot: "top", props: {}, data: {} },
943
+ { id: "hero.cover", version: "1.0.0", slot: "main", props: {}, data: {} },
944
+ { id: "categories.circles", version: "1.0.0", slot: "main", props: {}, data: {} },
945
+ { id: "featured.grid", version: "1.0.0", slot: "main", props: {}, data: {} },
946
+ { id: "catalogue.grid", version: "1.0.0", slot: "main", props: {}, data: {} },
947
+ { id: "product.detail", version: "1.0.0", slot: "main", props: {}, data: {} },
948
+ { id: "about.card", version: "1.0.0", slot: "main", props: {}, data: {} },
949
+ { id: "footer.simple", version: "1.0.0", slot: "footer", props: {}, data: {} },
950
+ { id: "checkout.sheet", version: "1.0.0", slot: "overlay", props: {}, data: {} }
951
+ ],
952
+ routing: { home: "/", product: "/product/:id", search: "/search" }
953
+ };
954
+
955
+ // packages/cli/src/generator/generate.ts
956
+ import { mkdir, writeFile } from "fs/promises";
957
+ import { dirname, join as join2 } from "path";
958
+
959
+ // packages/runtime/dist/index.js
960
+ var API_CONTEXT_PATH = "/api/stackverify/context";
961
+ var API_CHECKOUT_PATH = "/api/stackverify/checkout";
962
+ var GENERATED_RUNTIME_SOURCE = `import context from "./context.json";
963
+
964
+ export const API_CONTEXT_PATH = "${API_CONTEXT_PATH}";
965
+ export const API_CHECKOUT_PATH = "${API_CHECKOUT_PATH}";
966
+
967
+ export type StoreContext = typeof context;
968
+
969
+ export type BlockProps = {
970
+ context: StoreContext;
971
+ data: Record<string, unknown>;
972
+ props: Record<string, unknown>;
973
+ };
974
+
975
+ export type CartItem = {
976
+ productId: string;
977
+ quantity: number;
978
+ };
979
+
980
+ export type CheckoutInput = {
981
+ items: CartItem[];
982
+ name: string;
983
+ phone: string;
984
+ fulfillment: "pickup" | "delivery";
985
+ paymentChoice: "pay_now" | "on_delivery";
986
+ address?: string;
987
+ note?: string;
988
+ bookingAt?: string;
989
+ visitorId?: string;
990
+ sessionId?: string;
991
+ source?: string;
992
+ idempotencyKey?: string;
993
+ };
994
+
995
+ export type CheckoutResult =
996
+ | {
997
+ ok: true;
998
+ orderId: string;
999
+ token: string;
1000
+ orderNumber: string;
1001
+ totalMinor: number;
1002
+ depositMinor: number;
1003
+ scheduledFor: string | null;
1004
+ whatsappUrl: string;
1005
+ message: string;
1006
+ }
1007
+ | {
1008
+ ok: false;
1009
+ message: string;
1010
+ fieldErrors?: Record<string, string | string[]>;
1011
+ };
1012
+
1013
+ export async function fetchContext(): Promise<StoreContext> {
1014
+ const response = await fetch(API_CONTEXT_PATH, { cache: "no-store" });
1015
+ if (!response.ok) return context;
1016
+ return (await response.json()) as StoreContext;
1017
+ }
1018
+
1019
+ export async function createCheckout(input: CheckoutInput): Promise<CheckoutResult> {
1020
+ const { idempotencyKey, ...body } = input;
1021
+ const key = idempotencyKey ?? crypto.randomUUID();
1022
+ const response = await fetch(API_CHECKOUT_PATH, {
1023
+ body: JSON.stringify(body),
1024
+ headers: {
1025
+ "content-type": "application/json",
1026
+ "Idempotency-Key": key,
1027
+ },
1028
+ method: "POST",
1029
+ });
1030
+ return (await response.json()) as CheckoutResult;
1031
+ }
1032
+
1033
+ export function productsFor(context: StoreContext, limit = 12) {
1034
+ return context.products.slice(0, limit);
1035
+ }
1036
+
1037
+ export function featuredFor(context: StoreContext, limit = 6) {
1038
+ return context.products.filter((product) => product.isFeatured).slice(0, limit);
1039
+ }
1040
+
1041
+ export function categoriesFor(context: StoreContext) {
1042
+ return context.categories;
1043
+ }
1044
+
1045
+ export function productFor(context: StoreContext, data: Record<string, unknown>) {
1046
+ const requested = data.productId;
1047
+ if (typeof requested !== "string") return context.products[0];
1048
+ return context.products.find((product) => product.id === requested) ?? context.products[0];
1049
+ }
1050
+
1051
+ export function searchFor(context: StoreContext, data: Record<string, unknown>) {
1052
+ const query = data.query;
1053
+ if (typeof query !== "string" || query.trim().length === 0) return [];
1054
+ const needle = query.trim().toLowerCase();
1055
+ return context.products.filter(
1056
+ (product) =>
1057
+ product.name.toLowerCase().includes(needle) ||
1058
+ product.description.toLowerCase().includes(needle),
1059
+ );
1060
+ }
1061
+ `;
1062
+
1063
+ // packages/cli/src/generator/generate.ts
1064
+ async function writeText(root, relative, content) {
1065
+ const path = join2(root, relative);
1066
+ await mkdir(dirname(path), { recursive: true });
1067
+ await writeFile(path, content, "utf8");
1068
+ }
1069
+ function componentName(id, index) {
1070
+ const words = id.replace(/[^a-zA-Z0-9]+/g, " ").split(" ").filter(Boolean).map((word) => word.charAt(0).toUpperCase() + word.slice(1));
1071
+ return `${words.join("") || "Block"}${index}`;
1072
+ }
1073
+ function directoryName(id, index) {
1074
+ return `${id.replace(/[^a-z0-9]+/gi, "-").replace(/^-|-$/g, "")}-${index}`;
1075
+ }
1076
+ function tokensCss(manifest) {
1077
+ const tokens = manifest.skin.tokens;
1078
+ const heading = tokens.headingFont === "newsreader" ? '"Newsreader", Georgia, serif' : "Inter, ui-sans-serif, system-ui, sans-serif";
1079
+ const radius = {
1080
+ none: "0px",
1081
+ sm: "6px",
1082
+ md: "12px",
1083
+ lg: "20px"
1084
+ }[tokens.radius];
1085
+ const gap = tokens.density === "compact" ? "0.75rem" : "1.25rem";
1086
+ const pad = tokens.density === "compact" ? "0.9rem" : "1.4rem";
1087
+ return `:root {
1088
+ color-scheme: light;
1089
+ --sv-background: ${tokens.background};
1090
+ --sv-surface: ${tokens.surface};
1091
+ --sv-text: ${tokens.text};
1092
+ --sv-muted: ${tokens.mutedText};
1093
+ --sv-accent: ${tokens.accent};
1094
+ --sv-accent-soft: color-mix(in srgb, var(--sv-surface), var(--sv-accent) 10%);
1095
+ --sv-heading-font: ${heading};
1096
+ --sv-body-font: Inter, ui-sans-serif, system-ui, sans-serif;
1097
+ --sv-radius: ${radius};
1098
+ --sv-gap: ${gap};
1099
+ --sv-pad: ${pad};
1100
+ }
1101
+
1102
+ * {
1103
+ box-sizing: border-box;
1104
+ }
1105
+
1106
+ body {
1107
+ margin: 0;
1108
+ background: var(--sv-background);
1109
+ color: var(--sv-text);
1110
+ font-family: var(--sv-body-font);
1111
+ line-height: 1.5;
1112
+ }
1113
+
1114
+ button,
1115
+ input {
1116
+ font: inherit;
1117
+ }
1118
+
1119
+ .sv-app {
1120
+ width: 100%;
1121
+ max-width: 768px;
1122
+ min-height: 100dvh;
1123
+ margin: 0 auto;
1124
+ padding: 0 var(--sv-pad) 6rem;
1125
+ }
1126
+
1127
+ .sv-header,
1128
+ .sv-hero,
1129
+ .sv-section,
1130
+ .sv-checkout {
1131
+ padding: calc(var(--sv-pad) * 1.5) 0;
1132
+ border-bottom: 1px solid var(--sv-accent-soft);
1133
+ }
1134
+
1135
+ .sv-eyebrow {
1136
+ margin: 0 0 0.35rem;
1137
+ color: var(--sv-muted);
1138
+ font-size: 0.78rem;
1139
+ font-weight: 700;
1140
+ letter-spacing: 0.08em;
1141
+ text-transform: uppercase;
1142
+ }
1143
+
1144
+ .sv-title,
1145
+ .sv-heading,
1146
+ .sv-card-title,
1147
+ .sv-footer-name {
1148
+ margin: 0;
1149
+ font-family: var(--sv-heading-font);
1150
+ font-weight: 800;
1151
+ letter-spacing: -0.02em;
1152
+ }
1153
+
1154
+ .sv-title,
1155
+ .sv-heading {
1156
+ font-size: clamp(1.7rem, 6vw, 2.5rem);
1157
+ }
1158
+
1159
+ .sv-muted {
1160
+ color: var(--sv-muted);
1161
+ }
1162
+
1163
+ .sv-search {
1164
+ padding: var(--sv-gap) 0;
1165
+ }
1166
+
1167
+ .sv-input,
1168
+ .sv-button {
1169
+ width: 100%;
1170
+ min-height: 44px;
1171
+ margin-top: var(--sv-gap);
1172
+ padding: 0.7rem 0.9rem;
1173
+ border: 1px solid var(--sv-accent-soft);
1174
+ border-radius: var(--sv-radius);
1175
+ background: var(--sv-surface);
1176
+ color: var(--sv-text);
1177
+ }
1178
+
1179
+ .sv-button {
1180
+ border-color: var(--sv-accent);
1181
+ background: var(--sv-accent);
1182
+ color: var(--sv-surface);
1183
+ cursor: pointer;
1184
+ font-weight: 700;
1185
+ }
1186
+
1187
+ .sv-results {
1188
+ padding-left: 1.2rem;
1189
+ }
1190
+
1191
+ .sv-categories,
1192
+ .sv-grid {
1193
+ display: grid;
1194
+ gap: var(--sv-gap);
1195
+ grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
1196
+ margin-top: var(--sv-gap);
1197
+ }
1198
+
1199
+ .sv-category {
1200
+ display: flex;
1201
+ align-items: center;
1202
+ justify-content: center;
1203
+ min-height: 72px;
1204
+ padding: var(--sv-pad);
1205
+ border: 1px solid var(--sv-accent-soft);
1206
+ border-radius: var(--sv-radius);
1207
+ background: var(--sv-accent-soft);
1208
+ font-weight: 700;
1209
+ text-align: center;
1210
+ }
1211
+
1212
+ .sv-card {
1213
+ overflow: hidden;
1214
+ border: 1px solid var(--sv-accent-soft);
1215
+ border-radius: var(--sv-radius);
1216
+ background: var(--sv-surface);
1217
+ padding: var(--sv-pad);
1218
+ }
1219
+
1220
+ .sv-photo {
1221
+ aspect-ratio: 4 / 3;
1222
+ border-radius: var(--sv-radius);
1223
+ background: var(--sv-accent-soft);
1224
+ }
1225
+
1226
+ .sv-card-title {
1227
+ margin-top: var(--sv-gap);
1228
+ font-size: 1.1rem;
1229
+ }
1230
+
1231
+ .sv-footer {
1232
+ display: flex;
1233
+ flex-wrap: wrap;
1234
+ gap: var(--sv-gap);
1235
+ align-items: center;
1236
+ justify-content: space-between;
1237
+ padding: calc(var(--sv-pad) * 1.5) 0;
1238
+ border-top: 1px solid var(--sv-accent-soft);
1239
+ }
1240
+
1241
+ .sv-link {
1242
+ color: var(--sv-accent);
1243
+ font-weight: 700;
1244
+ }
1245
+
1246
+ .sv-message {
1247
+ margin-bottom: 0;
1248
+ font-weight: 700;
1249
+ }
1250
+
1251
+ @media (min-width: 640px) {
1252
+ .sv-app {
1253
+ padding-top: 2rem;
1254
+ }
1255
+ }
1256
+ `;
1257
+ }
1258
+ function appSource(manifest, blocks) {
1259
+ const components = blocks.map((block2, index) => ({
1260
+ id: block2.id,
1261
+ name: componentName(block2.id, index),
1262
+ dir: directoryName(block2.id, index)
1263
+ }));
1264
+ const imports = components.map((entry) => `import ${entry.name} from "./blocks/${entry.dir}/index";`).join("\n");
1265
+ const registry = components.map((entry) => ` "${entry.id}": ${entry.name},`).join("\n");
1266
+ const entries = manifest.blocks.map((block2, index) => ({
1267
+ key: `${block2.id}-${index}`,
1268
+ id: block2.id,
1269
+ slot: block2.slot,
1270
+ props: block2.props,
1271
+ data: block2.data
1272
+ }));
1273
+ const entriesText = JSON.stringify(entries, null, 2);
1274
+ return `"use client";
1275
+
1276
+ import { useEffect, useState } from "react";
1277
+ import type { ComponentType } from "react";
1278
+ import fixtureContext from "./context.json";
1279
+ import { fetchContext, type BlockProps, type StoreContext } from "./runtime";
1280
+ ${imports}
1281
+
1282
+ const components: Record<string, ComponentType<BlockProps>> = {
1283
+ ${registry}
1284
+ };
1285
+
1286
+ const entries: Array<{
1287
+ key: string;
1288
+ id: string;
1289
+ slot: string;
1290
+ props: Record<string, unknown>;
1291
+ data: Record<string, unknown>;
1292
+ }> = ${entriesText};
1293
+
1294
+ const slotOrder = ["top", "main", "aside", "footer", "overlay"];
1295
+
1296
+ export default function App() {
1297
+ const [context, setContext] = useState<StoreContext>(fixtureContext);
1298
+
1299
+ useEffect(() => {
1300
+ let active = true;
1301
+ void fetchContext().then((value) => {
1302
+ if (active) setContext(value);
1303
+ });
1304
+ return () => {
1305
+ active = false;
1306
+ };
1307
+ }, []);
1308
+
1309
+ return (
1310
+ <main className="sv-app">
1311
+ {slotOrder.map((slot) =>
1312
+ entries
1313
+ .filter((entry) => entry.slot === slot)
1314
+ .map((entry) => {
1315
+ const Component = components[entry.id];
1316
+ if (!Component) return null;
1317
+ return (
1318
+ <Component
1319
+ context={context}
1320
+ data={entry.data}
1321
+ key={entry.key}
1322
+ props={entry.props}
1323
+ />
1324
+ );
1325
+ }),
1326
+ )}
1327
+ </main>
1328
+ );
1329
+ }
1330
+ `;
1331
+ }
1332
+ async function generateProject(input) {
1333
+ const { root, manifest, target, contractVersion, blocks, context } = input;
1334
+ const lock = createLock(manifest, target, contractVersion, blocks);
1335
+ parseLock(JSON.parse(JSON.stringify(lock)));
1336
+ const name = input.projectName ?? `stackverify-${manifest.store.slug}`;
1337
+ await writeText(root, "store.json", `${JSON.stringify(manifest, null, 2)}
1338
+ `);
1339
+ await writeText(root, "stackverify.lock.json", `${JSON.stringify(lock, null, 2)}
1340
+ `);
1341
+ await writeText(root, "package.json", targetPackageJson(name, target));
1342
+ await writeText(root, ".gitignore", PROJECT_GITIGNORE);
1343
+ await writeText(root, ".env.example", ENV_EXAMPLE);
1344
+ for (const [path, content] of Object.entries(targetFiles(target))) {
1345
+ await writeText(root, path, content);
1346
+ }
1347
+ await writeText(root, "src/generated/context.json", `${JSON.stringify(context, null, 2)}
1348
+ `);
1349
+ await writeText(root, "src/generated/runtime.ts", GENERATED_RUNTIME_SOURCE);
1350
+ await writeText(root, "src/generated/tokens.css", tokensCss(manifest));
1351
+ await writeText(root, "src/generated/App.tsx", appSource(manifest, blocks));
1352
+ for (const [index, block2] of blocks.entries()) {
1353
+ for (const file of block2.files) {
1354
+ const relative = join2(
1355
+ "src",
1356
+ "generated",
1357
+ "blocks",
1358
+ directoryName(block2.id, index),
1359
+ file.path
1360
+ );
1361
+ await writeText(root, relative, file.content);
1362
+ }
1363
+ }
1364
+ return lock;
1365
+ }
1366
+ function assertTarget(value) {
1367
+ if (!TARGETS.some((target) => target === value)) {
1368
+ throw new Error(`Unknown target ${value}. Use vite-react, next or node.`);
1369
+ }
1370
+ return value;
1371
+ }
1372
+
1373
+ // packages/cli/src/platform/client.ts
1374
+ import { randomUUID } from "crypto";
1375
+
1376
+ // packages/cli/src/platform/fixtures.ts
1377
+ var CONTRACT_VERSION = 1;
1378
+ var FIXTURE_CONTEXT = {
1379
+ store: {
1380
+ name: "Demo Kitchen",
1381
+ slug: "demo",
1382
+ tagline: "Home cooked food, ready when you are.",
1383
+ about: "Demonstration store for the StackVerify UI SDK.",
1384
+ themeColor: "#db2777",
1385
+ logo: "",
1386
+ cover: "",
1387
+ acceptingOrders: true,
1388
+ pickupEnabled: true,
1389
+ deliveryEnabled: true,
1390
+ payment: {
1391
+ payOnDelivery: true,
1392
+ mpesa: false
1393
+ }
1394
+ },
1395
+ categories: [
1396
+ { id: "cat-meals", name: "Meals", image: "" },
1397
+ { id: "cat-drinks", name: "Drinks", image: "" }
1398
+ ],
1399
+ products: [
1400
+ {
1401
+ id: "product-1",
1402
+ name: "Chicken and rice",
1403
+ description: "A warm plate with vegetables.",
1404
+ priceMinor: 65e3,
1405
+ currency: "KES",
1406
+ image: "",
1407
+ categoryId: "cat-meals",
1408
+ isFeatured: true
1409
+ },
1410
+ {
1411
+ id: "product-2",
1412
+ name: "Beef stew",
1413
+ description: "Slow cooked beef with ugali.",
1414
+ priceMinor: 6e4,
1415
+ currency: "KES",
1416
+ image: "",
1417
+ categoryId: "cat-meals",
1418
+ isFeatured: false
1419
+ },
1420
+ {
1421
+ id: "product-3",
1422
+ name: "Fruit juice",
1423
+ description: "Fresh fruit juice, 500 ml.",
1424
+ priceMinor: 2e4,
1425
+ currency: "KES",
1426
+ image: "",
1427
+ categoryId: "cat-drinks",
1428
+ isFeatured: false
1429
+ }
1430
+ ],
1431
+ search: {
1432
+ query: "",
1433
+ results: []
1434
+ }
1435
+ };
1436
+ function block(id, version, entry, source, requiredContext, capabilities) {
1437
+ return {
1438
+ id,
1439
+ version,
1440
+ entry,
1441
+ requiredContext,
1442
+ capabilities,
1443
+ files: [{ path: entry, content: source }]
1444
+ };
1445
+ }
1446
+ var BLOCKS = {
1447
+ "header.simple": block(
1448
+ "header.simple",
1449
+ "1.0.0",
1450
+ "index.tsx",
1451
+ `import type { BlockProps } from "../../runtime";
1452
+
1453
+ export default function HeaderSimple({ context, props }: BlockProps) {
1454
+ const name = typeof props.name === "string" ? props.name : context.store.name;
1455
+ const tagline = typeof props.tagline === "string" ? props.tagline : context.store.tagline;
1456
+
1457
+ return (
1458
+ <header className="sv-header">
1459
+ <div>
1460
+ <p className="sv-eyebrow">Welcome to</p>
1461
+ <h1 className="sv-title">{name}</h1>
1462
+ <p className="sv-muted">{tagline}</p>
1463
+ </div>
1464
+ </header>
1465
+ );
1466
+ }
1467
+ `,
1468
+ ["store"],
1469
+ ["store"]
1470
+ ),
1471
+ "search.bar": block(
1472
+ "search.bar",
1473
+ "1.0.0",
1474
+ "index.tsx",
1475
+ `import { useState } from "react";
1476
+ import { searchFor, type BlockProps } from "../../runtime";
1477
+
1478
+ export default function SearchBar({ context }: BlockProps) {
1479
+ const [query, setQuery] = useState("");
1480
+ const results = searchFor(context, { query });
1481
+
1482
+ return (
1483
+ <section className="sv-search" aria-label="Search products">
1484
+ <input
1485
+ aria-label="Search products"
1486
+ className="sv-input"
1487
+ onChange={(event) => setQuery(event.target.value)}
1488
+ placeholder="Search products"
1489
+ value={query}
1490
+ />
1491
+ {query ? (
1492
+ <ul className="sv-results">
1493
+ {results.map((product) => (
1494
+ <li key={product.id}>{product.name}</li>
1495
+ ))}
1496
+ </ul>
1497
+ ) : null}
1498
+ </section>
1499
+ );
1500
+ }
1501
+ `,
1502
+ ["products"],
1503
+ ["products", "search"]
1504
+ ),
1505
+ "hero.cover": block(
1506
+ "hero.cover",
1507
+ "1.0.0",
1508
+ "index.tsx",
1509
+ `import type { BlockProps } from "../../runtime";
1510
+
1511
+ export default function HeroCover({ context, props }: BlockProps) {
1512
+ const title = typeof props.title === "string" ? props.title : context.store.name;
1513
+ const body = typeof props.body === "string" ? props.body : context.store.tagline;
1514
+
1515
+ return (
1516
+ <section className="sv-hero">
1517
+ <p className="sv-eyebrow">Fresh today</p>
1518
+ <h2 className="sv-heading">{title}</h2>
1519
+ <p className="sv-muted">{body}</p>
1520
+ </section>
1521
+ );
1522
+ }
1523
+ `,
1524
+ ["store"],
1525
+ ["store"]
1526
+ ),
1527
+ "categories.circles": block(
1528
+ "categories.circles",
1529
+ "1.0.0",
1530
+ "index.tsx",
1531
+ `import { categoriesFor, type BlockProps } from "../../runtime";
1532
+
1533
+ export default function CategoriesCircles({ context }: BlockProps) {
1534
+ return (
1535
+ <section className="sv-section">
1536
+ <h2 className="sv-heading">Categories</h2>
1537
+ <div className="sv-categories">
1538
+ {categoriesFor(context).map((category) => (
1539
+ <span className="sv-category" key={category.id}>
1540
+ {category.name}
1541
+ </span>
1542
+ ))}
1543
+ </div>
1544
+ </section>
1545
+ );
1546
+ }
1547
+ `,
1548
+ ["categories"],
1549
+ ["categories"]
1550
+ ),
1551
+ "featured.grid": block(
1552
+ "featured.grid",
1553
+ "1.0.0",
1554
+ "index.tsx",
1555
+ `import { featuredFor, type BlockProps } from "../../runtime";
1556
+
1557
+ export default function FeaturedGrid({ context }: BlockProps) {
1558
+ return (
1559
+ <section className="sv-section">
1560
+ <h2 className="sv-heading">Featured</h2>
1561
+ <div className="sv-grid">
1562
+ {featuredFor(context).map((product) => (
1563
+ <article className="sv-card" key={product.id}>
1564
+ <div className="sv-photo" aria-hidden="true" />
1565
+ <h3 className="sv-card-title">{product.name}</h3>
1566
+ <p className="sv-muted">{product.description}</p>
1567
+ </article>
1568
+ ))}
1569
+ </div>
1570
+ </section>
1571
+ );
1572
+ }
1573
+ `,
1574
+ ["products"],
1575
+ ["products"]
1576
+ ),
1577
+ "catalogue.grid": block(
1578
+ "catalogue.grid",
1579
+ "1.0.0",
1580
+ "index.tsx",
1581
+ `import { productsFor, type BlockProps } from "../../runtime";
1582
+
1583
+ export default function CatalogueGrid({ context }: BlockProps) {
1584
+ return (
1585
+ <section className="sv-section">
1586
+ <h2 className="sv-heading">Shop all</h2>
1587
+ <div className="sv-grid">
1588
+ {productsFor(context).map((product) => (
1589
+ <article className="sv-card" key={product.id}>
1590
+ <div className="sv-photo" aria-hidden="true" />
1591
+ <h3 className="sv-card-title">{product.name}</h3>
1592
+ <p className="sv-muted">{product.description}</p>
1593
+ </article>
1594
+ ))}
1595
+ </div>
1596
+ </section>
1597
+ );
1598
+ }
1599
+ `,
1600
+ ["products"],
1601
+ ["products"]
1602
+ ),
1603
+ "product.detail": block(
1604
+ "product.detail",
1605
+ "1.0.0",
1606
+ "index.tsx",
1607
+ `import { productFor, type BlockProps } from "../../runtime";
1608
+
1609
+ export default function ProductDetail({ context, data }: BlockProps) {
1610
+ const product = productFor(context, data);
1611
+ if (!product) return null;
1612
+
1613
+ return (
1614
+ <section className="sv-section">
1615
+ <h2 className="sv-heading">{product.name}</h2>
1616
+ <p className="sv-muted">{product.description}</p>
1617
+ </section>
1618
+ );
1619
+ }
1620
+ `,
1621
+ ["products"],
1622
+ ["products"]
1623
+ ),
1624
+ "about.card": block(
1625
+ "about.card",
1626
+ "1.0.0",
1627
+ "index.tsx",
1628
+ `import type { BlockProps } from "../../runtime";
1629
+
1630
+ export default function AboutCard({ context }: BlockProps) {
1631
+ return (
1632
+ <section className="sv-section">
1633
+ <h2 className="sv-heading">About this store</h2>
1634
+ <p className="sv-muted">{context.store.about}</p>
1635
+ </section>
1636
+ );
1637
+ }
1638
+ `,
1639
+ ["store"],
1640
+ ["store"]
1641
+ ),
1642
+ "footer.simple": block(
1643
+ "footer.simple",
1644
+ "1.0.0",
1645
+ "index.tsx",
1646
+ `import type { BlockProps } from "../../runtime";
1647
+
1648
+ export default function FooterSimple({ context }: BlockProps) {
1649
+ return (
1650
+ <footer className="sv-footer">
1651
+ <div>
1652
+ <p className="sv-footer-name">{context.store.name}</p>
1653
+ <p className="sv-muted">Orders and payments are handled by StackVerify.</p>
1654
+ </div>
1655
+ {context.store.slug ? (
1656
+ <a className="sv-link" href="/report">
1657
+ Report this store
1658
+ </a>
1659
+ ) : null}
1660
+ </footer>
1661
+ );
1662
+ }
1663
+ `,
1664
+ ["store"],
1665
+ ["store"]
1666
+ ),
1667
+ "checkout.sheet": block(
1668
+ "checkout.sheet",
1669
+ "1.0.0",
1670
+ "index.tsx",
1671
+ `import { useState } from "react";
1672
+ import { createCheckout, productFor, type BlockProps } from "../../runtime";
1673
+
1674
+ export default function CheckoutSheet({ context, data }: BlockProps) {
1675
+ const [name, setName] = useState("");
1676
+ const [phone, setPhone] = useState("");
1677
+ const [message, setMessage] = useState("");
1678
+ const [idempotencyKey, setIdempotencyKey] = useState(() => crypto.randomUUID());
1679
+ const product = productFor(context, data);
1680
+
1681
+ async function submit() {
1682
+ if (!product) return;
1683
+ const result = await createCheckout({
1684
+ items: [{ productId: product.id, quantity: 1 }],
1685
+ name,
1686
+ phone,
1687
+ fulfillment: "pickup",
1688
+ paymentChoice: "on_delivery",
1689
+ idempotencyKey,
1690
+ });
1691
+ setMessage(result.message);
1692
+ setIdempotencyKey(crypto.randomUUID());
1693
+ }
1694
+
1695
+ return (
1696
+ <section className="sv-checkout">
1697
+ <h2 className="sv-heading">Checkout</h2>
1698
+ <p className="sv-muted">{product?.name}</p>
1699
+ <input aria-label="Your name" className="sv-input" onChange={(event) => setName(event.target.value)} placeholder="Your name" value={name} />
1700
+ <input aria-label="Phone number" className="sv-input" onChange={(event) => setPhone(event.target.value)} placeholder="Phone number" value={phone} />
1701
+ <button className="sv-button" onClick={() => void submit()} type="button">
1702
+ Place order
1703
+ </button>
1704
+ {message ? <p className="sv-message">{message}</p> : null}
1705
+ </section>
1706
+ );
1707
+ }
1708
+ `,
1709
+ ["products"],
1710
+ ["checkout", "products"]
1711
+ )
1712
+ };
1713
+ function fixtureCheckout(input) {
1714
+ const value = input;
1715
+ if (!Array.isArray(value.items) || value.items.length === 0) {
1716
+ return { ok: false, message: "Add an item before checkout." };
1717
+ }
1718
+ return {
1719
+ ok: true,
1720
+ orderId: "sdk-demo-order",
1721
+ token: "sdk-demo-token",
1722
+ orderNumber: "SDK-DEMO-1",
1723
+ totalMinor: 0,
1724
+ depositMinor: 0,
1725
+ scheduledFor: null,
1726
+ whatsappUrl: "",
1727
+ message: "Demo checkout accepted."
1728
+ };
1729
+ }
1730
+
1731
+ // packages/cli/src/platform/schema.ts
1732
+ import { z as z3 } from "zod";
1733
+ var sha2562 = z3.string().regex(/^[0-9a-f]{64}$/);
1734
+ var semver2 = z3.string().regex(/^\d+\.\d+\.\d+$/);
1735
+ var contractSchema = z3.object({
1736
+ version: z3.literal(1),
1737
+ skinContractVersion: z3.literal(1),
1738
+ generatorVersion: z3.literal(GENERATOR_VERSION),
1739
+ targets: z3.array(z3.enum(["vite-react", "next", "node"])).min(1),
1740
+ blocks: z3.array(z3.object({ id: z3.string().min(1), version: semver2 }).strict()).min(1)
1741
+ }).strict();
1742
+ var blockFileSchema = z3.object({
1743
+ path: z3.string().min(1),
1744
+ sha256: sha2562,
1745
+ content: z3.string()
1746
+ }).strict();
1747
+ var blockSchema = z3.object({
1748
+ id: z3.string().min(1),
1749
+ version: semver2,
1750
+ entry: z3.string().min(1),
1751
+ files: z3.array(blockFileSchema).min(1),
1752
+ propsSchema: z3.unknown(),
1753
+ requiredContext: z3.array(z3.string()),
1754
+ capabilities: z3.array(z3.string()),
1755
+ sha256: sha2562
1756
+ }).strict();
1757
+ var blockListSchema = z3.object({ blocks: z3.array(blockSchema) }).strict();
1758
+ var storeSchema = z3.object({
1759
+ name: z3.string(),
1760
+ slug: z3.string().min(1),
1761
+ tagline: z3.string(),
1762
+ about: z3.string(),
1763
+ themeColor: z3.string(),
1764
+ logo: z3.string(),
1765
+ cover: z3.string(),
1766
+ acceptingOrders: z3.boolean(),
1767
+ pickupEnabled: z3.boolean(),
1768
+ deliveryEnabled: z3.boolean(),
1769
+ payment: z3.object({ payOnDelivery: z3.boolean(), mpesa: z3.boolean() }).strict()
1770
+ }).strict();
1771
+ var categorySchema = z3.object({ id: z3.string(), name: z3.string(), image: z3.string() }).strict();
1772
+ var productSchema = z3.object({
1773
+ id: z3.string(),
1774
+ name: z3.string(),
1775
+ description: z3.string(),
1776
+ priceMinor: z3.number().int().nonnegative(),
1777
+ currency: z3.string(),
1778
+ image: z3.string(),
1779
+ categoryId: z3.string(),
1780
+ isFeatured: z3.boolean()
1781
+ }).strict();
1782
+ var searchSchema = z3.object({
1783
+ query: z3.string(),
1784
+ results: z3.array(productSchema)
1785
+ }).strict();
1786
+ var storeContextSchema = z3.object({
1787
+ store: storeSchema,
1788
+ categories: z3.array(categorySchema),
1789
+ products: z3.array(productSchema),
1790
+ search: searchSchema
1791
+ }).strict();
1792
+ var fieldErrorsSchema = z3.record(z3.string(), z3.union([z3.string(), z3.array(z3.string())]));
1793
+ var checkoutResultSchema = z3.discriminatedUnion("ok", [
1794
+ z3.object({
1795
+ ok: z3.literal(true),
1796
+ orderId: z3.string().min(1),
1797
+ token: z3.string(),
1798
+ orderNumber: z3.string(),
1799
+ totalMinor: z3.number().int().nonnegative(),
1800
+ depositMinor: z3.number().int().nonnegative(),
1801
+ scheduledFor: z3.string().nullable(),
1802
+ whatsappUrl: z3.string(),
1803
+ message: z3.string()
1804
+ }).strict(),
1805
+ z3.object({
1806
+ ok: z3.literal(false),
1807
+ message: z3.string(),
1808
+ fieldErrors: fieldErrorsSchema.optional()
1809
+ }).strict()
1810
+ ]);
1811
+ var checkoutInputSchema = z3.object({
1812
+ items: z3.array(
1813
+ z3.object({ productId: z3.string().min(1), quantity: z3.number().int().min(1).max(99) }).strict()
1814
+ ).min(1).max(50),
1815
+ name: z3.string().min(1),
1816
+ phone: z3.string().min(1),
1817
+ fulfillment: z3.enum(["pickup", "delivery"]),
1818
+ paymentChoice: z3.enum(["pay_now", "on_delivery"]).default("pay_now"),
1819
+ address: z3.string().optional(),
1820
+ note: z3.string().optional(),
1821
+ bookingAt: z3.string().optional(),
1822
+ visitorId: z3.string().optional(),
1823
+ sessionId: z3.string().optional(),
1824
+ source: z3.string().optional(),
1825
+ idempotencyKey: z3.string().optional()
1826
+ }).strict().superRefine((value, context) => {
1827
+ if (value.fulfillment === "delivery" && !value.address?.trim()) {
1828
+ context.addIssue({
1829
+ code: z3.ZodIssueCode.custom,
1830
+ path: ["address"],
1831
+ message: "An address is required for delivery."
1832
+ });
1833
+ }
1834
+ });
1835
+
1836
+ // packages/cli/src/platform/client.ts
1837
+ var API_ROOT = "/api/sdk/v1";
1838
+ var TIMEOUT_MS = 1e4;
1839
+ function resolveBlock(id, version) {
1840
+ const block2 = BLOCKS[id];
1841
+ if (!block2) throw new Error(`Block ${id} is not in the SDK registry.`);
1842
+ if (block2.version !== version) {
1843
+ throw new Error(`Block ${id} does not have version ${version}.`);
1844
+ }
1845
+ const files = block2.files.map((file) => ({
1846
+ ...file,
1847
+ sha256: sha256(file.content)
1848
+ }));
1849
+ return {
1850
+ id,
1851
+ version: block2.version,
1852
+ entry: block2.entry,
1853
+ files,
1854
+ requiredContext: block2.requiredContext,
1855
+ capabilities: block2.capabilities,
1856
+ sha256: sha256({ id, version: block2.version, files })
1857
+ };
1858
+ }
1859
+ function createFixtureClient() {
1860
+ return {
1861
+ async contractVersion() {
1862
+ return CONTRACT_VERSION;
1863
+ },
1864
+ async resolveBlocks(manifest) {
1865
+ const seen = /* @__PURE__ */ new Set();
1866
+ const blocks = [];
1867
+ for (const item of manifest.blocks) {
1868
+ if (seen.has(`${item.id}@${item.version}`)) continue;
1869
+ seen.add(`${item.id}@${item.version}`);
1870
+ blocks.push(resolveBlock(item.id, item.version));
1871
+ }
1872
+ return blocks;
1873
+ },
1874
+ async context(manifest) {
1875
+ return {
1876
+ ...FIXTURE_CONTEXT,
1877
+ store: {
1878
+ ...FIXTURE_CONTEXT.store,
1879
+ name: manifest.store.slug === "demo" ? "Demo Kitchen" : manifest.store.slug,
1880
+ slug: manifest.store.slug,
1881
+ themeColor: manifest.skin.tokens.accent
1882
+ }
1883
+ };
1884
+ },
1885
+ async checkout(input) {
1886
+ return fixtureCheckout(input);
1887
+ }
1888
+ };
1889
+ }
1890
+ function buildUrl(baseUrl, segments, params = {}) {
1891
+ const url = new URL(baseUrl);
1892
+ const prefix = url.pathname.replace(/\/$/, "");
1893
+ url.pathname = `${prefix}${API_ROOT}/${segments.map(encodeURIComponent).join("/")}`;
1894
+ url.search = "";
1895
+ url.hash = "";
1896
+ for (const [key, value] of Object.entries(params)) {
1897
+ if (value) url.searchParams.set(key, value);
1898
+ }
1899
+ return url.toString();
1900
+ }
1901
+ function readKey(value, label, prefix) {
1902
+ const key = value?.trim();
1903
+ if (!key) throw new Error(`${label} is required.`);
1904
+ if (!key.startsWith(prefix)) throw new Error(`${label} is invalid.`);
1905
+ return key;
1906
+ }
1907
+ function writeKey(env) {
1908
+ const secret = env.secretKey?.trim();
1909
+ if (secret) return readKey(secret, "The secret key", "svsdk_sec_");
1910
+ const legacy = env.apiKey?.trim();
1911
+ if (!legacy) throw new Error("A secret key is required for checkout.");
1912
+ return legacy;
1913
+ }
1914
+ function readSlug(target) {
1915
+ const value = typeof target === "string" ? target : target?.store?.slug;
1916
+ const slug2 = value?.trim();
1917
+ if (!slug2 || !/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug2)) {
1918
+ throw new Error("A valid store slug is required for checkout.");
1919
+ }
1920
+ return slug2;
1921
+ }
1922
+ async function requestJson(url, key, init2 = {}) {
1923
+ let response;
1924
+ try {
1925
+ response = await fetch(url, {
1926
+ ...init2,
1927
+ headers: {
1928
+ accept: "application/json",
1929
+ authorization: `Bearer ${key}`,
1930
+ ...init2.headers
1931
+ },
1932
+ signal: AbortSignal.timeout(TIMEOUT_MS)
1933
+ });
1934
+ } catch (error) {
1935
+ if (error instanceof Error && error.name === "TimeoutError") {
1936
+ throw new Error("The platform API timed out.");
1937
+ }
1938
+ throw new Error("The platform API request failed.");
1939
+ }
1940
+ let value;
1941
+ try {
1942
+ value = await response.json();
1943
+ } catch {
1944
+ throw new Error("The platform API returned an invalid response.");
1945
+ }
1946
+ return { response, value };
1947
+ }
1948
+ async function readJson(url, key) {
1949
+ const { response, value } = await requestJson(url, key);
1950
+ if (!response.ok) {
1951
+ throw new Error(`The platform API rejected the request with status ${response.status}.`);
1952
+ }
1953
+ return value;
1954
+ }
1955
+ function verifyBlock(block2) {
1956
+ const files = block2.files.map((file) => {
1957
+ const hash2 = sha256(file.content);
1958
+ if (file.sha256 !== hash2) {
1959
+ throw new Error(`Block ${block2.id}@${block2.version} file ${file.path} has an invalid hash.`);
1960
+ }
1961
+ return { path: file.path, content: file.content, sha256: hash2 };
1962
+ });
1963
+ if (!files.some((file) => file.path === block2.entry)) {
1964
+ throw new Error(`Block ${block2.id}@${block2.version} entry is missing.`);
1965
+ }
1966
+ const hash = sha256({ id: block2.id, version: block2.version, files });
1967
+ if (block2.sha256 !== hash) {
1968
+ throw new Error(`Block ${block2.id}@${block2.version} has an invalid hash.`);
1969
+ }
1970
+ return {
1971
+ id: block2.id,
1972
+ version: block2.version,
1973
+ entry: block2.entry,
1974
+ files,
1975
+ requiredContext: block2.requiredContext,
1976
+ capabilities: block2.capabilities,
1977
+ sha256: hash
1978
+ };
1979
+ }
1980
+ function createHttpClient(env, publishableKey) {
1981
+ const baseUrl = parseApiUrl(env.apiUrl);
1982
+ return {
1983
+ async contractVersion() {
1984
+ const value = await readJson(buildUrl(baseUrl, ["contract"]), publishableKey);
1985
+ return contractSchema.parse(value).version;
1986
+ },
1987
+ async resolveBlocks(manifest) {
1988
+ const value = await readJson(buildUrl(baseUrl, ["blocks"]), publishableKey);
1989
+ const list = blockListSchema.parse(value);
1990
+ const seen = /* @__PURE__ */ new Set();
1991
+ const blocks = [];
1992
+ for (const item of manifest.blocks) {
1993
+ if (seen.has(`${item.id}@${item.version}`)) continue;
1994
+ seen.add(`${item.id}@${item.version}`);
1995
+ const found = list.blocks.find(
1996
+ (block2) => block2.id === item.id && block2.version === item.version
1997
+ );
1998
+ if (!found) {
1999
+ const sameId = list.blocks.some((block2) => block2.id === item.id);
2000
+ if (sameId) {
2001
+ throw new Error(`Block ${item.id} does not have version ${item.version}.`);
2002
+ }
2003
+ throw new Error(`Block ${item.id} is not available.`);
2004
+ }
2005
+ blocks.push(verifyBlock(found));
2006
+ }
2007
+ return blocks;
2008
+ },
2009
+ async context(manifest, query) {
2010
+ const trimmed = query?.trim();
2011
+ const value = await readJson(
2012
+ buildUrl(
2013
+ baseUrl,
2014
+ ["storefronts", manifest.store.slug, "context"],
2015
+ trimmed ? { q: trimmed } : {}
2016
+ ),
2017
+ publishableKey
2018
+ );
2019
+ return storeContextSchema.parse(value);
2020
+ },
2021
+ async checkout(input, target) {
2022
+ const parsed = checkoutInputSchema.safeParse(input);
2023
+ if (!parsed.success) throw new Error("Checkout input is invalid.");
2024
+ const { idempotencyKey, ...body } = parsed.data;
2025
+ const key = idempotencyKey ?? randomUUID();
2026
+ const { response, value } = await requestJson(
2027
+ buildUrl(baseUrl, ["storefronts", readSlug(target), "checkout"]),
2028
+ writeKey(env),
2029
+ {
2030
+ method: "POST",
2031
+ body: JSON.stringify(body),
2032
+ headers: {
2033
+ "content-type": "application/json",
2034
+ "Idempotency-Key": key
2035
+ }
2036
+ }
2037
+ );
2038
+ const result = checkoutResultSchema.safeParse(value);
2039
+ if (!result.success) {
2040
+ throw new Error("The platform API returned an invalid checkout response.");
2041
+ }
2042
+ if (response.ok || !result.data.ok) return result.data;
2043
+ throw new Error("The platform API rejected the checkout request.");
2044
+ }
2045
+ };
2046
+ }
2047
+ function createPlatformClient(env) {
2048
+ const publishableKey = env.publishableKey?.trim();
2049
+ if (env.fixtures || !publishableKey?.startsWith("svsdk_pub_")) {
2050
+ return createFixtureClient();
2051
+ }
2052
+ return createHttpClient(env, readKey(publishableKey, "The publishable key", "svsdk_pub_"));
2053
+ }
2054
+
2055
+ // packages/cli/src/index.ts
2056
+ function projectRoot(input) {
2057
+ return resolve(process.cwd(), input ?? ".");
2058
+ }
2059
+ async function platformClientFor(root, warn = false) {
2060
+ const env = await loadEnv(root);
2061
+ if (warn && (env.fixtures || !env.publishableKey?.startsWith("svsdk_pub_"))) {
2062
+ console.warn("Warning: fixtures mode is active. The app will use demo data.");
2063
+ }
2064
+ return createPlatformClient(env);
2065
+ }
2066
+ async function existingManifest(root) {
2067
+ const text = await readFile2(`${root}/store.json`, "utf8");
2068
+ return parseManifest(JSON.parse(text));
2069
+ }
2070
+ async function sync(root, warn = false) {
2071
+ const manifest = await existingManifest(root);
2072
+ const targetFile = await readFile2(`${root}/stackverify.lock.json`, "utf8");
2073
+ const lock = parseLock(JSON.parse(targetFile));
2074
+ const client = await platformClientFor(root, warn);
2075
+ const contractVersion = await client.contractVersion();
2076
+ const blocks = await client.resolveBlocks(manifest);
2077
+ if (!verifyLock(lock, manifest, lock.target, contractVersion, blocks)) {
2078
+ throw new Error("The lock file does not match the design JSON. Run stackverify sync.");
2079
+ }
2080
+ return { manifest, lock, client, contractVersion, blocks };
2081
+ }
2082
+ async function writeGenerated(input) {
2083
+ const client = await platformClientFor(input.root, input.warn);
2084
+ const contractVersion = await client.contractVersion();
2085
+ const blocks = await client.resolveBlocks(input.manifest);
2086
+ const context = await client.context(input.manifest);
2087
+ await generateProject({
2088
+ root: input.root,
2089
+ manifest: input.manifest,
2090
+ target: input.target,
2091
+ contractVersion,
2092
+ blocks,
2093
+ context,
2094
+ projectName: input.projectName
2095
+ });
2096
+ }
2097
+ async function init(name, target) {
2098
+ const root = projectRoot(name);
2099
+ const chosen = assertTarget(target);
2100
+ await mkdir2(root, { recursive: true });
2101
+ const manifestPath = `${root}/store.json`;
2102
+ const manifest = await (async () => {
2103
+ try {
2104
+ return parseManifest(JSON.parse(await readFile2(manifestPath, "utf8")));
2105
+ } catch {
2106
+ return DEFAULT_MANIFEST;
2107
+ }
2108
+ })();
2109
+ await writeGenerated({ root, manifest, target: chosen });
2110
+ console.log(`Created a ${chosen} StackVerify project in ${root}.`);
2111
+ console.log("Next: npm install, then npx stackverify dev.");
2112
+ }
2113
+ async function syncCommand(root, warn = false) {
2114
+ const manifest = await existingManifest(root);
2115
+ const target = await (async () => {
2116
+ try {
2117
+ const text = await readFile2(`${root}/stackverify.lock.json`, "utf8");
2118
+ return parseLock(JSON.parse(text)).target;
2119
+ } catch {
2120
+ return "vite-react";
2121
+ }
2122
+ })();
2123
+ await writeGenerated({ root, manifest, target, warn });
2124
+ console.log("StackVerify files updated.");
2125
+ return target;
2126
+ }
2127
+ async function runScript(root, command) {
2128
+ const target = command === "start" ? (await sync(root, true)).lock.target : await syncCommand(root, true);
2129
+ const [program, args] = TARGET_COMMANDS[target][command];
2130
+ const child = spawn(program ?? "npm", args ?? [], { cwd: root, stdio: "inherit" });
2131
+ await new Promise((done, reject) => {
2132
+ child.on("error", reject);
2133
+ child.on("exit", (code) => {
2134
+ if (code === 0) done();
2135
+ else reject(new Error(`${program} ${command} exited with ${code}.`));
2136
+ });
2137
+ });
2138
+ }
2139
+ function help() {
2140
+ return `StackVerify UI SDK
2141
+
2142
+ Usage:
2143
+ npx @stackverify/ui init [directory] [--target vite-react|next|node]
2144
+ npx stackverify sync [directory]
2145
+ npx stackverify dev [directory]
2146
+ npx stackverify build [directory]
2147
+ npx stackverify start [directory]
2148
+
2149
+ Commands:
2150
+ init Create a generated storefront project
2151
+ sync Rebuild generated files from store.json
2152
+ dev Sync files, then run the target dev server
2153
+ build Sync files, then build the target app
2154
+ start Check the lock file, then start the target app
2155
+ `;
2156
+ }
2157
+ async function runCli(argv) {
2158
+ const [command, ...rest] = argv;
2159
+ if (!command || command === "--help" || command === "-h") {
2160
+ console.log(help());
2161
+ return;
2162
+ }
2163
+ if (command === "init") {
2164
+ const targetFlag = rest.indexOf("--target");
2165
+ const target = targetFlag >= 0 ? rest[targetFlag + 1] ?? "vite-react" : "vite-react";
2166
+ if (!isTarget(target))
2167
+ throw new Error(`Unknown target ${target}. Use vite-react, next or node.`);
2168
+ const name = rest.find((item) => !item.startsWith("--") && item !== target);
2169
+ await init(name, target);
2170
+ return;
2171
+ }
2172
+ if (command === "sync") {
2173
+ await syncCommand(projectRoot(rest[0]));
2174
+ return;
2175
+ }
2176
+ if (command === "dev" || command === "build" || command === "start") {
2177
+ await runScript(projectRoot(rest[0]), command);
2178
+ return;
2179
+ }
2180
+ throw new Error(`Unknown command ${command}. Run stackverify --help.`);
2181
+ }
2182
+
2183
+ // packages/cli/src/bin.ts
2184
+ runCli(process.argv.slice(2)).catch((error) => {
2185
+ console.error(error instanceof Error ? error.message : "StackVerify command failed.");
2186
+ process.exitCode = 1;
2187
+ });