@caartzee/theme-sdk 1.0.0 → 1.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +208 -20
- package/dist/bin/caartzee-theme.js +1855 -81
- package/dist/lib/index.js +1857 -81
- 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/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/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 existsSync11, mkdirSync as mkdirSync5, readFileSync as readFileSync11, writeFileSync as writeFileSync5 } from "node:fs";
|
|
140
|
+
import { resolve as resolve9, join as join11 } 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";
|
|
@@ -1171,13 +1174,42 @@ function scaffoldCandyThemeInternal(params) {
|
|
|
1171
1174
|
</div>
|
|
1172
1175
|
</section>
|
|
1173
1176
|
`);
|
|
1174
|
-
writeFile("sections/header.candy", `<header class="cz-candy-header">
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
<
|
|
1179
|
-
|
|
1180
|
-
|
|
1177
|
+
writeFile("sections/header.candy", `<header class="cz-candy-header" style="background:{{ section.settings.bg_color | default: '#ffffff' }};color:{{ section.settings.text_color | default: '#0f172a' }};">
|
|
1178
|
+
{% if section.settings.show_announcement and section.settings.announcement_text != blank %}
|
|
1179
|
+
<div class="cz-announcement-bar">
|
|
1180
|
+
{% hook 'header_announcement_before' %}
|
|
1181
|
+
<span>{{ section.settings.announcement_text | escape }}</span>
|
|
1182
|
+
{% hook 'header_announcement_after' %}
|
|
1183
|
+
</div>
|
|
1184
|
+
{% endif %}
|
|
1185
|
+
<div class="cz-header-inner">
|
|
1186
|
+
<a href="/" class="cz-header-logo" aria-label="{{ shop.name | escape }}">
|
|
1187
|
+
{% if section.settings.logo != blank %}
|
|
1188
|
+
<img src="{{ section.settings.logo }}" alt="{{ shop.name | escape }}" style="max-width:{{ section.settings.logo_width | default: 120 }}px;" />
|
|
1189
|
+
{% else %}
|
|
1190
|
+
<span>{{ shop.name | escape }}</span>
|
|
1191
|
+
{% endif %}
|
|
1192
|
+
</a>
|
|
1193
|
+
<nav aria-label="Main navigation">
|
|
1194
|
+
{% assign nav_handle = section.settings.menuId | default: 'main-menu' %}
|
|
1195
|
+
{% if linklists[nav_handle].links.size > 0 %}
|
|
1196
|
+
{% for link in linklists[nav_handle].links %}
|
|
1197
|
+
<a href="{{ link.url }}">{{ link.title | escape }}</a>
|
|
1198
|
+
{% endfor %}
|
|
1199
|
+
{% else %}
|
|
1200
|
+
{% for block in section.blocks %}
|
|
1201
|
+
<a href="{{ block.settings.url }}" {{ block.candy_attributes }}>{{ block.settings.label | escape }}</a>
|
|
1202
|
+
{% endfor %}
|
|
1203
|
+
{% endif %}
|
|
1204
|
+
</nav>
|
|
1205
|
+
<div class="cz-header-actions">
|
|
1206
|
+
{% hook 'header_actions' %}
|
|
1207
|
+
{% if section.settings.show_search %}<a href="/search" aria-label="Search">Search</a>{% endif %}
|
|
1208
|
+
{% if section.settings.show_wishlist %}<a href="/wishlist" aria-label="Wishlist">Wishlist</a>{% endif %}
|
|
1209
|
+
{% if section.settings.show_account %}<a href="/account" aria-label="Account">Account</a>{% endif %}
|
|
1210
|
+
{% 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 %}
|
|
1211
|
+
</div>
|
|
1212
|
+
</div>
|
|
1181
1213
|
</header>
|
|
1182
1214
|
{% schema %}
|
|
1183
1215
|
{
|
|
@@ -1186,8 +1218,19 @@ function scaffoldCandyThemeInternal(params) {
|
|
|
1186
1218
|
"category": "Header",
|
|
1187
1219
|
"allowedRegions": ["header"],
|
|
1188
1220
|
"settings": [
|
|
1221
|
+
{ "id": "logo", "type": "image", "label": "Logo Image" },
|
|
1222
|
+
{ "id": "logo_width", "type": "range", "label": "Logo Width (px)", "min": 60, "max": 240, "step": 4, "default": 120 },
|
|
1223
|
+
{ "id": "mobile_logo", "type": "image", "label": "Mobile Logo" },
|
|
1224
|
+
{ "id": "show_announcement", "type": "checkbox", "label": "Show Announcement Bar", "default": true },
|
|
1225
|
+
{ "id": "announcement_text", "type": "text", "label": "Top Announcement", "default": "Free express shipping on all orders over $150." },
|
|
1226
|
+
{ "id": "bg_color", "type": "color", "label": "Background Color", "default": "#ffffff" },
|
|
1227
|
+
{ "id": "text_color", "type": "color", "label": "Text Color", "default": "#0f172a" },
|
|
1228
|
+
{ "id": "menuId", "type": "select", "label": "Navigation Menu", "options": [] },
|
|
1189
1229
|
{ "id": "sticky", "type": "checkbox", "label": "Sticky Header", "default": true },
|
|
1190
|
-
{ "id": "
|
|
1230
|
+
{ "id": "show_search", "type": "checkbox", "label": "Show Search", "default": true },
|
|
1231
|
+
{ "id": "show_wishlist", "type": "checkbox", "label": "Show Wishlist", "default": true },
|
|
1232
|
+
{ "id": "show_account", "type": "checkbox", "label": "Show Account", "default": true },
|
|
1233
|
+
{ "id": "show_cart", "type": "checkbox", "label": "Show Cart", "default": true }
|
|
1191
1234
|
],
|
|
1192
1235
|
"blocks": [
|
|
1193
1236
|
{
|
|
@@ -1204,9 +1247,24 @@ function scaffoldCandyThemeInternal(params) {
|
|
|
1204
1247
|
{% endschema %}
|
|
1205
1248
|
`);
|
|
1206
1249
|
writeFile("sections/hero-banner.candy", `<section class="cz-candy-hero">
|
|
1250
|
+
{% if mobile_sliders.size > 0 %}
|
|
1251
|
+
<div class="cz-mobile-sliders" data-mobile-sliders="true">
|
|
1252
|
+
{% for slide in mobile_sliders %}
|
|
1253
|
+
<a href="{{ slide.url | default: '/products' }}"><img src="{{ slide.image }}" alt="{{ slide.title | escape }}" /></a>
|
|
1254
|
+
{% endfor %}
|
|
1255
|
+
</div>
|
|
1256
|
+
{% endif %}
|
|
1257
|
+
{% if section.settings.desktop_image != blank %}
|
|
1258
|
+
<img class="cz-hero-desktop-img" src="{{ section.settings.desktop_image }}" alt="{{ section.settings.heading | escape }}" />
|
|
1259
|
+
{% endif %}
|
|
1207
1260
|
<h1>{{ section.settings.heading | escape }}</h1>
|
|
1208
1261
|
<p>{{ section.settings.subheading | escape }}</p>
|
|
1209
1262
|
<a href="{{ section.settings.button_url }}">{{ section.settings.button_label | escape }}</a>
|
|
1263
|
+
{% for block in section.blocks %}
|
|
1264
|
+
<div class="cz-hero-slide" {{ block.candy_attributes }}>
|
|
1265
|
+
<strong>{{ block.settings.title | escape }}</strong>
|
|
1266
|
+
</div>
|
|
1267
|
+
{% endfor %}
|
|
1210
1268
|
</section>
|
|
1211
1269
|
{% schema %}
|
|
1212
1270
|
{
|
|
@@ -1217,10 +1275,23 @@ function scaffoldCandyThemeInternal(params) {
|
|
|
1217
1275
|
"settings": [
|
|
1218
1276
|
{ "id": "heading", "type": "text", "label": "Heading", "default": "Curated Elegance for Modern Living." },
|
|
1219
1277
|
{ "id": "subheading", "type": "textarea", "label": "Subheading", "default": "Handcrafted essentials designed to endure." },
|
|
1278
|
+
{ "id": "desktop_image", "type": "image", "label": "Desktop Banner Image" },
|
|
1279
|
+
{ "id": "mobile_image", "type": "image", "label": "Mobile Banner Image" },
|
|
1220
1280
|
{ "id": "button_label", "type": "text", "label": "Button Label", "default": "Explore Collection" },
|
|
1221
1281
|
{ "id": "button_url", "type": "url", "label": "Button URL", "default": "/products" }
|
|
1222
1282
|
],
|
|
1223
|
-
"blocks": [
|
|
1283
|
+
"blocks": [
|
|
1284
|
+
{
|
|
1285
|
+
"type": "slide",
|
|
1286
|
+
"name": "Hero Slide",
|
|
1287
|
+
"limit": 6,
|
|
1288
|
+
"settings": [
|
|
1289
|
+
{ "id": "title", "type": "text", "label": "Slide Title", "default": "New Arrivals" },
|
|
1290
|
+
{ "id": "image", "type": "image", "label": "Slide Image" },
|
|
1291
|
+
{ "id": "url", "type": "url", "label": "Slide Link", "default": "/products" }
|
|
1292
|
+
]
|
|
1293
|
+
}
|
|
1294
|
+
]
|
|
1224
1295
|
}
|
|
1225
1296
|
{% endschema %}
|
|
1226
1297
|
`);
|
|
@@ -1269,8 +1340,25 @@ function scaffoldCandyThemeInternal(params) {
|
|
|
1269
1340
|
}
|
|
1270
1341
|
{% endschema %}
|
|
1271
1342
|
`);
|
|
1272
|
-
writeFile("sections/footer.candy", `<footer class="cz-candy-footer">
|
|
1273
|
-
|
|
1343
|
+
writeFile("sections/footer.candy", `<footer class="cz-candy-footer" style="background:{{ section.settings.bg_color | default: '#0f172a' }};color:{{ section.settings.text_color | default: '#f8fafc' }};">
|
|
1344
|
+
{% hook 'footer_widgets_before' %}
|
|
1345
|
+
<div class="cz-footer-grid">
|
|
1346
|
+
<div class="cz-footer-brand">
|
|
1347
|
+
{% if section.settings.logo != blank %}<img src="{{ section.settings.logo }}" alt="{{ shop.name | escape }}" />{% else %}<strong>{{ shop.name | escape }}</strong>{% endif %}
|
|
1348
|
+
<p>{{ section.settings.description | escape }}</p>
|
|
1349
|
+
</div>
|
|
1350
|
+
{% for block in section.blocks %}
|
|
1351
|
+
<div class="cz-footer-col" {{ block.candy_attributes }}>
|
|
1352
|
+
<h4>{{ block.settings.heading | escape }}</h4>
|
|
1353
|
+
<a href="{{ block.settings.url | default: '/products' }}">{{ block.settings.link_label | default: 'Browse' | escape }}</a>
|
|
1354
|
+
</div>
|
|
1355
|
+
{% endfor %}
|
|
1356
|
+
</div>
|
|
1357
|
+
{% hook 'footer_widgets_after' %}
|
|
1358
|
+
<div class="cz-footer-bottom">
|
|
1359
|
+
<p>{{ section.settings.copyright_text | escape }}</p>
|
|
1360
|
+
{% hook 'footer_bottom' %}
|
|
1361
|
+
</div>
|
|
1274
1362
|
</footer>
|
|
1275
1363
|
{% schema %}
|
|
1276
1364
|
{
|
|
@@ -1279,14 +1367,88 @@ function scaffoldCandyThemeInternal(params) {
|
|
|
1279
1367
|
"category": "Footer",
|
|
1280
1368
|
"allowedRegions": ["footer"],
|
|
1281
1369
|
"settings": [
|
|
1370
|
+
{ "id": "logo", "type": "image", "label": "Footer Logo" },
|
|
1371
|
+
{ "id": "description", "type": "textarea", "label": "Store Description", "default": "Thoughtfully crafted products delivered to your door." },
|
|
1372
|
+
{ "id": "bg_color", "type": "color", "label": "Background Color", "default": "#0f172a" },
|
|
1373
|
+
{ "id": "text_color", "type": "color", "label": "Text Color", "default": "#f8fafc" },
|
|
1374
|
+
{ "id": "show_newsletter", "type": "checkbox", "label": "Show Newsletter Signup", "default": true },
|
|
1282
1375
|
{ "id": "copyright_text", "type": "text", "label": "Copyright Notice", "default": "© Caartzee Storefront. Powered by Candy." }
|
|
1283
1376
|
],
|
|
1284
|
-
"blocks": [
|
|
1377
|
+
"blocks": [
|
|
1378
|
+
{
|
|
1379
|
+
"type": "link_column",
|
|
1380
|
+
"name": "Footer Column",
|
|
1381
|
+
"limit": 4,
|
|
1382
|
+
"settings": [
|
|
1383
|
+
{ "id": "heading", "type": "text", "label": "Column Heading", "default": "Quick Links" },
|
|
1384
|
+
{ "id": "link_label", "type": "text", "label": "Link Label", "default": "Shop All" },
|
|
1385
|
+
{ "id": "url", "type": "url", "label": "Link URL", "default": "/products" }
|
|
1386
|
+
]
|
|
1387
|
+
}
|
|
1388
|
+
]
|
|
1285
1389
|
}
|
|
1286
1390
|
{% endschema %}
|
|
1391
|
+
`);
|
|
1392
|
+
writeFile("templates/login.candy", `<section class="cz-auth-section">
|
|
1393
|
+
<h1>Sign In</h1>
|
|
1394
|
+
{% hook 'login_form_top' %}
|
|
1395
|
+
<form action="/_api/auth/login" method="POST" class="js-auth-form" data-redirect="{{ redirect_url | default: '/account' | escape }}">
|
|
1396
|
+
<input type="email" name="email" required placeholder="Email address" />
|
|
1397
|
+
<input type="password" name="password" required placeholder="Password" />
|
|
1398
|
+
<input type="hidden" name="redirect" value="{{ redirect_url | default: '/account' | escape }}" />
|
|
1399
|
+
<button type="submit" class="js-submit-btn">Sign In</button>
|
|
1400
|
+
{% if google_auth_enabled %}
|
|
1401
|
+
<button type="button" class="js-firebase-google-btn">Continue with Google</button>
|
|
1402
|
+
{% endif %}
|
|
1403
|
+
</form>
|
|
1404
|
+
{% hook 'login_form_bottom' %}
|
|
1405
|
+
</section>
|
|
1406
|
+
`);
|
|
1407
|
+
writeFile("templates/register.candy", `<section class="cz-auth-section">
|
|
1408
|
+
<h1>Create Account</h1>
|
|
1409
|
+
{% hook 'signup_form_top' %}
|
|
1410
|
+
<form action="/_api/auth/register" method="POST" class="js-auth-form" data-redirect="{{ redirect_url | default: '/account' | escape }}">
|
|
1411
|
+
<input type="text" name="firstName" required placeholder="First name" />
|
|
1412
|
+
<input type="text" name="lastName" placeholder="Last name" />
|
|
1413
|
+
<input type="email" name="email" required placeholder="Email address" />
|
|
1414
|
+
<input type="password" name="password" minlength="6" required placeholder="Password" />
|
|
1415
|
+
<input type="hidden" name="redirect" value="{{ redirect_url | default: '/account' | escape }}" />
|
|
1416
|
+
<button type="submit" class="js-submit-btn">Create Account</button>
|
|
1417
|
+
</form>
|
|
1418
|
+
{% hook 'signup_form_bottom' %}
|
|
1419
|
+
</section>
|
|
1420
|
+
`);
|
|
1421
|
+
writeFile("templates/wishlist.candy", `<section class="cz-wishlist-section">
|
|
1422
|
+
<h1>My Wishlist</h1>
|
|
1423
|
+
<p>Saved items appear here when signed in or in an active browser session.</p>
|
|
1424
|
+
</section>
|
|
1287
1425
|
`);
|
|
1288
1426
|
writeFile("snippets/price.candy", `<span class="candy-price">{{ product.price | money }}</span>
|
|
1289
1427
|
`);
|
|
1428
|
+
if (!existsSync3(join4(rootDir, "AGENTS.md")))
|
|
1429
|
+
writeFile("AGENTS.md", AGENTS_default);
|
|
1430
|
+
if (!existsSync3(join4(rootDir, "CLAUDE.md"))) {
|
|
1431
|
+
writeFile("CLAUDE.md", `# Claude Code Instructions — Caartzee Candy Storefront
|
|
1432
|
+
|
|
1433
|
+
Read [AGENTS.md](./AGENTS.md) and call the Candy MCP tool \`read_candy_guide\` before editing any files.
|
|
1434
|
+
|
|
1435
|
+
## Key Rules
|
|
1436
|
+
- Use Candy MCP (\`list_store_permissions\`, \`request_store_access\`, \`read_store_catalog\`) for authorized merchant data.
|
|
1437
|
+
- Keep every section editable via \`{% schema %}\` and emit \`{{ block.candy_attributes }}\` on blocks.
|
|
1438
|
+
- Never emit synthetic \`-default\` variant IDs or invent API endpoints.
|
|
1439
|
+
- Run \`caartzee-theme doctor .\`, \`caartzee-theme validate .\`, \`caartzee-theme test . --json\`, and \`caartzee-theme build .\` before finishing.
|
|
1440
|
+
- Never run \`caartzee-theme push\` without explicit developer authorization.
|
|
1441
|
+
`);
|
|
1442
|
+
}
|
|
1443
|
+
if (!existsSync3(join4(rootDir, ".cursorrules"))) {
|
|
1444
|
+
writeFile(".cursorrules", `# Caartzee Candy Theme Rules
|
|
1445
|
+
- Follow AGENTS.md and Candy MCP documentation (call read_candy_guide first).
|
|
1446
|
+
- Preserve merchant content, section IDs, Theme Editor schemas, {{ block.candy_attributes }}, cart/wishlist/auth runtime hooks, and {% hook "..." %} plugin slots.
|
|
1447
|
+
- Use document-level event delegation in assets/theme.js so UI survives live Theme Editor section re-rendering.
|
|
1448
|
+
- Never hardcode merchant products, prices, currencies, payment gateways, or secrets.
|
|
1449
|
+
- Verify changes with caartzee-theme doctor ., caartzee-theme validate ., caartzee-theme test . --json, and caartzee-theme build ..
|
|
1450
|
+
`);
|
|
1451
|
+
}
|
|
1290
1452
|
writeFile("snippets/product-card.candy", candyStarterProductCard);
|
|
1291
1453
|
writeFile("schemas/settings_schema.json", JSON.stringify([
|
|
1292
1454
|
{
|
|
@@ -1298,6 +1460,9 @@ function scaffoldCandyThemeInternal(params) {
|
|
|
1298
1460
|
], null, 2));
|
|
1299
1461
|
writeFile("assets/theme.css", candyStarterCss);
|
|
1300
1462
|
writeFile("assets/theme.js", `window.__CAARTZEE_CANDY_THEME__ = true;
|
|
1463
|
+
document.addEventListener('caartzee:section:load', function () {
|
|
1464
|
+
// Re-initialize any section-specific UI widgets after Theme Editor live swaps.
|
|
1465
|
+
});
|
|
1301
1466
|
`);
|
|
1302
1467
|
writeFile("locales/en.default.json", JSON.stringify({
|
|
1303
1468
|
general: {
|
|
@@ -2322,13 +2487,94 @@ ${cssBlocks.join(`
|
|
|
2322
2487
|
|
|
2323
2488
|
// src/dev-server/theme-preview.ts
|
|
2324
2489
|
var escape = (value) => String(value ?? "").replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]);
|
|
2325
|
-
function
|
|
2490
|
+
function renderBuiltInCommerceShellPage(context) {
|
|
2491
|
+
const ctx = context;
|
|
2492
|
+
const cart = ctx.cart || { items: [], subtotal: 0, discount: 0, tax: 0, shipping: 0, total: 0, itemCount: 0 };
|
|
2493
|
+
const customer = ctx.customer || { loggedIn: false, orders: [] };
|
|
2494
|
+
const orders = Array.isArray(ctx.orders) ? ctx.orders : [];
|
|
2495
|
+
if (context.pageType === "login") {
|
|
2496
|
+
return `<section style="max-width:420px;margin:48px auto;padding:24px;border:1px solid #e2e8f0;border-radius:12px;">
|
|
2497
|
+
<h1 style="margin:0 0 8px;">Customer Sign In</h1>
|
|
2498
|
+
<p style="font-size:13px;color:#64748b;margin:0 0 16px;">Sandbox demo account: <code>demo@caartzee.local</code> / <code>password123</code></p>
|
|
2499
|
+
<form action="/_api/auth/login" method="POST" class="js-auth-form" data-redirect="/account" style="display:grid;gap:12px;">
|
|
2500
|
+
<input name="email" type="email" required placeholder="Email" value="demo@caartzee.local" style="padding:10px;border:1px solid #cbd5e1;border-radius:8px;" />
|
|
2501
|
+
<input name="password" type="password" required placeholder="Password" value="password123" style="padding:10px;border:1px solid #cbd5e1;border-radius:8px;" />
|
|
2502
|
+
<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>
|
|
2503
|
+
<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>
|
|
2504
|
+
</form>
|
|
2505
|
+
<p style="font-size:13px;margin-top:14px;">New shopper? <a href="/register">Create an account</a></p>
|
|
2506
|
+
</section>`;
|
|
2507
|
+
}
|
|
2508
|
+
if (context.pageType === "signup") {
|
|
2509
|
+
return `<section style="max-width:440px;margin:48px auto;padding:24px;border:1px solid #e2e8f0;border-radius:12px;">
|
|
2510
|
+
<h1 style="margin:0 0 16px;">Create Customer Account</h1>
|
|
2511
|
+
<form action="/_api/auth/register" method="POST" class="js-auth-form" data-redirect="/account" style="display:grid;gap:12px;">
|
|
2512
|
+
<input name="firstName" required placeholder="First Name" style="padding:10px;border:1px solid #cbd5e1;border-radius:8px;" />
|
|
2513
|
+
<input name="lastName" placeholder="Last Name" style="padding:10px;border:1px solid #cbd5e1;border-radius:8px;" />
|
|
2514
|
+
<input name="email" type="email" required placeholder="Email" style="padding:10px;border:1px solid #cbd5e1;border-radius:8px;" />
|
|
2515
|
+
<input name="password" type="password" minlength="6" required placeholder="Password" style="padding:10px;border:1px solid #cbd5e1;border-radius:8px;" />
|
|
2516
|
+
<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>
|
|
2517
|
+
</form>
|
|
2518
|
+
</section>`;
|
|
2519
|
+
}
|
|
2520
|
+
if (context.pageType === "checkout") {
|
|
2521
|
+
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("");
|
|
2522
|
+
return `<section style="max-width:720px;margin:40px auto;padding:24px;border:1px solid #e2e8f0;border-radius:12px;">
|
|
2523
|
+
<h1 style="margin:0 0 6px;">Caartzee Sandbox Checkout</h1>
|
|
2524
|
+
<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>
|
|
2525
|
+
<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>
|
|
2526
|
+
<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>
|
|
2527
|
+
<form class="js-checkout-form" style="display:grid;gap:10px;">
|
|
2528
|
+
<input name="fullName" required placeholder="Full Name" value="${escape(customer.name || "Sandbox Shopper")}" style="padding:10px;border:1px solid #cbd5e1;border-radius:8px;" />
|
|
2529
|
+
<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;" />
|
|
2530
|
+
<input name="address1" required placeholder="Street Address" value="100 Sandbox Way" style="padding:10px;border:1px solid #cbd5e1;border-radius:8px;" />
|
|
2531
|
+
<input name="city" required placeholder="City" value="Testville" style="padding:10px;border:1px solid #cbd5e1;border-radius:8px;" />
|
|
2532
|
+
<input type="hidden" name="gateway" value="caartzee_test_sandbox" />
|
|
2533
|
+
<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>
|
|
2534
|
+
</form>
|
|
2535
|
+
</section>`;
|
|
2536
|
+
}
|
|
2537
|
+
if (context.pageType === "account") {
|
|
2538
|
+
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("");
|
|
2539
|
+
return `<section style="max-width:720px;margin:40px auto;padding:24px;border:1px solid #e2e8f0;border-radius:12px;">
|
|
2540
|
+
<div style="display:flex;justify-content:space-between;align-items:center;">
|
|
2541
|
+
<h1 style="margin:0;">Customer Account</h1>
|
|
2542
|
+
${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>'}
|
|
2543
|
+
</div>
|
|
2544
|
+
<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>
|
|
2545
|
+
<h3>Sandbox Order History (${orders.length})</h3>
|
|
2546
|
+
<ul style="list-style:none;padding:0;">${orderRows || "<li>No sandbox orders placed yet.</li>"}</ul>
|
|
2547
|
+
</section>`;
|
|
2548
|
+
}
|
|
2549
|
+
if (context.pageType === "order-success") {
|
|
2550
|
+
const latest = orders[0];
|
|
2551
|
+
return `<section style="max-width:600px;margin:48px auto;padding:24px;border:1px solid #bbf7d0;background:#f0fdf4;border-radius:12px;">
|
|
2552
|
+
<h1 style="margin:0 0 8px;color:#166534;">Sandbox Order Confirmed</h1>
|
|
2553
|
+
<p>${latest ? `Order <strong>${escape(latest.orderNumber)}</strong> placed for $${Number(latest.total).toFixed(2)} via sandbox payment.` : "Order confirmed in sandbox session."}</p>
|
|
2554
|
+
<p><a href="/account">View Order History</a> · <a href="/track-order">Track Order</a></p>
|
|
2555
|
+
</section>`;
|
|
2556
|
+
}
|
|
2557
|
+
if (context.pageType === "track-order") {
|
|
2558
|
+
const latest = orders[0];
|
|
2559
|
+
return `<section style="max-width:600px;margin:48px auto;padding:24px;border:1px solid #e2e8f0;border-radius:12px;">
|
|
2560
|
+
<h1 style="margin:0 0 12px;">Track Sandbox Order</h1>
|
|
2561
|
+
<p>${latest ? `Latest sandbox order <strong>${escape(latest.orderNumber)}</strong> — Status: <strong>${escape(latest.status)}</strong>` : "No sandbox orders in this session yet."}</p>
|
|
2562
|
+
</section>`;
|
|
2563
|
+
}
|
|
2564
|
+
return null;
|
|
2565
|
+
}
|
|
2566
|
+
function renderThemePreview(theme, context, preferContextSettings = false, editorOverride) {
|
|
2326
2567
|
const key = context.pageType === "product-list" ? "products" : context.pageType;
|
|
2327
2568
|
const page = theme.defaultTemplates.pages[key] || theme.defaultTemplates.pages[context.pageType];
|
|
2328
2569
|
const settings = theme.manifest.defaultGlobalSettings || {};
|
|
2329
|
-
context = {
|
|
2330
|
-
|
|
2331
|
-
|
|
2570
|
+
context = {
|
|
2571
|
+
...context,
|
|
2572
|
+
themeSlug: theme.slug,
|
|
2573
|
+
globalSettings: preferContextSettings ? { ...settings, ...context.globalSettings, ...editorOverride?.globalSettings || {} } : { ...context.globalSettings, ...settings, ...editorOverride?.globalSettings || {} }
|
|
2574
|
+
};
|
|
2575
|
+
if (context.pageType === "home") {
|
|
2576
|
+
context = { ...context, sections: editorOverride?.bodySections || page?.regions.body || [] };
|
|
2577
|
+
}
|
|
2332
2578
|
const render = (section) => {
|
|
2333
2579
|
const definition = theme.manifest.sections.find((s) => s.type === section.type);
|
|
2334
2580
|
const defaults = Object.fromEntries((definition?.settings || []).map((f) => [f.id, f.default]));
|
|
@@ -2349,15 +2595,23 @@ function renderThemePreview(theme, context, preferContextSettings = false) {
|
|
|
2349
2595
|
}
|
|
2350
2596
|
}), { section: resolved, themeSlug: theme.slug });
|
|
2351
2597
|
};
|
|
2352
|
-
const
|
|
2353
|
-
const
|
|
2598
|
+
const activeLayout = editorOverride?.layout || theme.defaultTemplates.layout;
|
|
2599
|
+
const header = (activeLayout.regions.header || []).map(render).join("");
|
|
2600
|
+
const footer = (activeLayout.regions.footer || []).map(render).join("");
|
|
2354
2601
|
const custom = theme.renderPage?.(context);
|
|
2355
2602
|
if (custom?.trimStart().toLowerCase().startsWith("<!doctype html"))
|
|
2356
2603
|
return custom;
|
|
2357
|
-
const body = custom || (page?.regions.body || []).map(render).join("");
|
|
2604
|
+
const body = custom || renderBuiltInCommerceShellPage(context) || (context.pageType === "home" ? editorOverride?.bodySections || page?.regions.body || [] : page?.regions.body || []).map(render).join("");
|
|
2358
2605
|
const missing = !body ? `<p>No template implemented for ${escape(context.pageType)}.</p>` : "";
|
|
2359
2606
|
const colors = theme.tokens?.colors || {};
|
|
2360
|
-
const variables = Object.entries({
|
|
2607
|
+
const variables = Object.entries({
|
|
2608
|
+
bg: colors.background,
|
|
2609
|
+
surface: colors.surface,
|
|
2610
|
+
text: colors.text,
|
|
2611
|
+
"text-muted": colors.muted,
|
|
2612
|
+
border: colors.border,
|
|
2613
|
+
primary: colors.primary
|
|
2614
|
+
}).filter(([, value]) => value).map(([k, value]) => `--sf-color-${k}:${value};`).join("");
|
|
2361
2615
|
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
2616
|
const themeCss = (tokenCss + (theme.tokens?.customCss || "")).replace(/<\/style/gi, "<\\/style");
|
|
2363
2617
|
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 +3479,7 @@ var SettingTypeSchema = z3.enum([
|
|
|
3225
3479
|
"radio",
|
|
3226
3480
|
"color",
|
|
3227
3481
|
"image",
|
|
3482
|
+
"image_picker",
|
|
3228
3483
|
"select",
|
|
3229
3484
|
"range",
|
|
3230
3485
|
"url",
|
|
@@ -4398,7 +4653,8 @@ function normalizeProductForCandy(product) {
|
|
|
4398
4653
|
const inventoryQuantity = Number(p.inventory_quantity ?? p.stockCount ?? (available ? 10 : 0));
|
|
4399
4654
|
const featuredImage = String(p.featured_image ?? p.imageUrl ?? p.image ?? "/assets/placeholder-product.svg");
|
|
4400
4655
|
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
|
|
4656
|
+
const rawUrl = String(p.url ?? p.productUrl ?? "").trim();
|
|
4657
|
+
const url = rawUrl.startsWith("/products/") ? rawUrl : `/products/${encodeURIComponent(handle)}`;
|
|
4402
4658
|
const description = String(p.description ?? p.summary ?? p.shortDescription ?? "");
|
|
4403
4659
|
const rawVariants = Array.isArray(p.variants) ? p.variants : Array.isArray(p.inventoryDetails) && p.inventoryDetails.length > 0 ? p.inventoryDetails.map((inv, idx) => ({
|
|
4404
4660
|
id: inv.id ?? `${id}-var-${idx + 1}`,
|
|
@@ -4508,6 +4764,7 @@ function normalizeCartForCandy(rawCart) {
|
|
|
4508
4764
|
const linePrice = item.line_price !== undefined ? Number(item.line_price) : item.final_line_price !== undefined ? Number(item.final_line_price) : price * qty;
|
|
4509
4765
|
const slug = String(item.handle ?? item.productSlug ?? item.slug ?? `item-${idx + 1}`);
|
|
4510
4766
|
const title = String(item.title ?? item.productName ?? item.name ?? "Item");
|
|
4767
|
+
const resolvedImage = String(item.image || item.imageUrl || item.img_url || item.image_url || item.product?.imageUrl || item.product?.image || "/assets/placeholder-product.svg");
|
|
4511
4768
|
return {
|
|
4512
4769
|
...item,
|
|
4513
4770
|
productId: item.productId ?? item.product_id ?? item.product?.id ?? item.id,
|
|
@@ -4524,9 +4781,9 @@ function normalizeCartForCandy(rawCart) {
|
|
|
4524
4781
|
line_price: linePrice,
|
|
4525
4782
|
final_line_price: linePrice,
|
|
4526
4783
|
url: String(item.url ?? `/products/${slug}`),
|
|
4527
|
-
image:
|
|
4784
|
+
image: resolvedImage,
|
|
4528
4785
|
featured_image: {
|
|
4529
|
-
url:
|
|
4786
|
+
url: resolvedImage,
|
|
4530
4787
|
alt: title
|
|
4531
4788
|
}
|
|
4532
4789
|
};
|
|
@@ -4720,7 +4977,47 @@ function buildCandyContext(options) {
|
|
|
4720
4977
|
`--font-body: ${mergedSettings.body_font};`
|
|
4721
4978
|
].join(" ");
|
|
4722
4979
|
const robotsMeta = pageContext.isPreview ? '<meta name="robots" content="noindex, nofollow" />' : '<meta name="robots" content="index, follow" />';
|
|
4723
|
-
const
|
|
4980
|
+
const hookNames = [
|
|
4981
|
+
"head_scripts",
|
|
4982
|
+
"body_start",
|
|
4983
|
+
"body_end",
|
|
4984
|
+
"header_actions",
|
|
4985
|
+
"header_announcement_before",
|
|
4986
|
+
"header_announcement_after",
|
|
4987
|
+
"footer_widgets_before",
|
|
4988
|
+
"footer_widgets_after",
|
|
4989
|
+
"footer_bottom",
|
|
4990
|
+
"login_form_top",
|
|
4991
|
+
"login_form_bottom",
|
|
4992
|
+
"signup_form_top",
|
|
4993
|
+
"signup_form_bottom",
|
|
4994
|
+
"product_price_after",
|
|
4995
|
+
"product_add_to_cart_before",
|
|
4996
|
+
"product_add_to_cart_after",
|
|
4997
|
+
"product_description_after",
|
|
4998
|
+
"product_reviews",
|
|
4999
|
+
"cart_items_after",
|
|
5000
|
+
"cart_drawer_bottom",
|
|
5001
|
+
"cart_summary_after",
|
|
5002
|
+
"checkout_payment_methods",
|
|
5003
|
+
"checkout_summary_after",
|
|
5004
|
+
"account_dashboard_top",
|
|
5005
|
+
"account_dashboard_bottom"
|
|
5006
|
+
];
|
|
5007
|
+
const hooksApi = pageContext.hooks;
|
|
5008
|
+
const extraHookKeys = hooksApi?.slots && typeof hooksApi.slots === "object" ? Object.keys(hooksApi.slots) : [];
|
|
5009
|
+
const allHookKeys = Array.from(new Set([...hookNames, ...extraHookKeys]));
|
|
5010
|
+
const renderedHooks = {};
|
|
5011
|
+
for (const key of allHookKeys) {
|
|
5012
|
+
let raw = "";
|
|
5013
|
+
if (typeof hooksApi?.render === "function") {
|
|
5014
|
+
raw = String(hooksApi.render(key) || "");
|
|
5015
|
+
} else if (typeof hooksApi?.[key] === "string") {
|
|
5016
|
+
raw = hooksApi[key];
|
|
5017
|
+
}
|
|
5018
|
+
renderedHooks[key] = raw ? markSafeHtml(raw) : "";
|
|
5019
|
+
}
|
|
5020
|
+
const hookScripts = typeof hooksApi?.render === "function" ? hooksApi.render("head_scripts") : hooksApi?.headEnd || "";
|
|
4724
5021
|
const headerHtml = [
|
|
4725
5022
|
`<meta name="generator" content="Caartzee Candy Engine 1.0" />`,
|
|
4726
5023
|
robotsMeta,
|
|
@@ -4790,6 +5087,17 @@ function buildCandyContext(options) {
|
|
|
4790
5087
|
image: campaign.imageUrl || campaign.image,
|
|
4791
5088
|
url: `/campaign/${encodeURIComponent(String(campaign.slug || campaign.id))}`
|
|
4792
5089
|
})),
|
|
5090
|
+
mobile_sliders: (Array.isArray(anyCtx.mobileSliders) ? anyCtx.mobileSliders : []).map((slide, idx) => ({
|
|
5091
|
+
id: slide.id ?? `slide-${idx + 1}`,
|
|
5092
|
+
title: String(slide.title || ""),
|
|
5093
|
+
description: String(slide.description || ""),
|
|
5094
|
+
image: String(slide.imageUrl || slide.image_url || slide.image || ""),
|
|
5095
|
+
image_url: String(slide.imageUrl || slide.image_url || slide.image || ""),
|
|
5096
|
+
button_text: String(slide.button_text || slide.buttonText || ""),
|
|
5097
|
+
button_url: String(slide.button_url || slide.buttonUrl || slide.url || "/products"),
|
|
5098
|
+
campaign: slide.campaign ? String(slide.campaign) : "",
|
|
5099
|
+
category: slide.category ? String(slide.category) : ""
|
|
5100
|
+
})),
|
|
4793
5101
|
recent_products: (anyCtx.recentProducts || []).map(normalizeProductForCandy),
|
|
4794
5102
|
collection: activeCollection,
|
|
4795
5103
|
current_category: activeCategory ? activeCollection : null,
|
|
@@ -4807,6 +5115,10 @@ function buildCandyContext(options) {
|
|
|
4807
5115
|
wishlist: pageContext.pageType === "wishlist" ? (anyCtx.items || []).map(normalizeProductForCandy) : [],
|
|
4808
5116
|
related_products: (anyCtx.relatedProducts || []).map(normalizeProductForCandy),
|
|
4809
5117
|
customer: anyCtx.customer || null,
|
|
5118
|
+
redirect_url: String(anyCtx.redirectUrl || "/account"),
|
|
5119
|
+
error: anyCtx.error ? String(anyCtx.error) : "",
|
|
5120
|
+
firebase_auth_enabled: Boolean(mergedSettings.firebaseAuthEnabled || mergedSettings.firebase?.enabled || anyCtx.bootstrap?.auth?.firebase?.enabled),
|
|
5121
|
+
google_auth_enabled: Boolean(mergedSettings.firebaseAuthEnabled || mergedSettings.firebase?.enabled || anyCtx.bootstrap?.auth?.firebase?.enabled),
|
|
4810
5122
|
order: anyCtx.order || null,
|
|
4811
5123
|
orders: anyCtx.orders || [],
|
|
4812
5124
|
blogs: anyCtx.blogs || [],
|
|
@@ -4825,6 +5137,7 @@ function buildCandyContext(options) {
|
|
|
4825
5137
|
currencyPosition
|
|
4826
5138
|
},
|
|
4827
5139
|
nonce: pageContext.nonce,
|
|
5140
|
+
hooks: renderedHooks,
|
|
4828
5141
|
is_preview: Boolean(pageContext.isPreview),
|
|
4829
5142
|
content_for_header: markSafeHtml(headerHtml),
|
|
4830
5143
|
content_for_layout: markSafeHtml(contentForLayout || ""),
|
|
@@ -5737,6 +6050,27 @@ function registerCandyTags(liquid, options = {}) {
|
|
|
5737
6050
|
}
|
|
5738
6051
|
}
|
|
5739
6052
|
liquid.registerTag("form", FormTag);
|
|
6053
|
+
|
|
6054
|
+
class HookTag extends Tag {
|
|
6055
|
+
hookName;
|
|
6056
|
+
constructor(tagToken, remainTokens, liquidInstance) {
|
|
6057
|
+
super(tagToken, remainTokens, liquidInstance);
|
|
6058
|
+
this.hookName = tagToken.args.trim().replace(/^['"]|['"]$/g, "");
|
|
6059
|
+
}
|
|
6060
|
+
*render(ctx, emitter) {
|
|
6061
|
+
if (!this.hookName)
|
|
6062
|
+
return;
|
|
6063
|
+
const all = ctx.getAll();
|
|
6064
|
+
const hooksObj = all?.hooks;
|
|
6065
|
+
if (!hooksObj)
|
|
6066
|
+
return;
|
|
6067
|
+
const val = hooksObj[this.hookName];
|
|
6068
|
+
if (val) {
|
|
6069
|
+
emitter.write(String(val));
|
|
6070
|
+
}
|
|
6071
|
+
}
|
|
6072
|
+
}
|
|
6073
|
+
liquid.registerTag("hook", HookTag);
|
|
5740
6074
|
}
|
|
5741
6075
|
|
|
5742
6076
|
// src/candy/types.ts
|
|
@@ -6203,13 +6537,45 @@ function loadCandyThemeFromSource(source, fallbackSlug = "candy-theme") {
|
|
|
6203
6537
|
}
|
|
6204
6538
|
}
|
|
6205
6539
|
}
|
|
6540
|
+
let globalSettingsSchema = rawManifestJson.globalSettingsSchema;
|
|
6541
|
+
const extractedGlobalDefaults = {};
|
|
6206
6542
|
for (const entry of source.list("schemas")) {
|
|
6207
6543
|
if (!entry.endsWith(".json"))
|
|
6208
6544
|
continue;
|
|
6209
6545
|
const path = `schemas/${entry}`;
|
|
6210
6546
|
try {
|
|
6211
6547
|
const parsed = JSON.parse(source.read(path) ?? "");
|
|
6212
|
-
if (
|
|
6548
|
+
if (entry === "settings_schema.json") {
|
|
6549
|
+
const rawCategories = Array.isArray(parsed) ? parsed : Array.isArray(parsed?.categories) ? parsed.categories : [];
|
|
6550
|
+
const normalizedCategories = rawCategories.filter((cat) => cat && typeof cat === "object" && Array.isArray(cat.settings)).map((cat, idx) => {
|
|
6551
|
+
const catName = String(cat.name || cat.label || `group-${idx + 1}`).trim();
|
|
6552
|
+
const slugName = catName.toLowerCase().replace(/[^a-z0-9]+/g, "-");
|
|
6553
|
+
const settings = cat.settings.filter((f) => f && typeof f === "object" && f.id && f.type).map((f) => {
|
|
6554
|
+
if (f.default !== undefined)
|
|
6555
|
+
extractedGlobalDefaults[String(f.id)] = f.default;
|
|
6556
|
+
return {
|
|
6557
|
+
id: String(f.id),
|
|
6558
|
+
type: f.type === "image_picker" ? "image" : f.type,
|
|
6559
|
+
label: String(f.label || f.id),
|
|
6560
|
+
...f.default !== undefined ? { default: f.default } : {},
|
|
6561
|
+
...Array.isArray(f.options) ? { options: f.options } : {},
|
|
6562
|
+
...typeof f.min === "number" ? { min: f.min } : {},
|
|
6563
|
+
...typeof f.max === "number" ? { max: f.max } : {},
|
|
6564
|
+
...typeof f.step === "number" ? { step: f.step } : {},
|
|
6565
|
+
...typeof f.placeholder === "string" ? { placeholder: f.placeholder } : {}
|
|
6566
|
+
};
|
|
6567
|
+
});
|
|
6568
|
+
return {
|
|
6569
|
+
name: slugName,
|
|
6570
|
+
label: String(cat.label || cat.name || `Settings ${idx + 1}`),
|
|
6571
|
+
...cat.description ? { description: String(cat.description) } : {},
|
|
6572
|
+
settings
|
|
6573
|
+
};
|
|
6574
|
+
});
|
|
6575
|
+
if (normalizedCategories.length > 0) {
|
|
6576
|
+
globalSettingsSchema = { categories: normalizedCategories };
|
|
6577
|
+
}
|
|
6578
|
+
} else if (parsed && typeof parsed === "object" && parsed.type && !sectionSchemas[parsed.type]) {
|
|
6213
6579
|
const check = SectionManifestSchema.safeParse(parsed);
|
|
6214
6580
|
if (check.success)
|
|
6215
6581
|
sectionSchemas[check.data.type] = check.data;
|
|
@@ -6378,9 +6744,12 @@ function loadCandyThemeFromSource(source, fallbackSlug = "candy-theme") {
|
|
|
6378
6744
|
capabilities: rawManifestJson.capabilities,
|
|
6379
6745
|
regions: ["header", "body", "footer"],
|
|
6380
6746
|
sections: compiledSections,
|
|
6747
|
+
...globalSettingsSchema ? { globalSettingsSchema } : {},
|
|
6381
6748
|
tokens,
|
|
6382
|
-
defaultGlobalSettings:
|
|
6383
|
-
storeName: name
|
|
6749
|
+
defaultGlobalSettings: {
|
|
6750
|
+
storeName: name,
|
|
6751
|
+
...extractedGlobalDefaults,
|
|
6752
|
+
...rawManifestJson.defaultGlobalSettings || {}
|
|
6384
6753
|
},
|
|
6385
6754
|
defaultLayout,
|
|
6386
6755
|
defaultPages
|
|
@@ -6485,20 +6854,31 @@ function createCandyStorefrontTheme(bundle, platform = {}) {
|
|
|
6485
6854
|
const resolvedNode = buildDefaultSectionNode(secManifest, ctx.section.id, ctx.section.settings, ctx.section.blocks);
|
|
6486
6855
|
const sectionDrop = decorateSectionNodeForCandy(resolvedNode, secManifest);
|
|
6487
6856
|
if (ctx.pageContext) {
|
|
6857
|
+
const isHeaderSec = secType === "header" || secType.startsWith("header-") || secType === "announcement-bar";
|
|
6858
|
+
const isFooterSec = secType === "footer" || secType.startsWith("footer-");
|
|
6859
|
+
const existingLayout = ctx.pageContext.layoutDocument;
|
|
6860
|
+
const layoutDocument = {
|
|
6861
|
+
regions: {
|
|
6862
|
+
header: isHeaderSec ? [resolvedNode] : existingLayout?.regions?.header || [],
|
|
6863
|
+
footer: isFooterSec ? [resolvedNode] : existingLayout?.regions?.footer || []
|
|
6864
|
+
}
|
|
6865
|
+
};
|
|
6488
6866
|
const fullScope = buildCandyContext({
|
|
6489
6867
|
pageContext: ctx.pageContext,
|
|
6490
6868
|
tokens: bundle.tokens,
|
|
6491
6869
|
defaultGlobalSettings: bundle.manifest.defaultGlobalSettings,
|
|
6492
|
-
layoutDocument
|
|
6870
|
+
layoutDocument,
|
|
6493
6871
|
sectionManifests: bundle.sectionSchemas,
|
|
6494
6872
|
extraContext: usesStorefrontShell ? { section: sectionDrop } : { ...extraScope, section: sectionDrop }
|
|
6495
6873
|
});
|
|
6496
|
-
|
|
6874
|
+
const rendered = engine.renderFileSync(`sections/${secType}.candy`, fullScope);
|
|
6875
|
+
return usesStorefrontShell ? rendered : wrapRenderedSectionHtml(resolvedNode, rendered);
|
|
6497
6876
|
}
|
|
6498
|
-
|
|
6877
|
+
const rendered = engine.renderFileSync(`sections/${secType}.candy`, {
|
|
6499
6878
|
...extraScope,
|
|
6500
6879
|
section: sectionDrop
|
|
6501
6880
|
});
|
|
6881
|
+
return usesStorefrontShell ? rendered : wrapRenderedSectionHtml(resolvedNode, rendered);
|
|
6502
6882
|
};
|
|
6503
6883
|
}
|
|
6504
6884
|
return {
|
|
@@ -6515,6 +6895,7 @@ function createCandyStorefrontTheme(bundle, platform = {}) {
|
|
|
6515
6895
|
return engine.renderPage(pageContext, {
|
|
6516
6896
|
tokens: bundle.tokens,
|
|
6517
6897
|
defaultGlobalSettings: bundle.manifest.defaultGlobalSettings,
|
|
6898
|
+
layoutDocument: pageContext.layoutDocument,
|
|
6518
6899
|
renderBodyOnly: usesStorefrontShell,
|
|
6519
6900
|
renderFallbackPage: platform.renderPage ? () => platform.renderPage?.(pageContext) ?? "" : undefined,
|
|
6520
6901
|
preferDocumentSections: usesStorefrontShell && pageContext.pageType === "custom-page",
|
|
@@ -6545,13 +6926,811 @@ function createCandyStorefrontTheme(bundle, platform = {}) {
|
|
|
6545
6926
|
};
|
|
6546
6927
|
}
|
|
6547
6928
|
|
|
6929
|
+
// src/dev-server/local-commerce-runtime.ts
|
|
6930
|
+
import { randomUUID } from "node:crypto";
|
|
6931
|
+
|
|
6932
|
+
class LocalCommerceStore {
|
|
6933
|
+
sessions = new Map;
|
|
6934
|
+
getOrCreateSession(req, res) {
|
|
6935
|
+
const cookieHeader = req.headers.cookie || "";
|
|
6936
|
+
const match = /(?:^|;\s*)cz_dev_sid=([^;]+)/.exec(cookieHeader);
|
|
6937
|
+
const existingId = match?.[1];
|
|
6938
|
+
if (existingId && this.sessions.has(existingId)) {
|
|
6939
|
+
return this.sessions.get(existingId);
|
|
6940
|
+
}
|
|
6941
|
+
const sessionId = existingId || randomUUID();
|
|
6942
|
+
const defaultCustomer = {
|
|
6943
|
+
id: "dev-cust-1",
|
|
6944
|
+
name: "Demo Shopper",
|
|
6945
|
+
firstName: "Demo",
|
|
6946
|
+
lastName: "Shopper",
|
|
6947
|
+
email: "demo@caartzee.local",
|
|
6948
|
+
addresses: [
|
|
6949
|
+
{
|
|
6950
|
+
id: "addr-1",
|
|
6951
|
+
fullName: "Demo Shopper",
|
|
6952
|
+
address1: "100 Sandbox Ave",
|
|
6953
|
+
city: "Testville",
|
|
6954
|
+
postalCode: "10001",
|
|
6955
|
+
country: "US"
|
|
6956
|
+
}
|
|
6957
|
+
]
|
|
6958
|
+
};
|
|
6959
|
+
const registeredUsers = new Map;
|
|
6960
|
+
registeredUsers.set(defaultCustomer.email, { password: "password123", customer: defaultCustomer });
|
|
6961
|
+
const session = {
|
|
6962
|
+
sessionId,
|
|
6963
|
+
cart: [],
|
|
6964
|
+
couponCode: null,
|
|
6965
|
+
shippingMethod: "standard",
|
|
6966
|
+
wishlist: [],
|
|
6967
|
+
customer: null,
|
|
6968
|
+
registeredUsers,
|
|
6969
|
+
orders: []
|
|
6970
|
+
};
|
|
6971
|
+
this.sessions.set(sessionId, session);
|
|
6972
|
+
res.setHeader("Set-Cookie", `cz_dev_sid=${sessionId}; Path=/; HttpOnly; SameSite=Lax`);
|
|
6973
|
+
return session;
|
|
6974
|
+
}
|
|
6975
|
+
computeTotals(session) {
|
|
6976
|
+
const subtotal = Number(session.cart.reduce((s, item) => s + item.price * item.quantity, 0).toFixed(2));
|
|
6977
|
+
const discount = session.couponCode === "TEST10" ? Number((subtotal * 0.1).toFixed(2)) : 0;
|
|
6978
|
+
const shipping = session.couponCode === "FREESHIP" || subtotal === 0 ? 0 : session.shippingMethod === "express" ? 15 : subtotal >= 100 ? 0 : 8;
|
|
6979
|
+
const taxable = Math.max(0, subtotal - discount);
|
|
6980
|
+
const tax = Number((taxable * 0.08).toFixed(2));
|
|
6981
|
+
const total = Number((taxable + tax + shipping).toFixed(2));
|
|
6982
|
+
const itemCount = session.cart.reduce((s, i) => s + i.quantity, 0);
|
|
6983
|
+
return { subtotal, discount, shipping, tax, total, itemCount };
|
|
6984
|
+
}
|
|
6985
|
+
applySessionToContext(session, context) {
|
|
6986
|
+
const totals = this.computeTotals(session);
|
|
6987
|
+
return {
|
|
6988
|
+
...context,
|
|
6989
|
+
cart: {
|
|
6990
|
+
items: session.cart.map((item) => ({
|
|
6991
|
+
id: item.id,
|
|
6992
|
+
productId: item.productId,
|
|
6993
|
+
variantId: item.variantId,
|
|
6994
|
+
title: item.title,
|
|
6995
|
+
name: item.title,
|
|
6996
|
+
slug: item.slug,
|
|
6997
|
+
price: item.price,
|
|
6998
|
+
quantity: item.quantity,
|
|
6999
|
+
imageUrl: item.imageUrl,
|
|
7000
|
+
lineTotal: Number((item.price * item.quantity).toFixed(2))
|
|
7001
|
+
})),
|
|
7002
|
+
itemCount: totals.itemCount,
|
|
7003
|
+
item_count: totals.itemCount,
|
|
7004
|
+
subtotal: totals.subtotal,
|
|
7005
|
+
discount: totals.discount,
|
|
7006
|
+
tax: totals.tax,
|
|
7007
|
+
shipping: totals.shipping,
|
|
7008
|
+
total: totals.total,
|
|
7009
|
+
couponCode: session.couponCode
|
|
7010
|
+
},
|
|
7011
|
+
wishlist: session.wishlist,
|
|
7012
|
+
wishlistIds: session.wishlist,
|
|
7013
|
+
customer: session.customer ? {
|
|
7014
|
+
loggedIn: true,
|
|
7015
|
+
logged_in: true,
|
|
7016
|
+
...session.customer,
|
|
7017
|
+
orders: session.orders
|
|
7018
|
+
} : { loggedIn: false, logged_in: false, orders: [] },
|
|
7019
|
+
orders: session.orders
|
|
7020
|
+
};
|
|
7021
|
+
}
|
|
7022
|
+
async handleApiRequest(req, res, pathname, searchParams, resolveCatalogProducts) {
|
|
7023
|
+
if (!pathname.startsWith("/_api/"))
|
|
7024
|
+
return false;
|
|
7025
|
+
const session = this.getOrCreateSession(req, res);
|
|
7026
|
+
const method = (req.method || "GET").toUpperCase();
|
|
7027
|
+
const json = (status, body) => {
|
|
7028
|
+
res.writeHead(status, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" });
|
|
7029
|
+
res.end(JSON.stringify(body));
|
|
7030
|
+
return true;
|
|
7031
|
+
};
|
|
7032
|
+
const readBody = async () => {
|
|
7033
|
+
const chunks = [];
|
|
7034
|
+
for await (const chunk of req)
|
|
7035
|
+
chunks.push(Buffer.from(chunk));
|
|
7036
|
+
const raw = Buffer.concat(chunks).toString("utf8").trim();
|
|
7037
|
+
if (!raw)
|
|
7038
|
+
return {};
|
|
7039
|
+
const ct = String(req.headers["content-type"] || "");
|
|
7040
|
+
if (ct.includes("application/x-www-form-urlencoded")) {
|
|
7041
|
+
return Object.fromEntries(new URLSearchParams(raw).entries());
|
|
7042
|
+
}
|
|
7043
|
+
try {
|
|
7044
|
+
return JSON.parse(raw);
|
|
7045
|
+
} catch {
|
|
7046
|
+
return {};
|
|
7047
|
+
}
|
|
7048
|
+
};
|
|
7049
|
+
if (pathname === "/_api/cart") {
|
|
7050
|
+
if (method === "GET") {
|
|
7051
|
+
return json(200, { success: true, items: session.cart, ...this.computeTotals(session), couponCode: session.couponCode });
|
|
7052
|
+
}
|
|
7053
|
+
const body = await readBody();
|
|
7054
|
+
if (method === "POST") {
|
|
7055
|
+
const productId = body.product_id ?? body.productId;
|
|
7056
|
+
const rawVariant = body.variant_id ?? body.variantId ?? null;
|
|
7057
|
+
if (!productId)
|
|
7058
|
+
return json(422, { success: false, message: "product_id is required." });
|
|
7059
|
+
if (typeof rawVariant === "string" && /-default$/i.test(rawVariant)) {
|
|
7060
|
+
return json(422, {
|
|
7061
|
+
success: false,
|
|
7062
|
+
code: "INVALID_VARIANT_ID",
|
|
7063
|
+
message: `Invalid synthetic variant_id "${rawVariant}". Guard data-variant-id with product.has_inventory_variants.`
|
|
7064
|
+
});
|
|
7065
|
+
}
|
|
7066
|
+
const qty = Math.max(1, Number(body.quantity ?? body.qty ?? 1));
|
|
7067
|
+
const products = await resolveCatalogProducts();
|
|
7068
|
+
const found = products.find((p) => String(p.id) === String(productId) || String(p.slug) === String(productId));
|
|
7069
|
+
const title = String(body.title || found?.title || found?.name || `Product #${productId}`);
|
|
7070
|
+
const price = Number(body.price ?? found?.salePrice ?? found?.price ?? 29.99);
|
|
7071
|
+
const slug = String(found?.slug || productId);
|
|
7072
|
+
const imageUrl = String(found?.imageUrl || found?.featured_image || "/assets/placeholder-product.svg");
|
|
7073
|
+
const variantId = rawVariant !== null && rawVariant !== "" ? rawVariant : null;
|
|
7074
|
+
const existing = session.cart.find((i) => String(i.productId) === String(productId) && String(i.variantId ?? "") === String(variantId ?? ""));
|
|
7075
|
+
if (existing)
|
|
7076
|
+
existing.quantity += qty;
|
|
7077
|
+
else
|
|
7078
|
+
session.cart.push({ id: `${productId}:${variantId ?? "base"}`, productId, variantId, title, slug, price, imageUrl, quantity: qty });
|
|
7079
|
+
return json(200, { success: true, items: session.cart, ...this.computeTotals(session) });
|
|
7080
|
+
}
|
|
7081
|
+
if (method === "PATCH" || method === "PUT") {
|
|
7082
|
+
const productId = body.product_id ?? body.productId;
|
|
7083
|
+
const variantId = body.variant_id ?? body.variantId ?? null;
|
|
7084
|
+
const itemId = body.item_id ?? body.itemId;
|
|
7085
|
+
const item = session.cart.find((i) => itemId && i.id === itemId || String(i.productId) === String(productId) && String(i.variantId ?? "") === String(variantId ?? ""));
|
|
7086
|
+
if (!item)
|
|
7087
|
+
return json(404, { success: false, message: "Cart item not found." });
|
|
7088
|
+
const nextQty = body.delta !== undefined ? item.quantity + Number(body.delta) : Number(body.quantity ?? item.quantity);
|
|
7089
|
+
if (nextQty <= 0)
|
|
7090
|
+
session.cart = session.cart.filter((i) => i !== item);
|
|
7091
|
+
else
|
|
7092
|
+
item.quantity = nextQty;
|
|
7093
|
+
return json(200, { success: true, items: session.cart, ...this.computeTotals(session) });
|
|
7094
|
+
}
|
|
7095
|
+
if (method === "DELETE") {
|
|
7096
|
+
const productId = body.product_id ?? body.productId;
|
|
7097
|
+
const variantId = body.variant_id ?? body.variantId ?? null;
|
|
7098
|
+
const itemId = body.item_id ?? body.itemId;
|
|
7099
|
+
if (body.clear) {
|
|
7100
|
+
session.cart = [];
|
|
7101
|
+
} else {
|
|
7102
|
+
session.cart = session.cart.filter((i) => !(itemId && i.id === itemId || String(i.productId) === String(productId) && String(i.variantId ?? "") === String(variantId ?? "")));
|
|
7103
|
+
}
|
|
7104
|
+
return json(200, { success: true, items: session.cart, ...this.computeTotals(session) });
|
|
7105
|
+
}
|
|
7106
|
+
}
|
|
7107
|
+
if (pathname === "/_api/wishlist" && method === "GET") {
|
|
7108
|
+
return json(200, { success: true, items: session.wishlist, count: session.wishlist.length });
|
|
7109
|
+
}
|
|
7110
|
+
if ((pathname === "/_api/wishlist/toggle" || pathname === "/_api/wishlist") && method === "POST") {
|
|
7111
|
+
const body = await readBody();
|
|
7112
|
+
const productId = body.product_id ?? body.productId;
|
|
7113
|
+
if (!productId)
|
|
7114
|
+
return json(422, { success: false, message: "product_id is required." });
|
|
7115
|
+
const idx = session.wishlist.findIndex((id) => String(id) === String(productId));
|
|
7116
|
+
const added = idx < 0;
|
|
7117
|
+
if (added)
|
|
7118
|
+
session.wishlist.push(productId);
|
|
7119
|
+
else
|
|
7120
|
+
session.wishlist.splice(idx, 1);
|
|
7121
|
+
return json(200, { success: true, added, items: session.wishlist, count: session.wishlist.length });
|
|
7122
|
+
}
|
|
7123
|
+
if (pathname === "/_api/auth/me" && method === "GET") {
|
|
7124
|
+
return json(200, { success: true, authenticated: Boolean(session.customer), customer: session.customer });
|
|
7125
|
+
}
|
|
7126
|
+
if (pathname === "/_api/auth/register" && method === "POST") {
|
|
7127
|
+
const body = await readBody();
|
|
7128
|
+
const email = String(body.email || "").trim().toLowerCase();
|
|
7129
|
+
const password = String(body.password || "");
|
|
7130
|
+
if (!email || !email.includes("@"))
|
|
7131
|
+
return json(422, { success: false, message: "Valid email is required." });
|
|
7132
|
+
if (password.length < 6)
|
|
7133
|
+
return json(422, { success: false, message: "Password must be at least 6 characters." });
|
|
7134
|
+
if (session.registeredUsers.has(email)) {
|
|
7135
|
+
return json(422, { success: false, message: "An account with this email already exists in this dev session." });
|
|
7136
|
+
}
|
|
7137
|
+
const firstName = String(body.firstName || body.name || "Shopper").trim();
|
|
7138
|
+
const lastName = String(body.lastName || "").trim();
|
|
7139
|
+
const customer = {
|
|
7140
|
+
id: `dev-cust-${randomUUID().slice(0, 8)}`,
|
|
7141
|
+
name: [firstName, lastName].filter(Boolean).join(" "),
|
|
7142
|
+
firstName,
|
|
7143
|
+
lastName,
|
|
7144
|
+
email,
|
|
7145
|
+
mobile: body.mobile ? String(body.mobile) : undefined,
|
|
7146
|
+
addresses: []
|
|
7147
|
+
};
|
|
7148
|
+
session.registeredUsers.set(email, { password, customer });
|
|
7149
|
+
session.customer = customer;
|
|
7150
|
+
return json(200, { success: true, authenticated: true, customer, redirect: body.redirect || "/account" });
|
|
7151
|
+
}
|
|
7152
|
+
if (pathname === "/_api/auth/login" && method === "POST") {
|
|
7153
|
+
const body = await readBody();
|
|
7154
|
+
const email = String(body.email || "").trim().toLowerCase();
|
|
7155
|
+
const password = String(body.password || "");
|
|
7156
|
+
const record = session.registeredUsers.get(email);
|
|
7157
|
+
if (!record || record.password !== password) {
|
|
7158
|
+
return json(401, { success: false, message: "Invalid email or password. (Demo account: demo@caartzee.local / password123)" });
|
|
7159
|
+
}
|
|
7160
|
+
session.customer = record.customer;
|
|
7161
|
+
return json(200, { success: true, authenticated: true, customer: record.customer, redirect: body.redirect || "/account" });
|
|
7162
|
+
}
|
|
7163
|
+
if (pathname === "/_api/auth/google" && method === "POST") {
|
|
7164
|
+
const customer = {
|
|
7165
|
+
id: "dev-google-1",
|
|
7166
|
+
name: "Google Sandbox Shopper",
|
|
7167
|
+
firstName: "Google",
|
|
7168
|
+
lastName: "Shopper",
|
|
7169
|
+
email: "google-sandbox@caartzee.local",
|
|
7170
|
+
addresses: []
|
|
7171
|
+
};
|
|
7172
|
+
session.customer = customer;
|
|
7173
|
+
return json(200, { success: true, authenticated: true, provider: "google_sandbox", customer, redirect: "/account" });
|
|
7174
|
+
}
|
|
7175
|
+
if (pathname === "/_api/auth/logout" && method === "POST") {
|
|
7176
|
+
session.customer = null;
|
|
7177
|
+
return json(200, { success: true, authenticated: false, redirect: "/" });
|
|
7178
|
+
}
|
|
7179
|
+
if (pathname === "/_api/checkout" && method === "GET") {
|
|
7180
|
+
return json(200, {
|
|
7181
|
+
success: true,
|
|
7182
|
+
sandboxOnly: true,
|
|
7183
|
+
cart: session.cart,
|
|
7184
|
+
couponCode: session.couponCode,
|
|
7185
|
+
shippingMethod: session.shippingMethod,
|
|
7186
|
+
customer: session.customer,
|
|
7187
|
+
paymentGateways: [{ id: "caartzee_test_sandbox", name: "Caartzee Test Sandbox Payment", sandbox: true }],
|
|
7188
|
+
...this.computeTotals(session)
|
|
7189
|
+
});
|
|
7190
|
+
}
|
|
7191
|
+
if (pathname === "/_api/checkout/shipping" && method === "POST") {
|
|
7192
|
+
const body = await readBody();
|
|
7193
|
+
session.shippingMethod = body.method === "express" ? "express" : "standard";
|
|
7194
|
+
return json(200, { success: true, shippingMethod: session.shippingMethod, ...this.computeTotals(session) });
|
|
7195
|
+
}
|
|
7196
|
+
if (pathname === "/_api/checkout/coupon" && method === "POST") {
|
|
7197
|
+
const body = await readBody();
|
|
7198
|
+
const code = String(body.code || "").trim().toUpperCase();
|
|
7199
|
+
if (!code) {
|
|
7200
|
+
session.couponCode = null;
|
|
7201
|
+
return json(200, { success: true, couponCode: null, ...this.computeTotals(session) });
|
|
7202
|
+
}
|
|
7203
|
+
if (!["TEST10", "FREESHIP"].includes(code)) {
|
|
7204
|
+
return json(422, { success: false, message: "Invalid coupon code. Try TEST10 (10% off) or FREESHIP." });
|
|
7205
|
+
}
|
|
7206
|
+
session.couponCode = code;
|
|
7207
|
+
return json(200, { success: true, couponCode: code, ...this.computeTotals(session) });
|
|
7208
|
+
}
|
|
7209
|
+
if (pathname === "/_api/checkout/address" && method === "POST") {
|
|
7210
|
+
const body = await readBody();
|
|
7211
|
+
const addr = {
|
|
7212
|
+
id: `addr-${randomUUID().slice(0, 6)}`,
|
|
7213
|
+
fullName: String(body.fullName || session.customer?.name || "Sandbox Shopper"),
|
|
7214
|
+
address1: String(body.address1 || "100 Sandbox Way"),
|
|
7215
|
+
city: String(body.city || "Testville"),
|
|
7216
|
+
postalCode: String(body.postalCode || "10001"),
|
|
7217
|
+
country: String(body.country || "US")
|
|
7218
|
+
};
|
|
7219
|
+
if (session.customer)
|
|
7220
|
+
session.customer.addresses.push(addr);
|
|
7221
|
+
return json(200, { success: true, address: addr });
|
|
7222
|
+
}
|
|
7223
|
+
if ((pathname === "/_api/checkout/place-order" || pathname === "/_api/orders") && method === "POST") {
|
|
7224
|
+
const body = await readBody();
|
|
7225
|
+
if (body.gateway && body.gateway !== "caartzee_test_sandbox") {
|
|
7226
|
+
return json(422, { success: false, message: 'Only sandbox payment gateway "caartzee_test_sandbox" is allowed in dev mode.' });
|
|
7227
|
+
}
|
|
7228
|
+
if (session.cart.length === 0) {
|
|
7229
|
+
return json(422, { success: false, message: "Your cart is empty." });
|
|
7230
|
+
}
|
|
7231
|
+
const totals = this.computeTotals(session);
|
|
7232
|
+
const order = {
|
|
7233
|
+
orderNumber: `CZ-DEV-${Date.now().toString().slice(-6)}`,
|
|
7234
|
+
status: "placed",
|
|
7235
|
+
paymentMode: "sandbox",
|
|
7236
|
+
paymentGateway: "caartzee_test_sandbox",
|
|
7237
|
+
customerEmail: String(body.email || session.customer?.email || "guest@caartzee.local"),
|
|
7238
|
+
shippingAddress: {
|
|
7239
|
+
fullName: String(body.fullName || session.customer?.name || "Sandbox Shopper"),
|
|
7240
|
+
address1: String(body.address1 || "100 Sandbox Way"),
|
|
7241
|
+
city: String(body.city || "Testville"),
|
|
7242
|
+
postalCode: String(body.postalCode || "10001"),
|
|
7243
|
+
country: String(body.country || "US")
|
|
7244
|
+
},
|
|
7245
|
+
shippingMethod: session.shippingMethod,
|
|
7246
|
+
subtotal: totals.subtotal,
|
|
7247
|
+
discount: totals.discount,
|
|
7248
|
+
tax: totals.tax,
|
|
7249
|
+
shipping: totals.shipping,
|
|
7250
|
+
total: totals.total,
|
|
7251
|
+
items: [...session.cart],
|
|
7252
|
+
createdAt: new Date().toISOString()
|
|
7253
|
+
};
|
|
7254
|
+
session.orders.unshift(order);
|
|
7255
|
+
session.cart = [];
|
|
7256
|
+
session.couponCode = null;
|
|
7257
|
+
return json(200, { success: true, sandboxOnly: true, order, redirect: `/order-success?order=${encodeURIComponent(order.orderNumber)}` });
|
|
7258
|
+
}
|
|
7259
|
+
if (pathname === "/_api/orders" && method === "GET") {
|
|
7260
|
+
return json(200, { success: true, orders: session.orders });
|
|
7261
|
+
}
|
|
7262
|
+
if (pathname === "/_api/orders/track" && method === "GET") {
|
|
7263
|
+
const orderNumber = searchParams.get("orderNumber") || searchParams.get("order") || "";
|
|
7264
|
+
const order = session.orders.find((o) => o.orderNumber === orderNumber) || null;
|
|
7265
|
+
if (!order)
|
|
7266
|
+
return json(404, { success: false, message: "Sandbox order not found in this dev session." });
|
|
7267
|
+
return json(200, { success: true, order });
|
|
7268
|
+
}
|
|
7269
|
+
return false;
|
|
7270
|
+
}
|
|
7271
|
+
}
|
|
7272
|
+
function buildStorefrontShellRuntimeScript(options) {
|
|
7273
|
+
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";
|
|
7274
|
+
return `<script data-caartzee-dev-shell="true">
|
|
7275
|
+
(function(){
|
|
7276
|
+
if (window.__CAARTZEE_DEV_SHELL_INIT__) return;
|
|
7277
|
+
window.__CAARTZEE_DEV_SHELL_INIT__ = true;
|
|
7278
|
+
|
|
7279
|
+
function toast(msg, isErr) {
|
|
7280
|
+
var el = document.getElementById('cz-dev-toast');
|
|
7281
|
+
if (!el) {
|
|
7282
|
+
el = document.createElement('div');
|
|
7283
|
+
el.id = 'cz-dev-toast';
|
|
7284
|
+
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;';
|
|
7285
|
+
document.body.appendChild(el);
|
|
7286
|
+
}
|
|
7287
|
+
el.style.background = isErr ? '#dc2626' : '#0f172a';
|
|
7288
|
+
el.textContent = msg;
|
|
7289
|
+
el.style.opacity = '1';
|
|
7290
|
+
clearTimeout(window.__czToastT);
|
|
7291
|
+
window.__czToastT = setTimeout(function(){ el.style.opacity = '0'; }, 2800);
|
|
7292
|
+
}
|
|
7293
|
+
|
|
7294
|
+
function updateCartBadges(count) {
|
|
7295
|
+
document.querySelectorAll('.js-cart-count, [data-cart-count]').forEach(function(el) {
|
|
7296
|
+
el.textContent = String(count);
|
|
7297
|
+
el.setAttribute('data-cart-count', String(count));
|
|
7298
|
+
});
|
|
7299
|
+
}
|
|
7300
|
+
|
|
7301
|
+
// Sync cart badge on load
|
|
7302
|
+
fetch('/_api/cart').then(function(r){ return r.json(); }).then(function(d){
|
|
7303
|
+
if (d && typeof d.itemCount === 'number') updateCartBadges(d.itemCount);
|
|
7304
|
+
}).catch(function(){});
|
|
7305
|
+
|
|
7306
|
+
// Event-delegated runtime (survives Theme Editor live section re-renders!)
|
|
7307
|
+
document.addEventListener('click', function(e) {
|
|
7308
|
+
var addBtn = e.target.closest && e.target.closest('.js-add-to-cart');
|
|
7309
|
+
if (addBtn) {
|
|
7310
|
+
e.preventDefault();
|
|
7311
|
+
var productId = addBtn.getAttribute('data-product-id');
|
|
7312
|
+
var variantId = addBtn.getAttribute('data-variant-id');
|
|
7313
|
+
var qtyInput = document.querySelector('[data-product-quantity]');
|
|
7314
|
+
var quantity = Number(addBtn.getAttribute('data-qty') || (qtyInput && qtyInput.value) || 1);
|
|
7315
|
+
var payload = { product_id: productId, quantity: quantity };
|
|
7316
|
+
if (variantId) payload.variant_id = variantId;
|
|
7317
|
+
fetch('/_api/cart', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) })
|
|
7318
|
+
.then(function(r){ return r.json().then(function(d){ return { ok: r.ok, d: d }; }); })
|
|
7319
|
+
.then(function(res){
|
|
7320
|
+
if (!res.ok) { toast(res.d.message || 'Add to cart failed', true); return; }
|
|
7321
|
+
updateCartBadges(res.d.itemCount || 0);
|
|
7322
|
+
toast('Added to sandbox cart (' + (res.d.itemCount || 0) + ' items)');
|
|
7323
|
+
});
|
|
7324
|
+
return;
|
|
7325
|
+
}
|
|
7326
|
+
|
|
7327
|
+
var wishBtn = e.target.closest && e.target.closest('.js-wishlist-toggle');
|
|
7328
|
+
if (wishBtn) {
|
|
7329
|
+
e.preventDefault();
|
|
7330
|
+
var pid = wishBtn.getAttribute('data-product-id');
|
|
7331
|
+
fetch('/_api/wishlist/toggle', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ product_id: pid }) })
|
|
7332
|
+
.then(function(r){ return r.json(); })
|
|
7333
|
+
.then(function(d){
|
|
7334
|
+
wishBtn.classList.toggle('is-active', Boolean(d.added));
|
|
7335
|
+
toast(d.added ? 'Saved to sandbox wishlist' : 'Removed from sandbox wishlist');
|
|
7336
|
+
});
|
|
7337
|
+
return;
|
|
7338
|
+
}
|
|
7339
|
+
|
|
7340
|
+
var qtyBtn = e.target.closest && e.target.closest('.js-cart-qty-btn');
|
|
7341
|
+
if (qtyBtn) {
|
|
7342
|
+
e.preventDefault();
|
|
7343
|
+
fetch('/_api/cart', {
|
|
7344
|
+
method: 'PATCH',
|
|
7345
|
+
headers: { 'Content-Type': 'application/json' },
|
|
7346
|
+
body: JSON.stringify({
|
|
7347
|
+
product_id: qtyBtn.getAttribute('data-product-id'),
|
|
7348
|
+
variant_id: qtyBtn.getAttribute('data-variant-id') || null,
|
|
7349
|
+
delta: Number(qtyBtn.getAttribute('data-delta') || 1),
|
|
7350
|
+
}),
|
|
7351
|
+
}).then(function(){ window.location.reload(); });
|
|
7352
|
+
return;
|
|
7353
|
+
}
|
|
7354
|
+
|
|
7355
|
+
var rmBtn = e.target.closest && e.target.closest('.js-remove-cart-item');
|
|
7356
|
+
if (rmBtn) {
|
|
7357
|
+
e.preventDefault();
|
|
7358
|
+
fetch('/_api/cart', {
|
|
7359
|
+
method: 'DELETE',
|
|
7360
|
+
headers: { 'Content-Type': 'application/json' },
|
|
7361
|
+
body: JSON.stringify({
|
|
7362
|
+
product_id: rmBtn.getAttribute('data-product-id'),
|
|
7363
|
+
variant_id: rmBtn.getAttribute('data-variant-id') || null,
|
|
7364
|
+
}),
|
|
7365
|
+
}).then(function(){ window.location.reload(); });
|
|
7366
|
+
return;
|
|
7367
|
+
}
|
|
7368
|
+
|
|
7369
|
+
var variantBtn = e.target.closest && e.target.closest('[data-product-variant]');
|
|
7370
|
+
if (variantBtn) {
|
|
7371
|
+
var vid = variantBtn.getAttribute('data-product-variant');
|
|
7372
|
+
var vPrice = variantBtn.getAttribute('data-variant-price');
|
|
7373
|
+
var vImg = variantBtn.getAttribute('data-variant-image');
|
|
7374
|
+
var vStock = variantBtn.getAttribute('data-variant-stock');
|
|
7375
|
+
var priceEl = document.querySelector('[data-product-price]');
|
|
7376
|
+
if (priceEl && vPrice) priceEl.textContent = vPrice;
|
|
7377
|
+
var imgEl = document.querySelector('[data-product-main-image]');
|
|
7378
|
+
if (imgEl && vImg) imgEl.setAttribute('src', vImg);
|
|
7379
|
+
var stockEl = document.querySelector('[data-product-stock]');
|
|
7380
|
+
if (stockEl && vStock !== null) stockEl.textContent = Number(vStock) > 0 ? 'In Stock' : 'Out of Stock';
|
|
7381
|
+
var pdpAdd = document.querySelector('[data-product-detail] .js-add-to-cart, .js-add-to-cart');
|
|
7382
|
+
if (pdpAdd && vid) pdpAdd.setAttribute('data-variant-id', vid);
|
|
7383
|
+
return;
|
|
7384
|
+
}
|
|
7385
|
+
|
|
7386
|
+
var googleBtn = e.target.closest && e.target.closest('.js-firebase-google-btn');
|
|
7387
|
+
if (googleBtn) {
|
|
7388
|
+
e.preventDefault();
|
|
7389
|
+
fetch('/_api/auth/google', { method: 'POST' }).then(function(r){ return r.json(); }).then(function(d){
|
|
7390
|
+
toast('Signed in with Google Sandbox');
|
|
7391
|
+
window.location.href = d.redirect || '/account';
|
|
7392
|
+
});
|
|
7393
|
+
return;
|
|
7394
|
+
}
|
|
7395
|
+
|
|
7396
|
+
var logoutBtn = e.target.closest && e.target.closest('.js-logout-btn');
|
|
7397
|
+
if (logoutBtn) {
|
|
7398
|
+
e.preventDefault();
|
|
7399
|
+
fetch('/_api/auth/logout', { method: 'POST' }).then(function(){ window.location.href = '/'; });
|
|
7400
|
+
return;
|
|
7401
|
+
}
|
|
7402
|
+
});
|
|
7403
|
+
|
|
7404
|
+
document.addEventListener('submit', function(e) {
|
|
7405
|
+
var authForm = e.target.closest && e.target.closest('form.js-auth-form');
|
|
7406
|
+
if (authForm) {
|
|
7407
|
+
e.preventDefault();
|
|
7408
|
+
var action = authForm.getAttribute('action') || '/_api/auth/login';
|
|
7409
|
+
var fd = new FormData(authForm);
|
|
7410
|
+
var body = {};
|
|
7411
|
+
fd.forEach(function(v, k){ body[k] = v; });
|
|
7412
|
+
fetch(action, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) })
|
|
7413
|
+
.then(function(r){ return r.json().then(function(d){ return { ok: r.ok, d: d }; }); })
|
|
7414
|
+
.then(function(res){
|
|
7415
|
+
if (!res.ok) { toast(res.d.message || 'Authentication failed', true); return; }
|
|
7416
|
+
toast('Signed in to sandbox session');
|
|
7417
|
+
window.location.href = res.d.redirect || authForm.getAttribute('data-redirect') || '/account';
|
|
7418
|
+
});
|
|
7419
|
+
return;
|
|
7420
|
+
}
|
|
7421
|
+
|
|
7422
|
+
var checkoutForm = e.target.closest && e.target.closest('form.js-checkout-form');
|
|
7423
|
+
if (checkoutForm) {
|
|
7424
|
+
e.preventDefault();
|
|
7425
|
+
var fd2 = new FormData(checkoutForm);
|
|
7426
|
+
var body2 = {};
|
|
7427
|
+
fd2.forEach(function(v, k){ body2[k] = v; });
|
|
7428
|
+
fetch('/_api/checkout/place-order', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body2) })
|
|
7429
|
+
.then(function(r){ return r.json().then(function(d){ return { ok: r.ok, d: d }; }); })
|
|
7430
|
+
.then(function(res){
|
|
7431
|
+
if (!res.ok) { toast(res.d.message || 'Order failed', true); return; }
|
|
7432
|
+
toast('Sandbox order placed: ' + res.d.order.orderNumber);
|
|
7433
|
+
window.location.href = res.d.redirect || '/order-success';
|
|
7434
|
+
});
|
|
7435
|
+
}
|
|
7436
|
+
});
|
|
7437
|
+
|
|
7438
|
+
// Live Theme Editor postMessage bridge (when embedded inside /_editor)
|
|
7439
|
+
window.addEventListener('message', function(event) {
|
|
7440
|
+
if (event.origin !== window.location.origin) return;
|
|
7441
|
+
var msg = event.data;
|
|
7442
|
+
if (!msg || typeof msg !== 'object') return;
|
|
7443
|
+
if (msg.type === 'CAARTZEE_EDITOR_SWAP_SECTION' && msg.sectionId && typeof msg.html === 'string') {
|
|
7444
|
+
var target = document.querySelector('[data-caartzee-section-id="' + msg.sectionId + '"], [data-section-id="' + msg.sectionId + '"]');
|
|
7445
|
+
if (target) {
|
|
7446
|
+
target.outerHTML = msg.html;
|
|
7447
|
+
document.dispatchEvent(new CustomEvent('caartzee:section:load', { detail: { sectionId: msg.sectionId } }));
|
|
7448
|
+
} else {
|
|
7449
|
+
window.location.reload();
|
|
7450
|
+
}
|
|
7451
|
+
} else if (msg.type === 'CAARTZEE_EDITOR_RELOAD') {
|
|
7452
|
+
window.location.reload();
|
|
7453
|
+
}
|
|
7454
|
+
});
|
|
7455
|
+
|
|
7456
|
+
// Visible sandbox indicator bar (hidden when inside iframe preview)
|
|
7457
|
+
if (window.self === window.top) {
|
|
7458
|
+
var bar = document.createElement('div');
|
|
7459
|
+
bar.setAttribute('data-caartzee-dev-banner', 'true');
|
|
7460
|
+
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;';
|
|
7461
|
+
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>';
|
|
7462
|
+
document.body.appendChild(bar);
|
|
7463
|
+
}
|
|
7464
|
+
})();
|
|
7465
|
+
</script>`;
|
|
7466
|
+
}
|
|
7467
|
+
|
|
7468
|
+
// src/dev-server/local-editor-server.ts
|
|
7469
|
+
class LocalThemeEditorState {
|
|
7470
|
+
state = null;
|
|
7471
|
+
ensureInitialized(theme) {
|
|
7472
|
+
if (this.state)
|
|
7473
|
+
return this.state;
|
|
7474
|
+
const defaultLayout = JSON.parse(JSON.stringify(theme.defaultTemplates?.layout || { regions: { header: [], footer: [] } }));
|
|
7475
|
+
const homePage = theme.defaultTemplates?.pages?.home || theme.defaultTemplates?.pages?.index;
|
|
7476
|
+
const defaultBody = JSON.parse(JSON.stringify(homePage?.regions?.body || []));
|
|
7477
|
+
const defaultGlobalSettings = { ...theme.manifest.defaultGlobalSettings || {} };
|
|
7478
|
+
this.state = {
|
|
7479
|
+
layout: defaultLayout,
|
|
7480
|
+
bodySections: defaultBody,
|
|
7481
|
+
globalSettings: defaultGlobalSettings,
|
|
7482
|
+
publishedLayout: null,
|
|
7483
|
+
publishedBodySections: null,
|
|
7484
|
+
publishedGlobalSettings: null,
|
|
7485
|
+
version: 1
|
|
7486
|
+
};
|
|
7487
|
+
return this.state;
|
|
7488
|
+
}
|
|
7489
|
+
getEffectiveConfig(theme, mode = "draft") {
|
|
7490
|
+
const s = this.ensureInitialized(theme);
|
|
7491
|
+
if (mode === "published" && s.publishedLayout) {
|
|
7492
|
+
return {
|
|
7493
|
+
layout: s.publishedLayout,
|
|
7494
|
+
bodySections: s.publishedBodySections || s.bodySections,
|
|
7495
|
+
globalSettings: s.publishedGlobalSettings || s.globalSettings
|
|
7496
|
+
};
|
|
7497
|
+
}
|
|
7498
|
+
return {
|
|
7499
|
+
layout: s.layout,
|
|
7500
|
+
bodySections: s.bodySections,
|
|
7501
|
+
globalSettings: s.globalSettings
|
|
7502
|
+
};
|
|
7503
|
+
}
|
|
7504
|
+
async handleRequest(req, res, pathname, theme, buildContext) {
|
|
7505
|
+
const state = this.ensureInitialized(theme);
|
|
7506
|
+
const method = (req.method || "GET").toUpperCase();
|
|
7507
|
+
const json = (status, body) => {
|
|
7508
|
+
res.writeHead(status, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" });
|
|
7509
|
+
res.end(JSON.stringify(body));
|
|
7510
|
+
return true;
|
|
7511
|
+
};
|
|
7512
|
+
const readBody = async () => {
|
|
7513
|
+
const chunks = [];
|
|
7514
|
+
for await (const chunk of req)
|
|
7515
|
+
chunks.push(Buffer.from(chunk));
|
|
7516
|
+
const raw = Buffer.concat(chunks).toString("utf8").trim();
|
|
7517
|
+
if (!raw)
|
|
7518
|
+
return {};
|
|
7519
|
+
try {
|
|
7520
|
+
return JSON.parse(raw);
|
|
7521
|
+
} catch {
|
|
7522
|
+
return {};
|
|
7523
|
+
}
|
|
7524
|
+
};
|
|
7525
|
+
if (pathname === "/_editor" && method === "GET") {
|
|
7526
|
+
res.writeHead(200, { "Content-Type": "text/html; charset=utf-8", "Cache-Control": "no-store" });
|
|
7527
|
+
res.end(renderLocalEditorHtml(theme.name, theme.slug));
|
|
7528
|
+
return true;
|
|
7529
|
+
}
|
|
7530
|
+
if (pathname === "/_api/editor/state" && method === "GET") {
|
|
7531
|
+
return json(200, {
|
|
7532
|
+
theme: {
|
|
7533
|
+
slug: theme.slug,
|
|
7534
|
+
name: theme.name,
|
|
7535
|
+
version: theme.version,
|
|
7536
|
+
sections: theme.manifest.sections,
|
|
7537
|
+
globalSettingsSchema: theme.manifest.globalSettingsSchema || null
|
|
7538
|
+
},
|
|
7539
|
+
draft: {
|
|
7540
|
+
version: state.version,
|
|
7541
|
+
layout: state.layout,
|
|
7542
|
+
bodySections: state.bodySections,
|
|
7543
|
+
globalSettings: state.globalSettings
|
|
7544
|
+
},
|
|
7545
|
+
hasPublishedPreview: Boolean(state.publishedLayout)
|
|
7546
|
+
});
|
|
7547
|
+
}
|
|
7548
|
+
if (pathname === "/_api/editor/update" && method === "POST") {
|
|
7549
|
+
const body = await readBody();
|
|
7550
|
+
if (body.layout)
|
|
7551
|
+
state.layout = body.layout;
|
|
7552
|
+
if (Array.isArray(body.bodySections))
|
|
7553
|
+
state.bodySections = body.bodySections;
|
|
7554
|
+
if (body.globalSettings && typeof body.globalSettings === "object") {
|
|
7555
|
+
state.globalSettings = { ...state.globalSettings, ...body.globalSettings };
|
|
7556
|
+
}
|
|
7557
|
+
let renderedSectionHtml = null;
|
|
7558
|
+
if (body.sectionId && body.region) {
|
|
7559
|
+
const list = body.region === "header" ? state.layout.regions.header || [] : body.region === "footer" ? state.layout.regions.footer || [] : state.bodySections;
|
|
7560
|
+
const sec = list.find((s) => s.id === body.sectionId);
|
|
7561
|
+
if (sec) {
|
|
7562
|
+
if (body.settings)
|
|
7563
|
+
sec.settings = { ...sec.settings || {}, ...body.settings };
|
|
7564
|
+
if (Array.isArray(body.blocks))
|
|
7565
|
+
sec.blocks = body.blocks;
|
|
7566
|
+
const renderer = theme.sections[sec.type];
|
|
7567
|
+
if (renderer) {
|
|
7568
|
+
const pageContext = await buildContext("home");
|
|
7569
|
+
pageContext.globalSettings = { ...pageContext.globalSettings, ...state.globalSettings };
|
|
7570
|
+
renderedSectionHtml = renderer({
|
|
7571
|
+
section: sec,
|
|
7572
|
+
themeSlug: theme.slug,
|
|
7573
|
+
globalSettings: pageContext.globalSettings,
|
|
7574
|
+
pageContext,
|
|
7575
|
+
catalog: {
|
|
7576
|
+
products: pageContext.products || pageContext.featuredProducts || [],
|
|
7577
|
+
featuredProducts: pageContext.featuredProducts || [],
|
|
7578
|
+
categories: pageContext.categories || []
|
|
7579
|
+
}
|
|
7580
|
+
});
|
|
7581
|
+
}
|
|
7582
|
+
}
|
|
7583
|
+
}
|
|
7584
|
+
state.version += 1;
|
|
7585
|
+
return json(200, {
|
|
7586
|
+
success: true,
|
|
7587
|
+
version: state.version,
|
|
7588
|
+
renderedSectionHtml,
|
|
7589
|
+
draft: {
|
|
7590
|
+
layout: state.layout,
|
|
7591
|
+
bodySections: state.bodySections,
|
|
7592
|
+
globalSettings: state.globalSettings
|
|
7593
|
+
}
|
|
7594
|
+
});
|
|
7595
|
+
}
|
|
7596
|
+
if (pathname === "/_api/editor/publish" && method === "POST") {
|
|
7597
|
+
state.publishedLayout = JSON.parse(JSON.stringify(state.layout));
|
|
7598
|
+
state.publishedBodySections = JSON.parse(JSON.stringify(state.bodySections));
|
|
7599
|
+
state.publishedGlobalSettings = JSON.parse(JSON.stringify(state.globalSettings));
|
|
7600
|
+
return json(200, { success: true, version: state.version, publishedPreviewUrl: "/?preview_mode=published" });
|
|
7601
|
+
}
|
|
7602
|
+
return false;
|
|
7603
|
+
}
|
|
7604
|
+
}
|
|
7605
|
+
function renderLocalEditorHtml(themeName, themeSlug) {
|
|
7606
|
+
return `<!doctype html>
|
|
7607
|
+
<html lang="en">
|
|
7608
|
+
<head>
|
|
7609
|
+
<meta charset="utf-8" />
|
|
7610
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
7611
|
+
<title>Caartzee Local Theme Editor — ${themeName}</title>
|
|
7612
|
+
<style>
|
|
7613
|
+
* { box-sizing: border-box; }
|
|
7614
|
+
body { margin: 0; font-family: system-ui, -apple-system, sans-serif; background: #0f172a; color: #f8fafc; height: 100vh; display: flex; flex-direction: column; }
|
|
7615
|
+
header { height: 48px; padding: 0 16px; border-bottom: 1px solid #1e293b; display: flex; align-items: center; justify-content: space-between; background: #020617; }
|
|
7616
|
+
.toolbar { display: flex; gap: 8px; align-items: center; }
|
|
7617
|
+
button { background: #1e293b; color: #f8fafc; border: 1px solid #334155; border-radius: 6px; padding: 6px 12px; font-size: 12px; cursor: pointer; }
|
|
7618
|
+
button.primary { background: #4f46e5; border-color: #6366f1; }
|
|
7619
|
+
main { flex: 1; display: grid; grid-template-columns: 340px 1fr; min-height: 0; }
|
|
7620
|
+
aside { border-right: 1px solid #1e293b; overflow-y: auto; padding: 14px; background: #0b1120; }
|
|
7621
|
+
.preview-wrap { background: #1e293b; display: flex; justify-content: center; align-items: stretch; padding: 12px; overflow: hidden; }
|
|
7622
|
+
iframe { border: 1px solid #334155; border-radius: 8px; background: #fff; width: 100%; height: 100%; transition: width .2s; }
|
|
7623
|
+
iframe.mobile { width: 390px; }
|
|
7624
|
+
.group-title { font-size: 11px; font-weight: 700; text-transform: uppercase; letter-spacing: .06em; color: #94a3b8; margin: 14px 0 6px; }
|
|
7625
|
+
.sec-card { border: 1px solid #1e293b; border-radius: 8px; padding: 10px; margin-bottom: 8px; background: #111827; }
|
|
7626
|
+
.sec-head { display: flex; justify-content: space-between; align-items: center; font-size: 13px; font-weight: 600; margin-bottom: 8px; }
|
|
7627
|
+
.field { margin-bottom: 8px; }
|
|
7628
|
+
.field label { display: block; font-size: 11px; color: #cbd5e1; margin-bottom: 3px; }
|
|
7629
|
+
.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; }
|
|
7630
|
+
</style>
|
|
7631
|
+
</head>
|
|
7632
|
+
<body>
|
|
7633
|
+
<header>
|
|
7634
|
+
<div><strong>Caartzee Dev Theme Editor</strong> <span style="color:#94a3b8;font-size:12px;">(${themeSlug})</span></div>
|
|
7635
|
+
<div class="toolbar">
|
|
7636
|
+
<button id="btn-desktop">Desktop</button>
|
|
7637
|
+
<button id="btn-mobile">Mobile</button>
|
|
7638
|
+
<button id="btn-publish" class="primary">Test Publish Preview</button>
|
|
7639
|
+
<a href="/" style="color:#38bdf8;font-size:12px;text-decoration:none;margin-left:6px;">Exit Editor</a>
|
|
7640
|
+
</div>
|
|
7641
|
+
</header>
|
|
7642
|
+
<main>
|
|
7643
|
+
<aside id="sidebar">Loading theme schemas...</aside>
|
|
7644
|
+
<div class="preview-wrap"><iframe id="preview-frame" src="/?editor_preview=1"></iframe></div>
|
|
7645
|
+
</main>
|
|
7646
|
+
<script>
|
|
7647
|
+
let editorState = null;
|
|
7648
|
+
const frame = document.getElementById('preview-frame');
|
|
7649
|
+
document.getElementById('btn-desktop').onclick = () => frame.classList.remove('mobile');
|
|
7650
|
+
document.getElementById('btn-mobile').onclick = () => frame.classList.add('mobile');
|
|
7651
|
+
document.getElementById('btn-publish').onclick = async () => {
|
|
7652
|
+
const res = await fetch('/_api/editor/publish', { method: 'POST' }).then(r => r.json());
|
|
7653
|
+
if (res.success) alert('Published to isolated local preview: ' + res.publishedPreviewUrl);
|
|
7654
|
+
};
|
|
7655
|
+
|
|
7656
|
+
async function load() {
|
|
7657
|
+
editorState = await fetch('/_api/editor/state').then(r => r.json());
|
|
7658
|
+
renderSidebar();
|
|
7659
|
+
}
|
|
7660
|
+
|
|
7661
|
+
async function patchSection(region, sectionId, patch) {
|
|
7662
|
+
const res = await fetch('/_api/editor/update', {
|
|
7663
|
+
method: 'POST',
|
|
7664
|
+
headers: { 'Content-Type': 'application/json' },
|
|
7665
|
+
body: JSON.stringify({ region, sectionId, settings: patch }),
|
|
7666
|
+
}).then(r => r.json());
|
|
7667
|
+
if (res.renderedSectionHtml) {
|
|
7668
|
+
frame.contentWindow.postMessage({ type: 'CAARTZEE_EDITOR_SWAP_SECTION', sectionId, html: res.renderedSectionHtml }, window.location.origin);
|
|
7669
|
+
} else {
|
|
7670
|
+
frame.contentWindow.postMessage({ type: 'CAARTZEE_EDITOR_RELOAD' }, window.location.origin);
|
|
7671
|
+
}
|
|
7672
|
+
}
|
|
7673
|
+
|
|
7674
|
+
function renderRegion(title, region, list) {
|
|
7675
|
+
const schemas = Object.fromEntries((editorState.theme.sections || []).map(s => [s.type, s]));
|
|
7676
|
+
let html = '<div class="group-title">' + title + '</div>';
|
|
7677
|
+
for (const sec of list || []) {
|
|
7678
|
+
const schema = schemas[sec.type];
|
|
7679
|
+
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>';
|
|
7680
|
+
for (const f of (schema?.settings || []).slice(0, 12)) {
|
|
7681
|
+
if (f.type === 'header' || f.type === 'paragraph') continue;
|
|
7682
|
+
const val = (sec.settings && sec.settings[f.id] !== undefined) ? sec.settings[f.id] : (f.default ?? '');
|
|
7683
|
+
const type = f.type === 'color' ? 'color' : f.type === 'checkbox' || f.type === 'boolean' ? 'checkbox' : 'text';
|
|
7684
|
+
html += '<div class="field"><label>' + f.label + '</label>';
|
|
7685
|
+
if (type === 'checkbox') {
|
|
7686
|
+
html += '<input type="checkbox" ' + (val ? 'checked' : '') + ' data-region="' + region + '" data-sec="' + sec.id + '" data-key="' + f.id + '" />';
|
|
7687
|
+
} else {
|
|
7688
|
+
html += '<input type="' + type + '" value="' + String(val).replace(/"/g, '"') + '" data-region="' + region + '" data-sec="' + sec.id + '" data-key="' + f.id + '" />';
|
|
7689
|
+
}
|
|
7690
|
+
html += '</div>';
|
|
7691
|
+
}
|
|
7692
|
+
html += '</div>';
|
|
7693
|
+
}
|
|
7694
|
+
return html;
|
|
7695
|
+
}
|
|
7696
|
+
|
|
7697
|
+
function renderSidebar() {
|
|
7698
|
+
const sidebar = document.getElementById('sidebar');
|
|
7699
|
+
sidebar.innerHTML =
|
|
7700
|
+
renderRegion('Header Region', 'header', editorState.draft.layout.regions.header) +
|
|
7701
|
+
renderRegion('Body Sections', 'body', editorState.draft.bodySections) +
|
|
7702
|
+
renderRegion('Footer Region', 'footer', editorState.draft.layout.regions.footer);
|
|
7703
|
+
|
|
7704
|
+
sidebar.querySelectorAll('input[data-sec]').forEach(input => {
|
|
7705
|
+
input.addEventListener('change', () => {
|
|
7706
|
+
const val = input.type === 'checkbox' ? input.checked : input.value;
|
|
7707
|
+
patchSection(input.dataset.region, input.dataset.sec, { [input.dataset.key]: val });
|
|
7708
|
+
});
|
|
7709
|
+
});
|
|
7710
|
+
}
|
|
7711
|
+
|
|
7712
|
+
load();
|
|
7713
|
+
</script>
|
|
7714
|
+
</body>
|
|
7715
|
+
</html>`;
|
|
7716
|
+
}
|
|
7717
|
+
|
|
6548
7718
|
// src/dev-server/dev-server.ts
|
|
7719
|
+
function injectRuntimeScript(html, script) {
|
|
7720
|
+
if (/<\/body>/i.test(html)) {
|
|
7721
|
+
return html.replace(/<\/body>/i, `${script}</body>`);
|
|
7722
|
+
}
|
|
7723
|
+
return `${html}
|
|
7724
|
+
${script}`;
|
|
7725
|
+
}
|
|
6549
7726
|
function createThemeDevServer(options = {}) {
|
|
6550
7727
|
const port = options.port ?? 3333;
|
|
6551
7728
|
const host = options.host ?? "127.0.0.1";
|
|
6552
7729
|
const themeDir = options.themeDir ?? process.cwd();
|
|
6553
7730
|
if (options.loadCatalog && host !== "127.0.0.1")
|
|
6554
7731
|
throw new Error("Store catalog previews must bind to 127.0.0.1.");
|
|
7732
|
+
const commerceStore = new LocalCommerceStore;
|
|
7733
|
+
const editorState = new LocalThemeEditorState;
|
|
6555
7734
|
let manifest = null;
|
|
6556
7735
|
const manifestPath = join7(themeDir, "manifest.json");
|
|
6557
7736
|
if (existsSync7(manifestPath)) {
|
|
@@ -6563,9 +7742,10 @@ function createThemeDevServer(options = {}) {
|
|
|
6563
7742
|
try {
|
|
6564
7743
|
const parsedUrl = new URL(req.url ?? "/", `http://${host}:${port}`);
|
|
6565
7744
|
const pathname = parsedUrl.pathname;
|
|
7745
|
+
const isEditorPreview = parsedUrl.searchParams.get("editor_preview") === "1" || pathname === "/_editor";
|
|
6566
7746
|
if (options.loadCatalog) {
|
|
6567
7747
|
res.setHeader("Cache-Control", "no-store");
|
|
6568
|
-
res.setHeader("Content-Security-Policy", "frame-ancestors 'none'");
|
|
7748
|
+
res.setHeader("Content-Security-Policy", isEditorPreview ? "frame-ancestors 'self'" : "frame-ancestors 'none'");
|
|
6569
7749
|
res.setHeader("Cross-Origin-Resource-Policy", "same-origin");
|
|
6570
7750
|
if (req.headers.host !== host + ":" + port) {
|
|
6571
7751
|
res.writeHead(403);
|
|
@@ -6576,28 +7756,66 @@ function createThemeDevServer(options = {}) {
|
|
|
6576
7756
|
if (pathname.startsWith("/assets/")) {
|
|
6577
7757
|
const root = resolve5(themeDir, "assets");
|
|
6578
7758
|
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())) {
|
|
7759
|
+
if (!file.startsWith(root + sep) || !existsSync7(file) || ![".css", ".js", ".svg", ".png", ".jpg", ".jpeg", ".webp", ".gif", ".woff2"].includes(extname(file).toLowerCase())) {
|
|
6580
7760
|
res.writeHead(404);
|
|
6581
7761
|
res.end("Asset not found");
|
|
6582
7762
|
return;
|
|
6583
7763
|
}
|
|
6584
|
-
const mime = {
|
|
7764
|
+
const mime = {
|
|
7765
|
+
".css": "text/css",
|
|
7766
|
+
".js": "application/javascript; charset=utf-8",
|
|
7767
|
+
".svg": "image/svg+xml",
|
|
7768
|
+
".png": "image/png",
|
|
7769
|
+
".jpg": "image/jpeg",
|
|
7770
|
+
".jpeg": "image/jpeg",
|
|
7771
|
+
".webp": "image/webp",
|
|
7772
|
+
".gif": "image/gif",
|
|
7773
|
+
".woff2": "font/woff2"
|
|
7774
|
+
};
|
|
6585
7775
|
res.writeHead(200, { "Content-Type": mime[extname(file).toLowerCase()], "Cache-Control": "no-store" });
|
|
6586
7776
|
res.end(readFileSync7(file));
|
|
6587
7777
|
return;
|
|
6588
7778
|
}
|
|
6589
7779
|
if (pathname === "/_api/status") {
|
|
6590
7780
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
6591
|
-
res.end(JSON.stringify({
|
|
7781
|
+
res.end(JSON.stringify({
|
|
7782
|
+
status: "ok",
|
|
7783
|
+
mode: options.loadCatalog ? "merchant-sandbox" : "demo",
|
|
7784
|
+
theme: manifest?.name ?? "Unknown Theme",
|
|
7785
|
+
version: manifest?.version ?? "1.0.0",
|
|
7786
|
+
editorUrl: `http://${host}:${port}/_editor`
|
|
7787
|
+
}));
|
|
6592
7788
|
return;
|
|
6593
7789
|
}
|
|
6594
7790
|
if (pathname === "/_api/context") {
|
|
6595
7791
|
const page = parsedUrl.searchParams.get("page") || "home";
|
|
6596
|
-
const
|
|
7792
|
+
const session = commerceStore.getOrCreateSession(req, res);
|
|
7793
|
+
const baseContext = options.loadCatalog ? await createCatalogDevContext(options.loadCatalog, page, "/", parsedUrl.searchParams) : createMockPageContext(page);
|
|
7794
|
+
const context = commerceStore.applySessionToContext(session, baseContext);
|
|
6597
7795
|
res.writeHead(200, { "Content-Type": "application/json" });
|
|
6598
7796
|
res.end(JSON.stringify(context, null, 2));
|
|
6599
7797
|
return;
|
|
6600
7798
|
}
|
|
7799
|
+
if (pathname === "/_editor" || pathname.startsWith("/_api/editor/")) {
|
|
7800
|
+
const theme = options.loadTheme ? await options.loadTheme() : await loadLocalTheme(themeDir);
|
|
7801
|
+
const session = commerceStore.getOrCreateSession(req, res);
|
|
7802
|
+
const handled = await editorState.handleRequest(req, res, pathname, theme, async (pt) => {
|
|
7803
|
+
const base = options.loadCatalog ? await createCatalogDevContext(options.loadCatalog, pt, "/", parsedUrl.searchParams) : createMockPageContext(pt);
|
|
7804
|
+
return commerceStore.applySessionToContext(session, base);
|
|
7805
|
+
});
|
|
7806
|
+
if (handled)
|
|
7807
|
+
return;
|
|
7808
|
+
}
|
|
7809
|
+
const handledCommerce = await commerceStore.handleApiRequest(req, res, pathname, parsedUrl.searchParams, async () => {
|
|
7810
|
+
if (options.loadCatalog) {
|
|
7811
|
+
const cat = await options.loadCatalog({});
|
|
7812
|
+
return cat.products || [];
|
|
7813
|
+
}
|
|
7814
|
+
const mock = createMockPageContext("product-list");
|
|
7815
|
+
return mock.products || mock.featuredProducts || [];
|
|
7816
|
+
});
|
|
7817
|
+
if (handledCommerce)
|
|
7818
|
+
return;
|
|
6601
7819
|
if (pathname.startsWith("/_assets/")) {
|
|
6602
7820
|
const parts = pathname.replace(/^\/_assets\/[^/]+\//, "");
|
|
6603
7821
|
const safeAsset = parts.split("/").filter((s) => s && s !== "." && s !== "..").join("/");
|
|
@@ -6625,7 +7843,7 @@ function createThemeDevServer(options = {}) {
|
|
|
6625
7843
|
pageType = "checkout";
|
|
6626
7844
|
} else if (pathname === "/login") {
|
|
6627
7845
|
pageType = "login";
|
|
6628
|
-
} else if (pathname === "/signup") {
|
|
7846
|
+
} else if (pathname === "/signup" || pathname === "/register") {
|
|
6629
7847
|
pageType = "signup";
|
|
6630
7848
|
} else if (pathname === "/account") {
|
|
6631
7849
|
pageType = "account";
|
|
@@ -6662,10 +7880,28 @@ function createThemeDevServer(options = {}) {
|
|
|
6662
7880
|
pageType = "order-detail";
|
|
6663
7881
|
else if (pathname.startsWith("/account/"))
|
|
6664
7882
|
pageType = "account";
|
|
6665
|
-
const
|
|
7883
|
+
const session = commerceStore.getOrCreateSession(req, res);
|
|
7884
|
+
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
7885
|
const theme = options.loadTheme ? await options.loadTheme() : await loadLocalTheme(themeDir);
|
|
6667
|
-
const
|
|
6668
|
-
|
|
7886
|
+
const previewMode = parsedUrl.searchParams.get("preview_mode") === "published" ? "published" : "draft";
|
|
7887
|
+
const editorConfig = editorState.getEffectiveConfig(theme, previewMode);
|
|
7888
|
+
const enrichedContext = commerceStore.applySessionToContext(session, {
|
|
7889
|
+
...baseContext,
|
|
7890
|
+
isPreview: true,
|
|
7891
|
+
globalSettings: { ...baseContext.globalSettings, ...editorConfig.globalSettings },
|
|
7892
|
+
layoutDocument: editorConfig.layout,
|
|
7893
|
+
...pageType === "home" ? { sections: editorConfig.bodySections } : {}
|
|
7894
|
+
});
|
|
7895
|
+
const rawHtml = renderThemePreview(theme, enrichedContext, Boolean(options.loadCatalog), editorConfig);
|
|
7896
|
+
const runtimeScript = buildStorefrontShellRuntimeScript({
|
|
7897
|
+
mode: options.loadCatalog ? "merchant-sandbox" : "demo",
|
|
7898
|
+
storeLabel: options.storeLabel,
|
|
7899
|
+
editorEnabled: Boolean(options.editor)
|
|
7900
|
+
});
|
|
7901
|
+
const html = injectRuntimeScript(rawHtml, runtimeScript);
|
|
7902
|
+
res.writeHead(enrichedContext.pageType === "not-found" && pageType !== "not-found" ? 404 : 200, {
|
|
7903
|
+
"Content-Type": "text/html; charset=utf-8"
|
|
7904
|
+
});
|
|
6669
7905
|
res.end(html);
|
|
6670
7906
|
} catch (error) {
|
|
6671
7907
|
res.writeHead(500, { "Content-Type": "text/plain; charset=utf-8" });
|
|
@@ -6676,6 +7912,7 @@ function createThemeDevServer(options = {}) {
|
|
|
6676
7912
|
server,
|
|
6677
7913
|
port,
|
|
6678
7914
|
url: `http://${host}:${port}`,
|
|
7915
|
+
editorUrl: `http://${host}:${port}/_editor`,
|
|
6679
7916
|
stop: () => new Promise((resolve) => {
|
|
6680
7917
|
server.close(() => resolve());
|
|
6681
7918
|
})
|
|
@@ -6708,8 +7945,9 @@ async function loadLocalTheme(themeDir) {
|
|
|
6708
7945
|
const source = await build.outputs[0].text();
|
|
6709
7946
|
const module = await import("data:text/javascript;base64," + Buffer.from(source).toString("base64"));
|
|
6710
7947
|
const theme = module.default || module.theme;
|
|
6711
|
-
if (!theme?.sections || !theme?.defaultTemplates || !theme?.manifest)
|
|
7948
|
+
if (!theme?.sections || !theme?.defaultTemplates || !theme?.manifest) {
|
|
6712
7949
|
throw new Error("src/index.ts must export a StorefrontThemeDefinition as default or theme.");
|
|
7950
|
+
}
|
|
6713
7951
|
return theme;
|
|
6714
7952
|
}
|
|
6715
7953
|
// src/validation/package-validator.ts
|
|
@@ -6958,6 +8196,257 @@ class PackageValidator {
|
|
|
6958
8196
|
}
|
|
6959
8197
|
var ThemePackageValidator = PackageValidator;
|
|
6960
8198
|
|
|
8199
|
+
// src/cli/mcp/editor-tools.ts
|
|
8200
|
+
import { existsSync as existsSync9, readFileSync as readFileSync9 } from "node:fs";
|
|
8201
|
+
import { join as join9, resolve as resolve7 } from "node:path";
|
|
8202
|
+
import { z as z4 } from "zod";
|
|
8203
|
+
function validateThemeEditorDirectory(themeDir) {
|
|
8204
|
+
const dir = resolve7(themeDir);
|
|
8205
|
+
const checks = [];
|
|
8206
|
+
if (!existsSync9(dir)) {
|
|
8207
|
+
return {
|
|
8208
|
+
valid: false,
|
|
8209
|
+
themeDir: dir,
|
|
8210
|
+
checks: [{ name: "directory_exists", status: "failed", message: `Theme directory not found: ${dir}` }],
|
|
8211
|
+
summary: { passed: 0, failed: 1, warnings: 0 }
|
|
8212
|
+
};
|
|
8213
|
+
}
|
|
8214
|
+
const { bundle, diagnostics } = loadCandyThemeFromDirectory(dir);
|
|
8215
|
+
const schemaErrors = diagnostics.filter((d) => d.severity === "error");
|
|
8216
|
+
const schemaWarnings = diagnostics.filter((d) => d.severity === "warning");
|
|
8217
|
+
if (schemaErrors.length === 0) {
|
|
8218
|
+
checks.push({
|
|
8219
|
+
name: "section_schemas_compile",
|
|
8220
|
+
status: "passed",
|
|
8221
|
+
message: `All ${Object.keys(bundle.sectionSchemas).length} section schema(s) compiled cleanly.`
|
|
8222
|
+
});
|
|
8223
|
+
} else {
|
|
8224
|
+
for (const err of schemaErrors) {
|
|
8225
|
+
checks.push({
|
|
8226
|
+
name: "section_schema_error",
|
|
8227
|
+
status: "failed",
|
|
8228
|
+
message: `${err.code}: ${err.message}`,
|
|
8229
|
+
file: err.file
|
|
8230
|
+
});
|
|
8231
|
+
}
|
|
8232
|
+
}
|
|
8233
|
+
for (const warn of schemaWarnings) {
|
|
8234
|
+
checks.push({
|
|
8235
|
+
name: "section_schema_warning",
|
|
8236
|
+
status: "warning",
|
|
8237
|
+
message: `${warn.code}: ${warn.message}`,
|
|
8238
|
+
file: warn.file
|
|
8239
|
+
});
|
|
8240
|
+
}
|
|
8241
|
+
for (const [sectionType, schema] of Object.entries(bundle.sectionSchemas)) {
|
|
8242
|
+
const relPath = `sections/${sectionType}.candy`;
|
|
8243
|
+
const source = bundle.files[relPath] || "";
|
|
8244
|
+
if (schema.blocks && schema.blocks.length > 0) {
|
|
8245
|
+
if (source.includes("block.candy_attributes")) {
|
|
8246
|
+
checks.push({
|
|
8247
|
+
name: `block_attributes:${sectionType}`,
|
|
8248
|
+
status: "passed",
|
|
8249
|
+
message: `Section "${sectionType}" outputs {{ block.candy_attributes }} for Theme Editor block selection.`,
|
|
8250
|
+
file: relPath
|
|
8251
|
+
});
|
|
8252
|
+
} else {
|
|
8253
|
+
checks.push({
|
|
8254
|
+
name: `block_attributes:${sectionType}`,
|
|
8255
|
+
status: "failed",
|
|
8256
|
+
message: `Section "${sectionType}" defines ${schema.blocks.length} block type(s) but is missing {{ block.candy_attributes }}.`,
|
|
8257
|
+
file: relPath
|
|
8258
|
+
});
|
|
8259
|
+
}
|
|
8260
|
+
}
|
|
8261
|
+
}
|
|
8262
|
+
const settingsSchemaPath = join9(dir, "schemas", "settings_schema.json");
|
|
8263
|
+
if (existsSync9(settingsSchemaPath)) {
|
|
8264
|
+
try {
|
|
8265
|
+
const parsed = JSON.parse(readFileSync9(settingsSchemaPath, "utf8"));
|
|
8266
|
+
if (Array.isArray(parsed) || parsed && typeof parsed === "object") {
|
|
8267
|
+
checks.push({ name: "global_settings_schema", status: "passed", message: "schemas/settings_schema.json is valid JSON.", file: "schemas/settings_schema.json" });
|
|
8268
|
+
} else {
|
|
8269
|
+
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" });
|
|
8270
|
+
}
|
|
8271
|
+
} catch (e) {
|
|
8272
|
+
checks.push({ name: "global_settings_schema", status: "failed", message: `Invalid JSON in schemas/settings_schema.json: ${e.message}`, file: "schemas/settings_schema.json" });
|
|
8273
|
+
}
|
|
8274
|
+
} else {
|
|
8275
|
+
checks.push({ name: "global_settings_schema", status: "warning", message: "schemas/settings_schema.json not found; global theme settings will be empty." });
|
|
8276
|
+
}
|
|
8277
|
+
const themeJs = bundle.assets["assets/theme.js"] || (existsSync9(join9(dir, "assets", "theme.js")) ? readFileSync9(join9(dir, "assets", "theme.js"), "utf8") : "");
|
|
8278
|
+
if (themeJs) {
|
|
8279
|
+
if (themeJs.includes("document.addEventListener") || themeJs.includes("caartzee:section:")) {
|
|
8280
|
+
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" });
|
|
8281
|
+
} else {
|
|
8282
|
+
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" });
|
|
8283
|
+
}
|
|
8284
|
+
}
|
|
8285
|
+
const passed = checks.filter((c) => c.status === "passed").length;
|
|
8286
|
+
const failed = checks.filter((c) => c.status === "failed").length;
|
|
8287
|
+
const warnings = checks.filter((c) => c.status === "warning").length;
|
|
8288
|
+
return {
|
|
8289
|
+
valid: failed === 0,
|
|
8290
|
+
themeDir: dir,
|
|
8291
|
+
slug: bundle.slug,
|
|
8292
|
+
version: bundle.version,
|
|
8293
|
+
sectionCount: Object.keys(bundle.sectionSchemas).length,
|
|
8294
|
+
sections: Object.keys(bundle.sectionSchemas),
|
|
8295
|
+
checks,
|
|
8296
|
+
summary: { passed, failed, warnings }
|
|
8297
|
+
};
|
|
8298
|
+
}
|
|
8299
|
+
|
|
8300
|
+
// src/cli/mcp/testing-tools.ts
|
|
8301
|
+
import { createHash as createHash2 } from "node:crypto";
|
|
8302
|
+
import { existsSync as existsSync10, readFileSync as readFileSync10 } from "node:fs";
|
|
8303
|
+
import { join as join10, resolve as resolve8 } from "node:path";
|
|
8304
|
+
import { z as z5 } from "zod";
|
|
8305
|
+
async function runThemeReadinessAudit(themeDir) {
|
|
8306
|
+
const dir = resolve8(themeDir);
|
|
8307
|
+
const checks = [];
|
|
8308
|
+
const readRel = (rel) => {
|
|
8309
|
+
const full = join10(dir, rel);
|
|
8310
|
+
return existsSync10(full) ? readFileSync10(full, "utf8") : null;
|
|
8311
|
+
};
|
|
8312
|
+
let slug = "unknown";
|
|
8313
|
+
let version = "0.0.0";
|
|
8314
|
+
let packageHash = createHash2("sha256").update(dir).digest("hex");
|
|
8315
|
+
try {
|
|
8316
|
+
const files = collectThemeSources(dir);
|
|
8317
|
+
const canonical = [...files].sort((a, b) => a.path < b.path ? -1 : a.path > b.path ? 1 : 0);
|
|
8318
|
+
packageHash = createHash2("sha256").update(JSON.stringify(canonical)).digest("hex");
|
|
8319
|
+
} catch {}
|
|
8320
|
+
const pkg = await ThemePackageValidator.validatePackage(dir);
|
|
8321
|
+
if (pkg.manifest) {
|
|
8322
|
+
slug = pkg.manifest.slug;
|
|
8323
|
+
version = pkg.manifest.version;
|
|
8324
|
+
}
|
|
8325
|
+
if (pkg.valid) {
|
|
8326
|
+
checks.push({ id: "security.package_validation", category: "security", status: "passed", message: "Manifest and security source-pattern audit passed." });
|
|
8327
|
+
} else {
|
|
8328
|
+
for (const err of pkg.errors) {
|
|
8329
|
+
checks.push({ id: "security.package_validation", category: "security", status: "failed", message: err });
|
|
8330
|
+
}
|
|
8331
|
+
}
|
|
8332
|
+
const editor = validateThemeEditorDirectory(dir);
|
|
8333
|
+
for (const c of editor.checks) {
|
|
8334
|
+
checks.push({
|
|
8335
|
+
id: `editor.${c.name}`,
|
|
8336
|
+
category: "editor",
|
|
8337
|
+
status: c.status,
|
|
8338
|
+
message: c.message,
|
|
8339
|
+
file: c.file
|
|
8340
|
+
});
|
|
8341
|
+
}
|
|
8342
|
+
const header = readRel("sections/header.candy") || "";
|
|
8343
|
+
const productTpl = readRel("templates/product.candy") || "";
|
|
8344
|
+
const collectionTpl = readRel("templates/collection.candy") || "";
|
|
8345
|
+
const cartTpl = readRel("templates/cart.candy") || "";
|
|
8346
|
+
const searchTpl = readRel("templates/search.candy") || "";
|
|
8347
|
+
const productCard = readRel("snippets/product-card.candy") || "";
|
|
8348
|
+
const themeCss = readRel("assets/theme.css") || "";
|
|
8349
|
+
checks.push({
|
|
8350
|
+
id: "commerce.navigation_header",
|
|
8351
|
+
category: "commerce",
|
|
8352
|
+
status: header.includes("linklists") || header.includes("<nav") ? "passed" : "warning",
|
|
8353
|
+
message: header.includes("linklists") ? "Header wires merchant navigation via linklists." : 'Header should render merchant linklists["main-menu"].links.',
|
|
8354
|
+
file: "sections/header.candy"
|
|
8355
|
+
});
|
|
8356
|
+
checks.push({
|
|
8357
|
+
id: "commerce.cart_count_badge",
|
|
8358
|
+
category: "commerce",
|
|
8359
|
+
status: header.includes("js-cart-count") ? "passed" : "warning",
|
|
8360
|
+
message: header.includes("js-cart-count") ? "Header includes .js-cart-count live cart counter." : "Header is missing .js-cart-count live cart badge.",
|
|
8361
|
+
file: "sections/header.candy"
|
|
8362
|
+
});
|
|
8363
|
+
const combinedProduct = `${productTpl}
|
|
8364
|
+
${productCard}`;
|
|
8365
|
+
const hasSyntheticVariant = /data-variant-id\s*=\s*["'][^"']*-default["']/i.test(combinedProduct);
|
|
8366
|
+
checks.push({
|
|
8367
|
+
id: "commerce.variant_id_contract",
|
|
8368
|
+
category: "commerce",
|
|
8369
|
+
status: hasSyntheticVariant ? "failed" : "passed",
|
|
8370
|
+
message: hasSyntheticVariant ? 'Synthetic "-default" variant ID detected; guard data-variant-id with product.has_inventory_variants.' : 'No synthetic "-default" variant IDs detected.'
|
|
8371
|
+
});
|
|
8372
|
+
checks.push({
|
|
8373
|
+
id: "commerce.product_template",
|
|
8374
|
+
category: "commerce",
|
|
8375
|
+
status: productTpl.trim().length > 0 ? "passed" : "failed",
|
|
8376
|
+
message: productTpl.trim().length > 0 ? "templates/product.candy exists." : "Missing templates/product.candy.",
|
|
8377
|
+
file: "templates/product.candy"
|
|
8378
|
+
});
|
|
8379
|
+
checks.push({
|
|
8380
|
+
id: "commerce.collection_template",
|
|
8381
|
+
category: "commerce",
|
|
8382
|
+
status: collectionTpl.trim().length > 0 ? "passed" : "failed",
|
|
8383
|
+
message: collectionTpl.trim().length > 0 ? "templates/collection.candy exists." : "Missing templates/collection.candy.",
|
|
8384
|
+
file: "templates/collection.candy"
|
|
8385
|
+
});
|
|
8386
|
+
checks.push({
|
|
8387
|
+
id: "commerce.cart_template",
|
|
8388
|
+
category: "commerce",
|
|
8389
|
+
status: cartTpl.trim().length > 0 ? "passed" : "failed",
|
|
8390
|
+
message: cartTpl.trim().length > 0 ? "templates/cart.candy exists." : "Missing templates/cart.candy.",
|
|
8391
|
+
file: "templates/cart.candy"
|
|
8392
|
+
});
|
|
8393
|
+
checks.push({
|
|
8394
|
+
id: "commerce.search_template",
|
|
8395
|
+
category: "commerce",
|
|
8396
|
+
status: searchTpl.trim().length > 0 ? "passed" : "warning",
|
|
8397
|
+
message: searchTpl.trim().length > 0 ? "templates/search.candy exists." : "Missing templates/search.candy.",
|
|
8398
|
+
file: "templates/search.candy"
|
|
8399
|
+
});
|
|
8400
|
+
let hasAnyPluginHook = false;
|
|
8401
|
+
try {
|
|
8402
|
+
const { bundle } = loadCandyThemeFromDirectory(dir);
|
|
8403
|
+
hasAnyPluginHook = Object.values(bundle.files).some((src) => /\{%-?\s*hook\s+['"]/.test(src));
|
|
8404
|
+
} catch {}
|
|
8405
|
+
checks.push({
|
|
8406
|
+
id: "plugins.extension_hooks",
|
|
8407
|
+
category: "plugins",
|
|
8408
|
+
status: hasAnyPluginHook ? "passed" : "warning",
|
|
8409
|
+
message: hasAnyPluginHook ? 'Theme includes {% hook "..." %} plugin extension slots.' : 'No {% hook "..." %} plugin extension slots detected. Add product/cart/header/footer hooks for plugin compatibility.'
|
|
8410
|
+
});
|
|
8411
|
+
const hasResponsiveMedia = /@media\s*\(/.test(themeCss) || themeCss.includes("clamp(") || themeCss.includes("grid-template-columns");
|
|
8412
|
+
checks.push({
|
|
8413
|
+
id: "responsive.css_layout",
|
|
8414
|
+
category: "responsive",
|
|
8415
|
+
status: hasResponsiveMedia ? "passed" : "warning",
|
|
8416
|
+
message: hasResponsiveMedia ? "assets/theme.css includes responsive layout rules." : "assets/theme.css lacks responsive @media or fluid grid rules.",
|
|
8417
|
+
file: "assets/theme.css"
|
|
8418
|
+
});
|
|
8419
|
+
const layout = readRel("layout/theme.candy") || "";
|
|
8420
|
+
const hasViewport = layout.includes("viewport") || !layout;
|
|
8421
|
+
const hasSkipOrAria = layout.includes("aria-") || header.includes("aria-label");
|
|
8422
|
+
checks.push({
|
|
8423
|
+
id: "accessibility.viewport_and_aria",
|
|
8424
|
+
category: "accessibility",
|
|
8425
|
+
status: hasViewport && hasSkipOrAria ? "passed" : "warning",
|
|
8426
|
+
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.',
|
|
8427
|
+
file: "layout/theme.candy"
|
|
8428
|
+
});
|
|
8429
|
+
const summary = {
|
|
8430
|
+
passed: checks.filter((c) => c.status === "passed").length,
|
|
8431
|
+
failed: checks.filter((c) => c.status === "failed").length,
|
|
8432
|
+
warnings: checks.filter((c) => c.status === "warning").length,
|
|
8433
|
+
skipped: checks.filter((c) => c.status === "skipped").length,
|
|
8434
|
+
blocked: checks.filter((c) => c.status === "blocked").length
|
|
8435
|
+
};
|
|
8436
|
+
return {
|
|
8437
|
+
generatedAt: new Date().toISOString(),
|
|
8438
|
+
themeDir: dir,
|
|
8439
|
+
slug,
|
|
8440
|
+
version,
|
|
8441
|
+
packageHash,
|
|
8442
|
+
sdkVersion: "1.2.0",
|
|
8443
|
+
runtimeVersion: "candy-1.0",
|
|
8444
|
+
status: summary.failed > 0 ? "failed" : summary.warnings > 0 ? "partial" : "passed",
|
|
8445
|
+
summary,
|
|
8446
|
+
checks
|
|
8447
|
+
};
|
|
8448
|
+
}
|
|
8449
|
+
|
|
6961
8450
|
// src/cli/caartzee-cli.ts
|
|
6962
8451
|
async function runCli(rawArgs, io = {}) {
|
|
6963
8452
|
const log = io.stdout ?? console.log;
|
|
@@ -7005,18 +8494,32 @@ async function runCli(rawArgs, io = {}) {
|
|
|
7005
8494
|
case "dev":
|
|
7006
8495
|
return await handleDev(args, log, error);
|
|
7007
8496
|
case "sync-manifest": {
|
|
7008
|
-
const theme = await loadLocalTheme(
|
|
7009
|
-
writeFileSync5(
|
|
8497
|
+
const theme = await loadLocalTheme(resolve9(args[0] || process.cwd()));
|
|
8498
|
+
writeFileSync5(resolve9(args[0] || process.cwd(), "manifest.json"), JSON.stringify(theme.manifest, null, 2));
|
|
7010
8499
|
log("Exported runtime theme manifest.");
|
|
7011
8500
|
return 0;
|
|
7012
8501
|
}
|
|
8502
|
+
case "doctor":
|
|
8503
|
+
return await handleDoctor(args, log, error);
|
|
8504
|
+
case "version":
|
|
8505
|
+
return await handleVersion(args, log, error);
|
|
7013
8506
|
case "validate":
|
|
7014
8507
|
return await handleValidate(args, log, error);
|
|
7015
8508
|
case "build":
|
|
7016
8509
|
return await handleBuild(args, log, error);
|
|
8510
|
+
case "test":
|
|
8511
|
+
return await handleTestSuite(args, "all", log, error);
|
|
8512
|
+
case "audit":
|
|
8513
|
+
return await handleTestSuite(args, "audit", log, error);
|
|
8514
|
+
case "test-editor":
|
|
8515
|
+
return await handleTestEditor(args, log, error);
|
|
8516
|
+
case "test-commerce":
|
|
8517
|
+
return await handleTestSuite(args, "commerce", log, error);
|
|
8518
|
+
case "test-report":
|
|
8519
|
+
return await handleTestReport(args, log, error);
|
|
7017
8520
|
case "ide":
|
|
7018
8521
|
case "ide-setup": {
|
|
7019
|
-
const targetDir = args[0] ?
|
|
8522
|
+
const targetDir = args[0] ? resolve9(args[0]) : process.cwd();
|
|
7020
8523
|
const res = installCandyIdeSupport({ workspaceDir: targetDir });
|
|
7021
8524
|
log(`
|
|
7022
8525
|
\uD83C\uDFA8 Installed Candy (.candy) IDE language support:`);
|
|
@@ -7050,10 +8553,8 @@ async function handleInit(args, log, error) {
|
|
|
7050
8553
|
throw new Error("Supported templates: commerce");
|
|
7051
8554
|
args = args.filter((_, index) => index !== templateIndex && index !== templateIndex + 1);
|
|
7052
8555
|
}
|
|
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
8556
|
const engineIndex = args.indexOf("--engine");
|
|
7056
|
-
const engine = engineIndex < 0 ?
|
|
8557
|
+
const engine = engineIndex < 0 ? "typescript" : args[engineIndex + 1];
|
|
7057
8558
|
if (engine !== "typescript" && engine !== "candy")
|
|
7058
8559
|
throw new Error("Supported engines are candy and typescript.");
|
|
7059
8560
|
if (commerce && engine === "candy")
|
|
@@ -7067,7 +8568,7 @@ async function handleInit(args, log, error) {
|
|
|
7067
8568
|
if (dirIndex >= 0)
|
|
7068
8569
|
args = args.filter((_, index) => index !== dirIndex && index !== dirIndex + 1);
|
|
7069
8570
|
const nameArg = args[0];
|
|
7070
|
-
const targetDir =
|
|
8571
|
+
const targetDir = resolve9(dir || args[1] || nameArg || "my-caartzee-theme");
|
|
7071
8572
|
const themeName = nameArg || "My Caartzee Theme";
|
|
7072
8573
|
log(`
|
|
7073
8574
|
\uD83D\uDCE6 Scaffolding new Caartzee theme in: ${targetDir}`);
|
|
@@ -7075,8 +8576,7 @@ async function handleInit(args, log, error) {
|
|
|
7075
8576
|
const create = commerce ? scaffoldCommerceTheme : scaffoldTheme;
|
|
7076
8577
|
const result = await create({
|
|
7077
8578
|
targetDir,
|
|
7078
|
-
sdkPath,
|
|
7079
|
-
sdkVersion,
|
|
8579
|
+
sdkPath: fileURLToPath3(new URL("../../", import.meta.url)),
|
|
7080
8580
|
name: themeName,
|
|
7081
8581
|
engine
|
|
7082
8582
|
});
|
|
@@ -7090,11 +8590,10 @@ async function handleInit(args, log, error) {
|
|
|
7090
8590
|
}
|
|
7091
8591
|
log(`
|
|
7092
8592
|
\uD83D\uDE80 Next steps:`);
|
|
7093
|
-
log(` 1. cd
|
|
7094
|
-
log(
|
|
8593
|
+
log(` 1. cd ${nameArg || "my-caartzee-theme"}`);
|
|
8594
|
+
log(` 2. bun install && bun run dev # preview your theme with mock data`);
|
|
7095
8595
|
log(` 3. Generate app SDK access in your developer portal`);
|
|
7096
|
-
log(
|
|
7097
|
-
` : ` 4. bun run validate
|
|
8596
|
+
log(` 4. bun run validate # check before submission
|
|
7098
8597
|
`);
|
|
7099
8598
|
return 0;
|
|
7100
8599
|
} catch (err) {
|
|
@@ -7211,17 +8710,20 @@ async function handleDev(args, log, error) {
|
|
|
7211
8710
|
let port = 3333;
|
|
7212
8711
|
let themeDir = process.cwd();
|
|
7213
8712
|
let store;
|
|
8713
|
+
let editor = false;
|
|
7214
8714
|
for (let i = 0;i < args.length; i++) {
|
|
7215
8715
|
if (args[i] === "--port" && args[i + 1]) {
|
|
7216
8716
|
port = parseInt(args[i + 1], 10);
|
|
7217
8717
|
i++;
|
|
7218
8718
|
} else if (args[i] === "--dir" && args[i + 1]) {
|
|
7219
|
-
themeDir =
|
|
8719
|
+
themeDir = resolve9(args[i + 1]);
|
|
7220
8720
|
i++;
|
|
7221
8721
|
} else if (args[i] === "--store") {
|
|
7222
8722
|
store = args[++i];
|
|
7223
8723
|
if (!store || store.startsWith("-"))
|
|
7224
8724
|
throw new Error("--store requires a store domain or tenant ID.");
|
|
8725
|
+
} else if (args[i] === "--editor") {
|
|
8726
|
+
editor = true;
|
|
7225
8727
|
}
|
|
7226
8728
|
}
|
|
7227
8729
|
log(`
|
|
@@ -7247,10 +8749,17 @@ async function handleDev(args, log, error) {
|
|
|
7247
8749
|
};
|
|
7248
8750
|
await loadCatalog({});
|
|
7249
8751
|
}
|
|
7250
|
-
const instance = await startThemeDevServer({
|
|
8752
|
+
const instance = await startThemeDevServer({
|
|
8753
|
+
port,
|
|
8754
|
+
themeDir,
|
|
8755
|
+
editor,
|
|
8756
|
+
...store ? { storeLabel: store } : {},
|
|
8757
|
+
...loadCatalog ? { loadCatalog } : {}
|
|
8758
|
+
});
|
|
7251
8759
|
log(` \x1B[32m✓ Local Preview ready at:\x1B[0m \x1B[36m${instance.url}\x1B[0m`);
|
|
7252
|
-
log(
|
|
7253
|
-
log(
|
|
8760
|
+
log(` \x1B[32m✓ Local Theme Editor ready at:\x1B[0m \x1B[36m${instance.editorUrl}\x1B[0m`);
|
|
8761
|
+
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.");
|
|
8762
|
+
log(` • Inspect storefront context at: ${instance.url}/_api/context`);
|
|
7254
8763
|
log(` • Press Ctrl+C to stop.
|
|
7255
8764
|
`);
|
|
7256
8765
|
if (process.env.CAARTZEE_DEV_ONESHOT === "true") {
|
|
@@ -7274,21 +8783,21 @@ Shutting down dev server...`);
|
|
|
7274
8783
|
}
|
|
7275
8784
|
}
|
|
7276
8785
|
async function handleValidate(args, log, error) {
|
|
7277
|
-
const targetDir = args[0] ?
|
|
8786
|
+
const targetDir = args[0] ? resolve9(args[0]) : process.cwd();
|
|
7278
8787
|
log(`
|
|
7279
8788
|
\uD83D\uDEE1️ Running Caartzee Theme Security & Package Validation...`);
|
|
7280
8789
|
log(` Target: ${targetDir}`);
|
|
7281
|
-
const manifestPath =
|
|
7282
|
-
if (!
|
|
8790
|
+
const manifestPath = join11(targetDir, "manifest.json");
|
|
8791
|
+
if (!existsSync11(manifestPath)) {
|
|
7283
8792
|
error(`❌ Missing manifest.json in ${targetDir}`);
|
|
7284
8793
|
return 1;
|
|
7285
8794
|
}
|
|
7286
8795
|
try {
|
|
7287
|
-
if (
|
|
8796
|
+
if (existsSync11(join11(targetDir, "src/manifest.ts")) && typeof Bun !== "undefined") {
|
|
7288
8797
|
const theme = await loadLocalTheme(targetDir);
|
|
7289
8798
|
writeFileSync5(manifestPath, JSON.stringify(theme.manifest, null, 2));
|
|
7290
8799
|
}
|
|
7291
|
-
const rawManifest = JSON.parse(
|
|
8800
|
+
const rawManifest = JSON.parse(readFileSync11(manifestPath, "utf-8"));
|
|
7292
8801
|
const manifestCheck = ThemePackageValidator.validateManifest(rawManifest);
|
|
7293
8802
|
if (!manifestCheck.success) {
|
|
7294
8803
|
error(`❌ Manifest validation failed:`);
|
|
@@ -7327,7 +8836,7 @@ async function handleValidate(args, log, error) {
|
|
|
7327
8836
|
}
|
|
7328
8837
|
}
|
|
7329
8838
|
async function handleBuild(args, log, error) {
|
|
7330
|
-
const targetDir = args[0] ?
|
|
8839
|
+
const targetDir = args[0] ? resolve9(args[0]) : process.cwd();
|
|
7331
8840
|
log(`
|
|
7332
8841
|
\uD83D\uDD28 Building Caartzee Theme Package...`);
|
|
7333
8842
|
log(` Source directory: ${targetDir}`);
|
|
@@ -7339,9 +8848,9 @@ async function handleBuild(args, log, error) {
|
|
|
7339
8848
|
}
|
|
7340
8849
|
return 1;
|
|
7341
8850
|
}
|
|
7342
|
-
const isCandy =
|
|
7343
|
-
const distDir =
|
|
7344
|
-
if (!
|
|
8851
|
+
const isCandy = existsSync11(join11(targetDir, "candy.config.json")) || existsSync11(join11(targetDir, "layout", "theme.candy")) || valResult.manifest?.engine === "candy";
|
|
8852
|
+
const distDir = join11(targetDir, "dist");
|
|
8853
|
+
if (!existsSync11(distDir)) {
|
|
7345
8854
|
mkdirSync5(distDir, { recursive: true });
|
|
7346
8855
|
}
|
|
7347
8856
|
if (isCandy) {
|
|
@@ -7354,8 +8863,8 @@ async function handleBuild(args, log, error) {
|
|
|
7354
8863
|
}
|
|
7355
8864
|
return 1;
|
|
7356
8865
|
}
|
|
7357
|
-
const bundlePath =
|
|
7358
|
-
const manifestOutPath =
|
|
8866
|
+
const bundlePath = join11(distDir, "candy-theme-bundle.json");
|
|
8867
|
+
const manifestOutPath = join11(distDir, "manifest.json");
|
|
7359
8868
|
writeFileSync5(bundlePath, JSON.stringify(bundle, null, 2), "utf-8");
|
|
7360
8869
|
writeFileSync5(manifestOutPath, JSON.stringify(bundle.manifest, null, 2), "utf-8");
|
|
7361
8870
|
log(`✓ Extracted ${Object.keys(bundle.sectionSchemas).length} section schemas`);
|
|
@@ -7365,7 +8874,7 @@ async function handleBuild(args, log, error) {
|
|
|
7365
8874
|
return 0;
|
|
7366
8875
|
}
|
|
7367
8876
|
if (valResult.manifest) {
|
|
7368
|
-
const manifestOutPath =
|
|
8877
|
+
const manifestOutPath = join11(distDir, "manifest.json");
|
|
7369
8878
|
writeFileSync5(manifestOutPath, JSON.stringify(valResult.manifest, null, 2), "utf-8");
|
|
7370
8879
|
log(`✓ Wrote validated manifest to ${manifestOutPath}
|
|
7371
8880
|
`);
|
|
@@ -7384,10 +8893,10 @@ async function handlePush(args, log, error) {
|
|
|
7384
8893
|
error(`❌ Insufficient scope. Your account lacks "theme:publish" permissions.`);
|
|
7385
8894
|
return 1;
|
|
7386
8895
|
}
|
|
7387
|
-
const targetDir = args[0] ?
|
|
7388
|
-
if (
|
|
8896
|
+
const targetDir = args[0] ? resolve9(args[0]) : process.cwd();
|
|
8897
|
+
if (existsSync11(join11(targetDir, "src/manifest.ts")) && typeof Bun !== "undefined") {
|
|
7389
8898
|
const theme = await loadLocalTheme(targetDir);
|
|
7390
|
-
writeFileSync5(
|
|
8899
|
+
writeFileSync5(join11(targetDir, "manifest.json"), JSON.stringify(theme.manifest, null, 2));
|
|
7391
8900
|
}
|
|
7392
8901
|
const valResult = await ThemePackageValidator.validatePackage(targetDir);
|
|
7393
8902
|
if (!valResult.valid) {
|
|
@@ -7408,10 +8917,266 @@ async function handlePush(args, log, error) {
|
|
|
7408
8917
|
`);
|
|
7409
8918
|
return 0;
|
|
7410
8919
|
}
|
|
8920
|
+
async function handleDoctor(args, log, error) {
|
|
8921
|
+
const targetDir = args[0] ? resolve9(args[0]) : process.cwd();
|
|
8922
|
+
log(`
|
|
8923
|
+
\uD83E\uDE7A Running Caartzee Candy Theme Doctor...`);
|
|
8924
|
+
log(` Target: ${targetDir}
|
|
8925
|
+
`);
|
|
8926
|
+
const issues = [];
|
|
8927
|
+
const warnings = [];
|
|
8928
|
+
const passed = [];
|
|
8929
|
+
const readIfExists = (rel) => {
|
|
8930
|
+
const full = join11(targetDir, rel);
|
|
8931
|
+
return existsSync11(full) ? readFileSync11(full, "utf8") : null;
|
|
8932
|
+
};
|
|
8933
|
+
const configRaw = readIfExists("candy.config.json");
|
|
8934
|
+
const manifestRaw = readIfExists("manifest.json");
|
|
8935
|
+
if (!configRaw)
|
|
8936
|
+
issues.push("Missing candy.config.json in theme root.");
|
|
8937
|
+
if (!manifestRaw)
|
|
8938
|
+
issues.push('Missing manifest.json. Run "caartzee-theme sync-manifest .".');
|
|
8939
|
+
let configJson = null;
|
|
8940
|
+
let manifestJson = null;
|
|
8941
|
+
try {
|
|
8942
|
+
if (configRaw)
|
|
8943
|
+
configJson = JSON.parse(configRaw);
|
|
8944
|
+
} catch {
|
|
8945
|
+
issues.push("candy.config.json is invalid JSON.");
|
|
8946
|
+
}
|
|
8947
|
+
try {
|
|
8948
|
+
if (manifestRaw)
|
|
8949
|
+
manifestJson = JSON.parse(manifestRaw);
|
|
8950
|
+
} catch {
|
|
8951
|
+
issues.push("manifest.json is invalid JSON.");
|
|
8952
|
+
}
|
|
8953
|
+
if (configJson && manifestJson) {
|
|
8954
|
+
if (configJson.slug !== manifestJson.slug) {
|
|
8955
|
+
issues.push(`Slug mismatch: candy.config.json ("${configJson.slug}") != manifest.json ("${manifestJson.slug}").`);
|
|
8956
|
+
} else {
|
|
8957
|
+
passed.push(`Slug aligned ("${configJson.slug}")`);
|
|
8958
|
+
}
|
|
8959
|
+
if (configJson.version !== manifestJson.version) {
|
|
8960
|
+
warnings.push(`Version mismatch: candy.config.json (${configJson.version}) != manifest.json (${manifestJson.version}). Run "caartzee-theme sync-manifest .".`);
|
|
8961
|
+
} else {
|
|
8962
|
+
passed.push(`Version aligned (v${configJson.version})`);
|
|
8963
|
+
}
|
|
8964
|
+
}
|
|
8965
|
+
const caps = manifestJson?.capabilities;
|
|
8966
|
+
const usesShell = Array.isArray(caps) ? caps.includes("storefront-shell") : caps?.["storefront-shell"] === true;
|
|
8967
|
+
const hasCommerce = Array.isArray(caps) ? caps.includes("commerce_pages") : caps?.commerce_pages === true;
|
|
8968
|
+
if (usesShell && hasCommerce) {
|
|
8969
|
+
passed.push("Storefront Shell + commerce_pages capabilities enabled");
|
|
8970
|
+
} else {
|
|
8971
|
+
warnings.push('Set capabilities: { "storefront-shell": true, "commerce_pages": true } in manifest.json for live cart/checkout/auth.');
|
|
8972
|
+
}
|
|
8973
|
+
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"];
|
|
8974
|
+
for (const name of templateNames) {
|
|
8975
|
+
const content = readIfExists(join11("templates", name));
|
|
8976
|
+
if (!content)
|
|
8977
|
+
continue;
|
|
8978
|
+
if (usesShell && /\{%\s*layout\s+/i.test(content)) {
|
|
8979
|
+
issues.push(`templates/${name} uses {% layout %}, which causes duplicate headers/footers when storefront-shell is enabled.`);
|
|
8980
|
+
}
|
|
8981
|
+
if (/data-variant-id\s*=\s*["'][^"']*-default["']/i.test(content)) {
|
|
8982
|
+
issues.push(`templates/${name} emits a synthetic "-default" variant ID, which causes POST /_api/cart 422 errors.`);
|
|
8983
|
+
}
|
|
8984
|
+
}
|
|
8985
|
+
const productCard = readIfExists(join11("snippets", "product-card.candy"));
|
|
8986
|
+
if (productCard) {
|
|
8987
|
+
if (/data-variant-id\s*=\s*["'][^"']*-default["']/i.test(productCard)) {
|
|
8988
|
+
issues.push('snippets/product-card.candy emits a synthetic "-default" variant ID. Guard data-variant-id with product.has_inventory_variants.');
|
|
8989
|
+
} else {
|
|
8990
|
+
passed.push("Product card variant ID contract looks safe");
|
|
8991
|
+
}
|
|
8992
|
+
}
|
|
8993
|
+
const headerCandy = readIfExists(join11("sections", "header.candy"));
|
|
8994
|
+
if (headerCandy) {
|
|
8995
|
+
if (!headerCandy.includes("js-cart-count")) {
|
|
8996
|
+
warnings.push("sections/header.candy is missing .js-cart-count on the cart badge (live Add to Cart count won't update).");
|
|
8997
|
+
} else {
|
|
8998
|
+
passed.push("Header cart count badge (.js-cart-count) present");
|
|
8999
|
+
}
|
|
9000
|
+
if (!headerCandy.includes("menuId") || !headerCandy.includes("linklists")) {
|
|
9001
|
+
warnings.push(`sections/header.candy should include "menuId" schema setting and render linklists['main-menu'].links.`);
|
|
9002
|
+
} else {
|
|
9003
|
+
passed.push("Header navigation menu (menuId + linklists) wired");
|
|
9004
|
+
}
|
|
9005
|
+
}
|
|
9006
|
+
const heroCandy = readIfExists(join11("sections", "hero-banner.candy"));
|
|
9007
|
+
if (heroCandy) {
|
|
9008
|
+
if (!heroCandy.includes("mobile_sliders")) {
|
|
9009
|
+
warnings.push("sections/hero-banner.candy does not read mobile_sliders (merchant Mobile Slider changes won't reflect).");
|
|
9010
|
+
} else {
|
|
9011
|
+
passed.push("Hero banner mobile_sliders support present");
|
|
9012
|
+
}
|
|
9013
|
+
}
|
|
9014
|
+
const loginCandy = readIfExists(join11("templates", "login.candy"));
|
|
9015
|
+
const registerCandy = readIfExists(join11("templates", "register.candy"));
|
|
9016
|
+
if (loginCandy) {
|
|
9017
|
+
if (!loginCandy.includes("/_api/auth/login") || !loginCandy.includes("js-auth-form")) {
|
|
9018
|
+
issues.push('templates/login.candy must post to /_api/auth/login with class="js-auth-form".');
|
|
9019
|
+
} else {
|
|
9020
|
+
passed.push("Login page (/login) auth contract verified");
|
|
9021
|
+
}
|
|
9022
|
+
}
|
|
9023
|
+
if (registerCandy) {
|
|
9024
|
+
if (!registerCandy.includes("/_api/auth/register") || !registerCandy.includes("js-auth-form")) {
|
|
9025
|
+
issues.push('templates/register.candy must post to /_api/auth/register with class="js-auth-form".');
|
|
9026
|
+
} else {
|
|
9027
|
+
passed.push("Signup page (/signup, /register) auth contract verified");
|
|
9028
|
+
}
|
|
9029
|
+
}
|
|
9030
|
+
if (readIfExists(join11("assets", "theme.css")))
|
|
9031
|
+
passed.push("assets/theme.css found");
|
|
9032
|
+
else
|
|
9033
|
+
warnings.push("assets/theme.css not found.");
|
|
9034
|
+
if (readIfExists(join11("assets", "theme.js")))
|
|
9035
|
+
passed.push("assets/theme.js found");
|
|
9036
|
+
else
|
|
9037
|
+
warnings.push("assets/theme.js not found.");
|
|
9038
|
+
for (const p of passed)
|
|
9039
|
+
log(` ✓ ${p}`);
|
|
9040
|
+
if (warnings.length > 0) {
|
|
9041
|
+
log("");
|
|
9042
|
+
for (const w of warnings)
|
|
9043
|
+
log(` ⚠️ ${w}`);
|
|
9044
|
+
}
|
|
9045
|
+
if (issues.length > 0) {
|
|
9046
|
+
log("");
|
|
9047
|
+
for (const i of issues)
|
|
9048
|
+
error(` ❌ ${i}`);
|
|
9049
|
+
log(`
|
|
9050
|
+
❌ Doctor found ${issues.length} error(s) and ${warnings.length} warning(s).
|
|
9051
|
+
`);
|
|
9052
|
+
return 1;
|
|
9053
|
+
}
|
|
9054
|
+
log(`
|
|
9055
|
+
✅ Theme Doctor passed! (${passed.length} checks passed, ${warnings.length} warning(s))
|
|
9056
|
+
`);
|
|
9057
|
+
return 0;
|
|
9058
|
+
}
|
|
9059
|
+
async function handleVersion(args, log, error) {
|
|
9060
|
+
const bump = args[0]?.trim();
|
|
9061
|
+
const targetDir = args[1] ? resolve9(args[1]) : process.cwd();
|
|
9062
|
+
if (!bump) {
|
|
9063
|
+
error("Usage: caartzee-theme version <patch|minor|major|x.y.z> [path]");
|
|
9064
|
+
return 1;
|
|
9065
|
+
}
|
|
9066
|
+
const configPath = join11(targetDir, "candy.config.json");
|
|
9067
|
+
const manifestPath = join11(targetDir, "manifest.json");
|
|
9068
|
+
if (!existsSync11(configPath) && !existsSync11(manifestPath)) {
|
|
9069
|
+
error(`No candy.config.json or manifest.json found in ${targetDir}`);
|
|
9070
|
+
return 1;
|
|
9071
|
+
}
|
|
9072
|
+
const readJson = (p) => JSON.parse(readFileSync11(p, "utf8"));
|
|
9073
|
+
const current = existsSync11(configPath) ? String(readJson(configPath).version || "1.0.0") : String(readJson(manifestPath).version || "1.0.0");
|
|
9074
|
+
let nextVersion = bump;
|
|
9075
|
+
if (bump === "patch" || bump === "minor" || bump === "major") {
|
|
9076
|
+
const parts = current.split(".").map((n) => parseInt(n, 10) || 0);
|
|
9077
|
+
const [maj = 1, min = 0, pat = 0] = parts;
|
|
9078
|
+
nextVersion = bump === "major" ? `${maj + 1}.0.0` : bump === "minor" ? `${maj}.${min + 1}.0` : `${maj}.${min}.${pat + 1}`;
|
|
9079
|
+
} else if (!/^\d+\.\d+\.\d+$/.test(bump)) {
|
|
9080
|
+
error(`Invalid version "${bump}". Use patch, minor, major, or semver like 1.0.3.`);
|
|
9081
|
+
return 1;
|
|
9082
|
+
}
|
|
9083
|
+
if (existsSync11(configPath)) {
|
|
9084
|
+
const cfg = readJson(configPath);
|
|
9085
|
+
cfg.version = nextVersion;
|
|
9086
|
+
writeFileSync5(configPath, JSON.stringify(cfg, null, 2) + `
|
|
9087
|
+
`, "utf8");
|
|
9088
|
+
}
|
|
9089
|
+
if (existsSync11(manifestPath)) {
|
|
9090
|
+
const man = readJson(manifestPath);
|
|
9091
|
+
man.version = nextVersion;
|
|
9092
|
+
writeFileSync5(manifestPath, JSON.stringify(man, null, 2) + `
|
|
9093
|
+
`, "utf8");
|
|
9094
|
+
}
|
|
9095
|
+
log(`✓ Bumped theme version: ${current} -> ${nextVersion}`);
|
|
9096
|
+
return 0;
|
|
9097
|
+
}
|
|
9098
|
+
function parseTargetAndJson(args) {
|
|
9099
|
+
const asJson = args.includes("--json");
|
|
9100
|
+
const positional = args.filter((a) => !a.startsWith("-"));
|
|
9101
|
+
const targetDir = positional[0] ? resolve9(positional[0]) : process.cwd();
|
|
9102
|
+
return { targetDir, asJson };
|
|
9103
|
+
}
|
|
9104
|
+
async function handleTestEditor(args, log, error) {
|
|
9105
|
+
const { targetDir, asJson } = parseTargetAndJson(args);
|
|
9106
|
+
const result = validateThemeEditorDirectory(targetDir);
|
|
9107
|
+
if (asJson) {
|
|
9108
|
+
log(JSON.stringify(result, null, 2));
|
|
9109
|
+
return result.valid ? 0 : 1;
|
|
9110
|
+
}
|
|
9111
|
+
log(`
|
|
9112
|
+
\uD83C\uDFA8 Caartzee Theme Editor Compatibility Check (${result.slug || targetDir})`);
|
|
9113
|
+
for (const c of result.checks) {
|
|
9114
|
+
const icon = c.status === "passed" ? "✓" : c.status === "warning" ? "⚠️" : "❌";
|
|
9115
|
+
(c.status === "failed" ? error : log)(` ${icon} [${c.name}] ${c.message}${c.file ? ` (${c.file})` : ""}`);
|
|
9116
|
+
}
|
|
9117
|
+
log(`
|
|
9118
|
+
${result.valid ? "✅" : "❌"} Theme Editor check: ${result.summary.passed} passed, ${result.summary.failed} failed, ${result.summary.warnings} warning(s).
|
|
9119
|
+
`);
|
|
9120
|
+
return result.valid ? 0 : 1;
|
|
9121
|
+
}
|
|
9122
|
+
async function handleTestSuite(args, mode, log, error) {
|
|
9123
|
+
const { targetDir, asJson } = parseTargetAndJson(args);
|
|
9124
|
+
const fullReport = await runThemeReadinessAudit(targetDir);
|
|
9125
|
+
const checks = mode === "commerce" ? fullReport.checks.filter((c) => c.category === "commerce" || c.category === "plugins") : fullReport.checks;
|
|
9126
|
+
const failed = checks.filter((c) => c.status === "failed").length;
|
|
9127
|
+
const passed = checks.filter((c) => c.status === "passed").length;
|
|
9128
|
+
const warnings = checks.filter((c) => c.status === "warning").length;
|
|
9129
|
+
const payload = {
|
|
9130
|
+
...fullReport,
|
|
9131
|
+
mode,
|
|
9132
|
+
status: failed > 0 ? "failed" : warnings > 0 ? "partial" : "passed",
|
|
9133
|
+
summary: { ...fullReport.summary, passed, failed, warnings },
|
|
9134
|
+
checks
|
|
9135
|
+
};
|
|
9136
|
+
if (asJson) {
|
|
9137
|
+
log(JSON.stringify(payload, null, 2));
|
|
9138
|
+
return failed > 0 ? 1 : 0;
|
|
9139
|
+
}
|
|
9140
|
+
const label = mode === "commerce" ? "Commerce & Plugin Hooks Test" : mode === "audit" ? "Theme Readiness Audit" : "Storefront Test Suite";
|
|
9141
|
+
log(`
|
|
9142
|
+
\uD83E\uDDEA Caartzee ${label} — ${payload.slug}@${payload.version}`);
|
|
9143
|
+
log(` Package Hash: ${payload.packageHash.slice(0, 16)}...`);
|
|
9144
|
+
for (const c of checks) {
|
|
9145
|
+
const icon = c.status === "passed" ? "✓" : c.status === "warning" ? "⚠️" : "❌";
|
|
9146
|
+
(c.status === "failed" ? error : log)(` ${icon} [${c.category}/${c.id}] ${c.message}${c.file ? ` (${c.file})` : ""}`);
|
|
9147
|
+
}
|
|
9148
|
+
log(`
|
|
9149
|
+
${failed === 0 ? "✅" : "❌"} Result: ${passed} passed, ${failed} failed, ${warnings} warning(s).
|
|
9150
|
+
`);
|
|
9151
|
+
return failed > 0 ? 1 : 0;
|
|
9152
|
+
}
|
|
9153
|
+
async function handleTestReport(args, log, error) {
|
|
9154
|
+
const { targetDir, asJson } = parseTargetAndJson(args);
|
|
9155
|
+
const report = await runThemeReadinessAudit(targetDir);
|
|
9156
|
+
const distDir = join11(targetDir, "dist");
|
|
9157
|
+
if (!existsSync11(distDir))
|
|
9158
|
+
mkdirSync5(distDir, { recursive: true });
|
|
9159
|
+
const outPath = join11(distDir, "theme-readiness-report.json");
|
|
9160
|
+
writeFileSync5(outPath, JSON.stringify(report, null, 2), "utf8");
|
|
9161
|
+
if (asJson) {
|
|
9162
|
+
log(JSON.stringify({ reportPath: outPath, ...report }, null, 2));
|
|
9163
|
+
} else {
|
|
9164
|
+
log(`
|
|
9165
|
+
\uD83D\uDCC4 Wrote readiness report bound to packageHash ${report.packageHash.slice(0, 16)}...`);
|
|
9166
|
+
log(` Path: ${outPath}`);
|
|
9167
|
+
log(` Status: ${report.status.toUpperCase()} (${report.summary.passed} passed, ${report.summary.failed} failed, ${report.summary.warnings} warning(s))
|
|
9168
|
+
`);
|
|
9169
|
+
}
|
|
9170
|
+
if (report.summary.failed > 0) {
|
|
9171
|
+
error(`Theme readiness report recorded ${report.summary.failed} failing check(s).`);
|
|
9172
|
+
return 1;
|
|
9173
|
+
}
|
|
9174
|
+
return 0;
|
|
9175
|
+
}
|
|
7411
9176
|
function printHelp(log) {
|
|
7412
9177
|
log(`
|
|
7413
9178
|
╔═══════════════════════════════════════════════════════════════╗
|
|
7414
|
-
║ CAARTZEE THEME SDK CLI (v1.
|
|
9179
|
+
║ CAARTZEE THEME SDK CLI (v1.2.0) ║
|
|
7415
9180
|
║ Build, test, and publish secure storefront themes locally ║
|
|
7416
9181
|
╚═══════════════════════════════════════════════════════════════╝
|
|
7417
9182
|
|
|
@@ -7421,15 +9186,24 @@ Usage:
|
|
|
7421
9186
|
|
|
7422
9187
|
Commands:
|
|
7423
9188
|
init [name] Scaffold a theme. Use --engine candy for Candy or --template commerce for TypeScript commerce.
|
|
7424
|
-
dev [--port 3333] [--store DOMAIN]
|
|
7425
|
-
|
|
7426
|
-
|
|
9189
|
+
dev [--port 3333] [--store DOMAIN] [--editor] Preview with full local commerce/auth & Theme Editor
|
|
9190
|
+
doctor [path] Audit storefront-shell, cart/variant hooks, auth forms, menus & mobile sliders
|
|
9191
|
+
version <patch|minor|major|x.y.z> [path] Bump version across candy.config.json and manifest.json
|
|
9192
|
+
sync-manifest [path] Export the locally authored theme manifest to JSON
|
|
9193
|
+
validate [path] Check source patterns and validate manifest
|
|
9194
|
+
test [path] [--json] Run full storefront validation, editor, commerce, security & responsive suite
|
|
9195
|
+
audit [path] [--json] Run comprehensive readiness, accessibility, security & commerce audit
|
|
9196
|
+
test-editor [path] [--json] Verify Theme Editor schemas, block attributes & live rendering
|
|
9197
|
+
test-commerce [path] [--json] Verify cart, variant, wishlist, search, auth & plugin contracts
|
|
9198
|
+
test-report [path] [--json] Generate packageHash-bound dist/theme-readiness-report.json
|
|
9199
|
+
build [path] Compile Candy templates and assets into dist/candy-theme-bundle.json
|
|
9200
|
+
ide-setup [path] Install .candy syntax highlighting for VS Code / Cursor / Antigravity
|
|
9201
|
+
connect --clipboard Connect using the Windows clipboard
|
|
9202
|
+
connect --stdin Connect using a piped Developer Portal connection
|
|
7427
9203
|
login --api URL --token-stdin Connect with app SDK access from developer portal
|
|
7428
9204
|
whoami Display current developer account & token status
|
|
7429
9205
|
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
|
|
9206
|
+
push [path] Validate and push theme to Caartzee Partner Portal
|
|
7433
9207
|
help Display this help message
|
|
7434
9208
|
|
|
7435
9209
|
Security Guarantee:
|