UNPKG

@shopify/cli

Version:

A CLI tool to build for the Shopify platform

67 lines (56 loc) • 172 kB
import{A as Bt,B as Io,C as J,D as To,E as ko,F as Fo,G as $t,K as Mo,L as Do,M as Ro,N as Oo,O as Uo,P as Bo,Q as $o,S as Lo,T as jo,V as No,X as Wo,a as bn,b as z,c as Oe,g as Ot,h as Eo,i as Cn,j as wn,l as Ut,m as So,n as ye,o as Po,p as En,q as vo,r as R,s as Ue,t as Be,u as Ao,v as ie,w as $e,x as k,y as oe,z as he}from"./chunk-7ESSIN27.js";import{a as go,b as Pp,c as vp,d as yo,e as ho,f as _o,g as xn,h as xo,i as bo,j as nt,k as Co,l as Ap,m as Rt,n as wo}from"./chunk-GZS44BUW.js";import{a as fo,b as mo}from"./chunk-7QIOUDCX.js";import{b as uo,o as Sp}from"./chunk-7MUKLZOL.js";import{a as Ep}from"./chunk-VBUZWRUL.js";import{a as lo}from"./chunk-KR6QDE7D.js";import{aa as wp}from"./chunk-UXVZ2P63.js";import{a as co}from"./chunk-EKXY5COY.js";import{b as tt,c as U}from"./chunk-4DCQNGUV.js";import{a as ao}from"./chunk-FQWB2F75.js";import{$ as It,H as Wi,I as Vi,N as zi,Z as fe,_ as me,aa as Ji,ba as W,da as Ze,ea as qi,j as Bi,n as $i,p as Li,r as p,t as ji,z as Ni}from"./chunk-XONFGLJQ.js";import{m as Tt,n as Ki,s as Hi,t as Gi,w as kt,x as Yi}from"./chunk-L2MGAEV3.js";import{a as le,b as ve}from"./chunk-XULPJ6UG.js";import{b as gn}from"./chunk-MHWV5RQV.js";import{b as po}from"./chunk-XOTA6JTZ.js";import{a as Ye,c as Ui,d as At}from"./chunk-JUVAGMIH.js";import{A as $,B as De,D as eo,F as et,G as to,I as no,O as ge,R as io,u as Qe,v as Xe,w as Ft,x as Qi,z as Xi}from"./chunk-6G6TMKXF.js";import{a as Zi,f as yn}from"./chunk-WSDN25F5.js";import{d as b,f as V,g as Q}from"./chunk-M56NDIMD.js";import{$ as mn,$a as te,Ba as Fi,Ea as de,Ga as Et,Gb as v,Hb as Mt,Ib as A,Ka as Mi,L as Pe,La as Di,N as Ii,Nb as Re,O as un,Oa as St,P as dn,Pa as Ri,Pb as Dt,Qb as S,Rb as ue,Ta as w,Tb as ro,Ua as H,Ub as so,W as He,Wa as D,Xa as Oi,Y as j,Z as fn,ba as bt,bb as Pt,db as vt,ea as Ti,fa as Me,ka as Ct,ma as F,na as ce,oa as Ge,pa as N,qa as wt,tb as ne,ua as B,va as ki,wa as Z}from"./chunk-N5PQPIBF.js";import{l as hn,m as _n,n as oo}from"./chunk-YTNDFQJT.js";import{a as Ke}from"./chunk-ULQG3XQS.js";import{d as y,e as Se,f as pe,g as I,h as Pi,i as P,j as T,k as _t,l as vi,n as xt,s as Ai,t as ln}from"./chunk-IU2ZQ6TE.js";import{a as Si,e as qe,g as u}from"./chunk-VPRTJUIN.js";u();import{pipeline as Ip}from"stream/promises";import Vo from"node:stream/promises";import*as zo from"node:zlib";import{fileURLToPath as An}from"node:url";var Jo="9.1.2",qo="7.0.1",Ko="3",Tp="123.0.0",Ho="1.0.2",Go="2.0.1";function Yo(e){return e==="0"||e==="1"?{functionRunner:"7.0.1",javy:"4.0.0",javyPlugin:"1"}:e==="2"?{functionRunner:Jo,javy:qo,javyPlugin:Ko}:null}var it=class{constructor(t,n,i,o,r=`v${n}`){this.name=t,this.version=n,this.release=r,this.supportsWindowsOnArm=o;let s;s=`${t}-${n}`,s=process.platform==="win32"?`${s}.exe`:s,this.path=y(P(An(import.meta.url)),"..","bin",s),this.gitHubRepo=i}downloadUrl(t,n){let i,o;switch(t.toLowerCase()){case"darwin":i="macos";break;case"linux":i="linux";break;case"win32":i="windows";break;default:throw Error(`Unsupported platform ${t}`)}switch(n.toLowerCase()){case"arm":case"arm64":o="arm";break;case"ia32":case"x64":o="x86_64";break;default:throw Error(`Unsupported architecture ${n}`)}let r=`${o}-${i}`,s=["arm-linux","arm-macos","x86_64-macos","x86_64-windows","x86_64-linux"];if(this.supportsWindowsOnArm&&s.push("arm-windows"),!s.includes(r))throw Error(`Unsupported platform/architecture combination ${t}/${n}`);return`https://github.com/${this.gitHubRepo}/releases/download/${this.release}/${this.name}-${r}-v${this.version}.gz`}async processResponse(t,n){return Fp(t,n)}},Pn=class{constructor(t){this.name=`shopify_functions_javy_v${t}`,this.version=t,this.path=y(P(An(import.meta.url)),"..","bin",`shopify_functions_javy_v${t}.wasm`)}downloadUrl(t,n){return`https://cdn.shopify.com/shopifycloud/shopify-functions-javy-plugin/shopify_functions_javy_v${this.version}.wasm`}async processResponse(t,n){return Ip(t,n)}},vn=class{constructor(t,n){this.name=t,this.version=n,this.path=y(P(An(import.meta.url)),"..","bin",t)}downloadUrl(t,n){return`https://cdn.jsdelivr.net/npm/binaryen@${this.version}/bin/wasm-opt`}async processResponse(t,n){await Vo.pipeline(t,n)}},Sn;function In(e=qo){return new it("javy",e,"bytecodealliance/javy",kt(e,">=7.0.0"))}function Tn(e=Ko){return new Pn(e)}function Zd(e=Jo){return new it("function-runner",e,"Shopify/function-runner",kt(e,">=9.1.1"))}function ot(){return Sn||(Sn=new vn("wasm-opt.cjs",Tp)),Sn}function Zo(e){return new it("shopify-function-trampoline",e,"Shopify/shopify-function-wasm-api",kt(e,">=2.0.1"),`shopify_function_trampoline/v${e}`)}var Lt=new Map;async function Ae(e){if(await w(e.path)&&!Lt.has(e.path))return;let n=Lt.get(e.path);if(n){await n;return}let i=kp(e);Lt.set(e.path,i);try{await i}finally{Lt.delete(e.path)}}async function kp(e){let t=e.downloadUrl(process.platform,process.arch);S(`Downloading ${e.name} ${e.version} from ${t} to ${e.path}`);let n=P(e.path);await w(n)||await Z(n),await go(async()=>{let i=await $i(t,void 0,"slow-request");if(i.status!==200)throw new Error(`Downloading ${e.name} failed with status code of ${i.status}`);let o=i.body;if(o===null)throw new Error(`Downloading ${e.name} failed with empty response body`);await Ct(async r=>{let s=y(r,"binary"),a=Di(s);await e.processResponse(o,a),await Ri(s,509),await St(s,e.path,{overwrite:!0})})},async()=>{},2)}async function Fp(e,t){let n=zo.createGunzip();await Vo.pipeline(e,n,t)}u();import{build as Xo}from"esbuild";var Mp="2",rt=class extends b{constructor(t){super(t,A`Make sure you have a compatible version of the ${v.yellow("@shopify/shopify_function")} library installed.`,[A`Add ${v.green(`"@shopify/shopify_function": "~${Mp}.0.0"`)} to the dependencies section of the package.json file in your function's directory, if not already present.`.value,"Run your package manager's install command to update dependencies."])}};async function er(e,t){let n=$p(e),i=n.length===0?Bp:new kn(n),o=await nr(e);return t.useTasks?Rp(e,t,i,o):Dp(e,t,i,o)}async function Dp(e,t,n,i){t.signal?.aborted||(t.stdout.write(`Building function ${e.localIdentifier}...`),t.stdout.write(`Building GraphQL types... `),await st(e,t)),t.signal?.aborted||(t.stdout.write(`Bundling JS function... `),await n.bundle(e,t)),t.signal?.aborted||(t.stdout.write(`Running javy... `),await n.compile(e,t,i)),t.signal?.aborted||t.stdout.write(`Done! `)}async function Rp(e,t,n,i){await eo([{title:"Building GraphQL types",task:async()=>{await st(e,t)}},{title:"Bundling JS function",task:async()=>{await n.bundle(e,t)}},{title:"Running javy",task:async()=>{await n.compile(e,t,i)}}])}async function st(e,t){if(e.typegenCommand){let i=e.typegenCommand.split(" ");return yn("cmd_all_timing_network_ms")(async()=>ge(i[0],i.slice(1),{cwd:e.directory,stdout:t.stdout,stderr:t.stderr,signal:t.signal}))}if(!e.isJavaScript)throw new b("No typegen_command specified. Set build.typegen_command in your function extension TOML to generate GraphQL types for non-JavaScript functions.");let n=await Ki(e.directory,"graphql-code-generator","--config","package.json");return yn("cmd_all_timing_network_ms")(async()=>ge(n.command,n.args,{cwd:e.directory,stderr:t.stderr,signal:t.signal}))}async function tr(e){let t=await te("node_modules/@shopify/shopify_function/index.ts",{type:"file",cwd:e.directory}),n=await te("node_modules/@shopify/shopify_function/run.ts",{type:"file",cwd:e.directory});if(!t||!n)throw new rt("Could not find the Shopify Functions JavaScript library.");if(!e.entrySourceFilePath)throw new b("Could not find your function entry point. It must be in src/index.js or src/index.ts");return t}async function nr(e){let t=await te("node_modules/@shopify/shopify_function/package.json",{type:"file",cwd:e.directory});if(!t)throw new rt("Could not find the Shopify Functions JavaScript library.");let i=JSON.parse(await F(t)).version.split(".")[0],o=Yo(i);if(o===null)throw new rt("The installed version of the Shopify Functions JavaScript library is not compatible with this version of Shopify CLI.");return o}async function Op(e,t,n=process.env){let i=await tr(e),o={...ir(e.directory,e.entrySourceFilePath,t.app.dotenv?.variables??{},n),entryPoints:[i]};return Xo(o)}function ir(e,t,n,i=process.env){let o=me(i,(c,d)=>Ot.test(d)&&c),r={...n,...o},s=Object.keys(r||{}).reduce((c,d)=>({...c,[`process.env.${d}`]:JSON.stringify(r[d])}),{});return{outfile:y(e,"dist/function.js"),alias:{"user-function":t},define:s,logLevel:"silent",bundle:!0,legalComments:"none",target:"es2022",format:"esm"}}async function or(e){let t=ot();await Ae(t);let n=P(ot().path),i="node",o=[ot().name,e,"-Oz","--enable-bulk-memory","--enable-multimemory","--enable-nontrapping-float-to-int","--strip-debug","-o",e];S(`Wasm binary: ${ot().name}`),S("Optimizing this wasm binary using wasm-opt."),await ge(i,o,{cwd:n})}async function rr(e){let t,n=await Up(e);if(n.includes("shopify_function_v1")?t=Ho:n.includes("shopify_function_v2")&&(t=Go),!t)return;let i=Zo(t);await Ae(i);let o=i.path,r=["-i",e,"-o",e];S(`Applying trampoline to the wasm binary with command: ${o} ${r.join(" ")}`),await ge(o,r)}async function Up(e){let t=new Uint8Array(ce(e));if(!WebAssembly.validate(t))return[];let i=new WebAssembly.Module(t),o=WebAssembly.Module.imports(i);return[...new Set(o.map(r=>r.module))]}async function sr(e,t,n,i=[]){let o=In(n.javy),r=Tn(n.javyPlugin);await Promise.all([Ae(o),Ae(r)]);let s=["build","-C","dynamic","-C",`plugin=${r.path}`,...i,"-o",e.outputPath,"dist/function.js"];return ge(o.path,s,{cwd:e.directory,stdout:"inherit",stderr:"inherit",signal:t.signal})}async function yf(e){let n=e.allExtensions.filter(a=>a.features.includes("function")&&a.isJavaScript).map(a=>nr(a)),i=await Promise.all(n),o=new Set,r=new Set;i.forEach(a=>{o.add(a.javy),r.add(a.javyPlugin)});let s=[];o.forEach(a=>{s.push(Ae(In(a)))}),r.forEach(a=>{s.push(Ae(Tn(a)))}),await Promise.all(s)}var Bp={async bundle(e,t){return Op(e,t)},async compile(e,t,n){return sr(e,t,n)}},Qo="shopify-function",kn=class{constructor(t){this.exports=t}async bundle(t,n,i=process.env){await tr(t);let o=this.entrypointContents;S("Generating dist/function.js using generated module:"),S(o);let r={...ir(t.directory,t.entrySourceFilePath,n.app.dotenv?.variables??{},i),stdin:{contents:o,loader:"ts",resolveDir:t.directory}};return Xo(r)}async compile(t,n,i){let o=this.wit;return S("Generating world to use with Javy:"),S(o),Ct(async r=>{let s=y(r,"javy-world.wit");return await B(s,o),sr(t,n,i,["-C",`wit=${s}`,"-C",`wit-world=${Qo}`])})}get wit(){let t=this.exports.map(n=>`export %${mn(n)}: func();`);return`package function:impl; world ${Qo} { ${t.join(` `)} }`}get entrypointContents(){let t=` import __runFunction from "@shopify/shopify_function/run"`,n=this.exports.map(i=>{let o=fn(i),r=fn(`run-${i}`);return` import { ${o} as ${r} } from "user-function" export function ${o}() { return __runFunction(${r}) }`});return`${t} ${n.join(` `)}`}};function $p(e){let t=e.configuration.targeting??[],n=t.filter(r=>!r.export),i=t.filter(r=>!!r.export);if(t.length>1&&n.length>0)throw new Error(`Can't infer export name for targets: ${n.map(({target:r})=>`- '${r}'`).join(` `)} All targets must have an export when multiple targets are present.`);let o=i.filter(r=>!r.export.match(/^[a-z0-9-]+$/));if(o.length>0){let r=[],s=o.map(a=>`'${a.export}'`);throw r.push(`Invalid export names: ${s.join(", ")}. The TOML's exports must be kebab-case (lowercase, hyphen or numbers) to comply with WebAssembly's Component Model. JavaScript exports with camelCase names are automatically mapped to kebab-case Wasm exports. `),r.push("Suggested TOML changes:"),o.forEach(a=>{let c=a.export;r.push(`- Change export for '${a.target}' to '${mn(c)}'.`)}),new Error(r.join(` `))}return i.map(r=>r.export)}u();function ar(e,t){return async n=>{let i=await e.appsForOrg(t,n);return{apps:i.apps,hasMorePages:i.hasMorePages}}}u();var Lp=Zi({cmd_app_warning_api_key_deprecation_displayed:!1}),q=Lp;u();u();import{deflate as jp}from"node:zlib";import{promisify as Np}from"node:util";var Wp=Np(jp);async function Vp(e){let t=await F(e),n=Buffer.byteLength(t),o=(await Wp(Buffer.from(t))).byteLength;return{path:e,rawBytes:n,compressedBytes:o}}function pr(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(2)} MB`:`${(e/1024).toFixed(1)} KB`}async function cr(e){try{let{rawBytes:t,compressedBytes:n}=await Vp(e);return` (${pr(t)} original, ~${pr(n)} compressed)`}catch(t){return S(`Failed to get bundle size for ${e}: ${t}`),""}}u();u();import{createInterface as zp}from"readline";var Jp=[".git",".hg",".bzr",".svn","_darcs","CVS",".sublime-(project|workspace)",".DS_Store",".sass-cache","Thumbs.db","desktop.ini","config.yml","node_modules",".gitkeep",".shopifyignore","*.toml"];async function Le(e){let n=y(e.directory,".shopifyignore"),i=Jp.map(o=>y("*",o));if(H(n)){let o=await qp(n);i.push(...o)}return D("*/*",{absolute:!0,cwd:e.directory,ignore:i})}function qp(e){return new Promise((t,n)=>{let i=[],o=zp({input:Mi(e),crlfDelay:1/0});o.on("line",r=>{let s=r.trim();s.length>0&&!s.startsWith("#")&&i.push(s)}),o.on("close",()=>{t(i)}),o.on("error",r=>{n(r)})})}import{context as Kp,formatMessagesSync as lr}from"esbuild";var ur=qe(Pp(),1);async function Fn(e,t=process.env){let n=Yp(e,t),i=await Kp(n),o=await i.rebuild();Gp(o,e),await Hp(o,e.outputPath),await i.dispose()}async function dr(e,t){t.stdout.write(`Bundling theme extension ${e.localIdentifier}...`);let n=await Le(e);await Promise.all(n.map(function(i){let o=I(e.directory,i),r=y(e.outputPath,o);if(i!==r)return N(i,r)}))}async function Hp(e,t){if(!e?.metafile)return;let{dir:n,name:i}=vi(t),o=y(n,`${i}.metafile.json`);try{await B(o,JSON.stringify(e.metafile))}catch(r){ue(`Failed to write metafile to ${o}: ${r}`)}}function Gp(e,t){let n=e?.warnings??[],i=e?.errors??[];n.length>0&&lr(n,{kind:"warning"}).forEach(r=>{t.stdout.write(r)}),i.length>0&&lr(i,{kind:"error"}).forEach(r=>{t.stderr.write(r)})}function Yp(e,t=process.env){let n=me(t,(s,a)=>Ot.test(a)&&s),i={...e.env,...n},o=Object.keys(i||{}).reduce((s,a)=>({...s,[`process.env.${a}`]:JSON.stringify(i[a])}),{"process.env.NODE_ENV":JSON.stringify(e.environment)}),r={outfile:e.outputPath,stdin:e.stdin,bundle:!0,define:o,jsx:"automatic",logLevel:e.logLevel??"error",loader:{".esnext":"ts",".js":"jsx"},legalComments:"none",minify:e.minify,plugins:Zp(e.stdin.resolveDir,t),target:"es6",resolveExtensions:[".tsx",".ts",".js",".json",".esnext",".mjs",".ejs"]};if(e.sourceMaps&&(r.sourcemap=!0,r.sourceRoot=`${e.stdin.resolveDir}/src`),e.environment==="production"&&(r.metafile=!0),e.environment==="development"){let s=i[bn.disableMinificationOnDev];r.minify=!Ke(s),r.logLevel="silent"}return r}function Zp(e,t=process.env){let n=[ur.default.default()],i=Ke(t[bn.skipEsbuildReactDedeuplication]);if(e&&!i){let o;try{o=Si.resolve("react",{paths:[e]})}catch{S(`Unable to load React in ${e}, skipping React de-duplication`)}o&&(S(`Deduplicating React dependency for ${e}, using ${o}`),n.push(Qp(o)))}return n}function Qp(e){return{name:"shopify:deduplicate-react",setup({onResolve:t}){t({filter:/^react$/},n=>({path:e}))}}}u();var jt="# api_version: ";function Yf(e,t){return`${jt}${t} ${e}`}async function Xp(e){if(!await w(e)){S(`Could not determine api_version: schema file not found at ${e}.`);return}let n=(await F(e)).split(` `,1)[0];if(n.startsWith(jt))return n.slice(jt.length).trim();S(`Could not determine api_version from ${e}: missing '${jt}' marker on the first line.`)}async function fr({directory:e,localIdentifier:t,apiVersion:n}){let i=y(e,"schema.graphql"),o=await Xp(i);if(o!==void 0&&o!==n)throw new b(A`The ${v.cyan("schema.graphql")} file for ${v.cyan(t)} was generated for api_version ${v.yellow(o)} but your function is now on api_version ${v.yellow(n)}.`,A`Run ${v.genericShellCommand("shopify app function schema")} to refresh it.`)}var mr=qe(vp(),1);async function gr(e,t){t.stdout.write(`Bundling UI extension ${e.localIdentifier}...`);let n=t.app.dotenv?.variables??{};t.appURL&&(n.APP_URL=t.appURL);let i=t.buildDirectory??"",o=y(e.directory,i,e.outputRelativePath),{main:r,assets:s}=e.getBundleExtensionStdinContent(),a=performance.now();try{await Fn({minify:!0,outputPath:o,stdin:{contents:r,resolveDir:e.directory,loader:"tsx"},environment:t.environment,env:n,stderr:t.stderr,stdout:t.stdout,sourceMaps:e.isSourceMapGeneratingExtension}),s&&await Promise.all(s.map(async l=>{await Fn({minify:!0,outputPath:y(P(o),l.outputFileName),stdin:{contents:l.content,resolveDir:e.directory,loader:"tsx"},environment:t.environment,env:n,stderr:t.stderr,stdout:t.stdout})}))}catch(l){let f=l.message??"Unknown error occurred",_=new b(`Failed to bundle extension ${e.localIdentifier}. Please check the extension source code for errors.`,f);throw _.errors=l.errors,_}await e.buildValidation({outputPath:o});let c=Math.round(performance.now()-a),d=await cr(o);return t.stdout.write(`${e.localIdentifier} successfully built in ${c}ms${d}`),o}async function yr(e,t){let n=y(e.directory,".build-lock"),i;try{i=await mr.default.lock(e.directory,{retries:20,lockfilePath:n})}catch(o){throw S(`Failed to acquire function build lock: ${o.message}`),new b("Failed to build function.","This is likely due to another in-progress build.",["Ensure there are no other function builds in-progress.","Delete the `.build-lock` file in your function directory."])}try{let o=e.configuration,r=e.outputPath,s=o.build?.path??e.outputRelativePath;e.outputPath=y(e.directory,s),await fr({directory:e.directory,localIdentifier:e.localIdentifier,apiVersion:o.api_version}),e.isJavaScript?await ec(e,t):await tc(e,t);let a=e.configuration.build?.wasm_opt;H(e.outputPath)&&a&&await or(e.outputPath),H(e.outputPath)&&await rr(e.outputPath);let c=y(e.directory,e.outputRelativePath);H(e.outputPath)&&r!==e.outputPath&&r!==c&&P(r)!==P(e.outputPath)&&await Mn(e.outputPath,r)}catch(o){if(o instanceof b)throw o;let r=o.message??"Unknown error occurred",s=new b("Failed to build function.",r);throw s.errors=o.errors,s}finally{await i()}}async function Mn(e,t){S(`Converting WASM from ${e} to base64 in ${t}`);let n=await F(e,{encoding:"base64"});await wt(t),await B(t,n)}async function ec(e,t){return e.buildCommand?(e.typegenCommand&&await st(e,t),hr(e.buildCommand,e,t)):er(e,t)}async function tc(e,t){if(!e.buildCommand)throw t.stderr.write(`The function extension ${e.localIdentifier} doesn't have a build command or it's empty`),t.stderr.write(` Edit the shopify.function.extension.toml configuration file and set how to build the extension. [build] command = "{COMMAND}" Note that the command must output a dist/index.wasm file. `),new V;return e.typegenCommand&&await st(e,t),hr(e.buildCommand,e,t)}async function hr(e,t,n){let i=e.split(" ");n.stdout.write(`Building function ${t.localIdentifier}...`),await ge(i[0],i.slice(1),{stdout:n.stdout,stderr:n.stderr,cwd:t.directory,signal:n.signal})}u();var _r="shopify.app*.toml",nc=/^shopify\.app(\.[-\w]+)?\.toml$/,ic="*.extension.toml",oc="shopify.web.toml",xr="extensions/*",br="**/node_modules/**",rc=".env*",at=class e{static async load(t){let n=await sc(t),i=[],o=await ac(n,i);if(o.length===0)throw new b(`Could not find a Shopify app TOML file in ${n}`);let r=new Set;for(let x of o){let C=x.content.extension_directories;if(Array.isArray(C))for(let E of C)r.add(E);else r.add(xr)}let s=await pc(n,[...r],i),a=new Set;for(let x of o){let C=x.content.web_directories;if(Array.isArray(C))for(let E of C)a.add(E)}let c=await cc(n,a.size>0?[...a]:void 0,i),d=y(n,"package.json"),l=await w(d),f=l?await Tt(n):"unknown",_=l?await Hi(d):{},g=l?await Gi(n):!1,m=await lc(n),h=await uc(n);return new e({directory:n,packageManager:f,nodeDependencies:_,usesWorkspaces:g,appConfigFiles:o,extensionConfigFiles:s,webConfigFiles:c,dotenvFiles:m,hiddenConfigRaw:h,errors:i})}constructor(t){this.directory=t.directory,this.packageManager=t.packageManager,this.nodeDependencies=t.nodeDependencies,this.usesWorkspaces=t.usesWorkspaces,this.appConfigFiles=t.appConfigFiles,this.extensionConfigFiles=t.extensionConfigFiles,this.webConfigFiles=t.webConfigFiles,this.dotenvFiles=t.dotenvFiles,this.hiddenConfigRaw=t.hiddenConfigRaw,this.errors=t.errors}appConfigByName(t){return this.appConfigFiles.find(n=>T(n.path)===t)}appConfigByClientId(t){return this.appConfigFiles.find(n=>n.content.client_id===t)}get defaultAppConfig(){return this.appConfigByName(z.app)}};async function sc(e){let t=await te(async n=>{if((await D(y(n,_r))).length>0)return n},{cwd:e,type:"directory"});if(!t)throw new b(`Could not find a Shopify app configuration file. Looked in ${e} and parent directories.`);return t}async function ac(e,t){let n=y(e,_r),o=(await D(n)).filter(r=>nc.test(T(r)));return Dn(o,t)}async function pc(e,t,n){let o=(t.length>0?t:[xr]).map(s=>y(e,s,ic));o.push(`!${y(e,br)}`);let r=await D(o);return Dn(r,n)}async function cc(e,t,n){let o=(t??["**"]).map(s=>y(e,s,oc));o.push(`!${y(e,br)}`);let r=await D(o);return Dn(r,n)}async function Dn(e,t){let n=[];return await Promise.all(e.map(async i=>{try{n.push(await U.read(i))}catch(o){let r=o instanceof tt?o:new tt(i,`Failed to read ${i}`),s=new U(i,{});s.errors.push(r),n.push(s),t.push(r)}})),n}async function lc(e){let t=y(e,rc),i=(await D(t,{dot:!0})).filter(s=>{let a=T(s);return a===".env"||/^\.env\.[\w-]+$/.test(a)}),o=await Promise.all(i.map(async s=>{try{let a=await fo(s);return[T(s),a]}catch{return}})),r=new Map;for(let s of o)s&&r.set(s[0],s[1]);return r}async function uc(e){let t=y(e,z.hiddenFolder,z.hiddenConfig);try{if(await w(t)){let n=await F(t);return JSON.parse(n)}}catch{}return{}}u();u();u();u();function dc(e,t){return t}async function Nt(e,t,n){let i={};try{let s=await F(e);i=JSON.parse(s)}catch{}let o={[t]:n},r=fe(i,o,dc);await B(e,JSON.stringify(r,null,2))}var fc=p.array(p.string()).optional().transform(mc).transform(gc);function mc(e){return e?.map(t=>t.replace(/[\/\\]+$/,""))}function gc(e){return e?.map(t=>t.replace(/([^\*])\*$/,"$1**"))}var pt=p.object({client_id:p.string(),build:p.object({automatically_update_urls_on_dev:p.boolean().optional(),dev_store_url:p.string().optional(),include_config_on_deploy:p.boolean().optional()}).optional(),extension_directories:fc,web_directories:p.array(p.string()).optional()}).passthrough();function Sr(e,t=!0){let n=e.reduce((i,o)=>o.contributeToAppConfigurationSchema(i),pt);return t?n.passthrough():e.length>0?n.strict():n}function Rn(e){return e.access_scopes?.scopes??""}function Vt(e){let t=Rn(e);return t.length?t.split(",").map(n=>n.trim()):[]}function yc(e){return y(e,z.hiddenFolder,z.hiddenConfig)}function On(e){let t=Object.keys(pt.shape).concat("organization_id");return Object.keys(e).filter(n=>!t.includes(n))}var Cr=p.preprocess(Cn,p.string()),wr=p.object({auth_callback_path:p.union([Cr,Cr.array()]).optional(),webhooks_path:p.preprocess(Cn,p.string()).optional(),port:p.number().max(65536).min(0).optional(),commands:p.object({build:p.string().optional(),predev:p.string().optional(),dev:p.string()}),name:p.string().optional(),hmr_server:p.object({http_paths:p.string().array()}).optional()}),Er=p.enum(["frontend","backend","background"]).default("frontend"),Pr=p.union([wr.extend({roles:p.array(Er)}),wr.extend({type:Er})]),Wt=class{constructor({name:t,directory:n,configPath:i,configuration:o,webs:r,modules:s,dotenv:a,errors:c,specifications:d,configSchema:l,remoteFlags:f,hiddenConfig:_,devApplicationURLs:g}){this.idEnvironmentVariableName="SHOPIFY_API_KEY";this.name=t,this.directory=n,this.configPath=i,this.configuration=o,this.webs=r,this.dotenv=a,this.realExtensions=s,this.errors=c??new lt,this.specifications=d,this.configSchema=l??pt,this.remoteFlags=f??[],this._hiddenConfig=_,g&&this.setDevApplicationURLs(g)}get allExtensions(){return this.includeConfigOnDeploy===!1?this.nonConfigExtensions:this.realExtensions}get nonConfigExtensions(){return this.realExtensions.filter(t=>!t.isAppConfigExtension)}get draftableExtensions(){return this.realExtensions.filter(t=>t.isUUIDStrategyExtension||t.specification.identifier===Bt)}setDevApplicationURLs(t){this.patchAppConfiguration(t),this.realExtensions.forEach(n=>n.patchWithAppDevURLs(t))}async manifest(t){let n=await Promise.all(this.realExtensions.map(async i=>{let o=await i.deployConfig({apiKey:String(this.configuration.client_id??""),appConfiguration:this.configuration});return{type:i.externalType,handle:i.handle,uid:i.uid,uuid:t?.extensions[i.localIdentifier],assets:i.uid,target:i.contextValue,config:o??{}}}));return{name:this.name,handle:"",modules:Pe(n)}}get hiddenConfig(){return this._hiddenConfig}getLogsDir(){return y(this.directory,".shopify","logs")}async updateHiddenConfig(t){if(!this.configuration.client_id)return;this._hiddenConfig=fe(this.hiddenConfig,t);let n=yc(this.directory);await Nt(n,String(this.configuration.client_id),this.hiddenConfig)}async preDeployValidation(){this.validateWebhookLegacyFlowCompatibility();let t=this.allExtensions.filter(i=>i.isFunctionExtension&&i.configuration.ui?.handle);if(t.length>0){let i=hc(t,this.allExtensions);if(i)throw new b("Invalid function configuration",i.join(` `))}let n=this.allExtensions.filter(i=>i.isEditorExtensionCollection);if(n.length>0){let i=_c(n,this.allExtensions);if(i)throw new b("Invalid editor extension collection configuration",i.join(` `))}await Promise.all(this.allExtensions.map(i=>i.preDeployValidation()))}extensionsForType(t){return this.allExtensions.filter(n=>n.type===t.identifier||n.type===t.externalIdentifier)}updateExtensionUUIDS(t){this.allExtensions.forEach(n=>{n.devUUID=t[n.localIdentifier]??n.devUUID})}appIsLaunchable(){let t=this.webs.find(i=>re(i,"frontend")),n=this.webs.find(i=>re(i,"backend"));return!!(t??n)}get appIsEmbedded(){return this.configuration.embedded}creationDefaultOptions(){return{isLaunchable:this.appIsLaunchable(),scopesArray:Vt(this.configuration),name:this.name,isEmbedded:this.appIsEmbedded,directory:this.directory}}removeExtension(t){this.realExtensions=this.realExtensions.filter(n=>n.uid!==t)}async generateExtensionTypes(){let t=new Map;await Promise.all(this.allExtensions.map(n=>n.contributeToSharedTypeFile(t))),t.forEach((n,i)=>{let o=H(i);if(n.size===0){o&&Fi(i);return}let r=o?ce(i).toString():"",s=[`import '@shopify/ui-extensions'; `,...Array.from(n)].join(` `);r!==s&&ki(i,s)})}get includeConfigOnDeploy(){return this.configuration.build?.include_config_on_deploy}patchAppConfiguration(t){this.devApplicationURLs=t,this.configuration.application_url=t.applicationUrl,t.appProxy&&(this.configuration.app_proxy={url:t.appProxy.proxyUrl,subpath:t.appProxy.proxySubPath,prefix:t.appProxy.proxySubPathPrefix}),this.configuration.auth?.redirect_urls&&(this.configuration.auth.redirect_urls=t.redirectUrlWhitelist)}validateWebhookLegacyFlowCompatibility(){let t=this.configuration.webhooks?.subscriptions?.some(i=>i.topics&&i.topics.length>0)??!1,n=this.configuration.access_scopes?.use_legacy_install_flow===!0;if(t&&n)throw new b("App-specific webhook subscriptions are not supported when use_legacy_install_flow is enabled.",`To use app-specific webhooks, you need to: 1. Remove 'use_legacy_install_flow = true' from your configuration 2. Run 'shopify app deploy' to sync your scopes with the Developer Dashboard Alternatively, continue using shop-specific webhooks with the legacy install flow. Learn more: https://shopify.dev/docs/apps/build/authentication-authorization/app-installation`)}};function hc(e,t){let n=[];return e.forEach(i=>{let o=i.configuration.ui.handle,r=vr(t,o);r?r.type!=="ui_extension"&&n.push(`[${i.name}] - Local app must contain one extension of type 'ui_extension' and handle '${o}'`):n.push(`[${i.name}] - Local app must contain a ui_extension with handle '${o}'`)}),n.length>0?n:void 0}function _c(e,t){let n=[],i=["ui_extension"];return e.forEach(o=>{o.configuration.inCollection.forEach(r=>{let s=vr(t,r.handle);s?i.includes(s.specification.identifier)?s.specification.identifier==="ui_extension"&&s.configuration.extension_points.forEach(c=>{c.target.startsWith("admin.")&&n.push(`[${o.handle}] editor extension collection: Remove extension '${s.configuration.handle}' with target '${c.target}' from this collection. This extension target is not supported in collections.`)}):n.push(`[${o.handle}] editor extension collection: Remove extension of type '${s.specification.identifier}' from this collection. This extension type is not supported in collections.`):n.push(`[${o.handle}] editor extension collection: Add extension with handle '${r.handle}' to local app. Local app must include extension with handle '${r.handle}'.`)})}),n.length>0?n:void 0}function vr(e,t){return e.find(n=>n.handle===t)}async function $m(e){let t=e.dependency;if(t)return ct(t,e.directory)}async function ct(e,t){let n=e.replace("-react","").split("/"),i=y("node_modules",n[0],n[1],"package.json"),o=await te(i,{cwd:t,type:"file",allowSymlinks:!0});if(!o)return"not_found";o=await Ge(o);let r=await Yi(o);return r.version?{name:e,version:r.version}:"not_found"}u();function xc(e){if(!e?.length)return null;let t=null,n=-1;for(let i of e){if(!i.issues?.length)continue;let o=0,r=0,s=0;for(let c of i.issues)c.message?.includes("Required")||c.message?.includes("required")?o++:c.message?.includes("Expected")&&c.message?.includes("received")?r++:s++;let a;o>0?a=1e3-o*10-r-s:r>0?a=100-r*5-s:a=50-s,a>n&&(n=a,t=i)}return t}function Ar(e){let t=[];for(let n of e)if(n.code==="invalid_union"&&n.unionErrors){let i=xc(n.unionErrors);if(i?.issues?.length)for(let o of i.issues)t.push({path:o.path,message:o.message,code:n.code});else t.push({path:n.path,message:n.message??"Configuration doesn't match any expected format",code:n.code})}else t.push({path:n.path,message:n.message??"Unknown error",code:n.code});return t}u();var Ir=/^shopify\.app(\.[-\w]+)?\.toml$/;function X(e){return e?zt(e)?e:`shopify.app.${j(e)}.toml`:z.app}function ut(e){return T(e).match(Ir)?.[1]?.slice(1)}function zt(e){return!!Ir.test(e)}u();u();u();u();u();u();u();async function je(e,t,n){let[i,o]=await Promise.all([Ge(e),Ge(t)]),r=I(o,i);if(r.split(/[/\\]/,1)[0]===".."||Pi(r))throw new b(`Asset path '${n}' resolves outside the app directory.`,`Asset sources must be inside the app folder. Resolved to: ${i}`)}async function kr(e){let{key:t,baseDir:n,outputDir:i,context:o,appDirectory:r,destination:s,usedBasenames:a=new Set,preserveFilePaths:c=!1}=e,{stdout:d}=o.options,l=Jt(o.extension.configuration,t),f;typeof l=="string"?f=[l]:Array.isArray(l)?f=l.filter(x=>typeof x=="string"):f=[];for(let x of f)if(x.trim()==="")throw new b(`'${t}' can't be empty.`);if(f.length===0)return S(`No value for configKey '${t}', skipping `,d),{filesCopied:0,pathMap:new Map};let _=s?y(i,s):i,g=[...new Set(f)],m=new Map,h=0;for(let x of g){let C=y(n,x);if(!await w(C))throw new Error(A`Couldn't find ${v.path(C)}\n Please check the path '${x}' in your configuration`.value);await je(C,r,x);let M=await de(C),Y=_;if(M){let K=await D(["**/*"],{cwd:C,absolute:!1}),ae=K.map(Ee=>I(i,y(Y,Ee)));if(c)for(let Ee of K)Tr(T(Ee),x,a);await vt(C,Y),d.write(`Included '${x}' `);for(let Ee of K)a.add(T(Ee));m.set(x,ae),h+=K.length}else{await Z(Y);let K=T(C),ae;c?(Tr(K,x,a),ae=K):ae=bc(K,a),a.add(ae);let Ee=I(i,y(Y,ae)),Cp=y(Y,ae);await N(C,Cp),d.write(`Included '${x}' `),m.set(x,Ee),h+=1}}return{filesCopied:h,pathMap:m}}function Tr(e,t,n){if(n.has(e))throw new b(`File collision: '${e}' from '${t}' would overwrite a file copied from a different source. Rename or relocate the conflicting file.`)}function bc(e,t){if(!t.has(e))return e;let n=_t(e),i=n?e.slice(0,-n.length):e,o=1e3,r=1;for(;t.has(`${i}-${r}${n}`);)if(r++,r>o)throw new Error(`Unable to find unique basename for '${e}' after ${o} attempts`);return`${i}-${r}${n}`}function Un(e){return e.split(".").map(t=>{let n=t.endsWith("[]");return{name:n?t.slice(0,-2):t,flatten:n}})}function Jt(e,t){let n=e;for(let{name:i,flatten:o}of Un(t)){if(n==null)return;if(Array.isArray(n)){let r=n.map(s=>s!==null&&typeof s=="object"?s[i]:void 0).filter(s=>s!==void 0);n=r.length>0?r:void 0}else if(typeof n=="object")n=n[i];else return;if(o){if(!Array.isArray(n))return;n=n.flat(1)}}return n}function Ln(e){return _t(e)?P(e):e}async function Fr(e,t,n,i){let{extension:o,options:r}=t,s=[],a=[];for(let l of e)typeof l.anchor=="string"&&typeof l.groupBy=="string"?s.push(l):a.push(l);if(s.length===0&&a.length===0&&i.length===0)return;let c={};for(let l of a){let f=Ec(l.key),_=Jt(o.configuration,l.key);_!=null&&(c[f]=qt(_,n))}let d=new Map;for(let l of s){let f=`${l.anchor}||${l.groupBy}`,_=d.get(f);_?_.push(l):d.set(f,[l])}for(let l of d.values()){let{anchor:f,groupBy:_}=l[0],g=Jt(o.configuration,f);if(Array.isArray(g))for(let m of g){if(m===null||typeof m!="object"||Array.isArray(m))continue;let h=m,x=h[_];if(typeof x!="string")continue;let C=l.map(Y=>{let K=Cc(Y.key,f),ae=Bn(h,K);return qt(ae,n)});C.some($n)&&r.stdout.write(`Warning: manifest entry '${x}' contains unresolved paths \u2014 source files may be missing `);let M=c[x]??{};c[x]=wc([M,...C])}}if(i.length>0&&(c.files=i),Object.keys(c).length===0){r.stdout.write(`Warning: no manifest entries produced \u2014 skipping manifest.json `);return}await jn(t,c)}async function jn(e,t){let n=Ln(e.extension.outputPath),i=y(n,"manifest.json");await w(n)||await Z(n);let o={};if(await w(i))try{let r=await F(i);o=JSON.parse(r)}catch{S(`Warning: could not parse existing manifest.json, starting fresh `,e.options.stdout)}for(let[r,s]of Object.entries(t)){let a=o[r];a&&typeof a=="object"&&!Array.isArray(a)&&typeof s=="object"&&!Array.isArray(s)?o[r]={...a,...s}:o[r]=s}await B(i,JSON.stringify(o,null,2)),S(`Updated manifest.json in ${n} `,e.options.stdout)}function Cc(e,t){if(t===e)return"";let n=`${t}.`;return e.startsWith(n)?e.slice(n.length):e}function Bn(e,t){if(t==="")return e;let n=Un(t),[i,...o]=n;if(!i)return e;let r=o.map(a=>`${a.name}${a.flatten?"[]":""}`).join("."),s=e[i.name];if(i.flatten){if(!Array.isArray(s))return{[i.name]:s};let a=s.map(c=>r?Bn(c,r):c);return{[i.name]:a}}return r&&s!==null&&s!==void 0&&typeof s=="object"&&!Array.isArray(s)?{[i.name]:Bn(s,r)}:{[i.name]:s}}function wc(e){return Object.assign({},...e)}function qt(e,t){if(typeof e=="string")return(e.startsWith(".")||e.includes("/")||e.includes("\\")||t.has(e)?t.get(e):void 0)??e;if(Array.isArray(e))return e.map(n=>qt(n,t));if(e!==null&&typeof e=="object"){let n={};for(let[i,o]of Object.entries(e))n[i]=qt(o,t);return n}return e}function Ec(e){let t=e.split(".").at(-1)??e;return t.endsWith("[]")?t.slice(0,-2):t}function $n(e){return typeof e=="string"?e.startsWith("./")||e.startsWith("../"):Array.isArray(e)?e.some($n):e!==null&&typeof e=="object"?Object.values(e).some($n):!1}u();async function Mr(e,t){let{sourceDir:n,outputDir:i,patterns:o,ignore:r,appDirectory:s,sourceDirConfigValue:a}=e;if(!await w(n))return{filesCopied:0,outputPaths:[]};await je(n,s,a);let c=await D(o,{absolute:!0,cwd:n,ignore:r});if(c.length===0)return{filesCopied:0,outputPaths:[]};await Z(i);let d=c,l=await Promise.all(d.map(async g=>{let m=I(n,g),h=y(i,m);return I(i,h).startsWith("..")?(t.stdout.write(`Warning: skipping '${g}' - resolved destination is outside the output directory `),{count:0,path:null}):g===h?{count:0,path:null}:(await Z(P(h)),await N(g,h),{count:1,path:m})})),f=l.reduce((g,m)=>g+m.count,0),_=l.flatMap(g=>g.path===null?[]:[g.path]);return t.stdout.write(`Included ${f} file(s) `),{filesCopied:f,outputPaths:_}}u();async function Dr(e,t){let{source:n,destination:i,baseDir:o,outputDir:r,appDirectory:s}=e,a=y(o,n);if(!await w(a))throw new Error(`Source does not exist: ${a}`);await je(a,s,n);let c=await de(a),d,l;if(i===void 0?(d=y(r,T(a)),l=`Included ${n} `):(d=y(r,i),l=`Included ${n} `),c){let f=await D(["**/*"],{cwd:a,absolute:!1});await vt(a,d),t.stdout.write(l);let _=I(r,d),g=_?f.map(m=>y(_,m)):f;return{filesCopied:f.length,outputPaths:g}}return await Z(P(d)),await N(a,d),t.stdout.write(l),{filesCopied:1,outputPaths:[I(r,d)]}}var Sc=p.object({type:p.literal("pattern"),baseDir:p.string().optional(),include:p.array(p.string()).default(["**/*"]),ignore:p.array(p.string()).optional(),destination:p.string().optional()}),Pc=p.object({type:p.literal("static"),source:p.string(),destination:p.string().optional()}),vc=p.object({type:p.literal("configKey"),key:p.string(),destination:p.string().optional(),anchor:p.string().optional(),groupBy:p.string().optional(),preserveFilePaths:p.boolean().default(!1)}),Ac=p.discriminatedUnion("type",[Sc,Pc,vc]),Ic=p.object({inclusions:p.array(Ac),generatesAssetsManifest:p.boolean().default(!1)}).strict().superRefine((e,t)=>{for(let[n,i]of e.inclusions.entries())if(i.type==="configKey"){let o=i.anchor!==void 0,r=i.groupBy!==void 0;o!==r&&t.addIssue({code:p.ZodIssueCode.custom,message:"`anchor` and `groupBy` must both be set or both be omitted",path:["inclusions",n]})}});async function Rr(e,t){let n=Ic.parse(e.config),{extension:i,options:o}=t,r=Ln(i.outputPath),s=o.app.directory,a=new Map,c=new Set,d=0;for(let g of n.inclusions){if(g.type!=="configKey")continue;let m=E=>o.stdout.write(E),h=g.destination?ln(g.destination,m):void 0,x=h===""?void 0:h,C=await kr({key:g.key,baseDir:i.directory,outputDir:r,context:t,appDirectory:s,destination:x,usedBasenames:c,preserveFilePaths:g.preserveFilePaths});C.pathMap.forEach((E,M)=>a.set(M,E)),d+=C.filesCopied}let l=await Promise.all(n.inclusions.filter(g=>g.type!=="configKey").map(async g=>{let m=C=>o.stdout.write(C),h=g.destination?ln(g.destination,m):void 0,x=h===""?void 0:h;if(g.type==="pattern"){let C=g.baseDir?y(i.directory,g.baseDir):i.directory,E=x?y(r,x):r,M=await Mr({sourceDir:C,outputDir:E,patterns:g.include,ignore:g.ignore??[],appDirectory:s,sourceDirConfigValue:g.baseDir??"."},o),Y=x?M.outputPaths.map(K=>y(x,K)):M.outputPaths;return{filesCopied:M.filesCopied,outputPaths:Y}}if(g.type==="static")return Dr({source:g.source,destination:x,baseDir:i.directory,outputDir:r,appDirectory:s},o)})),f=n.generatesAssetsManifest?l.flatMap(g=>g?.outputPaths??[]):[],_=[d,...l.map(g=>g?.filesCopied??0)];if(n.generatesAssetsManifest){let g=n.inclusions.filter(m=>m.type==="configKey");await Fr(g,t,a,f)}return{filesCopied:_.reduce((g,m)=>g+(m??0),0)}}u();u();var _e=qe(wp(),1);function Tc(e,t,n){let i=_e.path.fsPath(e),s=ce(i).toString().split(` `).slice(t,n+1),a=s.length===1;return s.map((c,d)=>{let l=t+d+1,f=a?c.trim():c;return`${l} ${f}`}).join(` `)}function kc(e){switch(e){case _e.Severity.ERROR:return{error:` [error]:`};case _e.Severity.WARNING:return{warn:` [warning]:`};case _e.Severity.INFO:return{info:` [info]:`}}}function Fc(e){return e.map((n,i)=>{let{message:o,uri:r,start:s,end:a,check:c,severity:d}=n,l=Tc(r,s.line,a.line),f=i===e.length-1?"":` `;return[kc(d),{bold:c},{subdued:` ${o}`},` ${l}`,f]}).flat()}async function Or(e){let n=await(0,_e.check)(e,"theme-check:theme-app-extension"),i=Fc(n);return so(i)}async function Ur(e,t){let{extension:n,options:i}=t;i.stdout.write("Running theme check on your Theme app extension...");let o=await Or(n.directory);o&&i.stdout.write(o)}u();async function Br(e,t){let{extension:n,options:i}=t;i.stdout.write(`Bundling theme extension ${n.localIdentifier}...`);let o=await Le(n);return await Promise.all(o.map(async r=>{let s=I(n.directory,r),a=y(n.outputPath,s);r!==a&&await N(r,a)})),{filesCopied:o.length}}u();async function $r(e,t){let n=t.extension.configuration;t.options.buildDirectory=e.config?.bundleFolder??void 0;let i=await gr(t.extension,t.options),o=P(i),r=e.config?.bundleFolder?y(P(t.extension.outputPath),e.config.bundleFolder):P(t.extension.outputPath);if(pe(o)===pe(r)||(await N(o,r),!e.config?.generatesAssetsManifest)||!Array.isArray(n.extension_points))return;let s=n.extension_points.filter(c=>typeof c=="object"&&c.build_manifest),a=Mc(s,e.config?.bundleFolder);Object.keys(a).length>0&&await jn(t,a)}function Mc(e,t){let n={};for(let{target:i,build_manifest:o}of e){if(!o?.assets)continue;let r={};for(let[s,a]of Object.entries(o.assets))a?.filepath&&(r[s]=t?y(t,a.filepath):a.filepath);Object.keys(r).length>0&&(n[i]=r)}return n}u();async function Lr(e,t){return yr(t.extension,t.options)}u();async function jr(e,t){let{extension:n}=t;if(await w(n.outputPath)&&await de(n.outputPath))throw new Error(`outputPath '${n.outputPath}' is a directory \u2014 expected a file path for the tax stub`);await wt(n.outputPath),await B(n.outputPath,"(()=>{})();")}async function Nr(e,t){switch(e.type){case"include_assets":return Rr(e,t);case"build_theme":return Ur(e,t);case"bundle_theme":return Br(e,t);case"bundle_ui":return $r(e,t);case"build_function":return Lr(e,t);case"create_tax_stub":return jr(e,t);default:throw new Error(`Unknown build step type: ${e.type}`)}}async function Wr(e,t){let n=Date.now();try{let i=await Nr(e,t);return{id:e.id,success:!0,duration:Date.now()-n,output:i}}catch(i){let o=i;if(e.continueOnError)return t.options.stderr.write(`Warning: Step "${e.name}" failed but continuing: ${o.message} `),{id:e.id,success:!1,duration:Date.now()-n,error:o};throw o.message=`Build step "${e.name}" failed: ${o.message}`,o}}var Dc=["**/node_modules/**","**/.git/**","**/*.test.*","**/dist/**","**/*.swp","**/generated/**","**/.gitignore"],Kt=class{get graphQLType(){return(this.specification.graphQLType??this.specification.identifier).toUpperCase()}get type(){return this.specification.identifier}get humanName(){return this.specification.externalName}get name(){return this.configuration.name??this.specification.externalName}get dependency(){return this.specification.dependency}get externalType(){return this.specification.externalIdentifier}get surface(){return this.specification.surface}get isPreviewable(){return this.features.includes("ui_preview")}get isThemeExtension(){return this.features.includes("theme")}get isFunctionExtension(){return this.features.includes("function")}get isESBuildExtension(){return this.features.includes("esbuild")}get isSourceMapGeneratingExtension(){return this.features.includes("generates_source_maps")}get isAppConfigExtension(){return this.specification.experience==="configuration"}get isFlow(){return this.specification.identifier.includes("flow")}get isEditorExtensionCollection(){return this.specification.identifier==="editor_extension_collection"}get hasDeploySteps(){return this.specification.clientSteps?.some(t=>t.lifecycle==="deploy"&&t.steps.length>0)??!1}get features(){return this.specification.appModuleFeatures(this.configuration)}get outputFileName(){return T(this.outputRelativePath)}get outputRelativePath(){return this.specification.getOutputRelativePath?.(this)??""}constructor(t){this.configuration=t.configuration,this.configurationPath=t.configurationPath,this.entrySourceFilePath=t.entryPath??"",this.directory=t.directory,this.specification=t.specification,this.handle=this.buildHandle(),this.localIdentifier=this.handle,this.idEnvironmentVariableName=`SHOPIFY_${bt(this.localIdentifier)}_ID`,this.outputPath=y(this.directory,this.outputRelativePath),this.uid=this.buildUIDFromStrategy(),this.devUUID=`dev-${this.uid}`}get draftMessages(){if(this.isAppConfigExtension)return{successMessage:void 0,errorMessage:void 0};let t=`Draft updated successfully for extension: ${this.localIdentifier}`,n=`Error updating extension draft for ${this.localIdentifier}`;return{successMessage:t,errorMessage:n}}get isUUIDStrategyExtension(){return this.specification.uidStrategy==="uuid"}get isSingleStrategyExtension(){return this.specification.uidStrategy==="single"}get isDynamicStrategyExtension(){return this.specification.uidStrategy==="dynamic"}get outputPrefix(){return this.handle}isSentToMetrics(){return!this.isAppConfigExtension}isReturnedAsInfo(){return!this.isAppConfigExtension}async deployConfig({apiKey:t,appConfiguration:n}){let i=await this.specification.deployConfig?.(this.configuration,this.directory,t,void 0),o=this.specification.transformLocalToRemote?.(this.configuration,n),r=i??o??void 0;return r&&Object.keys(r).length>0?r:void 0}validate(){return this.specification.validate?this.specification.validate(this.configuration,this.configurationPath,this.directory):Promise.resolve(le(void 0))}preDeployValidation(){return this.specification.preDeployValidation?this.specification.preDeployValidation(this):Promise.resolve()}buildValidation({outputPath:t}){return this.specification.buildValidation?this.specification.buildValidation(this,t):Promise.resolve()}async keepBuiltSourcemapsLocally(t){if(!this.isSourceMapGeneratingExtension)return Promise.resolve();let i=(await D(`**/${this.handle}.js.map`,{cwd:t,absolute:!0,followSymbolicLinks:!1}))[0];if(i===void 0)return Promise.resolve();let o=y(this.directory,I(t,i));await St(i,o,{overwrite:!0}),S(`Source map for ${this.localIdentifier} created: ${o}`)}async publishURL(t){let n=await ji(),i=this.specification.partnersWebIdentifier;return`https://${n}/${t.orgId}/apps/${t.appId}/extensions/${i}/${t.extensionId}`}getOutputFolderId(t){return t??this.uid}getBundleExtensionStdinContent(){return this.specification.getBundleExtensionStdinContent?this.specification.getBundleExtensionStdinContent(this.configuration):{main:`import '.${this.entrySourceFilePath.replace(this.directory,"")}';`}}shouldFetchCartUrl(){return this.features.includes("cart_url")}hasExtensionPointTarget(t){return this.specification.hasExtensionPointTarget?.(this.configuration,t)??!1}get buildCommand(){return this.configuration.build?.command}get typegenCommand(){return this.configuration.build?.typegen_command}devSessionDefaultWatchPaths(){if(this.specification.identifier==="ui_extension"){let{main:t,assets:n}=this.getBundleExtensionStdinContent(),i=xn(t,this.directory),o=n?.flatMap(r=>xn(r.content,this.directory))??[];return i.concat(...o)}return[this.entrySourceFilePath]}get devSessionWatchConfig(){return this.specification.devSessionWatchConfig?this.specification.devSessionWatchConfig(this):this.isAppConfigExtension?{paths:[]}:void 0}async watchConfigurationPaths(){if(this.isAppConfigExtension)return[this.configurationPath];{let t=[];return await w(y(this.directory,"locales"))&&t.push(y(this.directory,"locales","**.json")),t.push(y(this.directory,"**.toml")),t}}get inputQueryPath(){return y(this.directory,"input.graphql")}get isJavaScript(){return!!(this.entrySourceFilePath.endsWith(".js")||this.entrySourceFilePath.endsWith(".ts"))}async build(t){let{clientSteps:n=[]}=this.specification,i={extension:this,options:t,stepResults:new Map},o=n.find(r=>r.lifecycle==="deploy")?.steps??[];for(let r of o){let s=await Wr(r,i);i.stepResults.set(r.id,s)}}async buildForBundle(t,n,i){this.outputPath=this.getOutputPathForDirectory(n,i),await this.build(t);let o=y(n,this.getOutputFolderId(i));await this.keepBuiltSourcemapsLocally(o)}async copyIntoBundle(t,n,i){let o=this.outputPath;this.outputPath=this.getOutputPathForDirectory(n,i),this.isThemeExtension?await dr(this,t):this.hasDeploySteps&&(S(`Will copy pre-built file from ${o} to ${this.outputPath}`),await w(o)&&(await N(o,this.outputPath),this.isFunctionExtension&&await Mn(this.outputPath,this.outputPath)))}getOutputPathForDirectory(t,n){let i=this.getOutputFolderId(n);return y(t,i,this.outputRelativePath)}get singleTarget(){let t=W(this.configuration,"targeting")??[];if(t.length===1)return t[0]?.target}get contextValue(){let t=this.singleTarget??"";return this.isFlow&&(t=this.configuration.handle??""),t}async bundleConfig({identifiers:t,developerPlatformClient:n,apiKey:i,appConfiguration:o}){let r=await this.deployConfig({apiKey:i,appConfiguration:o});if(!r)return;let s={config:JSON.stringify(r),context:this.contextValue,handle:this.handle},a=this.isUUIDStrategyExtension?t.extensions[this.localIdentifier]:t.extensionsNonUuidManaged[this.localIdentifier];return{...s,uid:this.uid,uuid:a,specificationIdentifier:n.toExtensionGraphQLType(this.graphQLType)}}async getDevSessionUpdateMessages(){if(this.specification.getDevSessionUpdateMessages)return this.specification.getDevSessionUpdateMessages(this.configuration)}patchWithAppDevURLs(t){this.specification.patchWithAppDevURLs&&this.specification.patchWithAppDevURLs(this.configuration,t)}async contributeToSharedTypeFile(t){await this.specification.contributeToSharedTypeFile?.(this,t)}watchPatterns(){let t=this.devSessionWatchConfig;return{paths:t?.paths??["**/*"],ignore:t?.ignore??Dc}}watchedFiles(){let t=[],{paths:n,ignore:i}=this.watchPatterns(),o=n.flatMap(r=>Oi(r,{cwd:this.directory,absolute:!0,followSymbolicLinks:!1,ignore:i}));if(t.push(...o.flat()),!this.devSessionWatchConfig){let r=this.scanImports();t.push(...r)}return[...new Set(t.map(r=>Se(r)))]}async rescanImports(){let t=this.cachedImportPaths;return this.cachedImportPaths=void 0,yo(),this.scanImports(),t!==this.cachedImportPaths}scanImports(){if(this.cachedImportPaths!==void 0)return this.cachedImportPaths;if(Ke(process.env.SHOPIFY_CLI_DISABLE_IMPORT_SCANNING))return this.cachedImportPaths=[],this.cachedImportPaths;try{let t=performance.now(),n=this.devSessionDefaultWatchPaths(),i=n.flatMap(a=>ho(a).map(c=>Se(pe(c))));this.cachedImportPaths=Ii(i)??[];let o=Math.round(performance.now()-t),r=_o(),s=r?` (cache: ${r.directImports} parsed, ${r.fileExists} stats)`:"";return S(`Import scan for "${this.handle}": ${n.length} entries, ${this.cachedImportPaths.length} files, ${o}ms${s}`),this.cachedImportPaths}catch(t){return S(`Failed to scan imports for extension ${this.handle}: ${t}`),this.cachedImportPaths=[],this.cachedImportPaths}}buildHandle(){switch(this.specification.uidStrategy){case"single":return this.specification.identifier;case"uuid":return this.configuration.handle??j(this.name??"");case"dynamic":if("topic"in this.configuration&&"uri"in this.configuration){let t=this.configuration,n=`${t.topic}${t.uri}${t.filter}`;return Ye(n).substring(0,Ut)}else return At(JSON.stringify(this.configuration))}}buildUIDFromStrategy(){switch(this.specification.uidStrategy){case"single":return this.specification.identifier;case"uuid":return this.configuration.uid??At(this.handle);case"dynamic":if("topic"in this.configuration&&"uri"in this.configuration){let t=this.configuration;return`${t.topic}::${t.filter}::${t.uri}`.substr