@orunelle/theme-sdk 0.0.0-stage → 2.0.0-alpha.14

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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"commerce.d.ts","sourceRoot":"","sources":["../src/commerce.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,KAAK,EACV,aAAa,EACb,iBAAiB,EAClB,MAAM,0BAA0B,CAAC;AA2ClC,eAAO,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAcxB,CAAC;AACH,MAAM,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,aAAa,CAAC,CAAC;AACpD,eAAO,MAAM,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAWxB,CAAC;AACH,MAAM,MAAM,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,aAAa,CAAC,CAAC;AACpD,eAAO,MAAM,cAAc;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAKzB,CAAC;AACH,MAAM,MAAM,QAAQ,GAAG,CAAC,CAAC,KAAK,CAAC,OAAO,cAAc,CAAC,CAAC;AACtD,eAAO,MAAM,gBAAgB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;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,QAAQ,MAAM,YAAY,MAAM;6BAMxC,MAAM,QAAQ,MAAM;;;;;;;;;;;;;;;;;;;;;;qBAS5B,YAAY;;;;;;;;;;;;;;;;;qBACZ,MAAM,SAAS,OAAO,CAAC,YAAY,CAAC;;;;;;;;;;;;;;;;;qBAEpC,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;gCAKK,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAEjB,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;sBAML,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBAUJ,QAAQ,GAAG,MAAM,eAAe,MAAM;;;;;sBAOtC,aAAa,cAAc,MAAM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;6BAW1B,aAAa,cAAc,MAAM,KAAG,QAAQ;8BAQrC,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAiB3C;AACD,MAAM,MAAM,cAAc,GAAG,UAAU,CAAC,OAAO,oBAAoB,CAAC,CAAC"}
@@ -0,0 +1,468 @@
1
+ import { z } from "zod";
2
+ const text = z.string();
3
+ const integer = z.number().int().safe();
4
+ const translation = z.object({
5
+ locale: text,
6
+ name: text,
7
+ slug: text.optional(),
8
+ description: text.optional(),
9
+ });
10
+ const media = z.object({
11
+ mediaType: text,
12
+ variantId: text.nullish(),
13
+ position: integer.optional(),
14
+ asset: z.object({
15
+ resolvedCdnUrl: text,
16
+ altText: text,
17
+ mimeType: text,
18
+ width: z.number().int().positive().nullish(),
19
+ height: z.number().int().positive().nullish(),
20
+ }),
21
+ });
22
+ /** Merchant-defined product fields; storefront reads contain public ones only. */
23
+ const productFieldSchema = z.object({
24
+ key: text,
25
+ kind: z.enum([
26
+ "text",
27
+ "multiline",
28
+ "number",
29
+ "boolean",
30
+ "url",
31
+ "color",
32
+ "date",
33
+ ]),
34
+ name: z.object({ en: text, ar: text }),
35
+ value: z.union([
36
+ z.string(),
37
+ z.number(),
38
+ z.boolean(),
39
+ z.null(),
40
+ z.object({ en: text, ar: text }),
41
+ ]),
42
+ });
43
+ export const productSchema = z.object({
44
+ id: text,
45
+ storeId: text,
46
+ handle: text,
47
+ redirectHandle: text.optional(),
48
+ name: text,
49
+ description: text,
50
+ currency: text,
51
+ priceMinor: integer,
52
+ compareAtPriceMinor: integer.nullable(),
53
+ categoryId: text.nullish(),
54
+ translations: z.array(translation),
55
+ media: z.array(media),
56
+ customFields: z.array(productFieldSchema).optional(),
57
+ });
58
+ export const variantSchema = z.object({
59
+ id: text,
60
+ productId: text,
61
+ sku: text,
62
+ size: text,
63
+ color: text,
64
+ options: z.record(text).nullable(),
65
+ colorHex: text.optional(),
66
+ priceOverrideMinor: integer.nullable(),
67
+ availableQuantity: integer,
68
+ isActive: z.boolean(),
69
+ });
70
+ export const categorySchema = z.object({
71
+ id: text,
72
+ translations: z.array(translation),
73
+ parentId: text.nullable(),
74
+ icon: text,
75
+ });
76
+ export const collectionSchema = z.object({
77
+ id: text,
78
+ slug: text,
79
+ name: text,
80
+ description: text,
81
+ collectionItems: z.array(z.object({ product: productSchema })),
82
+ });
83
+ export const customerSchema = z.object({
84
+ id: text,
85
+ storeId: text,
86
+ email: text,
87
+ firstName: text,
88
+ lastName: text,
89
+ phone: text,
90
+ locale: text,
91
+ marketingConsent: z.boolean(),
92
+ });
93
+ export const addressSchema = z.object({
94
+ id: text,
95
+ label: text,
96
+ recipientName: text,
97
+ phone: text,
98
+ country: text,
99
+ governorate: text,
100
+ city: text,
101
+ district: text,
102
+ street: text,
103
+ building: text,
104
+ floor: text,
105
+ apartment: text,
106
+ landmark: text,
107
+ postalCode: text,
108
+ isDefault: z.boolean(),
109
+ });
110
+ export const cartSchema = z.object({
111
+ id: text,
112
+ currency: text,
113
+ version: integer,
114
+ items: z.array(z.object({
115
+ id: text,
116
+ variantId: text,
117
+ productId: text,
118
+ sku: text,
119
+ name: text,
120
+ quantity: integer,
121
+ unitPriceMinor: integer,
122
+ availableQuantity: integer,
123
+ unavailable: z.boolean(),
124
+ productHandle: text,
125
+ })),
126
+ });
127
+ const totalsSchema = z.object({
128
+ taxInclusive: z.boolean(),
129
+ subtotalMinor: integer,
130
+ shippingMinor: integer,
131
+ taxMinor: integer,
132
+ discountMinor: integer,
133
+ totalMinor: integer,
134
+ amountDueMinor: integer,
135
+ currency: text,
136
+ });
137
+ const shippingSchema = z.object({ id: text, name: text, amountMinor: integer });
138
+ export const summarySchema = z.object({
139
+ cart: cartSchema,
140
+ totals: totalsSchema,
141
+ shippingOptions: z.array(shippingSchema),
142
+ selectedShipping: shippingSchema.nullable(),
143
+ });
144
+ export const orderSchema = z.object({
145
+ id: text,
146
+ orderNumber: text,
147
+ status: text,
148
+ paymentStatus: text,
149
+ paymentMethod: text,
150
+ totals: totalsSchema,
151
+ delivery: shippingSchema,
152
+ items: z.array(z.object({ id: text, name: text, quantity: integer, totalMinor: integer })),
153
+ });
154
+ const wishlistItemSchema = z.object({
155
+ id: text,
156
+ available: z.boolean(),
157
+ productVariant: z.object({ id: text, product: productSchema }).nullable(),
158
+ });
159
+ export const wishlistSchema = z.object({
160
+ uncategorized: z.array(wishlistItemSchema),
161
+ collections: z.array(z.object({ id: text, name: text, items: z.array(wishlistItemSchema) })),
162
+ });
163
+ export class CommerceError extends Error {
164
+ code;
165
+ status;
166
+ requestId;
167
+ recovery;
168
+ constructor(code, status, requestId, recovery) {
169
+ super(code);
170
+ this.code = code;
171
+ this.status = status;
172
+ this.requestId = requestId;
173
+ this.recovery = recovery;
174
+ this.name = "CommerceError";
175
+ }
176
+ }
177
+ const envelopeSchema = z.object({
178
+ success: z.boolean(),
179
+ data: z.unknown(),
180
+ error: z.object({ code: text }).nullable(),
181
+ meta: z.object({
182
+ requestId: text,
183
+ pagination: z
184
+ .object({ page: integer, limit: integer, total: integer, pages: integer })
185
+ .optional(),
186
+ }),
187
+ });
188
+ const segment = (value) => {
189
+ if (!value ||
190
+ /[\u0000-\u001f/\\?#]/u.test(value) ||
191
+ value === "." ||
192
+ value === "..")
193
+ throw new CommerceError("INVALID_IDENTIFIER", 422, "");
194
+ return encodeURIComponent(value);
195
+ };
196
+ export const apiLocale = (locale) => locale === "ar" ? "ar-EG" : "en-US";
197
+ export function presentProduct(value, locale) {
198
+ const localized = (key, lang) => value.translations.find((t) => t.locale === apiLocale(lang))?.[key] ||
199
+ value[key];
200
+ const selected = value.translations.find((t) => t.locale === apiLocale(locale));
201
+ const images = value.media
202
+ .filter((m) => m.mediaType !== "video" && m.asset.mimeType.startsWith("image/"))
203
+ .sort((a, b) => (a.position ?? 0) - (b.position ?? 0))
204
+ .map((m) => ({
205
+ url: m.asset.resolvedCdnUrl,
206
+ alt: m.asset.altText,
207
+ ...(m.asset.width && m.asset.height
208
+ ? { width: m.asset.width, height: m.asset.height }
209
+ : {}),
210
+ ...(m.variantId ? { variantId: m.variantId } : {}),
211
+ }));
212
+ // The main image comes first even when its position says otherwise.
213
+ const main = value.media.findIndex((m) => m.mediaType === "main_image");
214
+ if (main > 0) {
215
+ const url = value.media[main].asset.resolvedCdnUrl;
216
+ const index = images.findIndex((image) => image.url === url);
217
+ if (index > 0)
218
+ images.unshift(...images.splice(index, 1));
219
+ }
220
+ const image = images[0];
221
+ return {
222
+ id: value.id,
223
+ handle: selected?.slug || value.handle,
224
+ name: { en: localized("name", "en"), ar: localized("name", "ar") },
225
+ description: {
226
+ en: localized("description", "en"),
227
+ ar: localized("description", "ar"),
228
+ },
229
+ price: { amountMinor: value.priceMinor, currency: value.currency },
230
+ ...(value.customFields?.length
231
+ ? {
232
+ fields: value.customFields.map((field) => ({
233
+ key: field.key,
234
+ kind: field.kind,
235
+ name: field.name,
236
+ value: field.value,
237
+ })),
238
+ }
239
+ : {}),
240
+ ...(image ? { image, images } : {}),
241
+ ...(value.compareAtPriceMinor &&
242
+ value.compareAtPriceMinor > value.priceMinor
243
+ ? {
244
+ compareAtPrice: {
245
+ amountMinor: value.compareAtPriceMinor,
246
+ currency: value.currency,
247
+ },
248
+ }
249
+ : {}),
250
+ ...(value.categoryId ? { categoryId: value.categoryId } : {}),
251
+ };
252
+ }
253
+ export function createCommerceClient(options) {
254
+ const fetcher = options.fetch ?? globalThis.fetch;
255
+ const base = options.baseUrl.replace(/\/$/, "");
256
+ const scope = JSON.stringify([
257
+ options.context.store.id,
258
+ options.context.origin,
259
+ ]);
260
+ async function request(path, schema, method = "GET", body, requestKey, settings = {}) {
261
+ const serialized = body === undefined ? undefined : JSON.stringify(body);
262
+ const recovery = method === "GET"
263
+ ? undefined
264
+ : Object.freeze({
265
+ scope,
266
+ path,
267
+ method,
268
+ // Only checkout supports receipt replay. Never attach passwords or
269
+ // address/profile payloads to errors that callers may log.
270
+ body: path === "/orders/checkout" ? (serialized ?? "") : "",
271
+ ...(requestKey ? { requestKey } : {}),
272
+ });
273
+ const headersFor = (token) => {
274
+ const headers = new Headers({
275
+ accept: "application/json",
276
+ "accept-language": apiLocale(options.context.locale),
277
+ });
278
+ if (serialized !== undefined)
279
+ headers.set("content-type", "application/json");
280
+ if (token)
281
+ headers.set("authorization", `Bearer ${token}`);
282
+ const guest = options.guestToken?.();
283
+ if (guest)
284
+ headers.set("x-session-token", guest);
285
+ if (requestKey)
286
+ headers.set("idempotency-key", requestKey);
287
+ return headers;
288
+ };
289
+ const token = options.accessToken?.();
290
+ let response = await send(headersFor(token));
291
+ // An expired access token is rejected before the request is processed, so
292
+ // renewing it and sending the same request again (same idempotency key)
293
+ // is safe for writes too.
294
+ if (response?.status === 401 &&
295
+ token &&
296
+ options.onUnauthorized &&
297
+ !path.startsWith("/auth/") &&
298
+ (await options.onUnauthorized(token).catch(() => false)))
299
+ response = await send(headersFor(options.accessToken?.()));
300
+ return parse(response);
301
+ async function send(headers) {
302
+ let response;
303
+ for (let attempt = 0; attempt <= (method === "GET" ? (options.readRetries ?? 1) : 0); attempt++) {
304
+ try {
305
+ response = await fetcher(base + path, {
306
+ method,
307
+ headers,
308
+ credentials: "same-origin",
309
+ redirect: "error",
310
+ cache: "no-store",
311
+ signal: settings.signal ?? null,
312
+ ...(serialized === undefined ? {} : { body: serialized }),
313
+ });
314
+ }
315
+ catch {
316
+ if (settings.signal?.aborted)
317
+ throw new CommerceError("CANCELLED", 0, "", recovery);
318
+ if (method === "GET" && attempt < (options.readRetries ?? 1))
319
+ continue;
320
+ throw new CommerceError(method === "GET" ? "NETWORK_ERROR" : "UNCERTAIN_WRITE", 0, "", recovery);
321
+ }
322
+ if (method !== "GET" ||
323
+ ![502, 503, 504].includes(response.status) ||
324
+ attempt === (options.readRetries ?? 1))
325
+ break;
326
+ }
327
+ return response;
328
+ }
329
+ async function parse(response) {
330
+ if (!response)
331
+ throw new CommerceError("NETWORK_ERROR", 0, "");
332
+ const id = response.headers.get("x-request-id") ?? "";
333
+ let raw;
334
+ try {
335
+ raw = await response.json();
336
+ }
337
+ catch {
338
+ throw new CommerceError(method === "GET" ? "INVALID_RESPONSE" : "UNCERTAIN_WRITE", response.status, id, recovery);
339
+ }
340
+ const parsed = envelopeSchema.safeParse(raw);
341
+ if (!parsed.success)
342
+ throw new CommerceError(method === "GET" ? "INVALID_RESPONSE" : "UNCERTAIN_WRITE", response.status, id, recovery);
343
+ const envelope = parsed.data;
344
+ if (!response.ok || !envelope.success)
345
+ throw new CommerceError(envelope.error?.code ?? "HTTP_ERROR", response.status, envelope.meta.requestId || id, response.status >= 500 ? recovery : undefined);
346
+ const data = schema.safeParse(envelope.data);
347
+ if (!data.success)
348
+ throw new CommerceError(method === "GET" ? "INVALID_RESPONSE" : "UNCERTAIN_WRITE", response.status, envelope.meta.requestId || id, recovery);
349
+ return {
350
+ data: data.data,
351
+ ...(envelope.meta.pagination
352
+ ? { pagination: envelope.meta.pagination }
353
+ : {}),
354
+ };
355
+ }
356
+ }
357
+ const read = async (path, schema, settings) => (await request(path, schema, "GET", undefined, undefined, settings)).data;
358
+ const write = async (path, schema, body, method = "POST", key) => (await request(path, schema, method, body, key)).data;
359
+ const query = (values) => {
360
+ const all = {
361
+ locale: apiLocale(options.context.locale),
362
+ ...values,
363
+ };
364
+ return ("?" +
365
+ new URLSearchParams(Object.entries(all)
366
+ .filter((entry) => entry[1] !== undefined)
367
+ .map(([key, value]) => [key, String(value)])));
368
+ };
369
+ async function page(path, schema, settings) {
370
+ const result = await request(path, z.array(schema), "GET", undefined, undefined, settings);
371
+ if (!result.pagination)
372
+ throw new CommerceError("INVALID_PAGINATION", 502, "");
373
+ return { items: result.data, pagination: result.pagination };
374
+ }
375
+ const auth = z.object({
376
+ accessToken: text.optional(),
377
+ user: customerSchema.optional(),
378
+ requiresVerification: z.boolean().optional(),
379
+ });
380
+ return {
381
+ context: options.context,
382
+ products: (values = {}, settings) => page("/products" +
383
+ query({
384
+ ...values,
385
+ ids: values.ids?.length ? values.ids.join(",") : undefined,
386
+ }), productSchema, settings),
387
+ product: (handle, settings) => read("/products/" + segment(handle) + query({}), productSchema, settings),
388
+ variants: (id, settings) => read("/products/" + segment(id) + "/variants", z.array(variantSchema), settings),
389
+ categories: (settings) => read("/categories", z.array(categorySchema), settings),
390
+ category: (slug, settings) => read("/categories/" + segment(slug), categorySchema, settings),
391
+ collections: (pageNumber = 1, settings) => page("/collections" + query({ page: pageNumber, limit: 20 }), collectionSchema, settings),
392
+ collection: async (slug, pageNumber = 1, settings) => request("/collections/" +
393
+ segment(slug) +
394
+ query({ page: pageNumber, limit: 20 }), collectionSchema, "GET", undefined, undefined, settings),
395
+ settings: (settings) => read("/settings", z.record(z.unknown()), settings),
396
+ cart: {
397
+ read: () => read("/cart", cartSchema),
398
+ add: (variantId, quantity) => write("/cart/items", cartSchema, { variantId, quantity }),
399
+ update: (id, quantity) => write("/cart/items/" + segment(id), cartSchema, { quantity }, "PATCH"),
400
+ remove: (id) => write("/cart/items/" + segment(id), cartSchema, undefined, "DELETE"),
401
+ mergeGuest: () => write("/cart/merge", cartSchema, {
402
+ ...(options.guestToken?.()
403
+ ? { sessionToken: options.guestToken() }
404
+ : {}),
405
+ }),
406
+ summary: (values) => write("/cart/summary", summarySchema, values),
407
+ },
408
+ customer: {
409
+ login: (email, password) => write("/auth/login", auth, { email, password }),
410
+ register: (input) => write("/auth/register", auth, input),
411
+ refresh: () => write("/auth/refresh", auth, {}),
412
+ logout: () => write("/auth/logout", z.object({ loggedOut: z.boolean() }), {}),
413
+ me: () => read("/auth/me", customerSchema),
414
+ update: (input) => write("/auth/me", customerSchema, input, "PATCH"),
415
+ resetWithToken: (token, newPassword) => write("/auth/reset-password", z.unknown(), { token, newPassword }),
416
+ requestReset: (email) => write("/auth/forgot-password", z.unknown(), { email }),
417
+ resetPassword: (email, code, password) => write("/auth/reset-password", z.unknown(), {
418
+ identifier: email,
419
+ code,
420
+ newPassword: password,
421
+ }),
422
+ verifyEmail: (email, code) => write("/auth/verify-otp", z.object({ verified: z.boolean() }), {
423
+ identifier: email,
424
+ code,
425
+ type: "email_verify",
426
+ }),
427
+ },
428
+ addresses: {
429
+ list: () => read("/addresses", z.array(addressSchema)),
430
+ add: (input) => write("/addresses", addressSchema, input),
431
+ update: (id, input) => write("/addresses/" + segment(id), addressSchema, input, "PATCH"),
432
+ remove: (id) => write("/addresses/" + segment(id), z.unknown(), undefined, "DELETE"),
433
+ },
434
+ wishlist: {
435
+ read: () => read("/wishlist", wishlistSchema),
436
+ add: (productVariantId) => write("/wishlist", wishlistItemSchema, { productVariantId }),
437
+ remove: (id) => write("/wishlist/" + segment(id), z.unknown(), undefined, "DELETE"),
438
+ },
439
+ orders: {
440
+ list: (pageNumber = 1) => page("/orders" + query({ page: pageNumber, limit: 20 }), orderSchema),
441
+ get: (number) => read("/orders/" + segment(number), orderSchema),
442
+ },
443
+ payments: {
444
+ methods: () => read("/payments/methods", z.array(z.object({ method: z.enum(["cod", "paymob", "xpay"]), name: text }))),
445
+ start: (method, orderNumber) => write(`/payments/${method}/intent`, z.object({ status: text, paymentUrl: text.optional() }), { orderNumber, locale: options.context.locale }),
446
+ },
447
+ checkout: (input, requestKey) => {
448
+ if (!/^[0-9a-f-]{36}$/i.test(requestKey))
449
+ throw new CommerceError("INVALID_REQUEST_KEY", 422, "");
450
+ return write("/orders/checkout", z.object({ order: orderSchema, idempotent: z.boolean() }), input, "POST", requestKey);
451
+ },
452
+ prepareCheckout: (input, requestKey) => Object.freeze({
453
+ scope,
454
+ path: "/orders/checkout",
455
+ method: "POST",
456
+ body: JSON.stringify(input),
457
+ requestKey,
458
+ }),
459
+ async recoverCheckout(recovery) {
460
+ if (recovery.scope !== scope ||
461
+ recovery.path !== "/orders/checkout" ||
462
+ recovery.method !== "POST" ||
463
+ !recovery.requestKey)
464
+ throw new CommerceError("INVALID_RECOVERY", 422, "");
465
+ return write(recovery.path, z.object({ order: orderSchema, idempotent: z.boolean() }), JSON.parse(recovery.body), recovery.method, recovery.requestKey);
466
+ },
467
+ };
468
+ }
@@ -0,0 +1,36 @@
1
+ import { type ReactNode } from "react";
2
+ import { type SettingDefinitions, type SettingValues, type SettingValue } from "@orunelle/theme-contract";
3
+ import { type ThemeSlotName } from "./index.js";
4
+ export declare function EditableField({ name, children, }: {
5
+ name: string;
6
+ children: ReactNode;
7
+ }): import("react").JSX.Element;
8
+ export declare function ThemeSlot({ name }: {
9
+ name: ThemeSlotName;
10
+ }): import("react").JSX.Element | null;
11
+ export declare function resolvePublicSettings(values: SettingValues, sources: Partial<Record<"store.name" | "store.logo" | "product.name" | "product.description" | "product.image" | "collection.name", SettingValue>>): SettingValues;
12
+ /** Composition identity comes from validated configuration, never DOM position. */
13
+ export declare function ThemeComposition({ scope, name, fallback, productId, }: {
14
+ scope: "template" | "group";
15
+ name: string;
16
+ fallback?: ReactNode;
17
+ productId?: string;
18
+ }): import("react").JSX.Element;
19
+ /**
20
+ * Turns global theme settings into CSS custom properties, so merchant choices
21
+ * reach every theme without per-theme wiring. Only values with a closed,
22
+ * CSS-safe shape are emitted (validated colors, finite numbers, option tokens).
23
+ *
24
+ * - color → `--setting-<id>: #rrggbb`
25
+ * - number → `--setting-<id>: <n>`; responsive adds `-sm` and `-lg`
26
+ * - boolean → `1` or `0`
27
+ * - select → the option value; font → `var(--font-<value>)`
28
+ */
29
+ export declare function themeSettingVariables(definitions: SettingDefinitions, values: SettingValues): Record<string, string>;
30
+ /** Global theme settings with merchant values over author defaults. */
31
+ export declare function useThemeSettings(): SettingValues;
32
+ /** Prefixes store-relative links with the locale; other links pass through. */
33
+ export declare function localizedHref(href: string, locale: "en" | "ar"): string;
34
+ /** Rendered by StorefrontProvider; updates live while a draft is edited. */
35
+ export declare function ThemeSettingsStyle(): import("react").JSX.Element | null;
36
+ //# sourceMappingURL=composition.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"composition.d.ts","sourceRoot":"","sources":["../src/composition.tsx"],"names":[],"mappings":"AAAA,OAAO,EAAY,KAAK,SAAS,EAAE,MAAM,OAAO,CAAC;AACjD,OAAO,EAEL,KAAK,kBAAkB,EACvB,KAAK,aAAa,EAElB,KAAK,YAAY,EAClB,MAAM,0BAA0B,CAAC;AAClC,OAAO,EAAmB,KAAK,aAAa,EAAE,MAAM,YAAY,CAAC;AAEjE,wBAAgB,aAAa,CAAC,EAC5B,IAAI,EACJ,QAAQ,GACT,EAAE;IACD,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,EAAE,SAAS,CAAC;CACrB,+BAEA;AACD,wBAAgB,SAAS,CAAC,EAAE,IAAI,EAAE,EAAE;IAAE,IAAI,EAAE,aAAa,CAAA;CAAE,sCAG1D;AACD,wBAAgB,qBAAqB,CACnC,MAAM,EAAE,aAAa,EACrB,OAAO,EAAE,OAAO,CACd,MAAM,CACF,YAAY,GACZ,YAAY,GACZ,cAAc,GACd,qBAAqB,GACrB,eAAe,GACf,iBAAiB,EACnB,YAAY,CACb,CACF,GACA,aAAa,CASf;AACD,mFAAmF;AACnF,wBAAgB,gBAAgB,CAAC,EAC/B,KAAK,EACL,IAAI,EACJ,QAAe,EACf,SAAS,GACV,EAAE;IACD,KAAK,EAAE,UAAU,GAAG,OAAO,CAAC;IAC5B,IAAI,EAAE,MAAM,CAAC;IACb,QAAQ,CAAC,EAAE,SAAS,CAAC;IACrB,SAAS,CAAC,EAAE,MAAM,CAAC;CACpB,+BAuDA;AAOD;;;;;;;;;GASG;AACH,wBAAgB,qBAAqB,CACnC,WAAW,EAAE,kBAAkB,EAC/B,MAAM,EAAE,aAAa,GACpB,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAuCxB;AAED,uEAAuE;AACvE,wBAAgB,gBAAgB,IAAI,aAAa,CAQhD;AAED,+EAA+E;AAC/E,wBAAgB,aAAa,CAAC,IAAI,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,GAAG,IAAI,GAAG,MAAM,CAIvE;AAED,4EAA4E;AAC5E,wBAAgB,kBAAkB,uCAcjC"}
@@ -0,0 +1,137 @@
1
+ import { jsx as _jsx, Fragment as _Fragment } from "react/jsx-runtime";
2
+ import { Fragment } from "react";
3
+ import { resolveSettingValues, } from "@orunelle/theme-contract";
4
+ import { useThemeRuntime } from "./index.js";
5
+ export function EditableField({ name, children, }) {
6
+ return _jsx("span", { "data-orunelle-field": name, children: children });
7
+ }
8
+ export function ThemeSlot({ name }) {
9
+ const Component = useThemeRuntime().theme.slots[name];
10
+ return Component ? _jsx(Component, {}) : null;
11
+ }
12
+ export function resolvePublicSettings(values, sources) {
13
+ return Object.fromEntries(Object.entries(values).map(([key, value]) => [
14
+ key,
15
+ value && typeof value === "object" && "binding" in value
16
+ ? structuredClone(sources[value.binding] ?? value.fallback)
17
+ : value,
18
+ ]));
19
+ }
20
+ /** Composition identity comes from validated configuration, never DOM position. */
21
+ export function ThemeComposition({ scope, name, fallback = null, productId, }) {
22
+ const { configuration, theme, storefront, products } = useThemeRuntime();
23
+ if (!configuration || !theme.manifest.editor)
24
+ return _jsx(_Fragment, { children: fallback });
25
+ const kind = scope === "template" ? "templates" : "groups";
26
+ const source = Object.hasOwn(configuration[kind], name)
27
+ ? configuration
28
+ : theme.defaults;
29
+ const composition = source?.[kind][name];
30
+ if (!source || !composition)
31
+ return _jsx(_Fragment, { children: fallback });
32
+ const nodes = new Map(source.nodes.map((node) => [node.id, node]));
33
+ const product = products.find((product) => product.id === productId);
34
+ function render(id) {
35
+ const node = nodes.get(id);
36
+ if (!node || node.hidden)
37
+ return null;
38
+ const definition = theme.manifest.editor.nodeTypes[node.type];
39
+ if (!definition)
40
+ return null;
41
+ const Component = (definition.kind === "section" ? theme.sections : theme.blocks)[node.type];
42
+ const settings = resolvePublicSettings(resolveSettingValues(definition.settings, node.settings), {
43
+ "store.name": storefront.store.name,
44
+ ...(storefront.store.logo ? { "store.logo": storefront.store.logo } : {}),
45
+ ...(product
46
+ ? {
47
+ "product.name": product.name,
48
+ "product.description": product.description,
49
+ }
50
+ : {}),
51
+ });
52
+ return (_jsx("div", { "data-orunelle-node-id": id, "data-orunelle-node-type": node.type, "data-orunelle-node-label": definition.label[storefront.locale], "data-orunelle-inherited": source !== configuration ? "true" : undefined, children: Component ? (_jsx(Component, { id: id, settings: settings, children: node.children.map(render) })) : (_jsx("p", { role: "status", children: storefront.locale === "ar"
53
+ ? "هذا المكوّن غير متاح؛ الإعدادات محفوظة."
54
+ : "This component is unavailable; its settings are retained." })) }, id));
55
+ }
56
+ return _jsx(Fragment, { children: composition.roots.map(render) });
57
+ }
58
+ const cssName = (id) => `--setting-${id.replace(/[^a-z0-9-]/g, "-")}`;
59
+ const cssToken = /^[a-z0-9][a-z0-9-]*$/i;
60
+ const finite = (value) => typeof value === "number" && Number.isFinite(value);
61
+ /**
62
+ * Turns global theme settings into CSS custom properties, so merchant choices
63
+ * reach every theme without per-theme wiring. Only values with a closed,
64
+ * CSS-safe shape are emitted (validated colors, finite numbers, option tokens).
65
+ *
66
+ * - color → `--setting-<id>: #rrggbb`
67
+ * - number → `--setting-<id>: <n>`; responsive adds `-sm` and `-lg`
68
+ * - boolean → `1` or `0`
69
+ * - select → the option value; font → `var(--font-<value>)`
70
+ */
71
+ export function themeSettingVariables(definitions, values) {
72
+ const out = {};
73
+ for (const [id, definition] of Object.entries(definitions)) {
74
+ const value = values[id];
75
+ const name = cssName(id);
76
+ switch (definition.kind) {
77
+ case "color":
78
+ if (typeof value === "string" && /^#[0-9a-f]{6}$/i.test(value))
79
+ out[name] = value;
80
+ break;
81
+ case "number":
82
+ if (finite(value))
83
+ out[name] = String(value);
84
+ break;
85
+ case "boolean":
86
+ if (typeof value === "boolean")
87
+ out[name] = value ? "1" : "0";
88
+ break;
89
+ case "responsive":
90
+ if (value && typeof value === "object" && "base" in value) {
91
+ const { base, sm, lg } = value;
92
+ if (finite(base))
93
+ out[name] = String(base);
94
+ if (finite(sm))
95
+ out[`${name}-sm`] = String(sm);
96
+ if (finite(lg))
97
+ out[`${name}-lg`] = String(lg);
98
+ }
99
+ break;
100
+ case "select":
101
+ if (typeof value === "string" && cssToken.test(value))
102
+ out[name] = value;
103
+ break;
104
+ case "font":
105
+ if (typeof value === "string" && cssToken.test(value))
106
+ out[name] = `var(--font-${value})`;
107
+ break;
108
+ }
109
+ }
110
+ return out;
111
+ }
112
+ /** Global theme settings with merchant values over author defaults. */
113
+ export function useThemeSettings() {
114
+ const { theme, configuration } = useThemeRuntime();
115
+ const editor = theme.manifest.editor;
116
+ if (!editor)
117
+ return {};
118
+ return resolveSettingValues(editor.settings, configuration?.settings ?? theme.defaults?.settings ?? {});
119
+ }
120
+ /** Prefixes store-relative links with the locale; other links pass through. */
121
+ export function localizedHref(href, locale) {
122
+ return /^\/(?!\/|en(?:\/|$)|ar(?:\/|$))/.test(href)
123
+ ? `/${locale}${href}`
124
+ : href;
125
+ }
126
+ /** Rendered by StorefrontProvider; updates live while a draft is edited. */
127
+ export function ThemeSettingsStyle() {
128
+ const { theme } = useThemeRuntime();
129
+ const values = useThemeSettings();
130
+ const editor = theme.manifest.editor;
131
+ if (!editor)
132
+ return null;
133
+ const entries = Object.entries(themeSettingVariables(editor.settings, values));
134
+ if (!entries.length)
135
+ return null;
136
+ return (_jsx("style", { "data-orunelle-settings": "", children: `:root{${entries.map(([name, value]) => `${name}:${value}`).join(";")}}` }));
137
+ }