← Files ShopifyARCHIVED FILE
skills/shopify/scripts/_validate_components.mjs
72 KB · Dec 5, 2026 · 00:24 UTC
#!/usr/bin/env node
var Tt=Object.defineProperty;var o=(e,t)=>Tt(e,"name",{value:t,configurable:!0});import{readFileSync as Pr}from"fs";import{parseArgs as _r}from"util";var f={PUBLIC:"public",EARLY_ACCESS:"earlyAccess",INTERNAL:"internal"},m={GRAPHQL:"graphql",FUNCTIONS:"functions",FUNCTION_GRAPHQL:"function-graphql",UI_FRAMEWORK:"ui-framework",THEME:"theme",CONFIGURATION:"configuration",EXECUTION:"execution",GUIDANCE:"guidance"};function Nt(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[t,{name:t,...n}]))}o(Nt,"defineApis");var J=Nt({flow:{displayName:"Flow workflows",description:"Build and manage Shopify Flow workflows through the Admin GraphQL API: create, list, read, update, activate, deactivate, and delete workflows; parse .flow exports; and discover templates, tasks, and environment fields. Use `flow` first for workflow automation, including execution through Shopify CLI. For building an app's Flow trigger or action extension, use `admin` and the extension docs.",category:m.EXECUTION,visibility:f.PUBLIC,searchable:"unscoped",exampleVectorStoreQuery:{query:"Shopify Flow automationWorkflowCreate",context:"creating Flow workflows through the unstable Admin API"}},"use-shopify-cli":{displayName:"Use Shopify CLI",routingNote:"For Shopify Flow workflow operations, use `flow` first.",description:"Choose when the user needs **Shopify CLI** to run or fix something now: validate app or extension config on disk (`shopify.app.toml`, `shopify.app.<name>.toml`, `shopify.extension.toml`); review or audit an app's code for security vulnerabilities; run or troubleshoot store workflows (`shopify store auth`, `shopify store execute`); or perform explicit store-scoped reads/writes on a named store domain (for example, show/list/find the first 10 products on my store at `foo.myshopify.com`, or inventory and product changes by handle, SKU, or location name). Emphasize **commands and operational steps**, not only authoring GraphQL. Skip for API-only understanding or codegen with no CLI execution, and skip for brand-new merchant asks to start a Shopify store or try Shopify before they have an account. Examples: validate configuration before deploy; run an existing query via CLI; show the first 10 products on `foo.myshopify.com`; missing `shopify store execute`.",category:m.EXECUTION,visibility:f.PUBLIC,searchable:!1},ucp:{displayName:"UCP CLI",description:'Use when the user wants to use the UCP CLI to find, compare, buy, or track products from online merchants, or to set up and troubleshoot the local UCP profile required for merchant-scoped operations. Covers global catalog search ("find me X under $Y"), named-merchant transactions ("buy this from Z.com"), order tracking, `ucp profile init`, `ucp doctor`, carts, checkout, orders, and UCP setup/help. Falls back to merchant-hosted handoff when direct in-protocol checkout isn\'t available.',category:m.EXECUTION,visibility:f.PUBLIC,searchable:!1,skillName:"ucp",compatibility:"Requires UCP CLI",frontmatterExtras:{requires_bin:"ucp",command:"ucp"}},admin:{displayName:"Admin API",routingNote:"For Shopify Flow workflow operations, use `flow` first.",versioned:!0,description:"Write or explain **Admin GraphQL** queries and mutations for apps and integrations that extend the Shopify admin. Use when the user wants to **understand, design, or generate** the operation itself\u2014even before deciding how to run it. Do **not** choose `admin` first for **app monetization**\u2014charging merchants for the app itself via app pricing plans, paid app tiers, app subscription charges, or app free trials\u2014use **`app-pricing`** unless the user is maintaining an existing Manual Pricing integration or explicitly needs an Admin Billing API operation. Merchant **product** subscriptions stay with `admin` (selling plans, subscription contracts, try-before-you-buy). Do **not** choose `admin` first for **app or extension config validation** \u2014use **`use-shopify-cli`**. Do **not** choose `admin` first to **execute** Admin GraphQL **now via Shopify CLI** or for CLI setup/troubleshooting on store workflows\u2014use **`use-shopify-cli`** (store auth/execute, handle/SKU/location lookups, inventory changes).",category:m.GRAPHQL,visibility:f.PUBLIC,schemaSource:{shopifyDevPrefix:"admin"},validation:!0,exampleVectorStoreQuery:{query:"productCreate mutation",context:"creating a product"}},shopifyql:{displayName:"ShopifyQL",versioned:!0,description:'Answer a merchant\'s **analytics and reporting** questions with **ShopifyQL** \u2014 Shopify\'s query language for aggregated store metrics that the Admin GraphQL API cannot compute. Choose this (not `admin`) whenever the ask is for **numbers, totals, trends, or breakdowns** rather than fetching or mutating individual records: including but not limited to total/gross/net sales and revenue, order counts, average order value, refunds, quantity sold, sessions, conversion rate, and traffic \u2014 sliced by product, channel, region, or customer, trended over time, or compared period-over-period. Examples: "total sales last 7 days", "orders by sales channel this month", "top products by revenue", "conversion rate this week", "sales this year vs last year". This topic covers writing the ShopifyQL query; if the merchant wants to run it against their store, execution is handed off to `use-shopify-cli`. Not for general Admin GraphQL record operations \u2014 fetching or mutating individual resources (use `admin`).',category:m.GUIDANCE,visibility:f.PUBLIC,exampleVectorStoreQuery:{query:"ShopifyQL total sales over time",context:"querying aggregated store analytics with ShopifyQL"}},"storefront-graphql":{displayName:"Storefront GraphQL API",versioned:!0,description:"Use for custom storefronts requiring direct GraphQL queries/mutations for data fetching and cart operations. Choose this when you need full control over data fetching and rendering your own UI. NOT for Web Components - if the prompt mentions HTML tags like <shopify-store>, <shopify-cart>, use storefront-web-components instead.",category:m.GRAPHQL,visibility:f.PUBLIC,schemaSource:{shopifyDevPrefix:"storefront"},validation:!0,exampleVectorStoreQuery:{query:"predictiveSearch query",context:"storefront search"}},partner:{displayName:"Partner API",versioned:!0,description:"The Partner API lets you programmatically access data about your Partner Dashboard, including your apps, themes, and affiliate referrals.",category:m.GRAPHQL,visibility:f.PUBLIC,schemaSource:{shopifyDevPrefix:"partner"},validation:!0,exampleVectorStoreQuery:{query:"transactions query",context:"partner transaction history"}},customer:{displayName:"Customer Account API",versioned:!0,description:"Write and validate GraphQL operations for developers integrating Shopify's Customer Account API. Generates code for Customer Account API integrations.",category:m.GRAPHQL,visibility:f.PUBLIC,schemaSource:{shopifyDevPrefix:"customer"},validation:!0,exampleVectorStoreQuery:{query:"customer orders query",context:"customer order history"}},"payments-apps":{displayName:"Payments Apps API",versioned:!0,description:"The Payments Apps API enables payment providers to integrate their payment solutions with Shopify's checkout.",category:m.GRAPHQL,visibility:f.PUBLIC,schemaSource:{shopifyDevPrefix:"payments_apps"},validation:!0,exampleVectorStoreQuery:{query:"paymentSessionPending mutation",context:"pending a payment session"}},functions:{displayName:"Shopify Functions",versioned:!0,description:"Shopify Functions allow developers to customize the backend logic that powers parts of Shopify. Available APIs: Discount, Cart and Checkout Validation, Cart Transform, Pickup Point Delivery Option Generator, Delivery Customization, Fulfillment Constraints, Local Pickup Delivery Option Generator, Order Routing Location Rule, Payment Customization",category:m.FUNCTIONS,visibility:f.PUBLIC,validation:!0,exampleVectorStoreQuery:{query:"cart transform function input query",context:"cart transform function inputs"}},functions_cart_checkout_validation:{displayName:"Cart Checkout Validation Function",versioned:!0,description:"GraphQL schema for Cart and Checkout Validation Function input queries",category:m.FUNCTION_GRAPHQL,visibility:f.PUBLIC,schemaSource:{shopifyDevPrefix:"functions_cart_checkout_validation_schema"}},functions_cart_transform:{displayName:"Cart Transform Function",versioned:!0,description:"GraphQL schema for Cart Transform Function input queries",category:m.FUNCTION_GRAPHQL,visibility:f.PUBLIC,schemaSource:{shopifyDevPrefix:"functions_cart_transform_schema"}},functions_delivery_customization:{displayName:"Delivery Customization Function",versioned:!0,description:"GraphQL schema for Delivery Customization Function input queries",category:m.FUNCTION_GRAPHQL,visibility:f.PUBLIC,schemaSource:{shopifyDevPrefix:"functions_delivery_customization_schema"}},functions_discount:{displayName:"Discount Function",versioned:!0,description:"GraphQL schema for Discount Function input queries",category:m.FUNCTION_GRAPHQL,visibility:f.PUBLIC,schemaSource:{shopifyDevPrefix:"functions_discount_schema"}},functions_fulfillment_constraints:{displayName:"Fulfillment Constraints Function",versioned:!0,description:"GraphQL schema for Fulfillment Constraints Function input queries",category:m.FUNCTION_GRAPHQL,visibility:f.PUBLIC,schemaSource:{shopifyDevPrefix:"functions_fulfillment_constraints_schema"}},functions_local_pickup_delivery_option_generator:{displayName:"Local Pickup Delivery Option Generator Function",versioned:!0,description:"GraphQL schema for Local Pickup Delivery Option Generator Function input queries",category:m.FUNCTION_GRAPHQL,visibility:f.PUBLIC,schemaSource:{shopifyDevPrefix:"functions_local_pickup_delivery_option_generator_schema"}},functions_order_discounts:{displayName:"Order Discounts Function",versioned:!0,description:"GraphQL schema for Order Discounts Function input queries",category:m.FUNCTION_GRAPHQL,visibility:f.PUBLIC,schemaSource:{shopifyDevPrefix:"functions_order_discounts_schema"}},functions_order_routing_location_rule:{displayName:"Order Routing Location Rule Function",versioned:!0,description:"GraphQL schema for Order Routing Location Rule Function input queries",category:m.FUNCTION_GRAPHQL,visibility:f.PUBLIC,schemaSource:{shopifyDevPrefix:"functions_order_routing_location_rule_schema"}},functions_payment_customization:{displayName:"Payment Customization Function",versioned:!0,description:"GraphQL schema for Payment Customization Function input queries",category:m.FUNCTION_GRAPHQL,visibility:f.PUBLIC,schemaSource:{shopifyDevPrefix:"functions_payment_customization_schema"}},functions_pickup_point_delivery_option_generator:{displayName:"Pickup Point Delivery Option Generator Function",versioned:!0,description:"GraphQL schema for Pickup Point Delivery Option Generator Function input queries",category:m.FUNCTION_GRAPHQL,visibility:f.PUBLIC,schemaSource:{shopifyDevPrefix:"functions_pickup_point_delivery_option_generator_schema"}},functions_product_discounts:{displayName:"Product Discounts Function",versioned:!0,description:"GraphQL schema for Product Discounts Function input queries",category:m.FUNCTION_GRAPHQL,visibility:f.PUBLIC,schemaSource:{shopifyDevPrefix:"functions_product_discounts_schema"}},functions_shipping_discounts:{displayName:"Shipping Discounts Function",versioned:!0,description:"GraphQL schema for Shipping Discounts Function input queries",category:m.FUNCTION_GRAPHQL,visibility:f.PUBLIC,schemaSource:{shopifyDevPrefix:"functions_shipping_discounts_schema"}},"polaris-app-home":{displayName:"Polaris App Home",versioned:!0,description:"Build your app's primary user interface embedded in the Shopify admin using the **iframe** model \u2014 a web app you host yourself, rendered with `@shopify/polaris-types` and App Bridge. Covers the Intents API (`shopify.intents.invoke`) for launching native workflows from App Home. For the Shopify-hosted `admin.app.home.render` extension target, use **`polaris-admin-extensions`** instead. If the prompt just mentions `Polaris` and you can't tell based off of the context what API they meant, assume they meant this API.",category:m.UI_FRAMEWORK,publicPackages:["@shopify/polaris-types",{name:"@shopify/app-bridge-types",versionIndependent:!0},{name:"@shopify/app-bridge-react",versionIndependent:!0},{name:"@shopify/analytics-ui-types",versionIndependent:!0}],visibility:f.PUBLIC,validation:!0,exampleVectorStoreQuery:{query:"s-page",context:"page layout in app home"}},"polaris-admin-extensions":{displayName:"Polaris Admin Extensions",versioned:!0,description:"Add custom actions and blocks from your app at contextually relevant spots throughout the Shopify Admin, including **App Home UI extensions** \u2014 the Shopify-hosted `admin.app.home.render` target (API version `2026-07` or later) that renders your app's landing page instead of an iframe. Covers the Intents API (`shopify.intents.invoke`) for launching native workflows from an extension. Admin UI Extensions also supports scaffolding new admin extensions using Shopify CLI commands.",category:m.UI_FRAMEWORK,publicPackages:["@shopify/ui-extensions",{name:"@shopify/ui-extensions-react",versions:["2025-07"]}],extensionSurfaceName:"admin",extensionTypeName:"Admin Extensions",extensionSearchContext:"admin UI extensions",visibility:f.PUBLIC,validation:!0,exampleVectorStoreQuery:{query:"admin.product-details.block.render",context:"admin extension target for product details blocks"},exampleExtensionTarget:"admin.product-details.block.render"},"polaris-checkout-extensions":{displayName:"Polaris Checkout Extensions",versioned:!0,description:"Build custom functionality that merchants can install at defined points in the checkout flow, including product information, shipping, payment, order summary, and Shop Pay. Checkout UI Extensions also supports scaffolding new checkout extensions using Shopify CLI commands. This topic covers the extension code only \u2014 when the prompt also needs an app backend (for example storing data in the developer's own database, or verifying session tokens on a server), also learn **`onboarding-dev`** to scaffold the app with Shopify's official backend libraries.",category:m.UI_FRAMEWORK,publicPackages:["@shopify/ui-extensions",{name:"@shopify/ui-extensions-react",versions:["2025-07"]}],extensionSurfaceName:"checkout",extensionTypeName:"Checkout Extensions",extensionSearchContext:"checkout UI extensions",visibility:f.PUBLIC,validation:!0,exampleVectorStoreQuery:{query:"s-button checkout",context:"checkout button"},exampleExtensionTarget:"purchase.checkout.block.render"},"polaris-customer-account-extensions":{displayName:"Polaris Customer Account Extensions",versioned:!0,description:"Build custom functionality that merchants can install at defined points on the Order index, Order status, and Profile pages in customer accounts. Customer Account UI Extensions also supports scaffolding new customer account extensions using Shopify CLI commands.",category:m.UI_FRAMEWORK,publicPackages:["@shopify/ui-extensions",{name:"@shopify/ui-extensions-react",versions:["2025-07"]}],extensionSurfaceName:"customer-account",extensionTypeName:"Customer Account Extensions",extensionSearchContext:"customer account UI extensions",visibility:f.PUBLIC,validation:!0,exampleVectorStoreQuery:{query:"s-card customer-account",context:"customer account card"},exampleExtensionTarget:"customer-account.order-status.block.render"},"pos-ui":{displayName:"POS UI",versioned:!0,description:"Build retail point-of-sale applications using Shopify's POS UI components. These components provide a consistent and familiar interface for POS applications. POS UI Extensions also supports scaffolding new POS extensions using Shopify CLI commands. Keywords: POS, Retail, smart grid",category:m.UI_FRAMEWORK,publicPackages:["@shopify/ui-extensions",{name:"@shopify/ui-extensions-react",versions:["2025-07"]}],extensionSurfaceName:"point-of-sale",extensionTypeName:"POS UI Extensions",extensionSearchContext:"POS UI extensions",visibility:f.PUBLIC,validation:!0,exampleVectorStoreQuery:{query:"pos.home.tile.render",context:"POS home tile extension target"},exampleExtensionTarget:"pos.customer-details.block.render"},hydrogen:{displayName:"Hydrogen",versioned:!0,description:"Hydrogen 2026-10 is an SDK for building custom storefronts in the developer's own framework, with the Storefront API client, cart, products, search, customer accounts, analytics, and Shop Pay. MANDATORY: Use this API for ANY Hydrogen storefront question - do NOT use Storefront GraphQL when 'Hydrogen' is mentioned.",category:m.UI_FRAMEWORK,publicPackages:["@shopify/hydrogen"],visibility:f.PUBLIC,validation:!0,exampleVectorStoreQuery:{query:"createCartComponents",context:"cart UI"}},"storefront-web-components":{displayName:"Storefront Web Components",description:"HTML-first web components for building storefronts WITHOUT GraphQL. Choose when prompts mention: Web Components, HTML tags (<shopify-store>, <shopify-context>, <shopify-cart>, <shopify-variant-selector>, <shopify-money>), native <dialog>, 'HTML-only', 'without JavaScript', or 'no GraphQL'. Components handle data fetching and state internally.",category:m.UI_FRAMEWORK,featureFlag:"storefrontWebComponentsEnabled",visibility:f.EARLY_ACCESS,validation:!0,exampleVectorStoreQuery:{query:"shopify-cart",context:"cart web component"}},liquid:{displayName:"Liquid",description:"Liquid is an open-source templating language created by Shopify. It is the backbone of Shopify themes and is used to load dynamic content on storefronts. Keywords: liquid, theme, shopify-theme, liquid-component, liquid-block, liquid-section, liquid-snippet, liquid-schemas, shopify-theme-schemas",category:m.THEME,visibility:f.PUBLIC,schemaSource:{npmPackage:"@shopify/theme-check-common"},validation:!0,exampleVectorStoreQuery:{query:"product metafields",context:"product metafield access in a theme"}},"custom-data":{displayName:"Custom Data",description:"MUST be used first when prompts mention Metafields or Metaobjects. Use Metafields and Metaobjects to model and store custom data for your app. Metafields extend built-in Shopify data types like products or customers, Metaobjects are custom data types that can be used to store bespoke data structures. Metafield and Metaobject definitions provide a schema and configuration for values to follow.",activationTerms:["metafields or metaobjects"],category:m.CONFIGURATION,visibility:f.PUBLIC,searchable:!1},"app-pricing":{displayName:"Shopify App Pricing",description:"Use first when a developer asks how to configure public-app plans, tiers, recurring or usage-based options, or trials. Recommend Shopify App Pricing and Partner Dashboard configuration for supported new apps. Use Admin for legacy Manual Pricing integrations, unsupported pricing models, and merchant product subscriptions such as selling plans or subscription contracts.",category:m.GUIDANCE,visibility:f.PUBLIC,searchable:"unscoped",exampleVectorStoreQuery:{query:"Shopify App Pricing",context:"choosing and implementing app monetization"}},"app-store-review":{displayName:"App Store Review",description:"Run a pre-submission compliance check against your Shopify app's codebase. Reviews App Store requirements and surfaces likely issues before you submit for official review.",category:m.GUIDANCE,visibility:f.PUBLIC,searchable:!1,compatibility:"Requires Node.js and Shopify CLI"},"onboarding-dev":{displayName:"Developer Onboarding",description:"Get started building on Shopify. Use when a developer asks to build an app, build a theme, create a dev store, set up a partner account, scaffold a project, or get started developing for Shopify \u2014 including building an app in a specific backend language or framework (for example Laravel, Symfony, Django, Flask, Rails, or Express); this topic covers scaffolding the app and choosing Shopify's official library for that language. When the prompt also involves an extension surface (checkout, admin, POS, customer accounts), learn this topic **in addition to** the surface topic. NOT for merchants managing stores.",category:m.GUIDANCE,visibility:f.PUBLIC,searchable:!1,compatibility:"Requires Node.js and Shopify CLI"},"onboarding-merchant":{displayName:"Merchant Onboarding",description:"Set up a Shopify store. Use to make, build, or open a store (e.g. 'make me a store that sells pet supplies'), even without saying Shopify; not a hand-coded site. Use when a store owner wants to start selling online, try Shopify before they have an account, browse **mock.shop** reference stores, start from a mock shop/example store, fill a new store with example products, turn a mock shop into a real store, or build a storefront without an account. Also use when developers explicitly need auth-free mock.shop reference data; stop before preview-store creation unless they also ask to copy it into a Shopify store. Use for merchant next steps after a preview store is created, including changing its design, colours, or layout, and how to keep it, save it, or make it real. Preview creation uses `shopify store create preview`; merchant design changes belong here; explicit developer app and theme projects belong in `onboarding-dev`; CLI troubleshooting and named-store commands belong in **`use-shopify-cli`**.",activationTerms:["make me a store that sells pet supplies","mock.shop reference stores","build a storefront without an account"],category:m.GUIDANCE,visibility:f.PUBLIC,searchable:!1,compatibility:"Requires Node.js and Shopify CLI",frontmatterExtras:{maintainer:"Shopify"}}});function te(e){return typeof e=="string"?e:e.name}o(te,"getPublicPackageName");function ye(e,t){return typeof e=="string"||!e.versions||t===void 0?!0:e.versions.includes(t)}o(ye,"publicPackageAppliesToVersion");var De={shopifyql:[{name:"2027-01",releaseCandidate:!0},{name:"2026-10",latestVersion:!0},{name:"2026-07"},{name:"2026-04"},{name:"2026-01"},{name:"2025-10"}],admin:[{name:"unstable"},{name:"2027-01",releaseCandidate:!0},{name:"2026-10",latestVersion:!0},{name:"2026-07"},{name:"2026-04"},{name:"2026-01"}],"storefront-graphql":[{name:"unstable"},{name:"2027-01",releaseCandidate:!0},{name:"2026-10",latestVersion:!0},{name:"2026-07"},{name:"2026-04"},{name:"2026-01"}],partner:[{name:"unstable"},{name:"2027-01",releaseCandidate:!0},{name:"2026-10",latestVersion:!0},{name:"2026-07"},{name:"2026-04"},{name:"2026-01"}],customer:[{name:"unstable"},{name:"2027-01",releaseCandidate:!0},{name:"2026-10",latestVersion:!0},{name:"2026-07"},{name:"2026-04"},{name:"2026-01"}],"payments-apps":[{name:"unstable"},{name:"2027-01",releaseCandidate:!0},{name:"2026-10",latestVersion:!0},{name:"2026-07"},{name:"2026-04"},{name:"2026-01"}],"polaris-app-home":[{name:"v2.0",latestVersion:!0},{name:"v1.1"},{name:"v1.0"}],"polaris-admin-extensions":[{name:"2026-10",latestVersion:!0},{name:"2026-07"},{name:"2026-04"},{name:"2026-01"},{name:"2025-10"},{name:"2025-07"}],"polaris-checkout-extensions":[{name:"2026-10",latestVersion:!0},{name:"2026-07"},{name:"2026-04"},{name:"2026-01"},{name:"2025-10"},{name:"2025-07"}],"polaris-customer-account-extensions":[{name:"2026-10",latestVersion:!0},{name:"2026-07"},{name:"2026-04"},{name:"2026-01"},{name:"2025-10"},{name:"2025-07"}],"pos-ui":[{name:"2026-10",latestVersion:!0},{name:"2026-07"},{name:"2026-04"},{name:"2026-01"},{name:"2025-10"},{name:"2025-07"}],hydrogen:[{name:"2026-10",latestVersion:!0},{name:"2026-04"},{name:"2026-01"},{name:"2025-10"},{name:"2025-07"}],"storefront-web-components":[],functions_cart_checkout_validation:[{name:"unstable"},{name:"2027-01",releaseCandidate:!0},{name:"2026-10",latestVersion:!0},{name:"2026-07"},{name:"2026-04"},{name:"2026-01"}],functions_cart_transform:[{name:"unstable"},{name:"2027-01",releaseCandidate:!0},{name:"2026-10",latestVersion:!0},{name:"2026-07"},{name:"2026-04"},{name:"2026-01"}],functions_delivery_customization:[{name:"unstable"},{name:"2027-01",releaseCandidate:!0},{name:"2026-10",latestVersion:!0},{name:"2026-07"},{name:"2026-04"},{name:"2026-01"}],functions_discount:[{name:"unstable"},{name:"2027-01",releaseCandidate:!0},{name:"2026-10",latestVersion:!0},{name:"2026-07"},{name:"2026-04"},{name:"2026-01"}],functions_fulfillment_constraints:[{name:"unstable"},{name:"2027-01",releaseCandidate:!0},{name:"2026-10",latestVersion:!0},{name:"2026-07"},{name:"2026-04"},{name:"2026-01"}],functions_local_pickup_delivery_option_generator:[{name:"unstable",latestVersion:!0}],functions_order_discounts:[{name:"unstable"},{name:"2027-01",releaseCandidate:!0},{name:"2026-10",latestVersion:!0},{name:"2026-07"},{name:"2026-04"},{name:"2026-01"}],functions_order_routing_location_rule:[{name:"unstable"},{name:"2027-01",releaseCandidate:!0},{name:"2026-10",latestVersion:!0},{name:"2026-07"},{name:"2026-04"},{name:"2026-01"}],functions_payment_customization:[{name:"unstable"},{name:"2027-01",releaseCandidate:!0},{name:"2026-10",latestVersion:!0},{name:"2026-07"},{name:"2026-04"},{name:"2026-01"}],functions_pickup_point_delivery_option_generator:[{name:"unstable",latestVersion:!0}],functions_product_discounts:[{name:"unstable"},{name:"2027-01",releaseCandidate:!0},{name:"2026-10",latestVersion:!0},{name:"2026-07"},{name:"2026-04"},{name:"2026-01"}],functions_shipping_discounts:[{name:"unstable"},{name:"2027-01",releaseCandidate:!0},{name:"2026-10",latestVersion:!0},{name:"2026-07"},{name:"2026-04"},{name:"2026-01"}]};var Se=De,Ve=Object.fromEntries(Object.entries(Se).filter(([e,t])=>t.length>0).map(([e,t])=>[e,t.map(n=>n.name)]));function we(e){return Object.prototype.hasOwnProperty.call(Ve,e)}o(we,"hasSupportedVersions");function ne(e){return we(e)?Ve[e]:[]}o(ne,"getSupportedVersions");function Lt(e){let t=Se[e];if(t)return t.find(n=>n.latestVersion)?.name??t[0]?.name}o(Lt,"getLatestVersion");function ke(e,t){if(!we(e))throw new Error(`API "${e}" is not in the supported versions catalog. Only call resolveVersion for APIs with entries in SUPPORTED_API_VERSIONS.`);let n=ne(e);if(n.length===0)return{ok:!1,reason:"no_versions",supportedVersions:n};let r=Ie(e,t);if(r)return n.includes(r)?{ok:!0,version:r,source:"explicit",supportedVersions:n}:{ok:!1,reason:"unsupported_version",supportedVersions:n};let i=Lt(e);return i?{ok:!0,version:i,source:"default",supportedVersions:n}:{ok:!1,reason:"no_versions",supportedVersions:n}}o(ke,"resolveVersion");function Ie(e,t){if(!t||e!=="polaris-app-home")return t;let n=t.replace(/^v/,""),r=/^(\d+)$/.exec(n)?.[1];if(r){let c=Se[e]?.filter(l=>!l.releaseCandidate&&new RegExp("^v?"+r+"\\.\\d+$").test(l.name)).sort((l,p)=>{let y=Number(l.name.replace(/^v/,"").split(".")[1]),u=Number(p.name.replace(/^v/,"").split(".")[1]);return y-u}).at(-1)?.name;if(c)return c}let i=n.replace(/-rc$/,""),s=[t,n,"v"+i,i],a=ne(e);return s.find(c=>a.includes(c))??t}o(Ie,"normalizeRequestedVersion");function Dt(e,t){return e.map(n=>t&&n.includes("@shopify/ui-extensions")?`import '${n}/${t}';`:`import '${n}';`).join(`
`)}o(Dt,"generateMissingImports");function Vt(e,t,n){if(t.includes("@shopify/ui-extensions")&&!n)throw new Error("Invalid input: extensionTarget is required");let r=Dt(t,n);if(e&&(e.includes("const shopify =")||e.includes("globalThis.shopify")))return r;let i=t.find(a=>a.includes("@shopify/ui-extensions"))&&n?`interface ShopifyApiOverride extends Omit<import('@shopify/ui-extensions/${n}').Api, 'query'> { query: (...args: any[]) => Promise<{ data: any; errors?: any[] }>; } const shopify: ShopifyApiOverride = (globalThis as any).shopify;`:"";return`${r}
${i}`.trim()}o(Vt,"addShopifyImports");function Fe(e,t,n){if(e.includes("!DOCTYPE")||e.includes("!html")){let s=e.match(/<body>(.*?)<\/body>/s)?.[1];s&&(e=`<>${s}</>`)}return`
${Vt(e,t,n)}
${e}
`}o(Fe,"formatCode");import*as U from"path";import _ from"typescript";import{fileURLToPath as wt}from"url";var Ue=o((e,t,n=_.ModuleResolutionKind.NodeJs)=>({target:_.ScriptTarget.ESNext,module:_.ModuleKind.ESNext,jsx:_.JsxEmit.ReactJSX,jsxImportSource:e||"preact",strict:!0,strictNullChecks:!1,esModuleInterop:!0,skipLibCheck:!0,moduleResolution:n,allowSyntheticDefaultImports:!0,lib:["es2020","dom"],allowJs:!0,checkJs:!1,...t?{baseUrl:t,paths:{"@shopify/ui-extensions/src/surfaces/*":["node_modules/@shopify/ui-extensions/build/ts/surfaces/*"]}}:{}}),"getCompilerOptions");function kt(){let e=wt(import.meta.url);return U.resolve(e,"../..")}o(kt,"getPackageRoot");function Ft(e,t){let n=t.get(e);if(n)return _.ScriptSnapshot.fromString(n);try{let r=_.sys.readFile(e);return r?_.ScriptSnapshot.fromString(r):void 0}catch{return}}o(Ft,"getScriptSnapshot");function Ut(e,t,n,r){return{getScriptFileNames:o(()=>Array.from(e.virtualFiles.keys()),"getScriptFileNames"),getScriptVersion:o(i=>e.fileVersions.get(i)?.toString()||"0","getScriptVersion"),getScriptSnapshot:o(i=>Ft(i,e.virtualFiles),"getScriptSnapshot"),getCurrentDirectory:o(()=>t,"getCurrentDirectory"),getCompilationSettings:o(()=>Ue(n,t,r),"getCompilationSettings"),getDefaultLibFileName:o(i=>_.getDefaultLibFilePath(i),"getDefaultLibFileName"),fileExists:o(i=>e.virtualFiles.has(i)||_.sys.fileExists(i),"fileExists"),readFile:o(i=>e.virtualFiles.get(i)||_.sys.readFile(i),"readFile"),readDirectory:_.sys.readDirectory,getDirectories:_.sys.getDirectories,directoryExists:o(i=>{let s=i.endsWith(U.sep)?i:i+U.sep;for(let a of e.virtualFiles.keys())if(a.startsWith(s))return!0;return _.sys.directoryExists(i)},"directoryExists"),getNewLine:o(()=>`
`,"getNewLine")}}o(Ut,"createLanguageServiceHost");function Me(e,t){let n=new Map,r=new Map,i=kt(),s=t??(e==="hydrogen"?"react":"preact"),a=Ut({fileVersions:n,virtualFiles:r},i,s,e==="hydrogen"?_.ModuleResolutionKind.Bundler:_.ModuleResolutionKind.NodeJs),c=_.createLanguageService(a,_.createDocumentRegistry()),l=U.dirname(_.getDefaultLibFilePath(Ue(s,i))),p=["lib.es5.d.ts","lib.es2020.d.ts","lib.dom.d.ts"];for(let y of p)try{let u=U.join(l,y),I=_.sys.readFile(u);I&&(r.set(u,I),n.set(u,1))}catch{}return{languageService:c,servicesHost:a,fileVersions:n,virtualFiles:r}}o(Me,"createVirtualTSEnvironment");function Mt(e,t){let r=(e.get(t)||0)+1;return e.set(t,r),r}o(Mt,"incrementFileVersion");function Y(e,t,n){e.virtualFiles.set(t,n),Mt(e.fileVersions,t)}o(Y,"addFileToVirtualEnv");var ve=["a","abbr","address","area","article","aside","audio","b","base","bdi","bdo","blockquote","body","br","button","canvas","caption","cite","code","col","colgroup","data","datalist","dd","del","details","dfn","dialog","div","dl","dt","em","embed","fieldset","figcaption","figure","footer","form","h1","h2","h3","h4","h5","h6","head","header","hgroup","hr","html","i","iframe","img","input","ins","kbd","label","legend","li","link","main","map","mark","math","menu","meta","meter","nav","noscript","object","ol","optgroup","option","output","p","picture","pre","progress","q","rp","rt","ruby","s","samp","script","search","section","select","selectedcontent","slot","small","source","span","strong","style","sub","summary","sup","svg","table","tbody","td","template","textarea","tfoot","th","thead","time","title","tr","track","u","ul","var","video","wbr"];import h from"typescript";var $e=["a","altGlyph","altGlyphDef","altGlyphItem","animate","animateColor","animateMotion","animateTransform","animation","audio","canvas","circle","clipPath","color-profile","cursor","defs","desc","discard","ellipse","feBlend","feColorMatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feDropShadow","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","filter","font","font-face","font-face-format","font-face-name","font-face-src","font-face-uri","foreignObject","g","glyph","glyphRef","handler","hkern","iframe","image","line","linearGradient","listener","marker","mask","metadata","missing-glyph","mpath","path","pattern","polygon","polyline","prefetch","radialGradient","rect","script","set","solidColor","stop","style","svg","switch","symbol","tbreak","text","textArea","textPath","title","tref","tspan","unknown","use","video","view","vkern"];var He={NAMESPACE_USED_AS_VALUE:2708,TYPE_NOT_ASSIGNABLE:2322,CANNOT_FIND_NAME:2304},C={PROPERTY_NOT_EXIST:/Property '(\w+)' does not exist on type/,TYPE_NOT_ASSIGNABLE:/Type '(.+?)' is not assignable to type '(.+?)'/,PROPERTY:/[Pp]roperty '(\w+)'/,SHOPIFY_MODULE:/@shopify\//,MODULE_NOT_FOUND:/Invalid module name in augmentation/,INTRINSIC_ELEMENT:/does not exist on type 'JSX.IntrinsicElements'/,INVALID_JSX_ELEMENT:/cannot be used as a JSX component|is not a valid JSX element type/,USED_BEFORE_BEING_DEFINED:/is used before being assigned/,IMPLICITLY_HAS_AN_ANY_TYPE:/implicitly has an 'any' type./,PREACT_REACT_COMPAT:/type '(?:VNode|ReactPortal)|not assignable to type '(?:ReactNode|ReactPortal)'/,NEVER_TYPE_CASCADE:/does not exist on type 'never'|is not assignable to type 'never'/,PRIMITIVE_PROPERTY_ACCESS:/does not exist on type '(?:string|number|boolean|undefined|null|void)(?:\s*\|\s*(?:string|number|boolean|undefined|null|void))*'/,CSS_PROPERTIES_COMPAT:/CSSProperties/,OBJECT_IS_UNKNOWN:/Object is of type 'unknown'/},Gt=new Set(["class","style","title","id","slot","role","hidden","lang","dir","tabindex","inert","part","is","nonce","popover","contenteditable","draggable","spellcheck","translate","autocapitalize","autofocus","accesskey","enterkeyhint","inputmode"]),Ht=/^(number|boolean)(\s*\|\s*(number|boolean|undefined|null))*$/;function Bt(e){return Gt.has(e)||/^on[a-z]+$/.test(e)}o(Bt,"isHtmlGlobalAttribute");function jt(e){let t=e.match(C.TYPE_NOT_ASSIGNABLE);if(!t)return!1;let n=t[1],r=t[2];return n!=="string"?!1:Ht.test(r.trim())}o(jt,"isHtmlStringCoercion");function Qt(e){return ve.includes(e)}o(Qt,"isStandardHTMLElement");function qt(e){return $e.includes(e)}o(qt,"isStandardSVGElement");function Wt(e){let t=[];function n(r){if(h.isJsxOpeningElement(r)||h.isJsxSelfClosingElement(r)){let i=r.tagName.getText(e),s=r.getStart(e),a=r.getEnd();t.push({tagName:i,node:r,start:s,end:a})}h.forEachChild(r,n)}return o(n,"visit"),h.forEachChild(e,n),t}o(Wt,"extractJSXElements");function z(e){return{componentName:e,valid:!0,errors:[],skipped:!0}}o(z,"createSkippedValidation");function Ee(e,t){let n=t==="custom"?`Custom component '${e}' is not allowed. UI extensions must only use Shopify Polaris web components. If this is a wrapper component, make sure to import it.`:`${t} element '${e}' is not allowed. UI extensions must only use Shopify Polaris web components.`;return{componentName:e,valid:!1,errors:[{property:"element",message:n}]}}o(Ee,"createDisallowedElementValidation");function Jt(e){return e.replace(/\./g,"")}o(Jt,"sanitizeComponentName");function Yt(e,t,n,r,i){let s=Jt(e);return Qt(s)?i?Ee(e,"HTML"):z(e):qt(s)?i?Ee(e,"SVG"):z(e):t.has(s)?null:i?n.has(s)||r.has(s)?z(e):Ee(e,"custom"):z(e)}o(Yt,"handleNonShopifyComponent");function zt(e){return!e.startsWith("@shopify/")}o(zt,"isUserDefinedImport");function Kt(e,t){e.name&&t.add(e.name.text)}o(Kt,"collectDefaultImportName");function Xt(e,t){let{namedBindings:n}=e;if(n&&h.isNamedImports(n))for(let r of n.elements)t.add(r.name.text)}o(Xt,"collectNamedImportNames");function Zt(e,t){Kt(e,t),Xt(e,t)}o(Zt,"collectImportedNames");function en(e){let{moduleSpecifier:t}=e;return h.isStringLiteral(t)?t.text:null}o(en,"getModulePath");function tn(e){let t=new Set;function n(r){h.isImportDeclaration(r)&&nn(r,t),h.forEachChild(r,n)}return o(n,"visitNode"),h.forEachChild(e,n),t}o(tn,"extractUserImportedComponents");function nn(e,t){let n=en(e);if(!n||!zt(n))return;let{importClause:r}=e;r&&Zt(r,t)}o(nn,"processImportDeclaration");function xe(e){return/^[A-Z]/.test(e)}o(xe,"isPascalCase");function rn(e){let t=new Set;function n(r){if(h.isFunctionDeclaration(r)&&r.name){let i=r.name.text;xe(i)&&t.add(i)}if(h.isVariableStatement(r)){for(let i of r.declarationList.declarations)if(h.isIdentifier(i.name)&&i.initializer&&(h.isArrowFunction(i.initializer)||h.isFunctionExpression(i.initializer))){let s=i.name.text;xe(s)&&t.add(s)}}if(h.isClassDeclaration(r)&&r.name){let i=r.name.text;xe(i)&&t.add(i)}h.forEachChild(r,n)}return o(n,"visitNode"),h.forEachChild(e,n),t}o(rn,"extractLocallyDefinedComponents");function on(e){return e.replace(/-([a-z])/g,(t,n)=>n.toUpperCase())}o(on,"hyphenatedToCamelCase");function sn(e){if(!h.isJsxOpeningElement(e)&&!h.isJsxSelfClosingElement(e))return[];let t=[];for(let n of e.attributes.properties){if(!h.isJsxAttribute(n))continue;let r=h.isIdentifier(n.name)?n.name.text:n.name.getText();if(!r.includes("-")||r.startsWith("aria-")||r.startsWith("data-"))continue;let i=on(r);t.push({property:r,message:`Property '${r}' uses a hyphenated name which is not a valid Polaris prop. Use camelCase '${i}' instead.`})}return t}o(sn,"checkHyphenatedAttributes");function an(e,t){let n=e.attributes.properties.find(r=>h.isJsxAttribute(r)&&r.name.getText()===t);if(!(!n||!h.isJsxAttribute(n))){if(!n.initializer)return"";if(h.isStringLiteral(n.initializer))return n.initializer.text;if(h.isJsxExpression(n.initializer)&&n.initializer.expression&&h.isStringLiteral(n.initializer.expression))return n.initializer.expression.text}}o(an,"getStaticJsxAttribute");function cn(e){return ln(e)?.openingElement}o(cn,"getParentOpeningElement");function ln(e){let t=h.isJsxOpeningElement(e)?e.parent:void 0,n=e.parent;for(;n;){if(h.isJsxElement(n)){if(n===t){n=n.parent;continue}return n}n=n.parent}}o(ln,"getContainingJsxElement");function Ge(e){return{property:"slot",message:e}}o(Ge,"slotError");function pn(e,t){let n=new Map;for(let{node:r}of e){let i=an(r,"slot");if(i===void 0)continue;let s=cn(r);if(!s){n.set(r,[Ge("A slotted element must have a parent component.")]);continue}let a=s.tagName.getText(),c=t.get(a);if(c&&!c.has(i)){n.set(r,[Ge(`Slot '${i}' is not defined on '${a}'. Allowed slots: ${Array.from(c).map(l=>l===""?"(default)":l).join(", ")}.`)]);continue}}return n}o(pn,"collectSlotValidationErrors");function Be(e,t,n,r={}){let{enforceShopifyOnlyComponents:i=!1,language:s,shopifyWebComponentSlots:a}=r,c=s==="html",l=[],p=new Set,y=h.createSourceFile("temp.tsx",e,h.ScriptTarget.Latest,!0,h.ScriptKind.TSX),u=Wt(y),I=a?pn(u,a):new Map,A=i?tn(y):new Set,P=i?rn(y):new Set;for(let{tagName:x,node:R,start:$,end:b}of u){let O=Yt(x,n,A,P,i);if(O){l.push(O);continue}let{errors:V,handledDiagnostics:H}=fn($,b,t,c);H.forEach(T=>p.add(T));let F=sn(R);V.push(...F),V.push(...I.get(R)??[]),l.push({componentName:x,valid:V.length===0,errors:V})}let v=t.filter(x=>!p.has(x)).filter(x=>je(x,c)).filter(un).map(x=>({message:h.flattenDiagnosticMessageText(x.messageText,`
`),code:x.code,start:x.start,end:x.start!==void 0&&x.length!==void 0?x.start+x.length:void 0}));return{validations:l,genericErrors:v}}o(Be,"extractComponentValidations");function je(e,t=!1){if(e.start===void 0||e.length===void 0)return!1;let n=h.flattenDiagnosticMessageText(e.messageText,`
`);if(e.code===He.NAMESPACE_USED_AS_VALUE)return!1;if(t){let r=n.match(C.PROPERTY_NOT_EXIST);if(r&&Bt(r[1])||jt(n))return!1}return!(n.includes("Cannot find module")&&!n.match(C.SHOPIFY_MODULE)||n.match(C.MODULE_NOT_FOUND)||n.match(C.USED_BEFORE_BEING_DEFINED)||n.match(C.INVALID_JSX_ELEMENT)||n.match(C.IMPLICITLY_HAS_AN_ANY_TYPE))}o(je,"shouldIncludeDiagnostic");function un(e){let t=h.flattenDiagnosticMessageText(e.messageText,`
`);return!(t.match(C.PREACT_REACT_COMPAT)||t.match(C.NEVER_TYPE_CASCADE)||t.match(C.PRIMITIVE_PROPERTY_ACCESS)||t.match(C.CSS_PROPERTIES_COMPAT)||t.match(C.OBJECT_IS_UNKNOWN))}o(un,"shouldIncludeGenericDiagnostic");function dn(e,t,n,r=!1){if(!je(e,r)||e.code===He.CANNOT_FIND_NAME)return!1;let i=e.start,s=e.start+e.length;return i>=t&&s<=n}o(dn,"isRelevantDiagnostic");function fn(e,t,n,r=!1){let i=[],s=[],a=n.filter(c=>dn(c,e,t,r));for(let c of a){let l=h.flattenDiagnosticMessageText(c.messageText,`
`),p=mn(c,l);p&&(i.push(p),s.push(c))}return{errors:i,handledDiagnostics:s}}o(fn,"getComponentErrors");function mn(e,t){let n="",r,i,s=t.match(C.PROPERTY_NOT_EXIST);if(s)n=s[1];else{let a=t.match(C.TYPE_NOT_ASSIGNABLE),c=t.match(C.PROPERTY);a&&(i=a[1],r=a[2]),c&&(n=c[1])}return{property:n||"unknown",message:t,expected:r,actual:i}}o(mn,"parseDiagnostic");function Pe(e,t=[],n={}){let{polarisHint:r=!0,notChecked:i=[],notCheckedFooter:s}=n,a=[],c=[],l=[];for(let u of e)if(u.valid)u.skipped?l.push(u.componentName):c.push(u.componentName);else for(let I of u.errors)a.push(`${u.componentName} validation failed: Property '${I.property}': ${I.message}`);for(let u of t)a.push(u.message);let p,y;if(a.length===0?(y="success",c.length>0?p=`All components validated successfully by TypeScript. Found components: ${Array.from(new Set(c)).join(", ")}.`:p="No components found to validate by TypeScript."):(y="failed",p=`Validation errors:
${a.join(`
`)}`),i.length>0){y==="success"&&(y="inform");let u=s&&y==="inform"?`
${s}`:"";p+=`
${i.join(`
`)}${u}`}return l.length>0&&(p+=`
${r?"Try and use component from Shopify Polaris components. ":""}Non-Shopify components (not validated):
${l.map(I=>` - ${I}`).join(`
`)}`),{result:y,resultDetail:p,componentValidationErrors:e.filter(u=>!u.skipped&&!u.valid).flatMap(u=>u.errors.map(I=>({componentName:u.componentName,...I}))),genericErrors:t,unvalidatedComponents:Array.from(new Set(l)),validatedComponents:Array.from(new Set(c))}}o(Pe,"formatValidationResponse");import qe from"typescript";var gn=/^@shopify\/hydrogen(?:-react)?(?:\/|$)/,hn=/Cannot find module '([^']+)'/,yn=/@shopify\//,Sn=5,In="2026-10",vn="Older Hydrogen project? Pass its version to the validator.",En=[{module:"@shopify/hydrogen-react",message:"'@shopify/hydrogen-react' was removed in Hydrogen 2026-10. Import from '@shopify/hydrogen' or its subpaths, such as '@shopify/hydrogen/react', instead."},{module:"@shopify/hydrogen/oxygen",message:"'@shopify/hydrogen/oxygen' was removed in Hydrogen 2026-10. Look up the 2026-10 server setup in the Hydrogen docs."},{module:"@remix-run/react",message:"'@remix-run/react' is not used in Hydrogen 2026-10. Import route APIs such as useLoaderData from 'react-router' instead."},{module:"@remix-run/node",message:"'@remix-run/node' is not used in Hydrogen 2026-10. Import server APIs such as redirect from 'react-router' instead."},{module:"@remix-run/server-runtime",message:"'@remix-run/server-runtime' is not used in Hydrogen 2026-10. Import server APIs such as redirect from 'react-router' instead."},{module:"@remix-run/dev",message:"'@remix-run/dev' is not used in Hydrogen 2026-10. Use '@react-router/dev' instead."},{module:"@shopify/remix-oxygen",message:"'@shopify/remix-oxygen' was removed in Hydrogen 2026-10. Import route APIs from 'react-router' instead, and look up the 2026-10 server setup in the Hydrogen docs."},{module:"@shopify/hydrogen/react-router-preset",message:"'@shopify/hydrogen/react-router-preset' was removed in Hydrogen 2026-10. Look up the 2026-10 react-router.config.ts setup in the Hydrogen docs."}];function Qe(e,t){return e===t||e.startsWith(`${t}/`)}o(Qe,"matchesModule");function xn(e){let t=new Set;for(let n of e){let i=qe.flattenDiagnosticMessageText(n.messageText,`
`).match(hn)?.[1];i&&!yn.test(i)&&t.add(i)}return Array.from(t)}o(xn,"findUnresolvedNonShopifyModules");function Pn(e){let t=e.slice(0,Sn).map(r=>`'${r}'`),n=e.length-t.length;return n>0?`${t.join(", ")} and ${n} more`:t.join(", ")}o(Pn,"formatModuleList");var We="These parts weren't checked, so this result says nothing about them. Check them against the Hydrogen docs. Validating again won't change it.",_n="\u26A0\uFE0F PARTLY CHECKED: no errors found in the parts that were checked";function Je(e){return e==="hydrogen"?{informStatus:_n}:{}}o(Je,"getFormatValidationOptions");function Ye({code:e,diagnostics:t,version:n}){let r=qe.preProcessFile(e,!0,!0).importedFiles.map(l=>l.fileName),s=!!n&&/^\d{4}-\d{2}$/.test(n)&&n>=In?En.filter(({module:l})=>r.some(p=>Qe(p,l))):[],a=[],c=xn(t).filter(l=>!s.some(({module:p})=>Qe(l,p)));if(c.length>0){let l=c.length===1?"it":"them";a.push(`Not checked: the validator can't load ${Pn(c)}, so anything imported from ${l} is typed 'any' and was not checked.`)}return r.some(l=>gn.test(l))||a.push("Not checked: this code doesn't import from '@shopify/hydrogen', so there were no Hydrogen types to check it against."),{legacyImportErrors:s.map(({message:l})=>({message:`${l} ${vn}`})),notChecked:a}}o(Ye,"checkHydrogenCode");import{existsSync as N,readFileSync as j,readdirSync as wn}from"fs";import*as g from"path";import{fileURLToPath as rt}from"url";import{gunzipSync as tt}from"zlib";import{brotliCompressSync as so,brotliDecompressSync as bn,constants as ao}from"zlib";var _e=4;function ze(e){let t=bn(e);if(t.length<_e)throw new Error(`Corrupt asset archive: ${t.length}-byte stream is shorter than the header-length field`);let n=t.readUInt32LE(0),r=_e+n;if(r>t.length)throw new Error(`Corrupt asset archive: header (${n} bytes) extends past the ${t.length}-byte stream`);let i=JSON.parse(t.subarray(_e,r).toString("utf-8")),s=t.subarray(r),a=new Map;for(let[c,l,p]of i){if(!Number.isInteger(l)||!Number.isInteger(p)||l<0||p<0||l+p>s.length)throw new Error(`Corrupt asset archive: member '${c}' (offset ${l}, length ${p}) is out of bounds for the ${s.length}-byte body`);a.set(c,s.subarray(l,l+p))}return a}o(ze,"unpackAssetArchive");function Ke(e,t){if(!t)return[];switch(t){case"@shopify/polaris-types":case"@shopify/ui-extensions":return Cn(e);case"@shopify/ui-extensions-react":return Nn(e);case"@shopify/app-bridge-types":return On(e);case"@shopify/analytics-ui-types":return Tn(e);case"@shopify/hydrogen":return Rn(e);case"@shopify/app-bridge-react":return An(e);default:return[]}}o(Ke,"extractShopifyComponents");function An(e){let t=[],n=/(?:export\s+)?declare\s+const\s+(\w+)\s*:\s*React\.(?:ComponentType|ForwardRefExoticComponent)\b/g,r;for(;(r=n.exec(e))!==null;)t.push(r[1]);let i=/export\s+default\s+function\s+([A-Z]\w*)\s*\(/g;for(;(r=i.exec(e))!==null;)t.push(r[1]);let s=/default\s+as\s+([A-Z]\w*)/g;for(;(r=s.exec(e))!==null;)t.push(r[1]);return[...new Set(t)]}o(An,"extractAppBridgeReactComponents");function Cn(e){let t=[],n=/declare\s+const\s+tagName\$?\w*\s*=\s*['"]([^'"]+)['"]/g,r=/\[['"]([a-z]+-[a-z-]+)['"]\]\s*:/g,i;for(;(i=n.exec(e))!==null||(i=r.exec(e))!==null;)t.push(i[1]);return[...new Set(t)]}o(Cn,"extractWebComponentTagNames");function Xe(e,t){let n=[],r=e.match(new RegExp(`interface\\s+${t}\\s*\\{([^}]+)\\}`));if(r){let i=/['"]([a-z]+-[a-z-]+)['"]\s*:/g,s;for(;(s=i.exec(r[1]))!==null;)n.push(s[1])}return n}o(Xe,"extractQuotedTagKeysFromInterface");function On(e){return Xe(e,"AppBridgeElements")}o(On,"extractAppBridgeElements");function Tn(e){return Xe(e,"AnalyticsUiIntrinsicElements")}o(Tn,"extractAnalyticsUiElements");function Nn(e){let t=new Set,n=/export\s+declare\s+const\s+([A-Z]\w*)\s*:\s*"\1"\s*&/g,r;for(;(r=n.exec(e))!==null;)t.add(r[1]);let i=/export\s+(?!type\b)\{([^}]+)\}/g;for(;(r=i.exec(e))!==null;)for(let s of r[1].split(",")){let a=s.trim();if(!a||/^type\s/.test(a))continue;let c=a.split(/\s+as\s+/),l=c[c.length-1].trim();/^[A-Z]\w*$/.test(l)&&t.add(l)}return[...t]}o(Nn,"extractReactBindingComponentNames");function Rn(e){let t=[],n,r=/declare\s+function\s+(\w+)\s*(?:<[^>]*>)?\s*\([^)]*\)\s*:\s*(?:react_jsx_runtime\.)?JSX\.Element/g;for(;(n=r.exec(e))!==null;)t.push(n[1]);let i=/declare\s+function\s+(\w+)\s*(?:<[^>]*>)?\s*\([^)]*\)\s*:\s*ReturnType<FC>/g;for(;(n=i.exec(e))!==null;)t.push(n[1]);let s=/declare\s+function\s+(\w+)\s*(?:<[^>]*>)?\s*\([^)]*\)\s*:\s*react\.FunctionComponentElement/g;for(;(n=s.exec(e))!==null;)t.push(n[1]);let a=/declare\s+function\s+(\w+)\s*(?:<[^>]*>)?\s*\([^)]*\)\s*:\s*(?:React\.)?ReactElement(?:<[^>]*>)?/g;for(;(n=a.exec(e))!==null;)t.push(n[1]);let c=/declare\s+const\s+(\w+)\s*:\s*react\.ForwardRefExoticComponent/g;for(;(n=c.exec(e))!==null;)t.push(n[1]);let l=/declare\s+const\s+(\w+)\s*:\s*react\.Provider/g;for(;(n=l.exec(e))!==null;)t.push(n[1]);return[...new Set(t)]}o(Rn,"extractHydrogenComponents");var Ln="@shopify/analytics-ui-types",Ze=/\ndeclare module ['"]preact['"] \{[\s\S]*?\n\}\n/,Dn=`
import type * as __preact from 'preact';
/**
* Mirrors @shopify/polaris-types' PreactBaseElementPropsWithChildren plus
* the global \`id\` attribute. Deliberately not preact's HTMLAttributes: its
* surface is wide enough that excess-property checks stop catching typos.
*/
interface AnalyticsUiPreactBaseProps<TElement extends HTMLElement> {
key?: __preact.Key;
ref?: __preact.Ref<TElement>;
slot?: Lowercase<string>;
id?: string;
children?: __preact.ComponentChildren;
}
type ShopifyQLMetricCardPreactProps = Partial<ShopifyQLMetricCardProps> &
AnalyticsUiPreactBaseProps<ShopifyQLMetricCardElement> & {
onReportLinkClick?:
| ((event: CallbackEvent<'s-shopifyql-metric-card'>) => void)
| null;
onreportlinkclick?: CallbackEventListener<'s-shopifyql-metric-card'>;
};
type MetricsBarPreactProps = Partial<MetricsBarProps> &
AnalyticsUiPreactBaseProps<MetricsBarElement>;
type MetricsBarDatePickerPreactProps = Partial<
Omit<MetricsBarDatePickerProps, 'value'>
> &
AnalyticsUiPreactBaseProps<MetricsBarDatePickerElement> & {
value?: MetricsBarDatePickerSetValue;
onChange?:
| ((event: CallbackEvent<'s-metrics-bar-date-picker'>) => void)
| null;
onchange?: CallbackEventListener<'s-metrics-bar-date-picker'>;
};
declare module 'preact' {
namespace createElement.JSX {
interface IntrinsicElements {
's-shopifyql-metric-card': ShopifyQLMetricCardPreactProps;
's-metrics-bar': MetricsBarPreactProps;
's-metrics-bar-date-picker': MetricsBarDatePickerPreactProps;
}
}
}
`;function Vn(e){return Ze.test(e)?e.replace(Ze,Dn):e}o(Vn,"patchAnalyticsUiTypesForPreact");function et(e,t,n){return e===Ln&&t.endsWith(".d.ts")?Vn(n):n}o(et,"patchAssetDeclaration");var re,oe,ie;function kn(e){let t=g.resolve(e,"..","assets","types");if(N(ot(t))||N(g.join(t,"index.json")))return t;if(e.includes("dev-mcp")&&e.includes("dist")&&!e.includes("shopify-dev-tools"))return g.join(e,"data","types");if(e.includes("/dist")||e.includes("\\dist")){let n=e.lastIndexOf(g.sep+"dist");if(n!==-1){let r=e.substring(0,n+5);return g.join(r,"data","types")}return g.join(e,"data","types")}return g.resolve(e,"../data/types")}o(kn,"resolveTypesDataDirectory");function X(){if(oe)return oe;let e=g.dirname(rt(import.meta.url));return oe=kn(e),oe}o(X,"getTypesDataDirectory");function Fn(){if(re)return re;let e=g.join(X(),"index.json"),t=M(e);if(t===void 0)throw new Error(`Types index not found at ${e}`);return re=JSON.parse(t),re}o(Fn,"readIndexJson");var K;function ot(e){return`${e}.archive.br`}o(ot,"typesArchivePathFor");function se(){if(K!==void 0)return K;let e=ot(X());if(!N(e))return K=null,null;let t=ze(j(e)),n=new Set([""]);for(let r of t.keys()){let i=r.split("/");for(let s=1;s<i.length;s++)n.add(i.slice(0,s).join("/"))}return K={files:t,dirs:n},K}o(se,"getArchiveStore");function ae(e){let t=g.relative(X(),e).split(g.sep).join("/");if(!(t===".."||t.startsWith("../")||g.isAbsolute(t)))return t}o(ae,"archiveRel");function it(e){return e.endsWith(".gz")?e.slice(0,-3):e}o(it,"logicalRel");function M(e){let t=se();if(t){let n=ae(e);return n===void 0?void 0:t.files.get(it(n))?.toString("utf-8")}return Gn(e)}o(M,"assetFileContent");function nt(e){let t=se();if(t){let n=ae(e);return n!==void 0&&t.files.has(it(n))}return e.endsWith(".gz")?N(e)||N(e.slice(0,-3)):N(e)||N(`${e}.gz`)}o(nt,"assetFileExists");function Ae(e){let t=se();if(t){let n=ae(e);return n!==void 0&&t.dirs.has(n)}return N(e)}o(Ae,"assetDirExists");function Ce(e){let t=se();if(t){let r=ae(e);if(r===void 0||!t.dirs.has(r))return[];let i=r===""?"":`${r}/`,s=new Map;for(let a of t.files.keys()){if(!a.startsWith(i))continue;let c=a.slice(i.length),l=c.indexOf("/");if(l===-1)s.set(c,{name:c,isDirectory:!1,isFile:!0});else{let p=c.slice(0,l);s.has(p)||s.set(p,{name:p,isDirectory:!0,isFile:!1})}}return[...s.values()].sort((a,c)=>a.name.localeCompare(c.name))}let n;try{n=wn(e,{withFileTypes:!0})}catch{return[]}return n.map(r=>({name:r.name,isDirectory:r.isDirectory(),isFile:r.isFile()}))}o(Ce,"assetDirEntries");function Un(e,t){if(e)try{let n=JSON.parse(e);for(let r of n.modules??[])for(let i of r.declarations??[])!i.tagName||!i.slots||t.set(i.tagName,new Set(i.slots.map(s=>s.name).filter(s=>typeof s=="string")))}catch{}}o(Un,"addCustomElementSlots");function st(){if(ie)return ie;let e=X(),t=g.join(e,"..","supported-versions-schema.json");return ie=JSON.parse(j(t,"utf-8")),ie}o(st,"readSupportedVersions");function Mn(e){let t=st()[e];if(t)return t.find(n=>n.latestVersion)?.name}o(Mn,"resolveLatestVersion");function at(e,t){return e==="hydrogen"||/^\s*(?:import|export)\b[^'"]*['"]@shopify\/ui-extensions-react(?:\/[^'"]*)?['"]/m.test(t)?"react":"preact"}o(at,"resolveJsxRuntime");function $n(e){return(st()[e]??[]).map(t=>t.name)}o($n,"supportedVersionNames");function Gn(e){if(e.endsWith(".gz")){if(N(e))return tt(j(e)).toString("utf-8");let n=e.slice(0,-3);return N(n)?j(n,"utf-8"):void 0}if(N(e))return j(e,"utf-8");let t=e+".gz";if(N(t))return tt(j(t)).toString("utf-8")}o(Gn,"readAssetFile");function Hn(e){return e.endsWith(".d.ts")||e.endsWith(".d.mts")||e.endsWith(".d.cts")}o(Hn,"isTypeDeclarationFile");function Bn(e,t){let n=[];if(!Ae(e))return n;function r(i,s){for(let a of Ce(i)){if(a.name.startsWith(".")||a.name==="node_modules")continue;let c=g.join(i,a.name),l=a.name.endsWith(".gz")?a.name.slice(0,-3):a.name,p=s?`${s}/${l}`:l;if(a.isDirectory)r(c,p);else if(a.isFile){if(!(Hn(l)||l.endsWith(".ts")&&!l.endsWith(".test.ts")&&!l.endsWith(".spec.ts"))||t&&!t(p))continue;n.push({assetPath:c,relPath:p})}}}return o(r,"walk"),r(e,""),n}o(Bn,"walkAssetDts");function jn(e,t,n,r){for(let i of Ce(e)){if(!i.isDirectory||i.name.startsWith(".")||i.name==="node_modules")continue;let s=g.join(e,i.name);if(nt(g.join(s,"package.json")))continue;let a;for(let p of["src/index.d.ts","src/index.d.mts","src/index.d.cts","index.d.ts","index.d.mts","index.d.cts"])if(nt(g.join(s,p))){a=`./${p}`;break}if(!a)continue;let c=JSON.stringify({name:`${t}/${i.name}`,types:a}),l=`${i.name}/package.json`;G(n,r,t,l,c)}}o(jn,"synthesizeNestedPackageJsons");function Qn(e,t,n){return g.join(e,"node_modules",t,n)}o(Qn,"virtualPathFor");function G(e,t,n,r,i,s){let a=Qn(t,n,r),c=et(n,r,i);if(Y(e,a,c),s)for(let l of Ke(c,n))s.add(l)}o(G,"addAssetToVirtualEnv");var qn={"customer-account":["checkout"]};function be(e){let t=[e,...qn[e]??[]],n=new Set(t.map(s=>`build/ts/surfaces/${s}.d.ts`)),r=t.map(s=>`build/ts/surfaces/${s}/`),i="build/ts/";return s=>!!(n.has(s)||r.some(a=>s.startsWith(a))||s.startsWith(i)&&s.endsWith(".d.ts")&&!s.slice(i.length).includes("/"))}o(be,"surfaceMatcher");function Q(e,t,n,r,i,s){for(let{assetPath:a,relPath:c}of Bn(e,s)){let l=M(a);l&&G(n,r,t,c,l,i)}}o(Q,"loadDtsTree");function Wn(e){let t=[],n=/import\s+['"]\.\.\/components\/(\w+)\.d\.ts['"]/g,r;for(;(r=n.exec(e))!==null;)t.push(r[1]);return t}o(Wn,"extractComponentImports");function Jn(e){let t=new Set;for(let n of Ce(e)){if(!n.isFile)continue;let r=n.name.endsWith(".gz")?n.name.slice(0,-3):n.name;r.endsWith(".d.ts")&&t.add(r.slice(0,-5))}return[...t].sort()}o(Jn,"listAvailableTargets");function Yn(e,t,n,r,i,s,a){let c=`build/ts/surfaces/${i}`,l=g.join(e,c,"targets"),p=`${c}/targets/${s}.d.ts`,y=M(g.join(e,p));if(!y)return Ae(l)?{hasTargetSubpath:!1,invalidTarget:{target:s,surface:i,supported:Jn(l)}}:(Q(e,t,n,r,a,be(i)),{hasTargetSubpath:!1});let u=`${c}.d.ts`,I=M(g.join(e,u));I&&G(n,r,t,u,I,a),G(n,r,t,p,y,a);let A=`${c}/components`;for(let P of Wn(y)){let E=`${A}/${P}.d.ts`,v=M(g.join(e,E));v&&G(n,r,t,E,v,a)}for(let P of["shared.d.ts","components-shared.d.ts"]){let E=`${A}/${P}`,v=M(g.join(e,E));v&&G(n,r,t,E,v,a)}for(let P of["api","types","event"]){let E=`${c}/${P}`;Q(e,t,n,r,a,v=>v===E||v.startsWith(`${E}/`))}for(let P of["extension-targets.d.ts","globals.d.ts","api.d.ts","extension.d.ts"]){let E=`${c}/${P}`,v=M(g.join(e,E));v&&G(n,r,t,E,v,a)}return Q(e,t,n,r,a,P=>{if(!P.startsWith("build/ts/"))return!1;let E=P.slice(9);return E.endsWith(".d.ts")&&!E.includes("/")}),{hasTargetSubpath:!0}}o(Yn,"loadTargetSpecificComponents");async function ct(e,t,n,r){let i=[],s=[],a=new Set,c=new Map,l=!1,p,y=J[e],u=y?.versioned===!0,I=y?.extensionSurfaceName,A=X(),P=Fn(),E=P[e],v;if(u){let S=Ie(e,t);if(S){let L=$n(e);if(L.length>0&&!L.includes(S))return{missingPackages:i,searchedPaths:s,shopifyWebComponents:a,shopifyWebComponentSlots:c,applicablePackageNames:[],hasTargetSubpath:l,unsupportedVersion:{requested:t,supported:L}};v=S}v??=Mn(e)}else v="_";let x=u?v:void 0,R=(y?.publicPackages??[]).filter(S=>ye(S,x)),$=R.map(te),b=new Set((y?.publicPackages??[]).filter(S=>!ye(S,x)).map(te)),O=E?._??[],V=v&&v!=="_"?E?.[v]??[]:[],F=[...O,...V].filter((S,L,D)=>D.findIndex(W=>W.package===S.package&&W.version===S.version)===L).filter(S=>!b.has(S.package)),T=new Set(F.map(({package:S})=>S));for(let S of R){let L=te(S);T.has(L)||(i.push(L),s.push(g.join(A,L,v??"<unknown-version>")))}let q=P._always_loaded??[],ge=[...F,...q],w=n.servicesHost.getCurrentDirectory();for(let{package:S,version:L}of ge){let D=g.join(A,S,L);if(!Ae(D)){i.push(S),s.push(D);continue}let W=M(g.join(D,"package.json"));if(W&&G(n,w,S,"package.json",W),S==="@shopify/polaris-types"&&Un(M(g.join(D,"dist/custom-elements.json")),c),jn(D,S,n,w),S==="@shopify/ui-extensions"&&I)if(r){let he=Yn(D,S,n,w,I,r,a);l=he.hasTargetSubpath,he.invalidTarget&&(p=he.invalidTarget)}else Q(D,S,n,w,a,be(I));else S==="@shopify/ui-extensions-react"&&I?Q(D,S,n,w,a,be(I)):Q(D,S,n,w,a);S==="@shopify/app-bridge-types"&&zn(n)}return{missingPackages:i,searchedPaths:s,shopifyWebComponents:a,shopifyWebComponentSlots:c,applicablePackageNames:$,hasTargetSubpath:l,invalidTarget:p,resolvedVersion:u?v:void 0}}o(ct,"loadTypesIntoTSEnv");function zn(e){let t=rt(import.meta.url),n=g.resolve(t,"../.."),r=g.join(n,"__shims__","app-bridge-preact-jsx.d.ts"),i=['import type { AppBridgeElements } from "@shopify/app-bridge-types/dist/shopify";','declare module "preact" {'," namespace createElement.JSX {"," interface IntrinsicElements extends AppBridgeElements {}"," }","}",""].join(`
`);Y(e,r,i)}o(zn,"addAppBridgePreactJSXShim");var Kn=["polaris-admin-extensions","polaris-checkout-extensions","polaris-customer-account-extensions","pos-ui"],Xn=["polaris-app-home"];function Zn(e){return Xn.includes(e)}o(Zn,"supportsRawHtmlComponentValidation");async function lt(e){try{let{code:t,apiName:n,version:r,extensionTarget:i,language:s}=e;if(!n)return{result:"failed",resultDetail:"Validation failed: Invalid input: apiName is required"};if(!t)return{result:"failed",resultDetail:"Validation failed: Invalid input: code is required"};let a=J[n];if(!a)return{result:"failed",resultDetail:`Validation failed: Unknown API: ${n}`};if(s==="html"&&!Zn(n))return{result:"failed",resultDetail:"Validation failed: HTML validation mode is only supported for API 'polaris-app-home'. Other UI framework APIs must use JSX/TSX code blocks."};if(a.extensionSurfaceName&&!i)return{result:"failed",resultDetail:`Extension target is required for API: ${n}. Look up the list of available extension targets in the API documentation.`};if(!a.publicPackages||a.publicPackages.length===0)return{result:"failed",resultDetail:`Validation failed: No packages configured for API: ${n}`};let c=Me(n,at(n,t)),{missingPackages:l,searchedPaths:p,shopifyWebComponents:y,shopifyWebComponentSlots:u,unsupportedVersion:I,invalidTarget:A,applicablePackageNames:P,hasTargetSubpath:E,resolvedVersion:v}=await ct(n,r,c,i),x=P;if(I)return{result:"failed",resultDetail:`Validation failed: Version '${I.requested}' is not supported for API '${n}'. Supported versions: ${I.supported.join(", ")}`};if(A){let T=A.supported.length?`Supported extension targets for surface '${A.surface}'${r?` at version '${r}'`:""}: ${A.supported.join(", ")}`:`No extension targets are bundled for surface '${A.surface}'${r?` at version '${r}'`:""}.`;return{result:"failed",resultDetail:`Validation failed: Unknown extension target '${A.target}' for API '${n}'. ${T}`}}if(l.length>0){let T=l.map(w=>` - ${w}`).join(`
`),q=`npm install -D ${l.join(" ")}`,ge=p.map(w=>` - ${w}`).join(`
`);return{result:"failed",resultDetail:`Missing required dev dependencies:
${T}
Searched paths:
${ge}
Please install them using:
${q}`}}let R=`validation-${Date.now()}.tsx`,$=E?x:x.filter(T=>!T.includes("@shopify/ui-extensions")),b=Fe(t,$,E?i:void 0);Y(c,R,b);let O=c.languageService.getSemanticDiagnostics(R),V=Kn.includes(n),{validations:H,genericErrors:F}=Be(b,O,y,{enforceShopifyOnlyComponents:V,language:s,shopifyWebComponentSlots:u});if(n==="hydrogen"){let{legacyImportErrors:T,notChecked:q}=Ye({code:t,diagnostics:O,version:v});return Pe(H,[...F,...T],{polarisHint:!1,notChecked:q,notCheckedFooter:We})}return Pe(H,F)}catch(t){return{result:"failed",resultDetail:`Validation failed: ${t instanceof Error?t.message:String(t)}`}}}o(lt,"validateComponentCodeBlock");import{randomUUID as er}from"crypto";function Oe(e){return e.some(t=>t.result==="failed")}o(Oe,"hasFailedValidation");function ce(e){return e.map(t=>({artifactId:t.artifactId||`artifact-${er()}`,revision:t.revision??1}))}o(ce,"extractArtifactsFromItems");function le(e,t){return e.map((n,r)=>{let i=t[r];return i?{...n,artifactId:i.artifactId,artifactRevision:i.revision}:n})}o(le,"attachArtifactIds");function pe(e,t="Items",{informStatus:n="\u26A0\uFE0F VALID (with warnings)"}={}){let r=Oe(e),i=e.some(c=>c.result==="inform"),s;r?s="\u274C INVALID":i?s=n:s="\u2705 VALID";let a=`## Validation Summary
`;return a+=`**Overall Status:** ${s}
`,a+=`**Total ${t}:** ${e.length}
`,a+=`## Detailed Results
`,e.forEach((c,l)=>{let p;c.result==="success"?p="\u2705":c.result==="inform"?p="\u26A0\uFE0F":p="\u274C",a+=`### ${t.slice(0,-1)} ${l+1}
`,c.artifactId&&(a+=`**Artifact ID:** ${c.artifactId}`,c.artifactRevision&&(a+=`
**Revision:** ${c.artifactRevision}`),a+=`
*Use same ID & increment revision when retrying on an improvement of this artifact*
`),a+=`**Status:** ${p} ${c.result.toUpperCase()}
`,a+=`**Details:** ${c.resultDetail}
`}),a}o(pe,"formatValidationResult");function pt(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>{let{description:r,valueName:i,choices:s,...a}=n;return[t,a]}))}o(pt,"toParseArgsOptions");var ut={model:{type:"string",valueName:"name",description:"Agent model name"},"client-name":{type:"string",valueName:"name",description:"Agent client name"},"client-version":{type:"string",valueName:"version",description:"Agent client version"}},dt={"user-prompt-base64":{type:"string",valueName:"base64",description:"Base64-encoded triggering prompt"},"session-id":{type:"string",valueName:"id",description:"Agent session identifier"},"tool-use-id":{type:"string",valueName:"id",description:"Agent tool-use identifier"}},ft={"artifact-id":{type:"string",valueName:"id",description:"Stable artifact identifier"},revision:{type:"string",valueName:"number",description:"Positive artifact revision"},...ut,...dt,json:{type:"boolean",description:"Emit machine-readable JSON"}},mt={help:{type:"boolean",short:"h",description:"Show this help"}};function gt(e,t){let n=new Set([...Object.keys(ut),...Object.keys(dt),"artifact-id","revision"]),r=Object.entries(t).filter(([s])=>!0).map(([s,a])=>{let c=a.type==="string"?a.valueName||a.choices?.join("|")||"value":void 0,l=`--${s}${c?` <${c}>`:""}`;return[a.short?`-${a.short}, ${l}`:l,a.description]}),i=Math.max(...r.map(([s])=>s.length));return["Usage:",...e.map(s=>` ${s}`),"","Options:",...r.map(([s,a])=>` ${s.padEnd(i)} ${a}`)].join(`
`)}o(gt,"formatCliHelp");function nr(e){return typeof e=="string"&&e.length>0?e:void 0}o(nr,"nonEmpty");var rr=["CLAUDE_SESSION_ID","CLAUDE_CODE_SESSION_ID","CODEX_SESSION_ID","CODEX_THREAD_ID","CURSOR_SESSION_ID","COPILOT_SESSION_ID"],or=["CODEX_TOOL_CALL_ID"];function ht(e){for(let t of e){let n=nr(process.env[t]);if(n)return n}}o(ht,"firstNonEmptyEnv");function yt(){return ht(rr)}o(yt,"readHostSessionId");function St(){return ht(or)}o(St,"readHostToolUseId");import{isIP as ir}from"node:net";var sr="https://shopify.dev/",ar="https://shopify-dev.shop.dev/";function It(e){return`https://shopify-dev-staging${e}.shopifycloud.com/`}o(It,"stagingHost");var cr="SHOPIFY_DEV_SUPPORT_CORE_MCP_DOMAIN",ue="SHOPIFY_DEV_LOCAL_SERVER_URL";function lr(e){let t;try{t=new URL(e)}catch{throw new Error(`${ue} must identify a local Shopify.dev origin`)}let n=t.hostname==="localhost"||t.hostname==="[::1]"||ir(t.hostname)===4&&t.hostname.startsWith("127."),r=/^shopify-dev-[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.shop\.dev$/u.test(t.hostname);if(!n&&!r||n&&!t.port||r&&t.protocol!=="https:"||n&&t.protocol!=="http:"&&t.protocol!=="https:"||t.username||t.password||t.pathname!==""&&t.pathname!=="/"||t.search||t.hash)throw new Error(`${ue} must identify a local Shopify.dev origin`);return`${t.origin}/`}o(lr,"normalizeLocalShopifyDevUrl");function Te(e){let t=e?.env??process.env,n=t.SHOPIFY_DEV_STAGING_SERVER_NUMBER?.trim(),r=t[ue]?.trim();if(r&&e?.allowLocalServer){if(n||t.DEV&&t.DEV!=="false"||t[cr]?.trim())throw new Error(`${ue} cannot be combined with staging, DEV, or Support Core routing overrides`);return{url:lr(r),headers:{}}}if(n){if(!/^\d+$/.test(n))throw new Error(`SHOPIFY_DEV_STAGING_SERVER_NUMBER must be a positive integer; got: "${n}"`);let s=Number(n);if(!Number.isSafeInteger(s)||s<=0)throw new Error(`SHOPIFY_DEV_STAGING_SERVER_NUMBER must be a positive integer; got: "${n}"`);let a=t.MINERVA_TOKEN;if(!a){let c=It(s).replace(/\/$/,"");throw new Error(`SHOPIFY_DEV_STAGING_SERVER_NUMBER=${s} is set but no Minerva token is available. Staging servers are behind Minerva. Get a token from fleet-installed Mint, then retry:
MINERVA_TOKEN=$(mint token ${c}) && export MINERVA_TOKEN`)}return{url:It(s),headers:{Cookie:`MINERVA_TOKEN=${a}`}}}let i=t.SHOPIFY_DEV_INSTRUMENTATION_URL?.trim();return i&&e?.uri?.startsWith("/mcp/usage")?{url:i,headers:{}}:t.DEV&&t.DEV!=="false"?{url:ar,headers:{}}:{url:sr,headers:{}}}o(Te,"resolveShopifyDevBaseUrl");async function vt(e,t){let n,r={};if(e.startsWith("http://")||e.startsWith("https://"))n=new URL(e);else{let s=Te({uri:e,allowLocalServer:t?.allowLocalServer});n=new URL(e,s.url),r=s.headers}t?.parameters&&Object.entries(t.parameters).forEach(([s,a])=>{n.searchParams.append(s,a)});let i=await fetch(n.toString(),{method:t?.method||"GET",...t?.redirect&&{redirect:t.redirect},headers:{Accept:"application/json","Cache-Control":"no-cache","X-Shopify-Surface":"mcp","X-Shopify-MCP-Version":t?.instrumentation?.packageVersion||"","X-Shopify-Timestamp":t?.instrumentation?.timestamp||"",...r,...t?.headers},...t?.body&&{body:t.body}});if(!i.ok){let s;try{s=await i.text()}catch{}throw new Error(s?`HTTP ${i.status}: ${s}`:`HTTP error! status: ${i.status}`)}return await i.text()}o(vt,"shopifyDevFetch");import{readFileSync as pr,statSync as ur}from"node:fs";import{homedir as dr}from"node:os";import{join as Z}from"node:path";var de="shopify-ai-toolkit",fe="opt-out",fr="SHOPIFY_AI_TOOLKIT_OPT_OUT_FILE",mr=new Set(["false","0","no","off"]);function Et(e){return{env:e?.env??process.env,platform:e?.platform??process.platform,homeDir:e&&"homeDir"in e?e.homeDir:gr(e?.env??process.env)}}o(Et,"resolveContext");function gr(e){let t=e.HOME?.trim()||e.USERPROFILE?.trim();if(t)return t;try{return dr()||void 0}catch{return}}o(gr,"resolveHomeDir");function hr(e){let{env:t,platform:n,homeDir:r}=Et(e),i=[],s=t[fr]?.trim();s&&i.push(s);let a=t.XDG_CONFIG_HOME?.trim();if(a&&i.push(Z(a,de,fe)),r&&(i.push(Z(r,".config",de,fe)),n==="darwin"&&i.push(Z(r,"Library","Application Support",de,fe))),n==="win32"){let c=t.APPDATA?.trim()||(r?Z(r,"AppData","Roaming"):void 0);c&&i.push(Z(c,de,fe))}return[...new Set(i.filter(c=>!!c))]}o(hr,"telemetryOptOutFileCandidates");function yr(e){if(e.OPT_OUT_INSTRUMENTATION?.trim().toLowerCase()==="true")return!0;let t=e.DO_NOT_TRACK?.trim().toLowerCase();return t==="1"||t==="true"}o(yr,"envSaysOptOut");function Sr(e){try{if(!ur(e).isFile())return!1}catch{return!1}try{let t=pr(e,"utf8").trim().toLowerCase();return!mr.has(t)}catch{return!0}}o(Sr,"fileSaysOptOut");function xt(e){try{let t=Et(e);return yr(t.env)?!0:hr(t).some(Sr)}catch{return!1}}o(xt,"isTelemetryOptedOut");function Pt(e){return{...e?.api&&{api:e.api},...e?.api_version&&{api_version:e.api_version},...e?.resolve_api_version&&{resolve_api_version:e.resolve_api_version}}}o(Pt,"nonEmptyUsageMetadata");var Ir={ucp:"ucp"},vr="functions_",Er="shopify-";function _t(e){if(e)return e.startsWith(vr)?"shopify-functions":Ir[e]??`${Er}${e}`}o(_t,"legacySkillName");function xr(){return xt()}o(xr,"isInstrumentationDisabled");function bt(e){if(!(typeof e!="string"||e.length===0))try{let t=Buffer.from(e,"base64").toString("utf8");return t.length>0?t:void 0}catch{return}}o(bt,"decodeUserPrompt");async function Ne(e,t,n,r){if(!!0||xr())return;let{model:i,clientName:s,clientVersion:a,user_prompt:c,sessionId:l,toolUseId:p,topic:y,...u}=n??{},I=typeof y=="string"&&y.length>0?y:void 0,P=o((...b)=>{for(let O of b)if(typeof O=="string"&&O.length>0)return O},"firstApi")(r?.api,(n??{}).api),E=_t(I??P??"")??"shopify",v=o(b=>typeof b=="string"&&b.length>0?b:void 0,"nonEmptyString"),x=yt()??v(l),R=St()??v(p),$=typeof c=="string"&&c.length>0?c.slice(0,2e3):void 0;try{let b={"Content-Type":"application/json","X-Shopify-Surface":"skills"};s&&(b["X-Shopify-Client-Name"]=String(s)),a&&(b["X-Shopify-Client-Version"]=String(a)),i&&(b["X-Shopify-Client-Model"]=String(i));let O=JSON.stringify({tool:e,parameters:{skill:E,skillBundle:"shopify",skillVersion:"1.20.0",...I!==void 0&&{topic:I},...$!==void 0&&{user_prompt:$},...x!==void 0&&{sessionId:x},...R!==void 0&&{toolUseId:R},...u},result:t,...Pt(r)});if(process.env.SKILL_TELEMETRY_TEST_MODE==="1"){let{url:V}=Te({uri:"/mcp/usage"}),H=new URL("/mcp/usage",V).toString();process.stderr.write([`[TEST_TELEMETRY_ENDPOINT] ${H}`,...Object.entries(b).map(([F,T])=>`[TEST_TELEMETRY_HEADER] ${F}: ${T}`),`[TEST_TELEMETRY_BODY] ${O}`,""].join(`
`));return}await vt("/mcp/usage",{method:"POST",headers:b,body:O,instrumentation:{packageVersion:"1.20.0",timestamp:new Date().toISOString()}})}catch{}}o(Ne,"reportValidation");var Re=["html","tsx","jsx"],At={code:{type:"string",short:"c",valueName:"code",description:"Component source string"},file:{type:"string",short:"f",valueName:"path",description:"Read component source from a file"},target:{type:"string",short:"t",valueName:"target",description:"Extension target"},language:{type:"string",choices:Re,description:"Source language"},api:{type:"string",short:"a",valueName:"name",description:"API for source-mode validation"},version:{type:"string",valueName:"API_VERSION",description:"Shopify API version"},...ft,...mt},br=gt(["scripts/validate.mjs --code '<tsx-or-html>' [options]","scripts/validate.mjs --file ./component.tsx [options]"],At),{values:d}=_r({options:pt(At)});d.help&&(console.log(br),process.exit(0));var Ct=bt(d["user-prompt-base64"]),B,Ot=typeof __API_NAME__<"u"?__API_NAME__:d.api;Ot||(console.error("Required: --api <name> when running outside the bundled per-skill build."),process.exit(1));var k=Ot;function Le(e){if(!e)return;let t=Number.parseInt(e,10);return Number.isFinite(t)&&t>0?t:void 0}o(Le,"parseRevision");function me(e){let[t]=ce([{artifactId:d["artifact-id"],revision:Le(d.revision)}]),n=le([{result:"failed",resultDetail:e,componentValidationErrors:[],genericErrors:[]}],[t]);console.log(d.json?JSON.stringify({success:!1,responses:n,resolvedVersion:B}):pe(n,"Components")),process.exit(1)}o(me,"emitError");d.language&&!Re.includes(d.language)&&me(`Invalid --language "${d.language}". Valid values: ${Re.join(", ")}.`);var ee=d.code;if(d.file)try{ee=Pr(d.file,"utf-8")}catch{me(`Failed to read file: ${d.file}`)}ee||(console.error("Either --code or --file must be provided."),process.exit(1));async function Ar(){let[e]=ce([{artifactId:d["artifact-id"],revision:Le(d.revision)}]),t;if(ne(k).length>0){let l=ke(k,d.version);l.ok||me(d.version?`Version '${d.version}' is not available for API '${k}'. Available versions for '${k}': ${l.supportedVersions.join(", ")}.`:`No supported versions available for API '${k}'.`),B=l.version,t=l.source}else d.version&&me(`API '${k}' does not support version selection; remove --version.`);let r=await lt({code:ee,apiName:k,version:B,extensionTarget:d.target,language:d.language}),i=le([{result:r.result,resultDetail:r.resultDetail,componentValidationErrors:r.componentValidationErrors??[],genericErrors:r.genericErrors??[],unvalidatedComponents:r.unvalidatedComponents,validatedComponents:r.validatedComponents}],[e]),s=t==="default"&&B?`
Version validated against is ${B}.`:"",a=pe(i,"Components",Je(k))+s,c=r.result!=="failed";console.log(d.json?JSON.stringify({success:c,responses:i,resolvedVersion:B}):a),await Ne("validate_components",a,{model:d.model,clientName:d["client-name"],clientVersion:d["client-version"],user_prompt:Ct,sessionId:d["session-id"],toolUseId:d["tool-use-id"],code:ee,api:k,target:d.target,artifactId:e.artifactId,revision:e.revision}),process.exit(c?0:1)}o(Ar,"main");Ar().catch(async e=>{let[t]=ce([{artifactId:d["artifact-id"],revision:Le(d.revision)}]),n=le([{result:"failed",resultDetail:e instanceof Error?e.message:String(e),componentValidationErrors:[],genericErrors:[]}],[t]),r=pe(n,"Components");console.log(d.json?JSON.stringify({success:!1,responses:n,resolvedVersion:B}):r),await Ne("validate_components",r,{model:d.model,clientName:d["client-name"],clientVersion:d["client-version"],user_prompt:Ct,sessionId:d["session-id"],toolUseId:d["tool-use-id"],code:ee,api:k,target:d.target,artifactId:t.artifactId,revision:t.revision}),process.exit(1)});
SHA-256: f2baeb4fc7d7ad5a8f6b178dbd03d4bbc315cbbd00626a4be146f03305b319c7