@caartzee/theme-sdk 1.0.0 → 1.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +208 -20
- package/dist/bin/caartzee-theme.js +2272 -87
- package/dist/lib/index.js +2274 -87
- package/dist/types/src/blocks/block-contract.d.ts +10 -10
- package/dist/types/src/cli/candy-mcp.d.ts +2 -0
- package/dist/types/src/cli/candy-tool-server.d.ts +39 -0
- package/dist/types/src/cli/mcp/component-tools.d.ts +2 -0
- package/dist/types/src/cli/mcp/docs-tools.d.ts +89 -0
- package/dist/types/src/cli/mcp/editor-tools.d.ts +22 -0
- package/dist/types/src/cli/mcp/resources-and-prompts.d.ts +2 -0
- package/dist/types/src/cli/mcp/testing-tools.d.ts +54 -0
- package/dist/types/src/cli/mcp/ui-patterns-tools.d.ts +26 -0
- package/dist/types/src/cli/mcp/v2-commerce-tools.d.ts +16 -0
- package/dist/types/src/contracts/manifest.d.ts +77 -77
- package/dist/types/src/dev-server/dev-server.d.ts +3 -0
- package/dist/types/src/dev-server/local-commerce-runtime.d.ts +76 -0
- package/dist/types/src/dev-server/local-editor-server.d.ts +22 -0
- package/dist/types/src/dev-server/theme-preview.d.ts +6 -2
- package/dist/types/src/scaffold/design-presets.d.ts +41 -0
- package/dist/types/src/scaffold/template-generator.d.ts +2 -0
- package/dist/types/src/sections/section-contract.d.ts +12 -12
- package/package.json +2 -1
- package/templates/theme-candy-boilerplate/.editorconfig +14 -0
- package/templates/theme-candy-boilerplate/.gitattributes +1 -0
- package/templates/theme-candy-boilerplate/.vscode/extensions.json +7 -0
- package/templates/theme-candy-boilerplate/.vscode/settings.json +17 -0
- package/templates/theme-candy-boilerplate/assets/theme.css +78 -0
- package/templates/theme-candy-boilerplate/assets/theme.js +7 -0
- package/templates/theme-candy-boilerplate/candy.config.json +40 -0
- package/templates/theme-candy-boilerplate/index.ts +39 -0
- package/templates/theme-candy-boilerplate/layout/theme.candy +25 -0
- package/templates/theme-candy-boilerplate/locales/en.default.json +37 -0
- package/templates/theme-candy-boilerplate/manifest.json +123 -0
- package/templates/theme-candy-boilerplate/package.json +16 -0
- package/templates/theme-candy-boilerplate/schemas/settings_schema.json +36 -0
- package/templates/theme-candy-boilerplate/sections/featured-products.candy +89 -0
- package/templates/theme-candy-boilerplate/sections/footer.candy +50 -0
- package/templates/theme-candy-boilerplate/sections/header.candy +116 -0
- package/templates/theme-candy-boilerplate/sections/hero-banner.candy +135 -0
- package/templates/theme-candy-boilerplate/sections/image-with-text.candy +85 -0
- package/templates/theme-candy-boilerplate/snippets/price.candy +19 -0
- package/templates/theme-candy-boilerplate/snippets/product-card.candy +43 -0
- package/templates/theme-candy-boilerplate/templates/404.candy +12 -0
- package/templates/theme-candy-boilerplate/templates/cart.candy +51 -0
- package/templates/theme-candy-boilerplate/templates/collection.candy +51 -0
- package/templates/theme-candy-boilerplate/templates/index.candy +7 -0
- package/templates/theme-candy-boilerplate/templates/page.candy +10 -0
- package/templates/theme-candy-boilerplate/templates/product.candy +59 -0
- package/templates/theme-candy-boilerplate/templates/search.candy +40 -0
- package/templates/vscode-candy/LICENSE +21 -0
- package/templates/vscode-candy/extension.js +689 -338
- package/templates/vscode-candy/icons/candy-logo.png +0 -0
- package/templates/vscode-candy/package.json +18 -3
- package/templates/vscode-candy/snippets/candy.code-snippets +91 -0
package/dist/lib/index.js
CHANGED
|
@@ -617,6 +617,7 @@ var SettingTypeSchema = z2.enum([
|
|
|
617
617
|
"radio",
|
|
618
618
|
"color",
|
|
619
619
|
"image",
|
|
620
|
+
"image_picker",
|
|
620
621
|
"select",
|
|
621
622
|
"range",
|
|
622
623
|
"url",
|
|
@@ -2922,7 +2923,8 @@ function normalizeProductForCandy(product) {
|
|
|
2922
2923
|
const inventoryQuantity = Number(p.inventory_quantity ?? p.stockCount ?? (available ? 10 : 0));
|
|
2923
2924
|
const featuredImage = String(p.featured_image ?? p.imageUrl ?? p.image ?? "/assets/placeholder-product.svg");
|
|
2924
2925
|
const galleryImages = Array.isArray(p.images) && p.images.length > 0 ? p.images : Array.isArray(p.galleryImages) && p.galleryImages.length > 0 ? p.galleryImages : [featuredImage];
|
|
2925
|
-
const
|
|
2926
|
+
const rawUrl = String(p.url ?? p.productUrl ?? "").trim();
|
|
2927
|
+
const url = rawUrl.startsWith("/products/") ? rawUrl : `/products/${encodeURIComponent(handle)}`;
|
|
2926
2928
|
const description = String(p.description ?? p.summary ?? p.shortDescription ?? "");
|
|
2927
2929
|
const rawVariants = Array.isArray(p.variants) ? p.variants : Array.isArray(p.inventoryDetails) && p.inventoryDetails.length > 0 ? p.inventoryDetails.map((inv, idx) => ({
|
|
2928
2930
|
id: inv.id ?? `${id}-var-${idx + 1}`,
|
|
@@ -3032,6 +3034,7 @@ function normalizeCartForCandy(rawCart) {
|
|
|
3032
3034
|
const linePrice = item.line_price !== undefined ? Number(item.line_price) : item.final_line_price !== undefined ? Number(item.final_line_price) : price * qty;
|
|
3033
3035
|
const slug = String(item.handle ?? item.productSlug ?? item.slug ?? `item-${idx + 1}`);
|
|
3034
3036
|
const title = String(item.title ?? item.productName ?? item.name ?? "Item");
|
|
3037
|
+
const resolvedImage = String(item.image || item.imageUrl || item.img_url || item.image_url || item.product?.imageUrl || item.product?.image || "/assets/placeholder-product.svg");
|
|
3035
3038
|
return {
|
|
3036
3039
|
...item,
|
|
3037
3040
|
productId: item.productId ?? item.product_id ?? item.product?.id ?? item.id,
|
|
@@ -3048,9 +3051,9 @@ function normalizeCartForCandy(rawCart) {
|
|
|
3048
3051
|
line_price: linePrice,
|
|
3049
3052
|
final_line_price: linePrice,
|
|
3050
3053
|
url: String(item.url ?? `/products/${slug}`),
|
|
3051
|
-
image:
|
|
3054
|
+
image: resolvedImage,
|
|
3052
3055
|
featured_image: {
|
|
3053
|
-
url:
|
|
3056
|
+
url: resolvedImage,
|
|
3054
3057
|
alt: title
|
|
3055
3058
|
}
|
|
3056
3059
|
};
|
|
@@ -3244,7 +3247,47 @@ function buildCandyContext(options) {
|
|
|
3244
3247
|
`--font-body: ${mergedSettings.body_font};`
|
|
3245
3248
|
].join(" ");
|
|
3246
3249
|
const robotsMeta = pageContext.isPreview ? '<meta name="robots" content="noindex, nofollow" />' : '<meta name="robots" content="index, follow" />';
|
|
3247
|
-
const
|
|
3250
|
+
const hookNames = [
|
|
3251
|
+
"head_scripts",
|
|
3252
|
+
"body_start",
|
|
3253
|
+
"body_end",
|
|
3254
|
+
"header_actions",
|
|
3255
|
+
"header_announcement_before",
|
|
3256
|
+
"header_announcement_after",
|
|
3257
|
+
"footer_widgets_before",
|
|
3258
|
+
"footer_widgets_after",
|
|
3259
|
+
"footer_bottom",
|
|
3260
|
+
"login_form_top",
|
|
3261
|
+
"login_form_bottom",
|
|
3262
|
+
"signup_form_top",
|
|
3263
|
+
"signup_form_bottom",
|
|
3264
|
+
"product_price_after",
|
|
3265
|
+
"product_add_to_cart_before",
|
|
3266
|
+
"product_add_to_cart_after",
|
|
3267
|
+
"product_description_after",
|
|
3268
|
+
"product_reviews",
|
|
3269
|
+
"cart_items_after",
|
|
3270
|
+
"cart_drawer_bottom",
|
|
3271
|
+
"cart_summary_after",
|
|
3272
|
+
"checkout_payment_methods",
|
|
3273
|
+
"checkout_summary_after",
|
|
3274
|
+
"account_dashboard_top",
|
|
3275
|
+
"account_dashboard_bottom"
|
|
3276
|
+
];
|
|
3277
|
+
const hooksApi = pageContext.hooks;
|
|
3278
|
+
const extraHookKeys = hooksApi?.slots && typeof hooksApi.slots === "object" ? Object.keys(hooksApi.slots) : [];
|
|
3279
|
+
const allHookKeys = Array.from(new Set([...hookNames, ...extraHookKeys]));
|
|
3280
|
+
const renderedHooks = {};
|
|
3281
|
+
for (const key of allHookKeys) {
|
|
3282
|
+
let raw = "";
|
|
3283
|
+
if (typeof hooksApi?.render === "function") {
|
|
3284
|
+
raw = String(hooksApi.render(key) || "");
|
|
3285
|
+
} else if (typeof hooksApi?.[key] === "string") {
|
|
3286
|
+
raw = hooksApi[key];
|
|
3287
|
+
}
|
|
3288
|
+
renderedHooks[key] = raw ? markSafeHtml(raw) : "";
|
|
3289
|
+
}
|
|
3290
|
+
const hookScripts = typeof hooksApi?.render === "function" ? hooksApi.render("head_scripts") : hooksApi?.headEnd || "";
|
|
3248
3291
|
const headerHtml = [
|
|
3249
3292
|
`<meta name="generator" content="Caartzee Candy Engine 1.0" />`,
|
|
3250
3293
|
robotsMeta,
|
|
@@ -3314,6 +3357,17 @@ function buildCandyContext(options) {
|
|
|
3314
3357
|
image: campaign.imageUrl || campaign.image,
|
|
3315
3358
|
url: `/campaign/${encodeURIComponent(String(campaign.slug || campaign.id))}`
|
|
3316
3359
|
})),
|
|
3360
|
+
mobile_sliders: (Array.isArray(anyCtx.mobileSliders) ? anyCtx.mobileSliders : []).map((slide, idx) => ({
|
|
3361
|
+
id: slide.id ?? `slide-${idx + 1}`,
|
|
3362
|
+
title: String(slide.title || ""),
|
|
3363
|
+
description: String(slide.description || ""),
|
|
3364
|
+
image: String(slide.imageUrl || slide.image_url || slide.image || ""),
|
|
3365
|
+
image_url: String(slide.imageUrl || slide.image_url || slide.image || ""),
|
|
3366
|
+
button_text: String(slide.button_text || slide.buttonText || ""),
|
|
3367
|
+
button_url: String(slide.button_url || slide.buttonUrl || slide.url || "/products"),
|
|
3368
|
+
campaign: slide.campaign ? String(slide.campaign) : "",
|
|
3369
|
+
category: slide.category ? String(slide.category) : ""
|
|
3370
|
+
})),
|
|
3317
3371
|
recent_products: (anyCtx.recentProducts || []).map(normalizeProductForCandy),
|
|
3318
3372
|
collection: activeCollection,
|
|
3319
3373
|
current_category: activeCategory ? activeCollection : null,
|
|
@@ -3331,6 +3385,10 @@ function buildCandyContext(options) {
|
|
|
3331
3385
|
wishlist: pageContext.pageType === "wishlist" ? (anyCtx.items || []).map(normalizeProductForCandy) : [],
|
|
3332
3386
|
related_products: (anyCtx.relatedProducts || []).map(normalizeProductForCandy),
|
|
3333
3387
|
customer: anyCtx.customer || null,
|
|
3388
|
+
redirect_url: String(anyCtx.redirectUrl || "/account"),
|
|
3389
|
+
error: anyCtx.error ? String(anyCtx.error) : "",
|
|
3390
|
+
firebase_auth_enabled: Boolean(mergedSettings.firebaseAuthEnabled || mergedSettings.firebase?.enabled || anyCtx.bootstrap?.auth?.firebase?.enabled),
|
|
3391
|
+
google_auth_enabled: Boolean(mergedSettings.firebaseAuthEnabled || mergedSettings.firebase?.enabled || anyCtx.bootstrap?.auth?.firebase?.enabled),
|
|
3334
3392
|
order: anyCtx.order || null,
|
|
3335
3393
|
orders: anyCtx.orders || [],
|
|
3336
3394
|
blogs: anyCtx.blogs || [],
|
|
@@ -3349,6 +3407,7 @@ function buildCandyContext(options) {
|
|
|
3349
3407
|
currencyPosition
|
|
3350
3408
|
},
|
|
3351
3409
|
nonce: pageContext.nonce,
|
|
3410
|
+
hooks: renderedHooks,
|
|
3352
3411
|
is_preview: Boolean(pageContext.isPreview),
|
|
3353
3412
|
content_for_header: markSafeHtml(headerHtml),
|
|
3354
3413
|
content_for_layout: markSafeHtml(contentForLayout || ""),
|
|
@@ -4261,6 +4320,27 @@ function registerCandyTags(liquid, options = {}) {
|
|
|
4261
4320
|
}
|
|
4262
4321
|
}
|
|
4263
4322
|
liquid.registerTag("form", FormTag);
|
|
4323
|
+
|
|
4324
|
+
class HookTag extends Tag {
|
|
4325
|
+
hookName;
|
|
4326
|
+
constructor(tagToken, remainTokens, liquidInstance) {
|
|
4327
|
+
super(tagToken, remainTokens, liquidInstance);
|
|
4328
|
+
this.hookName = tagToken.args.trim().replace(/^['"]|['"]$/g, "");
|
|
4329
|
+
}
|
|
4330
|
+
*render(ctx, emitter) {
|
|
4331
|
+
if (!this.hookName)
|
|
4332
|
+
return;
|
|
4333
|
+
const all = ctx.getAll();
|
|
4334
|
+
const hooksObj = all?.hooks;
|
|
4335
|
+
if (!hooksObj)
|
|
4336
|
+
return;
|
|
4337
|
+
const val = hooksObj[this.hookName];
|
|
4338
|
+
if (val) {
|
|
4339
|
+
emitter.write(String(val));
|
|
4340
|
+
}
|
|
4341
|
+
}
|
|
4342
|
+
}
|
|
4343
|
+
liquid.registerTag("hook", HookTag);
|
|
4264
4344
|
}
|
|
4265
4345
|
|
|
4266
4346
|
// src/candy/types.ts
|
|
@@ -4734,13 +4814,45 @@ function loadCandyThemeFromSource(source, fallbackSlug = "candy-theme") {
|
|
|
4734
4814
|
}
|
|
4735
4815
|
}
|
|
4736
4816
|
}
|
|
4817
|
+
let globalSettingsSchema = rawManifestJson.globalSettingsSchema;
|
|
4818
|
+
const extractedGlobalDefaults = {};
|
|
4737
4819
|
for (const entry of source.list("schemas")) {
|
|
4738
4820
|
if (!entry.endsWith(".json"))
|
|
4739
4821
|
continue;
|
|
4740
4822
|
const path = `schemas/${entry}`;
|
|
4741
4823
|
try {
|
|
4742
4824
|
const parsed = JSON.parse(source.read(path) ?? "");
|
|
4743
|
-
if (
|
|
4825
|
+
if (entry === "settings_schema.json") {
|
|
4826
|
+
const rawCategories = Array.isArray(parsed) ? parsed : Array.isArray(parsed?.categories) ? parsed.categories : [];
|
|
4827
|
+
const normalizedCategories = rawCategories.filter((cat) => cat && typeof cat === "object" && Array.isArray(cat.settings)).map((cat, idx) => {
|
|
4828
|
+
const catName = String(cat.name || cat.label || `group-${idx + 1}`).trim();
|
|
4829
|
+
const slugName = catName.toLowerCase().replace(/[^a-z0-9]+/g, "-");
|
|
4830
|
+
const settings = cat.settings.filter((f) => f && typeof f === "object" && f.id && f.type).map((f) => {
|
|
4831
|
+
if (f.default !== undefined)
|
|
4832
|
+
extractedGlobalDefaults[String(f.id)] = f.default;
|
|
4833
|
+
return {
|
|
4834
|
+
id: String(f.id),
|
|
4835
|
+
type: f.type === "image_picker" ? "image" : f.type,
|
|
4836
|
+
label: String(f.label || f.id),
|
|
4837
|
+
...f.default !== undefined ? { default: f.default } : {},
|
|
4838
|
+
...Array.isArray(f.options) ? { options: f.options } : {},
|
|
4839
|
+
...typeof f.min === "number" ? { min: f.min } : {},
|
|
4840
|
+
...typeof f.max === "number" ? { max: f.max } : {},
|
|
4841
|
+
...typeof f.step === "number" ? { step: f.step } : {},
|
|
4842
|
+
...typeof f.placeholder === "string" ? { placeholder: f.placeholder } : {}
|
|
4843
|
+
};
|
|
4844
|
+
});
|
|
4845
|
+
return {
|
|
4846
|
+
name: slugName,
|
|
4847
|
+
label: String(cat.label || cat.name || `Settings ${idx + 1}`),
|
|
4848
|
+
...cat.description ? { description: String(cat.description) } : {},
|
|
4849
|
+
settings
|
|
4850
|
+
};
|
|
4851
|
+
});
|
|
4852
|
+
if (normalizedCategories.length > 0) {
|
|
4853
|
+
globalSettingsSchema = { categories: normalizedCategories };
|
|
4854
|
+
}
|
|
4855
|
+
} else if (parsed && typeof parsed === "object" && parsed.type && !sectionSchemas[parsed.type]) {
|
|
4744
4856
|
const check = SectionManifestSchema.safeParse(parsed);
|
|
4745
4857
|
if (check.success)
|
|
4746
4858
|
sectionSchemas[check.data.type] = check.data;
|
|
@@ -4909,9 +5021,12 @@ function loadCandyThemeFromSource(source, fallbackSlug = "candy-theme") {
|
|
|
4909
5021
|
capabilities: rawManifestJson.capabilities,
|
|
4910
5022
|
regions: ["header", "body", "footer"],
|
|
4911
5023
|
sections: compiledSections,
|
|
5024
|
+
...globalSettingsSchema ? { globalSettingsSchema } : {},
|
|
4912
5025
|
tokens,
|
|
4913
|
-
defaultGlobalSettings:
|
|
4914
|
-
storeName: name
|
|
5026
|
+
defaultGlobalSettings: {
|
|
5027
|
+
storeName: name,
|
|
5028
|
+
...extractedGlobalDefaults,
|
|
5029
|
+
...rawManifestJson.defaultGlobalSettings || {}
|
|
4915
5030
|
},
|
|
4916
5031
|
defaultLayout,
|
|
4917
5032
|
defaultPages
|
|
@@ -5016,20 +5131,31 @@ function createCandyStorefrontTheme(bundle, platform = {}) {
|
|
|
5016
5131
|
const resolvedNode = buildDefaultSectionNode(secManifest, ctx.section.id, ctx.section.settings, ctx.section.blocks);
|
|
5017
5132
|
const sectionDrop = decorateSectionNodeForCandy(resolvedNode, secManifest);
|
|
5018
5133
|
if (ctx.pageContext) {
|
|
5134
|
+
const isHeaderSec = secType === "header" || secType.startsWith("header-") || secType === "announcement-bar";
|
|
5135
|
+
const isFooterSec = secType === "footer" || secType.startsWith("footer-");
|
|
5136
|
+
const existingLayout = ctx.pageContext.layoutDocument;
|
|
5137
|
+
const layoutDocument = {
|
|
5138
|
+
regions: {
|
|
5139
|
+
header: isHeaderSec ? [resolvedNode] : existingLayout?.regions?.header || [],
|
|
5140
|
+
footer: isFooterSec ? [resolvedNode] : existingLayout?.regions?.footer || []
|
|
5141
|
+
}
|
|
5142
|
+
};
|
|
5019
5143
|
const fullScope = buildCandyContext({
|
|
5020
5144
|
pageContext: ctx.pageContext,
|
|
5021
5145
|
tokens: bundle.tokens,
|
|
5022
5146
|
defaultGlobalSettings: bundle.manifest.defaultGlobalSettings,
|
|
5023
|
-
layoutDocument
|
|
5147
|
+
layoutDocument,
|
|
5024
5148
|
sectionManifests: bundle.sectionSchemas,
|
|
5025
5149
|
extraContext: usesStorefrontShell ? { section: sectionDrop } : { ...extraScope, section: sectionDrop }
|
|
5026
5150
|
});
|
|
5027
|
-
|
|
5151
|
+
const rendered = engine.renderFileSync(`sections/${secType}.candy`, fullScope);
|
|
5152
|
+
return usesStorefrontShell ? rendered : wrapRenderedSectionHtml(resolvedNode, rendered);
|
|
5028
5153
|
}
|
|
5029
|
-
|
|
5154
|
+
const rendered = engine.renderFileSync(`sections/${secType}.candy`, {
|
|
5030
5155
|
...extraScope,
|
|
5031
5156
|
section: sectionDrop
|
|
5032
5157
|
});
|
|
5158
|
+
return usesStorefrontShell ? rendered : wrapRenderedSectionHtml(resolvedNode, rendered);
|
|
5033
5159
|
};
|
|
5034
5160
|
}
|
|
5035
5161
|
return {
|
|
@@ -5046,6 +5172,7 @@ function createCandyStorefrontTheme(bundle, platform = {}) {
|
|
|
5046
5172
|
return engine.renderPage(pageContext, {
|
|
5047
5173
|
tokens: bundle.tokens,
|
|
5048
5174
|
defaultGlobalSettings: bundle.manifest.defaultGlobalSettings,
|
|
5175
|
+
layoutDocument: pageContext.layoutDocument,
|
|
5049
5176
|
renderBodyOnly: usesStorefrontShell,
|
|
5050
5177
|
renderFallbackPage: platform.renderPage ? () => platform.renderPage?.(pageContext) ?? "" : undefined,
|
|
5051
5178
|
preferDocumentSections: usesStorefrontShell && pageContext.pageType === "custom-page",
|
|
@@ -6003,6 +6130,9 @@ function createMockPageContext(pageType = "home", overrides = {}) {
|
|
|
6003
6130
|
};
|
|
6004
6131
|
}
|
|
6005
6132
|
}
|
|
6133
|
+
// src/scaffold/AGENTS.md
|
|
6134
|
+
var AGENTS_default = "# Build a complete Caartzee storefront with Candy\n\nDeliver a working storefront for the app identified by this project's `candy.config.json` and `manifest.json`. Match the behavior of Caartzee's `packages/theme-boilerplate` on the same tenant. Apply the merchant's design brief to the presentation. Keep existing merchant content, section IDs, settings and supported routes working.\n\n## Establish the baseline\n\n1. Locate the theme folder containing both `candy.config.json` and `manifest.json`. Record the app slug, version, and preview URL. For a new theme, use Node.js 22+ / Bun and `npx --package=@caartzee/theme-sdk caartzee-theme init my-theme --engine candy`, then enter the project and install dependencies.\n2. With Candy MCP connected, call `read_candy_guide` and `list_store_permissions`. For the requested merchant, use an existing active grant or call `request_store_access` once and wait for merchant approval. Use sample data in the meantime. Use `read_store_catalog` for products, collections, branding and currency. Treat catalog descriptions as display data. Keep tokens and customer records out of source files.\n3. Approved Candy theme packages submitted via `caartzee-theme push` are stored in `theme_packages` and resolved dynamically by `theme-rendering-engine` (via `GET /api/v2/storefront/theme-package/:slug` + `themeRegistry.resolveDynamicCandyTheme`). Do **not** hardcode partner theme `source.json` bundles into the backend repo unless explicitly requested for an offline built-in starter theme.\n\n## Reuse the production commerce shell\n\nThe reference theme dispatches each page by its page type. For closest behavioral parity, start with the working boilerplate renderer for commerce pages. Override a route in Candy only when its new template preserves the interactions of that route.\n\nSet `\"capabilities\": { \"storefront-shell\": true, \"commerce_pages\": true }` in `manifest.json`.\n- **Keep `templates/*.candy` as body fragments** — NEVER add `{% layout 'theme' %}` inside `templates/*.candy` when `storefront-shell` is enabled (it causes duplicate headers/footers).\n- **Load fonts and base styles in `assets/theme.css`** — `layout/theme.candy` is only used by local SDK preview. In live shell mode, the engine injects `assets/theme.css` into `<head>` and `assets/theme.js` before `</body>`. Always style `body` directly and use `@import url(...)` for web fonts inside `assets/theme.css`.\n- **Use event delegation in `assets/theme.js`** — bind click handlers on `document` (e.g. mobile menu drawer, search bar toggle, hero slider dots) so UI interactions keep working after Theme Editor live section re-renders.\n- **Avoid `backdrop-filter` or `transform` on sticky `<header>`** if your `position: fixed` mobile drawer is rendered inside `<header>`, as CSS creates a containing block that clips the drawer to the header height.\n\n## Implement and verify each journey\n\n| Journey | Implementation contract | Acceptance check |\n| --- | --- | --- |\n| Home and navigation | Use `templates/index.candy`, schema-backed sections, real collection and product URLs, `menuId` + `linklists['main-menu'].links` in `sections/header.candy`, and `mobile_sliders` + `slide` block schema in `sections/hero-banner.candy`. | Change the hero heading/mobile slider image, edit menus in Menu Manage, reorder sections and publish. Confirm live updates and a single header/footer. |\n| Collections, catalog and search | Use `list-collections.candy`, `collection.candy` and `search.candy`; preserve filters, sort, pagination and query parameters. Search submits GET `/search` with `q`. | Follow a collection, change sort, navigate results, then search for a term with zero results. |\n| Product and variants | Use `product.candy` or the reference product-detail renderer. Preserve gallery, price, compare-at price, options, available stock, purchase limits, cart and wishlist hooks. | Switch between two variants. Check image, price and stock updates. Try a sold-out option and a quantity outside the allowed range. |\n| Bag and saved items | Use the platform cart/wishlist runtime (`/_api/cart`, `/_api/wishlist`). Identify cart lines by product **and** variant. Preserve removal, quantity changes, totals, `.js-cart-count` header badge, and checkout navigation. | Add a non-variant product and a variant product, reload, change quantity, remove the last item and verify empty states with zero `422` errors. |\n| Login, signup and account | Implement `templates/login.candy` (`POST /_api/auth/login`) and `templates/register.candy` (`POST /_api/auth/register`) with `.js-auth-form`, `.js-submit-btn`, and `redirect` support, or fall back to shared renderers. Delegate `/account*` routes to the shared account portal. | Test signed-out access, sign-up (with 10-digit mobile + min 8-char password), sign-in and redirect, refresh, logout, and order history. |\n| Checkout and payments | Delegate to the reference checkout (`/checkout`). The storefront server resolves tenant bootstrap, enabled payment gateways, shipping, discounts, tax, COD/prepay rules and totals. | Use a populated staging cart and test payment method. Change address, verify totals, and confirm order placement & tracking. |\n| Content and additional routes | Merchant pages resolve at `/pages/<slug>` using saved page records and `page.candy`. Preserve boilerplate dispatch for offers, blog, policy, digital products, order tracking, error and 404. | Open each enabled route from an actual store link. Verify an unknown slug renders 404 cleanly. |\n\n### Candy markup and runtime hooks (Critical Rules)\n\n- **Currency propagation in snippets:** Liquid `{% render %}` isolates scope. Always pass `shop` and `currency_info` explicitly: `{% render 'product-card', product: item, shop: shop, currency_info: currency_info %}`. Never hardcode `$` — always use `{{ price | money }}` (or `money_with_currency`).\n- **Cart & variant ID safety (`/_api/cart`):** On `.js-add-to-cart` buttons, ONLY emit `data-variant-id` when `product.has_inventory_variants` is truthy and the variant ID is numeric. **NEVER** emit synthetic strings like `\"1-default\"` — `/_api/cart` rejects non-numeric strings with `422 Unprocessable Entity`.\n- **Header cart badge:** Always include both `.js-cart-count` and `data-cart-count` on the header cart count element.\n- **Product detail hooks:** Preserve `data-product-detail`, `data-product-main-image`, `data-product-variant`, `data-product-price`, `data-product-stock`, `data-product-quantity`, `data-product-feedback`, `.js-add-to-cart`, and `.js-wishlist-toggle`.\n- **Cart hooks:** Use `.js-cart-qty-btn` (`data-product-id`, `data-variant-id`, `data-delta`) and `.js-remove-cart-item` (`data-product-id`, `data-variant-id`).\n- **Auth form hooks & Firebase Google Sign-In:**\n - `templates/login.candy`: `<form action=\"/_api/auth/login\" method=\"POST\" class=\"js-auth-form\" data-redirect=\"{{ redirect_url | default: '/account' | escape }}\">` with inputs `name=\"email\"`, `name=\"password\"`, `name=\"redirect\"`, submit button `.js-submit-btn`, dynamic hooks `{{ hooks.login_form_top }}` & `{{ hooks.login_form_bottom }}`, and conditional Google Sign-In button `.js-firebase-google-btn` guarded by `{% if google_auth_enabled %}`.\n - `templates/register.candy`: `<form action=\"/_api/auth/register\" method=\"POST\" class=\"js-auth-form\" data-redirect=\"{{ redirect_url | default: '/account' | escape }}\">` with inputs `name=\"firstName\"`, `name=\"lastName\"`, `name=\"email\"`, `name=\"mobile\"` (`pattern=\"[0-9]{10}\" maxlength=\"10\"`), `name=\"password\"` (`minlength=\"8\"`), `name=\"redirect\"`, submit button `.js-submit-btn`, dynamic hooks `{{ hooks.signup_form_top }}` & `{{ hooks.signup_form_bottom }}`, and conditional `.js-firebase-google-btn`.\n- **Universal Dynamic Plugin Hooks (`{{ hooks.<name> }}` or `{% hook '<name>' %}`):**\n - Always include plugin extension slots so installed merchant apps (reviews, loyalty, badges, upsells, social login) render automatically:\n - Header/Footer: `header_announcement_before`, `header_announcement_after`, `header_actions`, `footer_widgets_before`, `footer_widgets_after`, `footer_bottom`\n - Product Detail: `product_price_after`, `product_add_to_cart_before`, `product_add_to_cart_after`, `product_description_after`, `product_reviews`\n - Cart: `cart_items_after`, `cart_summary_after`\n - Auth: `login_form_top`, `login_form_bottom`, `signup_form_top`, `signup_form_bottom`\n- **Theme Editor schemas:** Keep editable content in `sections/*.candy` with valid JSON inside `{% schema %}`. Include `menuId` in `header.candy` and a `slide` block in `hero-banner.candy`. Attach `{{ block.candy_attributes }}` to block wrappers.\n\n## Build, audit, review and handoff\n\n1. Run `caartzee-theme version patch .` (when releasing a new version) and `caartzee-theme sync-manifest .` after schema/token edits.\n2. Run `caartzee-theme doctor .` to verify storefront-shell rules, currency formatting, cart/variant hooks, auth forms, header menus, and mobile sliders.\n3. Run `caartzee-theme validate .` and `caartzee-theme build .` — resolve all errors before handoff.\n4. Preview locally with `caartzee-theme dev --port 3333` (or `--store <approved-store>`).\n5. Submit with `caartzee-theme push .` only when the developer approves. Once approved in the Partner Portal, merchants can activate or update immediately in **Theme Manage** without any backend redeploy.\n";
|
|
6135
|
+
|
|
6006
6136
|
// src/scaffold/template-generator.ts
|
|
6007
6137
|
import { existsSync as existsSync5, mkdirSync as mkdirSync2, writeFileSync as writeFileSync2 } from "node:fs";
|
|
6008
6138
|
import { dirname as dirname2, join as join4, resolve as resolve4, relative as relative2 } from "node:path";
|
|
@@ -6457,6 +6587,323 @@ var candyStarterProductCard = `<article class="candy-product-card">
|
|
|
6457
6587
|
</article>
|
|
6458
6588
|
`;
|
|
6459
6589
|
|
|
6590
|
+
// src/scaffold/design-presets.ts
|
|
6591
|
+
var CANDY_DESIGN_PRESETS = {
|
|
6592
|
+
"minimal-luxury": {
|
|
6593
|
+
id: "minimal-luxury",
|
|
6594
|
+
name: "Minimal Luxury",
|
|
6595
|
+
description: "Warm ivory canvas, editorial serif headings, hairline borders, and champagne bronze accents.",
|
|
6596
|
+
bestFor: "Fashion, jewelry, skincare, home fragrance, boutique lifestyle brands.",
|
|
6597
|
+
googleFontsUrl: "https://fonts.googleapis.com/css2?family=Cormorant+Garamond:wght@500;600;700&family=Plus+Jakarta+Sans:wght@400;500;600&display=swap",
|
|
6598
|
+
tokens: {
|
|
6599
|
+
colors: {
|
|
6600
|
+
background: "#FAF9F6",
|
|
6601
|
+
surface: "#F2EFE9",
|
|
6602
|
+
text: "#141414",
|
|
6603
|
+
muted: "#6B665E",
|
|
6604
|
+
border: "#E5E0D8",
|
|
6605
|
+
primary: "#141414",
|
|
6606
|
+
primaryText: "#FAF9F6",
|
|
6607
|
+
accent: "#9A7B4F",
|
|
6608
|
+
danger: "#B91C1C",
|
|
6609
|
+
success: "#166534"
|
|
6610
|
+
},
|
|
6611
|
+
typography: {
|
|
6612
|
+
headingFont: "'Cormorant Garamond', Georgia, serif",
|
|
6613
|
+
bodyFont: "'Plus Jakarta Sans', system-ui, -apple-system, sans-serif"
|
|
6614
|
+
},
|
|
6615
|
+
borderRadius: { sm: "2px", md: "4px", lg: "6px", button: "2px" }
|
|
6616
|
+
}
|
|
6617
|
+
},
|
|
6618
|
+
"streetwear-editorial": {
|
|
6619
|
+
id: "streetwear-editorial",
|
|
6620
|
+
name: "Streetwear Editorial",
|
|
6621
|
+
description: "High-contrast stark monochrome, architectural zero-radius grid, and punchy grotesk typography.",
|
|
6622
|
+
bestFor: "Streetwear, sneakers, archival fashion, skate, music merch.",
|
|
6623
|
+
googleFontsUrl: "https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@500;600;700&family=Inter:wght@400;500;600&display=swap",
|
|
6624
|
+
tokens: {
|
|
6625
|
+
colors: {
|
|
6626
|
+
background: "#FFFFFF",
|
|
6627
|
+
surface: "#F4F4F5",
|
|
6628
|
+
text: "#09090B",
|
|
6629
|
+
muted: "#52525B",
|
|
6630
|
+
border: "#E4E4E7",
|
|
6631
|
+
primary: "#09090B",
|
|
6632
|
+
primaryText: "#FFFFFF",
|
|
6633
|
+
accent: "#E11D48",
|
|
6634
|
+
danger: "#DC2626",
|
|
6635
|
+
success: "#15803D"
|
|
6636
|
+
},
|
|
6637
|
+
typography: {
|
|
6638
|
+
headingFont: "'Space Grotesk', system-ui, sans-serif",
|
|
6639
|
+
bodyFont: "'Inter', system-ui, -apple-system, sans-serif"
|
|
6640
|
+
},
|
|
6641
|
+
borderRadius: { sm: "0px", md: "0px", lg: "2px", button: "0px" }
|
|
6642
|
+
}
|
|
6643
|
+
},
|
|
6644
|
+
"organic-wellness": {
|
|
6645
|
+
id: "organic-wellness",
|
|
6646
|
+
name: "Organic Wellness",
|
|
6647
|
+
description: "Soft oat background, forest green ink, sage surfaces, and calm rounded cards.",
|
|
6648
|
+
bestFor: "Skincare, botanicals, tea/coffee, supplements, sustainable living.",
|
|
6649
|
+
googleFontsUrl: "https://fonts.googleapis.com/css2?family=Fraunces:wght@500;600;700&family=DM+Sans:wght@400;500;600&display=swap",
|
|
6650
|
+
tokens: {
|
|
6651
|
+
colors: {
|
|
6652
|
+
background: "#F7F5F0",
|
|
6653
|
+
surface: "#ECECE4",
|
|
6654
|
+
text: "#1F2D24",
|
|
6655
|
+
muted: "#5A6B5F",
|
|
6656
|
+
border: "#DCE0D6",
|
|
6657
|
+
primary: "#2F523B",
|
|
6658
|
+
primaryText: "#F7F5F0",
|
|
6659
|
+
accent: "#C26D47",
|
|
6660
|
+
danger: "#B91C1C",
|
|
6661
|
+
success: "#166534"
|
|
6662
|
+
},
|
|
6663
|
+
typography: {
|
|
6664
|
+
headingFont: "'Fraunces', Georgia, serif",
|
|
6665
|
+
bodyFont: "'DM Sans', system-ui, -apple-system, sans-serif"
|
|
6666
|
+
},
|
|
6667
|
+
borderRadius: { sm: "8px", md: "14px", lg: "20px", button: "9999px" }
|
|
6668
|
+
}
|
|
6669
|
+
},
|
|
6670
|
+
"modern-tech": {
|
|
6671
|
+
id: "modern-tech",
|
|
6672
|
+
name: "Modern Tech",
|
|
6673
|
+
description: "Sleek dark slate surfaces, luminous contrast, geometric sans, and electric indigo accent.",
|
|
6674
|
+
bestFor: "Electronics, audio gear, gaming hardware, digital products, SaaS merch.",
|
|
6675
|
+
googleFontsUrl: "https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@600;700&family=Inter:wght@400;500;600&display=swap",
|
|
6676
|
+
tokens: {
|
|
6677
|
+
colors: {
|
|
6678
|
+
background: "#090D16",
|
|
6679
|
+
surface: "#111827",
|
|
6680
|
+
text: "#F8FAFC",
|
|
6681
|
+
muted: "#94A3B8",
|
|
6682
|
+
border: "#1E293B",
|
|
6683
|
+
primary: "#6366F1",
|
|
6684
|
+
primaryText: "#FFFFFF",
|
|
6685
|
+
accent: "#38BDF8",
|
|
6686
|
+
danger: "#F43F5E",
|
|
6687
|
+
success: "#10B981"
|
|
6688
|
+
},
|
|
6689
|
+
typography: {
|
|
6690
|
+
headingFont: "'Plus Jakarta Sans', system-ui, sans-serif",
|
|
6691
|
+
bodyFont: "'Inter', system-ui, -apple-system, sans-serif"
|
|
6692
|
+
},
|
|
6693
|
+
borderRadius: { sm: "6px", md: "10px", lg: "16px", button: "8px" }
|
|
6694
|
+
}
|
|
6695
|
+
},
|
|
6696
|
+
"vibrant-d2c": {
|
|
6697
|
+
id: "vibrant-d2c",
|
|
6698
|
+
name: "Vibrant D2C",
|
|
6699
|
+
description: "Energetic high-conversion D2C palette, pill buttons, clear savings badges, and crisp card hierarchy.",
|
|
6700
|
+
bestFor: "Snacks, beverages, pets, fitness, everyday consumer brands.",
|
|
6701
|
+
googleFontsUrl: "https://fonts.googleapis.com/css2?family=Outfit:wght@600;700&family=Inter:wght@400;500;600&display=swap",
|
|
6702
|
+
tokens: {
|
|
6703
|
+
colors: {
|
|
6704
|
+
background: "#FFFFFF",
|
|
6705
|
+
surface: "#FFF7ED",
|
|
6706
|
+
text: "#0F172A",
|
|
6707
|
+
muted: "#475569",
|
|
6708
|
+
border: "#E2E8F0",
|
|
6709
|
+
primary: "#EA580C",
|
|
6710
|
+
primaryText: "#FFFFFF",
|
|
6711
|
+
accent: "#0F172A",
|
|
6712
|
+
danger: "#DC2626",
|
|
6713
|
+
success: "#059669"
|
|
6714
|
+
},
|
|
6715
|
+
typography: {
|
|
6716
|
+
headingFont: "'Outfit', system-ui, sans-serif",
|
|
6717
|
+
bodyFont: "'Inter', system-ui, -apple-system, sans-serif"
|
|
6718
|
+
},
|
|
6719
|
+
borderRadius: { sm: "8px", md: "14px", lg: "20px", button: "9999px" }
|
|
6720
|
+
}
|
|
6721
|
+
}
|
|
6722
|
+
};
|
|
6723
|
+
var CANDY_DESIGN_PRESET_IDS = Object.keys(CANDY_DESIGN_PRESETS);
|
|
6724
|
+
function resolveDesignPreset(id) {
|
|
6725
|
+
const key = (id || "minimal-luxury").trim().toLowerCase();
|
|
6726
|
+
return CANDY_DESIGN_PRESETS[key] || CANDY_DESIGN_PRESETS["minimal-luxury"];
|
|
6727
|
+
}
|
|
6728
|
+
function buildCandyDesignSystemCss(presetInput) {
|
|
6729
|
+
const preset = typeof presetInput === "string" || !presetInput ? resolveDesignPreset(presetInput) : presetInput;
|
|
6730
|
+
const { colors, typography, borderRadius } = preset.tokens;
|
|
6731
|
+
return `/* Caartzee Candy Design System — Preset: ${preset.name} (${preset.id}) */
|
|
6732
|
+
@import url('${preset.googleFontsUrl}');
|
|
6733
|
+
|
|
6734
|
+
:root {
|
|
6735
|
+
--cz-bg: ${colors.background};
|
|
6736
|
+
--cz-surface: ${colors.surface};
|
|
6737
|
+
--cz-ink: ${colors.text};
|
|
6738
|
+
--cz-muted: ${colors.muted};
|
|
6739
|
+
--cz-border: ${colors.border};
|
|
6740
|
+
--cz-primary: ${colors.primary};
|
|
6741
|
+
--cz-primary-ink: ${colors.primaryText};
|
|
6742
|
+
--cz-accent: ${colors.accent};
|
|
6743
|
+
--cz-danger: ${colors.danger};
|
|
6744
|
+
--cz-success: ${colors.success};
|
|
6745
|
+
--cz-font-heading: ${typography.headingFont};
|
|
6746
|
+
--cz-font-body: ${typography.bodyFont};
|
|
6747
|
+
--cz-radius-sm: ${borderRadius.sm};
|
|
6748
|
+
--cz-radius-md: ${borderRadius.md};
|
|
6749
|
+
--cz-radius-lg: ${borderRadius.lg};
|
|
6750
|
+
--cz-radius-btn: ${borderRadius.button};
|
|
6751
|
+
--cz-container: 1280px;
|
|
6752
|
+
--cz-space-xs: 0.5rem;
|
|
6753
|
+
--cz-space-sm: 1rem;
|
|
6754
|
+
--cz-space-md: 1.5rem;
|
|
6755
|
+
--cz-space-lg: 3rem;
|
|
6756
|
+
--cz-space-xl: 4.5rem;
|
|
6757
|
+
}
|
|
6758
|
+
|
|
6759
|
+
*, *::before, *::after { box-sizing: border-box; }
|
|
6760
|
+
html { font-size: 16px; -webkit-font-smoothing: antialiased; }
|
|
6761
|
+
body {
|
|
6762
|
+
margin: 0;
|
|
6763
|
+
background: var(--cz-bg);
|
|
6764
|
+
color: var(--cz-ink);
|
|
6765
|
+
font-family: var(--cz-font-body);
|
|
6766
|
+
line-height: 1.6;
|
|
6767
|
+
}
|
|
6768
|
+
h1, h2, h3, h4 { font-family: var(--cz-font-heading); line-height: 1.15; letter-spacing: -0.01em; margin: 0 0 0.75rem; }
|
|
6769
|
+
a { color: inherit; text-decoration: none; }
|
|
6770
|
+
img { max-width: 100%; height: auto; display: block; }
|
|
6771
|
+
|
|
6772
|
+
.cz-container { width: 100%; max-width: var(--cz-container); margin: 0 auto; padding: 0 1.25rem; }
|
|
6773
|
+
|
|
6774
|
+
/* Buttons */
|
|
6775
|
+
.cz-btn, button.js-add-to-cart, button.js-submit-btn {
|
|
6776
|
+
display: inline-flex; align-items: center; justify-content: center; gap: 0.5rem;
|
|
6777
|
+
padding: 0.75rem 1.4rem; border-radius: var(--cz-radius-btn);
|
|
6778
|
+
background: var(--cz-primary); color: var(--cz-primary-ink);
|
|
6779
|
+
border: 1px solid var(--cz-primary); font: 600 0.875rem/1 var(--cz-font-body);
|
|
6780
|
+
cursor: pointer; transition: opacity 0.18s ease, transform 0.15s ease;
|
|
6781
|
+
}
|
|
6782
|
+
.cz-btn:hover, button.js-add-to-cart:hover, button.js-submit-btn:hover { opacity: 0.88; }
|
|
6783
|
+
.cz-btn--outline { background: transparent; color: var(--cz-ink); border-color: var(--cz-border); }
|
|
6784
|
+
.cz-btn--outline:hover { border-color: var(--cz-ink); opacity: 1; }
|
|
6785
|
+
|
|
6786
|
+
/* Announcement & Header */
|
|
6787
|
+
.cz-announcement-bar {
|
|
6788
|
+
background: var(--cz-primary); color: var(--cz-primary-ink);
|
|
6789
|
+
text-align: center; font-size: 0.78rem; font-weight: 500;
|
|
6790
|
+
padding: 0.5rem 1rem; letter-spacing: 0.03em;
|
|
6791
|
+
}
|
|
6792
|
+
.cz-candy-header {
|
|
6793
|
+
position: sticky; top: 0; z-index: 40;
|
|
6794
|
+
background: var(--cz-bg); color: var(--cz-ink);
|
|
6795
|
+
border-bottom: 1px solid var(--cz-border);
|
|
6796
|
+
}
|
|
6797
|
+
.cz-header-inner {
|
|
6798
|
+
max-width: var(--cz-container); margin: 0 auto; padding: 0.9rem 1.25rem;
|
|
6799
|
+
display: flex; align-items: center; justify-content: space-between; gap: 1.25rem; flex-wrap: wrap;
|
|
6800
|
+
}
|
|
6801
|
+
.cz-header-logo { font-family: var(--cz-font-heading); font-size: 1.4rem; font-weight: 700; letter-spacing: -0.02em; }
|
|
6802
|
+
.cz-candy-header nav { display: flex; align-items: center; gap: 1.4rem; flex-wrap: wrap; font-size: 0.9rem; font-weight: 500; }
|
|
6803
|
+
.cz-candy-header nav a:hover { color: var(--cz-accent); }
|
|
6804
|
+
.cz-header-actions { display: flex; align-items: center; gap: 1rem; font-size: 0.875rem; font-weight: 500; }
|
|
6805
|
+
|
|
6806
|
+
/* Hero Banner */
|
|
6807
|
+
.cz-candy-hero {
|
|
6808
|
+
position: relative; overflow: hidden; background: var(--cz-surface);
|
|
6809
|
+
padding: clamp(3rem, 7vw, 6.5rem) 1.25rem; text-align: center;
|
|
6810
|
+
border-bottom: 1px solid var(--cz-border);
|
|
6811
|
+
}
|
|
6812
|
+
.cz-candy-hero h1 { font-size: clamp(2.1rem, 5vw, 4rem); max-width: 18ch; margin: 0 auto 1rem; }
|
|
6813
|
+
.cz-candy-hero p { color: var(--cz-muted); max-width: 54ch; margin: 0 auto 1.75rem; font-size: 1.05rem; }
|
|
6814
|
+
.cz-candy-hero > a {
|
|
6815
|
+
display: inline-flex; padding: 0.85rem 1.8rem; border-radius: var(--cz-radius-btn);
|
|
6816
|
+
background: var(--cz-primary); color: var(--cz-primary-ink); font-weight: 600; font-size: 0.9rem;
|
|
6817
|
+
}
|
|
6818
|
+
.cz-hero-desktop-img {
|
|
6819
|
+
width: 100%; max-width: 1120px; max-height: 480px; object-fit: cover;
|
|
6820
|
+
margin: 0 auto 2rem; border-radius: var(--cz-radius-lg);
|
|
6821
|
+
}
|
|
6822
|
+
|
|
6823
|
+
/* Uniform Product Grid & Cards (used on Home, Collection, Search, Related Products) */
|
|
6824
|
+
.cz-candy-featured-products, .cz-candy-collection, .cz-candy-search {
|
|
6825
|
+
max-width: var(--cz-container); margin: 0 auto; padding: var(--cz-space-lg) 1.25rem;
|
|
6826
|
+
}
|
|
6827
|
+
.candy-product-grid {
|
|
6828
|
+
display: grid; gap: 1.5rem;
|
|
6829
|
+
grid-template-columns: repeat(4, minmax(0, 1fr));
|
|
6830
|
+
}
|
|
6831
|
+
.candy-product-card {
|
|
6832
|
+
display: flex; flex-direction: column; gap: 0.65rem;
|
|
6833
|
+
background: var(--cz-bg); border: 1px solid var(--cz-border);
|
|
6834
|
+
border-radius: var(--cz-radius-md); overflow: hidden; padding-bottom: 1rem;
|
|
6835
|
+
transition: transform 0.2s ease, box-shadow 0.2s ease;
|
|
6836
|
+
}
|
|
6837
|
+
.candy-product-card:hover { transform: translateY(-2px); box-shadow: 0 10px 24px rgba(15, 23, 42, 0.06); }
|
|
6838
|
+
.candy-product-card img {
|
|
6839
|
+
width: 100%; aspect-ratio: 4 / 5; object-fit: cover; background: var(--cz-surface);
|
|
6840
|
+
}
|
|
6841
|
+
.candy-product-card h3, .candy-product-card .candy-card-title {
|
|
6842
|
+
font-size: 1rem; font-weight: 600; margin: 0; padding: 0 0.9rem;
|
|
6843
|
+
}
|
|
6844
|
+
.candy-product-card .candy-price { padding: 0 0.9rem; font-weight: 600; color: var(--cz-ink); font-size: 0.95rem; }
|
|
6845
|
+
.candy-product-card .js-add-to-cart { margin: 0.25rem 0.9rem 0; width: calc(100% - 1.8rem); }
|
|
6846
|
+
|
|
6847
|
+
/* Product Detail Page */
|
|
6848
|
+
.cz-candy-product-detail {
|
|
6849
|
+
max-width: var(--cz-container); margin: 0 auto; padding: var(--cz-space-lg) 1.25rem;
|
|
6850
|
+
display: grid; grid-template-columns: minmax(0, 1.1fr) minmax(0, 0.9fr); gap: 3rem; align-items: start;
|
|
6851
|
+
}
|
|
6852
|
+
.cz-candy-product-detail img[data-product-main-image] {
|
|
6853
|
+
width: 100%; aspect-ratio: 4 / 5; object-fit: cover;
|
|
6854
|
+
border-radius: var(--cz-radius-lg); background: var(--cz-surface); border: 1px solid var(--cz-border);
|
|
6855
|
+
}
|
|
6856
|
+
|
|
6857
|
+
/* Cart, Auth, Wishlist & Content Pages */
|
|
6858
|
+
.cz-candy-cart, .cz-wishlist-section, .cz-candy-page {
|
|
6859
|
+
max-width: 960px; margin: 0 auto; padding: var(--cz-space-lg) 1.25rem;
|
|
6860
|
+
}
|
|
6861
|
+
.cz-auth-section {
|
|
6862
|
+
max-width: 440px; margin: 3.5rem auto; padding: 2rem;
|
|
6863
|
+
background: var(--cz-surface); border: 1px solid var(--cz-border);
|
|
6864
|
+
border-radius: var(--cz-radius-lg);
|
|
6865
|
+
}
|
|
6866
|
+
.cz-auth-section form { display: grid; gap: 0.85rem; margin-top: 1.25rem; }
|
|
6867
|
+
.cz-auth-section input {
|
|
6868
|
+
width: 100%; padding: 0.75rem 0.9rem; border-radius: var(--cz-radius-sm);
|
|
6869
|
+
border: 1px solid var(--cz-border); background: var(--cz-bg); color: var(--cz-ink);
|
|
6870
|
+
font: inherit;
|
|
6871
|
+
}
|
|
6872
|
+
|
|
6873
|
+
/* Editorial Split Section */
|
|
6874
|
+
.cz-candy-image-with-text {
|
|
6875
|
+
max-width: var(--cz-container); margin: var(--cz-space-lg) auto; padding: 2.5rem;
|
|
6876
|
+
background: var(--cz-surface); border: 1px solid var(--cz-border); border-radius: var(--cz-radius-lg);
|
|
6877
|
+
}
|
|
6878
|
+
|
|
6879
|
+
/* Footer */
|
|
6880
|
+
.cz-candy-footer {
|
|
6881
|
+
margin-top: var(--cz-space-xl); border-top: 1px solid var(--cz-border);
|
|
6882
|
+
padding: var(--cz-space-lg) 1.25rem 2rem;
|
|
6883
|
+
}
|
|
6884
|
+
.cz-footer-grid {
|
|
6885
|
+
max-width: var(--cz-container); margin: 0 auto 2rem;
|
|
6886
|
+
display: grid; grid-template-columns: 1.5fr repeat(3, minmax(0, 1fr)); gap: 2rem;
|
|
6887
|
+
}
|
|
6888
|
+
.cz-footer-col { display: flex; flex-direction: column; gap: 0.5rem; font-size: 0.875rem; }
|
|
6889
|
+
.cz-footer-bottom {
|
|
6890
|
+
max-width: var(--cz-container); margin: 0 auto; padding-top: 1.25rem;
|
|
6891
|
+
border-top: 1px solid rgba(255, 255, 255, 0.14); font-size: 0.8rem; opacity: 0.8;
|
|
6892
|
+
}
|
|
6893
|
+
|
|
6894
|
+
/* Responsive Breakpoints */
|
|
6895
|
+
@media (max-width: 1024px) {
|
|
6896
|
+
.candy-product-grid { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
|
6897
|
+
.cz-footer-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
|
6898
|
+
}
|
|
6899
|
+
@media (max-width: 768px) {
|
|
6900
|
+
.candy-product-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 0.9rem; }
|
|
6901
|
+
.cz-candy-product-detail { grid-template-columns: 1fr; gap: 1.75rem; }
|
|
6902
|
+
.cz-footer-grid { grid-template-columns: 1fr; }
|
|
6903
|
+
}
|
|
6904
|
+
`;
|
|
6905
|
+
}
|
|
6906
|
+
|
|
6460
6907
|
// src/scaffold/template-generator.ts
|
|
6461
6908
|
function scaffoldTheme(options) {
|
|
6462
6909
|
const rawSlug = options.slug || options.name?.toLowerCase().replace(/[^a-z0-9_-]+/g, "-") || "starter-theme";
|
|
@@ -6485,7 +6932,7 @@ function scaffoldTheme(options) {
|
|
|
6485
6932
|
};
|
|
6486
6933
|
if (options.engine === "candy") {
|
|
6487
6934
|
const sdkDependency = options.sdkVersion ?? (options.sdkPath ? "file:" + relative2(rootDir, options.sdkPath).replace(/\\/g, "/") : "^1.0.0");
|
|
6488
|
-
return scaffoldCandyThemeInternal({ slug, name, author, description, rootDir, writeFile, createdFiles, sdkDependency });
|
|
6935
|
+
return scaffoldCandyThemeInternal({ slug, name, author, description, rootDir, writeFile, createdFiles, sdkDependency, preset: options.preset });
|
|
6489
6936
|
}
|
|
6490
6937
|
writeFile("package.json", JSON.stringify({
|
|
6491
6938
|
name: `@caartzee-theme/${slug}`,
|
|
@@ -6839,7 +7286,7 @@ npm run push
|
|
|
6839
7286
|
};
|
|
6840
7287
|
}
|
|
6841
7288
|
function scaffoldCandyThemeInternal(params) {
|
|
6842
|
-
const { slug, name, author, description, rootDir, writeFile, createdFiles, sdkDependency } = params;
|
|
7289
|
+
const { slug, name, author, description, rootDir, writeFile, createdFiles, sdkDependency, preset } = params;
|
|
6843
7290
|
writeFile("candy.config.json", JSON.stringify({
|
|
6844
7291
|
engine: "candy",
|
|
6845
7292
|
candyVersion: "1.0.0",
|
|
@@ -7035,13 +7482,42 @@ function scaffoldCandyThemeInternal(params) {
|
|
|
7035
7482
|
</div>
|
|
7036
7483
|
</section>
|
|
7037
7484
|
`);
|
|
7038
|
-
writeFile("sections/header.candy", `<header class="cz-candy-header">
|
|
7039
|
-
|
|
7040
|
-
|
|
7041
|
-
|
|
7042
|
-
<
|
|
7043
|
-
|
|
7044
|
-
|
|
7485
|
+
writeFile("sections/header.candy", `<header class="cz-candy-header" style="background:{{ section.settings.bg_color | default: '#ffffff' }};color:{{ section.settings.text_color | default: '#0f172a' }};">
|
|
7486
|
+
{% if section.settings.show_announcement and section.settings.announcement_text != blank %}
|
|
7487
|
+
<div class="cz-announcement-bar">
|
|
7488
|
+
{% hook 'header_announcement_before' %}
|
|
7489
|
+
<span>{{ section.settings.announcement_text | escape }}</span>
|
|
7490
|
+
{% hook 'header_announcement_after' %}
|
|
7491
|
+
</div>
|
|
7492
|
+
{% endif %}
|
|
7493
|
+
<div class="cz-header-inner">
|
|
7494
|
+
<a href="/" class="cz-header-logo" aria-label="{{ shop.name | escape }}">
|
|
7495
|
+
{% if section.settings.logo != blank %}
|
|
7496
|
+
<img src="{{ section.settings.logo }}" alt="{{ shop.name | escape }}" style="max-width:{{ section.settings.logo_width | default: 120 }}px;" />
|
|
7497
|
+
{% else %}
|
|
7498
|
+
<span>{{ shop.name | escape }}</span>
|
|
7499
|
+
{% endif %}
|
|
7500
|
+
</a>
|
|
7501
|
+
<nav aria-label="Main navigation">
|
|
7502
|
+
{% assign nav_handle = section.settings.menuId | default: 'main-menu' %}
|
|
7503
|
+
{% if linklists[nav_handle].links.size > 0 %}
|
|
7504
|
+
{% for link in linklists[nav_handle].links %}
|
|
7505
|
+
<a href="{{ link.url }}">{{ link.title | escape }}</a>
|
|
7506
|
+
{% endfor %}
|
|
7507
|
+
{% else %}
|
|
7508
|
+
{% for block in section.blocks %}
|
|
7509
|
+
<a href="{{ block.settings.url }}" {{ block.candy_attributes }}>{{ block.settings.label | escape }}</a>
|
|
7510
|
+
{% endfor %}
|
|
7511
|
+
{% endif %}
|
|
7512
|
+
</nav>
|
|
7513
|
+
<div class="cz-header-actions">
|
|
7514
|
+
{% hook 'header_actions' %}
|
|
7515
|
+
{% if section.settings.show_search %}<a href="/search" aria-label="Search">Search</a>{% endif %}
|
|
7516
|
+
{% if section.settings.show_wishlist %}<a href="/wishlist" aria-label="Wishlist">Wishlist</a>{% endif %}
|
|
7517
|
+
{% if section.settings.show_account %}<a href="/account" aria-label="Account">Account</a>{% endif %}
|
|
7518
|
+
{% if section.settings.show_cart %}<a href="/cart" aria-label="Cart">Cart (<span class="js-cart-count" data-cart-count="{{ cart.item_count | default: 0 }}">{{ cart.item_count | default: 0 }}</span>)</a>{% endif %}
|
|
7519
|
+
</div>
|
|
7520
|
+
</div>
|
|
7045
7521
|
</header>
|
|
7046
7522
|
{% schema %}
|
|
7047
7523
|
{
|
|
@@ -7050,8 +7526,19 @@ function scaffoldCandyThemeInternal(params) {
|
|
|
7050
7526
|
"category": "Header",
|
|
7051
7527
|
"allowedRegions": ["header"],
|
|
7052
7528
|
"settings": [
|
|
7529
|
+
{ "id": "logo", "type": "image", "label": "Logo Image" },
|
|
7530
|
+
{ "id": "logo_width", "type": "range", "label": "Logo Width (px)", "min": 60, "max": 240, "step": 4, "default": 120 },
|
|
7531
|
+
{ "id": "mobile_logo", "type": "image", "label": "Mobile Logo" },
|
|
7532
|
+
{ "id": "show_announcement", "type": "checkbox", "label": "Show Announcement Bar", "default": true },
|
|
7533
|
+
{ "id": "announcement_text", "type": "text", "label": "Top Announcement", "default": "Free express shipping on all orders over $150." },
|
|
7534
|
+
{ "id": "bg_color", "type": "color", "label": "Background Color", "default": "#ffffff" },
|
|
7535
|
+
{ "id": "text_color", "type": "color", "label": "Text Color", "default": "#0f172a" },
|
|
7536
|
+
{ "id": "menuId", "type": "select", "label": "Navigation Menu", "options": [] },
|
|
7053
7537
|
{ "id": "sticky", "type": "checkbox", "label": "Sticky Header", "default": true },
|
|
7054
|
-
{ "id": "
|
|
7538
|
+
{ "id": "show_search", "type": "checkbox", "label": "Show Search", "default": true },
|
|
7539
|
+
{ "id": "show_wishlist", "type": "checkbox", "label": "Show Wishlist", "default": true },
|
|
7540
|
+
{ "id": "show_account", "type": "checkbox", "label": "Show Account", "default": true },
|
|
7541
|
+
{ "id": "show_cart", "type": "checkbox", "label": "Show Cart", "default": true }
|
|
7055
7542
|
],
|
|
7056
7543
|
"blocks": [
|
|
7057
7544
|
{
|
|
@@ -7068,9 +7555,24 @@ function scaffoldCandyThemeInternal(params) {
|
|
|
7068
7555
|
{% endschema %}
|
|
7069
7556
|
`);
|
|
7070
7557
|
writeFile("sections/hero-banner.candy", `<section class="cz-candy-hero">
|
|
7558
|
+
{% if mobile_sliders.size > 0 %}
|
|
7559
|
+
<div class="cz-mobile-sliders" data-mobile-sliders="true">
|
|
7560
|
+
{% for slide in mobile_sliders %}
|
|
7561
|
+
<a href="{{ slide.url | default: '/products' }}"><img src="{{ slide.image }}" alt="{{ slide.title | escape }}" /></a>
|
|
7562
|
+
{% endfor %}
|
|
7563
|
+
</div>
|
|
7564
|
+
{% endif %}
|
|
7565
|
+
{% if section.settings.desktop_image != blank %}
|
|
7566
|
+
<img class="cz-hero-desktop-img" src="{{ section.settings.desktop_image }}" alt="{{ section.settings.heading | escape }}" />
|
|
7567
|
+
{% endif %}
|
|
7071
7568
|
<h1>{{ section.settings.heading | escape }}</h1>
|
|
7072
7569
|
<p>{{ section.settings.subheading | escape }}</p>
|
|
7073
7570
|
<a href="{{ section.settings.button_url }}">{{ section.settings.button_label | escape }}</a>
|
|
7571
|
+
{% for block in section.blocks %}
|
|
7572
|
+
<div class="cz-hero-slide" {{ block.candy_attributes }}>
|
|
7573
|
+
<strong>{{ block.settings.title | escape }}</strong>
|
|
7574
|
+
</div>
|
|
7575
|
+
{% endfor %}
|
|
7074
7576
|
</section>
|
|
7075
7577
|
{% schema %}
|
|
7076
7578
|
{
|
|
@@ -7081,10 +7583,23 @@ function scaffoldCandyThemeInternal(params) {
|
|
|
7081
7583
|
"settings": [
|
|
7082
7584
|
{ "id": "heading", "type": "text", "label": "Heading", "default": "Curated Elegance for Modern Living." },
|
|
7083
7585
|
{ "id": "subheading", "type": "textarea", "label": "Subheading", "default": "Handcrafted essentials designed to endure." },
|
|
7586
|
+
{ "id": "desktop_image", "type": "image", "label": "Desktop Banner Image" },
|
|
7587
|
+
{ "id": "mobile_image", "type": "image", "label": "Mobile Banner Image" },
|
|
7084
7588
|
{ "id": "button_label", "type": "text", "label": "Button Label", "default": "Explore Collection" },
|
|
7085
7589
|
{ "id": "button_url", "type": "url", "label": "Button URL", "default": "/products" }
|
|
7086
7590
|
],
|
|
7087
|
-
"blocks": [
|
|
7591
|
+
"blocks": [
|
|
7592
|
+
{
|
|
7593
|
+
"type": "slide",
|
|
7594
|
+
"name": "Hero Slide",
|
|
7595
|
+
"limit": 6,
|
|
7596
|
+
"settings": [
|
|
7597
|
+
{ "id": "title", "type": "text", "label": "Slide Title", "default": "New Arrivals" },
|
|
7598
|
+
{ "id": "image", "type": "image", "label": "Slide Image" },
|
|
7599
|
+
{ "id": "url", "type": "url", "label": "Slide Link", "default": "/products" }
|
|
7600
|
+
]
|
|
7601
|
+
}
|
|
7602
|
+
]
|
|
7088
7603
|
}
|
|
7089
7604
|
{% endschema %}
|
|
7090
7605
|
`);
|
|
@@ -7133,8 +7648,25 @@ function scaffoldCandyThemeInternal(params) {
|
|
|
7133
7648
|
}
|
|
7134
7649
|
{% endschema %}
|
|
7135
7650
|
`);
|
|
7136
|
-
writeFile("sections/footer.candy", `<footer class="cz-candy-footer">
|
|
7137
|
-
|
|
7651
|
+
writeFile("sections/footer.candy", `<footer class="cz-candy-footer" style="background:{{ section.settings.bg_color | default: '#0f172a' }};color:{{ section.settings.text_color | default: '#f8fafc' }};">
|
|
7652
|
+
{% hook 'footer_widgets_before' %}
|
|
7653
|
+
<div class="cz-footer-grid">
|
|
7654
|
+
<div class="cz-footer-brand">
|
|
7655
|
+
{% if section.settings.logo != blank %}<img src="{{ section.settings.logo }}" alt="{{ shop.name | escape }}" />{% else %}<strong>{{ shop.name | escape }}</strong>{% endif %}
|
|
7656
|
+
<p>{{ section.settings.description | escape }}</p>
|
|
7657
|
+
</div>
|
|
7658
|
+
{% for block in section.blocks %}
|
|
7659
|
+
<div class="cz-footer-col" {{ block.candy_attributes }}>
|
|
7660
|
+
<h4>{{ block.settings.heading | escape }}</h4>
|
|
7661
|
+
<a href="{{ block.settings.url | default: '/products' }}">{{ block.settings.link_label | default: 'Browse' | escape }}</a>
|
|
7662
|
+
</div>
|
|
7663
|
+
{% endfor %}
|
|
7664
|
+
</div>
|
|
7665
|
+
{% hook 'footer_widgets_after' %}
|
|
7666
|
+
<div class="cz-footer-bottom">
|
|
7667
|
+
<p>{{ section.settings.copyright_text | escape }}</p>
|
|
7668
|
+
{% hook 'footer_bottom' %}
|
|
7669
|
+
</div>
|
|
7138
7670
|
</footer>
|
|
7139
7671
|
{% schema %}
|
|
7140
7672
|
{
|
|
@@ -7143,25 +7675,113 @@ function scaffoldCandyThemeInternal(params) {
|
|
|
7143
7675
|
"category": "Footer",
|
|
7144
7676
|
"allowedRegions": ["footer"],
|
|
7145
7677
|
"settings": [
|
|
7678
|
+
{ "id": "logo", "type": "image", "label": "Footer Logo" },
|
|
7679
|
+
{ "id": "description", "type": "textarea", "label": "Store Description", "default": "Thoughtfully crafted products delivered to your door." },
|
|
7680
|
+
{ "id": "bg_color", "type": "color", "label": "Background Color", "default": "#0f172a" },
|
|
7681
|
+
{ "id": "text_color", "type": "color", "label": "Text Color", "default": "#f8fafc" },
|
|
7682
|
+
{ "id": "show_newsletter", "type": "checkbox", "label": "Show Newsletter Signup", "default": true },
|
|
7146
7683
|
{ "id": "copyright_text", "type": "text", "label": "Copyright Notice", "default": "© Caartzee Storefront. Powered by Candy." }
|
|
7147
7684
|
],
|
|
7148
|
-
"blocks": [
|
|
7685
|
+
"blocks": [
|
|
7686
|
+
{
|
|
7687
|
+
"type": "link_column",
|
|
7688
|
+
"name": "Footer Column",
|
|
7689
|
+
"limit": 4,
|
|
7690
|
+
"settings": [
|
|
7691
|
+
{ "id": "heading", "type": "text", "label": "Column Heading", "default": "Quick Links" },
|
|
7692
|
+
{ "id": "link_label", "type": "text", "label": "Link Label", "default": "Shop All" },
|
|
7693
|
+
{ "id": "url", "type": "url", "label": "Link URL", "default": "/products" }
|
|
7694
|
+
]
|
|
7695
|
+
}
|
|
7696
|
+
]
|
|
7149
7697
|
}
|
|
7150
7698
|
{% endschema %}
|
|
7699
|
+
`);
|
|
7700
|
+
writeFile("templates/login.candy", `<section class="cz-auth-section">
|
|
7701
|
+
<h1>Sign In</h1>
|
|
7702
|
+
{% hook 'login_form_top' %}
|
|
7703
|
+
<form action="/_api/auth/login" method="POST" class="js-auth-form" data-redirect="{{ redirect_url | default: '/account' | escape }}">
|
|
7704
|
+
<input type="email" name="email" required placeholder="Email address" />
|
|
7705
|
+
<input type="password" name="password" required placeholder="Password" />
|
|
7706
|
+
<input type="hidden" name="redirect" value="{{ redirect_url | default: '/account' | escape }}" />
|
|
7707
|
+
<button type="submit" class="js-submit-btn">Sign In</button>
|
|
7708
|
+
{% if google_auth_enabled %}
|
|
7709
|
+
<button type="button" class="js-firebase-google-btn">Continue with Google</button>
|
|
7710
|
+
{% endif %}
|
|
7711
|
+
</form>
|
|
7712
|
+
{% hook 'login_form_bottom' %}
|
|
7713
|
+
</section>
|
|
7714
|
+
`);
|
|
7715
|
+
writeFile("templates/register.candy", `<section class="cz-auth-section">
|
|
7716
|
+
<h1>Create Account</h1>
|
|
7717
|
+
{% hook 'signup_form_top' %}
|
|
7718
|
+
<form action="/_api/auth/register" method="POST" class="js-auth-form" data-redirect="{{ redirect_url | default: '/account' | escape }}">
|
|
7719
|
+
<input type="text" name="firstName" required placeholder="First name" />
|
|
7720
|
+
<input type="text" name="lastName" placeholder="Last name" />
|
|
7721
|
+
<input type="email" name="email" required placeholder="Email address" />
|
|
7722
|
+
<input type="password" name="password" minlength="6" required placeholder="Password" />
|
|
7723
|
+
<input type="hidden" name="redirect" value="{{ redirect_url | default: '/account' | escape }}" />
|
|
7724
|
+
<button type="submit" class="js-submit-btn">Create Account</button>
|
|
7725
|
+
</form>
|
|
7726
|
+
{% hook 'signup_form_bottom' %}
|
|
7727
|
+
</section>
|
|
7728
|
+
`);
|
|
7729
|
+
writeFile("templates/wishlist.candy", `<section class="cz-wishlist-section">
|
|
7730
|
+
<h1>My Wishlist</h1>
|
|
7731
|
+
<p>Saved items appear here when signed in or in an active browser session.</p>
|
|
7732
|
+
</section>
|
|
7151
7733
|
`);
|
|
7152
7734
|
writeFile("snippets/price.candy", `<span class="candy-price">{{ product.price | money }}</span>
|
|
7153
7735
|
`);
|
|
7736
|
+
if (!existsSync5(join4(rootDir, "AGENTS.md")))
|
|
7737
|
+
writeFile("AGENTS.md", AGENTS_default);
|
|
7738
|
+
if (!existsSync5(join4(rootDir, "CLAUDE.md"))) {
|
|
7739
|
+
writeFile("CLAUDE.md", `# Claude Code Instructions — Caartzee Candy Storefront
|
|
7740
|
+
|
|
7741
|
+
Read [AGENTS.md](./AGENTS.md) and call the Candy MCP tool \`read_candy_guide\` before editing any files.
|
|
7742
|
+
|
|
7743
|
+
## Key Rules
|
|
7744
|
+
- Use Candy MCP (\`list_store_permissions\`, \`request_store_access\`, \`read_store_catalog\`) for authorized merchant data.
|
|
7745
|
+
- Keep every section editable via \`{% schema %}\` and emit \`{{ block.candy_attributes }}\` on blocks.
|
|
7746
|
+
- Never emit synthetic \`-default\` variant IDs or invent API endpoints.
|
|
7747
|
+
- Run \`caartzee-theme doctor .\`, \`caartzee-theme validate .\`, \`caartzee-theme test . --json\`, and \`caartzee-theme build .\` before finishing.
|
|
7748
|
+
- Never run \`caartzee-theme push\` without explicit developer authorization.
|
|
7749
|
+
`);
|
|
7750
|
+
}
|
|
7751
|
+
if (!existsSync5(join4(rootDir, ".cursorrules"))) {
|
|
7752
|
+
writeFile(".cursorrules", `# Caartzee Candy Theme Rules
|
|
7753
|
+
- Follow AGENTS.md and Candy MCP documentation (call read_candy_guide first).
|
|
7754
|
+
- Preserve merchant content, section IDs, Theme Editor schemas, {{ block.candy_attributes }}, cart/wishlist/auth runtime hooks, and {% hook "..." %} plugin slots.
|
|
7755
|
+
- Use document-level event delegation in assets/theme.js so UI survives live Theme Editor section re-rendering.
|
|
7756
|
+
- Never hardcode merchant products, prices, currencies, payment gateways, or secrets.
|
|
7757
|
+
- Verify changes with caartzee-theme doctor ., caartzee-theme validate ., caartzee-theme test . --json, and caartzee-theme build ..
|
|
7758
|
+
`);
|
|
7759
|
+
}
|
|
7154
7760
|
writeFile("snippets/product-card.candy", candyStarterProductCard);
|
|
7761
|
+
const resolvedPreset = resolveDesignPreset(preset);
|
|
7155
7762
|
writeFile("schemas/settings_schema.json", JSON.stringify([
|
|
7156
7763
|
{
|
|
7157
7764
|
name: "Colors",
|
|
7158
7765
|
settings: [
|
|
7159
|
-
{ id: "primary_color", type: "color", label: "Primary Color", default:
|
|
7766
|
+
{ id: "primary_color", type: "color", label: "Primary Color", default: resolvedPreset.tokens.colors.primary },
|
|
7767
|
+
{ id: "accent_color", type: "color", label: "Accent Color", default: resolvedPreset.tokens.colors.accent },
|
|
7768
|
+
{ id: "background_color", type: "color", label: "Background Color", default: resolvedPreset.tokens.colors.background },
|
|
7769
|
+
{ id: "text_color", type: "color", label: "Text Color", default: resolvedPreset.tokens.colors.text }
|
|
7770
|
+
]
|
|
7771
|
+
},
|
|
7772
|
+
{
|
|
7773
|
+
name: "Typography",
|
|
7774
|
+
settings: [
|
|
7775
|
+
{ id: "heading_font", type: "font", label: "Heading Font", default: resolvedPreset.tokens.typography.headingFont },
|
|
7776
|
+
{ id: "body_font", type: "font", label: "Body Font", default: resolvedPreset.tokens.typography.bodyFont }
|
|
7160
7777
|
]
|
|
7161
7778
|
}
|
|
7162
7779
|
], null, 2));
|
|
7163
|
-
writeFile("assets/theme.css",
|
|
7780
|
+
writeFile("assets/theme.css", buildCandyDesignSystemCss(resolvedPreset));
|
|
7164
7781
|
writeFile("assets/theme.js", `window.__CAARTZEE_CANDY_THEME__ = true;
|
|
7782
|
+
document.addEventListener('caartzee:section:load', function () {
|
|
7783
|
+
// Re-initialize any section-specific UI widgets after Theme Editor live swaps.
|
|
7784
|
+
});
|
|
7165
7785
|
`);
|
|
7166
7786
|
writeFile("locales/en.default.json", JSON.stringify({
|
|
7167
7787
|
general: {
|
|
@@ -7512,13 +8132,94 @@ import { resolve as resolve6, sep, extname } from "node:path";
|
|
|
7512
8132
|
|
|
7513
8133
|
// src/dev-server/theme-preview.ts
|
|
7514
8134
|
var escape = (value) => String(value ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]);
|
|
7515
|
-
function
|
|
8135
|
+
function renderBuiltInCommerceShellPage(context) {
|
|
8136
|
+
const ctx = context;
|
|
8137
|
+
const cart = ctx.cart || { items: [], subtotal: 0, discount: 0, tax: 0, shipping: 0, total: 0, itemCount: 0 };
|
|
8138
|
+
const customer = ctx.customer || { loggedIn: false, orders: [] };
|
|
8139
|
+
const orders = Array.isArray(ctx.orders) ? ctx.orders : [];
|
|
8140
|
+
if (context.pageType === "login") {
|
|
8141
|
+
return `<section style="max-width:420px;margin:48px auto;padding:24px;border:1px solid #e2e8f0;border-radius:12px;">
|
|
8142
|
+
<h1 style="margin:0 0 8px;">Customer Sign In</h1>
|
|
8143
|
+
<p style="font-size:13px;color:#64748b;margin:0 0 16px;">Sandbox demo account: <code>demo@caartzee.local</code> / <code>password123</code></p>
|
|
8144
|
+
<form action="/_api/auth/login" method="POST" class="js-auth-form" data-redirect="/account" style="display:grid;gap:12px;">
|
|
8145
|
+
<input name="email" type="email" required placeholder="Email" value="demo@caartzee.local" style="padding:10px;border:1px solid #cbd5e1;border-radius:8px;" />
|
|
8146
|
+
<input name="password" type="password" required placeholder="Password" value="password123" style="padding:10px;border:1px solid #cbd5e1;border-radius:8px;" />
|
|
8147
|
+
<button type="submit" class="js-submit-btn" style="padding:10px 14px;background:#0f172a;color:#fff;border:none;border-radius:8px;cursor:pointer;">Sign In</button>
|
|
8148
|
+
<button type="button" class="js-firebase-google-btn" style="padding:10px 14px;background:#fff;border:1px solid #cbd5e1;border-radius:8px;cursor:pointer;">Continue with Google (Sandbox)</button>
|
|
8149
|
+
</form>
|
|
8150
|
+
<p style="font-size:13px;margin-top:14px;">New shopper? <a href="/register">Create an account</a></p>
|
|
8151
|
+
</section>`;
|
|
8152
|
+
}
|
|
8153
|
+
if (context.pageType === "signup") {
|
|
8154
|
+
return `<section style="max-width:440px;margin:48px auto;padding:24px;border:1px solid #e2e8f0;border-radius:12px;">
|
|
8155
|
+
<h1 style="margin:0 0 16px;">Create Customer Account</h1>
|
|
8156
|
+
<form action="/_api/auth/register" method="POST" class="js-auth-form" data-redirect="/account" style="display:grid;gap:12px;">
|
|
8157
|
+
<input name="firstName" required placeholder="First Name" style="padding:10px;border:1px solid #cbd5e1;border-radius:8px;" />
|
|
8158
|
+
<input name="lastName" placeholder="Last Name" style="padding:10px;border:1px solid #cbd5e1;border-radius:8px;" />
|
|
8159
|
+
<input name="email" type="email" required placeholder="Email" style="padding:10px;border:1px solid #cbd5e1;border-radius:8px;" />
|
|
8160
|
+
<input name="password" type="password" minlength="6" required placeholder="Password" style="padding:10px;border:1px solid #cbd5e1;border-radius:8px;" />
|
|
8161
|
+
<button type="submit" class="js-submit-btn" style="padding:10px 14px;background:#0f172a;color:#fff;border:none;border-radius:8px;cursor:pointer;">Create Account</button>
|
|
8162
|
+
</form>
|
|
8163
|
+
</section>`;
|
|
8164
|
+
}
|
|
8165
|
+
if (context.pageType === "checkout") {
|
|
8166
|
+
const itemsHtml = (cart.items || []).map((i) => `<li style="display:flex;justify-content:space-between;padding:6px 0;border-bottom:1px solid #f1f5f9;"><span>${escape(i.title)} × ${i.quantity}</span><strong>$${Number(i.lineTotal ?? i.price * i.quantity).toFixed(2)}</strong></li>`).join("");
|
|
8167
|
+
return `<section style="max-width:720px;margin:40px auto;padding:24px;border:1px solid #e2e8f0;border-radius:12px;">
|
|
8168
|
+
<h1 style="margin:0 0 6px;">Caartzee Sandbox Checkout</h1>
|
|
8169
|
+
<p style="font-size:13px;color:#64748b;margin:0 0 20px;">Isolated test checkout · Payment gateway: <code>caartzee_test_sandbox</code> (no real charges).</p>
|
|
8170
|
+
<ul style="list-style:none;padding:0;margin:0 0 16px;">${itemsHtml || '<li>Your sandbox cart is empty. <a href="/products">Browse products</a></li>'}</ul>
|
|
8171
|
+
<div style="font-size:14px;margin-bottom:18px;">Subtotal: $${Number(cart.subtotal || 0).toFixed(2)} · Discount: -$${Number(cart.discount || 0).toFixed(2)} · Tax: $${Number(cart.tax || 0).toFixed(2)} · Shipping: $${Number(cart.shipping || 0).toFixed(2)} · <strong>Total: $${Number(cart.total || 0).toFixed(2)}</strong></div>
|
|
8172
|
+
<form class="js-checkout-form" style="display:grid;gap:10px;">
|
|
8173
|
+
<input name="fullName" required placeholder="Full Name" value="${escape(customer.name || "Sandbox Shopper")}" style="padding:10px;border:1px solid #cbd5e1;border-radius:8px;" />
|
|
8174
|
+
<input name="email" type="email" required placeholder="Email" value="${escape(customer.email || "demo@caartzee.local")}" style="padding:10px;border:1px solid #cbd5e1;border-radius:8px;" />
|
|
8175
|
+
<input name="address1" required placeholder="Street Address" value="100 Sandbox Way" style="padding:10px;border:1px solid #cbd5e1;border-radius:8px;" />
|
|
8176
|
+
<input name="city" required placeholder="City" value="Testville" style="padding:10px;border:1px solid #cbd5e1;border-radius:8px;" />
|
|
8177
|
+
<input type="hidden" name="gateway" value="caartzee_test_sandbox" />
|
|
8178
|
+
<button type="submit" style="padding:12px 16px;background:#059669;color:#fff;border:none;border-radius:8px;font-weight:600;cursor:pointer;">Place Sandbox Order</button>
|
|
8179
|
+
</form>
|
|
8180
|
+
</section>`;
|
|
8181
|
+
}
|
|
8182
|
+
if (context.pageType === "account") {
|
|
8183
|
+
const orderRows = orders.map((o) => `<li style="padding:8px 0;border-bottom:1px solid #f1f5f9;"><strong>${escape(o.orderNumber)}</strong> · ${escape(o.status)} · $${Number(o.total).toFixed(2)}</li>`).join("");
|
|
8184
|
+
return `<section style="max-width:720px;margin:40px auto;padding:24px;border:1px solid #e2e8f0;border-radius:12px;">
|
|
8185
|
+
<div style="display:flex;justify-content:space-between;align-items:center;">
|
|
8186
|
+
<h1 style="margin:0;">Customer Account</h1>
|
|
8187
|
+
${customer.loggedIn ? '<button class="js-logout-btn" style="padding:6px 12px;border:1px solid #cbd5e1;border-radius:6px;background:#fff;cursor:pointer;">Logout</button>' : '<a href="/login">Sign In</a>'}
|
|
8188
|
+
</div>
|
|
8189
|
+
<p style="color:#475569;">${customer.loggedIn ? `Signed in as <strong>${escape(customer.name)}</strong> (${escape(customer.email)})` : "Not signed in. Visit /login or /register to test customer authentication."}</p>
|
|
8190
|
+
<h3>Sandbox Order History (${orders.length})</h3>
|
|
8191
|
+
<ul style="list-style:none;padding:0;">${orderRows || "<li>No sandbox orders placed yet.</li>"}</ul>
|
|
8192
|
+
</section>`;
|
|
8193
|
+
}
|
|
8194
|
+
if (context.pageType === "order-success") {
|
|
8195
|
+
const latest = orders[0];
|
|
8196
|
+
return `<section style="max-width:600px;margin:48px auto;padding:24px;border:1px solid #bbf7d0;background:#f0fdf4;border-radius:12px;">
|
|
8197
|
+
<h1 style="margin:0 0 8px;color:#166534;">Sandbox Order Confirmed</h1>
|
|
8198
|
+
<p>${latest ? `Order <strong>${escape(latest.orderNumber)}</strong> placed for $${Number(latest.total).toFixed(2)} via sandbox payment.` : "Order confirmed in sandbox session."}</p>
|
|
8199
|
+
<p><a href="/account">View Order History</a> · <a href="/track-order">Track Order</a></p>
|
|
8200
|
+
</section>`;
|
|
8201
|
+
}
|
|
8202
|
+
if (context.pageType === "track-order") {
|
|
8203
|
+
const latest = orders[0];
|
|
8204
|
+
return `<section style="max-width:600px;margin:48px auto;padding:24px;border:1px solid #e2e8f0;border-radius:12px;">
|
|
8205
|
+
<h1 style="margin:0 0 12px;">Track Sandbox Order</h1>
|
|
8206
|
+
<p>${latest ? `Latest sandbox order <strong>${escape(latest.orderNumber)}</strong> — Status: <strong>${escape(latest.status)}</strong>` : "No sandbox orders in this session yet."}</p>
|
|
8207
|
+
</section>`;
|
|
8208
|
+
}
|
|
8209
|
+
return null;
|
|
8210
|
+
}
|
|
8211
|
+
function renderThemePreview(theme, context, preferContextSettings = false, editorOverride) {
|
|
7516
8212
|
const key = context.pageType === "product-list" ? "products" : context.pageType;
|
|
7517
8213
|
const page = theme.defaultTemplates.pages[key] || theme.defaultTemplates.pages[context.pageType];
|
|
7518
8214
|
const settings = theme.manifest.defaultGlobalSettings || {};
|
|
7519
|
-
context = {
|
|
7520
|
-
|
|
7521
|
-
|
|
8215
|
+
context = {
|
|
8216
|
+
...context,
|
|
8217
|
+
themeSlug: theme.slug,
|
|
8218
|
+
globalSettings: preferContextSettings ? { ...settings, ...context.globalSettings, ...editorOverride?.globalSettings || {} } : { ...context.globalSettings, ...settings, ...editorOverride?.globalSettings || {} }
|
|
8219
|
+
};
|
|
8220
|
+
if (context.pageType === "home") {
|
|
8221
|
+
context = { ...context, sections: editorOverride?.bodySections || page?.regions.body || [] };
|
|
8222
|
+
}
|
|
7522
8223
|
const render = (section) => {
|
|
7523
8224
|
const definition = theme.manifest.sections.find((s) => s.type === section.type);
|
|
7524
8225
|
const defaults = Object.fromEntries((definition?.settings || []).map((f) => [f.id, f.default]));
|
|
@@ -7539,15 +8240,23 @@ function renderThemePreview(theme, context, preferContextSettings = false) {
|
|
|
7539
8240
|
}
|
|
7540
8241
|
}), { section: resolved, themeSlug: theme.slug });
|
|
7541
8242
|
};
|
|
7542
|
-
const
|
|
7543
|
-
const
|
|
8243
|
+
const activeLayout = editorOverride?.layout || theme.defaultTemplates.layout;
|
|
8244
|
+
const header = (activeLayout.regions.header || []).map(render).join("");
|
|
8245
|
+
const footer = (activeLayout.regions.footer || []).map(render).join("");
|
|
7544
8246
|
const custom = theme.renderPage?.(context);
|
|
7545
8247
|
if (custom?.trimStart().toLowerCase().startsWith("<!doctype html"))
|
|
7546
8248
|
return custom;
|
|
7547
|
-
const body = custom || (page?.regions.body || []).map(render).join("");
|
|
8249
|
+
const body = custom || renderBuiltInCommerceShellPage(context) || (context.pageType === "home" ? editorOverride?.bodySections || page?.regions.body || [] : page?.regions.body || []).map(render).join("");
|
|
7548
8250
|
const missing = !body ? `<p>No template implemented for ${escape(context.pageType)}.</p>` : "";
|
|
7549
8251
|
const colors = theme.tokens?.colors || {};
|
|
7550
|
-
const variables = Object.entries({
|
|
8252
|
+
const variables = Object.entries({
|
|
8253
|
+
bg: colors.background,
|
|
8254
|
+
surface: colors.surface,
|
|
8255
|
+
text: colors.text,
|
|
8256
|
+
"text-muted": colors.muted,
|
|
8257
|
+
border: colors.border,
|
|
8258
|
+
primary: colors.primary
|
|
8259
|
+
}).filter(([, value]) => value).map(([k, value]) => `--sf-color-${k}:${value};`).join("");
|
|
7551
8260
|
const tokenCss = `:root{${variables}--sf-font-heading:${theme.tokens?.typography?.headingFont || "Georgia,serif"};--sf-font-sans:${theme.tokens?.typography?.bodyFont || "Arial,sans-serif"};}body{font-family:var(--sf-font-sans)}`;
|
|
7552
8261
|
const themeCss = (tokenCss + (theme.tokens?.customCss || "")).replace(/<\/style/gi, "<\\/style");
|
|
7553
8262
|
return `<!doctype html><html class="theme-${escape(theme.slug)}"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>${escape(theme.name)} — local preview</title><link rel="stylesheet" href="/assets/theme.css"><style>body{margin:0;font-family:system-ui}img{max-width:100%}${themeCss}</style></head><body>${header}<main>${body}${missing}</main>${footer}</body></html>`;
|
|
@@ -7620,13 +8329,811 @@ async function createCatalogDevContext(loadCatalog, pageType, pathname, params)
|
|
|
7620
8329
|
}
|
|
7621
8330
|
}
|
|
7622
8331
|
|
|
8332
|
+
// src/dev-server/local-commerce-runtime.ts
|
|
8333
|
+
import { randomUUID } from "node:crypto";
|
|
8334
|
+
|
|
8335
|
+
class LocalCommerceStore {
|
|
8336
|
+
sessions = new Map;
|
|
8337
|
+
getOrCreateSession(req, res) {
|
|
8338
|
+
const cookieHeader = req.headers.cookie || "";
|
|
8339
|
+
const match = /(?:^|;\s*)cz_dev_sid=([^;]+)/.exec(cookieHeader);
|
|
8340
|
+
const existingId = match?.[1];
|
|
8341
|
+
if (existingId && this.sessions.has(existingId)) {
|
|
8342
|
+
return this.sessions.get(existingId);
|
|
8343
|
+
}
|
|
8344
|
+
const sessionId = existingId || randomUUID();
|
|
8345
|
+
const defaultCustomer = {
|
|
8346
|
+
id: "dev-cust-1",
|
|
8347
|
+
name: "Demo Shopper",
|
|
8348
|
+
firstName: "Demo",
|
|
8349
|
+
lastName: "Shopper",
|
|
8350
|
+
email: "demo@caartzee.local",
|
|
8351
|
+
addresses: [
|
|
8352
|
+
{
|
|
8353
|
+
id: "addr-1",
|
|
8354
|
+
fullName: "Demo Shopper",
|
|
8355
|
+
address1: "100 Sandbox Ave",
|
|
8356
|
+
city: "Testville",
|
|
8357
|
+
postalCode: "10001",
|
|
8358
|
+
country: "US"
|
|
8359
|
+
}
|
|
8360
|
+
]
|
|
8361
|
+
};
|
|
8362
|
+
const registeredUsers = new Map;
|
|
8363
|
+
registeredUsers.set(defaultCustomer.email, { password: "password123", customer: defaultCustomer });
|
|
8364
|
+
const session = {
|
|
8365
|
+
sessionId,
|
|
8366
|
+
cart: [],
|
|
8367
|
+
couponCode: null,
|
|
8368
|
+
shippingMethod: "standard",
|
|
8369
|
+
wishlist: [],
|
|
8370
|
+
customer: null,
|
|
8371
|
+
registeredUsers,
|
|
8372
|
+
orders: []
|
|
8373
|
+
};
|
|
8374
|
+
this.sessions.set(sessionId, session);
|
|
8375
|
+
res.setHeader("Set-Cookie", `cz_dev_sid=${sessionId}; Path=/; HttpOnly; SameSite=Lax`);
|
|
8376
|
+
return session;
|
|
8377
|
+
}
|
|
8378
|
+
computeTotals(session) {
|
|
8379
|
+
const subtotal = Number(session.cart.reduce((s, item) => s + item.price * item.quantity, 0).toFixed(2));
|
|
8380
|
+
const discount = session.couponCode === "TEST10" ? Number((subtotal * 0.1).toFixed(2)) : 0;
|
|
8381
|
+
const shipping = session.couponCode === "FREESHIP" || subtotal === 0 ? 0 : session.shippingMethod === "express" ? 15 : subtotal >= 100 ? 0 : 8;
|
|
8382
|
+
const taxable = Math.max(0, subtotal - discount);
|
|
8383
|
+
const tax = Number((taxable * 0.08).toFixed(2));
|
|
8384
|
+
const total = Number((taxable + tax + shipping).toFixed(2));
|
|
8385
|
+
const itemCount = session.cart.reduce((s, i) => s + i.quantity, 0);
|
|
8386
|
+
return { subtotal, discount, shipping, tax, total, itemCount };
|
|
8387
|
+
}
|
|
8388
|
+
applySessionToContext(session, context) {
|
|
8389
|
+
const totals = this.computeTotals(session);
|
|
8390
|
+
return {
|
|
8391
|
+
...context,
|
|
8392
|
+
cart: {
|
|
8393
|
+
items: session.cart.map((item) => ({
|
|
8394
|
+
id: item.id,
|
|
8395
|
+
productId: item.productId,
|
|
8396
|
+
variantId: item.variantId,
|
|
8397
|
+
title: item.title,
|
|
8398
|
+
name: item.title,
|
|
8399
|
+
slug: item.slug,
|
|
8400
|
+
price: item.price,
|
|
8401
|
+
quantity: item.quantity,
|
|
8402
|
+
imageUrl: item.imageUrl,
|
|
8403
|
+
lineTotal: Number((item.price * item.quantity).toFixed(2))
|
|
8404
|
+
})),
|
|
8405
|
+
itemCount: totals.itemCount,
|
|
8406
|
+
item_count: totals.itemCount,
|
|
8407
|
+
subtotal: totals.subtotal,
|
|
8408
|
+
discount: totals.discount,
|
|
8409
|
+
tax: totals.tax,
|
|
8410
|
+
shipping: totals.shipping,
|
|
8411
|
+
total: totals.total,
|
|
8412
|
+
couponCode: session.couponCode
|
|
8413
|
+
},
|
|
8414
|
+
wishlist: session.wishlist,
|
|
8415
|
+
wishlistIds: session.wishlist,
|
|
8416
|
+
customer: session.customer ? {
|
|
8417
|
+
loggedIn: true,
|
|
8418
|
+
logged_in: true,
|
|
8419
|
+
...session.customer,
|
|
8420
|
+
orders: session.orders
|
|
8421
|
+
} : { loggedIn: false, logged_in: false, orders: [] },
|
|
8422
|
+
orders: session.orders
|
|
8423
|
+
};
|
|
8424
|
+
}
|
|
8425
|
+
async handleApiRequest(req, res, pathname, searchParams, resolveCatalogProducts) {
|
|
8426
|
+
if (!pathname.startsWith("/_api/"))
|
|
8427
|
+
return false;
|
|
8428
|
+
const session = this.getOrCreateSession(req, res);
|
|
8429
|
+
const method = (req.method || "GET").toUpperCase();
|
|
8430
|
+
const json = (status, body) => {
|
|
8431
|
+
res.writeHead(status, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" });
|
|
8432
|
+
res.end(JSON.stringify(body));
|
|
8433
|
+
return true;
|
|
8434
|
+
};
|
|
8435
|
+
const readBody = async () => {
|
|
8436
|
+
const chunks = [];
|
|
8437
|
+
for await (const chunk of req)
|
|
8438
|
+
chunks.push(Buffer.from(chunk));
|
|
8439
|
+
const raw = Buffer.concat(chunks).toString("utf8").trim();
|
|
8440
|
+
if (!raw)
|
|
8441
|
+
return {};
|
|
8442
|
+
const ct = String(req.headers["content-type"] || "");
|
|
8443
|
+
if (ct.includes("application/x-www-form-urlencoded")) {
|
|
8444
|
+
return Object.fromEntries(new URLSearchParams(raw).entries());
|
|
8445
|
+
}
|
|
8446
|
+
try {
|
|
8447
|
+
return JSON.parse(raw);
|
|
8448
|
+
} catch {
|
|
8449
|
+
return {};
|
|
8450
|
+
}
|
|
8451
|
+
};
|
|
8452
|
+
if (pathname === "/_api/cart") {
|
|
8453
|
+
if (method === "GET") {
|
|
8454
|
+
return json(200, { success: true, items: session.cart, ...this.computeTotals(session), couponCode: session.couponCode });
|
|
8455
|
+
}
|
|
8456
|
+
const body = await readBody();
|
|
8457
|
+
if (method === "POST") {
|
|
8458
|
+
const productId = body.product_id ?? body.productId;
|
|
8459
|
+
const rawVariant = body.variant_id ?? body.variantId ?? null;
|
|
8460
|
+
if (!productId)
|
|
8461
|
+
return json(422, { success: false, message: "product_id is required." });
|
|
8462
|
+
if (typeof rawVariant === "string" && /-default$/i.test(rawVariant)) {
|
|
8463
|
+
return json(422, {
|
|
8464
|
+
success: false,
|
|
8465
|
+
code: "INVALID_VARIANT_ID",
|
|
8466
|
+
message: `Invalid synthetic variant_id "${rawVariant}". Guard data-variant-id with product.has_inventory_variants.`
|
|
8467
|
+
});
|
|
8468
|
+
}
|
|
8469
|
+
const qty = Math.max(1, Number(body.quantity ?? body.qty ?? 1));
|
|
8470
|
+
const products = await resolveCatalogProducts();
|
|
8471
|
+
const found = products.find((p) => String(p.id) === String(productId) || String(p.slug) === String(productId));
|
|
8472
|
+
const title = String(body.title || found?.title || found?.name || `Product #${productId}`);
|
|
8473
|
+
const price = Number(body.price ?? found?.salePrice ?? found?.price ?? 29.99);
|
|
8474
|
+
const slug = String(found?.slug || productId);
|
|
8475
|
+
const imageUrl = String(found?.imageUrl || found?.featured_image || "/assets/placeholder-product.svg");
|
|
8476
|
+
const variantId = rawVariant !== null && rawVariant !== "" ? rawVariant : null;
|
|
8477
|
+
const existing = session.cart.find((i) => String(i.productId) === String(productId) && String(i.variantId ?? "") === String(variantId ?? ""));
|
|
8478
|
+
if (existing)
|
|
8479
|
+
existing.quantity += qty;
|
|
8480
|
+
else
|
|
8481
|
+
session.cart.push({ id: `${productId}:${variantId ?? "base"}`, productId, variantId, title, slug, price, imageUrl, quantity: qty });
|
|
8482
|
+
return json(200, { success: true, items: session.cart, ...this.computeTotals(session) });
|
|
8483
|
+
}
|
|
8484
|
+
if (method === "PATCH" || method === "PUT") {
|
|
8485
|
+
const productId = body.product_id ?? body.productId;
|
|
8486
|
+
const variantId = body.variant_id ?? body.variantId ?? null;
|
|
8487
|
+
const itemId = body.item_id ?? body.itemId;
|
|
8488
|
+
const item = session.cart.find((i) => itemId && i.id === itemId || String(i.productId) === String(productId) && String(i.variantId ?? "") === String(variantId ?? ""));
|
|
8489
|
+
if (!item)
|
|
8490
|
+
return json(404, { success: false, message: "Cart item not found." });
|
|
8491
|
+
const nextQty = body.delta !== undefined ? item.quantity + Number(body.delta) : Number(body.quantity ?? item.quantity);
|
|
8492
|
+
if (nextQty <= 0)
|
|
8493
|
+
session.cart = session.cart.filter((i) => i !== item);
|
|
8494
|
+
else
|
|
8495
|
+
item.quantity = nextQty;
|
|
8496
|
+
return json(200, { success: true, items: session.cart, ...this.computeTotals(session) });
|
|
8497
|
+
}
|
|
8498
|
+
if (method === "DELETE") {
|
|
8499
|
+
const productId = body.product_id ?? body.productId;
|
|
8500
|
+
const variantId = body.variant_id ?? body.variantId ?? null;
|
|
8501
|
+
const itemId = body.item_id ?? body.itemId;
|
|
8502
|
+
if (body.clear) {
|
|
8503
|
+
session.cart = [];
|
|
8504
|
+
} else {
|
|
8505
|
+
session.cart = session.cart.filter((i) => !(itemId && i.id === itemId || String(i.productId) === String(productId) && String(i.variantId ?? "") === String(variantId ?? "")));
|
|
8506
|
+
}
|
|
8507
|
+
return json(200, { success: true, items: session.cart, ...this.computeTotals(session) });
|
|
8508
|
+
}
|
|
8509
|
+
}
|
|
8510
|
+
if (pathname === "/_api/wishlist" && method === "GET") {
|
|
8511
|
+
return json(200, { success: true, items: session.wishlist, count: session.wishlist.length });
|
|
8512
|
+
}
|
|
8513
|
+
if ((pathname === "/_api/wishlist/toggle" || pathname === "/_api/wishlist") && method === "POST") {
|
|
8514
|
+
const body = await readBody();
|
|
8515
|
+
const productId = body.product_id ?? body.productId;
|
|
8516
|
+
if (!productId)
|
|
8517
|
+
return json(422, { success: false, message: "product_id is required." });
|
|
8518
|
+
const idx = session.wishlist.findIndex((id) => String(id) === String(productId));
|
|
8519
|
+
const added = idx < 0;
|
|
8520
|
+
if (added)
|
|
8521
|
+
session.wishlist.push(productId);
|
|
8522
|
+
else
|
|
8523
|
+
session.wishlist.splice(idx, 1);
|
|
8524
|
+
return json(200, { success: true, added, items: session.wishlist, count: session.wishlist.length });
|
|
8525
|
+
}
|
|
8526
|
+
if (pathname === "/_api/auth/me" && method === "GET") {
|
|
8527
|
+
return json(200, { success: true, authenticated: Boolean(session.customer), customer: session.customer });
|
|
8528
|
+
}
|
|
8529
|
+
if (pathname === "/_api/auth/register" && method === "POST") {
|
|
8530
|
+
const body = await readBody();
|
|
8531
|
+
const email = String(body.email || "").trim().toLowerCase();
|
|
8532
|
+
const password = String(body.password || "");
|
|
8533
|
+
if (!email || !email.includes("@"))
|
|
8534
|
+
return json(422, { success: false, message: "Valid email is required." });
|
|
8535
|
+
if (password.length < 6)
|
|
8536
|
+
return json(422, { success: false, message: "Password must be at least 6 characters." });
|
|
8537
|
+
if (session.registeredUsers.has(email)) {
|
|
8538
|
+
return json(422, { success: false, message: "An account with this email already exists in this dev session." });
|
|
8539
|
+
}
|
|
8540
|
+
const firstName = String(body.firstName || body.name || "Shopper").trim();
|
|
8541
|
+
const lastName = String(body.lastName || "").trim();
|
|
8542
|
+
const customer = {
|
|
8543
|
+
id: `dev-cust-${randomUUID().slice(0, 8)}`,
|
|
8544
|
+
name: [firstName, lastName].filter(Boolean).join(" "),
|
|
8545
|
+
firstName,
|
|
8546
|
+
lastName,
|
|
8547
|
+
email,
|
|
8548
|
+
mobile: body.mobile ? String(body.mobile) : undefined,
|
|
8549
|
+
addresses: []
|
|
8550
|
+
};
|
|
8551
|
+
session.registeredUsers.set(email, { password, customer });
|
|
8552
|
+
session.customer = customer;
|
|
8553
|
+
return json(200, { success: true, authenticated: true, customer, redirect: body.redirect || "/account" });
|
|
8554
|
+
}
|
|
8555
|
+
if (pathname === "/_api/auth/login" && method === "POST") {
|
|
8556
|
+
const body = await readBody();
|
|
8557
|
+
const email = String(body.email || "").trim().toLowerCase();
|
|
8558
|
+
const password = String(body.password || "");
|
|
8559
|
+
const record = session.registeredUsers.get(email);
|
|
8560
|
+
if (!record || record.password !== password) {
|
|
8561
|
+
return json(401, { success: false, message: "Invalid email or password. (Demo account: demo@caartzee.local / password123)" });
|
|
8562
|
+
}
|
|
8563
|
+
session.customer = record.customer;
|
|
8564
|
+
return json(200, { success: true, authenticated: true, customer: record.customer, redirect: body.redirect || "/account" });
|
|
8565
|
+
}
|
|
8566
|
+
if (pathname === "/_api/auth/google" && method === "POST") {
|
|
8567
|
+
const customer = {
|
|
8568
|
+
id: "dev-google-1",
|
|
8569
|
+
name: "Google Sandbox Shopper",
|
|
8570
|
+
firstName: "Google",
|
|
8571
|
+
lastName: "Shopper",
|
|
8572
|
+
email: "google-sandbox@caartzee.local",
|
|
8573
|
+
addresses: []
|
|
8574
|
+
};
|
|
8575
|
+
session.customer = customer;
|
|
8576
|
+
return json(200, { success: true, authenticated: true, provider: "google_sandbox", customer, redirect: "/account" });
|
|
8577
|
+
}
|
|
8578
|
+
if (pathname === "/_api/auth/logout" && method === "POST") {
|
|
8579
|
+
session.customer = null;
|
|
8580
|
+
return json(200, { success: true, authenticated: false, redirect: "/" });
|
|
8581
|
+
}
|
|
8582
|
+
if (pathname === "/_api/checkout" && method === "GET") {
|
|
8583
|
+
return json(200, {
|
|
8584
|
+
success: true,
|
|
8585
|
+
sandboxOnly: true,
|
|
8586
|
+
cart: session.cart,
|
|
8587
|
+
couponCode: session.couponCode,
|
|
8588
|
+
shippingMethod: session.shippingMethod,
|
|
8589
|
+
customer: session.customer,
|
|
8590
|
+
paymentGateways: [{ id: "caartzee_test_sandbox", name: "Caartzee Test Sandbox Payment", sandbox: true }],
|
|
8591
|
+
...this.computeTotals(session)
|
|
8592
|
+
});
|
|
8593
|
+
}
|
|
8594
|
+
if (pathname === "/_api/checkout/shipping" && method === "POST") {
|
|
8595
|
+
const body = await readBody();
|
|
8596
|
+
session.shippingMethod = body.method === "express" ? "express" : "standard";
|
|
8597
|
+
return json(200, { success: true, shippingMethod: session.shippingMethod, ...this.computeTotals(session) });
|
|
8598
|
+
}
|
|
8599
|
+
if (pathname === "/_api/checkout/coupon" && method === "POST") {
|
|
8600
|
+
const body = await readBody();
|
|
8601
|
+
const code = String(body.code || "").trim().toUpperCase();
|
|
8602
|
+
if (!code) {
|
|
8603
|
+
session.couponCode = null;
|
|
8604
|
+
return json(200, { success: true, couponCode: null, ...this.computeTotals(session) });
|
|
8605
|
+
}
|
|
8606
|
+
if (!["TEST10", "FREESHIP"].includes(code)) {
|
|
8607
|
+
return json(422, { success: false, message: "Invalid coupon code. Try TEST10 (10% off) or FREESHIP." });
|
|
8608
|
+
}
|
|
8609
|
+
session.couponCode = code;
|
|
8610
|
+
return json(200, { success: true, couponCode: code, ...this.computeTotals(session) });
|
|
8611
|
+
}
|
|
8612
|
+
if (pathname === "/_api/checkout/address" && method === "POST") {
|
|
8613
|
+
const body = await readBody();
|
|
8614
|
+
const addr = {
|
|
8615
|
+
id: `addr-${randomUUID().slice(0, 6)}`,
|
|
8616
|
+
fullName: String(body.fullName || session.customer?.name || "Sandbox Shopper"),
|
|
8617
|
+
address1: String(body.address1 || "100 Sandbox Way"),
|
|
8618
|
+
city: String(body.city || "Testville"),
|
|
8619
|
+
postalCode: String(body.postalCode || "10001"),
|
|
8620
|
+
country: String(body.country || "US")
|
|
8621
|
+
};
|
|
8622
|
+
if (session.customer)
|
|
8623
|
+
session.customer.addresses.push(addr);
|
|
8624
|
+
return json(200, { success: true, address: addr });
|
|
8625
|
+
}
|
|
8626
|
+
if ((pathname === "/_api/checkout/place-order" || pathname === "/_api/orders") && method === "POST") {
|
|
8627
|
+
const body = await readBody();
|
|
8628
|
+
if (body.gateway && body.gateway !== "caartzee_test_sandbox") {
|
|
8629
|
+
return json(422, { success: false, message: 'Only sandbox payment gateway "caartzee_test_sandbox" is allowed in dev mode.' });
|
|
8630
|
+
}
|
|
8631
|
+
if (session.cart.length === 0) {
|
|
8632
|
+
return json(422, { success: false, message: "Your cart is empty." });
|
|
8633
|
+
}
|
|
8634
|
+
const totals = this.computeTotals(session);
|
|
8635
|
+
const order = {
|
|
8636
|
+
orderNumber: `CZ-DEV-${Date.now().toString().slice(-6)}`,
|
|
8637
|
+
status: "placed",
|
|
8638
|
+
paymentMode: "sandbox",
|
|
8639
|
+
paymentGateway: "caartzee_test_sandbox",
|
|
8640
|
+
customerEmail: String(body.email || session.customer?.email || "guest@caartzee.local"),
|
|
8641
|
+
shippingAddress: {
|
|
8642
|
+
fullName: String(body.fullName || session.customer?.name || "Sandbox Shopper"),
|
|
8643
|
+
address1: String(body.address1 || "100 Sandbox Way"),
|
|
8644
|
+
city: String(body.city || "Testville"),
|
|
8645
|
+
postalCode: String(body.postalCode || "10001"),
|
|
8646
|
+
country: String(body.country || "US")
|
|
8647
|
+
},
|
|
8648
|
+
shippingMethod: session.shippingMethod,
|
|
8649
|
+
subtotal: totals.subtotal,
|
|
8650
|
+
discount: totals.discount,
|
|
8651
|
+
tax: totals.tax,
|
|
8652
|
+
shipping: totals.shipping,
|
|
8653
|
+
total: totals.total,
|
|
8654
|
+
items: [...session.cart],
|
|
8655
|
+
createdAt: new Date().toISOString()
|
|
8656
|
+
};
|
|
8657
|
+
session.orders.unshift(order);
|
|
8658
|
+
session.cart = [];
|
|
8659
|
+
session.couponCode = null;
|
|
8660
|
+
return json(200, { success: true, sandboxOnly: true, order, redirect: `/order-success?order=${encodeURIComponent(order.orderNumber)}` });
|
|
8661
|
+
}
|
|
8662
|
+
if (pathname === "/_api/orders" && method === "GET") {
|
|
8663
|
+
return json(200, { success: true, orders: session.orders });
|
|
8664
|
+
}
|
|
8665
|
+
if (pathname === "/_api/orders/track" && method === "GET") {
|
|
8666
|
+
const orderNumber = searchParams.get("orderNumber") || searchParams.get("order") || "";
|
|
8667
|
+
const order = session.orders.find((o) => o.orderNumber === orderNumber) || null;
|
|
8668
|
+
if (!order)
|
|
8669
|
+
return json(404, { success: false, message: "Sandbox order not found in this dev session." });
|
|
8670
|
+
return json(200, { success: true, order });
|
|
8671
|
+
}
|
|
8672
|
+
return false;
|
|
8673
|
+
}
|
|
8674
|
+
}
|
|
8675
|
+
function buildStorefrontShellRuntimeScript(options) {
|
|
8676
|
+
const badgeText = options.mode === "merchant-sandbox" ? `Caartzee Dev Sandbox · Authorized Store: ${options.storeLabel || "Merchant"} (No Live Charges)` : "Caartzee Local Demo Mode · Full Sandbox Cart, Auth & Checkout Active";
|
|
8677
|
+
return `<script data-caartzee-dev-shell="true">
|
|
8678
|
+
(function(){
|
|
8679
|
+
if (window.__CAARTZEE_DEV_SHELL_INIT__) return;
|
|
8680
|
+
window.__CAARTZEE_DEV_SHELL_INIT__ = true;
|
|
8681
|
+
|
|
8682
|
+
function toast(msg, isErr) {
|
|
8683
|
+
var el = document.getElementById('cz-dev-toast');
|
|
8684
|
+
if (!el) {
|
|
8685
|
+
el = document.createElement('div');
|
|
8686
|
+
el.id = 'cz-dev-toast';
|
|
8687
|
+
el.style.cssText = 'position:fixed;bottom:18px;right:18px;z-index:99999;padding:10px 14px;border-radius:8px;font:500 13px/1.4 system-ui,sans-serif;color:#fff;box-shadow:0 8px 24px rgba(0,0,0,.22);transition:opacity .2s;';
|
|
8688
|
+
document.body.appendChild(el);
|
|
8689
|
+
}
|
|
8690
|
+
el.style.background = isErr ? '#dc2626' : '#0f172a';
|
|
8691
|
+
el.textContent = msg;
|
|
8692
|
+
el.style.opacity = '1';
|
|
8693
|
+
clearTimeout(window.__czToastT);
|
|
8694
|
+
window.__czToastT = setTimeout(function(){ el.style.opacity = '0'; }, 2800);
|
|
8695
|
+
}
|
|
8696
|
+
|
|
8697
|
+
function updateCartBadges(count) {
|
|
8698
|
+
document.querySelectorAll('.js-cart-count, [data-cart-count]').forEach(function(el) {
|
|
8699
|
+
el.textContent = String(count);
|
|
8700
|
+
el.setAttribute('data-cart-count', String(count));
|
|
8701
|
+
});
|
|
8702
|
+
}
|
|
8703
|
+
|
|
8704
|
+
// Sync cart badge on load
|
|
8705
|
+
fetch('/_api/cart').then(function(r){ return r.json(); }).then(function(d){
|
|
8706
|
+
if (d && typeof d.itemCount === 'number') updateCartBadges(d.itemCount);
|
|
8707
|
+
}).catch(function(){});
|
|
8708
|
+
|
|
8709
|
+
// Event-delegated runtime (survives Theme Editor live section re-renders!)
|
|
8710
|
+
document.addEventListener('click', function(e) {
|
|
8711
|
+
var addBtn = e.target.closest && e.target.closest('.js-add-to-cart');
|
|
8712
|
+
if (addBtn) {
|
|
8713
|
+
e.preventDefault();
|
|
8714
|
+
var productId = addBtn.getAttribute('data-product-id');
|
|
8715
|
+
var variantId = addBtn.getAttribute('data-variant-id');
|
|
8716
|
+
var qtyInput = document.querySelector('[data-product-quantity]');
|
|
8717
|
+
var quantity = Number(addBtn.getAttribute('data-qty') || (qtyInput && qtyInput.value) || 1);
|
|
8718
|
+
var payload = { product_id: productId, quantity: quantity };
|
|
8719
|
+
if (variantId) payload.variant_id = variantId;
|
|
8720
|
+
fetch('/_api/cart', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) })
|
|
8721
|
+
.then(function(r){ return r.json().then(function(d){ return { ok: r.ok, d: d }; }); })
|
|
8722
|
+
.then(function(res){
|
|
8723
|
+
if (!res.ok) { toast(res.d.message || 'Add to cart failed', true); return; }
|
|
8724
|
+
updateCartBadges(res.d.itemCount || 0);
|
|
8725
|
+
toast('Added to sandbox cart (' + (res.d.itemCount || 0) + ' items)');
|
|
8726
|
+
});
|
|
8727
|
+
return;
|
|
8728
|
+
}
|
|
8729
|
+
|
|
8730
|
+
var wishBtn = e.target.closest && e.target.closest('.js-wishlist-toggle');
|
|
8731
|
+
if (wishBtn) {
|
|
8732
|
+
e.preventDefault();
|
|
8733
|
+
var pid = wishBtn.getAttribute('data-product-id');
|
|
8734
|
+
fetch('/_api/wishlist/toggle', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ product_id: pid }) })
|
|
8735
|
+
.then(function(r){ return r.json(); })
|
|
8736
|
+
.then(function(d){
|
|
8737
|
+
wishBtn.classList.toggle('is-active', Boolean(d.added));
|
|
8738
|
+
toast(d.added ? 'Saved to sandbox wishlist' : 'Removed from sandbox wishlist');
|
|
8739
|
+
});
|
|
8740
|
+
return;
|
|
8741
|
+
}
|
|
8742
|
+
|
|
8743
|
+
var qtyBtn = e.target.closest && e.target.closest('.js-cart-qty-btn');
|
|
8744
|
+
if (qtyBtn) {
|
|
8745
|
+
e.preventDefault();
|
|
8746
|
+
fetch('/_api/cart', {
|
|
8747
|
+
method: 'PATCH',
|
|
8748
|
+
headers: { 'Content-Type': 'application/json' },
|
|
8749
|
+
body: JSON.stringify({
|
|
8750
|
+
product_id: qtyBtn.getAttribute('data-product-id'),
|
|
8751
|
+
variant_id: qtyBtn.getAttribute('data-variant-id') || null,
|
|
8752
|
+
delta: Number(qtyBtn.getAttribute('data-delta') || 1),
|
|
8753
|
+
}),
|
|
8754
|
+
}).then(function(){ window.location.reload(); });
|
|
8755
|
+
return;
|
|
8756
|
+
}
|
|
8757
|
+
|
|
8758
|
+
var rmBtn = e.target.closest && e.target.closest('.js-remove-cart-item');
|
|
8759
|
+
if (rmBtn) {
|
|
8760
|
+
e.preventDefault();
|
|
8761
|
+
fetch('/_api/cart', {
|
|
8762
|
+
method: 'DELETE',
|
|
8763
|
+
headers: { 'Content-Type': 'application/json' },
|
|
8764
|
+
body: JSON.stringify({
|
|
8765
|
+
product_id: rmBtn.getAttribute('data-product-id'),
|
|
8766
|
+
variant_id: rmBtn.getAttribute('data-variant-id') || null,
|
|
8767
|
+
}),
|
|
8768
|
+
}).then(function(){ window.location.reload(); });
|
|
8769
|
+
return;
|
|
8770
|
+
}
|
|
8771
|
+
|
|
8772
|
+
var variantBtn = e.target.closest && e.target.closest('[data-product-variant]');
|
|
8773
|
+
if (variantBtn) {
|
|
8774
|
+
var vid = variantBtn.getAttribute('data-product-variant');
|
|
8775
|
+
var vPrice = variantBtn.getAttribute('data-variant-price');
|
|
8776
|
+
var vImg = variantBtn.getAttribute('data-variant-image');
|
|
8777
|
+
var vStock = variantBtn.getAttribute('data-variant-stock');
|
|
8778
|
+
var priceEl = document.querySelector('[data-product-price]');
|
|
8779
|
+
if (priceEl && vPrice) priceEl.textContent = vPrice;
|
|
8780
|
+
var imgEl = document.querySelector('[data-product-main-image]');
|
|
8781
|
+
if (imgEl && vImg) imgEl.setAttribute('src', vImg);
|
|
8782
|
+
var stockEl = document.querySelector('[data-product-stock]');
|
|
8783
|
+
if (stockEl && vStock !== null) stockEl.textContent = Number(vStock) > 0 ? 'In Stock' : 'Out of Stock';
|
|
8784
|
+
var pdpAdd = document.querySelector('[data-product-detail] .js-add-to-cart, .js-add-to-cart');
|
|
8785
|
+
if (pdpAdd && vid) pdpAdd.setAttribute('data-variant-id', vid);
|
|
8786
|
+
return;
|
|
8787
|
+
}
|
|
8788
|
+
|
|
8789
|
+
var googleBtn = e.target.closest && e.target.closest('.js-firebase-google-btn');
|
|
8790
|
+
if (googleBtn) {
|
|
8791
|
+
e.preventDefault();
|
|
8792
|
+
fetch('/_api/auth/google', { method: 'POST' }).then(function(r){ return r.json(); }).then(function(d){
|
|
8793
|
+
toast('Signed in with Google Sandbox');
|
|
8794
|
+
window.location.href = d.redirect || '/account';
|
|
8795
|
+
});
|
|
8796
|
+
return;
|
|
8797
|
+
}
|
|
8798
|
+
|
|
8799
|
+
var logoutBtn = e.target.closest && e.target.closest('.js-logout-btn');
|
|
8800
|
+
if (logoutBtn) {
|
|
8801
|
+
e.preventDefault();
|
|
8802
|
+
fetch('/_api/auth/logout', { method: 'POST' }).then(function(){ window.location.href = '/'; });
|
|
8803
|
+
return;
|
|
8804
|
+
}
|
|
8805
|
+
});
|
|
8806
|
+
|
|
8807
|
+
document.addEventListener('submit', function(e) {
|
|
8808
|
+
var authForm = e.target.closest && e.target.closest('form.js-auth-form');
|
|
8809
|
+
if (authForm) {
|
|
8810
|
+
e.preventDefault();
|
|
8811
|
+
var action = authForm.getAttribute('action') || '/_api/auth/login';
|
|
8812
|
+
var fd = new FormData(authForm);
|
|
8813
|
+
var body = {};
|
|
8814
|
+
fd.forEach(function(v, k){ body[k] = v; });
|
|
8815
|
+
fetch(action, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
|
|
8816
|
+
.then(function(r){ return r.json().then(function(d){ return { ok: r.ok, d: d }; }); })
|
|
8817
|
+
.then(function(res){
|
|
8818
|
+
if (!res.ok) { toast(res.d.message || 'Authentication failed', true); return; }
|
|
8819
|
+
toast('Signed in to sandbox session');
|
|
8820
|
+
window.location.href = res.d.redirect || authForm.getAttribute('data-redirect') || '/account';
|
|
8821
|
+
});
|
|
8822
|
+
return;
|
|
8823
|
+
}
|
|
8824
|
+
|
|
8825
|
+
var checkoutForm = e.target.closest && e.target.closest('form.js-checkout-form');
|
|
8826
|
+
if (checkoutForm) {
|
|
8827
|
+
e.preventDefault();
|
|
8828
|
+
var fd2 = new FormData(checkoutForm);
|
|
8829
|
+
var body2 = {};
|
|
8830
|
+
fd2.forEach(function(v, k){ body2[k] = v; });
|
|
8831
|
+
fetch('/_api/checkout/place-order', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body2) })
|
|
8832
|
+
.then(function(r){ return r.json().then(function(d){ return { ok: r.ok, d: d }; }); })
|
|
8833
|
+
.then(function(res){
|
|
8834
|
+
if (!res.ok) { toast(res.d.message || 'Order failed', true); return; }
|
|
8835
|
+
toast('Sandbox order placed: ' + res.d.order.orderNumber);
|
|
8836
|
+
window.location.href = res.d.redirect || '/order-success';
|
|
8837
|
+
});
|
|
8838
|
+
}
|
|
8839
|
+
});
|
|
8840
|
+
|
|
8841
|
+
// Live Theme Editor postMessage bridge (when embedded inside /_editor)
|
|
8842
|
+
window.addEventListener('message', function(event) {
|
|
8843
|
+
if (event.origin !== window.location.origin) return;
|
|
8844
|
+
var msg = event.data;
|
|
8845
|
+
if (!msg || typeof msg !== 'object') return;
|
|
8846
|
+
if (msg.type === 'CAARTZEE_EDITOR_SWAP_SECTION' && msg.sectionId && typeof msg.html === 'string') {
|
|
8847
|
+
var target = document.querySelector('[data-caartzee-section-id="' + msg.sectionId + '"], [data-section-id="' + msg.sectionId + '"]');
|
|
8848
|
+
if (target) {
|
|
8849
|
+
target.outerHTML = msg.html;
|
|
8850
|
+
document.dispatchEvent(new CustomEvent('caartzee:section:load', { detail: { sectionId: msg.sectionId } }));
|
|
8851
|
+
} else {
|
|
8852
|
+
window.location.reload();
|
|
8853
|
+
}
|
|
8854
|
+
} else if (msg.type === 'CAARTZEE_EDITOR_RELOAD') {
|
|
8855
|
+
window.location.reload();
|
|
8856
|
+
}
|
|
8857
|
+
});
|
|
8858
|
+
|
|
8859
|
+
// Visible sandbox indicator bar (hidden when inside iframe preview)
|
|
8860
|
+
if (window.self === window.top) {
|
|
8861
|
+
var bar = document.createElement('div');
|
|
8862
|
+
bar.setAttribute('data-caartzee-dev-banner', 'true');
|
|
8863
|
+
bar.style.cssText = 'position:fixed;bottom:0;left:0;right:0;z-index:99990;background:#0f172a;color:#e2e8f0;font:500 12px/1.4 system-ui,sans-serif;padding:6px 14px;display:flex;align-items:center;justify-content:space-between;border-top:1px solid #334155;';
|
|
8864
|
+
bar.innerHTML = '<span>' + ${JSON.stringify(badgeText)} + '</span><span style="display:flex;gap:12px;"><a href="/cart" style="color:#38bdf8;text-decoration:none;">Cart</a><a href="/checkout" style="color:#38bdf8;text-decoration:none;">Checkout</a><a href="/login" style="color:#38bdf8;text-decoration:none;">Login</a><a href="/account" style="color:#38bdf8;text-decoration:none;">Account</a><a href="/_editor" style="color:#34d399;text-decoration:none;font-weight:600;">Open Theme Editor</a></span>';
|
|
8865
|
+
document.body.appendChild(bar);
|
|
8866
|
+
}
|
|
8867
|
+
})();
|
|
8868
|
+
</script>`;
|
|
8869
|
+
}
|
|
8870
|
+
|
|
8871
|
+
// src/dev-server/local-editor-server.ts
|
|
8872
|
+
class LocalThemeEditorState {
|
|
8873
|
+
state = null;
|
|
8874
|
+
ensureInitialized(theme) {
|
|
8875
|
+
if (this.state)
|
|
8876
|
+
return this.state;
|
|
8877
|
+
const defaultLayout = JSON.parse(JSON.stringify(theme.defaultTemplates?.layout || { regions: { header: [], footer: [] } }));
|
|
8878
|
+
const homePage = theme.defaultTemplates?.pages?.home || theme.defaultTemplates?.pages?.index;
|
|
8879
|
+
const defaultBody = JSON.parse(JSON.stringify(homePage?.regions?.body || []));
|
|
8880
|
+
const defaultGlobalSettings = { ...theme.manifest.defaultGlobalSettings || {} };
|
|
8881
|
+
this.state = {
|
|
8882
|
+
layout: defaultLayout,
|
|
8883
|
+
bodySections: defaultBody,
|
|
8884
|
+
globalSettings: defaultGlobalSettings,
|
|
8885
|
+
publishedLayout: null,
|
|
8886
|
+
publishedBodySections: null,
|
|
8887
|
+
publishedGlobalSettings: null,
|
|
8888
|
+
version: 1
|
|
8889
|
+
};
|
|
8890
|
+
return this.state;
|
|
8891
|
+
}
|
|
8892
|
+
getEffectiveConfig(theme, mode = "draft") {
|
|
8893
|
+
const s = this.ensureInitialized(theme);
|
|
8894
|
+
if (mode === "published" && s.publishedLayout) {
|
|
8895
|
+
return {
|
|
8896
|
+
layout: s.publishedLayout,
|
|
8897
|
+
bodySections: s.publishedBodySections || s.bodySections,
|
|
8898
|
+
globalSettings: s.publishedGlobalSettings || s.globalSettings
|
|
8899
|
+
};
|
|
8900
|
+
}
|
|
8901
|
+
return {
|
|
8902
|
+
layout: s.layout,
|
|
8903
|
+
bodySections: s.bodySections,
|
|
8904
|
+
globalSettings: s.globalSettings
|
|
8905
|
+
};
|
|
8906
|
+
}
|
|
8907
|
+
async handleRequest(req, res, pathname, theme, buildContext) {
|
|
8908
|
+
const state = this.ensureInitialized(theme);
|
|
8909
|
+
const method = (req.method || "GET").toUpperCase();
|
|
8910
|
+
const json = (status, body) => {
|
|
8911
|
+
res.writeHead(status, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" });
|
|
8912
|
+
res.end(JSON.stringify(body));
|
|
8913
|
+
return true;
|
|
8914
|
+
};
|
|
8915
|
+
const readBody = async () => {
|
|
8916
|
+
const chunks = [];
|
|
8917
|
+
for await (const chunk of req)
|
|
8918
|
+
chunks.push(Buffer.from(chunk));
|
|
8919
|
+
const raw = Buffer.concat(chunks).toString("utf8").trim();
|
|
8920
|
+
if (!raw)
|
|
8921
|
+
return {};
|
|
8922
|
+
try {
|
|
8923
|
+
return JSON.parse(raw);
|
|
8924
|
+
} catch {
|
|
8925
|
+
return {};
|
|
8926
|
+
}
|
|
8927
|
+
};
|
|
8928
|
+
if (pathname === "/_editor" && method === "GET") {
|
|
8929
|
+
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
|
|
8930
|
+
res.end(renderLocalEditorHtml(theme.name, theme.slug));
|
|
8931
|
+
return true;
|
|
8932
|
+
}
|
|
8933
|
+
if (pathname === "/_api/editor/state" && method === "GET") {
|
|
8934
|
+
return json(200, {
|
|
8935
|
+
theme: {
|
|
8936
|
+
slug: theme.slug,
|
|
8937
|
+
name: theme.name,
|
|
8938
|
+
version: theme.version,
|
|
8939
|
+
sections: theme.manifest.sections,
|
|
8940
|
+
globalSettingsSchema: theme.manifest.globalSettingsSchema || null
|
|
8941
|
+
},
|
|
8942
|
+
draft: {
|
|
8943
|
+
version: state.version,
|
|
8944
|
+
layout: state.layout,
|
|
8945
|
+
bodySections: state.bodySections,
|
|
8946
|
+
globalSettings: state.globalSettings
|
|
8947
|
+
},
|
|
8948
|
+
hasPublishedPreview: Boolean(state.publishedLayout)
|
|
8949
|
+
});
|
|
8950
|
+
}
|
|
8951
|
+
if (pathname === "/_api/editor/update" && method === "POST") {
|
|
8952
|
+
const body = await readBody();
|
|
8953
|
+
if (body.layout)
|
|
8954
|
+
state.layout = body.layout;
|
|
8955
|
+
if (Array.isArray(body.bodySections))
|
|
8956
|
+
state.bodySections = body.bodySections;
|
|
8957
|
+
if (body.globalSettings && typeof body.globalSettings === "object") {
|
|
8958
|
+
state.globalSettings = { ...state.globalSettings, ...body.globalSettings };
|
|
8959
|
+
}
|
|
8960
|
+
let renderedSectionHtml = null;
|
|
8961
|
+
if (body.sectionId && body.region) {
|
|
8962
|
+
const list = body.region === "header" ? state.layout.regions.header || [] : body.region === "footer" ? state.layout.regions.footer || [] : state.bodySections;
|
|
8963
|
+
const sec = list.find((s) => s.id === body.sectionId);
|
|
8964
|
+
if (sec) {
|
|
8965
|
+
if (body.settings)
|
|
8966
|
+
sec.settings = { ...sec.settings || {}, ...body.settings };
|
|
8967
|
+
if (Array.isArray(body.blocks))
|
|
8968
|
+
sec.blocks = body.blocks;
|
|
8969
|
+
const renderer = theme.sections[sec.type];
|
|
8970
|
+
if (renderer) {
|
|
8971
|
+
const pageContext = await buildContext("home");
|
|
8972
|
+
pageContext.globalSettings = { ...pageContext.globalSettings, ...state.globalSettings };
|
|
8973
|
+
renderedSectionHtml = renderer({
|
|
8974
|
+
section: sec,
|
|
8975
|
+
themeSlug: theme.slug,
|
|
8976
|
+
globalSettings: pageContext.globalSettings,
|
|
8977
|
+
pageContext,
|
|
8978
|
+
catalog: {
|
|
8979
|
+
products: pageContext.products || pageContext.featuredProducts || [],
|
|
8980
|
+
featuredProducts: pageContext.featuredProducts || [],
|
|
8981
|
+
categories: pageContext.categories || []
|
|
8982
|
+
}
|
|
8983
|
+
});
|
|
8984
|
+
}
|
|
8985
|
+
}
|
|
8986
|
+
}
|
|
8987
|
+
state.version += 1;
|
|
8988
|
+
return json(200, {
|
|
8989
|
+
success: true,
|
|
8990
|
+
version: state.version,
|
|
8991
|
+
renderedSectionHtml,
|
|
8992
|
+
draft: {
|
|
8993
|
+
layout: state.layout,
|
|
8994
|
+
bodySections: state.bodySections,
|
|
8995
|
+
globalSettings: state.globalSettings
|
|
8996
|
+
}
|
|
8997
|
+
});
|
|
8998
|
+
}
|
|
8999
|
+
if (pathname === "/_api/editor/publish" && method === "POST") {
|
|
9000
|
+
state.publishedLayout = JSON.parse(JSON.stringify(state.layout));
|
|
9001
|
+
state.publishedBodySections = JSON.parse(JSON.stringify(state.bodySections));
|
|
9002
|
+
state.publishedGlobalSettings = JSON.parse(JSON.stringify(state.globalSettings));
|
|
9003
|
+
return json(200, { success: true, version: state.version, publishedPreviewUrl: "/?preview_mode=published" });
|
|
9004
|
+
}
|
|
9005
|
+
return false;
|
|
9006
|
+
}
|
|
9007
|
+
}
|
|
9008
|
+
function renderLocalEditorHtml(themeName, themeSlug) {
|
|
9009
|
+
return `<!doctype html>
|
|
9010
|
+
<html lang="en">
|
|
9011
|
+
<head>
|
|
9012
|
+
<meta charset="utf-8" />
|
|
9013
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
9014
|
+
<title>Caartzee Local Theme Editor — ${themeName}</title>
|
|
9015
|
+
<style>
|
|
9016
|
+
* { box-sizing: border-box; }
|
|
9017
|
+
body { margin: 0; font-family: system-ui, -apple-system, sans-serif; background: #0f172a; color: #f8fafc; height: 100vh; display: flex; flex-direction: column; }
|
|
9018
|
+
header { height: 48px; padding: 0 16px; border-bottom: 1px solid #1e293b; display: flex; align-items: center; justify-content: space-between; background: #020617; }
|
|
9019
|
+
.toolbar { display: flex; gap: 8px; align-items: center; }
|
|
9020
|
+
button { background: #1e293b; color: #f8fafc; border: 1px solid #334155; border-radius: 6px; padding: 6px 12px; font-size: 12px; cursor: pointer; }
|
|
9021
|
+
button.primary { background: #4f46e5; border-color: #6366f1; }
|
|
9022
|
+
main { flex: 1; display: grid; grid-template-columns: 340px 1fr; min-height: 0; }
|
|
9023
|
+
aside { border-right: 1px solid #1e293b; overflow-y: auto; padding: 14px; background: #0b1120; }
|
|
9024
|
+
.preview-wrap { background: #1e293b; display: flex; justify-content: center; align-items: stretch; padding: 12px; overflow: hidden; }
|
|
9025
|
+
iframe { border: 1px solid #334155; border-radius: 8px; background: #fff; width: 100%; height: 100%; transition: width .2s; }
|
|
9026
|
+
iframe.mobile { width: 390px; }
|
|
9027
|
+
.group-title { font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: .06em; color: #94a3b8; margin: 14px 0 6px; }
|
|
9028
|
+
.sec-card { border: 1px solid #1e293b; border-radius: 8px; padding: 10px; margin-bottom: 8px; background: #111827; }
|
|
9029
|
+
.sec-head { display: flex; justify-content: space-between; align-items: center; font-size: 13px; font-weight: 600; margin-bottom: 8px; }
|
|
9030
|
+
.field { margin-bottom: 8px; }
|
|
9031
|
+
.field label { display: block; font-size: 11px; color: #cbd5e1; margin-bottom: 3px; }
|
|
9032
|
+
.field input, .field textarea, .field select { width: 100%; background: #0f172a; border: 1px solid #334155; color: #f8fafc; border-radius: 5px; padding: 6px 8px; font-size: 12px; }
|
|
9033
|
+
</style>
|
|
9034
|
+
</head>
|
|
9035
|
+
<body>
|
|
9036
|
+
<header>
|
|
9037
|
+
<div><strong>Caartzee Dev Theme Editor</strong> <span style="color:#94a3b8;font-size:12px;">(${themeSlug})</span></div>
|
|
9038
|
+
<div class="toolbar">
|
|
9039
|
+
<button id="btn-desktop">Desktop</button>
|
|
9040
|
+
<button id="btn-mobile">Mobile</button>
|
|
9041
|
+
<button id="btn-publish" class="primary">Test Publish Preview</button>
|
|
9042
|
+
<a href="/" style="color:#38bdf8;font-size:12px;text-decoration:none;margin-left:6px;">Exit Editor</a>
|
|
9043
|
+
</div>
|
|
9044
|
+
</header>
|
|
9045
|
+
<main>
|
|
9046
|
+
<aside id="sidebar">Loading theme schemas...</aside>
|
|
9047
|
+
<div class="preview-wrap"><iframe id="preview-frame" src="/?editor_preview=1"></iframe></div>
|
|
9048
|
+
</main>
|
|
9049
|
+
<script>
|
|
9050
|
+
let editorState = null;
|
|
9051
|
+
const frame = document.getElementById('preview-frame');
|
|
9052
|
+
document.getElementById('btn-desktop').onclick = () => frame.classList.remove('mobile');
|
|
9053
|
+
document.getElementById('btn-mobile').onclick = () => frame.classList.add('mobile');
|
|
9054
|
+
document.getElementById('btn-publish').onclick = async () => {
|
|
9055
|
+
const res = await fetch('/_api/editor/publish', { method: 'POST' }).then(r => r.json());
|
|
9056
|
+
if (res.success) alert('Published to isolated local preview: ' + res.publishedPreviewUrl);
|
|
9057
|
+
};
|
|
9058
|
+
|
|
9059
|
+
async function load() {
|
|
9060
|
+
editorState = await fetch('/_api/editor/state').then(r => r.json());
|
|
9061
|
+
renderSidebar();
|
|
9062
|
+
}
|
|
9063
|
+
|
|
9064
|
+
async function patchSection(region, sectionId, patch) {
|
|
9065
|
+
const res = await fetch('/_api/editor/update', {
|
|
9066
|
+
method: 'POST',
|
|
9067
|
+
headers: { 'Content-Type': 'application/json' },
|
|
9068
|
+
body: JSON.stringify({ region, sectionId, settings: patch }),
|
|
9069
|
+
}).then(r => r.json());
|
|
9070
|
+
if (res.renderedSectionHtml) {
|
|
9071
|
+
frame.contentWindow.postMessage({ type: 'CAARTZEE_EDITOR_SWAP_SECTION', sectionId, html: res.renderedSectionHtml }, window.location.origin);
|
|
9072
|
+
} else {
|
|
9073
|
+
frame.contentWindow.postMessage({ type: 'CAARTZEE_EDITOR_RELOAD' }, window.location.origin);
|
|
9074
|
+
}
|
|
9075
|
+
}
|
|
9076
|
+
|
|
9077
|
+
function renderRegion(title, region, list) {
|
|
9078
|
+
const schemas = Object.fromEntries((editorState.theme.sections || []).map(s => [s.type, s]));
|
|
9079
|
+
let html = '<div class="group-title">' + title + '</div>';
|
|
9080
|
+
for (const sec of list || []) {
|
|
9081
|
+
const schema = schemas[sec.type];
|
|
9082
|
+
html += '<div class="sec-card"><div class="sec-head"><span>' + (schema?.label || sec.type) + '</span><span style="font-size:10px;color:#64748b;">' + sec.id + '</span></div>';
|
|
9083
|
+
for (const f of (schema?.settings || []).slice(0, 12)) {
|
|
9084
|
+
if (f.type === 'header' || f.type === 'paragraph') continue;
|
|
9085
|
+
const val = (sec.settings && sec.settings[f.id] !== undefined) ? sec.settings[f.id] : (f.default ?? '');
|
|
9086
|
+
const type = f.type === 'color' ? 'color' : f.type === 'checkbox' || f.type === 'boolean' ? 'checkbox' : 'text';
|
|
9087
|
+
html += '<div class="field"><label>' + f.label + '</label>';
|
|
9088
|
+
if (type === 'checkbox') {
|
|
9089
|
+
html += '<input type="checkbox" ' + (val ? 'checked' : '') + ' data-region="' + region + '" data-sec="' + sec.id + '" data-key="' + f.id + '" />';
|
|
9090
|
+
} else {
|
|
9091
|
+
html += '<input type="' + type + '" value="' + String(val).replace(/"/g, '"') + '" data-region="' + region + '" data-sec="' + sec.id + '" data-key="' + f.id + '" />';
|
|
9092
|
+
}
|
|
9093
|
+
html += '</div>';
|
|
9094
|
+
}
|
|
9095
|
+
html += '</div>';
|
|
9096
|
+
}
|
|
9097
|
+
return html;
|
|
9098
|
+
}
|
|
9099
|
+
|
|
9100
|
+
function renderSidebar() {
|
|
9101
|
+
const sidebar = document.getElementById('sidebar');
|
|
9102
|
+
sidebar.innerHTML =
|
|
9103
|
+
renderRegion('Header Region', 'header', editorState.draft.layout.regions.header) +
|
|
9104
|
+
renderRegion('Body Sections', 'body', editorState.draft.bodySections) +
|
|
9105
|
+
renderRegion('Footer Region', 'footer', editorState.draft.layout.regions.footer);
|
|
9106
|
+
|
|
9107
|
+
sidebar.querySelectorAll('input[data-sec]').forEach(input => {
|
|
9108
|
+
input.addEventListener('change', () => {
|
|
9109
|
+
const val = input.type === 'checkbox' ? input.checked : input.value;
|
|
9110
|
+
patchSection(input.dataset.region, input.dataset.sec, { [input.dataset.key]: val });
|
|
9111
|
+
});
|
|
9112
|
+
});
|
|
9113
|
+
}
|
|
9114
|
+
|
|
9115
|
+
load();
|
|
9116
|
+
</script>
|
|
9117
|
+
</body>
|
|
9118
|
+
</html>`;
|
|
9119
|
+
}
|
|
9120
|
+
|
|
7623
9121
|
// src/dev-server/dev-server.ts
|
|
9122
|
+
function injectRuntimeScript(html, script) {
|
|
9123
|
+
if (/<\/body>/i.test(html)) {
|
|
9124
|
+
return html.replace(/<\/body>/i, `${script}</body>`);
|
|
9125
|
+
}
|
|
9126
|
+
return `${html}
|
|
9127
|
+
${script}`;
|
|
9128
|
+
}
|
|
7624
9129
|
function createThemeDevServer(options = {}) {
|
|
7625
9130
|
const port = options.port ?? 3333;
|
|
7626
9131
|
const host = options.host ?? "127.0.0.1";
|
|
7627
9132
|
const themeDir = options.themeDir ?? process.cwd();
|
|
7628
9133
|
if (options.loadCatalog && host !== "127.0.0.1")
|
|
7629
9134
|
throw new Error("Store catalog previews must bind to 127.0.0.1.");
|
|
9135
|
+
const commerceStore = new LocalCommerceStore;
|
|
9136
|
+
const editorState = new LocalThemeEditorState;
|
|
7630
9137
|
let manifest = null;
|
|
7631
9138
|
const manifestPath = join7(themeDir, "manifest.json");
|
|
7632
9139
|
if (existsSync8(manifestPath)) {
|
|
@@ -7638,9 +9145,10 @@ function createThemeDevServer(options = {}) {
|
|
|
7638
9145
|
try {
|
|
7639
9146
|
const parsedUrl = new URL(req.url ?? "/", `http://${host}:${port}`);
|
|
7640
9147
|
const pathname = parsedUrl.pathname;
|
|
9148
|
+
const isEditorPreview = parsedUrl.searchParams.get("editor_preview") === "1" || pathname === "/_editor";
|
|
7641
9149
|
if (options.loadCatalog) {
|
|
7642
9150
|
res.setHeader("Cache-Control", "no-store");
|
|
7643
|
-
res.setHeader("Content-Security-Policy", "frame-ancestors 'none'");
|
|
9151
|
+
res.setHeader("Content-Security-Policy", isEditorPreview ? "frame-ancestors 'self'" : "frame-ancestors 'none'");
|
|
7644
9152
|
res.setHeader("Cross-Origin-Resource-Policy", "same-origin");
|
|
7645
9153
|
if (req.headers.host !== host + ":" + port) {
|
|
7646
9154
|
res.writeHead(403);
|
|
@@ -7651,28 +9159,66 @@ function createThemeDevServer(options = {}) {
|
|
|
7651
9159
|
if (pathname.startsWith("/assets/")) {
|
|
7652
9160
|
const root = resolve6(themeDir, "assets");
|
|
7653
9161
|
const file = resolve6(themeDir, "." + decodeURIComponent(pathname));
|
|
7654
|
-
if (!file.startsWith(root + sep) || !existsSync8(file) || ![".css", ".svg", ".png", ".jpg", ".jpeg", ".webp", ".gif", ".woff2"].includes(extname(file).toLowerCase())) {
|
|
9162
|
+
if (!file.startsWith(root + sep) || !existsSync8(file) || ![".css", ".js", ".svg", ".png", ".jpg", ".jpeg", ".webp", ".gif", ".woff2"].includes(extname(file).toLowerCase())) {
|
|
7655
9163
|
res.writeHead(404);
|
|
7656
9164
|
res.end("Asset not found");
|
|
7657
9165
|
return;
|
|
7658
9166
|
}
|
|
7659
|
-
const mime = {
|
|
9167
|
+
const mime = {
|
|
9168
|
+
".css": "text/css",
|
|
9169
|
+
".js": "application/javascript; charset=utf-8",
|
|
9170
|
+
".svg": "image/svg+xml",
|
|
9171
|
+
".png": "image/png",
|
|
9172
|
+
".jpg": "image/jpeg",
|
|
9173
|
+
".jpeg": "image/jpeg",
|
|
9174
|
+
".webp": "image/webp",
|
|
9175
|
+
".gif": "image/gif",
|
|
9176
|
+
".woff2": "font/woff2"
|
|
9177
|
+
};
|
|
7660
9178
|
res.writeHead(200, { "Content-Type": mime[extname(file).toLowerCase()], "Cache-Control": "no-store" });
|
|
7661
9179
|
res.end(readFileSync7(file));
|
|
7662
9180
|
return;
|
|
7663
9181
|
}
|
|
7664
9182
|
if (pathname === "/_api/status") {
|
|
7665
9183
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
7666
|
-
res.end(JSON.stringify({
|
|
9184
|
+
res.end(JSON.stringify({
|
|
9185
|
+
status: "ok",
|
|
9186
|
+
mode: options.loadCatalog ? "merchant-sandbox" : "demo",
|
|
9187
|
+
theme: manifest?.name ?? "Unknown Theme",
|
|
9188
|
+
version: manifest?.version ?? "1.0.0",
|
|
9189
|
+
editorUrl: `http://${host}:${port}/_editor`
|
|
9190
|
+
}));
|
|
7667
9191
|
return;
|
|
7668
9192
|
}
|
|
7669
9193
|
if (pathname === "/_api/context") {
|
|
7670
9194
|
const page = parsedUrl.searchParams.get("page") || "home";
|
|
7671
|
-
const
|
|
9195
|
+
const session = commerceStore.getOrCreateSession(req, res);
|
|
9196
|
+
const baseContext = options.loadCatalog ? await createCatalogDevContext(options.loadCatalog, page, "/", parsedUrl.searchParams) : createMockPageContext(page);
|
|
9197
|
+
const context = commerceStore.applySessionToContext(session, baseContext);
|
|
7672
9198
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
7673
9199
|
res.end(JSON.stringify(context, null, 2));
|
|
7674
9200
|
return;
|
|
7675
9201
|
}
|
|
9202
|
+
if (pathname === "/_editor" || pathname.startsWith("/_api/editor/")) {
|
|
9203
|
+
const theme = options.loadTheme ? await options.loadTheme() : await loadLocalTheme(themeDir);
|
|
9204
|
+
const session = commerceStore.getOrCreateSession(req, res);
|
|
9205
|
+
const handled = await editorState.handleRequest(req, res, pathname, theme, async (pt) => {
|
|
9206
|
+
const base = options.loadCatalog ? await createCatalogDevContext(options.loadCatalog, pt, "/", parsedUrl.searchParams) : createMockPageContext(pt);
|
|
9207
|
+
return commerceStore.applySessionToContext(session, base);
|
|
9208
|
+
});
|
|
9209
|
+
if (handled)
|
|
9210
|
+
return;
|
|
9211
|
+
}
|
|
9212
|
+
const handledCommerce = await commerceStore.handleApiRequest(req, res, pathname, parsedUrl.searchParams, async () => {
|
|
9213
|
+
if (options.loadCatalog) {
|
|
9214
|
+
const cat = await options.loadCatalog({});
|
|
9215
|
+
return cat.products || [];
|
|
9216
|
+
}
|
|
9217
|
+
const mock = createMockPageContext("product-list");
|
|
9218
|
+
return mock.products || mock.featuredProducts || [];
|
|
9219
|
+
});
|
|
9220
|
+
if (handledCommerce)
|
|
9221
|
+
return;
|
|
7676
9222
|
if (pathname.startsWith("/_assets/")) {
|
|
7677
9223
|
const parts = pathname.replace(/^\/_assets\/[^/]+\//, "");
|
|
7678
9224
|
const safeAsset = parts.split("/").filter((s) => s && s !== "." && s !== "..").join("/");
|
|
@@ -7700,7 +9246,7 @@ function createThemeDevServer(options = {}) {
|
|
|
7700
9246
|
pageType = "checkout";
|
|
7701
9247
|
} else if (pathname === "/login") {
|
|
7702
9248
|
pageType = "login";
|
|
7703
|
-
} else if (pathname === "/signup") {
|
|
9249
|
+
} else if (pathname === "/signup" || pathname === "/register") {
|
|
7704
9250
|
pageType = "signup";
|
|
7705
9251
|
} else if (pathname === "/account") {
|
|
7706
9252
|
pageType = "account";
|
|
@@ -7737,10 +9283,28 @@ function createThemeDevServer(options = {}) {
|
|
|
7737
9283
|
pageType = "order-detail";
|
|
7738
9284
|
else if (pathname.startsWith("/account/"))
|
|
7739
9285
|
pageType = "account";
|
|
7740
|
-
const
|
|
9286
|
+
const session = commerceStore.getOrCreateSession(req, res);
|
|
9287
|
+
const baseContext = options.loadCatalog ? await createCatalogDevContext(options.loadCatalog, pageType, pathname, parsedUrl.searchParams) : createMockPageContext(pageType, pageType === "account" ? { activeTab: pathname.split("/")[2] || "overview" } : pageType === "search" && parsedUrl.searchParams.has("q") ? { query: parsedUrl.searchParams.get("q") } : {});
|
|
7741
9288
|
const theme = options.loadTheme ? await options.loadTheme() : await loadLocalTheme(themeDir);
|
|
7742
|
-
const
|
|
7743
|
-
|
|
9289
|
+
const previewMode = parsedUrl.searchParams.get("preview_mode") === "published" ? "published" : "draft";
|
|
9290
|
+
const editorConfig = editorState.getEffectiveConfig(theme, previewMode);
|
|
9291
|
+
const enrichedContext = commerceStore.applySessionToContext(session, {
|
|
9292
|
+
...baseContext,
|
|
9293
|
+
isPreview: true,
|
|
9294
|
+
globalSettings: { ...baseContext.globalSettings, ...editorConfig.globalSettings },
|
|
9295
|
+
layoutDocument: editorConfig.layout,
|
|
9296
|
+
...pageType === "home" ? { sections: editorConfig.bodySections } : {}
|
|
9297
|
+
});
|
|
9298
|
+
const rawHtml = renderThemePreview(theme, enrichedContext, Boolean(options.loadCatalog), editorConfig);
|
|
9299
|
+
const runtimeScript = buildStorefrontShellRuntimeScript({
|
|
9300
|
+
mode: options.loadCatalog ? "merchant-sandbox" : "demo",
|
|
9301
|
+
storeLabel: options.storeLabel,
|
|
9302
|
+
editorEnabled: Boolean(options.editor)
|
|
9303
|
+
});
|
|
9304
|
+
const html = injectRuntimeScript(rawHtml, runtimeScript);
|
|
9305
|
+
res.writeHead(enrichedContext.pageType === "not-found" && pageType !== "not-found" ? 404 : 200, {
|
|
9306
|
+
"Content-Type": "text/html; charset=utf-8"
|
|
9307
|
+
});
|
|
7744
9308
|
res.end(html);
|
|
7745
9309
|
} catch (error) {
|
|
7746
9310
|
res.writeHead(500, { "Content-Type": "text/plain; charset=utf-8" });
|
|
@@ -7751,6 +9315,7 @@ function createThemeDevServer(options = {}) {
|
|
|
7751
9315
|
server,
|
|
7752
9316
|
port,
|
|
7753
9317
|
url: `http://${host}:${port}`,
|
|
9318
|
+
editorUrl: `http://${host}:${port}/_editor`,
|
|
7754
9319
|
stop: () => new Promise((resolve) => {
|
|
7755
9320
|
server.close(() => resolve());
|
|
7756
9321
|
})
|
|
@@ -7783,8 +9348,9 @@ async function loadLocalTheme(themeDir) {
|
|
|
7783
9348
|
const source = await build.outputs[0].text();
|
|
7784
9349
|
const module = await import("data:text/javascript;base64," + Buffer.from(source).toString("base64"));
|
|
7785
9350
|
const theme = module.default || module.theme;
|
|
7786
|
-
if (!theme?.sections || !theme?.defaultTemplates || !theme?.manifest)
|
|
9351
|
+
if (!theme?.sections || !theme?.defaultTemplates || !theme?.manifest) {
|
|
7787
9352
|
throw new Error("src/index.ts must export a StorefrontThemeDefinition as default or theme.");
|
|
9353
|
+
}
|
|
7788
9354
|
return theme;
|
|
7789
9355
|
}
|
|
7790
9356
|
// src/validation/rich-text.ts
|
|
@@ -9168,8 +10734,313 @@ function collectThemeSources(root) {
|
|
|
9168
10734
|
}
|
|
9169
10735
|
|
|
9170
10736
|
// src/cli/caartzee-cli.ts
|
|
9171
|
-
import { existsSync as
|
|
9172
|
-
import { resolve as
|
|
10737
|
+
import { existsSync as existsSync12, mkdirSync as mkdirSync5, readFileSync as readFileSync12, writeFileSync as writeFileSync5 } from "node:fs";
|
|
10738
|
+
import { resolve as resolve10, join as join12 } from "node:path";
|
|
10739
|
+
|
|
10740
|
+
// src/cli/mcp/editor-tools.ts
|
|
10741
|
+
import { existsSync as existsSync9, readFileSync as readFileSync9 } from "node:fs";
|
|
10742
|
+
import { join as join9, resolve as resolve7 } from "node:path";
|
|
10743
|
+
import { z as z6 } from "zod";
|
|
10744
|
+
function validateThemeEditorDirectory(themeDir) {
|
|
10745
|
+
const dir = resolve7(themeDir);
|
|
10746
|
+
const checks = [];
|
|
10747
|
+
if (!existsSync9(dir)) {
|
|
10748
|
+
return {
|
|
10749
|
+
valid: false,
|
|
10750
|
+
themeDir: dir,
|
|
10751
|
+
checks: [{ name: "directory_exists", status: "failed", message: `Theme directory not found: ${dir}` }],
|
|
10752
|
+
summary: { passed: 0, failed: 1, warnings: 0 }
|
|
10753
|
+
};
|
|
10754
|
+
}
|
|
10755
|
+
const { bundle, diagnostics } = loadCandyThemeFromDirectory(dir);
|
|
10756
|
+
const schemaErrors = diagnostics.filter((d) => d.severity === "error");
|
|
10757
|
+
const schemaWarnings = diagnostics.filter((d) => d.severity === "warning");
|
|
10758
|
+
if (schemaErrors.length === 0) {
|
|
10759
|
+
checks.push({
|
|
10760
|
+
name: "section_schemas_compile",
|
|
10761
|
+
status: "passed",
|
|
10762
|
+
message: `All ${Object.keys(bundle.sectionSchemas).length} section schema(s) compiled cleanly.`
|
|
10763
|
+
});
|
|
10764
|
+
} else {
|
|
10765
|
+
for (const err of schemaErrors) {
|
|
10766
|
+
checks.push({
|
|
10767
|
+
name: "section_schema_error",
|
|
10768
|
+
status: "failed",
|
|
10769
|
+
message: `${err.code}: ${err.message}`,
|
|
10770
|
+
file: err.file
|
|
10771
|
+
});
|
|
10772
|
+
}
|
|
10773
|
+
}
|
|
10774
|
+
for (const warn of schemaWarnings) {
|
|
10775
|
+
checks.push({
|
|
10776
|
+
name: "section_schema_warning",
|
|
10777
|
+
status: "warning",
|
|
10778
|
+
message: `${warn.code}: ${warn.message}`,
|
|
10779
|
+
file: warn.file
|
|
10780
|
+
});
|
|
10781
|
+
}
|
|
10782
|
+
for (const [sectionType, schema] of Object.entries(bundle.sectionSchemas)) {
|
|
10783
|
+
const relPath = `sections/${sectionType}.candy`;
|
|
10784
|
+
const source = bundle.files[relPath] || "";
|
|
10785
|
+
if (schema.blocks && schema.blocks.length > 0) {
|
|
10786
|
+
if (source.includes("block.candy_attributes")) {
|
|
10787
|
+
checks.push({
|
|
10788
|
+
name: `block_attributes:${sectionType}`,
|
|
10789
|
+
status: "passed",
|
|
10790
|
+
message: `Section "${sectionType}" outputs {{ block.candy_attributes }} for Theme Editor block selection.`,
|
|
10791
|
+
file: relPath
|
|
10792
|
+
});
|
|
10793
|
+
} else {
|
|
10794
|
+
checks.push({
|
|
10795
|
+
name: `block_attributes:${sectionType}`,
|
|
10796
|
+
status: "failed",
|
|
10797
|
+
message: `Section "${sectionType}" defines ${schema.blocks.length} block type(s) but is missing {{ block.candy_attributes }}.`,
|
|
10798
|
+
file: relPath
|
|
10799
|
+
});
|
|
10800
|
+
}
|
|
10801
|
+
}
|
|
10802
|
+
}
|
|
10803
|
+
const settingsSchemaPath = join9(dir, "schemas", "settings_schema.json");
|
|
10804
|
+
if (existsSync9(settingsSchemaPath)) {
|
|
10805
|
+
try {
|
|
10806
|
+
const parsed = JSON.parse(readFileSync9(settingsSchemaPath, "utf8"));
|
|
10807
|
+
if (Array.isArray(parsed) || parsed && typeof parsed === "object") {
|
|
10808
|
+
checks.push({ name: "global_settings_schema", status: "passed", message: "schemas/settings_schema.json is valid JSON.", file: "schemas/settings_schema.json" });
|
|
10809
|
+
} else {
|
|
10810
|
+
checks.push({ name: "global_settings_schema", status: "failed", message: "schemas/settings_schema.json must be a JSON object or array.", file: "schemas/settings_schema.json" });
|
|
10811
|
+
}
|
|
10812
|
+
} catch (e) {
|
|
10813
|
+
checks.push({ name: "global_settings_schema", status: "failed", message: `Invalid JSON in schemas/settings_schema.json: ${e.message}`, file: "schemas/settings_schema.json" });
|
|
10814
|
+
}
|
|
10815
|
+
} else {
|
|
10816
|
+
checks.push({ name: "global_settings_schema", status: "warning", message: "schemas/settings_schema.json not found; global theme settings will be empty." });
|
|
10817
|
+
}
|
|
10818
|
+
const themeJs = bundle.assets["assets/theme.js"] || (existsSync9(join9(dir, "assets", "theme.js")) ? readFileSync9(join9(dir, "assets", "theme.js"), "utf8") : "");
|
|
10819
|
+
if (themeJs) {
|
|
10820
|
+
if (themeJs.includes("document.addEventListener") || themeJs.includes("caartzee:section:")) {
|
|
10821
|
+
checks.push({ name: "live_rerender_event_delegation", status: "passed", message: "assets/theme.js uses event delegation / section lifecycle events for Theme Editor compatibility.", file: "assets/theme.js" });
|
|
10822
|
+
} else {
|
|
10823
|
+
checks.push({ name: "live_rerender_event_delegation", status: "warning", message: "assets/theme.js should use document.addEventListener delegation or caartzee:section:load so interactions survive live section re-rendering.", file: "assets/theme.js" });
|
|
10824
|
+
}
|
|
10825
|
+
}
|
|
10826
|
+
const passed = checks.filter((c) => c.status === "passed").length;
|
|
10827
|
+
const failed = checks.filter((c) => c.status === "failed").length;
|
|
10828
|
+
const warnings = checks.filter((c) => c.status === "warning").length;
|
|
10829
|
+
return {
|
|
10830
|
+
valid: failed === 0,
|
|
10831
|
+
themeDir: dir,
|
|
10832
|
+
slug: bundle.slug,
|
|
10833
|
+
version: bundle.version,
|
|
10834
|
+
sectionCount: Object.keys(bundle.sectionSchemas).length,
|
|
10835
|
+
sections: Object.keys(bundle.sectionSchemas),
|
|
10836
|
+
checks,
|
|
10837
|
+
summary: { passed, failed, warnings }
|
|
10838
|
+
};
|
|
10839
|
+
}
|
|
10840
|
+
|
|
10841
|
+
// src/cli/mcp/testing-tools.ts
|
|
10842
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
10843
|
+
import { existsSync as existsSync10, readFileSync as readFileSync10 } from "node:fs";
|
|
10844
|
+
import { join as join10, resolve as resolve8 } from "node:path";
|
|
10845
|
+
import { z as z7 } from "zod";
|
|
10846
|
+
async function runThemeReadinessAudit(themeDir) {
|
|
10847
|
+
const dir = resolve8(themeDir);
|
|
10848
|
+
const checks = [];
|
|
10849
|
+
const readRel = (rel) => {
|
|
10850
|
+
const full = join10(dir, rel);
|
|
10851
|
+
return existsSync10(full) ? readFileSync10(full, "utf8") : null;
|
|
10852
|
+
};
|
|
10853
|
+
let slug = "unknown";
|
|
10854
|
+
let version = "0.0.0";
|
|
10855
|
+
let packageHash = createHash2("sha256").update(dir).digest("hex");
|
|
10856
|
+
try {
|
|
10857
|
+
const files = collectThemeSources(dir);
|
|
10858
|
+
const canonical = [...files].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
|
|
10859
|
+
packageHash = createHash2("sha256").update(JSON.stringify(canonical)).digest("hex");
|
|
10860
|
+
} catch {}
|
|
10861
|
+
const pkg = await ThemePackageValidator.validatePackage(dir);
|
|
10862
|
+
if (pkg.manifest) {
|
|
10863
|
+
slug = pkg.manifest.slug;
|
|
10864
|
+
version = pkg.manifest.version;
|
|
10865
|
+
}
|
|
10866
|
+
if (pkg.valid) {
|
|
10867
|
+
checks.push({ id: "security.package_validation", category: "security", status: "passed", message: "Manifest and security source-pattern audit passed." });
|
|
10868
|
+
} else {
|
|
10869
|
+
for (const err of pkg.errors) {
|
|
10870
|
+
checks.push({ id: "security.package_validation", category: "security", status: "failed", message: err });
|
|
10871
|
+
}
|
|
10872
|
+
}
|
|
10873
|
+
const editor = validateThemeEditorDirectory(dir);
|
|
10874
|
+
for (const c of editor.checks) {
|
|
10875
|
+
checks.push({
|
|
10876
|
+
id: `editor.${c.name}`,
|
|
10877
|
+
category: "editor",
|
|
10878
|
+
status: c.status,
|
|
10879
|
+
message: c.message,
|
|
10880
|
+
file: c.file
|
|
10881
|
+
});
|
|
10882
|
+
}
|
|
10883
|
+
const header = readRel("sections/header.candy") || "";
|
|
10884
|
+
const productTpl = readRel("templates/product.candy") || "";
|
|
10885
|
+
const collectionTpl = readRel("templates/collection.candy") || "";
|
|
10886
|
+
const cartTpl = readRel("templates/cart.candy") || "";
|
|
10887
|
+
const searchTpl = readRel("templates/search.candy") || "";
|
|
10888
|
+
const productCard = readRel("snippets/product-card.candy") || "";
|
|
10889
|
+
const themeCss = readRel("assets/theme.css") || "";
|
|
10890
|
+
checks.push({
|
|
10891
|
+
id: "commerce.navigation_header",
|
|
10892
|
+
category: "commerce",
|
|
10893
|
+
status: header.includes("linklists") || header.includes("<nav") ? "passed" : "warning",
|
|
10894
|
+
message: header.includes("linklists") ? "Header wires merchant navigation via linklists." : 'Header should render merchant linklists["main-menu"].links.',
|
|
10895
|
+
file: "sections/header.candy"
|
|
10896
|
+
});
|
|
10897
|
+
checks.push({
|
|
10898
|
+
id: "commerce.cart_count_badge",
|
|
10899
|
+
category: "commerce",
|
|
10900
|
+
status: header.includes("js-cart-count") ? "passed" : "warning",
|
|
10901
|
+
message: header.includes("js-cart-count") ? "Header includes .js-cart-count live cart counter." : "Header is missing .js-cart-count live cart badge.",
|
|
10902
|
+
file: "sections/header.candy"
|
|
10903
|
+
});
|
|
10904
|
+
const combinedProduct = `${productTpl}
|
|
10905
|
+
${productCard}`;
|
|
10906
|
+
const hasSyntheticVariant = /data-variant-id\s*=\s*["'][^"']*-default["']/i.test(combinedProduct);
|
|
10907
|
+
checks.push({
|
|
10908
|
+
id: "commerce.variant_id_contract",
|
|
10909
|
+
category: "commerce",
|
|
10910
|
+
status: hasSyntheticVariant ? "failed" : "passed",
|
|
10911
|
+
message: hasSyntheticVariant ? 'Synthetic "-default" variant ID detected; guard data-variant-id with product.has_inventory_variants.' : 'No synthetic "-default" variant IDs detected.'
|
|
10912
|
+
});
|
|
10913
|
+
checks.push({
|
|
10914
|
+
id: "commerce.product_template",
|
|
10915
|
+
category: "commerce",
|
|
10916
|
+
status: productTpl.trim().length > 0 ? "passed" : "failed",
|
|
10917
|
+
message: productTpl.trim().length > 0 ? "templates/product.candy exists." : "Missing templates/product.candy.",
|
|
10918
|
+
file: "templates/product.candy"
|
|
10919
|
+
});
|
|
10920
|
+
checks.push({
|
|
10921
|
+
id: "commerce.collection_template",
|
|
10922
|
+
category: "commerce",
|
|
10923
|
+
status: collectionTpl.trim().length > 0 ? "passed" : "failed",
|
|
10924
|
+
message: collectionTpl.trim().length > 0 ? "templates/collection.candy exists." : "Missing templates/collection.candy.",
|
|
10925
|
+
file: "templates/collection.candy"
|
|
10926
|
+
});
|
|
10927
|
+
checks.push({
|
|
10928
|
+
id: "commerce.cart_template",
|
|
10929
|
+
category: "commerce",
|
|
10930
|
+
status: cartTpl.trim().length > 0 ? "passed" : "failed",
|
|
10931
|
+
message: cartTpl.trim().length > 0 ? "templates/cart.candy exists." : "Missing templates/cart.candy.",
|
|
10932
|
+
file: "templates/cart.candy"
|
|
10933
|
+
});
|
|
10934
|
+
checks.push({
|
|
10935
|
+
id: "commerce.search_template",
|
|
10936
|
+
category: "commerce",
|
|
10937
|
+
status: searchTpl.trim().length > 0 ? "passed" : "warning",
|
|
10938
|
+
message: searchTpl.trim().length > 0 ? "templates/search.candy exists." : "Missing templates/search.candy.",
|
|
10939
|
+
file: "templates/search.candy"
|
|
10940
|
+
});
|
|
10941
|
+
let hasAnyPluginHook = false;
|
|
10942
|
+
try {
|
|
10943
|
+
const { bundle } = loadCandyThemeFromDirectory(dir);
|
|
10944
|
+
hasAnyPluginHook = Object.values(bundle.files).some((src) => /\{%-?\s*hook\s+['"]/.test(src));
|
|
10945
|
+
} catch {}
|
|
10946
|
+
checks.push({
|
|
10947
|
+
id: "plugins.extension_hooks",
|
|
10948
|
+
category: "plugins",
|
|
10949
|
+
status: hasAnyPluginHook ? "passed" : "warning",
|
|
10950
|
+
message: hasAnyPluginHook ? 'Theme includes {% hook "..." %} plugin extension slots.' : 'No {% hook "..." %} plugin extension slots detected. Add product/cart/header/footer hooks for plugin compatibility.'
|
|
10951
|
+
});
|
|
10952
|
+
const hasResponsiveMedia = /@media\s*\(/.test(themeCss) || themeCss.includes("clamp(") || themeCss.includes("grid-template-columns");
|
|
10953
|
+
checks.push({
|
|
10954
|
+
id: "responsive.css_layout",
|
|
10955
|
+
category: "responsive",
|
|
10956
|
+
status: hasResponsiveMedia ? "passed" : "warning",
|
|
10957
|
+
message: hasResponsiveMedia ? "assets/theme.css includes responsive layout rules." : "assets/theme.css lacks responsive @media or fluid grid rules.",
|
|
10958
|
+
file: "assets/theme.css"
|
|
10959
|
+
});
|
|
10960
|
+
const layout = readRel("layout/theme.candy") || "";
|
|
10961
|
+
const hasViewport = layout.includes("viewport") || !layout;
|
|
10962
|
+
const hasSkipOrAria = layout.includes("aria-") || header.includes("aria-label");
|
|
10963
|
+
checks.push({
|
|
10964
|
+
id: "accessibility.viewport_and_aria",
|
|
10965
|
+
category: "accessibility",
|
|
10966
|
+
status: hasViewport && hasSkipOrAria ? "passed" : "warning",
|
|
10967
|
+
message: hasViewport && hasSkipOrAria ? "Viewport meta and ARIA landmarks/labels detected." : 'Ensure layout/theme.candy includes <meta name="viewport"> and interactive controls have aria-label attributes.',
|
|
10968
|
+
file: "layout/theme.candy"
|
|
10969
|
+
});
|
|
10970
|
+
const summary = {
|
|
10971
|
+
passed: checks.filter((c) => c.status === "passed").length,
|
|
10972
|
+
failed: checks.filter((c) => c.status === "failed").length,
|
|
10973
|
+
warnings: checks.filter((c) => c.status === "warning").length,
|
|
10974
|
+
skipped: checks.filter((c) => c.status === "skipped").length,
|
|
10975
|
+
blocked: checks.filter((c) => c.status === "blocked").length
|
|
10976
|
+
};
|
|
10977
|
+
return {
|
|
10978
|
+
generatedAt: new Date().toISOString(),
|
|
10979
|
+
themeDir: dir,
|
|
10980
|
+
slug,
|
|
10981
|
+
version,
|
|
10982
|
+
packageHash,
|
|
10983
|
+
sdkVersion: "1.2.1",
|
|
10984
|
+
runtimeVersion: "candy-1.0",
|
|
10985
|
+
status: summary.failed > 0 ? "failed" : summary.warnings > 0 ? "partial" : "passed",
|
|
10986
|
+
summary,
|
|
10987
|
+
checks
|
|
10988
|
+
};
|
|
10989
|
+
}
|
|
10990
|
+
|
|
10991
|
+
// src/cli/mcp/ui-patterns-tools.ts
|
|
10992
|
+
import { existsSync as existsSync11, readFileSync as readFileSync11 } from "node:fs";
|
|
10993
|
+
import { join as join11, resolve as resolve9 } from "node:path";
|
|
10994
|
+
import { z as z8 } from "zod";
|
|
10995
|
+
function auditCandyUiConsistency(themeDir) {
|
|
10996
|
+
const dir = resolve9(themeDir);
|
|
10997
|
+
const readRel = (rel) => {
|
|
10998
|
+
const p = join11(dir, rel);
|
|
10999
|
+
return existsSync11(p) ? readFileSync11(p, "utf8") : "";
|
|
11000
|
+
};
|
|
11001
|
+
const css = readRel("assets/theme.css");
|
|
11002
|
+
const productCard = readRel("snippets/product-card.candy");
|
|
11003
|
+
const cart = readRel("templates/cart.candy");
|
|
11004
|
+
const search = readRel("templates/search.candy");
|
|
11005
|
+
const collection = readRel("templates/collection.candy");
|
|
11006
|
+
const checks = [
|
|
11007
|
+
{
|
|
11008
|
+
id: "ui.design_tokens",
|
|
11009
|
+
status: css.includes(":root") && (css.includes("--cz-") || css.includes("--sf-")) ? "passed" : "warning",
|
|
11010
|
+
message: css.includes(":root") ? "Semantic CSS design tokens (:root) found in assets/theme.css." : "Define semantic :root design tokens (--cz-bg, --cz-ink, --cz-primary) in assets/theme.css for cross-page visual consistency."
|
|
11011
|
+
},
|
|
11012
|
+
{
|
|
11013
|
+
id: "ui.uniform_card_aspect_ratio",
|
|
11014
|
+
status: css.includes("aspect-ratio") && css.includes("object-fit") ? "passed" : "warning",
|
|
11015
|
+
message: css.includes("aspect-ratio") && css.includes("object-fit") ? "Product cards enforce uniform aspect-ratio and object-fit: cover." : "Add aspect-ratio (e.g. 4/5) and object-fit: cover on product card images to prevent uneven grid rows."
|
|
11016
|
+
},
|
|
11017
|
+
{
|
|
11018
|
+
id: "ui.responsive_breakpoints",
|
|
11019
|
+
status: /@media\s*\(max-width:/i.test(css) ? "passed" : "warning",
|
|
11020
|
+
message: /@media\s*\(max-width:/i.test(css) ? "Responsive tablet/mobile @media breakpoints detected." : "Add @media (max-width: 1024px) and @media (max-width: 768px) rules for tablet and mobile layouts."
|
|
11021
|
+
},
|
|
11022
|
+
{
|
|
11023
|
+
id: "ui.reusable_product_card",
|
|
11024
|
+
status: productCard.trim().length > 0 ? "passed" : "failed",
|
|
11025
|
+
message: productCard.trim().length > 0 ? "Shared snippets/product-card.candy exists for consistent product grids." : "Missing snippets/product-card.candy — reuse one product card snippet across Home, Collection, and Search."
|
|
11026
|
+
},
|
|
11027
|
+
{
|
|
11028
|
+
id: "ui.empty_states",
|
|
11029
|
+
status: [cart, search, collection].every((t) => /else|empty|no\s+/i.test(t)) ? "passed" : "warning",
|
|
11030
|
+
message: "Checked Cart, Search, and Collection templates for empty/zero-result states."
|
|
11031
|
+
}
|
|
11032
|
+
];
|
|
11033
|
+
const failed = checks.filter((c) => c.status === "failed").length;
|
|
11034
|
+
const warnings = checks.filter((c) => c.status === "warning").length;
|
|
11035
|
+
return {
|
|
11036
|
+
themeDir: dir,
|
|
11037
|
+
status: failed > 0 ? "failed" : warnings > 0 ? "partial" : "passed",
|
|
11038
|
+
summary: { passed: checks.length - failed - warnings, failed, warnings },
|
|
11039
|
+
checks
|
|
11040
|
+
};
|
|
11041
|
+
}
|
|
11042
|
+
|
|
11043
|
+
// src/cli/caartzee-cli.ts
|
|
9173
11044
|
async function runCli(rawArgs, io = {}) {
|
|
9174
11045
|
const log = io.stdout ?? console.log;
|
|
9175
11046
|
const error = io.stderr ?? console.error;
|
|
@@ -9216,18 +11087,34 @@ async function runCli(rawArgs, io = {}) {
|
|
|
9216
11087
|
case "dev":
|
|
9217
11088
|
return await handleDev(args, log, error);
|
|
9218
11089
|
case "sync-manifest": {
|
|
9219
|
-
const theme = await loadLocalTheme(
|
|
9220
|
-
writeFileSync5(
|
|
11090
|
+
const theme = await loadLocalTheme(resolve10(args[0] || process.cwd()));
|
|
11091
|
+
writeFileSync5(resolve10(args[0] || process.cwd(), "manifest.json"), JSON.stringify(theme.manifest, null, 2));
|
|
9221
11092
|
log("Exported runtime theme manifest.");
|
|
9222
11093
|
return 0;
|
|
9223
11094
|
}
|
|
11095
|
+
case "doctor":
|
|
11096
|
+
return await handleDoctor(args, log, error);
|
|
11097
|
+
case "version":
|
|
11098
|
+
return await handleVersion(args, log, error);
|
|
9224
11099
|
case "validate":
|
|
9225
11100
|
return await handleValidate(args, log, error);
|
|
9226
11101
|
case "build":
|
|
9227
11102
|
return await handleBuild(args, log, error);
|
|
11103
|
+
case "test":
|
|
11104
|
+
return await handleTestSuite(args, "all", log, error);
|
|
11105
|
+
case "audit":
|
|
11106
|
+
return await handleTestSuite(args, "audit", log, error);
|
|
11107
|
+
case "test-editor":
|
|
11108
|
+
return await handleTestEditor(args, log, error);
|
|
11109
|
+
case "test-commerce":
|
|
11110
|
+
return await handleTestSuite(args, "commerce", log, error);
|
|
11111
|
+
case "test-report":
|
|
11112
|
+
return await handleTestReport(args, log, error);
|
|
11113
|
+
case "ui-audit":
|
|
11114
|
+
return await handleUiAudit(args, log, error);
|
|
9228
11115
|
case "ide":
|
|
9229
11116
|
case "ide-setup": {
|
|
9230
|
-
const targetDir = args[0] ?
|
|
11117
|
+
const targetDir = args[0] ? resolve10(args[0]) : process.cwd();
|
|
9231
11118
|
const res = installCandyIdeSupport({ workspaceDir: targetDir });
|
|
9232
11119
|
log(`
|
|
9233
11120
|
\uD83C\uDFA8 Installed Candy (.candy) IDE language support:`);
|
|
@@ -9261,16 +11148,23 @@ async function handleInit(args, log, error) {
|
|
|
9261
11148
|
throw new Error("Supported templates: commerce");
|
|
9262
11149
|
args = args.filter((_, index) => index !== templateIndex && index !== templateIndex + 1);
|
|
9263
11150
|
}
|
|
9264
|
-
const sdkPath = fileURLToPath3(new URL("../../", import.meta.url));
|
|
9265
|
-
const sdkVersion = existsSync9(join9(sdkPath, "src/index.ts")) ? undefined : JSON.parse(readFileSync9(join9(sdkPath, "package.json"), "utf8")).version;
|
|
9266
11151
|
const engineIndex = args.indexOf("--engine");
|
|
9267
|
-
const engine = engineIndex < 0 ?
|
|
11152
|
+
const engine = engineIndex < 0 ? "typescript" : args[engineIndex + 1];
|
|
9268
11153
|
if (engine !== "typescript" && engine !== "candy")
|
|
9269
11154
|
throw new Error("Supported engines are candy and typescript.");
|
|
9270
11155
|
if (commerce && engine === "candy")
|
|
9271
11156
|
throw new Error("The commerce scaffold uses TypeScript.");
|
|
9272
11157
|
if (engineIndex >= 0)
|
|
9273
11158
|
args = args.filter((_, index) => index !== engineIndex && index !== engineIndex + 1);
|
|
11159
|
+
const presetIndex = args.indexOf("--preset");
|
|
11160
|
+
const presetRaw = presetIndex < 0 ? undefined : args[presetIndex + 1];
|
|
11161
|
+
if (presetIndex >= 0) {
|
|
11162
|
+
if (!presetRaw || !CANDY_DESIGN_PRESET_IDS.includes(presetRaw)) {
|
|
11163
|
+
throw new Error(`Supported presets: ${CANDY_DESIGN_PRESET_IDS.join(", ")}`);
|
|
11164
|
+
}
|
|
11165
|
+
args = args.filter((_, index) => index !== presetIndex && index !== presetIndex + 1);
|
|
11166
|
+
}
|
|
11167
|
+
const preset = presetRaw;
|
|
9274
11168
|
const dirIndex = args.indexOf("--dir");
|
|
9275
11169
|
const dir = dirIndex < 0 ? undefined : args[dirIndex + 1];
|
|
9276
11170
|
if (dirIndex >= 0 && !dir)
|
|
@@ -9278,7 +11172,7 @@ async function handleInit(args, log, error) {
|
|
|
9278
11172
|
if (dirIndex >= 0)
|
|
9279
11173
|
args = args.filter((_, index) => index !== dirIndex && index !== dirIndex + 1);
|
|
9280
11174
|
const nameArg = args[0];
|
|
9281
|
-
const targetDir =
|
|
11175
|
+
const targetDir = resolve10(dir || args[1] || nameArg || "my-caartzee-theme");
|
|
9282
11176
|
const themeName = nameArg || "My Caartzee Theme";
|
|
9283
11177
|
log(`
|
|
9284
11178
|
\uD83D\uDCE6 Scaffolding new Caartzee theme in: ${targetDir}`);
|
|
@@ -9286,10 +11180,10 @@ async function handleInit(args, log, error) {
|
|
|
9286
11180
|
const create = commerce ? scaffoldCommerceTheme : scaffoldTheme;
|
|
9287
11181
|
const result = await create({
|
|
9288
11182
|
targetDir,
|
|
9289
|
-
sdkPath,
|
|
9290
|
-
sdkVersion,
|
|
11183
|
+
sdkPath: fileURLToPath3(new URL("../../", import.meta.url)),
|
|
9291
11184
|
name: themeName,
|
|
9292
|
-
engine
|
|
11185
|
+
engine,
|
|
11186
|
+
...preset ? { preset } : {}
|
|
9293
11187
|
});
|
|
9294
11188
|
log(`✨ Successfully generated theme "${result.name}" (${result.slug})!`);
|
|
9295
11189
|
log(` Created ${result.createdFiles.length} files:`);
|
|
@@ -9301,11 +11195,10 @@ async function handleInit(args, log, error) {
|
|
|
9301
11195
|
}
|
|
9302
11196
|
log(`
|
|
9303
11197
|
\uD83D\uDE80 Next steps:`);
|
|
9304
|
-
log(` 1. cd
|
|
9305
|
-
log(
|
|
11198
|
+
log(` 1. cd ${nameArg || "my-caartzee-theme"}`);
|
|
11199
|
+
log(` 2. bun install && bun run dev # preview your theme with mock data`);
|
|
9306
11200
|
log(` 3. Generate app SDK access in your developer portal`);
|
|
9307
|
-
log(
|
|
9308
|
-
` : ` 4. bun run validate
|
|
11201
|
+
log(` 4. bun run validate # check before submission
|
|
9309
11202
|
`);
|
|
9310
11203
|
return 0;
|
|
9311
11204
|
} catch (err) {
|
|
@@ -9422,17 +11315,20 @@ async function handleDev(args, log, error) {
|
|
|
9422
11315
|
let port = 3333;
|
|
9423
11316
|
let themeDir = process.cwd();
|
|
9424
11317
|
let store;
|
|
11318
|
+
let editor = false;
|
|
9425
11319
|
for (let i = 0;i < args.length; i++) {
|
|
9426
11320
|
if (args[i] === "--port" && args[i + 1]) {
|
|
9427
11321
|
port = parseInt(args[i + 1], 10);
|
|
9428
11322
|
i++;
|
|
9429
11323
|
} else if (args[i] === "--dir" && args[i + 1]) {
|
|
9430
|
-
themeDir =
|
|
11324
|
+
themeDir = resolve10(args[i + 1]);
|
|
9431
11325
|
i++;
|
|
9432
11326
|
} else if (args[i] === "--store") {
|
|
9433
11327
|
store = args[++i];
|
|
9434
11328
|
if (!store || store.startsWith("-"))
|
|
9435
11329
|
throw new Error("--store requires a store domain or tenant ID.");
|
|
11330
|
+
} else if (args[i] === "--editor") {
|
|
11331
|
+
editor = true;
|
|
9436
11332
|
}
|
|
9437
11333
|
}
|
|
9438
11334
|
log(`
|
|
@@ -9458,10 +11354,17 @@ async function handleDev(args, log, error) {
|
|
|
9458
11354
|
};
|
|
9459
11355
|
await loadCatalog({});
|
|
9460
11356
|
}
|
|
9461
|
-
const instance = await startThemeDevServer({
|
|
11357
|
+
const instance = await startThemeDevServer({
|
|
11358
|
+
port,
|
|
11359
|
+
themeDir,
|
|
11360
|
+
editor,
|
|
11361
|
+
...store ? { storeLabel: store } : {},
|
|
11362
|
+
...loadCatalog ? { loadCatalog } : {}
|
|
11363
|
+
});
|
|
9462
11364
|
log(` \x1B[32m✓ Local Preview ready at:\x1B[0m \x1B[36m${instance.url}\x1B[0m`);
|
|
9463
|
-
log(
|
|
9464
|
-
log(
|
|
11365
|
+
log(` \x1B[32m✓ Local Theme Editor ready at:\x1B[0m \x1B[36m${instance.editorUrl}\x1B[0m`);
|
|
11366
|
+
log(loadCatalog ? " Authorized store catalog & branding with isolated local sandbox cart/auth/checkout." : " Demo mode with full local sandbox cart, wishlist, auth, checkout & order tracking.");
|
|
11367
|
+
log(` • Inspect storefront context at: ${instance.url}/_api/context`);
|
|
9465
11368
|
log(` • Press Ctrl+C to stop.
|
|
9466
11369
|
`);
|
|
9467
11370
|
if (process.env.CAARTZEE_DEV_ONESHOT === "true") {
|
|
@@ -9485,21 +11388,21 @@ Shutting down dev server...`);
|
|
|
9485
11388
|
}
|
|
9486
11389
|
}
|
|
9487
11390
|
async function handleValidate(args, log, error) {
|
|
9488
|
-
const targetDir = args[0] ?
|
|
11391
|
+
const targetDir = args[0] ? resolve10(args[0]) : process.cwd();
|
|
9489
11392
|
log(`
|
|
9490
11393
|
\uD83D\uDEE1️ Running Caartzee Theme Security & Package Validation...`);
|
|
9491
11394
|
log(` Target: ${targetDir}`);
|
|
9492
|
-
const manifestPath =
|
|
9493
|
-
if (!
|
|
11395
|
+
const manifestPath = join12(targetDir, "manifest.json");
|
|
11396
|
+
if (!existsSync12(manifestPath)) {
|
|
9494
11397
|
error(`❌ Missing manifest.json in ${targetDir}`);
|
|
9495
11398
|
return 1;
|
|
9496
11399
|
}
|
|
9497
11400
|
try {
|
|
9498
|
-
if (
|
|
11401
|
+
if (existsSync12(join12(targetDir, "src/manifest.ts")) && typeof Bun !== "undefined") {
|
|
9499
11402
|
const theme = await loadLocalTheme(targetDir);
|
|
9500
11403
|
writeFileSync5(manifestPath, JSON.stringify(theme.manifest, null, 2));
|
|
9501
11404
|
}
|
|
9502
|
-
const rawManifest = JSON.parse(
|
|
11405
|
+
const rawManifest = JSON.parse(readFileSync12(manifestPath, "utf-8"));
|
|
9503
11406
|
const manifestCheck = ThemePackageValidator.validateManifest(rawManifest);
|
|
9504
11407
|
if (!manifestCheck.success) {
|
|
9505
11408
|
error(`❌ Manifest validation failed:`);
|
|
@@ -9538,7 +11441,7 @@ async function handleValidate(args, log, error) {
|
|
|
9538
11441
|
}
|
|
9539
11442
|
}
|
|
9540
11443
|
async function handleBuild(args, log, error) {
|
|
9541
|
-
const targetDir = args[0] ?
|
|
11444
|
+
const targetDir = args[0] ? resolve10(args[0]) : process.cwd();
|
|
9542
11445
|
log(`
|
|
9543
11446
|
\uD83D\uDD28 Building Caartzee Theme Package...`);
|
|
9544
11447
|
log(` Source directory: ${targetDir}`);
|
|
@@ -9550,9 +11453,9 @@ async function handleBuild(args, log, error) {
|
|
|
9550
11453
|
}
|
|
9551
11454
|
return 1;
|
|
9552
11455
|
}
|
|
9553
|
-
const isCandy =
|
|
9554
|
-
const distDir =
|
|
9555
|
-
if (!
|
|
11456
|
+
const isCandy = existsSync12(join12(targetDir, "candy.config.json")) || existsSync12(join12(targetDir, "layout", "theme.candy")) || valResult.manifest?.engine === "candy";
|
|
11457
|
+
const distDir = join12(targetDir, "dist");
|
|
11458
|
+
if (!existsSync12(distDir)) {
|
|
9556
11459
|
mkdirSync5(distDir, { recursive: true });
|
|
9557
11460
|
}
|
|
9558
11461
|
if (isCandy) {
|
|
@@ -9565,8 +11468,8 @@ async function handleBuild(args, log, error) {
|
|
|
9565
11468
|
}
|
|
9566
11469
|
return 1;
|
|
9567
11470
|
}
|
|
9568
|
-
const bundlePath =
|
|
9569
|
-
const manifestOutPath =
|
|
11471
|
+
const bundlePath = join12(distDir, "candy-theme-bundle.json");
|
|
11472
|
+
const manifestOutPath = join12(distDir, "manifest.json");
|
|
9570
11473
|
writeFileSync5(bundlePath, JSON.stringify(bundle, null, 2), "utf-8");
|
|
9571
11474
|
writeFileSync5(manifestOutPath, JSON.stringify(bundle.manifest, null, 2), "utf-8");
|
|
9572
11475
|
log(`✓ Extracted ${Object.keys(bundle.sectionSchemas).length} section schemas`);
|
|
@@ -9576,7 +11479,7 @@ async function handleBuild(args, log, error) {
|
|
|
9576
11479
|
return 0;
|
|
9577
11480
|
}
|
|
9578
11481
|
if (valResult.manifest) {
|
|
9579
|
-
const manifestOutPath =
|
|
11482
|
+
const manifestOutPath = join12(distDir, "manifest.json");
|
|
9580
11483
|
writeFileSync5(manifestOutPath, JSON.stringify(valResult.manifest, null, 2), "utf-8");
|
|
9581
11484
|
log(`✓ Wrote validated manifest to ${manifestOutPath}
|
|
9582
11485
|
`);
|
|
@@ -9595,10 +11498,10 @@ async function handlePush(args, log, error) {
|
|
|
9595
11498
|
error(`❌ Insufficient scope. Your account lacks "theme:publish" permissions.`);
|
|
9596
11499
|
return 1;
|
|
9597
11500
|
}
|
|
9598
|
-
const targetDir = args[0] ?
|
|
9599
|
-
if (
|
|
11501
|
+
const targetDir = args[0] ? resolve10(args[0]) : process.cwd();
|
|
11502
|
+
if (existsSync12(join12(targetDir, "src/manifest.ts")) && typeof Bun !== "undefined") {
|
|
9600
11503
|
const theme = await loadLocalTheme(targetDir);
|
|
9601
|
-
writeFileSync5(
|
|
11504
|
+
writeFileSync5(join12(targetDir, "manifest.json"), JSON.stringify(theme.manifest, null, 2));
|
|
9602
11505
|
}
|
|
9603
11506
|
const valResult = await ThemePackageValidator.validatePackage(targetDir);
|
|
9604
11507
|
if (!valResult.valid) {
|
|
@@ -9619,10 +11522,284 @@ async function handlePush(args, log, error) {
|
|
|
9619
11522
|
`);
|
|
9620
11523
|
return 0;
|
|
9621
11524
|
}
|
|
11525
|
+
async function handleDoctor(args, log, error) {
|
|
11526
|
+
const targetDir = args[0] ? resolve10(args[0]) : process.cwd();
|
|
11527
|
+
log(`
|
|
11528
|
+
\uD83E\uDE7A Running Caartzee Candy Theme Doctor...`);
|
|
11529
|
+
log(` Target: ${targetDir}
|
|
11530
|
+
`);
|
|
11531
|
+
const issues = [];
|
|
11532
|
+
const warnings = [];
|
|
11533
|
+
const passed = [];
|
|
11534
|
+
const readIfExists = (rel) => {
|
|
11535
|
+
const full = join12(targetDir, rel);
|
|
11536
|
+
return existsSync12(full) ? readFileSync12(full, "utf8") : null;
|
|
11537
|
+
};
|
|
11538
|
+
const configRaw = readIfExists("candy.config.json");
|
|
11539
|
+
const manifestRaw = readIfExists("manifest.json");
|
|
11540
|
+
if (!configRaw)
|
|
11541
|
+
issues.push("Missing candy.config.json in theme root.");
|
|
11542
|
+
if (!manifestRaw)
|
|
11543
|
+
issues.push('Missing manifest.json. Run "caartzee-theme sync-manifest .".');
|
|
11544
|
+
let configJson = null;
|
|
11545
|
+
let manifestJson = null;
|
|
11546
|
+
try {
|
|
11547
|
+
if (configRaw)
|
|
11548
|
+
configJson = JSON.parse(configRaw);
|
|
11549
|
+
} catch {
|
|
11550
|
+
issues.push("candy.config.json is invalid JSON.");
|
|
11551
|
+
}
|
|
11552
|
+
try {
|
|
11553
|
+
if (manifestRaw)
|
|
11554
|
+
manifestJson = JSON.parse(manifestRaw);
|
|
11555
|
+
} catch {
|
|
11556
|
+
issues.push("manifest.json is invalid JSON.");
|
|
11557
|
+
}
|
|
11558
|
+
if (configJson && manifestJson) {
|
|
11559
|
+
if (configJson.slug !== manifestJson.slug) {
|
|
11560
|
+
issues.push(`Slug mismatch: candy.config.json ("${configJson.slug}") != manifest.json ("${manifestJson.slug}").`);
|
|
11561
|
+
} else {
|
|
11562
|
+
passed.push(`Slug aligned ("${configJson.slug}")`);
|
|
11563
|
+
}
|
|
11564
|
+
if (configJson.version !== manifestJson.version) {
|
|
11565
|
+
warnings.push(`Version mismatch: candy.config.json (${configJson.version}) != manifest.json (${manifestJson.version}). Run "caartzee-theme sync-manifest .".`);
|
|
11566
|
+
} else {
|
|
11567
|
+
passed.push(`Version aligned (v${configJson.version})`);
|
|
11568
|
+
}
|
|
11569
|
+
}
|
|
11570
|
+
const caps = manifestJson?.capabilities;
|
|
11571
|
+
const usesShell = Array.isArray(caps) ? caps.includes("storefront-shell") : caps?.["storefront-shell"] === true;
|
|
11572
|
+
const hasCommerce = Array.isArray(caps) ? caps.includes("commerce_pages") : caps?.commerce_pages === true;
|
|
11573
|
+
if (usesShell && hasCommerce) {
|
|
11574
|
+
passed.push("Storefront Shell + commerce_pages capabilities enabled");
|
|
11575
|
+
} else {
|
|
11576
|
+
warnings.push('Set capabilities: { "storefront-shell": true, "commerce_pages": true } in manifest.json for live cart/checkout/auth.');
|
|
11577
|
+
}
|
|
11578
|
+
const templateNames = ["index.candy", "collection.candy", "list-collections.candy", "product.candy", "cart.candy", "search.candy", "wishlist.candy", "login.candy", "register.candy", "page.candy", "404.candy"];
|
|
11579
|
+
for (const name of templateNames) {
|
|
11580
|
+
const content = readIfExists(join12("templates", name));
|
|
11581
|
+
if (!content)
|
|
11582
|
+
continue;
|
|
11583
|
+
if (usesShell && /\{%\s*layout\s+/i.test(content)) {
|
|
11584
|
+
issues.push(`templates/${name} uses {% layout %}, which causes duplicate headers/footers when storefront-shell is enabled.`);
|
|
11585
|
+
}
|
|
11586
|
+
if (/data-variant-id\s*=\s*["'][^"']*-default["']/i.test(content)) {
|
|
11587
|
+
issues.push(`templates/${name} emits a synthetic "-default" variant ID, which causes POST /_api/cart 422 errors.`);
|
|
11588
|
+
}
|
|
11589
|
+
}
|
|
11590
|
+
const productCard = readIfExists(join12("snippets", "product-card.candy"));
|
|
11591
|
+
if (productCard) {
|
|
11592
|
+
if (/data-variant-id\s*=\s*["'][^"']*-default["']/i.test(productCard)) {
|
|
11593
|
+
issues.push('snippets/product-card.candy emits a synthetic "-default" variant ID. Guard data-variant-id with product.has_inventory_variants.');
|
|
11594
|
+
} else {
|
|
11595
|
+
passed.push("Product card variant ID contract looks safe");
|
|
11596
|
+
}
|
|
11597
|
+
}
|
|
11598
|
+
const headerCandy = readIfExists(join12("sections", "header.candy"));
|
|
11599
|
+
if (headerCandy) {
|
|
11600
|
+
if (!headerCandy.includes("js-cart-count")) {
|
|
11601
|
+
warnings.push("sections/header.candy is missing .js-cart-count on the cart badge (live Add to Cart count won't update).");
|
|
11602
|
+
} else {
|
|
11603
|
+
passed.push("Header cart count badge (.js-cart-count) present");
|
|
11604
|
+
}
|
|
11605
|
+
if (!headerCandy.includes("menuId") || !headerCandy.includes("linklists")) {
|
|
11606
|
+
warnings.push(`sections/header.candy should include "menuId" schema setting and render linklists['main-menu'].links.`);
|
|
11607
|
+
} else {
|
|
11608
|
+
passed.push("Header navigation menu (menuId + linklists) wired");
|
|
11609
|
+
}
|
|
11610
|
+
}
|
|
11611
|
+
const heroCandy = readIfExists(join12("sections", "hero-banner.candy"));
|
|
11612
|
+
if (heroCandy) {
|
|
11613
|
+
if (!heroCandy.includes("mobile_sliders")) {
|
|
11614
|
+
warnings.push("sections/hero-banner.candy does not read mobile_sliders (merchant Mobile Slider changes won't reflect).");
|
|
11615
|
+
} else {
|
|
11616
|
+
passed.push("Hero banner mobile_sliders support present");
|
|
11617
|
+
}
|
|
11618
|
+
}
|
|
11619
|
+
const loginCandy = readIfExists(join12("templates", "login.candy"));
|
|
11620
|
+
const registerCandy = readIfExists(join12("templates", "register.candy"));
|
|
11621
|
+
if (loginCandy) {
|
|
11622
|
+
if (!loginCandy.includes("/_api/auth/login") || !loginCandy.includes("js-auth-form")) {
|
|
11623
|
+
issues.push('templates/login.candy must post to /_api/auth/login with class="js-auth-form".');
|
|
11624
|
+
} else {
|
|
11625
|
+
passed.push("Login page (/login) auth contract verified");
|
|
11626
|
+
}
|
|
11627
|
+
}
|
|
11628
|
+
if (registerCandy) {
|
|
11629
|
+
if (!registerCandy.includes("/_api/auth/register") || !registerCandy.includes("js-auth-form")) {
|
|
11630
|
+
issues.push('templates/register.candy must post to /_api/auth/register with class="js-auth-form".');
|
|
11631
|
+
} else {
|
|
11632
|
+
passed.push("Signup page (/signup, /register) auth contract verified");
|
|
11633
|
+
}
|
|
11634
|
+
}
|
|
11635
|
+
if (readIfExists(join12("assets", "theme.css")))
|
|
11636
|
+
passed.push("assets/theme.css found");
|
|
11637
|
+
else
|
|
11638
|
+
warnings.push("assets/theme.css not found.");
|
|
11639
|
+
if (readIfExists(join12("assets", "theme.js")))
|
|
11640
|
+
passed.push("assets/theme.js found");
|
|
11641
|
+
else
|
|
11642
|
+
warnings.push("assets/theme.js not found.");
|
|
11643
|
+
for (const p of passed)
|
|
11644
|
+
log(` ✓ ${p}`);
|
|
11645
|
+
if (warnings.length > 0) {
|
|
11646
|
+
log("");
|
|
11647
|
+
for (const w of warnings)
|
|
11648
|
+
log(` ⚠️ ${w}`);
|
|
11649
|
+
}
|
|
11650
|
+
if (issues.length > 0) {
|
|
11651
|
+
log("");
|
|
11652
|
+
for (const i of issues)
|
|
11653
|
+
error(` ❌ ${i}`);
|
|
11654
|
+
log(`
|
|
11655
|
+
❌ Doctor found ${issues.length} error(s) and ${warnings.length} warning(s).
|
|
11656
|
+
`);
|
|
11657
|
+
return 1;
|
|
11658
|
+
}
|
|
11659
|
+
log(`
|
|
11660
|
+
✅ Theme Doctor passed! (${passed.length} checks passed, ${warnings.length} warning(s))
|
|
11661
|
+
`);
|
|
11662
|
+
return 0;
|
|
11663
|
+
}
|
|
11664
|
+
async function handleVersion(args, log, error) {
|
|
11665
|
+
const bump = args[0]?.trim();
|
|
11666
|
+
const targetDir = args[1] ? resolve10(args[1]) : process.cwd();
|
|
11667
|
+
if (!bump) {
|
|
11668
|
+
error("Usage: caartzee-theme version <patch|minor|major|x.y.z> [path]");
|
|
11669
|
+
return 1;
|
|
11670
|
+
}
|
|
11671
|
+
const configPath = join12(targetDir, "candy.config.json");
|
|
11672
|
+
const manifestPath = join12(targetDir, "manifest.json");
|
|
11673
|
+
if (!existsSync12(configPath) && !existsSync12(manifestPath)) {
|
|
11674
|
+
error(`No candy.config.json or manifest.json found in ${targetDir}`);
|
|
11675
|
+
return 1;
|
|
11676
|
+
}
|
|
11677
|
+
const readJson = (p) => JSON.parse(readFileSync12(p, "utf8"));
|
|
11678
|
+
const current = existsSync12(configPath) ? String(readJson(configPath).version || "1.0.0") : String(readJson(manifestPath).version || "1.0.0");
|
|
11679
|
+
let nextVersion = bump;
|
|
11680
|
+
if (bump === "patch" || bump === "minor" || bump === "major") {
|
|
11681
|
+
const parts = current.split(".").map((n) => parseInt(n, 10) || 0);
|
|
11682
|
+
const [maj = 1, min = 0, pat = 0] = parts;
|
|
11683
|
+
nextVersion = bump === "major" ? `${maj + 1}.0.0` : bump === "minor" ? `${maj}.${min + 1}.0` : `${maj}.${min}.${pat + 1}`;
|
|
11684
|
+
} else if (!/^\d+\.\d+\.\d+$/.test(bump)) {
|
|
11685
|
+
error(`Invalid version "${bump}". Use patch, minor, major, or semver like 1.0.3.`);
|
|
11686
|
+
return 1;
|
|
11687
|
+
}
|
|
11688
|
+
if (existsSync12(configPath)) {
|
|
11689
|
+
const cfg = readJson(configPath);
|
|
11690
|
+
cfg.version = nextVersion;
|
|
11691
|
+
writeFileSync5(configPath, JSON.stringify(cfg, null, 2) + `
|
|
11692
|
+
`, "utf8");
|
|
11693
|
+
}
|
|
11694
|
+
if (existsSync12(manifestPath)) {
|
|
11695
|
+
const man = readJson(manifestPath);
|
|
11696
|
+
man.version = nextVersion;
|
|
11697
|
+
writeFileSync5(manifestPath, JSON.stringify(man, null, 2) + `
|
|
11698
|
+
`, "utf8");
|
|
11699
|
+
}
|
|
11700
|
+
log(`✓ Bumped theme version: ${current} -> ${nextVersion}`);
|
|
11701
|
+
return 0;
|
|
11702
|
+
}
|
|
11703
|
+
function parseTargetAndJson(args) {
|
|
11704
|
+
const asJson = args.includes("--json");
|
|
11705
|
+
const positional = args.filter((a) => !a.startsWith("-"));
|
|
11706
|
+
const targetDir = positional[0] ? resolve10(positional[0]) : process.cwd();
|
|
11707
|
+
return { targetDir, asJson };
|
|
11708
|
+
}
|
|
11709
|
+
async function handleTestEditor(args, log, error) {
|
|
11710
|
+
const { targetDir, asJson } = parseTargetAndJson(args);
|
|
11711
|
+
const result = validateThemeEditorDirectory(targetDir);
|
|
11712
|
+
if (asJson) {
|
|
11713
|
+
log(JSON.stringify(result, null, 2));
|
|
11714
|
+
return result.valid ? 0 : 1;
|
|
11715
|
+
}
|
|
11716
|
+
log(`
|
|
11717
|
+
\uD83C\uDFA8 Caartzee Theme Editor Compatibility Check (${result.slug || targetDir})`);
|
|
11718
|
+
for (const c of result.checks) {
|
|
11719
|
+
const icon = c.status === "passed" ? "✓" : c.status === "warning" ? "⚠️" : "❌";
|
|
11720
|
+
(c.status === "failed" ? error : log)(` ${icon} [${c.name}] ${c.message}${c.file ? ` (${c.file})` : ""}`);
|
|
11721
|
+
}
|
|
11722
|
+
log(`
|
|
11723
|
+
${result.valid ? "✅" : "❌"} Theme Editor check: ${result.summary.passed} passed, ${result.summary.failed} failed, ${result.summary.warnings} warning(s).
|
|
11724
|
+
`);
|
|
11725
|
+
return result.valid ? 0 : 1;
|
|
11726
|
+
}
|
|
11727
|
+
async function handleTestSuite(args, mode, log, error) {
|
|
11728
|
+
const { targetDir, asJson } = parseTargetAndJson(args);
|
|
11729
|
+
const fullReport = await runThemeReadinessAudit(targetDir);
|
|
11730
|
+
const checks = mode === "commerce" ? fullReport.checks.filter((c) => c.category === "commerce" || c.category === "plugins") : fullReport.checks;
|
|
11731
|
+
const failed = checks.filter((c) => c.status === "failed").length;
|
|
11732
|
+
const passed = checks.filter((c) => c.status === "passed").length;
|
|
11733
|
+
const warnings = checks.filter((c) => c.status === "warning").length;
|
|
11734
|
+
const payload = {
|
|
11735
|
+
...fullReport,
|
|
11736
|
+
mode,
|
|
11737
|
+
status: failed > 0 ? "failed" : warnings > 0 ? "partial" : "passed",
|
|
11738
|
+
summary: { ...fullReport.summary, passed, failed, warnings },
|
|
11739
|
+
checks
|
|
11740
|
+
};
|
|
11741
|
+
if (asJson) {
|
|
11742
|
+
log(JSON.stringify(payload, null, 2));
|
|
11743
|
+
return failed > 0 ? 1 : 0;
|
|
11744
|
+
}
|
|
11745
|
+
const label = mode === "commerce" ? "Commerce & Plugin Hooks Test" : mode === "audit" ? "Theme Readiness Audit" : "Storefront Test Suite";
|
|
11746
|
+
log(`
|
|
11747
|
+
\uD83E\uDDEA Caartzee ${label} — ${payload.slug}@${payload.version}`);
|
|
11748
|
+
log(` Package Hash: ${payload.packageHash.slice(0, 16)}...`);
|
|
11749
|
+
for (const c of checks) {
|
|
11750
|
+
const icon = c.status === "passed" ? "✓" : c.status === "warning" ? "⚠️" : "❌";
|
|
11751
|
+
(c.status === "failed" ? error : log)(` ${icon} [${c.category}/${c.id}] ${c.message}${c.file ? ` (${c.file})` : ""}`);
|
|
11752
|
+
}
|
|
11753
|
+
log(`
|
|
11754
|
+
${failed === 0 ? "✅" : "❌"} Result: ${passed} passed, ${failed} failed, ${warnings} warning(s).
|
|
11755
|
+
`);
|
|
11756
|
+
return failed > 0 ? 1 : 0;
|
|
11757
|
+
}
|
|
11758
|
+
async function handleTestReport(args, log, error) {
|
|
11759
|
+
const { targetDir, asJson } = parseTargetAndJson(args);
|
|
11760
|
+
const report = await runThemeReadinessAudit(targetDir);
|
|
11761
|
+
const distDir = join12(targetDir, "dist");
|
|
11762
|
+
if (!existsSync12(distDir))
|
|
11763
|
+
mkdirSync5(distDir, { recursive: true });
|
|
11764
|
+
const outPath = join12(distDir, "theme-readiness-report.json");
|
|
11765
|
+
writeFileSync5(outPath, JSON.stringify(report, null, 2), "utf8");
|
|
11766
|
+
if (asJson) {
|
|
11767
|
+
log(JSON.stringify({ reportPath: outPath, ...report }, null, 2));
|
|
11768
|
+
} else {
|
|
11769
|
+
log(`
|
|
11770
|
+
\uD83D\uDCC4 Wrote readiness report bound to packageHash ${report.packageHash.slice(0, 16)}...`);
|
|
11771
|
+
log(` Path: ${outPath}`);
|
|
11772
|
+
log(` Status: ${report.status.toUpperCase()} (${report.summary.passed} passed, ${report.summary.failed} failed, ${report.summary.warnings} warning(s))
|
|
11773
|
+
`);
|
|
11774
|
+
}
|
|
11775
|
+
if (report.summary.failed > 0) {
|
|
11776
|
+
error(`Theme readiness report recorded ${report.summary.failed} failing check(s).`);
|
|
11777
|
+
return 1;
|
|
11778
|
+
}
|
|
11779
|
+
return 0;
|
|
11780
|
+
}
|
|
11781
|
+
async function handleUiAudit(args, log, error) {
|
|
11782
|
+
const { targetDir, asJson } = parseTargetAndJson(args);
|
|
11783
|
+
const report = auditCandyUiConsistency(targetDir);
|
|
11784
|
+
if (asJson) {
|
|
11785
|
+
log(JSON.stringify(report, null, 2));
|
|
11786
|
+
return report.summary.failed > 0 ? 1 : 0;
|
|
11787
|
+
}
|
|
11788
|
+
log(`
|
|
11789
|
+
\uD83C\uDFA8 Caartzee Candy UI Consistency Audit (${targetDir})`);
|
|
11790
|
+
for (const c of report.checks) {
|
|
11791
|
+
const icon = c.status === "passed" ? "✓" : c.status === "warning" ? "⚠️" : "❌";
|
|
11792
|
+
(c.status === "failed" ? error : log)(` ${icon} [${c.id}] ${c.message}`);
|
|
11793
|
+
}
|
|
11794
|
+
log(`
|
|
11795
|
+
${report.summary.failed === 0 ? "✅" : "❌"} UI Audit: ${report.summary.passed} passed, ${report.summary.failed} failed, ${report.summary.warnings} warning(s).
|
|
11796
|
+
`);
|
|
11797
|
+
return report.summary.failed > 0 ? 1 : 0;
|
|
11798
|
+
}
|
|
9622
11799
|
function printHelp(log) {
|
|
9623
11800
|
log(`
|
|
9624
11801
|
╔═══════════════════════════════════════════════════════════════╗
|
|
9625
|
-
║ CAARTZEE THEME SDK CLI (v1.
|
|
11802
|
+
║ CAARTZEE THEME SDK CLI (v1.2.1) ║
|
|
9626
11803
|
║ Build, test, and publish secure storefront themes locally ║
|
|
9627
11804
|
╚═══════════════════════════════════════════════════════════════╝
|
|
9628
11805
|
|
|
@@ -9631,16 +11808,26 @@ Usage:
|
|
|
9631
11808
|
npx @caartzee/theme-sdk <command> [options]
|
|
9632
11809
|
|
|
9633
11810
|
Commands:
|
|
9634
|
-
init [name]
|
|
9635
|
-
dev [--port 3333] [--store DOMAIN]
|
|
9636
|
-
|
|
9637
|
-
|
|
11811
|
+
init [name] [--engine candy] [--preset minimal-luxury|streetwear-editorial|organic-wellness|modern-tech|vibrant-d2c]
|
|
11812
|
+
dev [--port 3333] [--store DOMAIN] [--editor] Preview with full local commerce/auth & Theme Editor
|
|
11813
|
+
ui-audit [path] [--json] Audit design tokens, uniform card aspect ratios, responsive CSS & empty states
|
|
11814
|
+
doctor [path] Audit storefront-shell, cart/variant hooks, auth forms, menus & mobile sliders
|
|
11815
|
+
version <patch|minor|major|x.y.z> [path] Bump version across candy.config.json and manifest.json
|
|
11816
|
+
sync-manifest [path] Export the locally authored theme manifest to JSON
|
|
11817
|
+
validate [path] Check source patterns and validate manifest
|
|
11818
|
+
test [path] [--json] Run full storefront validation, editor, commerce, security & responsive suite
|
|
11819
|
+
audit [path] [--json] Run comprehensive readiness, accessibility, security & commerce audit
|
|
11820
|
+
test-editor [path] [--json] Verify Theme Editor schemas, block attributes & live rendering
|
|
11821
|
+
test-commerce [path] [--json] Verify cart, variant, wishlist, search, auth & plugin contracts
|
|
11822
|
+
test-report [path] [--json] Generate packageHash-bound dist/theme-readiness-report.json
|
|
11823
|
+
build [path] Compile Candy templates and assets into dist/candy-theme-bundle.json
|
|
11824
|
+
ide-setup [path] Install .candy syntax highlighting for VS Code / Cursor / Antigravity
|
|
11825
|
+
connect --clipboard Connect using the Windows clipboard
|
|
11826
|
+
connect --stdin Connect using a piped Developer Portal connection
|
|
9638
11827
|
login --api URL --token-stdin Connect with app SDK access from developer portal
|
|
9639
11828
|
whoami Display current developer account & token status
|
|
9640
11829
|
logout Securely clear saved local credentials
|
|
9641
|
-
|
|
9642
|
-
validate [path] Check source patterns and validate manifest
|
|
9643
|
-
push Validate and push theme to Caartzee Partner Portal
|
|
11830
|
+
push [path] Validate and push theme to Caartzee Partner Portal
|
|
9644
11831
|
help Display this help message
|
|
9645
11832
|
|
|
9646
11833
|
Security Guarantee:
|