@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
|
@@ -136,8 +136,11 @@ function collectThemeSources(root) {
|
|
|
136
136
|
}
|
|
137
137
|
|
|
138
138
|
// src/cli/caartzee-cli.ts
|
|
139
|
-
import { existsSync as
|
|
140
|
-
import { resolve as
|
|
139
|
+
import { existsSync as existsSync12, mkdirSync as mkdirSync5, readFileSync as readFileSync12, writeFileSync as writeFileSync5 } from "node:fs";
|
|
140
|
+
import { resolve as resolve10, join as join12 } from "node:path";
|
|
141
|
+
|
|
142
|
+
// src/scaffold/AGENTS.md
|
|
143
|
+
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";
|
|
141
144
|
|
|
142
145
|
// src/scaffold/template-generator.ts
|
|
143
146
|
import { existsSync as existsSync3, mkdirSync as mkdirSync3, writeFileSync as writeFileSync3 } from "node:fs";
|
|
@@ -593,6 +596,323 @@ var candyStarterProductCard = `<article class="candy-product-card">
|
|
|
593
596
|
</article>
|
|
594
597
|
`;
|
|
595
598
|
|
|
599
|
+
// src/scaffold/design-presets.ts
|
|
600
|
+
var CANDY_DESIGN_PRESETS = {
|
|
601
|
+
"minimal-luxury": {
|
|
602
|
+
id: "minimal-luxury",
|
|
603
|
+
name: "Minimal Luxury",
|
|
604
|
+
description: "Warm ivory canvas, editorial serif headings, hairline borders, and champagne bronze accents.",
|
|
605
|
+
bestFor: "Fashion, jewelry, skincare, home fragrance, boutique lifestyle brands.",
|
|
606
|
+
googleFontsUrl: "https://fonts.googleapis.com/css2?family=Cormorant+Garamond:wght@500;600;700&family=Plus+Jakarta+Sans:wght@400;500;600&display=swap",
|
|
607
|
+
tokens: {
|
|
608
|
+
colors: {
|
|
609
|
+
background: "#FAF9F6",
|
|
610
|
+
surface: "#F2EFE9",
|
|
611
|
+
text: "#141414",
|
|
612
|
+
muted: "#6B665E",
|
|
613
|
+
border: "#E5E0D8",
|
|
614
|
+
primary: "#141414",
|
|
615
|
+
primaryText: "#FAF9F6",
|
|
616
|
+
accent: "#9A7B4F",
|
|
617
|
+
danger: "#B91C1C",
|
|
618
|
+
success: "#166534"
|
|
619
|
+
},
|
|
620
|
+
typography: {
|
|
621
|
+
headingFont: "'Cormorant Garamond', Georgia, serif",
|
|
622
|
+
bodyFont: "'Plus Jakarta Sans', system-ui, -apple-system, sans-serif"
|
|
623
|
+
},
|
|
624
|
+
borderRadius: { sm: "2px", md: "4px", lg: "6px", button: "2px" }
|
|
625
|
+
}
|
|
626
|
+
},
|
|
627
|
+
"streetwear-editorial": {
|
|
628
|
+
id: "streetwear-editorial",
|
|
629
|
+
name: "Streetwear Editorial",
|
|
630
|
+
description: "High-contrast stark monochrome, architectural zero-radius grid, and punchy grotesk typography.",
|
|
631
|
+
bestFor: "Streetwear, sneakers, archival fashion, skate, music merch.",
|
|
632
|
+
googleFontsUrl: "https://fonts.googleapis.com/css2?family=Space+Grotesk:wght@500;600;700&family=Inter:wght@400;500;600&display=swap",
|
|
633
|
+
tokens: {
|
|
634
|
+
colors: {
|
|
635
|
+
background: "#FFFFFF",
|
|
636
|
+
surface: "#F4F4F5",
|
|
637
|
+
text: "#09090B",
|
|
638
|
+
muted: "#52525B",
|
|
639
|
+
border: "#E4E4E7",
|
|
640
|
+
primary: "#09090B",
|
|
641
|
+
primaryText: "#FFFFFF",
|
|
642
|
+
accent: "#E11D48",
|
|
643
|
+
danger: "#DC2626",
|
|
644
|
+
success: "#15803D"
|
|
645
|
+
},
|
|
646
|
+
typography: {
|
|
647
|
+
headingFont: "'Space Grotesk', system-ui, sans-serif",
|
|
648
|
+
bodyFont: "'Inter', system-ui, -apple-system, sans-serif"
|
|
649
|
+
},
|
|
650
|
+
borderRadius: { sm: "0px", md: "0px", lg: "2px", button: "0px" }
|
|
651
|
+
}
|
|
652
|
+
},
|
|
653
|
+
"organic-wellness": {
|
|
654
|
+
id: "organic-wellness",
|
|
655
|
+
name: "Organic Wellness",
|
|
656
|
+
description: "Soft oat background, forest green ink, sage surfaces, and calm rounded cards.",
|
|
657
|
+
bestFor: "Skincare, botanicals, tea/coffee, supplements, sustainable living.",
|
|
658
|
+
googleFontsUrl: "https://fonts.googleapis.com/css2?family=Fraunces:wght@500;600;700&family=DM+Sans:wght@400;500;600&display=swap",
|
|
659
|
+
tokens: {
|
|
660
|
+
colors: {
|
|
661
|
+
background: "#F7F5F0",
|
|
662
|
+
surface: "#ECECE4",
|
|
663
|
+
text: "#1F2D24",
|
|
664
|
+
muted: "#5A6B5F",
|
|
665
|
+
border: "#DCE0D6",
|
|
666
|
+
primary: "#2F523B",
|
|
667
|
+
primaryText: "#F7F5F0",
|
|
668
|
+
accent: "#C26D47",
|
|
669
|
+
danger: "#B91C1C",
|
|
670
|
+
success: "#166534"
|
|
671
|
+
},
|
|
672
|
+
typography: {
|
|
673
|
+
headingFont: "'Fraunces', Georgia, serif",
|
|
674
|
+
bodyFont: "'DM Sans', system-ui, -apple-system, sans-serif"
|
|
675
|
+
},
|
|
676
|
+
borderRadius: { sm: "8px", md: "14px", lg: "20px", button: "9999px" }
|
|
677
|
+
}
|
|
678
|
+
},
|
|
679
|
+
"modern-tech": {
|
|
680
|
+
id: "modern-tech",
|
|
681
|
+
name: "Modern Tech",
|
|
682
|
+
description: "Sleek dark slate surfaces, luminous contrast, geometric sans, and electric indigo accent.",
|
|
683
|
+
bestFor: "Electronics, audio gear, gaming hardware, digital products, SaaS merch.",
|
|
684
|
+
googleFontsUrl: "https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@600;700&family=Inter:wght@400;500;600&display=swap",
|
|
685
|
+
tokens: {
|
|
686
|
+
colors: {
|
|
687
|
+
background: "#090D16",
|
|
688
|
+
surface: "#111827",
|
|
689
|
+
text: "#F8FAFC",
|
|
690
|
+
muted: "#94A3B8",
|
|
691
|
+
border: "#1E293B",
|
|
692
|
+
primary: "#6366F1",
|
|
693
|
+
primaryText: "#FFFFFF",
|
|
694
|
+
accent: "#38BDF8",
|
|
695
|
+
danger: "#F43F5E",
|
|
696
|
+
success: "#10B981"
|
|
697
|
+
},
|
|
698
|
+
typography: {
|
|
699
|
+
headingFont: "'Plus Jakarta Sans', system-ui, sans-serif",
|
|
700
|
+
bodyFont: "'Inter', system-ui, -apple-system, sans-serif"
|
|
701
|
+
},
|
|
702
|
+
borderRadius: { sm: "6px", md: "10px", lg: "16px", button: "8px" }
|
|
703
|
+
}
|
|
704
|
+
},
|
|
705
|
+
"vibrant-d2c": {
|
|
706
|
+
id: "vibrant-d2c",
|
|
707
|
+
name: "Vibrant D2C",
|
|
708
|
+
description: "Energetic high-conversion D2C palette, pill buttons, clear savings badges, and crisp card hierarchy.",
|
|
709
|
+
bestFor: "Snacks, beverages, pets, fitness, everyday consumer brands.",
|
|
710
|
+
googleFontsUrl: "https://fonts.googleapis.com/css2?family=Outfit:wght@600;700&family=Inter:wght@400;500;600&display=swap",
|
|
711
|
+
tokens: {
|
|
712
|
+
colors: {
|
|
713
|
+
background: "#FFFFFF",
|
|
714
|
+
surface: "#FFF7ED",
|
|
715
|
+
text: "#0F172A",
|
|
716
|
+
muted: "#475569",
|
|
717
|
+
border: "#E2E8F0",
|
|
718
|
+
primary: "#EA580C",
|
|
719
|
+
primaryText: "#FFFFFF",
|
|
720
|
+
accent: "#0F172A",
|
|
721
|
+
danger: "#DC2626",
|
|
722
|
+
success: "#059669"
|
|
723
|
+
},
|
|
724
|
+
typography: {
|
|
725
|
+
headingFont: "'Outfit', system-ui, sans-serif",
|
|
726
|
+
bodyFont: "'Inter', system-ui, -apple-system, sans-serif"
|
|
727
|
+
},
|
|
728
|
+
borderRadius: { sm: "8px", md: "14px", lg: "20px", button: "9999px" }
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
};
|
|
732
|
+
var CANDY_DESIGN_PRESET_IDS = Object.keys(CANDY_DESIGN_PRESETS);
|
|
733
|
+
function resolveDesignPreset(id) {
|
|
734
|
+
const key = (id || "minimal-luxury").trim().toLowerCase();
|
|
735
|
+
return CANDY_DESIGN_PRESETS[key] || CANDY_DESIGN_PRESETS["minimal-luxury"];
|
|
736
|
+
}
|
|
737
|
+
function buildCandyDesignSystemCss(presetInput) {
|
|
738
|
+
const preset = typeof presetInput === "string" || !presetInput ? resolveDesignPreset(presetInput) : presetInput;
|
|
739
|
+
const { colors, typography, borderRadius } = preset.tokens;
|
|
740
|
+
return `/* Caartzee Candy Design System — Preset: ${preset.name} (${preset.id}) */
|
|
741
|
+
@import url('${preset.googleFontsUrl}');
|
|
742
|
+
|
|
743
|
+
:root {
|
|
744
|
+
--cz-bg: ${colors.background};
|
|
745
|
+
--cz-surface: ${colors.surface};
|
|
746
|
+
--cz-ink: ${colors.text};
|
|
747
|
+
--cz-muted: ${colors.muted};
|
|
748
|
+
--cz-border: ${colors.border};
|
|
749
|
+
--cz-primary: ${colors.primary};
|
|
750
|
+
--cz-primary-ink: ${colors.primaryText};
|
|
751
|
+
--cz-accent: ${colors.accent};
|
|
752
|
+
--cz-danger: ${colors.danger};
|
|
753
|
+
--cz-success: ${colors.success};
|
|
754
|
+
--cz-font-heading: ${typography.headingFont};
|
|
755
|
+
--cz-font-body: ${typography.bodyFont};
|
|
756
|
+
--cz-radius-sm: ${borderRadius.sm};
|
|
757
|
+
--cz-radius-md: ${borderRadius.md};
|
|
758
|
+
--cz-radius-lg: ${borderRadius.lg};
|
|
759
|
+
--cz-radius-btn: ${borderRadius.button};
|
|
760
|
+
--cz-container: 1280px;
|
|
761
|
+
--cz-space-xs: 0.5rem;
|
|
762
|
+
--cz-space-sm: 1rem;
|
|
763
|
+
--cz-space-md: 1.5rem;
|
|
764
|
+
--cz-space-lg: 3rem;
|
|
765
|
+
--cz-space-xl: 4.5rem;
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
*, *::before, *::after { box-sizing: border-box; }
|
|
769
|
+
html { font-size: 16px; -webkit-font-smoothing: antialiased; }
|
|
770
|
+
body {
|
|
771
|
+
margin: 0;
|
|
772
|
+
background: var(--cz-bg);
|
|
773
|
+
color: var(--cz-ink);
|
|
774
|
+
font-family: var(--cz-font-body);
|
|
775
|
+
line-height: 1.6;
|
|
776
|
+
}
|
|
777
|
+
h1, h2, h3, h4 { font-family: var(--cz-font-heading); line-height: 1.15; letter-spacing: -0.01em; margin: 0 0 0.75rem; }
|
|
778
|
+
a { color: inherit; text-decoration: none; }
|
|
779
|
+
img { max-width: 100%; height: auto; display: block; }
|
|
780
|
+
|
|
781
|
+
.cz-container { width: 100%; max-width: var(--cz-container); margin: 0 auto; padding: 0 1.25rem; }
|
|
782
|
+
|
|
783
|
+
/* Buttons */
|
|
784
|
+
.cz-btn, button.js-add-to-cart, button.js-submit-btn {
|
|
785
|
+
display: inline-flex; align-items: center; justify-content: center; gap: 0.5rem;
|
|
786
|
+
padding: 0.75rem 1.4rem; border-radius: var(--cz-radius-btn);
|
|
787
|
+
background: var(--cz-primary); color: var(--cz-primary-ink);
|
|
788
|
+
border: 1px solid var(--cz-primary); font: 600 0.875rem/1 var(--cz-font-body);
|
|
789
|
+
cursor: pointer; transition: opacity 0.18s ease, transform 0.15s ease;
|
|
790
|
+
}
|
|
791
|
+
.cz-btn:hover, button.js-add-to-cart:hover, button.js-submit-btn:hover { opacity: 0.88; }
|
|
792
|
+
.cz-btn--outline { background: transparent; color: var(--cz-ink); border-color: var(--cz-border); }
|
|
793
|
+
.cz-btn--outline:hover { border-color: var(--cz-ink); opacity: 1; }
|
|
794
|
+
|
|
795
|
+
/* Announcement & Header */
|
|
796
|
+
.cz-announcement-bar {
|
|
797
|
+
background: var(--cz-primary); color: var(--cz-primary-ink);
|
|
798
|
+
text-align: center; font-size: 0.78rem; font-weight: 500;
|
|
799
|
+
padding: 0.5rem 1rem; letter-spacing: 0.03em;
|
|
800
|
+
}
|
|
801
|
+
.cz-candy-header {
|
|
802
|
+
position: sticky; top: 0; z-index: 40;
|
|
803
|
+
background: var(--cz-bg); color: var(--cz-ink);
|
|
804
|
+
border-bottom: 1px solid var(--cz-border);
|
|
805
|
+
}
|
|
806
|
+
.cz-header-inner {
|
|
807
|
+
max-width: var(--cz-container); margin: 0 auto; padding: 0.9rem 1.25rem;
|
|
808
|
+
display: flex; align-items: center; justify-content: space-between; gap: 1.25rem; flex-wrap: wrap;
|
|
809
|
+
}
|
|
810
|
+
.cz-header-logo { font-family: var(--cz-font-heading); font-size: 1.4rem; font-weight: 700; letter-spacing: -0.02em; }
|
|
811
|
+
.cz-candy-header nav { display: flex; align-items: center; gap: 1.4rem; flex-wrap: wrap; font-size: 0.9rem; font-weight: 500; }
|
|
812
|
+
.cz-candy-header nav a:hover { color: var(--cz-accent); }
|
|
813
|
+
.cz-header-actions { display: flex; align-items: center; gap: 1rem; font-size: 0.875rem; font-weight: 500; }
|
|
814
|
+
|
|
815
|
+
/* Hero Banner */
|
|
816
|
+
.cz-candy-hero {
|
|
817
|
+
position: relative; overflow: hidden; background: var(--cz-surface);
|
|
818
|
+
padding: clamp(3rem, 7vw, 6.5rem) 1.25rem; text-align: center;
|
|
819
|
+
border-bottom: 1px solid var(--cz-border);
|
|
820
|
+
}
|
|
821
|
+
.cz-candy-hero h1 { font-size: clamp(2.1rem, 5vw, 4rem); max-width: 18ch; margin: 0 auto 1rem; }
|
|
822
|
+
.cz-candy-hero p { color: var(--cz-muted); max-width: 54ch; margin: 0 auto 1.75rem; font-size: 1.05rem; }
|
|
823
|
+
.cz-candy-hero > a {
|
|
824
|
+
display: inline-flex; padding: 0.85rem 1.8rem; border-radius: var(--cz-radius-btn);
|
|
825
|
+
background: var(--cz-primary); color: var(--cz-primary-ink); font-weight: 600; font-size: 0.9rem;
|
|
826
|
+
}
|
|
827
|
+
.cz-hero-desktop-img {
|
|
828
|
+
width: 100%; max-width: 1120px; max-height: 480px; object-fit: cover;
|
|
829
|
+
margin: 0 auto 2rem; border-radius: var(--cz-radius-lg);
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
/* Uniform Product Grid & Cards (used on Home, Collection, Search, Related Products) */
|
|
833
|
+
.cz-candy-featured-products, .cz-candy-collection, .cz-candy-search {
|
|
834
|
+
max-width: var(--cz-container); margin: 0 auto; padding: var(--cz-space-lg) 1.25rem;
|
|
835
|
+
}
|
|
836
|
+
.candy-product-grid {
|
|
837
|
+
display: grid; gap: 1.5rem;
|
|
838
|
+
grid-template-columns: repeat(4, minmax(0, 1fr));
|
|
839
|
+
}
|
|
840
|
+
.candy-product-card {
|
|
841
|
+
display: flex; flex-direction: column; gap: 0.65rem;
|
|
842
|
+
background: var(--cz-bg); border: 1px solid var(--cz-border);
|
|
843
|
+
border-radius: var(--cz-radius-md); overflow: hidden; padding-bottom: 1rem;
|
|
844
|
+
transition: transform 0.2s ease, box-shadow 0.2s ease;
|
|
845
|
+
}
|
|
846
|
+
.candy-product-card:hover { transform: translateY(-2px); box-shadow: 0 10px 24px rgba(15, 23, 42, 0.06); }
|
|
847
|
+
.candy-product-card img {
|
|
848
|
+
width: 100%; aspect-ratio: 4 / 5; object-fit: cover; background: var(--cz-surface);
|
|
849
|
+
}
|
|
850
|
+
.candy-product-card h3, .candy-product-card .candy-card-title {
|
|
851
|
+
font-size: 1rem; font-weight: 600; margin: 0; padding: 0 0.9rem;
|
|
852
|
+
}
|
|
853
|
+
.candy-product-card .candy-price { padding: 0 0.9rem; font-weight: 600; color: var(--cz-ink); font-size: 0.95rem; }
|
|
854
|
+
.candy-product-card .js-add-to-cart { margin: 0.25rem 0.9rem 0; width: calc(100% - 1.8rem); }
|
|
855
|
+
|
|
856
|
+
/* Product Detail Page */
|
|
857
|
+
.cz-candy-product-detail {
|
|
858
|
+
max-width: var(--cz-container); margin: 0 auto; padding: var(--cz-space-lg) 1.25rem;
|
|
859
|
+
display: grid; grid-template-columns: minmax(0, 1.1fr) minmax(0, 0.9fr); gap: 3rem; align-items: start;
|
|
860
|
+
}
|
|
861
|
+
.cz-candy-product-detail img[data-product-main-image] {
|
|
862
|
+
width: 100%; aspect-ratio: 4 / 5; object-fit: cover;
|
|
863
|
+
border-radius: var(--cz-radius-lg); background: var(--cz-surface); border: 1px solid var(--cz-border);
|
|
864
|
+
}
|
|
865
|
+
|
|
866
|
+
/* Cart, Auth, Wishlist & Content Pages */
|
|
867
|
+
.cz-candy-cart, .cz-wishlist-section, .cz-candy-page {
|
|
868
|
+
max-width: 960px; margin: 0 auto; padding: var(--cz-space-lg) 1.25rem;
|
|
869
|
+
}
|
|
870
|
+
.cz-auth-section {
|
|
871
|
+
max-width: 440px; margin: 3.5rem auto; padding: 2rem;
|
|
872
|
+
background: var(--cz-surface); border: 1px solid var(--cz-border);
|
|
873
|
+
border-radius: var(--cz-radius-lg);
|
|
874
|
+
}
|
|
875
|
+
.cz-auth-section form { display: grid; gap: 0.85rem; margin-top: 1.25rem; }
|
|
876
|
+
.cz-auth-section input {
|
|
877
|
+
width: 100%; padding: 0.75rem 0.9rem; border-radius: var(--cz-radius-sm);
|
|
878
|
+
border: 1px solid var(--cz-border); background: var(--cz-bg); color: var(--cz-ink);
|
|
879
|
+
font: inherit;
|
|
880
|
+
}
|
|
881
|
+
|
|
882
|
+
/* Editorial Split Section */
|
|
883
|
+
.cz-candy-image-with-text {
|
|
884
|
+
max-width: var(--cz-container); margin: var(--cz-space-lg) auto; padding: 2.5rem;
|
|
885
|
+
background: var(--cz-surface); border: 1px solid var(--cz-border); border-radius: var(--cz-radius-lg);
|
|
886
|
+
}
|
|
887
|
+
|
|
888
|
+
/* Footer */
|
|
889
|
+
.cz-candy-footer {
|
|
890
|
+
margin-top: var(--cz-space-xl); border-top: 1px solid var(--cz-border);
|
|
891
|
+
padding: var(--cz-space-lg) 1.25rem 2rem;
|
|
892
|
+
}
|
|
893
|
+
.cz-footer-grid {
|
|
894
|
+
max-width: var(--cz-container); margin: 0 auto 2rem;
|
|
895
|
+
display: grid; grid-template-columns: 1.5fr repeat(3, minmax(0, 1fr)); gap: 2rem;
|
|
896
|
+
}
|
|
897
|
+
.cz-footer-col { display: flex; flex-direction: column; gap: 0.5rem; font-size: 0.875rem; }
|
|
898
|
+
.cz-footer-bottom {
|
|
899
|
+
max-width: var(--cz-container); margin: 0 auto; padding-top: 1.25rem;
|
|
900
|
+
border-top: 1px solid rgba(255, 255, 255, 0.14); font-size: 0.8rem; opacity: 0.8;
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
/* Responsive Breakpoints */
|
|
904
|
+
@media (max-width: 1024px) {
|
|
905
|
+
.candy-product-grid { grid-template-columns: repeat(3, minmax(0, 1fr)); }
|
|
906
|
+
.cz-footer-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
|
907
|
+
}
|
|
908
|
+
@media (max-width: 768px) {
|
|
909
|
+
.candy-product-grid { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 0.9rem; }
|
|
910
|
+
.cz-candy-product-detail { grid-template-columns: 1fr; gap: 1.75rem; }
|
|
911
|
+
.cz-footer-grid { grid-template-columns: 1fr; }
|
|
912
|
+
}
|
|
913
|
+
`;
|
|
914
|
+
}
|
|
915
|
+
|
|
596
916
|
// src/scaffold/template-generator.ts
|
|
597
917
|
function scaffoldTheme(options) {
|
|
598
918
|
const rawSlug = options.slug || options.name?.toLowerCase().replace(/[^a-z0-9_-]+/g, "-") || "starter-theme";
|
|
@@ -621,7 +941,7 @@ function scaffoldTheme(options) {
|
|
|
621
941
|
};
|
|
622
942
|
if (options.engine === "candy") {
|
|
623
943
|
const sdkDependency = options.sdkVersion ?? (options.sdkPath ? "file:" + relative(rootDir, options.sdkPath).replace(/\\/g, "/") : "^1.0.0");
|
|
624
|
-
return scaffoldCandyThemeInternal({ slug, name, author, description, rootDir, writeFile, createdFiles, sdkDependency });
|
|
944
|
+
return scaffoldCandyThemeInternal({ slug, name, author, description, rootDir, writeFile, createdFiles, sdkDependency, preset: options.preset });
|
|
625
945
|
}
|
|
626
946
|
writeFile("package.json", JSON.stringify({
|
|
627
947
|
name: `@caartzee-theme/${slug}`,
|
|
@@ -975,7 +1295,7 @@ npm run push
|
|
|
975
1295
|
};
|
|
976
1296
|
}
|
|
977
1297
|
function scaffoldCandyThemeInternal(params) {
|
|
978
|
-
const { slug, name, author, description, rootDir, writeFile, createdFiles, sdkDependency } = params;
|
|
1298
|
+
const { slug, name, author, description, rootDir, writeFile, createdFiles, sdkDependency, preset } = params;
|
|
979
1299
|
writeFile("candy.config.json", JSON.stringify({
|
|
980
1300
|
engine: "candy",
|
|
981
1301
|
candyVersion: "1.0.0",
|
|
@@ -1171,13 +1491,42 @@ function scaffoldCandyThemeInternal(params) {
|
|
|
1171
1491
|
</div>
|
|
1172
1492
|
</section>
|
|
1173
1493
|
`);
|
|
1174
|
-
writeFile("sections/header.candy", `<header class="cz-candy-header">
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
<
|
|
1179
|
-
|
|
1180
|
-
|
|
1494
|
+
writeFile("sections/header.candy", `<header class="cz-candy-header" style="background:{{ section.settings.bg_color | default: '#ffffff' }};color:{{ section.settings.text_color | default: '#0f172a' }};">
|
|
1495
|
+
{% if section.settings.show_announcement and section.settings.announcement_text != blank %}
|
|
1496
|
+
<div class="cz-announcement-bar">
|
|
1497
|
+
{% hook 'header_announcement_before' %}
|
|
1498
|
+
<span>{{ section.settings.announcement_text | escape }}</span>
|
|
1499
|
+
{% hook 'header_announcement_after' %}
|
|
1500
|
+
</div>
|
|
1501
|
+
{% endif %}
|
|
1502
|
+
<div class="cz-header-inner">
|
|
1503
|
+
<a href="/" class="cz-header-logo" aria-label="{{ shop.name | escape }}">
|
|
1504
|
+
{% if section.settings.logo != blank %}
|
|
1505
|
+
<img src="{{ section.settings.logo }}" alt="{{ shop.name | escape }}" style="max-width:{{ section.settings.logo_width | default: 120 }}px;" />
|
|
1506
|
+
{% else %}
|
|
1507
|
+
<span>{{ shop.name | escape }}</span>
|
|
1508
|
+
{% endif %}
|
|
1509
|
+
</a>
|
|
1510
|
+
<nav aria-label="Main navigation">
|
|
1511
|
+
{% assign nav_handle = section.settings.menuId | default: 'main-menu' %}
|
|
1512
|
+
{% if linklists[nav_handle].links.size > 0 %}
|
|
1513
|
+
{% for link in linklists[nav_handle].links %}
|
|
1514
|
+
<a href="{{ link.url }}">{{ link.title | escape }}</a>
|
|
1515
|
+
{% endfor %}
|
|
1516
|
+
{% else %}
|
|
1517
|
+
{% for block in section.blocks %}
|
|
1518
|
+
<a href="{{ block.settings.url }}" {{ block.candy_attributes }}>{{ block.settings.label | escape }}</a>
|
|
1519
|
+
{% endfor %}
|
|
1520
|
+
{% endif %}
|
|
1521
|
+
</nav>
|
|
1522
|
+
<div class="cz-header-actions">
|
|
1523
|
+
{% hook 'header_actions' %}
|
|
1524
|
+
{% if section.settings.show_search %}<a href="/search" aria-label="Search">Search</a>{% endif %}
|
|
1525
|
+
{% if section.settings.show_wishlist %}<a href="/wishlist" aria-label="Wishlist">Wishlist</a>{% endif %}
|
|
1526
|
+
{% if section.settings.show_account %}<a href="/account" aria-label="Account">Account</a>{% endif %}
|
|
1527
|
+
{% 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 %}
|
|
1528
|
+
</div>
|
|
1529
|
+
</div>
|
|
1181
1530
|
</header>
|
|
1182
1531
|
{% schema %}
|
|
1183
1532
|
{
|
|
@@ -1186,8 +1535,19 @@ function scaffoldCandyThemeInternal(params) {
|
|
|
1186
1535
|
"category": "Header",
|
|
1187
1536
|
"allowedRegions": ["header"],
|
|
1188
1537
|
"settings": [
|
|
1538
|
+
{ "id": "logo", "type": "image", "label": "Logo Image" },
|
|
1539
|
+
{ "id": "logo_width", "type": "range", "label": "Logo Width (px)", "min": 60, "max": 240, "step": 4, "default": 120 },
|
|
1540
|
+
{ "id": "mobile_logo", "type": "image", "label": "Mobile Logo" },
|
|
1541
|
+
{ "id": "show_announcement", "type": "checkbox", "label": "Show Announcement Bar", "default": true },
|
|
1542
|
+
{ "id": "announcement_text", "type": "text", "label": "Top Announcement", "default": "Free express shipping on all orders over $150." },
|
|
1543
|
+
{ "id": "bg_color", "type": "color", "label": "Background Color", "default": "#ffffff" },
|
|
1544
|
+
{ "id": "text_color", "type": "color", "label": "Text Color", "default": "#0f172a" },
|
|
1545
|
+
{ "id": "menuId", "type": "select", "label": "Navigation Menu", "options": [] },
|
|
1189
1546
|
{ "id": "sticky", "type": "checkbox", "label": "Sticky Header", "default": true },
|
|
1190
|
-
{ "id": "
|
|
1547
|
+
{ "id": "show_search", "type": "checkbox", "label": "Show Search", "default": true },
|
|
1548
|
+
{ "id": "show_wishlist", "type": "checkbox", "label": "Show Wishlist", "default": true },
|
|
1549
|
+
{ "id": "show_account", "type": "checkbox", "label": "Show Account", "default": true },
|
|
1550
|
+
{ "id": "show_cart", "type": "checkbox", "label": "Show Cart", "default": true }
|
|
1191
1551
|
],
|
|
1192
1552
|
"blocks": [
|
|
1193
1553
|
{
|
|
@@ -1204,9 +1564,24 @@ function scaffoldCandyThemeInternal(params) {
|
|
|
1204
1564
|
{% endschema %}
|
|
1205
1565
|
`);
|
|
1206
1566
|
writeFile("sections/hero-banner.candy", `<section class="cz-candy-hero">
|
|
1567
|
+
{% if mobile_sliders.size > 0 %}
|
|
1568
|
+
<div class="cz-mobile-sliders" data-mobile-sliders="true">
|
|
1569
|
+
{% for slide in mobile_sliders %}
|
|
1570
|
+
<a href="{{ slide.url | default: '/products' }}"><img src="{{ slide.image }}" alt="{{ slide.title | escape }}" /></a>
|
|
1571
|
+
{% endfor %}
|
|
1572
|
+
</div>
|
|
1573
|
+
{% endif %}
|
|
1574
|
+
{% if section.settings.desktop_image != blank %}
|
|
1575
|
+
<img class="cz-hero-desktop-img" src="{{ section.settings.desktop_image }}" alt="{{ section.settings.heading | escape }}" />
|
|
1576
|
+
{% endif %}
|
|
1207
1577
|
<h1>{{ section.settings.heading | escape }}</h1>
|
|
1208
1578
|
<p>{{ section.settings.subheading | escape }}</p>
|
|
1209
1579
|
<a href="{{ section.settings.button_url }}">{{ section.settings.button_label | escape }}</a>
|
|
1580
|
+
{% for block in section.blocks %}
|
|
1581
|
+
<div class="cz-hero-slide" {{ block.candy_attributes }}>
|
|
1582
|
+
<strong>{{ block.settings.title | escape }}</strong>
|
|
1583
|
+
</div>
|
|
1584
|
+
{% endfor %}
|
|
1210
1585
|
</section>
|
|
1211
1586
|
{% schema %}
|
|
1212
1587
|
{
|
|
@@ -1217,10 +1592,23 @@ function scaffoldCandyThemeInternal(params) {
|
|
|
1217
1592
|
"settings": [
|
|
1218
1593
|
{ "id": "heading", "type": "text", "label": "Heading", "default": "Curated Elegance for Modern Living." },
|
|
1219
1594
|
{ "id": "subheading", "type": "textarea", "label": "Subheading", "default": "Handcrafted essentials designed to endure." },
|
|
1595
|
+
{ "id": "desktop_image", "type": "image", "label": "Desktop Banner Image" },
|
|
1596
|
+
{ "id": "mobile_image", "type": "image", "label": "Mobile Banner Image" },
|
|
1220
1597
|
{ "id": "button_label", "type": "text", "label": "Button Label", "default": "Explore Collection" },
|
|
1221
1598
|
{ "id": "button_url", "type": "url", "label": "Button URL", "default": "/products" }
|
|
1222
1599
|
],
|
|
1223
|
-
"blocks": [
|
|
1600
|
+
"blocks": [
|
|
1601
|
+
{
|
|
1602
|
+
"type": "slide",
|
|
1603
|
+
"name": "Hero Slide",
|
|
1604
|
+
"limit": 6,
|
|
1605
|
+
"settings": [
|
|
1606
|
+
{ "id": "title", "type": "text", "label": "Slide Title", "default": "New Arrivals" },
|
|
1607
|
+
{ "id": "image", "type": "image", "label": "Slide Image" },
|
|
1608
|
+
{ "id": "url", "type": "url", "label": "Slide Link", "default": "/products" }
|
|
1609
|
+
]
|
|
1610
|
+
}
|
|
1611
|
+
]
|
|
1224
1612
|
}
|
|
1225
1613
|
{% endschema %}
|
|
1226
1614
|
`);
|
|
@@ -1269,8 +1657,25 @@ function scaffoldCandyThemeInternal(params) {
|
|
|
1269
1657
|
}
|
|
1270
1658
|
{% endschema %}
|
|
1271
1659
|
`);
|
|
1272
|
-
writeFile("sections/footer.candy", `<footer class="cz-candy-footer">
|
|
1273
|
-
|
|
1660
|
+
writeFile("sections/footer.candy", `<footer class="cz-candy-footer" style="background:{{ section.settings.bg_color | default: '#0f172a' }};color:{{ section.settings.text_color | default: '#f8fafc' }};">
|
|
1661
|
+
{% hook 'footer_widgets_before' %}
|
|
1662
|
+
<div class="cz-footer-grid">
|
|
1663
|
+
<div class="cz-footer-brand">
|
|
1664
|
+
{% if section.settings.logo != blank %}<img src="{{ section.settings.logo }}" alt="{{ shop.name | escape }}" />{% else %}<strong>{{ shop.name | escape }}</strong>{% endif %}
|
|
1665
|
+
<p>{{ section.settings.description | escape }}</p>
|
|
1666
|
+
</div>
|
|
1667
|
+
{% for block in section.blocks %}
|
|
1668
|
+
<div class="cz-footer-col" {{ block.candy_attributes }}>
|
|
1669
|
+
<h4>{{ block.settings.heading | escape }}</h4>
|
|
1670
|
+
<a href="{{ block.settings.url | default: '/products' }}">{{ block.settings.link_label | default: 'Browse' | escape }}</a>
|
|
1671
|
+
</div>
|
|
1672
|
+
{% endfor %}
|
|
1673
|
+
</div>
|
|
1674
|
+
{% hook 'footer_widgets_after' %}
|
|
1675
|
+
<div class="cz-footer-bottom">
|
|
1676
|
+
<p>{{ section.settings.copyright_text | escape }}</p>
|
|
1677
|
+
{% hook 'footer_bottom' %}
|
|
1678
|
+
</div>
|
|
1274
1679
|
</footer>
|
|
1275
1680
|
{% schema %}
|
|
1276
1681
|
{
|
|
@@ -1279,25 +1684,113 @@ function scaffoldCandyThemeInternal(params) {
|
|
|
1279
1684
|
"category": "Footer",
|
|
1280
1685
|
"allowedRegions": ["footer"],
|
|
1281
1686
|
"settings": [
|
|
1687
|
+
{ "id": "logo", "type": "image", "label": "Footer Logo" },
|
|
1688
|
+
{ "id": "description", "type": "textarea", "label": "Store Description", "default": "Thoughtfully crafted products delivered to your door." },
|
|
1689
|
+
{ "id": "bg_color", "type": "color", "label": "Background Color", "default": "#0f172a" },
|
|
1690
|
+
{ "id": "text_color", "type": "color", "label": "Text Color", "default": "#f8fafc" },
|
|
1691
|
+
{ "id": "show_newsletter", "type": "checkbox", "label": "Show Newsletter Signup", "default": true },
|
|
1282
1692
|
{ "id": "copyright_text", "type": "text", "label": "Copyright Notice", "default": "© Caartzee Storefront. Powered by Candy." }
|
|
1283
1693
|
],
|
|
1284
|
-
"blocks": [
|
|
1694
|
+
"blocks": [
|
|
1695
|
+
{
|
|
1696
|
+
"type": "link_column",
|
|
1697
|
+
"name": "Footer Column",
|
|
1698
|
+
"limit": 4,
|
|
1699
|
+
"settings": [
|
|
1700
|
+
{ "id": "heading", "type": "text", "label": "Column Heading", "default": "Quick Links" },
|
|
1701
|
+
{ "id": "link_label", "type": "text", "label": "Link Label", "default": "Shop All" },
|
|
1702
|
+
{ "id": "url", "type": "url", "label": "Link URL", "default": "/products" }
|
|
1703
|
+
]
|
|
1704
|
+
}
|
|
1705
|
+
]
|
|
1285
1706
|
}
|
|
1286
1707
|
{% endschema %}
|
|
1708
|
+
`);
|
|
1709
|
+
writeFile("templates/login.candy", `<section class="cz-auth-section">
|
|
1710
|
+
<h1>Sign In</h1>
|
|
1711
|
+
{% hook 'login_form_top' %}
|
|
1712
|
+
<form action="/_api/auth/login" method="POST" class="js-auth-form" data-redirect="{{ redirect_url | default: '/account' | escape }}">
|
|
1713
|
+
<input type="email" name="email" required placeholder="Email address" />
|
|
1714
|
+
<input type="password" name="password" required placeholder="Password" />
|
|
1715
|
+
<input type="hidden" name="redirect" value="{{ redirect_url | default: '/account' | escape }}" />
|
|
1716
|
+
<button type="submit" class="js-submit-btn">Sign In</button>
|
|
1717
|
+
{% if google_auth_enabled %}
|
|
1718
|
+
<button type="button" class="js-firebase-google-btn">Continue with Google</button>
|
|
1719
|
+
{% endif %}
|
|
1720
|
+
</form>
|
|
1721
|
+
{% hook 'login_form_bottom' %}
|
|
1722
|
+
</section>
|
|
1723
|
+
`);
|
|
1724
|
+
writeFile("templates/register.candy", `<section class="cz-auth-section">
|
|
1725
|
+
<h1>Create Account</h1>
|
|
1726
|
+
{% hook 'signup_form_top' %}
|
|
1727
|
+
<form action="/_api/auth/register" method="POST" class="js-auth-form" data-redirect="{{ redirect_url | default: '/account' | escape }}">
|
|
1728
|
+
<input type="text" name="firstName" required placeholder="First name" />
|
|
1729
|
+
<input type="text" name="lastName" placeholder="Last name" />
|
|
1730
|
+
<input type="email" name="email" required placeholder="Email address" />
|
|
1731
|
+
<input type="password" name="password" minlength="6" required placeholder="Password" />
|
|
1732
|
+
<input type="hidden" name="redirect" value="{{ redirect_url | default: '/account' | escape }}" />
|
|
1733
|
+
<button type="submit" class="js-submit-btn">Create Account</button>
|
|
1734
|
+
</form>
|
|
1735
|
+
{% hook 'signup_form_bottom' %}
|
|
1736
|
+
</section>
|
|
1737
|
+
`);
|
|
1738
|
+
writeFile("templates/wishlist.candy", `<section class="cz-wishlist-section">
|
|
1739
|
+
<h1>My Wishlist</h1>
|
|
1740
|
+
<p>Saved items appear here when signed in or in an active browser session.</p>
|
|
1741
|
+
</section>
|
|
1287
1742
|
`);
|
|
1288
1743
|
writeFile("snippets/price.candy", `<span class="candy-price">{{ product.price | money }}</span>
|
|
1289
1744
|
`);
|
|
1745
|
+
if (!existsSync3(join4(rootDir, "AGENTS.md")))
|
|
1746
|
+
writeFile("AGENTS.md", AGENTS_default);
|
|
1747
|
+
if (!existsSync3(join4(rootDir, "CLAUDE.md"))) {
|
|
1748
|
+
writeFile("CLAUDE.md", `# Claude Code Instructions — Caartzee Candy Storefront
|
|
1749
|
+
|
|
1750
|
+
Read [AGENTS.md](./AGENTS.md) and call the Candy MCP tool \`read_candy_guide\` before editing any files.
|
|
1751
|
+
|
|
1752
|
+
## Key Rules
|
|
1753
|
+
- Use Candy MCP (\`list_store_permissions\`, \`request_store_access\`, \`read_store_catalog\`) for authorized merchant data.
|
|
1754
|
+
- Keep every section editable via \`{% schema %}\` and emit \`{{ block.candy_attributes }}\` on blocks.
|
|
1755
|
+
- Never emit synthetic \`-default\` variant IDs or invent API endpoints.
|
|
1756
|
+
- Run \`caartzee-theme doctor .\`, \`caartzee-theme validate .\`, \`caartzee-theme test . --json\`, and \`caartzee-theme build .\` before finishing.
|
|
1757
|
+
- Never run \`caartzee-theme push\` without explicit developer authorization.
|
|
1758
|
+
`);
|
|
1759
|
+
}
|
|
1760
|
+
if (!existsSync3(join4(rootDir, ".cursorrules"))) {
|
|
1761
|
+
writeFile(".cursorrules", `# Caartzee Candy Theme Rules
|
|
1762
|
+
- Follow AGENTS.md and Candy MCP documentation (call read_candy_guide first).
|
|
1763
|
+
- Preserve merchant content, section IDs, Theme Editor schemas, {{ block.candy_attributes }}, cart/wishlist/auth runtime hooks, and {% hook "..." %} plugin slots.
|
|
1764
|
+
- Use document-level event delegation in assets/theme.js so UI survives live Theme Editor section re-rendering.
|
|
1765
|
+
- Never hardcode merchant products, prices, currencies, payment gateways, or secrets.
|
|
1766
|
+
- Verify changes with caartzee-theme doctor ., caartzee-theme validate ., caartzee-theme test . --json, and caartzee-theme build ..
|
|
1767
|
+
`);
|
|
1768
|
+
}
|
|
1290
1769
|
writeFile("snippets/product-card.candy", candyStarterProductCard);
|
|
1770
|
+
const resolvedPreset = resolveDesignPreset(preset);
|
|
1291
1771
|
writeFile("schemas/settings_schema.json", JSON.stringify([
|
|
1292
1772
|
{
|
|
1293
1773
|
name: "Colors",
|
|
1294
1774
|
settings: [
|
|
1295
|
-
{ id: "primary_color", type: "color", label: "Primary Color", default:
|
|
1775
|
+
{ id: "primary_color", type: "color", label: "Primary Color", default: resolvedPreset.tokens.colors.primary },
|
|
1776
|
+
{ id: "accent_color", type: "color", label: "Accent Color", default: resolvedPreset.tokens.colors.accent },
|
|
1777
|
+
{ id: "background_color", type: "color", label: "Background Color", default: resolvedPreset.tokens.colors.background },
|
|
1778
|
+
{ id: "text_color", type: "color", label: "Text Color", default: resolvedPreset.tokens.colors.text }
|
|
1779
|
+
]
|
|
1780
|
+
},
|
|
1781
|
+
{
|
|
1782
|
+
name: "Typography",
|
|
1783
|
+
settings: [
|
|
1784
|
+
{ id: "heading_font", type: "font", label: "Heading Font", default: resolvedPreset.tokens.typography.headingFont },
|
|
1785
|
+
{ id: "body_font", type: "font", label: "Body Font", default: resolvedPreset.tokens.typography.bodyFont }
|
|
1296
1786
|
]
|
|
1297
1787
|
}
|
|
1298
1788
|
], null, 2));
|
|
1299
|
-
writeFile("assets/theme.css",
|
|
1789
|
+
writeFile("assets/theme.css", buildCandyDesignSystemCss(resolvedPreset));
|
|
1300
1790
|
writeFile("assets/theme.js", `window.__CAARTZEE_CANDY_THEME__ = true;
|
|
1791
|
+
document.addEventListener('caartzee:section:load', function () {
|
|
1792
|
+
// Re-initialize any section-specific UI widgets after Theme Editor live swaps.
|
|
1793
|
+
});
|
|
1301
1794
|
`);
|
|
1302
1795
|
writeFile("locales/en.default.json", JSON.stringify({
|
|
1303
1796
|
general: {
|
|
@@ -2322,13 +2815,94 @@ ${cssBlocks.join(`
|
|
|
2322
2815
|
|
|
2323
2816
|
// src/dev-server/theme-preview.ts
|
|
2324
2817
|
var escape = (value) => String(value ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]);
|
|
2325
|
-
function
|
|
2818
|
+
function renderBuiltInCommerceShellPage(context) {
|
|
2819
|
+
const ctx = context;
|
|
2820
|
+
const cart = ctx.cart || { items: [], subtotal: 0, discount: 0, tax: 0, shipping: 0, total: 0, itemCount: 0 };
|
|
2821
|
+
const customer = ctx.customer || { loggedIn: false, orders: [] };
|
|
2822
|
+
const orders = Array.isArray(ctx.orders) ? ctx.orders : [];
|
|
2823
|
+
if (context.pageType === "login") {
|
|
2824
|
+
return `<section style="max-width:420px;margin:48px auto;padding:24px;border:1px solid #e2e8f0;border-radius:12px;">
|
|
2825
|
+
<h1 style="margin:0 0 8px;">Customer Sign In</h1>
|
|
2826
|
+
<p style="font-size:13px;color:#64748b;margin:0 0 16px;">Sandbox demo account: <code>demo@caartzee.local</code> / <code>password123</code></p>
|
|
2827
|
+
<form action="/_api/auth/login" method="POST" class="js-auth-form" data-redirect="/account" style="display:grid;gap:12px;">
|
|
2828
|
+
<input name="email" type="email" required placeholder="Email" value="demo@caartzee.local" style="padding:10px;border:1px solid #cbd5e1;border-radius:8px;" />
|
|
2829
|
+
<input name="password" type="password" required placeholder="Password" value="password123" style="padding:10px;border:1px solid #cbd5e1;border-radius:8px;" />
|
|
2830
|
+
<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>
|
|
2831
|
+
<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>
|
|
2832
|
+
</form>
|
|
2833
|
+
<p style="font-size:13px;margin-top:14px;">New shopper? <a href="/register">Create an account</a></p>
|
|
2834
|
+
</section>`;
|
|
2835
|
+
}
|
|
2836
|
+
if (context.pageType === "signup") {
|
|
2837
|
+
return `<section style="max-width:440px;margin:48px auto;padding:24px;border:1px solid #e2e8f0;border-radius:12px;">
|
|
2838
|
+
<h1 style="margin:0 0 16px;">Create Customer Account</h1>
|
|
2839
|
+
<form action="/_api/auth/register" method="POST" class="js-auth-form" data-redirect="/account" style="display:grid;gap:12px;">
|
|
2840
|
+
<input name="firstName" required placeholder="First Name" style="padding:10px;border:1px solid #cbd5e1;border-radius:8px;" />
|
|
2841
|
+
<input name="lastName" placeholder="Last Name" style="padding:10px;border:1px solid #cbd5e1;border-radius:8px;" />
|
|
2842
|
+
<input name="email" type="email" required placeholder="Email" style="padding:10px;border:1px solid #cbd5e1;border-radius:8px;" />
|
|
2843
|
+
<input name="password" type="password" minlength="6" required placeholder="Password" style="padding:10px;border:1px solid #cbd5e1;border-radius:8px;" />
|
|
2844
|
+
<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>
|
|
2845
|
+
</form>
|
|
2846
|
+
</section>`;
|
|
2847
|
+
}
|
|
2848
|
+
if (context.pageType === "checkout") {
|
|
2849
|
+
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("");
|
|
2850
|
+
return `<section style="max-width:720px;margin:40px auto;padding:24px;border:1px solid #e2e8f0;border-radius:12px;">
|
|
2851
|
+
<h1 style="margin:0 0 6px;">Caartzee Sandbox Checkout</h1>
|
|
2852
|
+
<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>
|
|
2853
|
+
<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>
|
|
2854
|
+
<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>
|
|
2855
|
+
<form class="js-checkout-form" style="display:grid;gap:10px;">
|
|
2856
|
+
<input name="fullName" required placeholder="Full Name" value="${escape(customer.name || "Sandbox Shopper")}" style="padding:10px;border:1px solid #cbd5e1;border-radius:8px;" />
|
|
2857
|
+
<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;" />
|
|
2858
|
+
<input name="address1" required placeholder="Street Address" value="100 Sandbox Way" style="padding:10px;border:1px solid #cbd5e1;border-radius:8px;" />
|
|
2859
|
+
<input name="city" required placeholder="City" value="Testville" style="padding:10px;border:1px solid #cbd5e1;border-radius:8px;" />
|
|
2860
|
+
<input type="hidden" name="gateway" value="caartzee_test_sandbox" />
|
|
2861
|
+
<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>
|
|
2862
|
+
</form>
|
|
2863
|
+
</section>`;
|
|
2864
|
+
}
|
|
2865
|
+
if (context.pageType === "account") {
|
|
2866
|
+
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("");
|
|
2867
|
+
return `<section style="max-width:720px;margin:40px auto;padding:24px;border:1px solid #e2e8f0;border-radius:12px;">
|
|
2868
|
+
<div style="display:flex;justify-content:space-between;align-items:center;">
|
|
2869
|
+
<h1 style="margin:0;">Customer Account</h1>
|
|
2870
|
+
${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>'}
|
|
2871
|
+
</div>
|
|
2872
|
+
<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>
|
|
2873
|
+
<h3>Sandbox Order History (${orders.length})</h3>
|
|
2874
|
+
<ul style="list-style:none;padding:0;">${orderRows || "<li>No sandbox orders placed yet.</li>"}</ul>
|
|
2875
|
+
</section>`;
|
|
2876
|
+
}
|
|
2877
|
+
if (context.pageType === "order-success") {
|
|
2878
|
+
const latest = orders[0];
|
|
2879
|
+
return `<section style="max-width:600px;margin:48px auto;padding:24px;border:1px solid #bbf7d0;background:#f0fdf4;border-radius:12px;">
|
|
2880
|
+
<h1 style="margin:0 0 8px;color:#166534;">Sandbox Order Confirmed</h1>
|
|
2881
|
+
<p>${latest ? `Order <strong>${escape(latest.orderNumber)}</strong> placed for $${Number(latest.total).toFixed(2)} via sandbox payment.` : "Order confirmed in sandbox session."}</p>
|
|
2882
|
+
<p><a href="/account">View Order History</a> · <a href="/track-order">Track Order</a></p>
|
|
2883
|
+
</section>`;
|
|
2884
|
+
}
|
|
2885
|
+
if (context.pageType === "track-order") {
|
|
2886
|
+
const latest = orders[0];
|
|
2887
|
+
return `<section style="max-width:600px;margin:48px auto;padding:24px;border:1px solid #e2e8f0;border-radius:12px;">
|
|
2888
|
+
<h1 style="margin:0 0 12px;">Track Sandbox Order</h1>
|
|
2889
|
+
<p>${latest ? `Latest sandbox order <strong>${escape(latest.orderNumber)}</strong> — Status: <strong>${escape(latest.status)}</strong>` : "No sandbox orders in this session yet."}</p>
|
|
2890
|
+
</section>`;
|
|
2891
|
+
}
|
|
2892
|
+
return null;
|
|
2893
|
+
}
|
|
2894
|
+
function renderThemePreview(theme, context, preferContextSettings = false, editorOverride) {
|
|
2326
2895
|
const key = context.pageType === "product-list" ? "products" : context.pageType;
|
|
2327
2896
|
const page = theme.defaultTemplates.pages[key] || theme.defaultTemplates.pages[context.pageType];
|
|
2328
2897
|
const settings = theme.manifest.defaultGlobalSettings || {};
|
|
2329
|
-
context = {
|
|
2330
|
-
|
|
2331
|
-
|
|
2898
|
+
context = {
|
|
2899
|
+
...context,
|
|
2900
|
+
themeSlug: theme.slug,
|
|
2901
|
+
globalSettings: preferContextSettings ? { ...settings, ...context.globalSettings, ...editorOverride?.globalSettings || {} } : { ...context.globalSettings, ...settings, ...editorOverride?.globalSettings || {} }
|
|
2902
|
+
};
|
|
2903
|
+
if (context.pageType === "home") {
|
|
2904
|
+
context = { ...context, sections: editorOverride?.bodySections || page?.regions.body || [] };
|
|
2905
|
+
}
|
|
2332
2906
|
const render = (section) => {
|
|
2333
2907
|
const definition = theme.manifest.sections.find((s) => s.type === section.type);
|
|
2334
2908
|
const defaults = Object.fromEntries((definition?.settings || []).map((f) => [f.id, f.default]));
|
|
@@ -2349,15 +2923,23 @@ function renderThemePreview(theme, context, preferContextSettings = false) {
|
|
|
2349
2923
|
}
|
|
2350
2924
|
}), { section: resolved, themeSlug: theme.slug });
|
|
2351
2925
|
};
|
|
2352
|
-
const
|
|
2353
|
-
const
|
|
2926
|
+
const activeLayout = editorOverride?.layout || theme.defaultTemplates.layout;
|
|
2927
|
+
const header = (activeLayout.regions.header || []).map(render).join("");
|
|
2928
|
+
const footer = (activeLayout.regions.footer || []).map(render).join("");
|
|
2354
2929
|
const custom = theme.renderPage?.(context);
|
|
2355
2930
|
if (custom?.trimStart().toLowerCase().startsWith("<!doctype html"))
|
|
2356
2931
|
return custom;
|
|
2357
|
-
const body = custom || (page?.regions.body || []).map(render).join("");
|
|
2932
|
+
const body = custom || renderBuiltInCommerceShellPage(context) || (context.pageType === "home" ? editorOverride?.bodySections || page?.regions.body || [] : page?.regions.body || []).map(render).join("");
|
|
2358
2933
|
const missing = !body ? `<p>No template implemented for ${escape(context.pageType)}.</p>` : "";
|
|
2359
2934
|
const colors = theme.tokens?.colors || {};
|
|
2360
|
-
const variables = Object.entries({
|
|
2935
|
+
const variables = Object.entries({
|
|
2936
|
+
bg: colors.background,
|
|
2937
|
+
surface: colors.surface,
|
|
2938
|
+
text: colors.text,
|
|
2939
|
+
"text-muted": colors.muted,
|
|
2940
|
+
border: colors.border,
|
|
2941
|
+
primary: colors.primary
|
|
2942
|
+
}).filter(([, value]) => value).map(([k, value]) => `--sf-color-${k}:${value};`).join("");
|
|
2361
2943
|
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)}`;
|
|
2362
2944
|
const themeCss = (tokenCss + (theme.tokens?.customCss || "")).replace(/<\/style/gi, "<\\/style");
|
|
2363
2945
|
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>`;
|
|
@@ -3225,6 +3807,7 @@ var SettingTypeSchema = z3.enum([
|
|
|
3225
3807
|
"radio",
|
|
3226
3808
|
"color",
|
|
3227
3809
|
"image",
|
|
3810
|
+
"image_picker",
|
|
3228
3811
|
"select",
|
|
3229
3812
|
"range",
|
|
3230
3813
|
"url",
|
|
@@ -4398,7 +4981,8 @@ function normalizeProductForCandy(product) {
|
|
|
4398
4981
|
const inventoryQuantity = Number(p.inventory_quantity ?? p.stockCount ?? (available ? 10 : 0));
|
|
4399
4982
|
const featuredImage = String(p.featured_image ?? p.imageUrl ?? p.image ?? "/assets/placeholder-product.svg");
|
|
4400
4983
|
const galleryImages = Array.isArray(p.images) && p.images.length > 0 ? p.images : Array.isArray(p.galleryImages) && p.galleryImages.length > 0 ? p.galleryImages : [featuredImage];
|
|
4401
|
-
const
|
|
4984
|
+
const rawUrl = String(p.url ?? p.productUrl ?? "").trim();
|
|
4985
|
+
const url = rawUrl.startsWith("/products/") ? rawUrl : `/products/${encodeURIComponent(handle)}`;
|
|
4402
4986
|
const description = String(p.description ?? p.summary ?? p.shortDescription ?? "");
|
|
4403
4987
|
const rawVariants = Array.isArray(p.variants) ? p.variants : Array.isArray(p.inventoryDetails) && p.inventoryDetails.length > 0 ? p.inventoryDetails.map((inv, idx) => ({
|
|
4404
4988
|
id: inv.id ?? `${id}-var-${idx + 1}`,
|
|
@@ -4508,6 +5092,7 @@ function normalizeCartForCandy(rawCart) {
|
|
|
4508
5092
|
const linePrice = item.line_price !== undefined ? Number(item.line_price) : item.final_line_price !== undefined ? Number(item.final_line_price) : price * qty;
|
|
4509
5093
|
const slug = String(item.handle ?? item.productSlug ?? item.slug ?? `item-${idx + 1}`);
|
|
4510
5094
|
const title = String(item.title ?? item.productName ?? item.name ?? "Item");
|
|
5095
|
+
const resolvedImage = String(item.image || item.imageUrl || item.img_url || item.image_url || item.product?.imageUrl || item.product?.image || "/assets/placeholder-product.svg");
|
|
4511
5096
|
return {
|
|
4512
5097
|
...item,
|
|
4513
5098
|
productId: item.productId ?? item.product_id ?? item.product?.id ?? item.id,
|
|
@@ -4524,9 +5109,9 @@ function normalizeCartForCandy(rawCart) {
|
|
|
4524
5109
|
line_price: linePrice,
|
|
4525
5110
|
final_line_price: linePrice,
|
|
4526
5111
|
url: String(item.url ?? `/products/${slug}`),
|
|
4527
|
-
image:
|
|
5112
|
+
image: resolvedImage,
|
|
4528
5113
|
featured_image: {
|
|
4529
|
-
url:
|
|
5114
|
+
url: resolvedImage,
|
|
4530
5115
|
alt: title
|
|
4531
5116
|
}
|
|
4532
5117
|
};
|
|
@@ -4720,7 +5305,47 @@ function buildCandyContext(options) {
|
|
|
4720
5305
|
`--font-body: ${mergedSettings.body_font};`
|
|
4721
5306
|
].join(" ");
|
|
4722
5307
|
const robotsMeta = pageContext.isPreview ? '<meta name="robots" content="noindex, nofollow" />' : '<meta name="robots" content="index, follow" />';
|
|
4723
|
-
const
|
|
5308
|
+
const hookNames = [
|
|
5309
|
+
"head_scripts",
|
|
5310
|
+
"body_start",
|
|
5311
|
+
"body_end",
|
|
5312
|
+
"header_actions",
|
|
5313
|
+
"header_announcement_before",
|
|
5314
|
+
"header_announcement_after",
|
|
5315
|
+
"footer_widgets_before",
|
|
5316
|
+
"footer_widgets_after",
|
|
5317
|
+
"footer_bottom",
|
|
5318
|
+
"login_form_top",
|
|
5319
|
+
"login_form_bottom",
|
|
5320
|
+
"signup_form_top",
|
|
5321
|
+
"signup_form_bottom",
|
|
5322
|
+
"product_price_after",
|
|
5323
|
+
"product_add_to_cart_before",
|
|
5324
|
+
"product_add_to_cart_after",
|
|
5325
|
+
"product_description_after",
|
|
5326
|
+
"product_reviews",
|
|
5327
|
+
"cart_items_after",
|
|
5328
|
+
"cart_drawer_bottom",
|
|
5329
|
+
"cart_summary_after",
|
|
5330
|
+
"checkout_payment_methods",
|
|
5331
|
+
"checkout_summary_after",
|
|
5332
|
+
"account_dashboard_top",
|
|
5333
|
+
"account_dashboard_bottom"
|
|
5334
|
+
];
|
|
5335
|
+
const hooksApi = pageContext.hooks;
|
|
5336
|
+
const extraHookKeys = hooksApi?.slots && typeof hooksApi.slots === "object" ? Object.keys(hooksApi.slots) : [];
|
|
5337
|
+
const allHookKeys = Array.from(new Set([...hookNames, ...extraHookKeys]));
|
|
5338
|
+
const renderedHooks = {};
|
|
5339
|
+
for (const key of allHookKeys) {
|
|
5340
|
+
let raw = "";
|
|
5341
|
+
if (typeof hooksApi?.render === "function") {
|
|
5342
|
+
raw = String(hooksApi.render(key) || "");
|
|
5343
|
+
} else if (typeof hooksApi?.[key] === "string") {
|
|
5344
|
+
raw = hooksApi[key];
|
|
5345
|
+
}
|
|
5346
|
+
renderedHooks[key] = raw ? markSafeHtml(raw) : "";
|
|
5347
|
+
}
|
|
5348
|
+
const hookScripts = typeof hooksApi?.render === "function" ? hooksApi.render("head_scripts") : hooksApi?.headEnd || "";
|
|
4724
5349
|
const headerHtml = [
|
|
4725
5350
|
`<meta name="generator" content="Caartzee Candy Engine 1.0" />`,
|
|
4726
5351
|
robotsMeta,
|
|
@@ -4790,6 +5415,17 @@ function buildCandyContext(options) {
|
|
|
4790
5415
|
image: campaign.imageUrl || campaign.image,
|
|
4791
5416
|
url: `/campaign/${encodeURIComponent(String(campaign.slug || campaign.id))}`
|
|
4792
5417
|
})),
|
|
5418
|
+
mobile_sliders: (Array.isArray(anyCtx.mobileSliders) ? anyCtx.mobileSliders : []).map((slide, idx) => ({
|
|
5419
|
+
id: slide.id ?? `slide-${idx + 1}`,
|
|
5420
|
+
title: String(slide.title || ""),
|
|
5421
|
+
description: String(slide.description || ""),
|
|
5422
|
+
image: String(slide.imageUrl || slide.image_url || slide.image || ""),
|
|
5423
|
+
image_url: String(slide.imageUrl || slide.image_url || slide.image || ""),
|
|
5424
|
+
button_text: String(slide.button_text || slide.buttonText || ""),
|
|
5425
|
+
button_url: String(slide.button_url || slide.buttonUrl || slide.url || "/products"),
|
|
5426
|
+
campaign: slide.campaign ? String(slide.campaign) : "",
|
|
5427
|
+
category: slide.category ? String(slide.category) : ""
|
|
5428
|
+
})),
|
|
4793
5429
|
recent_products: (anyCtx.recentProducts || []).map(normalizeProductForCandy),
|
|
4794
5430
|
collection: activeCollection,
|
|
4795
5431
|
current_category: activeCategory ? activeCollection : null,
|
|
@@ -4807,6 +5443,10 @@ function buildCandyContext(options) {
|
|
|
4807
5443
|
wishlist: pageContext.pageType === "wishlist" ? (anyCtx.items || []).map(normalizeProductForCandy) : [],
|
|
4808
5444
|
related_products: (anyCtx.relatedProducts || []).map(normalizeProductForCandy),
|
|
4809
5445
|
customer: anyCtx.customer || null,
|
|
5446
|
+
redirect_url: String(anyCtx.redirectUrl || "/account"),
|
|
5447
|
+
error: anyCtx.error ? String(anyCtx.error) : "",
|
|
5448
|
+
firebase_auth_enabled: Boolean(mergedSettings.firebaseAuthEnabled || mergedSettings.firebase?.enabled || anyCtx.bootstrap?.auth?.firebase?.enabled),
|
|
5449
|
+
google_auth_enabled: Boolean(mergedSettings.firebaseAuthEnabled || mergedSettings.firebase?.enabled || anyCtx.bootstrap?.auth?.firebase?.enabled),
|
|
4810
5450
|
order: anyCtx.order || null,
|
|
4811
5451
|
orders: anyCtx.orders || [],
|
|
4812
5452
|
blogs: anyCtx.blogs || [],
|
|
@@ -4825,6 +5465,7 @@ function buildCandyContext(options) {
|
|
|
4825
5465
|
currencyPosition
|
|
4826
5466
|
},
|
|
4827
5467
|
nonce: pageContext.nonce,
|
|
5468
|
+
hooks: renderedHooks,
|
|
4828
5469
|
is_preview: Boolean(pageContext.isPreview),
|
|
4829
5470
|
content_for_header: markSafeHtml(headerHtml),
|
|
4830
5471
|
content_for_layout: markSafeHtml(contentForLayout || ""),
|
|
@@ -5737,6 +6378,27 @@ function registerCandyTags(liquid, options = {}) {
|
|
|
5737
6378
|
}
|
|
5738
6379
|
}
|
|
5739
6380
|
liquid.registerTag("form", FormTag);
|
|
6381
|
+
|
|
6382
|
+
class HookTag extends Tag {
|
|
6383
|
+
hookName;
|
|
6384
|
+
constructor(tagToken, remainTokens, liquidInstance) {
|
|
6385
|
+
super(tagToken, remainTokens, liquidInstance);
|
|
6386
|
+
this.hookName = tagToken.args.trim().replace(/^['"]|['"]$/g, "");
|
|
6387
|
+
}
|
|
6388
|
+
*render(ctx, emitter) {
|
|
6389
|
+
if (!this.hookName)
|
|
6390
|
+
return;
|
|
6391
|
+
const all = ctx.getAll();
|
|
6392
|
+
const hooksObj = all?.hooks;
|
|
6393
|
+
if (!hooksObj)
|
|
6394
|
+
return;
|
|
6395
|
+
const val = hooksObj[this.hookName];
|
|
6396
|
+
if (val) {
|
|
6397
|
+
emitter.write(String(val));
|
|
6398
|
+
}
|
|
6399
|
+
}
|
|
6400
|
+
}
|
|
6401
|
+
liquid.registerTag("hook", HookTag);
|
|
5740
6402
|
}
|
|
5741
6403
|
|
|
5742
6404
|
// src/candy/types.ts
|
|
@@ -6203,13 +6865,45 @@ function loadCandyThemeFromSource(source, fallbackSlug = "candy-theme") {
|
|
|
6203
6865
|
}
|
|
6204
6866
|
}
|
|
6205
6867
|
}
|
|
6868
|
+
let globalSettingsSchema = rawManifestJson.globalSettingsSchema;
|
|
6869
|
+
const extractedGlobalDefaults = {};
|
|
6206
6870
|
for (const entry of source.list("schemas")) {
|
|
6207
6871
|
if (!entry.endsWith(".json"))
|
|
6208
6872
|
continue;
|
|
6209
6873
|
const path = `schemas/${entry}`;
|
|
6210
6874
|
try {
|
|
6211
6875
|
const parsed = JSON.parse(source.read(path) ?? "");
|
|
6212
|
-
if (
|
|
6876
|
+
if (entry === "settings_schema.json") {
|
|
6877
|
+
const rawCategories = Array.isArray(parsed) ? parsed : Array.isArray(parsed?.categories) ? parsed.categories : [];
|
|
6878
|
+
const normalizedCategories = rawCategories.filter((cat) => cat && typeof cat === "object" && Array.isArray(cat.settings)).map((cat, idx) => {
|
|
6879
|
+
const catName = String(cat.name || cat.label || `group-${idx + 1}`).trim();
|
|
6880
|
+
const slugName = catName.toLowerCase().replace(/[^a-z0-9]+/g, "-");
|
|
6881
|
+
const settings = cat.settings.filter((f) => f && typeof f === "object" && f.id && f.type).map((f) => {
|
|
6882
|
+
if (f.default !== undefined)
|
|
6883
|
+
extractedGlobalDefaults[String(f.id)] = f.default;
|
|
6884
|
+
return {
|
|
6885
|
+
id: String(f.id),
|
|
6886
|
+
type: f.type === "image_picker" ? "image" : f.type,
|
|
6887
|
+
label: String(f.label || f.id),
|
|
6888
|
+
...f.default !== undefined ? { default: f.default } : {},
|
|
6889
|
+
...Array.isArray(f.options) ? { options: f.options } : {},
|
|
6890
|
+
...typeof f.min === "number" ? { min: f.min } : {},
|
|
6891
|
+
...typeof f.max === "number" ? { max: f.max } : {},
|
|
6892
|
+
...typeof f.step === "number" ? { step: f.step } : {},
|
|
6893
|
+
...typeof f.placeholder === "string" ? { placeholder: f.placeholder } : {}
|
|
6894
|
+
};
|
|
6895
|
+
});
|
|
6896
|
+
return {
|
|
6897
|
+
name: slugName,
|
|
6898
|
+
label: String(cat.label || cat.name || `Settings ${idx + 1}`),
|
|
6899
|
+
...cat.description ? { description: String(cat.description) } : {},
|
|
6900
|
+
settings
|
|
6901
|
+
};
|
|
6902
|
+
});
|
|
6903
|
+
if (normalizedCategories.length > 0) {
|
|
6904
|
+
globalSettingsSchema = { categories: normalizedCategories };
|
|
6905
|
+
}
|
|
6906
|
+
} else if (parsed && typeof parsed === "object" && parsed.type && !sectionSchemas[parsed.type]) {
|
|
6213
6907
|
const check = SectionManifestSchema.safeParse(parsed);
|
|
6214
6908
|
if (check.success)
|
|
6215
6909
|
sectionSchemas[check.data.type] = check.data;
|
|
@@ -6378,9 +7072,12 @@ function loadCandyThemeFromSource(source, fallbackSlug = "candy-theme") {
|
|
|
6378
7072
|
capabilities: rawManifestJson.capabilities,
|
|
6379
7073
|
regions: ["header", "body", "footer"],
|
|
6380
7074
|
sections: compiledSections,
|
|
7075
|
+
...globalSettingsSchema ? { globalSettingsSchema } : {},
|
|
6381
7076
|
tokens,
|
|
6382
|
-
defaultGlobalSettings:
|
|
6383
|
-
storeName: name
|
|
7077
|
+
defaultGlobalSettings: {
|
|
7078
|
+
storeName: name,
|
|
7079
|
+
...extractedGlobalDefaults,
|
|
7080
|
+
...rawManifestJson.defaultGlobalSettings || {}
|
|
6384
7081
|
},
|
|
6385
7082
|
defaultLayout,
|
|
6386
7083
|
defaultPages
|
|
@@ -6485,20 +7182,31 @@ function createCandyStorefrontTheme(bundle, platform = {}) {
|
|
|
6485
7182
|
const resolvedNode = buildDefaultSectionNode(secManifest, ctx.section.id, ctx.section.settings, ctx.section.blocks);
|
|
6486
7183
|
const sectionDrop = decorateSectionNodeForCandy(resolvedNode, secManifest);
|
|
6487
7184
|
if (ctx.pageContext) {
|
|
7185
|
+
const isHeaderSec = secType === "header" || secType.startsWith("header-") || secType === "announcement-bar";
|
|
7186
|
+
const isFooterSec = secType === "footer" || secType.startsWith("footer-");
|
|
7187
|
+
const existingLayout = ctx.pageContext.layoutDocument;
|
|
7188
|
+
const layoutDocument = {
|
|
7189
|
+
regions: {
|
|
7190
|
+
header: isHeaderSec ? [resolvedNode] : existingLayout?.regions?.header || [],
|
|
7191
|
+
footer: isFooterSec ? [resolvedNode] : existingLayout?.regions?.footer || []
|
|
7192
|
+
}
|
|
7193
|
+
};
|
|
6488
7194
|
const fullScope = buildCandyContext({
|
|
6489
7195
|
pageContext: ctx.pageContext,
|
|
6490
7196
|
tokens: bundle.tokens,
|
|
6491
7197
|
defaultGlobalSettings: bundle.manifest.defaultGlobalSettings,
|
|
6492
|
-
layoutDocument
|
|
7198
|
+
layoutDocument,
|
|
6493
7199
|
sectionManifests: bundle.sectionSchemas,
|
|
6494
7200
|
extraContext: usesStorefrontShell ? { section: sectionDrop } : { ...extraScope, section: sectionDrop }
|
|
6495
7201
|
});
|
|
6496
|
-
|
|
7202
|
+
const rendered = engine.renderFileSync(`sections/${secType}.candy`, fullScope);
|
|
7203
|
+
return usesStorefrontShell ? rendered : wrapRenderedSectionHtml(resolvedNode, rendered);
|
|
6497
7204
|
}
|
|
6498
|
-
|
|
7205
|
+
const rendered = engine.renderFileSync(`sections/${secType}.candy`, {
|
|
6499
7206
|
...extraScope,
|
|
6500
7207
|
section: sectionDrop
|
|
6501
7208
|
});
|
|
7209
|
+
return usesStorefrontShell ? rendered : wrapRenderedSectionHtml(resolvedNode, rendered);
|
|
6502
7210
|
};
|
|
6503
7211
|
}
|
|
6504
7212
|
return {
|
|
@@ -6515,6 +7223,7 @@ function createCandyStorefrontTheme(bundle, platform = {}) {
|
|
|
6515
7223
|
return engine.renderPage(pageContext, {
|
|
6516
7224
|
tokens: bundle.tokens,
|
|
6517
7225
|
defaultGlobalSettings: bundle.manifest.defaultGlobalSettings,
|
|
7226
|
+
layoutDocument: pageContext.layoutDocument,
|
|
6518
7227
|
renderBodyOnly: usesStorefrontShell,
|
|
6519
7228
|
renderFallbackPage: platform.renderPage ? () => platform.renderPage?.(pageContext) ?? "" : undefined,
|
|
6520
7229
|
preferDocumentSections: usesStorefrontShell && pageContext.pageType === "custom-page",
|
|
@@ -6545,13 +7254,811 @@ function createCandyStorefrontTheme(bundle, platform = {}) {
|
|
|
6545
7254
|
};
|
|
6546
7255
|
}
|
|
6547
7256
|
|
|
7257
|
+
// src/dev-server/local-commerce-runtime.ts
|
|
7258
|
+
import { randomUUID } from "node:crypto";
|
|
7259
|
+
|
|
7260
|
+
class LocalCommerceStore {
|
|
7261
|
+
sessions = new Map;
|
|
7262
|
+
getOrCreateSession(req, res) {
|
|
7263
|
+
const cookieHeader = req.headers.cookie || "";
|
|
7264
|
+
const match = /(?:^|;\s*)cz_dev_sid=([^;]+)/.exec(cookieHeader);
|
|
7265
|
+
const existingId = match?.[1];
|
|
7266
|
+
if (existingId && this.sessions.has(existingId)) {
|
|
7267
|
+
return this.sessions.get(existingId);
|
|
7268
|
+
}
|
|
7269
|
+
const sessionId = existingId || randomUUID();
|
|
7270
|
+
const defaultCustomer = {
|
|
7271
|
+
id: "dev-cust-1",
|
|
7272
|
+
name: "Demo Shopper",
|
|
7273
|
+
firstName: "Demo",
|
|
7274
|
+
lastName: "Shopper",
|
|
7275
|
+
email: "demo@caartzee.local",
|
|
7276
|
+
addresses: [
|
|
7277
|
+
{
|
|
7278
|
+
id: "addr-1",
|
|
7279
|
+
fullName: "Demo Shopper",
|
|
7280
|
+
address1: "100 Sandbox Ave",
|
|
7281
|
+
city: "Testville",
|
|
7282
|
+
postalCode: "10001",
|
|
7283
|
+
country: "US"
|
|
7284
|
+
}
|
|
7285
|
+
]
|
|
7286
|
+
};
|
|
7287
|
+
const registeredUsers = new Map;
|
|
7288
|
+
registeredUsers.set(defaultCustomer.email, { password: "password123", customer: defaultCustomer });
|
|
7289
|
+
const session = {
|
|
7290
|
+
sessionId,
|
|
7291
|
+
cart: [],
|
|
7292
|
+
couponCode: null,
|
|
7293
|
+
shippingMethod: "standard",
|
|
7294
|
+
wishlist: [],
|
|
7295
|
+
customer: null,
|
|
7296
|
+
registeredUsers,
|
|
7297
|
+
orders: []
|
|
7298
|
+
};
|
|
7299
|
+
this.sessions.set(sessionId, session);
|
|
7300
|
+
res.setHeader("Set-Cookie", `cz_dev_sid=${sessionId}; Path=/; HttpOnly; SameSite=Lax`);
|
|
7301
|
+
return session;
|
|
7302
|
+
}
|
|
7303
|
+
computeTotals(session) {
|
|
7304
|
+
const subtotal = Number(session.cart.reduce((s, item) => s + item.price * item.quantity, 0).toFixed(2));
|
|
7305
|
+
const discount = session.couponCode === "TEST10" ? Number((subtotal * 0.1).toFixed(2)) : 0;
|
|
7306
|
+
const shipping = session.couponCode === "FREESHIP" || subtotal === 0 ? 0 : session.shippingMethod === "express" ? 15 : subtotal >= 100 ? 0 : 8;
|
|
7307
|
+
const taxable = Math.max(0, subtotal - discount);
|
|
7308
|
+
const tax = Number((taxable * 0.08).toFixed(2));
|
|
7309
|
+
const total = Number((taxable + tax + shipping).toFixed(2));
|
|
7310
|
+
const itemCount = session.cart.reduce((s, i) => s + i.quantity, 0);
|
|
7311
|
+
return { subtotal, discount, shipping, tax, total, itemCount };
|
|
7312
|
+
}
|
|
7313
|
+
applySessionToContext(session, context) {
|
|
7314
|
+
const totals = this.computeTotals(session);
|
|
7315
|
+
return {
|
|
7316
|
+
...context,
|
|
7317
|
+
cart: {
|
|
7318
|
+
items: session.cart.map((item) => ({
|
|
7319
|
+
id: item.id,
|
|
7320
|
+
productId: item.productId,
|
|
7321
|
+
variantId: item.variantId,
|
|
7322
|
+
title: item.title,
|
|
7323
|
+
name: item.title,
|
|
7324
|
+
slug: item.slug,
|
|
7325
|
+
price: item.price,
|
|
7326
|
+
quantity: item.quantity,
|
|
7327
|
+
imageUrl: item.imageUrl,
|
|
7328
|
+
lineTotal: Number((item.price * item.quantity).toFixed(2))
|
|
7329
|
+
})),
|
|
7330
|
+
itemCount: totals.itemCount,
|
|
7331
|
+
item_count: totals.itemCount,
|
|
7332
|
+
subtotal: totals.subtotal,
|
|
7333
|
+
discount: totals.discount,
|
|
7334
|
+
tax: totals.tax,
|
|
7335
|
+
shipping: totals.shipping,
|
|
7336
|
+
total: totals.total,
|
|
7337
|
+
couponCode: session.couponCode
|
|
7338
|
+
},
|
|
7339
|
+
wishlist: session.wishlist,
|
|
7340
|
+
wishlistIds: session.wishlist,
|
|
7341
|
+
customer: session.customer ? {
|
|
7342
|
+
loggedIn: true,
|
|
7343
|
+
logged_in: true,
|
|
7344
|
+
...session.customer,
|
|
7345
|
+
orders: session.orders
|
|
7346
|
+
} : { loggedIn: false, logged_in: false, orders: [] },
|
|
7347
|
+
orders: session.orders
|
|
7348
|
+
};
|
|
7349
|
+
}
|
|
7350
|
+
async handleApiRequest(req, res, pathname, searchParams, resolveCatalogProducts) {
|
|
7351
|
+
if (!pathname.startsWith("/_api/"))
|
|
7352
|
+
return false;
|
|
7353
|
+
const session = this.getOrCreateSession(req, res);
|
|
7354
|
+
const method = (req.method || "GET").toUpperCase();
|
|
7355
|
+
const json = (status, body) => {
|
|
7356
|
+
res.writeHead(status, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" });
|
|
7357
|
+
res.end(JSON.stringify(body));
|
|
7358
|
+
return true;
|
|
7359
|
+
};
|
|
7360
|
+
const readBody = async () => {
|
|
7361
|
+
const chunks = [];
|
|
7362
|
+
for await (const chunk of req)
|
|
7363
|
+
chunks.push(Buffer.from(chunk));
|
|
7364
|
+
const raw = Buffer.concat(chunks).toString("utf8").trim();
|
|
7365
|
+
if (!raw)
|
|
7366
|
+
return {};
|
|
7367
|
+
const ct = String(req.headers["content-type"] || "");
|
|
7368
|
+
if (ct.includes("application/x-www-form-urlencoded")) {
|
|
7369
|
+
return Object.fromEntries(new URLSearchParams(raw).entries());
|
|
7370
|
+
}
|
|
7371
|
+
try {
|
|
7372
|
+
return JSON.parse(raw);
|
|
7373
|
+
} catch {
|
|
7374
|
+
return {};
|
|
7375
|
+
}
|
|
7376
|
+
};
|
|
7377
|
+
if (pathname === "/_api/cart") {
|
|
7378
|
+
if (method === "GET") {
|
|
7379
|
+
return json(200, { success: true, items: session.cart, ...this.computeTotals(session), couponCode: session.couponCode });
|
|
7380
|
+
}
|
|
7381
|
+
const body = await readBody();
|
|
7382
|
+
if (method === "POST") {
|
|
7383
|
+
const productId = body.product_id ?? body.productId;
|
|
7384
|
+
const rawVariant = body.variant_id ?? body.variantId ?? null;
|
|
7385
|
+
if (!productId)
|
|
7386
|
+
return json(422, { success: false, message: "product_id is required." });
|
|
7387
|
+
if (typeof rawVariant === "string" && /-default$/i.test(rawVariant)) {
|
|
7388
|
+
return json(422, {
|
|
7389
|
+
success: false,
|
|
7390
|
+
code: "INVALID_VARIANT_ID",
|
|
7391
|
+
message: `Invalid synthetic variant_id "${rawVariant}". Guard data-variant-id with product.has_inventory_variants.`
|
|
7392
|
+
});
|
|
7393
|
+
}
|
|
7394
|
+
const qty = Math.max(1, Number(body.quantity ?? body.qty ?? 1));
|
|
7395
|
+
const products = await resolveCatalogProducts();
|
|
7396
|
+
const found = products.find((p) => String(p.id) === String(productId) || String(p.slug) === String(productId));
|
|
7397
|
+
const title = String(body.title || found?.title || found?.name || `Product #${productId}`);
|
|
7398
|
+
const price = Number(body.price ?? found?.salePrice ?? found?.price ?? 29.99);
|
|
7399
|
+
const slug = String(found?.slug || productId);
|
|
7400
|
+
const imageUrl = String(found?.imageUrl || found?.featured_image || "/assets/placeholder-product.svg");
|
|
7401
|
+
const variantId = rawVariant !== null && rawVariant !== "" ? rawVariant : null;
|
|
7402
|
+
const existing = session.cart.find((i) => String(i.productId) === String(productId) && String(i.variantId ?? "") === String(variantId ?? ""));
|
|
7403
|
+
if (existing)
|
|
7404
|
+
existing.quantity += qty;
|
|
7405
|
+
else
|
|
7406
|
+
session.cart.push({ id: `${productId}:${variantId ?? "base"}`, productId, variantId, title, slug, price, imageUrl, quantity: qty });
|
|
7407
|
+
return json(200, { success: true, items: session.cart, ...this.computeTotals(session) });
|
|
7408
|
+
}
|
|
7409
|
+
if (method === "PATCH" || method === "PUT") {
|
|
7410
|
+
const productId = body.product_id ?? body.productId;
|
|
7411
|
+
const variantId = body.variant_id ?? body.variantId ?? null;
|
|
7412
|
+
const itemId = body.item_id ?? body.itemId;
|
|
7413
|
+
const item = session.cart.find((i) => itemId && i.id === itemId || String(i.productId) === String(productId) && String(i.variantId ?? "") === String(variantId ?? ""));
|
|
7414
|
+
if (!item)
|
|
7415
|
+
return json(404, { success: false, message: "Cart item not found." });
|
|
7416
|
+
const nextQty = body.delta !== undefined ? item.quantity + Number(body.delta) : Number(body.quantity ?? item.quantity);
|
|
7417
|
+
if (nextQty <= 0)
|
|
7418
|
+
session.cart = session.cart.filter((i) => i !== item);
|
|
7419
|
+
else
|
|
7420
|
+
item.quantity = nextQty;
|
|
7421
|
+
return json(200, { success: true, items: session.cart, ...this.computeTotals(session) });
|
|
7422
|
+
}
|
|
7423
|
+
if (method === "DELETE") {
|
|
7424
|
+
const productId = body.product_id ?? body.productId;
|
|
7425
|
+
const variantId = body.variant_id ?? body.variantId ?? null;
|
|
7426
|
+
const itemId = body.item_id ?? body.itemId;
|
|
7427
|
+
if (body.clear) {
|
|
7428
|
+
session.cart = [];
|
|
7429
|
+
} else {
|
|
7430
|
+
session.cart = session.cart.filter((i) => !(itemId && i.id === itemId || String(i.productId) === String(productId) && String(i.variantId ?? "") === String(variantId ?? "")));
|
|
7431
|
+
}
|
|
7432
|
+
return json(200, { success: true, items: session.cart, ...this.computeTotals(session) });
|
|
7433
|
+
}
|
|
7434
|
+
}
|
|
7435
|
+
if (pathname === "/_api/wishlist" && method === "GET") {
|
|
7436
|
+
return json(200, { success: true, items: session.wishlist, count: session.wishlist.length });
|
|
7437
|
+
}
|
|
7438
|
+
if ((pathname === "/_api/wishlist/toggle" || pathname === "/_api/wishlist") && method === "POST") {
|
|
7439
|
+
const body = await readBody();
|
|
7440
|
+
const productId = body.product_id ?? body.productId;
|
|
7441
|
+
if (!productId)
|
|
7442
|
+
return json(422, { success: false, message: "product_id is required." });
|
|
7443
|
+
const idx = session.wishlist.findIndex((id) => String(id) === String(productId));
|
|
7444
|
+
const added = idx < 0;
|
|
7445
|
+
if (added)
|
|
7446
|
+
session.wishlist.push(productId);
|
|
7447
|
+
else
|
|
7448
|
+
session.wishlist.splice(idx, 1);
|
|
7449
|
+
return json(200, { success: true, added, items: session.wishlist, count: session.wishlist.length });
|
|
7450
|
+
}
|
|
7451
|
+
if (pathname === "/_api/auth/me" && method === "GET") {
|
|
7452
|
+
return json(200, { success: true, authenticated: Boolean(session.customer), customer: session.customer });
|
|
7453
|
+
}
|
|
7454
|
+
if (pathname === "/_api/auth/register" && method === "POST") {
|
|
7455
|
+
const body = await readBody();
|
|
7456
|
+
const email = String(body.email || "").trim().toLowerCase();
|
|
7457
|
+
const password = String(body.password || "");
|
|
7458
|
+
if (!email || !email.includes("@"))
|
|
7459
|
+
return json(422, { success: false, message: "Valid email is required." });
|
|
7460
|
+
if (password.length < 6)
|
|
7461
|
+
return json(422, { success: false, message: "Password must be at least 6 characters." });
|
|
7462
|
+
if (session.registeredUsers.has(email)) {
|
|
7463
|
+
return json(422, { success: false, message: "An account with this email already exists in this dev session." });
|
|
7464
|
+
}
|
|
7465
|
+
const firstName = String(body.firstName || body.name || "Shopper").trim();
|
|
7466
|
+
const lastName = String(body.lastName || "").trim();
|
|
7467
|
+
const customer = {
|
|
7468
|
+
id: `dev-cust-${randomUUID().slice(0, 8)}`,
|
|
7469
|
+
name: [firstName, lastName].filter(Boolean).join(" "),
|
|
7470
|
+
firstName,
|
|
7471
|
+
lastName,
|
|
7472
|
+
email,
|
|
7473
|
+
mobile: body.mobile ? String(body.mobile) : undefined,
|
|
7474
|
+
addresses: []
|
|
7475
|
+
};
|
|
7476
|
+
session.registeredUsers.set(email, { password, customer });
|
|
7477
|
+
session.customer = customer;
|
|
7478
|
+
return json(200, { success: true, authenticated: true, customer, redirect: body.redirect || "/account" });
|
|
7479
|
+
}
|
|
7480
|
+
if (pathname === "/_api/auth/login" && method === "POST") {
|
|
7481
|
+
const body = await readBody();
|
|
7482
|
+
const email = String(body.email || "").trim().toLowerCase();
|
|
7483
|
+
const password = String(body.password || "");
|
|
7484
|
+
const record = session.registeredUsers.get(email);
|
|
7485
|
+
if (!record || record.password !== password) {
|
|
7486
|
+
return json(401, { success: false, message: "Invalid email or password. (Demo account: demo@caartzee.local / password123)" });
|
|
7487
|
+
}
|
|
7488
|
+
session.customer = record.customer;
|
|
7489
|
+
return json(200, { success: true, authenticated: true, customer: record.customer, redirect: body.redirect || "/account" });
|
|
7490
|
+
}
|
|
7491
|
+
if (pathname === "/_api/auth/google" && method === "POST") {
|
|
7492
|
+
const customer = {
|
|
7493
|
+
id: "dev-google-1",
|
|
7494
|
+
name: "Google Sandbox Shopper",
|
|
7495
|
+
firstName: "Google",
|
|
7496
|
+
lastName: "Shopper",
|
|
7497
|
+
email: "google-sandbox@caartzee.local",
|
|
7498
|
+
addresses: []
|
|
7499
|
+
};
|
|
7500
|
+
session.customer = customer;
|
|
7501
|
+
return json(200, { success: true, authenticated: true, provider: "google_sandbox", customer, redirect: "/account" });
|
|
7502
|
+
}
|
|
7503
|
+
if (pathname === "/_api/auth/logout" && method === "POST") {
|
|
7504
|
+
session.customer = null;
|
|
7505
|
+
return json(200, { success: true, authenticated: false, redirect: "/" });
|
|
7506
|
+
}
|
|
7507
|
+
if (pathname === "/_api/checkout" && method === "GET") {
|
|
7508
|
+
return json(200, {
|
|
7509
|
+
success: true,
|
|
7510
|
+
sandboxOnly: true,
|
|
7511
|
+
cart: session.cart,
|
|
7512
|
+
couponCode: session.couponCode,
|
|
7513
|
+
shippingMethod: session.shippingMethod,
|
|
7514
|
+
customer: session.customer,
|
|
7515
|
+
paymentGateways: [{ id: "caartzee_test_sandbox", name: "Caartzee Test Sandbox Payment", sandbox: true }],
|
|
7516
|
+
...this.computeTotals(session)
|
|
7517
|
+
});
|
|
7518
|
+
}
|
|
7519
|
+
if (pathname === "/_api/checkout/shipping" && method === "POST") {
|
|
7520
|
+
const body = await readBody();
|
|
7521
|
+
session.shippingMethod = body.method === "express" ? "express" : "standard";
|
|
7522
|
+
return json(200, { success: true, shippingMethod: session.shippingMethod, ...this.computeTotals(session) });
|
|
7523
|
+
}
|
|
7524
|
+
if (pathname === "/_api/checkout/coupon" && method === "POST") {
|
|
7525
|
+
const body = await readBody();
|
|
7526
|
+
const code = String(body.code || "").trim().toUpperCase();
|
|
7527
|
+
if (!code) {
|
|
7528
|
+
session.couponCode = null;
|
|
7529
|
+
return json(200, { success: true, couponCode: null, ...this.computeTotals(session) });
|
|
7530
|
+
}
|
|
7531
|
+
if (!["TEST10", "FREESHIP"].includes(code)) {
|
|
7532
|
+
return json(422, { success: false, message: "Invalid coupon code. Try TEST10 (10% off) or FREESHIP." });
|
|
7533
|
+
}
|
|
7534
|
+
session.couponCode = code;
|
|
7535
|
+
return json(200, { success: true, couponCode: code, ...this.computeTotals(session) });
|
|
7536
|
+
}
|
|
7537
|
+
if (pathname === "/_api/checkout/address" && method === "POST") {
|
|
7538
|
+
const body = await readBody();
|
|
7539
|
+
const addr = {
|
|
7540
|
+
id: `addr-${randomUUID().slice(0, 6)}`,
|
|
7541
|
+
fullName: String(body.fullName || session.customer?.name || "Sandbox Shopper"),
|
|
7542
|
+
address1: String(body.address1 || "100 Sandbox Way"),
|
|
7543
|
+
city: String(body.city || "Testville"),
|
|
7544
|
+
postalCode: String(body.postalCode || "10001"),
|
|
7545
|
+
country: String(body.country || "US")
|
|
7546
|
+
};
|
|
7547
|
+
if (session.customer)
|
|
7548
|
+
session.customer.addresses.push(addr);
|
|
7549
|
+
return json(200, { success: true, address: addr });
|
|
7550
|
+
}
|
|
7551
|
+
if ((pathname === "/_api/checkout/place-order" || pathname === "/_api/orders") && method === "POST") {
|
|
7552
|
+
const body = await readBody();
|
|
7553
|
+
if (body.gateway && body.gateway !== "caartzee_test_sandbox") {
|
|
7554
|
+
return json(422, { success: false, message: 'Only sandbox payment gateway "caartzee_test_sandbox" is allowed in dev mode.' });
|
|
7555
|
+
}
|
|
7556
|
+
if (session.cart.length === 0) {
|
|
7557
|
+
return json(422, { success: false, message: "Your cart is empty." });
|
|
7558
|
+
}
|
|
7559
|
+
const totals = this.computeTotals(session);
|
|
7560
|
+
const order = {
|
|
7561
|
+
orderNumber: `CZ-DEV-${Date.now().toString().slice(-6)}`,
|
|
7562
|
+
status: "placed",
|
|
7563
|
+
paymentMode: "sandbox",
|
|
7564
|
+
paymentGateway: "caartzee_test_sandbox",
|
|
7565
|
+
customerEmail: String(body.email || session.customer?.email || "guest@caartzee.local"),
|
|
7566
|
+
shippingAddress: {
|
|
7567
|
+
fullName: String(body.fullName || session.customer?.name || "Sandbox Shopper"),
|
|
7568
|
+
address1: String(body.address1 || "100 Sandbox Way"),
|
|
7569
|
+
city: String(body.city || "Testville"),
|
|
7570
|
+
postalCode: String(body.postalCode || "10001"),
|
|
7571
|
+
country: String(body.country || "US")
|
|
7572
|
+
},
|
|
7573
|
+
shippingMethod: session.shippingMethod,
|
|
7574
|
+
subtotal: totals.subtotal,
|
|
7575
|
+
discount: totals.discount,
|
|
7576
|
+
tax: totals.tax,
|
|
7577
|
+
shipping: totals.shipping,
|
|
7578
|
+
total: totals.total,
|
|
7579
|
+
items: [...session.cart],
|
|
7580
|
+
createdAt: new Date().toISOString()
|
|
7581
|
+
};
|
|
7582
|
+
session.orders.unshift(order);
|
|
7583
|
+
session.cart = [];
|
|
7584
|
+
session.couponCode = null;
|
|
7585
|
+
return json(200, { success: true, sandboxOnly: true, order, redirect: `/order-success?order=${encodeURIComponent(order.orderNumber)}` });
|
|
7586
|
+
}
|
|
7587
|
+
if (pathname === "/_api/orders" && method === "GET") {
|
|
7588
|
+
return json(200, { success: true, orders: session.orders });
|
|
7589
|
+
}
|
|
7590
|
+
if (pathname === "/_api/orders/track" && method === "GET") {
|
|
7591
|
+
const orderNumber = searchParams.get("orderNumber") || searchParams.get("order") || "";
|
|
7592
|
+
const order = session.orders.find((o) => o.orderNumber === orderNumber) || null;
|
|
7593
|
+
if (!order)
|
|
7594
|
+
return json(404, { success: false, message: "Sandbox order not found in this dev session." });
|
|
7595
|
+
return json(200, { success: true, order });
|
|
7596
|
+
}
|
|
7597
|
+
return false;
|
|
7598
|
+
}
|
|
7599
|
+
}
|
|
7600
|
+
function buildStorefrontShellRuntimeScript(options) {
|
|
7601
|
+
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";
|
|
7602
|
+
return `<script data-caartzee-dev-shell="true">
|
|
7603
|
+
(function(){
|
|
7604
|
+
if (window.__CAARTZEE_DEV_SHELL_INIT__) return;
|
|
7605
|
+
window.__CAARTZEE_DEV_SHELL_INIT__ = true;
|
|
7606
|
+
|
|
7607
|
+
function toast(msg, isErr) {
|
|
7608
|
+
var el = document.getElementById('cz-dev-toast');
|
|
7609
|
+
if (!el) {
|
|
7610
|
+
el = document.createElement('div');
|
|
7611
|
+
el.id = 'cz-dev-toast';
|
|
7612
|
+
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;';
|
|
7613
|
+
document.body.appendChild(el);
|
|
7614
|
+
}
|
|
7615
|
+
el.style.background = isErr ? '#dc2626' : '#0f172a';
|
|
7616
|
+
el.textContent = msg;
|
|
7617
|
+
el.style.opacity = '1';
|
|
7618
|
+
clearTimeout(window.__czToastT);
|
|
7619
|
+
window.__czToastT = setTimeout(function(){ el.style.opacity = '0'; }, 2800);
|
|
7620
|
+
}
|
|
7621
|
+
|
|
7622
|
+
function updateCartBadges(count) {
|
|
7623
|
+
document.querySelectorAll('.js-cart-count, [data-cart-count]').forEach(function(el) {
|
|
7624
|
+
el.textContent = String(count);
|
|
7625
|
+
el.setAttribute('data-cart-count', String(count));
|
|
7626
|
+
});
|
|
7627
|
+
}
|
|
7628
|
+
|
|
7629
|
+
// Sync cart badge on load
|
|
7630
|
+
fetch('/_api/cart').then(function(r){ return r.json(); }).then(function(d){
|
|
7631
|
+
if (d && typeof d.itemCount === 'number') updateCartBadges(d.itemCount);
|
|
7632
|
+
}).catch(function(){});
|
|
7633
|
+
|
|
7634
|
+
// Event-delegated runtime (survives Theme Editor live section re-renders!)
|
|
7635
|
+
document.addEventListener('click', function(e) {
|
|
7636
|
+
var addBtn = e.target.closest && e.target.closest('.js-add-to-cart');
|
|
7637
|
+
if (addBtn) {
|
|
7638
|
+
e.preventDefault();
|
|
7639
|
+
var productId = addBtn.getAttribute('data-product-id');
|
|
7640
|
+
var variantId = addBtn.getAttribute('data-variant-id');
|
|
7641
|
+
var qtyInput = document.querySelector('[data-product-quantity]');
|
|
7642
|
+
var quantity = Number(addBtn.getAttribute('data-qty') || (qtyInput && qtyInput.value) || 1);
|
|
7643
|
+
var payload = { product_id: productId, quantity: quantity };
|
|
7644
|
+
if (variantId) payload.variant_id = variantId;
|
|
7645
|
+
fetch('/_api/cart', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) })
|
|
7646
|
+
.then(function(r){ return r.json().then(function(d){ return { ok: r.ok, d: d }; }); })
|
|
7647
|
+
.then(function(res){
|
|
7648
|
+
if (!res.ok) { toast(res.d.message || 'Add to cart failed', true); return; }
|
|
7649
|
+
updateCartBadges(res.d.itemCount || 0);
|
|
7650
|
+
toast('Added to sandbox cart (' + (res.d.itemCount || 0) + ' items)');
|
|
7651
|
+
});
|
|
7652
|
+
return;
|
|
7653
|
+
}
|
|
7654
|
+
|
|
7655
|
+
var wishBtn = e.target.closest && e.target.closest('.js-wishlist-toggle');
|
|
7656
|
+
if (wishBtn) {
|
|
7657
|
+
e.preventDefault();
|
|
7658
|
+
var pid = wishBtn.getAttribute('data-product-id');
|
|
7659
|
+
fetch('/_api/wishlist/toggle', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ product_id: pid }) })
|
|
7660
|
+
.then(function(r){ return r.json(); })
|
|
7661
|
+
.then(function(d){
|
|
7662
|
+
wishBtn.classList.toggle('is-active', Boolean(d.added));
|
|
7663
|
+
toast(d.added ? 'Saved to sandbox wishlist' : 'Removed from sandbox wishlist');
|
|
7664
|
+
});
|
|
7665
|
+
return;
|
|
7666
|
+
}
|
|
7667
|
+
|
|
7668
|
+
var qtyBtn = e.target.closest && e.target.closest('.js-cart-qty-btn');
|
|
7669
|
+
if (qtyBtn) {
|
|
7670
|
+
e.preventDefault();
|
|
7671
|
+
fetch('/_api/cart', {
|
|
7672
|
+
method: 'PATCH',
|
|
7673
|
+
headers: { 'Content-Type': 'application/json' },
|
|
7674
|
+
body: JSON.stringify({
|
|
7675
|
+
product_id: qtyBtn.getAttribute('data-product-id'),
|
|
7676
|
+
variant_id: qtyBtn.getAttribute('data-variant-id') || null,
|
|
7677
|
+
delta: Number(qtyBtn.getAttribute('data-delta') || 1),
|
|
7678
|
+
}),
|
|
7679
|
+
}).then(function(){ window.location.reload(); });
|
|
7680
|
+
return;
|
|
7681
|
+
}
|
|
7682
|
+
|
|
7683
|
+
var rmBtn = e.target.closest && e.target.closest('.js-remove-cart-item');
|
|
7684
|
+
if (rmBtn) {
|
|
7685
|
+
e.preventDefault();
|
|
7686
|
+
fetch('/_api/cart', {
|
|
7687
|
+
method: 'DELETE',
|
|
7688
|
+
headers: { 'Content-Type': 'application/json' },
|
|
7689
|
+
body: JSON.stringify({
|
|
7690
|
+
product_id: rmBtn.getAttribute('data-product-id'),
|
|
7691
|
+
variant_id: rmBtn.getAttribute('data-variant-id') || null,
|
|
7692
|
+
}),
|
|
7693
|
+
}).then(function(){ window.location.reload(); });
|
|
7694
|
+
return;
|
|
7695
|
+
}
|
|
7696
|
+
|
|
7697
|
+
var variantBtn = e.target.closest && e.target.closest('[data-product-variant]');
|
|
7698
|
+
if (variantBtn) {
|
|
7699
|
+
var vid = variantBtn.getAttribute('data-product-variant');
|
|
7700
|
+
var vPrice = variantBtn.getAttribute('data-variant-price');
|
|
7701
|
+
var vImg = variantBtn.getAttribute('data-variant-image');
|
|
7702
|
+
var vStock = variantBtn.getAttribute('data-variant-stock');
|
|
7703
|
+
var priceEl = document.querySelector('[data-product-price]');
|
|
7704
|
+
if (priceEl && vPrice) priceEl.textContent = vPrice;
|
|
7705
|
+
var imgEl = document.querySelector('[data-product-main-image]');
|
|
7706
|
+
if (imgEl && vImg) imgEl.setAttribute('src', vImg);
|
|
7707
|
+
var stockEl = document.querySelector('[data-product-stock]');
|
|
7708
|
+
if (stockEl && vStock !== null) stockEl.textContent = Number(vStock) > 0 ? 'In Stock' : 'Out of Stock';
|
|
7709
|
+
var pdpAdd = document.querySelector('[data-product-detail] .js-add-to-cart, .js-add-to-cart');
|
|
7710
|
+
if (pdpAdd && vid) pdpAdd.setAttribute('data-variant-id', vid);
|
|
7711
|
+
return;
|
|
7712
|
+
}
|
|
7713
|
+
|
|
7714
|
+
var googleBtn = e.target.closest && e.target.closest('.js-firebase-google-btn');
|
|
7715
|
+
if (googleBtn) {
|
|
7716
|
+
e.preventDefault();
|
|
7717
|
+
fetch('/_api/auth/google', { method: 'POST' }).then(function(r){ return r.json(); }).then(function(d){
|
|
7718
|
+
toast('Signed in with Google Sandbox');
|
|
7719
|
+
window.location.href = d.redirect || '/account';
|
|
7720
|
+
});
|
|
7721
|
+
return;
|
|
7722
|
+
}
|
|
7723
|
+
|
|
7724
|
+
var logoutBtn = e.target.closest && e.target.closest('.js-logout-btn');
|
|
7725
|
+
if (logoutBtn) {
|
|
7726
|
+
e.preventDefault();
|
|
7727
|
+
fetch('/_api/auth/logout', { method: 'POST' }).then(function(){ window.location.href = '/'; });
|
|
7728
|
+
return;
|
|
7729
|
+
}
|
|
7730
|
+
});
|
|
7731
|
+
|
|
7732
|
+
document.addEventListener('submit', function(e) {
|
|
7733
|
+
var authForm = e.target.closest && e.target.closest('form.js-auth-form');
|
|
7734
|
+
if (authForm) {
|
|
7735
|
+
e.preventDefault();
|
|
7736
|
+
var action = authForm.getAttribute('action') || '/_api/auth/login';
|
|
7737
|
+
var fd = new FormData(authForm);
|
|
7738
|
+
var body = {};
|
|
7739
|
+
fd.forEach(function(v, k){ body[k] = v; });
|
|
7740
|
+
fetch(action, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
|
|
7741
|
+
.then(function(r){ return r.json().then(function(d){ return { ok: r.ok, d: d }; }); })
|
|
7742
|
+
.then(function(res){
|
|
7743
|
+
if (!res.ok) { toast(res.d.message || 'Authentication failed', true); return; }
|
|
7744
|
+
toast('Signed in to sandbox session');
|
|
7745
|
+
window.location.href = res.d.redirect || authForm.getAttribute('data-redirect') || '/account';
|
|
7746
|
+
});
|
|
7747
|
+
return;
|
|
7748
|
+
}
|
|
7749
|
+
|
|
7750
|
+
var checkoutForm = e.target.closest && e.target.closest('form.js-checkout-form');
|
|
7751
|
+
if (checkoutForm) {
|
|
7752
|
+
e.preventDefault();
|
|
7753
|
+
var fd2 = new FormData(checkoutForm);
|
|
7754
|
+
var body2 = {};
|
|
7755
|
+
fd2.forEach(function(v, k){ body2[k] = v; });
|
|
7756
|
+
fetch('/_api/checkout/place-order', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body2) })
|
|
7757
|
+
.then(function(r){ return r.json().then(function(d){ return { ok: r.ok, d: d }; }); })
|
|
7758
|
+
.then(function(res){
|
|
7759
|
+
if (!res.ok) { toast(res.d.message || 'Order failed', true); return; }
|
|
7760
|
+
toast('Sandbox order placed: ' + res.d.order.orderNumber);
|
|
7761
|
+
window.location.href = res.d.redirect || '/order-success';
|
|
7762
|
+
});
|
|
7763
|
+
}
|
|
7764
|
+
});
|
|
7765
|
+
|
|
7766
|
+
// Live Theme Editor postMessage bridge (when embedded inside /_editor)
|
|
7767
|
+
window.addEventListener('message', function(event) {
|
|
7768
|
+
if (event.origin !== window.location.origin) return;
|
|
7769
|
+
var msg = event.data;
|
|
7770
|
+
if (!msg || typeof msg !== 'object') return;
|
|
7771
|
+
if (msg.type === 'CAARTZEE_EDITOR_SWAP_SECTION' && msg.sectionId && typeof msg.html === 'string') {
|
|
7772
|
+
var target = document.querySelector('[data-caartzee-section-id="' + msg.sectionId + '"], [data-section-id="' + msg.sectionId + '"]');
|
|
7773
|
+
if (target) {
|
|
7774
|
+
target.outerHTML = msg.html;
|
|
7775
|
+
document.dispatchEvent(new CustomEvent('caartzee:section:load', { detail: { sectionId: msg.sectionId } }));
|
|
7776
|
+
} else {
|
|
7777
|
+
window.location.reload();
|
|
7778
|
+
}
|
|
7779
|
+
} else if (msg.type === 'CAARTZEE_EDITOR_RELOAD') {
|
|
7780
|
+
window.location.reload();
|
|
7781
|
+
}
|
|
7782
|
+
});
|
|
7783
|
+
|
|
7784
|
+
// Visible sandbox indicator bar (hidden when inside iframe preview)
|
|
7785
|
+
if (window.self === window.top) {
|
|
7786
|
+
var bar = document.createElement('div');
|
|
7787
|
+
bar.setAttribute('data-caartzee-dev-banner', 'true');
|
|
7788
|
+
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;';
|
|
7789
|
+
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>';
|
|
7790
|
+
document.body.appendChild(bar);
|
|
7791
|
+
}
|
|
7792
|
+
})();
|
|
7793
|
+
</script>`;
|
|
7794
|
+
}
|
|
7795
|
+
|
|
7796
|
+
// src/dev-server/local-editor-server.ts
|
|
7797
|
+
class LocalThemeEditorState {
|
|
7798
|
+
state = null;
|
|
7799
|
+
ensureInitialized(theme) {
|
|
7800
|
+
if (this.state)
|
|
7801
|
+
return this.state;
|
|
7802
|
+
const defaultLayout = JSON.parse(JSON.stringify(theme.defaultTemplates?.layout || { regions: { header: [], footer: [] } }));
|
|
7803
|
+
const homePage = theme.defaultTemplates?.pages?.home || theme.defaultTemplates?.pages?.index;
|
|
7804
|
+
const defaultBody = JSON.parse(JSON.stringify(homePage?.regions?.body || []));
|
|
7805
|
+
const defaultGlobalSettings = { ...theme.manifest.defaultGlobalSettings || {} };
|
|
7806
|
+
this.state = {
|
|
7807
|
+
layout: defaultLayout,
|
|
7808
|
+
bodySections: defaultBody,
|
|
7809
|
+
globalSettings: defaultGlobalSettings,
|
|
7810
|
+
publishedLayout: null,
|
|
7811
|
+
publishedBodySections: null,
|
|
7812
|
+
publishedGlobalSettings: null,
|
|
7813
|
+
version: 1
|
|
7814
|
+
};
|
|
7815
|
+
return this.state;
|
|
7816
|
+
}
|
|
7817
|
+
getEffectiveConfig(theme, mode = "draft") {
|
|
7818
|
+
const s = this.ensureInitialized(theme);
|
|
7819
|
+
if (mode === "published" && s.publishedLayout) {
|
|
7820
|
+
return {
|
|
7821
|
+
layout: s.publishedLayout,
|
|
7822
|
+
bodySections: s.publishedBodySections || s.bodySections,
|
|
7823
|
+
globalSettings: s.publishedGlobalSettings || s.globalSettings
|
|
7824
|
+
};
|
|
7825
|
+
}
|
|
7826
|
+
return {
|
|
7827
|
+
layout: s.layout,
|
|
7828
|
+
bodySections: s.bodySections,
|
|
7829
|
+
globalSettings: s.globalSettings
|
|
7830
|
+
};
|
|
7831
|
+
}
|
|
7832
|
+
async handleRequest(req, res, pathname, theme, buildContext) {
|
|
7833
|
+
const state = this.ensureInitialized(theme);
|
|
7834
|
+
const method = (req.method || "GET").toUpperCase();
|
|
7835
|
+
const json = (status, body) => {
|
|
7836
|
+
res.writeHead(status, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" });
|
|
7837
|
+
res.end(JSON.stringify(body));
|
|
7838
|
+
return true;
|
|
7839
|
+
};
|
|
7840
|
+
const readBody = async () => {
|
|
7841
|
+
const chunks = [];
|
|
7842
|
+
for await (const chunk of req)
|
|
7843
|
+
chunks.push(Buffer.from(chunk));
|
|
7844
|
+
const raw = Buffer.concat(chunks).toString("utf8").trim();
|
|
7845
|
+
if (!raw)
|
|
7846
|
+
return {};
|
|
7847
|
+
try {
|
|
7848
|
+
return JSON.parse(raw);
|
|
7849
|
+
} catch {
|
|
7850
|
+
return {};
|
|
7851
|
+
}
|
|
7852
|
+
};
|
|
7853
|
+
if (pathname === "/_editor" && method === "GET") {
|
|
7854
|
+
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
|
|
7855
|
+
res.end(renderLocalEditorHtml(theme.name, theme.slug));
|
|
7856
|
+
return true;
|
|
7857
|
+
}
|
|
7858
|
+
if (pathname === "/_api/editor/state" && method === "GET") {
|
|
7859
|
+
return json(200, {
|
|
7860
|
+
theme: {
|
|
7861
|
+
slug: theme.slug,
|
|
7862
|
+
name: theme.name,
|
|
7863
|
+
version: theme.version,
|
|
7864
|
+
sections: theme.manifest.sections,
|
|
7865
|
+
globalSettingsSchema: theme.manifest.globalSettingsSchema || null
|
|
7866
|
+
},
|
|
7867
|
+
draft: {
|
|
7868
|
+
version: state.version,
|
|
7869
|
+
layout: state.layout,
|
|
7870
|
+
bodySections: state.bodySections,
|
|
7871
|
+
globalSettings: state.globalSettings
|
|
7872
|
+
},
|
|
7873
|
+
hasPublishedPreview: Boolean(state.publishedLayout)
|
|
7874
|
+
});
|
|
7875
|
+
}
|
|
7876
|
+
if (pathname === "/_api/editor/update" && method === "POST") {
|
|
7877
|
+
const body = await readBody();
|
|
7878
|
+
if (body.layout)
|
|
7879
|
+
state.layout = body.layout;
|
|
7880
|
+
if (Array.isArray(body.bodySections))
|
|
7881
|
+
state.bodySections = body.bodySections;
|
|
7882
|
+
if (body.globalSettings && typeof body.globalSettings === "object") {
|
|
7883
|
+
state.globalSettings = { ...state.globalSettings, ...body.globalSettings };
|
|
7884
|
+
}
|
|
7885
|
+
let renderedSectionHtml = null;
|
|
7886
|
+
if (body.sectionId && body.region) {
|
|
7887
|
+
const list = body.region === "header" ? state.layout.regions.header || [] : body.region === "footer" ? state.layout.regions.footer || [] : state.bodySections;
|
|
7888
|
+
const sec = list.find((s) => s.id === body.sectionId);
|
|
7889
|
+
if (sec) {
|
|
7890
|
+
if (body.settings)
|
|
7891
|
+
sec.settings = { ...sec.settings || {}, ...body.settings };
|
|
7892
|
+
if (Array.isArray(body.blocks))
|
|
7893
|
+
sec.blocks = body.blocks;
|
|
7894
|
+
const renderer = theme.sections[sec.type];
|
|
7895
|
+
if (renderer) {
|
|
7896
|
+
const pageContext = await buildContext("home");
|
|
7897
|
+
pageContext.globalSettings = { ...pageContext.globalSettings, ...state.globalSettings };
|
|
7898
|
+
renderedSectionHtml = renderer({
|
|
7899
|
+
section: sec,
|
|
7900
|
+
themeSlug: theme.slug,
|
|
7901
|
+
globalSettings: pageContext.globalSettings,
|
|
7902
|
+
pageContext,
|
|
7903
|
+
catalog: {
|
|
7904
|
+
products: pageContext.products || pageContext.featuredProducts || [],
|
|
7905
|
+
featuredProducts: pageContext.featuredProducts || [],
|
|
7906
|
+
categories: pageContext.categories || []
|
|
7907
|
+
}
|
|
7908
|
+
});
|
|
7909
|
+
}
|
|
7910
|
+
}
|
|
7911
|
+
}
|
|
7912
|
+
state.version += 1;
|
|
7913
|
+
return json(200, {
|
|
7914
|
+
success: true,
|
|
7915
|
+
version: state.version,
|
|
7916
|
+
renderedSectionHtml,
|
|
7917
|
+
draft: {
|
|
7918
|
+
layout: state.layout,
|
|
7919
|
+
bodySections: state.bodySections,
|
|
7920
|
+
globalSettings: state.globalSettings
|
|
7921
|
+
}
|
|
7922
|
+
});
|
|
7923
|
+
}
|
|
7924
|
+
if (pathname === "/_api/editor/publish" && method === "POST") {
|
|
7925
|
+
state.publishedLayout = JSON.parse(JSON.stringify(state.layout));
|
|
7926
|
+
state.publishedBodySections = JSON.parse(JSON.stringify(state.bodySections));
|
|
7927
|
+
state.publishedGlobalSettings = JSON.parse(JSON.stringify(state.globalSettings));
|
|
7928
|
+
return json(200, { success: true, version: state.version, publishedPreviewUrl: "/?preview_mode=published" });
|
|
7929
|
+
}
|
|
7930
|
+
return false;
|
|
7931
|
+
}
|
|
7932
|
+
}
|
|
7933
|
+
function renderLocalEditorHtml(themeName, themeSlug) {
|
|
7934
|
+
return `<!doctype html>
|
|
7935
|
+
<html lang="en">
|
|
7936
|
+
<head>
|
|
7937
|
+
<meta charset="utf-8" />
|
|
7938
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
7939
|
+
<title>Caartzee Local Theme Editor — ${themeName}</title>
|
|
7940
|
+
<style>
|
|
7941
|
+
* { box-sizing: border-box; }
|
|
7942
|
+
body { margin: 0; font-family: system-ui, -apple-system, sans-serif; background: #0f172a; color: #f8fafc; height: 100vh; display: flex; flex-direction: column; }
|
|
7943
|
+
header { height: 48px; padding: 0 16px; border-bottom: 1px solid #1e293b; display: flex; align-items: center; justify-content: space-between; background: #020617; }
|
|
7944
|
+
.toolbar { display: flex; gap: 8px; align-items: center; }
|
|
7945
|
+
button { background: #1e293b; color: #f8fafc; border: 1px solid #334155; border-radius: 6px; padding: 6px 12px; font-size: 12px; cursor: pointer; }
|
|
7946
|
+
button.primary { background: #4f46e5; border-color: #6366f1; }
|
|
7947
|
+
main { flex: 1; display: grid; grid-template-columns: 340px 1fr; min-height: 0; }
|
|
7948
|
+
aside { border-right: 1px solid #1e293b; overflow-y: auto; padding: 14px; background: #0b1120; }
|
|
7949
|
+
.preview-wrap { background: #1e293b; display: flex; justify-content: center; align-items: stretch; padding: 12px; overflow: hidden; }
|
|
7950
|
+
iframe { border: 1px solid #334155; border-radius: 8px; background: #fff; width: 100%; height: 100%; transition: width .2s; }
|
|
7951
|
+
iframe.mobile { width: 390px; }
|
|
7952
|
+
.group-title { font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: .06em; color: #94a3b8; margin: 14px 0 6px; }
|
|
7953
|
+
.sec-card { border: 1px solid #1e293b; border-radius: 8px; padding: 10px; margin-bottom: 8px; background: #111827; }
|
|
7954
|
+
.sec-head { display: flex; justify-content: space-between; align-items: center; font-size: 13px; font-weight: 600; margin-bottom: 8px; }
|
|
7955
|
+
.field { margin-bottom: 8px; }
|
|
7956
|
+
.field label { display: block; font-size: 11px; color: #cbd5e1; margin-bottom: 3px; }
|
|
7957
|
+
.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; }
|
|
7958
|
+
</style>
|
|
7959
|
+
</head>
|
|
7960
|
+
<body>
|
|
7961
|
+
<header>
|
|
7962
|
+
<div><strong>Caartzee Dev Theme Editor</strong> <span style="color:#94a3b8;font-size:12px;">(${themeSlug})</span></div>
|
|
7963
|
+
<div class="toolbar">
|
|
7964
|
+
<button id="btn-desktop">Desktop</button>
|
|
7965
|
+
<button id="btn-mobile">Mobile</button>
|
|
7966
|
+
<button id="btn-publish" class="primary">Test Publish Preview</button>
|
|
7967
|
+
<a href="/" style="color:#38bdf8;font-size:12px;text-decoration:none;margin-left:6px;">Exit Editor</a>
|
|
7968
|
+
</div>
|
|
7969
|
+
</header>
|
|
7970
|
+
<main>
|
|
7971
|
+
<aside id="sidebar">Loading theme schemas...</aside>
|
|
7972
|
+
<div class="preview-wrap"><iframe id="preview-frame" src="/?editor_preview=1"></iframe></div>
|
|
7973
|
+
</main>
|
|
7974
|
+
<script>
|
|
7975
|
+
let editorState = null;
|
|
7976
|
+
const frame = document.getElementById('preview-frame');
|
|
7977
|
+
document.getElementById('btn-desktop').onclick = () => frame.classList.remove('mobile');
|
|
7978
|
+
document.getElementById('btn-mobile').onclick = () => frame.classList.add('mobile');
|
|
7979
|
+
document.getElementById('btn-publish').onclick = async () => {
|
|
7980
|
+
const res = await fetch('/_api/editor/publish', { method: 'POST' }).then(r => r.json());
|
|
7981
|
+
if (res.success) alert('Published to isolated local preview: ' + res.publishedPreviewUrl);
|
|
7982
|
+
};
|
|
7983
|
+
|
|
7984
|
+
async function load() {
|
|
7985
|
+
editorState = await fetch('/_api/editor/state').then(r => r.json());
|
|
7986
|
+
renderSidebar();
|
|
7987
|
+
}
|
|
7988
|
+
|
|
7989
|
+
async function patchSection(region, sectionId, patch) {
|
|
7990
|
+
const res = await fetch('/_api/editor/update', {
|
|
7991
|
+
method: 'POST',
|
|
7992
|
+
headers: { 'Content-Type': 'application/json' },
|
|
7993
|
+
body: JSON.stringify({ region, sectionId, settings: patch }),
|
|
7994
|
+
}).then(r => r.json());
|
|
7995
|
+
if (res.renderedSectionHtml) {
|
|
7996
|
+
frame.contentWindow.postMessage({ type: 'CAARTZEE_EDITOR_SWAP_SECTION', sectionId, html: res.renderedSectionHtml }, window.location.origin);
|
|
7997
|
+
} else {
|
|
7998
|
+
frame.contentWindow.postMessage({ type: 'CAARTZEE_EDITOR_RELOAD' }, window.location.origin);
|
|
7999
|
+
}
|
|
8000
|
+
}
|
|
8001
|
+
|
|
8002
|
+
function renderRegion(title, region, list) {
|
|
8003
|
+
const schemas = Object.fromEntries((editorState.theme.sections || []).map(s => [s.type, s]));
|
|
8004
|
+
let html = '<div class="group-title">' + title + '</div>';
|
|
8005
|
+
for (const sec of list || []) {
|
|
8006
|
+
const schema = schemas[sec.type];
|
|
8007
|
+
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>';
|
|
8008
|
+
for (const f of (schema?.settings || []).slice(0, 12)) {
|
|
8009
|
+
if (f.type === 'header' || f.type === 'paragraph') continue;
|
|
8010
|
+
const val = (sec.settings && sec.settings[f.id] !== undefined) ? sec.settings[f.id] : (f.default ?? '');
|
|
8011
|
+
const type = f.type === 'color' ? 'color' : f.type === 'checkbox' || f.type === 'boolean' ? 'checkbox' : 'text';
|
|
8012
|
+
html += '<div class="field"><label>' + f.label + '</label>';
|
|
8013
|
+
if (type === 'checkbox') {
|
|
8014
|
+
html += '<input type="checkbox" ' + (val ? 'checked' : '') + ' data-region="' + region + '" data-sec="' + sec.id + '" data-key="' + f.id + '" />';
|
|
8015
|
+
} else {
|
|
8016
|
+
html += '<input type="' + type + '" value="' + String(val).replace(/"/g, '"') + '" data-region="' + region + '" data-sec="' + sec.id + '" data-key="' + f.id + '" />';
|
|
8017
|
+
}
|
|
8018
|
+
html += '</div>';
|
|
8019
|
+
}
|
|
8020
|
+
html += '</div>';
|
|
8021
|
+
}
|
|
8022
|
+
return html;
|
|
8023
|
+
}
|
|
8024
|
+
|
|
8025
|
+
function renderSidebar() {
|
|
8026
|
+
const sidebar = document.getElementById('sidebar');
|
|
8027
|
+
sidebar.innerHTML =
|
|
8028
|
+
renderRegion('Header Region', 'header', editorState.draft.layout.regions.header) +
|
|
8029
|
+
renderRegion('Body Sections', 'body', editorState.draft.bodySections) +
|
|
8030
|
+
renderRegion('Footer Region', 'footer', editorState.draft.layout.regions.footer);
|
|
8031
|
+
|
|
8032
|
+
sidebar.querySelectorAll('input[data-sec]').forEach(input => {
|
|
8033
|
+
input.addEventListener('change', () => {
|
|
8034
|
+
const val = input.type === 'checkbox' ? input.checked : input.value;
|
|
8035
|
+
patchSection(input.dataset.region, input.dataset.sec, { [input.dataset.key]: val });
|
|
8036
|
+
});
|
|
8037
|
+
});
|
|
8038
|
+
}
|
|
8039
|
+
|
|
8040
|
+
load();
|
|
8041
|
+
</script>
|
|
8042
|
+
</body>
|
|
8043
|
+
</html>`;
|
|
8044
|
+
}
|
|
8045
|
+
|
|
6548
8046
|
// src/dev-server/dev-server.ts
|
|
8047
|
+
function injectRuntimeScript(html, script) {
|
|
8048
|
+
if (/<\/body>/i.test(html)) {
|
|
8049
|
+
return html.replace(/<\/body>/i, `${script}</body>`);
|
|
8050
|
+
}
|
|
8051
|
+
return `${html}
|
|
8052
|
+
${script}`;
|
|
8053
|
+
}
|
|
6549
8054
|
function createThemeDevServer(options = {}) {
|
|
6550
8055
|
const port = options.port ?? 3333;
|
|
6551
8056
|
const host = options.host ?? "127.0.0.1";
|
|
6552
8057
|
const themeDir = options.themeDir ?? process.cwd();
|
|
6553
8058
|
if (options.loadCatalog && host !== "127.0.0.1")
|
|
6554
8059
|
throw new Error("Store catalog previews must bind to 127.0.0.1.");
|
|
8060
|
+
const commerceStore = new LocalCommerceStore;
|
|
8061
|
+
const editorState = new LocalThemeEditorState;
|
|
6555
8062
|
let manifest = null;
|
|
6556
8063
|
const manifestPath = join7(themeDir, "manifest.json");
|
|
6557
8064
|
if (existsSync7(manifestPath)) {
|
|
@@ -6563,9 +8070,10 @@ function createThemeDevServer(options = {}) {
|
|
|
6563
8070
|
try {
|
|
6564
8071
|
const parsedUrl = new URL(req.url ?? "/", `http://${host}:${port}`);
|
|
6565
8072
|
const pathname = parsedUrl.pathname;
|
|
8073
|
+
const isEditorPreview = parsedUrl.searchParams.get("editor_preview") === "1" || pathname === "/_editor";
|
|
6566
8074
|
if (options.loadCatalog) {
|
|
6567
8075
|
res.setHeader("Cache-Control", "no-store");
|
|
6568
|
-
res.setHeader("Content-Security-Policy", "frame-ancestors 'none'");
|
|
8076
|
+
res.setHeader("Content-Security-Policy", isEditorPreview ? "frame-ancestors 'self'" : "frame-ancestors 'none'");
|
|
6569
8077
|
res.setHeader("Cross-Origin-Resource-Policy", "same-origin");
|
|
6570
8078
|
if (req.headers.host !== host + ":" + port) {
|
|
6571
8079
|
res.writeHead(403);
|
|
@@ -6576,28 +8084,66 @@ function createThemeDevServer(options = {}) {
|
|
|
6576
8084
|
if (pathname.startsWith("/assets/")) {
|
|
6577
8085
|
const root = resolve5(themeDir, "assets");
|
|
6578
8086
|
const file = resolve5(themeDir, "." + decodeURIComponent(pathname));
|
|
6579
|
-
if (!file.startsWith(root + sep) || !existsSync7(file) || ![".css", ".svg", ".png", ".jpg", ".jpeg", ".webp", ".gif", ".woff2"].includes(extname(file).toLowerCase())) {
|
|
8087
|
+
if (!file.startsWith(root + sep) || !existsSync7(file) || ![".css", ".js", ".svg", ".png", ".jpg", ".jpeg", ".webp", ".gif", ".woff2"].includes(extname(file).toLowerCase())) {
|
|
6580
8088
|
res.writeHead(404);
|
|
6581
8089
|
res.end("Asset not found");
|
|
6582
8090
|
return;
|
|
6583
8091
|
}
|
|
6584
|
-
const mime = {
|
|
8092
|
+
const mime = {
|
|
8093
|
+
".css": "text/css",
|
|
8094
|
+
".js": "application/javascript; charset=utf-8",
|
|
8095
|
+
".svg": "image/svg+xml",
|
|
8096
|
+
".png": "image/png",
|
|
8097
|
+
".jpg": "image/jpeg",
|
|
8098
|
+
".jpeg": "image/jpeg",
|
|
8099
|
+
".webp": "image/webp",
|
|
8100
|
+
".gif": "image/gif",
|
|
8101
|
+
".woff2": "font/woff2"
|
|
8102
|
+
};
|
|
6585
8103
|
res.writeHead(200, { "Content-Type": mime[extname(file).toLowerCase()], "Cache-Control": "no-store" });
|
|
6586
8104
|
res.end(readFileSync7(file));
|
|
6587
8105
|
return;
|
|
6588
8106
|
}
|
|
6589
8107
|
if (pathname === "/_api/status") {
|
|
6590
8108
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
6591
|
-
res.end(JSON.stringify({
|
|
8109
|
+
res.end(JSON.stringify({
|
|
8110
|
+
status: "ok",
|
|
8111
|
+
mode: options.loadCatalog ? "merchant-sandbox" : "demo",
|
|
8112
|
+
theme: manifest?.name ?? "Unknown Theme",
|
|
8113
|
+
version: manifest?.version ?? "1.0.0",
|
|
8114
|
+
editorUrl: `http://${host}:${port}/_editor`
|
|
8115
|
+
}));
|
|
6592
8116
|
return;
|
|
6593
8117
|
}
|
|
6594
8118
|
if (pathname === "/_api/context") {
|
|
6595
8119
|
const page = parsedUrl.searchParams.get("page") || "home";
|
|
6596
|
-
const
|
|
8120
|
+
const session = commerceStore.getOrCreateSession(req, res);
|
|
8121
|
+
const baseContext = options.loadCatalog ? await createCatalogDevContext(options.loadCatalog, page, "/", parsedUrl.searchParams) : createMockPageContext(page);
|
|
8122
|
+
const context = commerceStore.applySessionToContext(session, baseContext);
|
|
6597
8123
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
6598
8124
|
res.end(JSON.stringify(context, null, 2));
|
|
6599
8125
|
return;
|
|
6600
8126
|
}
|
|
8127
|
+
if (pathname === "/_editor" || pathname.startsWith("/_api/editor/")) {
|
|
8128
|
+
const theme = options.loadTheme ? await options.loadTheme() : await loadLocalTheme(themeDir);
|
|
8129
|
+
const session = commerceStore.getOrCreateSession(req, res);
|
|
8130
|
+
const handled = await editorState.handleRequest(req, res, pathname, theme, async (pt) => {
|
|
8131
|
+
const base = options.loadCatalog ? await createCatalogDevContext(options.loadCatalog, pt, "/", parsedUrl.searchParams) : createMockPageContext(pt);
|
|
8132
|
+
return commerceStore.applySessionToContext(session, base);
|
|
8133
|
+
});
|
|
8134
|
+
if (handled)
|
|
8135
|
+
return;
|
|
8136
|
+
}
|
|
8137
|
+
const handledCommerce = await commerceStore.handleApiRequest(req, res, pathname, parsedUrl.searchParams, async () => {
|
|
8138
|
+
if (options.loadCatalog) {
|
|
8139
|
+
const cat = await options.loadCatalog({});
|
|
8140
|
+
return cat.products || [];
|
|
8141
|
+
}
|
|
8142
|
+
const mock = createMockPageContext("product-list");
|
|
8143
|
+
return mock.products || mock.featuredProducts || [];
|
|
8144
|
+
});
|
|
8145
|
+
if (handledCommerce)
|
|
8146
|
+
return;
|
|
6601
8147
|
if (pathname.startsWith("/_assets/")) {
|
|
6602
8148
|
const parts = pathname.replace(/^\/_assets\/[^/]+\//, "");
|
|
6603
8149
|
const safeAsset = parts.split("/").filter((s) => s && s !== "." && s !== "..").join("/");
|
|
@@ -6625,7 +8171,7 @@ function createThemeDevServer(options = {}) {
|
|
|
6625
8171
|
pageType = "checkout";
|
|
6626
8172
|
} else if (pathname === "/login") {
|
|
6627
8173
|
pageType = "login";
|
|
6628
|
-
} else if (pathname === "/signup") {
|
|
8174
|
+
} else if (pathname === "/signup" || pathname === "/register") {
|
|
6629
8175
|
pageType = "signup";
|
|
6630
8176
|
} else if (pathname === "/account") {
|
|
6631
8177
|
pageType = "account";
|
|
@@ -6662,10 +8208,28 @@ function createThemeDevServer(options = {}) {
|
|
|
6662
8208
|
pageType = "order-detail";
|
|
6663
8209
|
else if (pathname.startsWith("/account/"))
|
|
6664
8210
|
pageType = "account";
|
|
6665
|
-
const
|
|
8211
|
+
const session = commerceStore.getOrCreateSession(req, res);
|
|
8212
|
+
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") } : {});
|
|
6666
8213
|
const theme = options.loadTheme ? await options.loadTheme() : await loadLocalTheme(themeDir);
|
|
6667
|
-
const
|
|
6668
|
-
|
|
8214
|
+
const previewMode = parsedUrl.searchParams.get("preview_mode") === "published" ? "published" : "draft";
|
|
8215
|
+
const editorConfig = editorState.getEffectiveConfig(theme, previewMode);
|
|
8216
|
+
const enrichedContext = commerceStore.applySessionToContext(session, {
|
|
8217
|
+
...baseContext,
|
|
8218
|
+
isPreview: true,
|
|
8219
|
+
globalSettings: { ...baseContext.globalSettings, ...editorConfig.globalSettings },
|
|
8220
|
+
layoutDocument: editorConfig.layout,
|
|
8221
|
+
...pageType === "home" ? { sections: editorConfig.bodySections } : {}
|
|
8222
|
+
});
|
|
8223
|
+
const rawHtml = renderThemePreview(theme, enrichedContext, Boolean(options.loadCatalog), editorConfig);
|
|
8224
|
+
const runtimeScript = buildStorefrontShellRuntimeScript({
|
|
8225
|
+
mode: options.loadCatalog ? "merchant-sandbox" : "demo",
|
|
8226
|
+
storeLabel: options.storeLabel,
|
|
8227
|
+
editorEnabled: Boolean(options.editor)
|
|
8228
|
+
});
|
|
8229
|
+
const html = injectRuntimeScript(rawHtml, runtimeScript);
|
|
8230
|
+
res.writeHead(enrichedContext.pageType === "not-found" && pageType !== "not-found" ? 404 : 200, {
|
|
8231
|
+
"Content-Type": "text/html; charset=utf-8"
|
|
8232
|
+
});
|
|
6669
8233
|
res.end(html);
|
|
6670
8234
|
} catch (error) {
|
|
6671
8235
|
res.writeHead(500, { "Content-Type": "text/plain; charset=utf-8" });
|
|
@@ -6676,6 +8240,7 @@ function createThemeDevServer(options = {}) {
|
|
|
6676
8240
|
server,
|
|
6677
8241
|
port,
|
|
6678
8242
|
url: `http://${host}:${port}`,
|
|
8243
|
+
editorUrl: `http://${host}:${port}/_editor`,
|
|
6679
8244
|
stop: () => new Promise((resolve) => {
|
|
6680
8245
|
server.close(() => resolve());
|
|
6681
8246
|
})
|
|
@@ -6708,8 +8273,9 @@ async function loadLocalTheme(themeDir) {
|
|
|
6708
8273
|
const source = await build.outputs[0].text();
|
|
6709
8274
|
const module = await import("data:text/javascript;base64," + Buffer.from(source).toString("base64"));
|
|
6710
8275
|
const theme = module.default || module.theme;
|
|
6711
|
-
if (!theme?.sections || !theme?.defaultTemplates || !theme?.manifest)
|
|
8276
|
+
if (!theme?.sections || !theme?.defaultTemplates || !theme?.manifest) {
|
|
6712
8277
|
throw new Error("src/index.ts must export a StorefrontThemeDefinition as default or theme.");
|
|
8278
|
+
}
|
|
6713
8279
|
return theme;
|
|
6714
8280
|
}
|
|
6715
8281
|
// src/validation/package-validator.ts
|
|
@@ -6958,6 +8524,309 @@ class PackageValidator {
|
|
|
6958
8524
|
}
|
|
6959
8525
|
var ThemePackageValidator = PackageValidator;
|
|
6960
8526
|
|
|
8527
|
+
// src/cli/mcp/editor-tools.ts
|
|
8528
|
+
import { existsSync as existsSync9, readFileSync as readFileSync9 } from "node:fs";
|
|
8529
|
+
import { join as join9, resolve as resolve7 } from "node:path";
|
|
8530
|
+
import { z as z4 } from "zod";
|
|
8531
|
+
function validateThemeEditorDirectory(themeDir) {
|
|
8532
|
+
const dir = resolve7(themeDir);
|
|
8533
|
+
const checks = [];
|
|
8534
|
+
if (!existsSync9(dir)) {
|
|
8535
|
+
return {
|
|
8536
|
+
valid: false,
|
|
8537
|
+
themeDir: dir,
|
|
8538
|
+
checks: [{ name: "directory_exists", status: "failed", message: `Theme directory not found: ${dir}` }],
|
|
8539
|
+
summary: { passed: 0, failed: 1, warnings: 0 }
|
|
8540
|
+
};
|
|
8541
|
+
}
|
|
8542
|
+
const { bundle, diagnostics } = loadCandyThemeFromDirectory(dir);
|
|
8543
|
+
const schemaErrors = diagnostics.filter((d) => d.severity === "error");
|
|
8544
|
+
const schemaWarnings = diagnostics.filter((d) => d.severity === "warning");
|
|
8545
|
+
if (schemaErrors.length === 0) {
|
|
8546
|
+
checks.push({
|
|
8547
|
+
name: "section_schemas_compile",
|
|
8548
|
+
status: "passed",
|
|
8549
|
+
message: `All ${Object.keys(bundle.sectionSchemas).length} section schema(s) compiled cleanly.`
|
|
8550
|
+
});
|
|
8551
|
+
} else {
|
|
8552
|
+
for (const err of schemaErrors) {
|
|
8553
|
+
checks.push({
|
|
8554
|
+
name: "section_schema_error",
|
|
8555
|
+
status: "failed",
|
|
8556
|
+
message: `${err.code}: ${err.message}`,
|
|
8557
|
+
file: err.file
|
|
8558
|
+
});
|
|
8559
|
+
}
|
|
8560
|
+
}
|
|
8561
|
+
for (const warn of schemaWarnings) {
|
|
8562
|
+
checks.push({
|
|
8563
|
+
name: "section_schema_warning",
|
|
8564
|
+
status: "warning",
|
|
8565
|
+
message: `${warn.code}: ${warn.message}`,
|
|
8566
|
+
file: warn.file
|
|
8567
|
+
});
|
|
8568
|
+
}
|
|
8569
|
+
for (const [sectionType, schema] of Object.entries(bundle.sectionSchemas)) {
|
|
8570
|
+
const relPath = `sections/${sectionType}.candy`;
|
|
8571
|
+
const source = bundle.files[relPath] || "";
|
|
8572
|
+
if (schema.blocks && schema.blocks.length > 0) {
|
|
8573
|
+
if (source.includes("block.candy_attributes")) {
|
|
8574
|
+
checks.push({
|
|
8575
|
+
name: `block_attributes:${sectionType}`,
|
|
8576
|
+
status: "passed",
|
|
8577
|
+
message: `Section "${sectionType}" outputs {{ block.candy_attributes }} for Theme Editor block selection.`,
|
|
8578
|
+
file: relPath
|
|
8579
|
+
});
|
|
8580
|
+
} else {
|
|
8581
|
+
checks.push({
|
|
8582
|
+
name: `block_attributes:${sectionType}`,
|
|
8583
|
+
status: "failed",
|
|
8584
|
+
message: `Section "${sectionType}" defines ${schema.blocks.length} block type(s) but is missing {{ block.candy_attributes }}.`,
|
|
8585
|
+
file: relPath
|
|
8586
|
+
});
|
|
8587
|
+
}
|
|
8588
|
+
}
|
|
8589
|
+
}
|
|
8590
|
+
const settingsSchemaPath = join9(dir, "schemas", "settings_schema.json");
|
|
8591
|
+
if (existsSync9(settingsSchemaPath)) {
|
|
8592
|
+
try {
|
|
8593
|
+
const parsed = JSON.parse(readFileSync9(settingsSchemaPath, "utf8"));
|
|
8594
|
+
if (Array.isArray(parsed) || parsed && typeof parsed === "object") {
|
|
8595
|
+
checks.push({ name: "global_settings_schema", status: "passed", message: "schemas/settings_schema.json is valid JSON.", file: "schemas/settings_schema.json" });
|
|
8596
|
+
} else {
|
|
8597
|
+
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" });
|
|
8598
|
+
}
|
|
8599
|
+
} catch (e) {
|
|
8600
|
+
checks.push({ name: "global_settings_schema", status: "failed", message: `Invalid JSON in schemas/settings_schema.json: ${e.message}`, file: "schemas/settings_schema.json" });
|
|
8601
|
+
}
|
|
8602
|
+
} else {
|
|
8603
|
+
checks.push({ name: "global_settings_schema", status: "warning", message: "schemas/settings_schema.json not found; global theme settings will be empty." });
|
|
8604
|
+
}
|
|
8605
|
+
const themeJs = bundle.assets["assets/theme.js"] || (existsSync9(join9(dir, "assets", "theme.js")) ? readFileSync9(join9(dir, "assets", "theme.js"), "utf8") : "");
|
|
8606
|
+
if (themeJs) {
|
|
8607
|
+
if (themeJs.includes("document.addEventListener") || themeJs.includes("caartzee:section:")) {
|
|
8608
|
+
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" });
|
|
8609
|
+
} else {
|
|
8610
|
+
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" });
|
|
8611
|
+
}
|
|
8612
|
+
}
|
|
8613
|
+
const passed = checks.filter((c) => c.status === "passed").length;
|
|
8614
|
+
const failed = checks.filter((c) => c.status === "failed").length;
|
|
8615
|
+
const warnings = checks.filter((c) => c.status === "warning").length;
|
|
8616
|
+
return {
|
|
8617
|
+
valid: failed === 0,
|
|
8618
|
+
themeDir: dir,
|
|
8619
|
+
slug: bundle.slug,
|
|
8620
|
+
version: bundle.version,
|
|
8621
|
+
sectionCount: Object.keys(bundle.sectionSchemas).length,
|
|
8622
|
+
sections: Object.keys(bundle.sectionSchemas),
|
|
8623
|
+
checks,
|
|
8624
|
+
summary: { passed, failed, warnings }
|
|
8625
|
+
};
|
|
8626
|
+
}
|
|
8627
|
+
|
|
8628
|
+
// src/cli/mcp/testing-tools.ts
|
|
8629
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
8630
|
+
import { existsSync as existsSync10, readFileSync as readFileSync10 } from "node:fs";
|
|
8631
|
+
import { join as join10, resolve as resolve8 } from "node:path";
|
|
8632
|
+
import { z as z5 } from "zod";
|
|
8633
|
+
async function runThemeReadinessAudit(themeDir) {
|
|
8634
|
+
const dir = resolve8(themeDir);
|
|
8635
|
+
const checks = [];
|
|
8636
|
+
const readRel = (rel) => {
|
|
8637
|
+
const full = join10(dir, rel);
|
|
8638
|
+
return existsSync10(full) ? readFileSync10(full, "utf8") : null;
|
|
8639
|
+
};
|
|
8640
|
+
let slug = "unknown";
|
|
8641
|
+
let version = "0.0.0";
|
|
8642
|
+
let packageHash = createHash2("sha256").update(dir).digest("hex");
|
|
8643
|
+
try {
|
|
8644
|
+
const files = collectThemeSources(dir);
|
|
8645
|
+
const canonical = [...files].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
|
|
8646
|
+
packageHash = createHash2("sha256").update(JSON.stringify(canonical)).digest("hex");
|
|
8647
|
+
} catch {}
|
|
8648
|
+
const pkg = await ThemePackageValidator.validatePackage(dir);
|
|
8649
|
+
if (pkg.manifest) {
|
|
8650
|
+
slug = pkg.manifest.slug;
|
|
8651
|
+
version = pkg.manifest.version;
|
|
8652
|
+
}
|
|
8653
|
+
if (pkg.valid) {
|
|
8654
|
+
checks.push({ id: "security.package_validation", category: "security", status: "passed", message: "Manifest and security source-pattern audit passed." });
|
|
8655
|
+
} else {
|
|
8656
|
+
for (const err of pkg.errors) {
|
|
8657
|
+
checks.push({ id: "security.package_validation", category: "security", status: "failed", message: err });
|
|
8658
|
+
}
|
|
8659
|
+
}
|
|
8660
|
+
const editor = validateThemeEditorDirectory(dir);
|
|
8661
|
+
for (const c of editor.checks) {
|
|
8662
|
+
checks.push({
|
|
8663
|
+
id: `editor.${c.name}`,
|
|
8664
|
+
category: "editor",
|
|
8665
|
+
status: c.status,
|
|
8666
|
+
message: c.message,
|
|
8667
|
+
file: c.file
|
|
8668
|
+
});
|
|
8669
|
+
}
|
|
8670
|
+
const header = readRel("sections/header.candy") || "";
|
|
8671
|
+
const productTpl = readRel("templates/product.candy") || "";
|
|
8672
|
+
const collectionTpl = readRel("templates/collection.candy") || "";
|
|
8673
|
+
const cartTpl = readRel("templates/cart.candy") || "";
|
|
8674
|
+
const searchTpl = readRel("templates/search.candy") || "";
|
|
8675
|
+
const productCard = readRel("snippets/product-card.candy") || "";
|
|
8676
|
+
const themeCss = readRel("assets/theme.css") || "";
|
|
8677
|
+
checks.push({
|
|
8678
|
+
id: "commerce.navigation_header",
|
|
8679
|
+
category: "commerce",
|
|
8680
|
+
status: header.includes("linklists") || header.includes("<nav") ? "passed" : "warning",
|
|
8681
|
+
message: header.includes("linklists") ? "Header wires merchant navigation via linklists." : 'Header should render merchant linklists["main-menu"].links.',
|
|
8682
|
+
file: "sections/header.candy"
|
|
8683
|
+
});
|
|
8684
|
+
checks.push({
|
|
8685
|
+
id: "commerce.cart_count_badge",
|
|
8686
|
+
category: "commerce",
|
|
8687
|
+
status: header.includes("js-cart-count") ? "passed" : "warning",
|
|
8688
|
+
message: header.includes("js-cart-count") ? "Header includes .js-cart-count live cart counter." : "Header is missing .js-cart-count live cart badge.",
|
|
8689
|
+
file: "sections/header.candy"
|
|
8690
|
+
});
|
|
8691
|
+
const combinedProduct = `${productTpl}
|
|
8692
|
+
${productCard}`;
|
|
8693
|
+
const hasSyntheticVariant = /data-variant-id\s*=\s*["'][^"']*-default["']/i.test(combinedProduct);
|
|
8694
|
+
checks.push({
|
|
8695
|
+
id: "commerce.variant_id_contract",
|
|
8696
|
+
category: "commerce",
|
|
8697
|
+
status: hasSyntheticVariant ? "failed" : "passed",
|
|
8698
|
+
message: hasSyntheticVariant ? 'Synthetic "-default" variant ID detected; guard data-variant-id with product.has_inventory_variants.' : 'No synthetic "-default" variant IDs detected.'
|
|
8699
|
+
});
|
|
8700
|
+
checks.push({
|
|
8701
|
+
id: "commerce.product_template",
|
|
8702
|
+
category: "commerce",
|
|
8703
|
+
status: productTpl.trim().length > 0 ? "passed" : "failed",
|
|
8704
|
+
message: productTpl.trim().length > 0 ? "templates/product.candy exists." : "Missing templates/product.candy.",
|
|
8705
|
+
file: "templates/product.candy"
|
|
8706
|
+
});
|
|
8707
|
+
checks.push({
|
|
8708
|
+
id: "commerce.collection_template",
|
|
8709
|
+
category: "commerce",
|
|
8710
|
+
status: collectionTpl.trim().length > 0 ? "passed" : "failed",
|
|
8711
|
+
message: collectionTpl.trim().length > 0 ? "templates/collection.candy exists." : "Missing templates/collection.candy.",
|
|
8712
|
+
file: "templates/collection.candy"
|
|
8713
|
+
});
|
|
8714
|
+
checks.push({
|
|
8715
|
+
id: "commerce.cart_template",
|
|
8716
|
+
category: "commerce",
|
|
8717
|
+
status: cartTpl.trim().length > 0 ? "passed" : "failed",
|
|
8718
|
+
message: cartTpl.trim().length > 0 ? "templates/cart.candy exists." : "Missing templates/cart.candy.",
|
|
8719
|
+
file: "templates/cart.candy"
|
|
8720
|
+
});
|
|
8721
|
+
checks.push({
|
|
8722
|
+
id: "commerce.search_template",
|
|
8723
|
+
category: "commerce",
|
|
8724
|
+
status: searchTpl.trim().length > 0 ? "passed" : "warning",
|
|
8725
|
+
message: searchTpl.trim().length > 0 ? "templates/search.candy exists." : "Missing templates/search.candy.",
|
|
8726
|
+
file: "templates/search.candy"
|
|
8727
|
+
});
|
|
8728
|
+
let hasAnyPluginHook = false;
|
|
8729
|
+
try {
|
|
8730
|
+
const { bundle } = loadCandyThemeFromDirectory(dir);
|
|
8731
|
+
hasAnyPluginHook = Object.values(bundle.files).some((src) => /\{%-?\s*hook\s+['"]/.test(src));
|
|
8732
|
+
} catch {}
|
|
8733
|
+
checks.push({
|
|
8734
|
+
id: "plugins.extension_hooks",
|
|
8735
|
+
category: "plugins",
|
|
8736
|
+
status: hasAnyPluginHook ? "passed" : "warning",
|
|
8737
|
+
message: hasAnyPluginHook ? 'Theme includes {% hook "..." %} plugin extension slots.' : 'No {% hook "..." %} plugin extension slots detected. Add product/cart/header/footer hooks for plugin compatibility.'
|
|
8738
|
+
});
|
|
8739
|
+
const hasResponsiveMedia = /@media\s*\(/.test(themeCss) || themeCss.includes("clamp(") || themeCss.includes("grid-template-columns");
|
|
8740
|
+
checks.push({
|
|
8741
|
+
id: "responsive.css_layout",
|
|
8742
|
+
category: "responsive",
|
|
8743
|
+
status: hasResponsiveMedia ? "passed" : "warning",
|
|
8744
|
+
message: hasResponsiveMedia ? "assets/theme.css includes responsive layout rules." : "assets/theme.css lacks responsive @media or fluid grid rules.",
|
|
8745
|
+
file: "assets/theme.css"
|
|
8746
|
+
});
|
|
8747
|
+
const layout = readRel("layout/theme.candy") || "";
|
|
8748
|
+
const hasViewport = layout.includes("viewport") || !layout;
|
|
8749
|
+
const hasSkipOrAria = layout.includes("aria-") || header.includes("aria-label");
|
|
8750
|
+
checks.push({
|
|
8751
|
+
id: "accessibility.viewport_and_aria",
|
|
8752
|
+
category: "accessibility",
|
|
8753
|
+
status: hasViewport && hasSkipOrAria ? "passed" : "warning",
|
|
8754
|
+
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.',
|
|
8755
|
+
file: "layout/theme.candy"
|
|
8756
|
+
});
|
|
8757
|
+
const summary = {
|
|
8758
|
+
passed: checks.filter((c) => c.status === "passed").length,
|
|
8759
|
+
failed: checks.filter((c) => c.status === "failed").length,
|
|
8760
|
+
warnings: checks.filter((c) => c.status === "warning").length,
|
|
8761
|
+
skipped: checks.filter((c) => c.status === "skipped").length,
|
|
8762
|
+
blocked: checks.filter((c) => c.status === "blocked").length
|
|
8763
|
+
};
|
|
8764
|
+
return {
|
|
8765
|
+
generatedAt: new Date().toISOString(),
|
|
8766
|
+
themeDir: dir,
|
|
8767
|
+
slug,
|
|
8768
|
+
version,
|
|
8769
|
+
packageHash,
|
|
8770
|
+
sdkVersion: "1.2.1",
|
|
8771
|
+
runtimeVersion: "candy-1.0",
|
|
8772
|
+
status: summary.failed > 0 ? "failed" : summary.warnings > 0 ? "partial" : "passed",
|
|
8773
|
+
summary,
|
|
8774
|
+
checks
|
|
8775
|
+
};
|
|
8776
|
+
}
|
|
8777
|
+
|
|
8778
|
+
// src/cli/mcp/ui-patterns-tools.ts
|
|
8779
|
+
import { existsSync as existsSync11, readFileSync as readFileSync11 } from "node:fs";
|
|
8780
|
+
import { join as join11, resolve as resolve9 } from "node:path";
|
|
8781
|
+
import { z as z6 } from "zod";
|
|
8782
|
+
function auditCandyUiConsistency(themeDir) {
|
|
8783
|
+
const dir = resolve9(themeDir);
|
|
8784
|
+
const readRel = (rel) => {
|
|
8785
|
+
const p = join11(dir, rel);
|
|
8786
|
+
return existsSync11(p) ? readFileSync11(p, "utf8") : "";
|
|
8787
|
+
};
|
|
8788
|
+
const css = readRel("assets/theme.css");
|
|
8789
|
+
const productCard = readRel("snippets/product-card.candy");
|
|
8790
|
+
const cart = readRel("templates/cart.candy");
|
|
8791
|
+
const search = readRel("templates/search.candy");
|
|
8792
|
+
const collection = readRel("templates/collection.candy");
|
|
8793
|
+
const checks = [
|
|
8794
|
+
{
|
|
8795
|
+
id: "ui.design_tokens",
|
|
8796
|
+
status: css.includes(":root") && (css.includes("--cz-") || css.includes("--sf-")) ? "passed" : "warning",
|
|
8797
|
+
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."
|
|
8798
|
+
},
|
|
8799
|
+
{
|
|
8800
|
+
id: "ui.uniform_card_aspect_ratio",
|
|
8801
|
+
status: css.includes("aspect-ratio") && css.includes("object-fit") ? "passed" : "warning",
|
|
8802
|
+
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."
|
|
8803
|
+
},
|
|
8804
|
+
{
|
|
8805
|
+
id: "ui.responsive_breakpoints",
|
|
8806
|
+
status: /@media\s*\(max-width:/i.test(css) ? "passed" : "warning",
|
|
8807
|
+
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."
|
|
8808
|
+
},
|
|
8809
|
+
{
|
|
8810
|
+
id: "ui.reusable_product_card",
|
|
8811
|
+
status: productCard.trim().length > 0 ? "passed" : "failed",
|
|
8812
|
+
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."
|
|
8813
|
+
},
|
|
8814
|
+
{
|
|
8815
|
+
id: "ui.empty_states",
|
|
8816
|
+
status: [cart, search, collection].every((t) => /else|empty|no\s+/i.test(t)) ? "passed" : "warning",
|
|
8817
|
+
message: "Checked Cart, Search, and Collection templates for empty/zero-result states."
|
|
8818
|
+
}
|
|
8819
|
+
];
|
|
8820
|
+
const failed = checks.filter((c) => c.status === "failed").length;
|
|
8821
|
+
const warnings = checks.filter((c) => c.status === "warning").length;
|
|
8822
|
+
return {
|
|
8823
|
+
themeDir: dir,
|
|
8824
|
+
status: failed > 0 ? "failed" : warnings > 0 ? "partial" : "passed",
|
|
8825
|
+
summary: { passed: checks.length - failed - warnings, failed, warnings },
|
|
8826
|
+
checks
|
|
8827
|
+
};
|
|
8828
|
+
}
|
|
8829
|
+
|
|
6961
8830
|
// src/cli/caartzee-cli.ts
|
|
6962
8831
|
async function runCli(rawArgs, io = {}) {
|
|
6963
8832
|
const log = io.stdout ?? console.log;
|
|
@@ -7005,18 +8874,34 @@ async function runCli(rawArgs, io = {}) {
|
|
|
7005
8874
|
case "dev":
|
|
7006
8875
|
return await handleDev(args, log, error);
|
|
7007
8876
|
case "sync-manifest": {
|
|
7008
|
-
const theme = await loadLocalTheme(
|
|
7009
|
-
writeFileSync5(
|
|
8877
|
+
const theme = await loadLocalTheme(resolve10(args[0] || process.cwd()));
|
|
8878
|
+
writeFileSync5(resolve10(args[0] || process.cwd(), "manifest.json"), JSON.stringify(theme.manifest, null, 2));
|
|
7010
8879
|
log("Exported runtime theme manifest.");
|
|
7011
8880
|
return 0;
|
|
7012
8881
|
}
|
|
8882
|
+
case "doctor":
|
|
8883
|
+
return await handleDoctor(args, log, error);
|
|
8884
|
+
case "version":
|
|
8885
|
+
return await handleVersion(args, log, error);
|
|
7013
8886
|
case "validate":
|
|
7014
8887
|
return await handleValidate(args, log, error);
|
|
7015
8888
|
case "build":
|
|
7016
8889
|
return await handleBuild(args, log, error);
|
|
8890
|
+
case "test":
|
|
8891
|
+
return await handleTestSuite(args, "all", log, error);
|
|
8892
|
+
case "audit":
|
|
8893
|
+
return await handleTestSuite(args, "audit", log, error);
|
|
8894
|
+
case "test-editor":
|
|
8895
|
+
return await handleTestEditor(args, log, error);
|
|
8896
|
+
case "test-commerce":
|
|
8897
|
+
return await handleTestSuite(args, "commerce", log, error);
|
|
8898
|
+
case "test-report":
|
|
8899
|
+
return await handleTestReport(args, log, error);
|
|
8900
|
+
case "ui-audit":
|
|
8901
|
+
return await handleUiAudit(args, log, error);
|
|
7017
8902
|
case "ide":
|
|
7018
8903
|
case "ide-setup": {
|
|
7019
|
-
const targetDir = args[0] ?
|
|
8904
|
+
const targetDir = args[0] ? resolve10(args[0]) : process.cwd();
|
|
7020
8905
|
const res = installCandyIdeSupport({ workspaceDir: targetDir });
|
|
7021
8906
|
log(`
|
|
7022
8907
|
\uD83C\uDFA8 Installed Candy (.candy) IDE language support:`);
|
|
@@ -7050,16 +8935,23 @@ async function handleInit(args, log, error) {
|
|
|
7050
8935
|
throw new Error("Supported templates: commerce");
|
|
7051
8936
|
args = args.filter((_, index) => index !== templateIndex && index !== templateIndex + 1);
|
|
7052
8937
|
}
|
|
7053
|
-
const sdkPath = fileURLToPath3(new URL("../../", import.meta.url));
|
|
7054
|
-
const sdkVersion = existsSync9(join9(sdkPath, "src/index.ts")) ? undefined : JSON.parse(readFileSync9(join9(sdkPath, "package.json"), "utf8")).version;
|
|
7055
8938
|
const engineIndex = args.indexOf("--engine");
|
|
7056
|
-
const engine = engineIndex < 0 ?
|
|
8939
|
+
const engine = engineIndex < 0 ? "typescript" : args[engineIndex + 1];
|
|
7057
8940
|
if (engine !== "typescript" && engine !== "candy")
|
|
7058
8941
|
throw new Error("Supported engines are candy and typescript.");
|
|
7059
8942
|
if (commerce && engine === "candy")
|
|
7060
8943
|
throw new Error("The commerce scaffold uses TypeScript.");
|
|
7061
8944
|
if (engineIndex >= 0)
|
|
7062
8945
|
args = args.filter((_, index) => index !== engineIndex && index !== engineIndex + 1);
|
|
8946
|
+
const presetIndex = args.indexOf("--preset");
|
|
8947
|
+
const presetRaw = presetIndex < 0 ? undefined : args[presetIndex + 1];
|
|
8948
|
+
if (presetIndex >= 0) {
|
|
8949
|
+
if (!presetRaw || !CANDY_DESIGN_PRESET_IDS.includes(presetRaw)) {
|
|
8950
|
+
throw new Error(`Supported presets: ${CANDY_DESIGN_PRESET_IDS.join(", ")}`);
|
|
8951
|
+
}
|
|
8952
|
+
args = args.filter((_, index) => index !== presetIndex && index !== presetIndex + 1);
|
|
8953
|
+
}
|
|
8954
|
+
const preset = presetRaw;
|
|
7063
8955
|
const dirIndex = args.indexOf("--dir");
|
|
7064
8956
|
const dir = dirIndex < 0 ? undefined : args[dirIndex + 1];
|
|
7065
8957
|
if (dirIndex >= 0 && !dir)
|
|
@@ -7067,7 +8959,7 @@ async function handleInit(args, log, error) {
|
|
|
7067
8959
|
if (dirIndex >= 0)
|
|
7068
8960
|
args = args.filter((_, index) => index !== dirIndex && index !== dirIndex + 1);
|
|
7069
8961
|
const nameArg = args[0];
|
|
7070
|
-
const targetDir =
|
|
8962
|
+
const targetDir = resolve10(dir || args[1] || nameArg || "my-caartzee-theme");
|
|
7071
8963
|
const themeName = nameArg || "My Caartzee Theme";
|
|
7072
8964
|
log(`
|
|
7073
8965
|
\uD83D\uDCE6 Scaffolding new Caartzee theme in: ${targetDir}`);
|
|
@@ -7075,10 +8967,10 @@ async function handleInit(args, log, error) {
|
|
|
7075
8967
|
const create = commerce ? scaffoldCommerceTheme : scaffoldTheme;
|
|
7076
8968
|
const result = await create({
|
|
7077
8969
|
targetDir,
|
|
7078
|
-
sdkPath,
|
|
7079
|
-
sdkVersion,
|
|
8970
|
+
sdkPath: fileURLToPath3(new URL("../../", import.meta.url)),
|
|
7080
8971
|
name: themeName,
|
|
7081
|
-
engine
|
|
8972
|
+
engine,
|
|
8973
|
+
...preset ? { preset } : {}
|
|
7082
8974
|
});
|
|
7083
8975
|
log(`✨ Successfully generated theme "${result.name}" (${result.slug})!`);
|
|
7084
8976
|
log(` Created ${result.createdFiles.length} files:`);
|
|
@@ -7090,11 +8982,10 @@ async function handleInit(args, log, error) {
|
|
|
7090
8982
|
}
|
|
7091
8983
|
log(`
|
|
7092
8984
|
\uD83D\uDE80 Next steps:`);
|
|
7093
|
-
log(` 1. cd
|
|
7094
|
-
log(
|
|
8985
|
+
log(` 1. cd ${nameArg || "my-caartzee-theme"}`);
|
|
8986
|
+
log(` 2. bun install && bun run dev # preview your theme with mock data`);
|
|
7095
8987
|
log(` 3. Generate app SDK access in your developer portal`);
|
|
7096
|
-
log(
|
|
7097
|
-
` : ` 4. bun run validate
|
|
8988
|
+
log(` 4. bun run validate # check before submission
|
|
7098
8989
|
`);
|
|
7099
8990
|
return 0;
|
|
7100
8991
|
} catch (err) {
|
|
@@ -7211,17 +9102,20 @@ async function handleDev(args, log, error) {
|
|
|
7211
9102
|
let port = 3333;
|
|
7212
9103
|
let themeDir = process.cwd();
|
|
7213
9104
|
let store;
|
|
9105
|
+
let editor = false;
|
|
7214
9106
|
for (let i = 0;i < args.length; i++) {
|
|
7215
9107
|
if (args[i] === "--port" && args[i + 1]) {
|
|
7216
9108
|
port = parseInt(args[i + 1], 10);
|
|
7217
9109
|
i++;
|
|
7218
9110
|
} else if (args[i] === "--dir" && args[i + 1]) {
|
|
7219
|
-
themeDir =
|
|
9111
|
+
themeDir = resolve10(args[i + 1]);
|
|
7220
9112
|
i++;
|
|
7221
9113
|
} else if (args[i] === "--store") {
|
|
7222
9114
|
store = args[++i];
|
|
7223
9115
|
if (!store || store.startsWith("-"))
|
|
7224
9116
|
throw new Error("--store requires a store domain or tenant ID.");
|
|
9117
|
+
} else if (args[i] === "--editor") {
|
|
9118
|
+
editor = true;
|
|
7225
9119
|
}
|
|
7226
9120
|
}
|
|
7227
9121
|
log(`
|
|
@@ -7247,10 +9141,17 @@ async function handleDev(args, log, error) {
|
|
|
7247
9141
|
};
|
|
7248
9142
|
await loadCatalog({});
|
|
7249
9143
|
}
|
|
7250
|
-
const instance = await startThemeDevServer({
|
|
9144
|
+
const instance = await startThemeDevServer({
|
|
9145
|
+
port,
|
|
9146
|
+
themeDir,
|
|
9147
|
+
editor,
|
|
9148
|
+
...store ? { storeLabel: store } : {},
|
|
9149
|
+
...loadCatalog ? { loadCatalog } : {}
|
|
9150
|
+
});
|
|
7251
9151
|
log(` \x1B[32m✓ Local Preview ready at:\x1B[0m \x1B[36m${instance.url}\x1B[0m`);
|
|
7252
|
-
log(
|
|
7253
|
-
log(
|
|
9152
|
+
log(` \x1B[32m✓ Local Theme Editor ready at:\x1B[0m \x1B[36m${instance.editorUrl}\x1B[0m`);
|
|
9153
|
+
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.");
|
|
9154
|
+
log(` • Inspect storefront context at: ${instance.url}/_api/context`);
|
|
7254
9155
|
log(` • Press Ctrl+C to stop.
|
|
7255
9156
|
`);
|
|
7256
9157
|
if (process.env.CAARTZEE_DEV_ONESHOT === "true") {
|
|
@@ -7274,21 +9175,21 @@ Shutting down dev server...`);
|
|
|
7274
9175
|
}
|
|
7275
9176
|
}
|
|
7276
9177
|
async function handleValidate(args, log, error) {
|
|
7277
|
-
const targetDir = args[0] ?
|
|
9178
|
+
const targetDir = args[0] ? resolve10(args[0]) : process.cwd();
|
|
7278
9179
|
log(`
|
|
7279
9180
|
\uD83D\uDEE1️ Running Caartzee Theme Security & Package Validation...`);
|
|
7280
9181
|
log(` Target: ${targetDir}`);
|
|
7281
|
-
const manifestPath =
|
|
7282
|
-
if (!
|
|
9182
|
+
const manifestPath = join12(targetDir, "manifest.json");
|
|
9183
|
+
if (!existsSync12(manifestPath)) {
|
|
7283
9184
|
error(`❌ Missing manifest.json in ${targetDir}`);
|
|
7284
9185
|
return 1;
|
|
7285
9186
|
}
|
|
7286
9187
|
try {
|
|
7287
|
-
if (
|
|
9188
|
+
if (existsSync12(join12(targetDir, "src/manifest.ts")) && typeof Bun !== "undefined") {
|
|
7288
9189
|
const theme = await loadLocalTheme(targetDir);
|
|
7289
9190
|
writeFileSync5(manifestPath, JSON.stringify(theme.manifest, null, 2));
|
|
7290
9191
|
}
|
|
7291
|
-
const rawManifest = JSON.parse(
|
|
9192
|
+
const rawManifest = JSON.parse(readFileSync12(manifestPath, "utf-8"));
|
|
7292
9193
|
const manifestCheck = ThemePackageValidator.validateManifest(rawManifest);
|
|
7293
9194
|
if (!manifestCheck.success) {
|
|
7294
9195
|
error(`❌ Manifest validation failed:`);
|
|
@@ -7327,7 +9228,7 @@ async function handleValidate(args, log, error) {
|
|
|
7327
9228
|
}
|
|
7328
9229
|
}
|
|
7329
9230
|
async function handleBuild(args, log, error) {
|
|
7330
|
-
const targetDir = args[0] ?
|
|
9231
|
+
const targetDir = args[0] ? resolve10(args[0]) : process.cwd();
|
|
7331
9232
|
log(`
|
|
7332
9233
|
\uD83D\uDD28 Building Caartzee Theme Package...`);
|
|
7333
9234
|
log(` Source directory: ${targetDir}`);
|
|
@@ -7339,9 +9240,9 @@ async function handleBuild(args, log, error) {
|
|
|
7339
9240
|
}
|
|
7340
9241
|
return 1;
|
|
7341
9242
|
}
|
|
7342
|
-
const isCandy =
|
|
7343
|
-
const distDir =
|
|
7344
|
-
if (!
|
|
9243
|
+
const isCandy = existsSync12(join12(targetDir, "candy.config.json")) || existsSync12(join12(targetDir, "layout", "theme.candy")) || valResult.manifest?.engine === "candy";
|
|
9244
|
+
const distDir = join12(targetDir, "dist");
|
|
9245
|
+
if (!existsSync12(distDir)) {
|
|
7345
9246
|
mkdirSync5(distDir, { recursive: true });
|
|
7346
9247
|
}
|
|
7347
9248
|
if (isCandy) {
|
|
@@ -7354,8 +9255,8 @@ async function handleBuild(args, log, error) {
|
|
|
7354
9255
|
}
|
|
7355
9256
|
return 1;
|
|
7356
9257
|
}
|
|
7357
|
-
const bundlePath =
|
|
7358
|
-
const manifestOutPath =
|
|
9258
|
+
const bundlePath = join12(distDir, "candy-theme-bundle.json");
|
|
9259
|
+
const manifestOutPath = join12(distDir, "manifest.json");
|
|
7359
9260
|
writeFileSync5(bundlePath, JSON.stringify(bundle, null, 2), "utf-8");
|
|
7360
9261
|
writeFileSync5(manifestOutPath, JSON.stringify(bundle.manifest, null, 2), "utf-8");
|
|
7361
9262
|
log(`✓ Extracted ${Object.keys(bundle.sectionSchemas).length} section schemas`);
|
|
@@ -7365,7 +9266,7 @@ async function handleBuild(args, log, error) {
|
|
|
7365
9266
|
return 0;
|
|
7366
9267
|
}
|
|
7367
9268
|
if (valResult.manifest) {
|
|
7368
|
-
const manifestOutPath =
|
|
9269
|
+
const manifestOutPath = join12(distDir, "manifest.json");
|
|
7369
9270
|
writeFileSync5(manifestOutPath, JSON.stringify(valResult.manifest, null, 2), "utf-8");
|
|
7370
9271
|
log(`✓ Wrote validated manifest to ${manifestOutPath}
|
|
7371
9272
|
`);
|
|
@@ -7384,10 +9285,10 @@ async function handlePush(args, log, error) {
|
|
|
7384
9285
|
error(`❌ Insufficient scope. Your account lacks "theme:publish" permissions.`);
|
|
7385
9286
|
return 1;
|
|
7386
9287
|
}
|
|
7387
|
-
const targetDir = args[0] ?
|
|
7388
|
-
if (
|
|
9288
|
+
const targetDir = args[0] ? resolve10(args[0]) : process.cwd();
|
|
9289
|
+
if (existsSync12(join12(targetDir, "src/manifest.ts")) && typeof Bun !== "undefined") {
|
|
7389
9290
|
const theme = await loadLocalTheme(targetDir);
|
|
7390
|
-
writeFileSync5(
|
|
9291
|
+
writeFileSync5(join12(targetDir, "manifest.json"), JSON.stringify(theme.manifest, null, 2));
|
|
7391
9292
|
}
|
|
7392
9293
|
const valResult = await ThemePackageValidator.validatePackage(targetDir);
|
|
7393
9294
|
if (!valResult.valid) {
|
|
@@ -7408,10 +9309,284 @@ async function handlePush(args, log, error) {
|
|
|
7408
9309
|
`);
|
|
7409
9310
|
return 0;
|
|
7410
9311
|
}
|
|
9312
|
+
async function handleDoctor(args, log, error) {
|
|
9313
|
+
const targetDir = args[0] ? resolve10(args[0]) : process.cwd();
|
|
9314
|
+
log(`
|
|
9315
|
+
\uD83E\uDE7A Running Caartzee Candy Theme Doctor...`);
|
|
9316
|
+
log(` Target: ${targetDir}
|
|
9317
|
+
`);
|
|
9318
|
+
const issues = [];
|
|
9319
|
+
const warnings = [];
|
|
9320
|
+
const passed = [];
|
|
9321
|
+
const readIfExists = (rel) => {
|
|
9322
|
+
const full = join12(targetDir, rel);
|
|
9323
|
+
return existsSync12(full) ? readFileSync12(full, "utf8") : null;
|
|
9324
|
+
};
|
|
9325
|
+
const configRaw = readIfExists("candy.config.json");
|
|
9326
|
+
const manifestRaw = readIfExists("manifest.json");
|
|
9327
|
+
if (!configRaw)
|
|
9328
|
+
issues.push("Missing candy.config.json in theme root.");
|
|
9329
|
+
if (!manifestRaw)
|
|
9330
|
+
issues.push('Missing manifest.json. Run "caartzee-theme sync-manifest .".');
|
|
9331
|
+
let configJson = null;
|
|
9332
|
+
let manifestJson = null;
|
|
9333
|
+
try {
|
|
9334
|
+
if (configRaw)
|
|
9335
|
+
configJson = JSON.parse(configRaw);
|
|
9336
|
+
} catch {
|
|
9337
|
+
issues.push("candy.config.json is invalid JSON.");
|
|
9338
|
+
}
|
|
9339
|
+
try {
|
|
9340
|
+
if (manifestRaw)
|
|
9341
|
+
manifestJson = JSON.parse(manifestRaw);
|
|
9342
|
+
} catch {
|
|
9343
|
+
issues.push("manifest.json is invalid JSON.");
|
|
9344
|
+
}
|
|
9345
|
+
if (configJson && manifestJson) {
|
|
9346
|
+
if (configJson.slug !== manifestJson.slug) {
|
|
9347
|
+
issues.push(`Slug mismatch: candy.config.json ("${configJson.slug}") != manifest.json ("${manifestJson.slug}").`);
|
|
9348
|
+
} else {
|
|
9349
|
+
passed.push(`Slug aligned ("${configJson.slug}")`);
|
|
9350
|
+
}
|
|
9351
|
+
if (configJson.version !== manifestJson.version) {
|
|
9352
|
+
warnings.push(`Version mismatch: candy.config.json (${configJson.version}) != manifest.json (${manifestJson.version}). Run "caartzee-theme sync-manifest .".`);
|
|
9353
|
+
} else {
|
|
9354
|
+
passed.push(`Version aligned (v${configJson.version})`);
|
|
9355
|
+
}
|
|
9356
|
+
}
|
|
9357
|
+
const caps = manifestJson?.capabilities;
|
|
9358
|
+
const usesShell = Array.isArray(caps) ? caps.includes("storefront-shell") : caps?.["storefront-shell"] === true;
|
|
9359
|
+
const hasCommerce = Array.isArray(caps) ? caps.includes("commerce_pages") : caps?.commerce_pages === true;
|
|
9360
|
+
if (usesShell && hasCommerce) {
|
|
9361
|
+
passed.push("Storefront Shell + commerce_pages capabilities enabled");
|
|
9362
|
+
} else {
|
|
9363
|
+
warnings.push('Set capabilities: { "storefront-shell": true, "commerce_pages": true } in manifest.json for live cart/checkout/auth.');
|
|
9364
|
+
}
|
|
9365
|
+
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"];
|
|
9366
|
+
for (const name of templateNames) {
|
|
9367
|
+
const content = readIfExists(join12("templates", name));
|
|
9368
|
+
if (!content)
|
|
9369
|
+
continue;
|
|
9370
|
+
if (usesShell && /\{%\s*layout\s+/i.test(content)) {
|
|
9371
|
+
issues.push(`templates/${name} uses {% layout %}, which causes duplicate headers/footers when storefront-shell is enabled.`);
|
|
9372
|
+
}
|
|
9373
|
+
if (/data-variant-id\s*=\s*["'][^"']*-default["']/i.test(content)) {
|
|
9374
|
+
issues.push(`templates/${name} emits a synthetic "-default" variant ID, which causes POST /_api/cart 422 errors.`);
|
|
9375
|
+
}
|
|
9376
|
+
}
|
|
9377
|
+
const productCard = readIfExists(join12("snippets", "product-card.candy"));
|
|
9378
|
+
if (productCard) {
|
|
9379
|
+
if (/data-variant-id\s*=\s*["'][^"']*-default["']/i.test(productCard)) {
|
|
9380
|
+
issues.push('snippets/product-card.candy emits a synthetic "-default" variant ID. Guard data-variant-id with product.has_inventory_variants.');
|
|
9381
|
+
} else {
|
|
9382
|
+
passed.push("Product card variant ID contract looks safe");
|
|
9383
|
+
}
|
|
9384
|
+
}
|
|
9385
|
+
const headerCandy = readIfExists(join12("sections", "header.candy"));
|
|
9386
|
+
if (headerCandy) {
|
|
9387
|
+
if (!headerCandy.includes("js-cart-count")) {
|
|
9388
|
+
warnings.push("sections/header.candy is missing .js-cart-count on the cart badge (live Add to Cart count won't update).");
|
|
9389
|
+
} else {
|
|
9390
|
+
passed.push("Header cart count badge (.js-cart-count) present");
|
|
9391
|
+
}
|
|
9392
|
+
if (!headerCandy.includes("menuId") || !headerCandy.includes("linklists")) {
|
|
9393
|
+
warnings.push(`sections/header.candy should include "menuId" schema setting and render linklists['main-menu'].links.`);
|
|
9394
|
+
} else {
|
|
9395
|
+
passed.push("Header navigation menu (menuId + linklists) wired");
|
|
9396
|
+
}
|
|
9397
|
+
}
|
|
9398
|
+
const heroCandy = readIfExists(join12("sections", "hero-banner.candy"));
|
|
9399
|
+
if (heroCandy) {
|
|
9400
|
+
if (!heroCandy.includes("mobile_sliders")) {
|
|
9401
|
+
warnings.push("sections/hero-banner.candy does not read mobile_sliders (merchant Mobile Slider changes won't reflect).");
|
|
9402
|
+
} else {
|
|
9403
|
+
passed.push("Hero banner mobile_sliders support present");
|
|
9404
|
+
}
|
|
9405
|
+
}
|
|
9406
|
+
const loginCandy = readIfExists(join12("templates", "login.candy"));
|
|
9407
|
+
const registerCandy = readIfExists(join12("templates", "register.candy"));
|
|
9408
|
+
if (loginCandy) {
|
|
9409
|
+
if (!loginCandy.includes("/_api/auth/login") || !loginCandy.includes("js-auth-form")) {
|
|
9410
|
+
issues.push('templates/login.candy must post to /_api/auth/login with class="js-auth-form".');
|
|
9411
|
+
} else {
|
|
9412
|
+
passed.push("Login page (/login) auth contract verified");
|
|
9413
|
+
}
|
|
9414
|
+
}
|
|
9415
|
+
if (registerCandy) {
|
|
9416
|
+
if (!registerCandy.includes("/_api/auth/register") || !registerCandy.includes("js-auth-form")) {
|
|
9417
|
+
issues.push('templates/register.candy must post to /_api/auth/register with class="js-auth-form".');
|
|
9418
|
+
} else {
|
|
9419
|
+
passed.push("Signup page (/signup, /register) auth contract verified");
|
|
9420
|
+
}
|
|
9421
|
+
}
|
|
9422
|
+
if (readIfExists(join12("assets", "theme.css")))
|
|
9423
|
+
passed.push("assets/theme.css found");
|
|
9424
|
+
else
|
|
9425
|
+
warnings.push("assets/theme.css not found.");
|
|
9426
|
+
if (readIfExists(join12("assets", "theme.js")))
|
|
9427
|
+
passed.push("assets/theme.js found");
|
|
9428
|
+
else
|
|
9429
|
+
warnings.push("assets/theme.js not found.");
|
|
9430
|
+
for (const p of passed)
|
|
9431
|
+
log(` ✓ ${p}`);
|
|
9432
|
+
if (warnings.length > 0) {
|
|
9433
|
+
log("");
|
|
9434
|
+
for (const w of warnings)
|
|
9435
|
+
log(` ⚠️ ${w}`);
|
|
9436
|
+
}
|
|
9437
|
+
if (issues.length > 0) {
|
|
9438
|
+
log("");
|
|
9439
|
+
for (const i of issues)
|
|
9440
|
+
error(` ❌ ${i}`);
|
|
9441
|
+
log(`
|
|
9442
|
+
❌ Doctor found ${issues.length} error(s) and ${warnings.length} warning(s).
|
|
9443
|
+
`);
|
|
9444
|
+
return 1;
|
|
9445
|
+
}
|
|
9446
|
+
log(`
|
|
9447
|
+
✅ Theme Doctor passed! (${passed.length} checks passed, ${warnings.length} warning(s))
|
|
9448
|
+
`);
|
|
9449
|
+
return 0;
|
|
9450
|
+
}
|
|
9451
|
+
async function handleVersion(args, log, error) {
|
|
9452
|
+
const bump = args[0]?.trim();
|
|
9453
|
+
const targetDir = args[1] ? resolve10(args[1]) : process.cwd();
|
|
9454
|
+
if (!bump) {
|
|
9455
|
+
error("Usage: caartzee-theme version <patch|minor|major|x.y.z> [path]");
|
|
9456
|
+
return 1;
|
|
9457
|
+
}
|
|
9458
|
+
const configPath = join12(targetDir, "candy.config.json");
|
|
9459
|
+
const manifestPath = join12(targetDir, "manifest.json");
|
|
9460
|
+
if (!existsSync12(configPath) && !existsSync12(manifestPath)) {
|
|
9461
|
+
error(`No candy.config.json or manifest.json found in ${targetDir}`);
|
|
9462
|
+
return 1;
|
|
9463
|
+
}
|
|
9464
|
+
const readJson = (p) => JSON.parse(readFileSync12(p, "utf8"));
|
|
9465
|
+
const current = existsSync12(configPath) ? String(readJson(configPath).version || "1.0.0") : String(readJson(manifestPath).version || "1.0.0");
|
|
9466
|
+
let nextVersion = bump;
|
|
9467
|
+
if (bump === "patch" || bump === "minor" || bump === "major") {
|
|
9468
|
+
const parts = current.split(".").map((n) => parseInt(n, 10) || 0);
|
|
9469
|
+
const [maj = 1, min = 0, pat = 0] = parts;
|
|
9470
|
+
nextVersion = bump === "major" ? `${maj + 1}.0.0` : bump === "minor" ? `${maj}.${min + 1}.0` : `${maj}.${min}.${pat + 1}`;
|
|
9471
|
+
} else if (!/^\d+\.\d+\.\d+$/.test(bump)) {
|
|
9472
|
+
error(`Invalid version "${bump}". Use patch, minor, major, or semver like 1.0.3.`);
|
|
9473
|
+
return 1;
|
|
9474
|
+
}
|
|
9475
|
+
if (existsSync12(configPath)) {
|
|
9476
|
+
const cfg = readJson(configPath);
|
|
9477
|
+
cfg.version = nextVersion;
|
|
9478
|
+
writeFileSync5(configPath, JSON.stringify(cfg, null, 2) + `
|
|
9479
|
+
`, "utf8");
|
|
9480
|
+
}
|
|
9481
|
+
if (existsSync12(manifestPath)) {
|
|
9482
|
+
const man = readJson(manifestPath);
|
|
9483
|
+
man.version = nextVersion;
|
|
9484
|
+
writeFileSync5(manifestPath, JSON.stringify(man, null, 2) + `
|
|
9485
|
+
`, "utf8");
|
|
9486
|
+
}
|
|
9487
|
+
log(`✓ Bumped theme version: ${current} -> ${nextVersion}`);
|
|
9488
|
+
return 0;
|
|
9489
|
+
}
|
|
9490
|
+
function parseTargetAndJson(args) {
|
|
9491
|
+
const asJson = args.includes("--json");
|
|
9492
|
+
const positional = args.filter((a) => !a.startsWith("-"));
|
|
9493
|
+
const targetDir = positional[0] ? resolve10(positional[0]) : process.cwd();
|
|
9494
|
+
return { targetDir, asJson };
|
|
9495
|
+
}
|
|
9496
|
+
async function handleTestEditor(args, log, error) {
|
|
9497
|
+
const { targetDir, asJson } = parseTargetAndJson(args);
|
|
9498
|
+
const result = validateThemeEditorDirectory(targetDir);
|
|
9499
|
+
if (asJson) {
|
|
9500
|
+
log(JSON.stringify(result, null, 2));
|
|
9501
|
+
return result.valid ? 0 : 1;
|
|
9502
|
+
}
|
|
9503
|
+
log(`
|
|
9504
|
+
\uD83C\uDFA8 Caartzee Theme Editor Compatibility Check (${result.slug || targetDir})`);
|
|
9505
|
+
for (const c of result.checks) {
|
|
9506
|
+
const icon = c.status === "passed" ? "✓" : c.status === "warning" ? "⚠️" : "❌";
|
|
9507
|
+
(c.status === "failed" ? error : log)(` ${icon} [${c.name}] ${c.message}${c.file ? ` (${c.file})` : ""}`);
|
|
9508
|
+
}
|
|
9509
|
+
log(`
|
|
9510
|
+
${result.valid ? "✅" : "❌"} Theme Editor check: ${result.summary.passed} passed, ${result.summary.failed} failed, ${result.summary.warnings} warning(s).
|
|
9511
|
+
`);
|
|
9512
|
+
return result.valid ? 0 : 1;
|
|
9513
|
+
}
|
|
9514
|
+
async function handleTestSuite(args, mode, log, error) {
|
|
9515
|
+
const { targetDir, asJson } = parseTargetAndJson(args);
|
|
9516
|
+
const fullReport = await runThemeReadinessAudit(targetDir);
|
|
9517
|
+
const checks = mode === "commerce" ? fullReport.checks.filter((c) => c.category === "commerce" || c.category === "plugins") : fullReport.checks;
|
|
9518
|
+
const failed = checks.filter((c) => c.status === "failed").length;
|
|
9519
|
+
const passed = checks.filter((c) => c.status === "passed").length;
|
|
9520
|
+
const warnings = checks.filter((c) => c.status === "warning").length;
|
|
9521
|
+
const payload = {
|
|
9522
|
+
...fullReport,
|
|
9523
|
+
mode,
|
|
9524
|
+
status: failed > 0 ? "failed" : warnings > 0 ? "partial" : "passed",
|
|
9525
|
+
summary: { ...fullReport.summary, passed, failed, warnings },
|
|
9526
|
+
checks
|
|
9527
|
+
};
|
|
9528
|
+
if (asJson) {
|
|
9529
|
+
log(JSON.stringify(payload, null, 2));
|
|
9530
|
+
return failed > 0 ? 1 : 0;
|
|
9531
|
+
}
|
|
9532
|
+
const label = mode === "commerce" ? "Commerce & Plugin Hooks Test" : mode === "audit" ? "Theme Readiness Audit" : "Storefront Test Suite";
|
|
9533
|
+
log(`
|
|
9534
|
+
\uD83E\uDDEA Caartzee ${label} — ${payload.slug}@${payload.version}`);
|
|
9535
|
+
log(` Package Hash: ${payload.packageHash.slice(0, 16)}...`);
|
|
9536
|
+
for (const c of checks) {
|
|
9537
|
+
const icon = c.status === "passed" ? "✓" : c.status === "warning" ? "⚠️" : "❌";
|
|
9538
|
+
(c.status === "failed" ? error : log)(` ${icon} [${c.category}/${c.id}] ${c.message}${c.file ? ` (${c.file})` : ""}`);
|
|
9539
|
+
}
|
|
9540
|
+
log(`
|
|
9541
|
+
${failed === 0 ? "✅" : "❌"} Result: ${passed} passed, ${failed} failed, ${warnings} warning(s).
|
|
9542
|
+
`);
|
|
9543
|
+
return failed > 0 ? 1 : 0;
|
|
9544
|
+
}
|
|
9545
|
+
async function handleTestReport(args, log, error) {
|
|
9546
|
+
const { targetDir, asJson } = parseTargetAndJson(args);
|
|
9547
|
+
const report = await runThemeReadinessAudit(targetDir);
|
|
9548
|
+
const distDir = join12(targetDir, "dist");
|
|
9549
|
+
if (!existsSync12(distDir))
|
|
9550
|
+
mkdirSync5(distDir, { recursive: true });
|
|
9551
|
+
const outPath = join12(distDir, "theme-readiness-report.json");
|
|
9552
|
+
writeFileSync5(outPath, JSON.stringify(report, null, 2), "utf8");
|
|
9553
|
+
if (asJson) {
|
|
9554
|
+
log(JSON.stringify({ reportPath: outPath, ...report }, null, 2));
|
|
9555
|
+
} else {
|
|
9556
|
+
log(`
|
|
9557
|
+
\uD83D\uDCC4 Wrote readiness report bound to packageHash ${report.packageHash.slice(0, 16)}...`);
|
|
9558
|
+
log(` Path: ${outPath}`);
|
|
9559
|
+
log(` Status: ${report.status.toUpperCase()} (${report.summary.passed} passed, ${report.summary.failed} failed, ${report.summary.warnings} warning(s))
|
|
9560
|
+
`);
|
|
9561
|
+
}
|
|
9562
|
+
if (report.summary.failed > 0) {
|
|
9563
|
+
error(`Theme readiness report recorded ${report.summary.failed} failing check(s).`);
|
|
9564
|
+
return 1;
|
|
9565
|
+
}
|
|
9566
|
+
return 0;
|
|
9567
|
+
}
|
|
9568
|
+
async function handleUiAudit(args, log, error) {
|
|
9569
|
+
const { targetDir, asJson } = parseTargetAndJson(args);
|
|
9570
|
+
const report = auditCandyUiConsistency(targetDir);
|
|
9571
|
+
if (asJson) {
|
|
9572
|
+
log(JSON.stringify(report, null, 2));
|
|
9573
|
+
return report.summary.failed > 0 ? 1 : 0;
|
|
9574
|
+
}
|
|
9575
|
+
log(`
|
|
9576
|
+
\uD83C\uDFA8 Caartzee Candy UI Consistency Audit (${targetDir})`);
|
|
9577
|
+
for (const c of report.checks) {
|
|
9578
|
+
const icon = c.status === "passed" ? "✓" : c.status === "warning" ? "⚠️" : "❌";
|
|
9579
|
+
(c.status === "failed" ? error : log)(` ${icon} [${c.id}] ${c.message}`);
|
|
9580
|
+
}
|
|
9581
|
+
log(`
|
|
9582
|
+
${report.summary.failed === 0 ? "✅" : "❌"} UI Audit: ${report.summary.passed} passed, ${report.summary.failed} failed, ${report.summary.warnings} warning(s).
|
|
9583
|
+
`);
|
|
9584
|
+
return report.summary.failed > 0 ? 1 : 0;
|
|
9585
|
+
}
|
|
7411
9586
|
function printHelp(log) {
|
|
7412
9587
|
log(`
|
|
7413
9588
|
╔═══════════════════════════════════════════════════════════════╗
|
|
7414
|
-
║ CAARTZEE THEME SDK CLI (v1.
|
|
9589
|
+
║ CAARTZEE THEME SDK CLI (v1.2.1) ║
|
|
7415
9590
|
║ Build, test, and publish secure storefront themes locally ║
|
|
7416
9591
|
╚═══════════════════════════════════════════════════════════════╝
|
|
7417
9592
|
|
|
@@ -7420,16 +9595,26 @@ Usage:
|
|
|
7420
9595
|
npx @caartzee/theme-sdk <command> [options]
|
|
7421
9596
|
|
|
7422
9597
|
Commands:
|
|
7423
|
-
init [name]
|
|
7424
|
-
dev [--port 3333] [--store DOMAIN]
|
|
7425
|
-
|
|
7426
|
-
|
|
9598
|
+
init [name] [--engine candy] [--preset minimal-luxury|streetwear-editorial|organic-wellness|modern-tech|vibrant-d2c]
|
|
9599
|
+
dev [--port 3333] [--store DOMAIN] [--editor] Preview with full local commerce/auth & Theme Editor
|
|
9600
|
+
ui-audit [path] [--json] Audit design tokens, uniform card aspect ratios, responsive CSS & empty states
|
|
9601
|
+
doctor [path] Audit storefront-shell, cart/variant hooks, auth forms, menus & mobile sliders
|
|
9602
|
+
version <patch|minor|major|x.y.z> [path] Bump version across candy.config.json and manifest.json
|
|
9603
|
+
sync-manifest [path] Export the locally authored theme manifest to JSON
|
|
9604
|
+
validate [path] Check source patterns and validate manifest
|
|
9605
|
+
test [path] [--json] Run full storefront validation, editor, commerce, security & responsive suite
|
|
9606
|
+
audit [path] [--json] Run comprehensive readiness, accessibility, security & commerce audit
|
|
9607
|
+
test-editor [path] [--json] Verify Theme Editor schemas, block attributes & live rendering
|
|
9608
|
+
test-commerce [path] [--json] Verify cart, variant, wishlist, search, auth & plugin contracts
|
|
9609
|
+
test-report [path] [--json] Generate packageHash-bound dist/theme-readiness-report.json
|
|
9610
|
+
build [path] Compile Candy templates and assets into dist/candy-theme-bundle.json
|
|
9611
|
+
ide-setup [path] Install .candy syntax highlighting for VS Code / Cursor / Antigravity
|
|
9612
|
+
connect --clipboard Connect using the Windows clipboard
|
|
9613
|
+
connect --stdin Connect using a piped Developer Portal connection
|
|
7427
9614
|
login --api URL --token-stdin Connect with app SDK access from developer portal
|
|
7428
9615
|
whoami Display current developer account & token status
|
|
7429
9616
|
logout Securely clear saved local credentials
|
|
7430
|
-
|
|
7431
|
-
validate [path] Check source patterns and validate manifest
|
|
7432
|
-
push Validate and push theme to Caartzee Partner Portal
|
|
9617
|
+
push [path] Validate and push theme to Caartzee Partner Portal
|
|
7433
9618
|
help Display this help message
|
|
7434
9619
|
|
|
7435
9620
|
Security Guarantee:
|