@orunelle/theme-runtime 0.0.0-stage → 2.0.0-alpha.13

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 (97) hide show
  1. package/dist/application.d.ts +7 -0
  2. package/dist/application.d.ts.map +1 -0
  3. package/dist/application.js +58 -0
  4. package/dist/cli.d.ts +3 -0
  5. package/dist/cli.d.ts.map +1 -0
  6. package/dist/cli.js +429 -0
  7. package/dist/commerce.d.ts +235 -0
  8. package/dist/commerce.d.ts.map +1 -0
  9. package/dist/commerce.js +316 -0
  10. package/dist/credentials.d.ts +11 -0
  11. package/dist/credentials.d.ts.map +1 -0
  12. package/dist/credentials.js +79 -0
  13. package/dist/fixtures.d.ts +23 -0
  14. package/dist/fixtures.d.ts.map +1 -0
  15. package/dist/fixtures.js +131 -0
  16. package/dist/host/package.json +1 -0
  17. package/dist/host/preview/editor.css +116 -0
  18. package/dist/host/preview/editor.tsx +193 -0
  19. package/dist/host/preview/src/bridge.tsx +371 -0
  20. package/dist/host/preview/src/client.tsx +15 -0
  21. package/dist/host/preview/src/env.d.ts +5 -0
  22. package/dist/host/preview/src/preview.css +40 -0
  23. package/dist/host/preview/src/server.tsx +95 -0
  24. package/dist/host/preview/src/surface.tsx +264 -0
  25. package/dist/host/serve-node.mjs +133 -0
  26. package/dist/host/storefront/public/fonts/9da48a48bf6500f8-s.p.woff2 +0 -0
  27. package/dist/host/storefront/public/fonts/e4af272ccee01ff0-s.p.woff2 +0 -0
  28. package/dist/host/storefront/public/fonts/e4efb0298547fad0-s.p.woff2 +0 -0
  29. package/dist/host/storefront/public/fonts/f022b1629605b85c-s.p.woff2 +0 -0
  30. package/dist/host/storefront/public/fonts/fb66eb17bf011c3b-s.p.woff2 +0 -0
  31. package/dist/host/storefront/public/fonts.css +7 -0
  32. package/dist/host/storefront/public/samples/pouch-navy.svg +4 -0
  33. package/dist/host/storefront/public/samples/throw-oat.svg +2 -0
  34. package/dist/host/storefront/public/samples/throw-sage.svg +2 -0
  35. package/dist/host/storefront/public/samples/tote-charcoal.svg +5 -0
  36. package/dist/host/storefront/public/samples/tote-detail.svg +1 -0
  37. package/dist/host/storefront/public/samples/tote-sand.svg +5 -0
  38. package/dist/host/storefront/src/binding.server.ts +1 -0
  39. package/dist/host/storefront/src/data.ts +2 -0
  40. package/dist/host/storefront/src/env.d.ts +5 -0
  41. package/dist/host/storefront/src/queries.ts +1 -0
  42. package/dist/host/storefront/src/routeTree.gen.ts +155 -0
  43. package/dist/host/storefront/src/router.tsx +31 -0
  44. package/dist/host/storefront/src/routes/$locale.$.tsx +135 -0
  45. package/dist/host/storefront/src/routes/$locale.index.tsx +19 -0
  46. package/dist/host/storefront/src/routes/$locale.products.$handle.tsx +57 -0
  47. package/dist/host/storefront/src/routes/$locale.tsx +36 -0
  48. package/dist/host/storefront/src/routes/__root.tsx +103 -0
  49. package/dist/host/storefront/src/routes/index.tsx +6 -0
  50. package/dist/host/storefront/src/server.ts +1 -0
  51. package/dist/host.d.ts +45 -0
  52. package/dist/host.d.ts.map +1 -0
  53. package/dist/host.js +380 -0
  54. package/dist/local-editor.d.ts +2 -0
  55. package/dist/local-editor.d.ts.map +1 -0
  56. package/dist/local-editor.js +111 -0
  57. package/dist/managed-worker.d.ts +2 -0
  58. package/dist/managed-worker.d.ts.map +1 -0
  59. package/dist/managed-worker.js +22 -0
  60. package/dist/server.d.ts +5 -0
  61. package/dist/server.d.ts.map +1 -0
  62. package/dist/server.js +98 -0
  63. package/dist/source.d.ts +19 -0
  64. package/dist/source.d.ts.map +1 -0
  65. package/dist/source.js +131 -0
  66. package/dist/tanstack/binding.server.d.ts +4 -0
  67. package/dist/tanstack/binding.server.d.ts.map +1 -0
  68. package/dist/tanstack/binding.server.js +9 -0
  69. package/dist/tanstack/data.d.ts +44 -0
  70. package/dist/tanstack/data.d.ts.map +1 -0
  71. package/dist/tanstack/data.js +320 -0
  72. package/dist/tanstack/index.d.ts +4 -0
  73. package/dist/tanstack/index.d.ts.map +1 -0
  74. package/dist/tanstack/index.js +2 -0
  75. package/dist/tanstack/queries.d.ts +6 -0
  76. package/dist/tanstack/queries.d.ts.map +1 -0
  77. package/dist/tanstack/queries.js +5 -0
  78. package/dist/template/app/client.tsx +3 -0
  79. package/dist/template/app/env.d.ts +1 -0
  80. package/dist/template/app/router.tsx +40 -0
  81. package/dist/template/app/routes/$locale.$.tsx +135 -0
  82. package/dist/template/app/routes/$locale.index.tsx +19 -0
  83. package/dist/template/app/routes/$locale.products.$handle.tsx +57 -0
  84. package/dist/template/app/routes/$locale.tsx +46 -0
  85. package/dist/template/app/routes/__root.tsx +103 -0
  86. package/dist/template/app/routes/index.tsx +6 -0
  87. package/dist/template/app/server.ts +1 -0
  88. package/dist/template/app/start.ts +2 -0
  89. package/dist/template/app/theme.ts +12 -0
  90. package/dist/template/tests/router-isolation.test.ts +14 -0
  91. package/dist/template/vite.config.ts +5 -0
  92. package/dist/template/vitest.config.ts +9 -0
  93. package/dist/vite.d.ts +7 -0
  94. package/dist/vite.d.ts.map +1 -0
  95. package/dist/vite.js +22 -0
  96. package/package.json +88 -3
  97. package/README.md +0 -3
