← Files ShopifyARCHIVED FILE
skills/shopify-onboarding-merchant/scripts/import_mock_shop_catalog.mjs
30.2 KB · Oct 5, 2026 · 12:03 UTC
#!/usr/bin/env node
import{execFile as Ae}from"child_process";import{existsSync as Pe,mkdtempSync as Le,readFileSync as He,realpathSync as te,writeFileSync as P}from"fs";import{tmpdir as Ue}from"os";import{join as N,resolve as qe}from"path";import{fileURLToPath as Me}from"url";import{parseArgs as Fe,promisify as Be}from"util";var Te=Object.defineProperty,d=(e,t)=>Te(e,"name",{value:t,configurable:!0});function oe(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>{let{description:o,valueName:l,choices:r,...s}=n;return[t,s]}))}d(oe,"toParseArgsOptions");var le={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"}},ie={"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"}},jt={"artifact-id":{type:"string",valueName:"id",description:"Stable artifact identifier"},revision:{type:"string",valueName:"number",description:"Positive artifact revision"},...le,...ie,json:{type:"boolean",description:"Emit machine-readable JSON"}},Re={help:{type:"boolean",short:"h",description:"Show this help"}};function re(e,t){let n=new Set([...Object.keys(le),...Object.keys(ie),"artifact-id","revision"]),o=Object.entries(t).filter(([r])=>!n.has(r)).map(([r,s])=>{let i=s.type==="string"?s.valueName||s.choices?.join("|")||"value":void 0,c=`--${r}${i?` <${i}>`:""}`;return[s.short?`-${s.short}, ${c}`:c,s.description]}),l=Math.max(...o.map(([r])=>r.length));return["Usage:",...e.map(r=>` ${r}`),"","Options:",...o.map(([r,s])=>` ${r.padEnd(l)} ${s}`)].join(`
`)}d(re,"formatCliHelp");var Je=`
query Extras {
shop {
name
brand {
slogan
shortDescription
logo { image { url } }
squareLogo { image { url } }
coverImage { image { url altText } }
colors { primary { background foreground } secondary { background foreground } }
}
}
main: menu(handle: "main-menu") { title items { ...MenuItemFields items { ...MenuItemFields } } }
footer: menu(handle: "footer") { title items { ...MenuItemFields items { ...MenuItemFields } } }
pages(first: 50) { nodes { handle title body } }
blogs(first: 10) {
nodes {
handle title
articles(first: 50) {
nodes { handle title contentHtml excerpt publishedAt authorV2 { name } image { url altText } }
}
}
}
}
fragment MenuItemFields on MenuItem { title url type }`;function se(e){let t=e?.shop?.brand??{},n=d(l=>l?{title:l.title??"",items:(l.items??[]).map(o)}:null,"menu"),o=d(l=>({title:l.title,url:l.url??"",type:l.type??"HTTP",...l.items?.length?{items:l.items.map(o)}:{}}),"menuItem");return{brand:{slogan:t.slogan??null,shortDescription:t.shortDescription??null,logoUrl:t.logo?.image?.url??t.squareLogo?.image?.url??null,coverImageUrl:t.coverImage?.image?.url??null,coverImageAlt:t.coverImage?.image?.altText??null,primaryBackground:t.colors?.primary?.[0]?.background??null,secondaryBackground:t.colors?.secondary?.[0]?.background??null},menus:{main:n(e?.main),footer:n(e?.footer)},pages:(e?.pages?.nodes??[]).map(l=>({handle:l.handle,title:l.title,body:l.body??""})),blogs:(e?.blogs?.nodes??[]).map(l=>({handle:l.handle,title:l.title,articles:(l.articles?.nodes??[]).map(r=>({handle:r.handle,title:r.title,contentHtml:r.contentHtml??"",excerpt:r.excerpt??null,publishedAt:r.publishedAt??null,author:r.authorV2?.name??null,imageUrl:r.image?.url??null,imageAlt:r.image?.altText??null}))}))}}d(se,"parseExtras");function ae(e){if(e.brand.coverImageUrl)return{url:e.brand.coverImageUrl,source:"brand"};let t=e.collectionImageUrls.find(Boolean);if(t)return{url:t,source:"collection"};let n=e.productImageUrls.find(Boolean);return n?{url:n,source:"product"}:null}d(ae,"pickHero");var De="mock-shop-hero",Ge="mock-shop-logo";function D(e,t){let n=t.split(/[?#]/)[0],o=/\.(png|jpe?g|gif|webp|svg)$/i.exec(n)?.[1]?.toLowerCase()??"png";return`${e}.${o==="jpeg"?"jpg":o}`}d(D,"filenameFor");function G(e){return`shopify://shop_images/${e}`}d(G,"shopImageRef");function L(e){let t=e.replace(/\/\*[\s\S]*?\*\//g,"").split(`
`).map(n=>n.trimStart().startsWith("//")?"":n).join(`
`);return JSON.parse(t)}d(L,"parseThemeJson");function de(e){let t=/\{%-?\s*schema\s*-?%\}([\s\S]*?)\{%-?\s*endschema\s*-?%\}/.exec(e);return t?JSON.parse(t[1]):null}d(de,"sectionSchema");function V(e,t){let n=e;for(let o of t.split(".")){if(!n||typeof n!="object"||!(o in n))return null;n=n[o]}return typeof n=="string"?n:null}d(V,"lookupTranslation");var F=Symbol("drop");function H(e,t){if(typeof e=="string")return e.startsWith("t:")?V(t,e.slice(2))??F:e;if(Array.isArray(e))return e.map(n=>H(n,t)).filter(n=>n!==F);if(e&&typeof e=="object"){let n={};for(let[o,l]of Object.entries(e)){let r=H(l,t);r!==F&&(n[o]=r)}return n}return e}d(H,"resolveValue");function U(e,t){if(Array.isArray(e))return e.map(n=>U(n,t));if(e&&typeof e=="object"){let n={};for(let[o,l]of Object.entries(e))n[o]=o==="settings"?H(l,t):U(l,t);return n}return e}d(U,"resolveSettingTranslations");function q(e,t="",n=!1){return typeof e=="string"?n&&e.startsWith("t:")?[`${t} = ${e}`]:[]:Array.isArray(e)?e.flatMap((o,l)=>q(o,`${t}[${l}]`,n)):e&&typeof e=="object"?Object.entries(e).flatMap(([o,l])=>q(l,`${t}/${o}`,n||o==="settings")):[]}d(q,"unresolvedSettingKeys");var B="mock_shop_collections",ce=2,R="shop_now_button",ze={section_height:"large",horizontal_alignment_flex_direction_column:"center",vertical_alignment_flex_direction_column:"center",toggle_overlay:!0,"padding-block-start":40,"padding-block-end":40},We={type_preset:"h1",alignment:"center",width:"fit-content"};function ue(e,t){let n=structuredClone(e),o=n.sections??{},l=Object.keys(o).find(i=>o[i]?.type==="hero")??null,r={index:n,heroSectionId:l,heroImageSet:!1,headingSet:!1,collectionListAdded:!1,featuredHandles:[]};if(l){let i=o[l];i.settings??={},t.heroRef&&(Object.assign(i.settings,ze,{media_type_1:"image",image_1:t.heroRef}),r.heroImageSet=!0);let c=(i.block_order??Object.keys(i.blocks??{})).find(g=>i.blocks?.[g]?.type==="text");if(c){let g=i.blocks[c];g.settings??={},t.heroRef&&Object.assign(g.settings,We),t.slogan&&(g.settings.text=`<p>${ge(t.slogan)}</p>`,r.headingSet=!0)}}let s=t.collectionHandles.slice(0,ce);if(s.length&&t.collectionListLiquid){let i=de(t.collectionListLiquid)?.presets??[],c=i.find(g=>g?.settings?.layout_type==="grid")??i[0];if(c){o[B]=pe(U(c,t.locale),s,t.locale),n.sections=o;let g=(n.order??Object.keys(o)).filter(v=>v!==B),y=l?g.indexOf(l)+1:0;g.splice(y,0,B),n.order=g,r.collectionListAdded=!0,r.featuredHandles=s}}return r}d(ue,"wireIndexJson");function pe(e,t,n){let o=Object.fromEntries(Object.entries(e.blocks??{}).filter(([,r])=>r?.static)),l=Object.values(o).find(r=>r.type==="_collection-card");if(l){l.settings={...l.settings??{},placement:"on_image",horizontal_alignment:"flex-start",vertical_alignment:"flex-end"},l.blocks??={};for(let s of Object.values(l.blocks))s.settings??={},s.type==="_collection-card-image"?Object.assign(s.settings,{image_ratio:"square",toggle_overlay:!0,overlay_style:"gradient",gradient_direction:"to top",overlay_color:"#00000080"}):s.type==="collection-title"&&Object.assign(s.settings,{type_preset:"h2",font:"var(--font-heading--family)",alignment:"left",width:"fit-content",background:!1,text_color:"#ffffff"});l.blocks[R]={type:"button",name:"t:names.button",settings:{label:V(n,"text_defaults.shop_now_button_label")??"Shop now",link:"{{ closest.collection.url }}",open_in_new_tab:!1,style_class:"button",width:"fit-content"}};let r=(l.block_order??Object.keys(l.blocks)).filter(s=>s!==R&&l.blocks[s]&&!l.blocks[s].static);l.block_order=[...r,R]}return{type:"collection-list",settings:{...e.settings??{},layout_type:"grid",columns:ce,mobile_columns:"1",columns_gap:8,rows_gap:8,carousel_on_mobile:!1,section_width:"page-width",collection_list:t,max_collections:t.length},blocks:o}}d(pe,"buildFeaturedCollections");function me(e,t){let n=structuredClone(e);return t?(n.current??={},n.current.logo=t,n.current.logo_height??=48,{settings:n,logoSet:!0}):{settings:n,logoSet:!1}}d(me,"wireSettingsData");function ge(e){return e.replace(/[&<>"]/g,t=>({"&":"&","<":"<",">":">",'"':"""})[t])}d(ge,"escapeHtml");function he(e){try{let t=new URL(e);return`${t.pathname}${t.search}`||"/"}catch{return e||"/"}}d(he,"menuPath");function X(e,t){let n=he(e.url),o=n.split("?")[0].split("/").filter(Boolean).pop()??"",l;return n==="/"||e.type==="FRONTPAGE"?l={title:e.title,type:"FRONTPAGE"}:n==="/collections"||e.type==="COLLECTIONS"||e.type==="CATALOG"?l={title:e.title,type:"CATALOG"}:n.startsWith("/collections/")&&t.collectionIdByHandle.has(o)?l={title:e.title,type:"COLLECTION",resourceId:t.collectionIdByHandle.get(o)}:n.startsWith("/blogs/")&&t.blogIdByHandle.has(o)?l={title:e.title,type:"BLOG",resourceId:t.blogIdByHandle.get(o)}:n.startsWith("/pages/")&&t.pageIdByHandle.has(o)?l={title:e.title,type:"PAGE",resourceId:t.pageIdByHandle.get(o)}:n==="/search"||e.type==="SEARCH"?l={title:e.title,type:"SEARCH"}:l={title:e.title,type:"HTTP",url:n},e.items?.length&&(l.items=e.items.map(r=>X(r,t))),l}d(X,"toMenuItemInput");var Ve=`mutation CreateFiles($files: [FileCreateInput!]!) {
fileCreate(files: $files) {
files { id fileStatus alt }
userErrors { field message }
}
}`,Xe=`query FileStatus($query: String!) {
files(first: 10, query: $query) { nodes { id fileStatus alt } }
}`,Ke="query Pages { pages(first: 250) { nodes { id handle } } }",Qe=`mutation CreatePage($page: PageCreateInput!) {
pageCreate(page: $page) { page { id handle } userErrors { field message } }
}`,Ye="query Blogs { blogs(first: 50) { nodes { id handle articles(first: 250) { nodes { id handle } } } } }",Ze=`mutation CreateBlog($blog: BlogCreateInput!) {
blogCreate(blog: $blog) { blog { id handle } userErrors { field message } }
}`,et=`mutation CreateArticle($article: ArticleCreateInput!) {
articleCreate(article: $article) { article { id handle } userErrors { field message } }
}`,tt="query Menus { menus(first: 50) { nodes { id handle title } } }",nt=`mutation UpdateMenu($id: ID!, $title: String!, $handle: String!, $items: [MenuItemUpdateInput!]!) {
menuUpdate(id: $id, title: $title, handle: $handle, items: $items) { menu { id handle } userErrors { field message } }
}`,ot=`mutation CreateMenu($title: String!, $handle: String!, $items: [MenuItemCreateInput!]!) {
menuCreate(title: $title, handle: $handle, items: $items) { menu { id handle } userErrors { field message } }
}`,lt="query Themes { themes(first: 20) { nodes { id name role themeStoreId processing processingFailed } } }",it=`query ThemeFiles($id: ID!, $filenames: [String!]!) {
theme(id: $id) {
files(first: 10, filenames: $filenames) {
nodes { filename body { ... on OnlineStoreThemeFileBodyText { content } } }
}
}
}`,rt=`mutation UpsertThemeFiles($themeId: ID!, $files: [OnlineStoreThemeFilesUpsertFileInput!]!) {
themeFilesUpsert(themeId: $themeId, files: $files) {
upsertedThemeFiles { filename }
userErrors { field message }
}
}`,st=["templates/index.json","config/settings_data.json","sections/collection-list.liquid","locales/en.default.schema.json"],at=Be(Ae),dt="shopify-onboarding-merchant",ct="1.15.0",x="mock.shop",ut="Online Store",j=250,pt=64*1024*1024,J="shopify",mt=2481,gt=15,ht=d(e=>new Promise(t=>setTimeout(t,e)),"sleep");function fe(e){let t=e.trim().toLowerCase();t=t.replace(/^[a-z]+:\/\//,"").split(/[/?#]/)[0],(t===""||t==="default")&&(t=x);let n;if(t===x||t===`hydrogen.${x}`)n="";else if(t.endsWith(`.hydrogen.${x}`))n=t.slice(0,-`.hydrogen.${x}`.length);else if(t.endsWith(`.${x}`))n=t.slice(0,-`.${x}`.length);else if(!t.includes("."))n=t;else throw new Error(`"${e}" is not a mock.shop store. Pass a subdomain like "candles" or a host like candles.mock.shop.`);if(n&&!/^[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/.test(n))throw new Error(`"${e}" is not a valid mock.shop subdomain.`);let o=n?`${n}.${x}`:x,l=n?`${n}.hydrogen.${x}`:`hydrogen.${x}`;return{subdomain:n,apiUrl:`https://${o}/api`,previewUrl:`https://${l}`,label:o}}d(fe,"resolveSource");var ft=`
query Products($after: String) {
shop { name }
products(first: ${j}, after: $after) {
pageInfo { hasNextPage endCursor }
nodes {
handle title descriptionHtml vendor productType tags
options { name values }
images(first: ${j}) { pageInfo { hasNextPage } nodes { url altText } }
variants(first: ${j}) {
pageInfo { hasNextPage }
nodes {
sku requiresShipping
price { amount }
compareAtPrice { amount }
selectedOptions { name value }
}
}
}
}
}`,bt=`
query Collections($after: String) {
collections(first: ${j}, after: $after) {
pageInfo { hasNextPage endCursor }
nodes {
handle title descriptionHtml
image { url altText }
products(first: ${j}) { pageInfo { hasNextPage endCursor } nodes { handle } }
}
}
}`,yt=`
query CollectionProducts($handle: String!, $after: String) {
collection(handle: $handle) {
products(first: ${j}, after: $after) { pageInfo { hasNextPage endCursor } nodes { handle } }
}
}`;async function T(e,t,n,o){let l=await e(t,{method:"POST",headers:{"Content-Type":"application/json","User-Agent":`shopify-ai-toolkit/${dt} ${ct}`},body:JSON.stringify({query:n,variables:o})}),r=await l.text();if(!l.ok)throw new Error(`${t} answered ${l.status}: ${r.slice(0,300)}`);let s=JSON.parse(r);if(s.errors?.length)throw new Error(`${t} returned GraphQL errors: ${s.errors.map(i=>i.message).join("; ")}`);return s.data}d(T,"storefrontQuery");async function be(e,t=fetch){let n=[],o="",l=null;do{let s=await T(t,e,ft,{after:l});o=s.shop?.name??o;for(let i of s.products.nodes){if(i.images.pageInfo.hasNextPage||i.variants.pageInfo.hasNextPage)throw new Error(`Product ${i.handle} has more than ${j} images or variants; this importer does not page inside a product.`);n.push({handle:i.handle,title:i.title,descriptionHtml:i.descriptionHtml??"",vendor:i.vendor??"",productType:i.productType??"",tags:i.tags??[],options:i.options??[],images:i.images.nodes,variants:i.variants.nodes})}l=s.products.pageInfo.hasNextPage?s.products.pageInfo.endCursor:null}while(l);let r=[];l=null;do{let s=await T(t,e,bt,{after:l});for(let i of s.collections.nodes){let c=i.products.nodes.map(y=>y.handle),g=i.products.pageInfo;for(;g.hasNextPage;){let y=await T(t,e,yt,{handle:i.handle,after:g.endCursor});c.push(...y.collection.products.nodes.map(v=>v.handle)),g=y.collection.products.pageInfo}r.push({handle:i.handle,title:i.title,descriptionHtml:i.descriptionHtml??"",image:i.image??null,productHandles:c})}l=s.collections.pageInfo.hasNextPage?s.collections.pageInfo.endCursor:null}while(l);return{shopName:o,products:n,collections:r}}d(be,"fetchCatalog");async function ye(e,t=fetch){return se(await T(t,e,Je,{}))}d(ye,"fetchExtras");var ne=`mutation ImportProduct($identifier: ProductSetIdentifiers, $input: ProductSetInput!) {
productSet(identifier: $identifier, input: $input) {
product { id handle }
userErrors { field message }
}
}`,$t=`mutation Publish($id: ID!, $input: [PublicationInput!]!) {
publishablePublish(id: $id, input: $input) {
userErrors { field message }
}
}`,It=`mutation CreateCollection($input: CollectionCreateInput!) {
collectionCreate(collection: $input) {
collection { id handle }
userErrors { field message }
}
}`;function $e(e,t){let n={handle:e.handle,title:e.title,descriptionHtml:e.descriptionHtml,vendor:e.vendor,productType:e.productType,tags:e.tags,status:"ACTIVE",productOptions:e.options.map(o=>({name:o.name,values:o.values.map(l=>({name:l}))})),variants:e.variants.map(o=>{let l={optionValues:o.selectedOptions.map(r=>({optionName:r.name,name:r.value})),price:o.price.amount,inventoryPolicy:"CONTINUE",inventoryItem:{tracked:!1,requiresShipping:o.requiresShipping!==!1}};return o.compareAtPrice?.amount&&(l.compareAtPrice=o.compareAtPrice.amount),o.sku&&(l.sku=o.sku),l})};return e.images.length&&(n.files=e.images.map(o=>({originalSource:o.url,contentType:"IMAGE",...o.altText?{alt:o.altText}:{}}))),t.length&&(n.collections=t),{identifier:{handle:e.handle},input:n}}d($e,"toProductSetVariables");function Ie(e){return{handle:e.handle,title:e.title,descriptionHtml:e.descriptionHtml,...e.image?{image:{src:e.image.url,...e.image.altText?{altText:e.image.altText}:{}}}:{}}}d(Ie,"toCollectionCreateInput");function we(e,t){return e.map(n=>({id:n,input:[{publicationId:t}]}))}d(we,"buildPublishVariables");function Se(e){let t=ut.toLowerCase();return e.find(n=>n.name?.toLowerCase()===t||n.catalog?.title?.toLowerCase()===t)??null}d(Se,"findOnlineStorePublication");function z(e,t){let n={succeeded:[],failed:[]};return e.split(`
`).filter(o=>o.trim().startsWith("{")).forEach((o,l)=>{let r;try{r=JSON.parse(o)}catch{n.failed.push({line:l,errors:["unparseable result line"]});return}let s=typeof r.__lineNumber=="number"?r.__lineNumber:l,i=r.data?.[t]??r[t],c=(r.errors??[]).map(v=>v.message??JSON.stringify(v)),g=(i?.userErrors??[]).map(v=>`${(v.field??[]).join(".")||"input"}: ${v.message}`),y=[...c,...g];y.length||!i?n.failed.push({line:s,errors:y.length?y:["no payload returned"]}):n.succeeded.push({line:s,id:i.product?.id??i.collection?.id??null,handle:i.product?.handle??i.collection?.handle??null})}),n}d(z,"parseBulkResults");function W(e){return e.map(t=>JSON.stringify(t)).join(`
`)+`
`}d(W,"toJsonl");function ve(e){let t=e.indexOf("{");if(t<0)throw new Error(`Shopify CLI returned no JSON: ${e.slice(0,200)}`);let n=JSON.parse(e.slice(t));if(n.errors?.length)throw new Error(`Admin API errors: ${n.errors.map(o=>o.message??JSON.stringify(o)).join("; ")}`);return n.data??n.result?.data??n}d(ve,"unwrapData");function xe(e){async function t(n){e(`$ ${J} ${n.map(o=>/\s/.test(o)?JSON.stringify(o):o).join(" ")}`);try{let{stdout:o}=await at(J,n,{maxBuffer:pt,env:{...process.env,SHOPIFY_FLAG_NO_COLOR:"1"}});return o}catch(o){let l=[o.stdout,o.stderr].filter(Boolean).join(`
`);throw new Error(`\`${J} ${n.slice(0,3).join(" ")}\` failed: ${l.trim()||o.message}`)}}return d(t,"run"),{async execute(n,o,l,r=!1){let s=["store","execute","--store",n,"--json","--query",o];return l&&s.push("--variables",JSON.stringify(l)),r&&s.push("--allow-mutations"),ve(await t(s))},async bulk(n,o,l,r){if(await t(["store","bulk","execute","--store",n,"--query-file",o,"--variable-file",l,"--allow-mutations","--watch","--output-file",r]),!Pe(r))throw new Error("bulk operation wrote no results file; it likely failed before running (see the CLI output above)");return He(r,"utf-8")}}}d(xe,"makeCliRunner");function O(e,t){let n=e?.[t];if(n?.userErrors?.length)throw new Error(`${t}: ${n.userErrors.map(o=>`${(o.field??[]).join(".")||"input"}: ${o.message}`).join("; ")}`);return n}d(O,"payloadOf");async function Oe(e){let{log:t}=e,{store:n}=e,o=fe(e.source),l=Le(N(Ue(),"mock-shop-import-"));t(`Reading ${o.label} catalog\u2026`);let r=await be(o.apiUrl,e.fetchImpl),s=await ye(o.apiUrl,e.fetchImpl);t(` ${r.products.length} products, ${r.collections.length} collections, ${s.pages.length} pages, ${s.blogs.length} blogs from "${r.shopName}"`);let i={source:{...o,shopName:r.shopName},store:n,storeName:null,collections:{total:r.collections.length,created:0,reused:0},products:{total:r.products.length,imported:0,failed:[]},published:{attempted:0,failed:0,publicationId:null},files:{hero:null,logo:null,ready:!1},content:{pages:{created:0,reused:0},blogs:{created:0,reused:0},articles:{created:0,reused:0},menus:[],note:null},theme:{id:null,name:null,heroImageSet:!1,headingSet:!1,logoSet:!1,collectionListAdded:!1,featuredCollections:[],upserted:[],note:null}},c=xe(t),g=new Map,y=null,v=r.collections.map((a,m)=>`c${m}: collections(first: 1, query: ${JSON.stringify(`handle:${a.handle}`)}) { nodes { id handle } }`).join(`
`),K=await c.execute(n,`query Lookup { publications(first: 25) { nodes { id name catalog { title } } } ${v} }`);r.collections.forEach((a,m)=>{let u=K[`c${m}`]?.nodes?.find(f=>f.handle===a.handle);u&&g.set(a.handle,u.id)}),y=Se(K.publications?.nodes??[])?.id??null,i.published.publicationId=y,y||t(" warning: no Online Store publication found; products will be imported but not published");for(let a of r.collections){if(g.has(a.handle)){i.collections.reused+=1;continue}let m=await c.execute(n,It,{input:Ie(a)},!0),u=O(m,"collectionCreate");g.set(a.handle,u.collection.id),i.collections.created+=1}t(` collections: ${i.collections.created} created, ${i.collections.reused} already present`);let M=new Map;for(let a of r.collections){let m=g.get(a.handle);if(m)for(let u of a.productHandles)M.set(u,[...M.get(u)??[],m])}let E=r.products.map(a=>$e(a,M.get(a.handle)??[])),Q=N(l,"product_set.graphql"),Y=N(l,"products.jsonl"),je=N(l,"products.results.jsonl");P(Q,ne),P(Y,W(E)),t(`Importing ${E.length} products\u2026`);let Ee=await c.bulk(n,Q,Y,je),Z=z(Ee,"productSet"),ee=Z.succeeded.map(a=>a.id).filter(a=>!!a);for(let a of Z.failed){let m=E[a.line];if(m){t(` retrying ${m.identifier.handle}: ${a.errors.join("; ")}`);try{let u=await c.execute(n,ne,m,!0),f=O(u,"productSet");f?.product?.id&&ee.push(f.product.id)}catch(u){i.products.failed.push({handle:m.identifier.handle,errors:[u.message]})}}}if(i.products.imported=E.length-i.products.failed.length,t(` ${i.products.imported}/${E.length} products imported`),y){let a=[...ee,...g.values()],m=we(a,y),u=N(l,"publish.graphql"),f=N(l,"publish.jsonl"),b=N(l,"publish.results.jsonl");P(u,$t),P(f,W(m)),t(`Publishing ${a.length} products and collections to the Online Store\u2026`);let p=await c.bulk(n,u,f,b),$=z(p,"publishablePublish");i.published={attempted:a.length,failed:$.failed.length,publicationId:y},$.failed.length&&t(` ${$.failed.length} publish operations failed; rerun to converge`)}let A=ae({brand:s.brand,collectionImageUrls:r.collections.map(a=>a.image?.url),productImageUrls:r.products.map(a=>a.images[0]?.url)}),_=[];if(A){let a=D(De,A.url);i.files.hero={filename:a,source:A.source},_.push({originalSource:A.url,filename:a,contentType:"IMAGE",duplicateResolutionMode:"REPLACE",alt:s.brand.coverImageAlt??`${r.shopName} hero image`})}if(s.brand.logoUrl){let a=D(Ge,s.brand.logoUrl);i.files.logo={filename:a},_.push({originalSource:s.brand.logoUrl,filename:a,contentType:"IMAGE",duplicateResolutionMode:"REPLACE",alt:`${r.shopName} logo`})}if(_.length){t(`Uploading brand assets: ${_.map(u=>u.filename).join(", ")}\u2026`),O(await c.execute(n,Ve,{files:_},!0),"fileCreate");let a=_.map(u=>`filename:${u.filename}`).join(" OR "),m=!1;for(let u=0;u<gt;u++){let f=(await c.execute(n,Xe,{query:a})).files?.nodes??[];if(f.length>=_.length&&f.every(b=>b.fileStatus==="READY")){i.files.ready=!0;break}if(f.some(b=>b.fileStatus==="FAILED")){m=!0;break}await ht(2e3)}m?(i.files.hero=null,i.files.logo=null,t(" brand asset upload failed; hero and logo will not be wired")):t(i.files.ready?" brand assets ready":" brand assets still processing; the theme will pick them up shortly")}try{let a=new Map,m=new Map;if(s.pages.length){let b=new Map(((await c.execute(n,Ke)).pages?.nodes??[]).map(p=>[p.handle,p.id]));for(let p of s.pages){if(b.has(p.handle)){m.set(p.handle,b.get(p.handle)),i.content.pages.reused+=1;continue}let $=O(await c.execute(n,Qe,{page:{title:p.title,handle:p.handle,body:p.body,isPublished:!0}},!0),"pageCreate");m.set(p.handle,$.page.id),i.content.pages.created+=1}}if(s.blogs.length){let b=(await c.execute(n,Ye)).blogs?.nodes??[];for(let p of s.blogs){let $=b.find(h=>h.handle===p.handle),C,I=new Set(($?.articles?.nodes??[]).map(h=>h.handle));$?(C=$.id,i.content.blogs.reused+=1):(C=O(await c.execute(n,Ze,{blog:{title:p.title,handle:p.handle}},!0),"blogCreate").blog.id,i.content.blogs.created+=1),a.set(p.handle,C);for(let h of p.articles){if(I.has(h.handle)){i.content.articles.reused+=1;continue}let w={blogId:C,title:h.title,handle:h.handle,body:h.contentHtml,isPublished:!0,author:{name:h.author??r.shopName}};h.excerpt&&(w.summary=h.excerpt),h.publishedAt&&(w.publishDate=h.publishedAt),h.imageUrl&&(w.image={url:h.imageUrl,altText:h.imageAlt??h.title}),O(await c.execute(n,et,{article:w},!0),"articleCreate"),i.content.articles.created+=1}}}(i.content.pages.created||i.content.blogs.created)&&t(` content: ${i.content.pages.created} pages, ${i.content.blogs.created} blogs, ${i.content.articles.created} articles created`);let u={collectionIdByHandle:g,blogIdByHandle:a,pageIdByHandle:m},f=[];if(s.menus.main?.items.length&&f.push(["main-menu",s.menus.main]),s.menus.footer?.items.length&&f.push(["footer",s.menus.footer]),f.length){let b=(await c.execute(n,tt)).menus?.nodes??[];for(let[p,$]of f){let C=$.items.map(w=>X(w,u)),I=$.title||(p==="footer"?"Footer menu":"Main menu"),h=b.find(w=>w.handle===p);h?O(await c.execute(n,nt,{id:h.id,title:I,handle:p,items:C},!0),"menuUpdate"):O(await c.execute(n,ot,{title:I,handle:p,items:C},!0),"menuCreate"),i.content.menus.push(p)}t(` menus: ${i.content.menus.join(", ")}`)}}catch(a){i.content.note=a.message,t(` content copy stopped: ${a.message}`)}try{let a=((await c.execute(n,lt)).themes?.nodes??[]).find(S=>S.role==="MAIN");if(!a)throw new Error("no live theme found");if(a.themeStoreId!==mt&&!/horizon/i.test(a.name??""))throw new Error(`live theme "${a.name}" is not Horizon; homepage left untouched`);let m=a.id,u=a.name;i.theme.id=m,i.theme.name=u;let f=(await c.execute(n,it,{id:m,filenames:st})).theme?.files?.nodes??[],b=new Map(f.map(S=>[S.filename,S.body?.content??""])),p=b.get("templates/index.json"),$=b.get("config/settings_data.json");if(!p)throw new Error(`theme "${u}" has no templates/index.json; skipping wiring`);let C=b.get("locales/en.default.schema.json")?L(b.get("locales/en.default.schema.json")):{},I=ue(L(p),{heroRef:i.files.hero?G(i.files.hero.filename):null,slogan:s.brand.slogan,collectionHandles:[...r.collections].sort((S,k)=>+!!k.image-+!!S.image).map(S=>S.handle),collectionListLiquid:b.get("sections/collection-list.liquid")??null,locale:C}),h=q(I.index);if(h.length)throw new Error(`unresolved translation keys in settings: ${h.join(", ")}`);let w=[];if((I.heroImageSet||I.headingSet||I.collectionListAdded)&&w.push({filename:"templates/index.json",body:{type:"TEXT",value:JSON.stringify(I.index,null,2)}}),$&&i.files.logo){let S=me(L($),G(i.files.logo.filename));S.logoSet&&(i.theme.logoSet=!0,w.push({filename:"config/settings_data.json",body:{type:"TEXT",value:JSON.stringify(S.settings,null,2)}}))}if(w.length){t(`Wiring theme "${u}": ${w.map(k=>k.filename).join(", ")}\u2026`);let S=O(await c.execute(n,rt,{themeId:m,files:w},!0),"themeFilesUpsert");i.theme.upserted=(S.upsertedThemeFiles??[]).map(k=>k.filename)}i.theme.heroImageSet=I.heroImageSet,i.theme.headingSet=I.headingSet,i.theme.collectionListAdded=I.collectionListAdded,i.theme.featuredCollections=I.featuredHandles,I.heroSectionId||(i.theme.note="no hero section in templates/index.json; hero and heading not set")}catch(a){i.theme.note=a.message,t(` theme wiring skipped: ${a.message}`)}let ke=await c.execute(n,"query StoreName { shop { name } }");return i.storeName=ke.shop?.name??null,i}d(Oe,"importCatalog");function Ce(e){let t=[`Copied "${e.source.shopName}" (${e.source.label}) into ${e.store}:`,` products: ${e.products.imported} of ${e.products.total} imported${e.products.failed.length?`, ${e.products.failed.length} failed`:""}`,` collections: ${e.collections.created} created, ${e.collections.reused} reused (${e.collections.total} total)`,e.published.publicationId?` published to Online Store: ${e.published.attempted-e.published.failed} of ${e.published.attempted}`:" not published: no Online Store publication found"],n=[e.files.hero?`hero (${e.files.hero.source} image)`:null,e.files.logo?"logo":null].filter(Boolean);t.push(n.length?` brand assets: ${n.join(", ")}${e.files.ready?"":" (still processing)"}`:" brand assets: none available from the reference store");let o=e.content,l=[o.pages.created+o.pages.reused?`${o.pages.created+o.pages.reused} pages`:null,o.blogs.created+o.blogs.reused?`${o.blogs.created+o.blogs.reused} blogs`:null,o.articles.created+o.articles.reused?`${o.articles.created+o.articles.reused} articles`:null,o.menus.length?`menus: ${o.menus.join(", ")}`:null].filter(Boolean);t.push(` content: ${l.length?l.join(", "):"nothing to copy"}${o.note?` (stopped: ${o.note})`:""}`);let r=e.theme,s=[r.heroImageSet?"hero image":null,r.headingSet?"hero heading":null,r.collectionListAdded?`featured collections (${r.featuredCollections.join(", ")})`:null,r.logoSet?"logo":null].filter(Boolean);t.push(r.id?` theme: "${r.name}"${s.length?`, wired ${s.join(", ")}`:", nothing to wire"}${r.note?` (${r.note})`:""}`:` theme: not wired${r.note?` (${r.note})`:""}`),e.storeName&&t.push(e.storeName===e.source.shopName?` store name: "${e.storeName}"`:` store name: "${e.storeName}" (reference is "${e.source.shopName}"; a store's name is set when it is created and this import does not change it)`);for(let i of e.products.failed)t.push(` FAILED ${i.handle}: ${i.errors.join("; ")}`);return(e.products.failed.length||e.published.failed)&&t.push(" Rerun the same command to converge; existing handles are updated, not duplicated."),t.join(`
`)}d(Ce,"summarize");var _e={store:{type:"string",valueName:"domain",description:"Target store domain, e.g. my-store.myshopify.com"},source:{type:"string",valueName:"store",description:"mock.shop reference store: subdomain, host, or preview URL (e.g. candles)"},json:{type:"boolean",description:"Print the full report as JSON"},...Re},wt=re(["scripts/import_mock_shop_catalog.mjs --store <domain> --source <store> [options]"],_e);async function Ne(){let{values:e}=Fe({options:oe(_e),allowPositionals:!1});e.help&&(console.log(wt),process.exit(0)),(!e.store||!e.source)&&(console.error("Usage: scripts/import_mock_shop_catalog.mjs --store <domain> --source <store> (run with --help for details)"),process.exit(1));let t=await Oe({store:e.store,source:e.source,log:d(n=>console.error(n),"log")});console.log(e.json?JSON.stringify(t,null,2):Ce(t)),process.exit(t.products.failed.length||t.published.failed?2:0)}d(Ne,"main");var St=(()=>{try{if(!process.argv[1])return!1;let e=te(Me(import.meta.url)),t=te(qe(process.argv[1]));return e===t}catch{return!1}})();St&&Ne().catch(e=>{console.error(e instanceof Error?e.message:String(e)),process.exit(1)});export{It as COLLECTION_CREATE_MUTATION,x as MOCK_SHOP_APEX,ut as ONLINE_STORE_PUBLICATION_NAME,ne as PRODUCT_SET_MUTATION,$t as PUBLISH_MUTATION,we as buildPublishVariables,be as fetchCatalog,ye as fetchExtras,Se as findOnlineStorePublication,Oe as importCatalog,z as parseBulkResults,fe as resolveSource,Ce as summarize,Ie as toCollectionCreateInput,W as toJsonl,$e as toProductSetVariables};
SHA-256: 73b6dc6fea53a5198422b412da326a04767d1ad6147aa5c58cfccb9dcd228d73