package/dist/source.js ADDED
@@ -0,0 +1,131 @@
1
+ import { createHash } from "node:crypto";
2
+ import { lstat, open, readdir, realpath } from "node:fs/promises";
3
+ import { constants } from "node:fs";
4
+ import { resolve, join, relative, sep, posix } from "node:path";
5
+ import { themeManifestSchema, validateConfigurationTemplate, } from "@orunelle/theme-contract";
6
+ export const sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex");
7
+ export function validateSource(source) {
8
+ if (source.schemaVersion !== 2 ||
9
+ !Array.isArray(source.files) ||
10
+ !source.files.length ||
11
+ source.files.length > 128)
12
+ throw new Error("Source must contain 1–128 files (schemaVersion 2).");
13
+ let previous = "", size = 0;
14
+ const lines = [];
15
+ const files = new Map();
16
+ for (const file of source.files) {
17
+ const path = file.path;
18
+ if (typeof path !== "string" ||
19
+ path.length > 160 ||
20
+ !/^[a-zA-Z0-9_$/-]+(?:\.[a-zA-Z0-9_$-]+)*$/.test(path) ||
21
+ posix.normalize(path) !== path ||
22
+ path.startsWith("/") ||
23
+ path <= previous)
24
+ throw new Error("Source paths must be unique, sorted, relative and portable.");
25
+ previous = path;
26
+ const allowed = ["orunelle.theme.json", "defaults.json"].includes(path) ||
27
+ /^app\/.+\.(ts|tsx|css|json)$/.test(path) ||
28
+ /^locales\/.+\.json$/.test(path) ||
29
+ /^public\/.+\.(png|jpg|jpeg|webp|avif|woff2|ico)$/.test(path);
30
+ if (!allowed ||
31
+ typeof file.content !== "string" ||
32
+ file.content.length > 700000)
33
+ throw new Error(`Unsupported or oversized source file: ${path}`);
34
+ const bytes = Buffer.from(file.content, "base64");
35
+ size += bytes.length;
36
+ if (bytes.toString("base64") !== file.content ||
37
+ bytes.length > 512 * 1024 ||
38
+ size > 2 * 1024 * 1024)
39
+ throw new Error("Source exceeds file/total limits or contains invalid base64.");
40
+ if (!path.startsWith("public/") &&
41
+ (bytes.includes(0) || !Buffer.from(bytes.toString("utf8")).equals(bytes)))
42
+ throw new Error(`Text must be UTF-8 without NUL: ${path}`);
43
+ lines.push(`${sha256(bytes)} ${path}\n`);
44
+ files.set(path, bytes);
45
+ }
46
+ const manifest = themeManifestSchema.parse(JSON.parse(files.get("orunelle.theme.json")?.toString() ?? "null"));
47
+ if (!files.has("app/theme.ts") && !files.has("app/theme.tsx"))
48
+ throw new Error("Missing app/theme.ts or app/theme.tsx.");
49
+ const application = files.has("app/router.tsx");
50
+ if (application && !files.has("app/routes/__root.tsx"))
51
+ throw new Error("A theme application requires app/routes/__root.tsx.");
52
+ const defaults = files.has("defaults.json")
53
+ ? JSON.parse(files.get("defaults.json").toString())
54
+ : undefined;
55
+ if (defaults && validateConfigurationTemplate(manifest, defaults))
56
+ throw new Error("defaults.json does not match the manifest.");
57
+ return {
58
+ manifest,
59
+ defaults,
60
+ sourceDigest: sha256(lines.join("")),
61
+ files,
62
+ application,
63
+ };
64
+ }
65
+ /** Never follows a source symlink or reads credentials/package lifecycle hooks. */
66
+ export async function readSource(directory) {
67
+ const root = await realpath(directory), files = [];
68
+ async function walk(path) {
69
+ if (relative(root, path).split(sep).join("/") === "app/routeTree.gen.ts")
70
+ return;
71
+ const info = await lstat(path);
72
+ if (info.isSymbolicLink())
73
+ throw new Error(`Source symlinks are unsupported: ${relative(root, path)}`);
74
+ if (info.isDirectory()) {
75
+ for (const entry of (await readdir(path)).sort())
76
+ await walk(join(path, entry));
77
+ return;
78
+ }
79
+ if (!info.isFile() || info.nlink !== 1 || info.size > 512 * 1024)
80
+ throw new Error(`Source must be a single regular file under 512 KiB: ${path}`);
81
+ const file = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
82
+ try {
83
+ const before = await file.stat();
84
+ if (!before.isFile() ||
85
+ before.nlink !== 1 ||
86
+ before.size > 512 * 1024 ||
87
+ before.ino !== info.ino ||
88
+ before.dev !== info.dev)
89
+ throw new Error("Source file changed while reading.");
90
+ const bytes = Buffer.alloc(before.size);
91
+ let count = 0;
92
+ while (count < bytes.length) {
93
+ const read = await file.read(bytes, count, bytes.length - count, count);
94
+ if (!read.bytesRead)
95
+ break;
96
+ count += read.bytesRead;
97
+ }
98
+ const after = await file.stat();
99
+ if (count !== before.size ||
100
+ after.size !== before.size ||
101
+ after.mtimeMs !== before.mtimeMs ||
102
+ after.ctimeMs !== before.ctimeMs ||
103
+ after.nlink !== 1)
104
+ throw new Error("Source file changed while reading.");
105
+ files.push({
106
+ path: relative(root, path).split(sep).join("/"),
107
+ content: bytes.toString("base64"),
108
+ });
109
+ if (files.length > 128)
110
+ throw new Error("Source has more than 128 files.");
111
+ }
112
+ finally {
113
+ await file.close();
114
+ }
115
+ }
116
+ for (const name of [
117
+ "app",
118
+ "locales",
119
+ "public",
120
+ "defaults.json",
121
+ "orunelle.theme.json",
122
+ ]) {
123
+ const path = resolve(root, name);
124
+ if (await lstat(path).catch(() => null))
125
+ await walk(path);
126
+ }
127
+ files.sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
128
+ const source = { schemaVersion: 2, files };
129
+ validateSource(source);
130
+ return source;
131
+ }
@@ -0,0 +1,4 @@
1
+ import type { CommerceEnvironment } from "../commerce.js";
2
+ export declare const requestEnvironment: () => CommerceEnvironment;
3
+ export declare function withBinding<T>(env: CommerceEnvironment, fn: () => T): T;
4
+ //# sourceMappingURL=binding.server.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"binding.server.d.ts","sourceRoot":"","sources":["../../src/tanstack/binding.server.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,gBAAgB,CAAC;AAK1D,eAAO,MAAM,kBAAkB,QACzB,mBACL,CAAC;AACF,wBAAgB,WAAW,CAAC,CAAC,EAAE,GAAG,EAAE,mBAAmB,EAAE,EAAE,EAAE,MAAM,CAAC,GAAG,CAAC,CAEvE"}
@@ -0,0 +1,9 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { createServerOnlyFn } from "@tanstack/react-start";
3
+ // Each SSR/server-function request has its own binding. A worker may render
4
+ // multiple stores concurrently; process.env is never changed per request.
5
+ const bindings = new AsyncLocalStorage();
6
+ export const requestEnvironment = createServerOnlyFn(() => bindings.getStore() ?? process.env);
7
+ export function withBinding(env, fn) {
8
+ return bindings.run(env, fn);
9
+ }
@@ -0,0 +1,44 @@
1
+ import { z } from "zod";
2
+ import { type RoutePageData } from "@orunelle/theme-sdk";
3
+ export declare const getStorefront: import("@tanstack/react-start").OptionalFetcher<undefined, undefined, import("@orunelle/theme-contract").StorefrontContext>;
4
+ declare const inputSchema: z.ZodObject<{
5
+ kind: z.ZodEnum<["home", "catalog", "categories", "category", "collections", "collection", "search", "product", "content"]>;
6
+ locale: z.ZodEnum<["en", "ar"]>;
7
+ slug: z.ZodDefault<z.ZodString>;
8
+ page: z.ZodDefault<z.ZodNumber>;
9
+ q: z.ZodDefault<z.ZodString>;
10
+ }, "strip", z.ZodTypeAny, {
11
+ kind: "search" | "home" | "collections" | "product" | "collection" | "catalog" | "categories" | "category" | "content";
12
+ locale: "en" | "ar";
13
+ slug: string;
14
+ page: number;
15
+ q: string;
16
+ }, {
17
+ kind: "search" | "home" | "collections" | "product" | "collection" | "catalog" | "categories" | "category" | "content";
18
+ locale: "en" | "ar";
19
+ slug?: string | undefined;
20
+ page?: number | undefined;
21
+ q?: string | undefined;
22
+ }>;
23
+ export type PublicInput = z.input<typeof inputSchema>;
24
+ export declare const getPublicPage: import("@tanstack/react-start").RequiredFetcher<undefined, z.ZodObject<{
25
+ kind: z.ZodEnum<["home", "catalog", "categories", "category", "collections", "collection", "search", "product", "content"]>;
26
+ locale: z.ZodEnum<["en", "ar"]>;
27
+ slug: z.ZodDefault<z.ZodString>;
28
+ page: z.ZodDefault<z.ZodNumber>;
29
+ q: z.ZodDefault<z.ZodString>;
30
+ }, "strip", z.ZodTypeAny, {
31
+ kind: "search" | "home" | "collections" | "product" | "collection" | "catalog" | "categories" | "category" | "content";
32
+ locale: "en" | "ar";
33
+ slug: string;
34
+ page: number;
35
+ q: string;
36
+ }, {
37
+ kind: "search" | "home" | "collections" | "product" | "collection" | "catalog" | "categories" | "category" | "content";
38
+ locale: "en" | "ar";
39
+ slug?: string | undefined;
40
+ page?: number | undefined;
41
+ q?: string | undefined;
42
+ }>, Promise<RoutePageData>>;
43
+ export {};
44
+ //# sourceMappingURL=data.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"data.d.ts","sourceRoot":"","sources":["../../src/tanstack/data.ts"],"names":[],"mappings":"AAGA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAYxB,OAAO,EAGL,KAAK,aAAa,EAGnB,MAAM,qBAAqB,CAAC;AAuH7B,eAAO,MAAM,aAAa,6HAEzB,CAAC;AACF,QAAA,MAAM,WAAW;;;;;;;;;;;;;;;;;;EAgBf,CAAC;AACH,MAAM,MAAM,WAAW,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,WAAW,CAAC,CAAC;AACtD,eAAO,MAAM,aAAa;;;;;;;;;;;;;;;;;;2BAgNtB,CAAC"}
@@ -0,0 +1,320 @@
1
+ import { createServerFn } from "@tanstack/react-start";
2
+ import { getRequest } from "@tanstack/react-start/server";
3
+ import { notFound, redirect } from "@tanstack/react-router";
4
+ import { z } from "zod";
5
+ import { fixtureOptionVisuals, fixtureProducts, fixtureVariants, } from "../fixtures.js";
6
+ import { apiStoreUrl, resolveCommerceBinding } from "../commerce.js";
7
+ import { CommerceError, createCommerceClient, presentProduct, } from "@orunelle/theme-sdk/commerce";
8
+ import { referencedResources, visualsFromOptionLibrary, } from "@orunelle/theme-sdk";
9
+ import { requestEnvironment } from "./binding.server.js";
10
+ function resolve() {
11
+ const result = resolveCommerceBinding(getRequest(), requestEnvironment());
12
+ if (!result)
13
+ throw notFound();
14
+ return result;
15
+ }
16
+ /**
17
+ * Server-side data fetch, portable across Node and the isolate pool. Browser
18
+ * options (credentials, cache) are dropped, redirects are never followed, and
19
+ * the render capability is attached when present.
20
+ */
21
+ async function serverFetch(input, init, brokerToken) {
22
+ const { credentials: _credentials, cache: _cache, redirect: _redirect, ...rest } = init ?? {};
23
+ const headers = new Headers(rest.headers);
24
+ if (brokerToken)
25
+ headers.set("authorization", `Bearer ${brokerToken}`);
26
+ const response = await fetch(input, {
27
+ ...rest,
28
+ headers,
29
+ redirect: "manual",
30
+ signal: AbortSignal.any([
31
+ getRequest().signal,
32
+ AbortSignal.timeout(10000),
33
+ ...(rest.signal ? [rest.signal] : []),
34
+ ]),
35
+ });
36
+ if (response.status >= 300 && response.status < 400)
37
+ throw new Error("Unexpected redirect from the data service");
38
+ return response;
39
+ }
40
+ const noResources = { products: {}, collections: {} };
41
+ /**
42
+ * Loads the products and collections that the home page's theme settings
43
+ * reference. Failures leave sections empty instead of failing the page.
44
+ */
45
+ async function loadResources(client, storefront, configuration) {
46
+ const refs = referencedResources(configuration, "home");
47
+ const present = (product) => {
48
+ if (product.storeId !== storefront.store.id)
49
+ throw new Error("Store binding mismatch");
50
+ return presentProduct(product, storefront.locale);
51
+ };
52
+ const products = async () => {
53
+ if (!refs.products.length)
54
+ return {};
55
+ const page = await client.products({
56
+ ids: refs.products,
57
+ limit: refs.products.length,
58
+ });
59
+ return Object.fromEntries(page.items.map((p) => [p.id, present(p)]));
60
+ };
61
+ const collections = async () => {
62
+ const wanted = new Set(refs.collections);
63
+ const found = {};
64
+ // Collections are addressed by slug; resolve the picked IDs from the list.
65
+ for (let page = 1; wanted.size && page <= 3; page++) {
66
+ const result = await client.collections(page);
67
+ for (const item of result.items)
68
+ if (wanted.delete(item.id))
69
+ found[item.id] = {
70
+ id: item.id,
71
+ slug: item.slug,
72
+ name: item.name,
73
+ description: item.description,
74
+ };
75
+ if (page >= result.pagination.pages)
76
+ break;
77
+ }
78
+ await Promise.all(refs.collectionProducts.map(async (id) => {
79
+ const summary = found[id];
80
+ if (!summary)
81
+ return;
82
+ const detail = await client.collection(summary.slug);
83
+ found[id] = {
84
+ ...summary,
85
+ products: detail.data.collectionItems.map((item) => present(item.product)),
86
+ };
87
+ }));
88
+ return found;
89
+ };
90
+ const [picked, picks] = await Promise.allSettled([products(), collections()]);
91
+ return {
92
+ products: picked.status === "fulfilled" ? picked.value : {},
93
+ collections: picks.status === "fulfilled" ? picks.value : {},
94
+ };
95
+ }
96
+ function fixtureResources(products, configuration) {
97
+ const refs = referencedResources(configuration, "home");
98
+ return {
99
+ products: Object.fromEntries(products
100
+ .filter((product) => refs.products.includes(product.id))
101
+ .map((product) => [product.id, product])),
102
+ collections: {},
103
+ };
104
+ }
105
+ export const getStorefront = createServerFn({ method: "GET" }).handler(() => resolve().context);
106
+ const inputSchema = z.object({
107
+ kind: z.enum([
108
+ "home",
109
+ "catalog",
110
+ "categories",
111
+ "category",
112
+ "collections",
113
+ "collection",
114
+ "search",
115
+ "product",
116
+ "content",
117
+ ]),
118
+ locale: z.enum(["en", "ar"]),
119
+ slug: z.string().max(200).default(""),
120
+ page: z.number().int().min(1).max(10000).default(1),
121
+ q: z.string().max(200).default(""),
122
+ });
123
+ export const getPublicPage = createServerFn({ method: "GET" })
124
+ .validator(inputSchema)
125
+ .handler(async ({ data }) => {
126
+ const { binding, context } = resolve();
127
+ const storefront = { ...context, locale: data.locale };
128
+ const titles = {
129
+ home: ["Products", "المنتجات"],
130
+ catalog: ["All products", "جميع المنتجات"],
131
+ search: ["Search", "البحث"],
132
+ collections: ["Collections", "المجموعات"],
133
+ categories: ["Categories", "الفئات"],
134
+ category: ["Category", "الفئة"],
135
+ collection: ["Collection", "المجموعة"],
136
+ product: ["Product", "المنتج"],
137
+ content: ["Page", "صفحة"],
138
+ };
139
+ let title = titles[data.kind][data.locale === "ar" ? 1 : 0];
140
+ if (data.kind === "content") {
141
+ const content = binding?.pages.find((p) => p.slug === data.slug);
142
+ if (!content)
143
+ throw notFound();
144
+ return {
145
+ kind: "content",
146
+ title: content.title[data.locale],
147
+ paragraphs: content.paragraphs[data.locale],
148
+ };
149
+ }
150
+ if (!binding) {
151
+ const products = fixtureProducts(storefront);
152
+ if (data.kind === "product") {
153
+ const product = products.find((p) => p.handle === data.slug);
154
+ if (!product)
155
+ throw notFound();
156
+ return {
157
+ kind: "product",
158
+ title: product.name[data.locale],
159
+ product,
160
+ variants: fixtureVariants(product),
161
+ related: products.filter((p) => p.id !== product.id),
162
+ optionVisuals: fixtureOptionVisuals,
163
+ };
164
+ }
165
+ if (["category", "collection"].includes(data.kind))
166
+ throw notFound();
167
+ if (data.kind === "collections" || data.kind === "categories")
168
+ return {
169
+ kind: "collections",
170
+ title,
171
+ collections: [],
172
+ pagination: { page: 1, limit: 20, total: 0, pages: 0 },
173
+ };
174
+ const filtered = products.filter((p) => !data.q ||
175
+ p.name[data.locale].toLowerCase().includes(data.q.toLowerCase()));
176
+ return {
177
+ kind: "catalog",
178
+ title,
179
+ products: data.page === 1 ? filtered : [],
180
+ pagination: {
181
+ page: data.page,
182
+ limit: 20,
183
+ total: filtered.length,
184
+ pages: filtered.length ? 1 : 0,
185
+ },
186
+ ...(data.kind === "home"
187
+ ? {
188
+ resources: fixtureResources(products, storefront.configuration),
189
+ }
190
+ : {}),
191
+ };
192
+ }
193
+ const client = createCommerceClient({
194
+ baseUrl: apiStoreUrl(binding, ""),
195
+ context: storefront,
196
+ fetch: (input, init) => serverFetch(input, init, binding.brokerToken),
197
+ });
198
+ try {
199
+ if (data.kind === "product") {
200
+ const raw = await client.product(data.slug);
201
+ if (raw.storeId !== storefront.store.id)
202
+ throw new Error("Store binding mismatch");
203
+ const product = presentProduct(raw, data.locale);
204
+ const canonical = raw.redirectHandle || product.handle;
205
+ if (canonical !== data.slug)
206
+ throw redirect({
207
+ href: `/${data.locale}/products/${encodeURIComponent(canonical)}`,
208
+ statusCode: 301,
209
+ });
210
+ // Variants are required; related products and swatches are optional
211
+ // and never fail the page.
212
+ const [variants, related, settings] = await Promise.all([
213
+ client.variants(raw.id),
214
+ raw.categoryId
215
+ ? client
216
+ .products({ categoryId: raw.categoryId, limit: 9 })
217
+ .then((page) => page.items
218
+ .filter((p) => p.id !== raw.id && p.storeId === storefront.store.id)
219
+ .slice(0, 8)
220
+ .map((p) => presentProduct(p, data.locale)))
221
+ .catch(() => [])
222
+ : Promise.resolve([]),
223
+ client.settings().catch(() => ({})),
224
+ ]);
225
+ return {
226
+ kind: "product",
227
+ title: product.name[data.locale],
228
+ product,
229
+ variants,
230
+ related,
231
+ optionVisuals: visualsFromOptionLibrary(settings["catalog.optionTypes"]),
232
+ };
233
+ }
234
+ if (data.kind === "categories") {
235
+ const categories = await client.categories();
236
+ const collections = categories.flatMap((category) => {
237
+ const selected = category.translations.find((t) => t.locale.startsWith(data.locale)) ?? category.translations[0];
238
+ return selected?.slug
239
+ ? [
240
+ {
241
+ id: category.id,
242
+ slug: selected.slug,
243
+ name: selected.name,
244
+ description: selected.description ?? "",
245
+ collectionItems: [],
246
+ },
247
+ ]
248
+ : [];
249
+ });
250
+ return {
251
+ kind: "collections",
252
+ basePath: "categories",
253
+ title,
254
+ collections,
255
+ pagination: {
256
+ page: 1,
257
+ limit: Math.max(1, collections.length),
258
+ total: collections.length,
259
+ pages: collections.length ? 1 : 0,
260
+ },
261
+ };
262
+ }
263
+ if (data.kind === "collections") {
264
+ const page = await client.collections(data.page);
265
+ return {
266
+ kind: "collections",
267
+ title,
268
+ collections: page.items,
269
+ pagination: page.pagination,
270
+ };
271
+ }
272
+ if (data.kind === "collection") {
273
+ const result = await client.collection(data.slug, data.page);
274
+ return {
275
+ kind: "catalog",
276
+ title: result.data.name,
277
+ products: result.data.collectionItems.map((p) => presentProduct(p.product, data.locale)),
278
+ pagination: result.pagination ?? {
279
+ page: data.page,
280
+ limit: 20,
281
+ total: 0,
282
+ pages: 0,
283
+ },
284
+ };
285
+ }
286
+ let categoryId;
287
+ if (data.kind === "category") {
288
+ const category = await client.category(data.slug);
289
+ categoryId = category.id;
290
+ title =
291
+ category.translations.find((t) => t.locale.startsWith(data.locale))
292
+ ?.name ?? title;
293
+ }
294
+ const [page, resources] = await Promise.all([
295
+ client.products({
296
+ page: data.page,
297
+ limit: 20,
298
+ ...(data.q ? { q: data.q } : {}),
299
+ ...(categoryId ? { categoryId } : {}),
300
+ }),
301
+ data.kind === "home"
302
+ ? loadResources(client, storefront, storefront.configuration)
303
+ : noResources,
304
+ ]);
305
+ if (page.items.some((p) => p.storeId !== storefront.store.id))
306
+ throw new Error("Store binding mismatch");
307
+ return {
308
+ kind: "catalog",
309
+ title,
310
+ products: page.items.map((p) => presentProduct(p, data.locale)),
311
+ pagination: page.pagination,
312
+ ...(data.kind === "home" ? { resources } : {}),
313
+ };
314
+ }
315
+ catch (error) {
316
+ if (error instanceof CommerceError && error.status === 404)
317
+ throw notFound();
318
+ throw error;
319
+ }
320
+ });
@@ -0,0 +1,4 @@
1
+ export { getStorefront, getPublicPage } from "./data.js";
2
+ export type { PublicInput } from "./data.js";
3
+ export { pageQuery } from "./queries.js";
4
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/tanstack/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,aAAa,EAAE,MAAM,WAAW,CAAC;AACzD,YAAY,EAAE,WAAW,EAAE,MAAM,WAAW,CAAC;AAC7C,OAAO,EAAE,SAAS,EAAE,MAAM,cAAc,CAAC"}
@@ -0,0 +1,2 @@
1
+ export { getStorefront, getPublicPage } from "./data.js";
2
+ export { pageQuery } from "./queries.js";
@@ -0,0 +1,6 @@
1
+ import type { StorefrontContext } from "@orunelle/theme-sdk";
2
+ import { type PublicInput } from "./data.js";
3
+ export declare function pageQuery(context: StorefrontContext, input: PublicInput): import("@tanstack/react-query").OmitKeyof<import("@tanstack/react-query").UseQueryOptions<import("@orunelle/theme-sdk").RoutePageData, Error, import("@orunelle/theme-sdk").RoutePageData, readonly ["storefront", string, string, "en" | "ar", string, string, string, number, "public" | "preview", string, unknown]>, "queryFn", "strictly"> & {
4
+ queryFn?: import("@tanstack/react-query").QueryFunction<import("@orunelle/theme-sdk").RoutePageData, readonly ["storefront", string, string, "en" | "ar", string, string, string, number, "public" | "preview", string, unknown], never>;
5
+ } & import("@tanstack/react-query").QueryKeyWithDataTag<readonly ["storefront", string, string, "en" | "ar", string, string, string, number, "public" | "preview", string, unknown], import("@orunelle/theme-sdk").RoutePageData, Error>;
6
+ //# sourceMappingURL=queries.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"queries.d.ts","sourceRoot":"","sources":["../../src/tanstack/queries.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAC7D,OAAO,EAAiB,KAAK,WAAW,EAAE,MAAM,WAAW,CAAC;AAE5D,wBAAgB,SAAS,CAAC,OAAO,EAAE,iBAAiB,EAAE,KAAK,EAAE,WAAW;;yOAIvE"}
@@ -0,0 +1,5 @@
1
+ import { publicQuery } from "@orunelle/theme-sdk/query";
2
+ import { getPublicPage } from "./data.js";
3
+ export function pageQuery(context, input) {
4
+ return publicQuery(context, "page", input, (signal) => getPublicPage({ data: input, signal }));
5
+ }
@@ -0,0 +1,3 @@
1
+ import { hydrateRoot } from "react-dom/client";
2
+ import { StartClient } from "@tanstack/react-start/client";
3
+ hydrateRoot(document, <StartClient />);
@@ -0,0 +1 @@
1
+ /// <reference types="vite/client"/>
@@ -0,0 +1,40 @@
1
+ import { createRouter } from "@tanstack/react-router";
2
+ import { routeTree } from "./routeTree.gen";
3
+ import { QueryClient } from "@tanstack/react-query";
4
+ import { setupRouterSsrQueryIntegration } from "@tanstack/react-router-ssr-query";
5
+
6
+ function createApplicationRouter() {
7
+ const queryClient = new QueryClient({
8
+ defaultOptions: { queries: { retry: false, staleTime: 30_000 } },
9
+ });
10
+ const router = createRouter({
11
+ routeTree,
12
+ context: { queryClient },
13
+ scrollRestoration: true,
14
+ defaultPreload: "intent",
15
+ defaultPreloadStaleTime: 0,
16
+ });
17
+ setupRouterSsrQueryIntegration({
18
+ router,
19
+ queryClient,
20
+ dehydrateOptions: {
21
+ shouldDehydrateQuery: (query) =>
22
+ query.meta?.visibility === "public" && query.state.status === "success",
23
+ },
24
+ });
25
+ return router;
26
+ }
27
+ // Never share a router/query cache between SSR requests. Keep the browser's
28
+ // instance across navigations so query state and commerce UI remain continuous.
29
+ let clientRouter: ReturnType<typeof createApplicationRouter> | undefined;
30
+ export function getRouter() {
31
+ if (typeof window !== "undefined")
32
+ return (clientRouter ??= createApplicationRouter());
33
+ return createApplicationRouter();
34
+ }
35
+
36
+ declare module "@tanstack/react-router" {
37
+ interface Register {
38
+ router: ReturnType<typeof getRouter>;
39
+ }
40
+ }