@mercurjs/cli 2.2.0-canary.5 → 2.2.0-canary.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,73 +1,42 @@
1
1
  #!/usr/bin/env node
2
- import {Command}from'commander';import*as R from'path';import R__default,{join,basename}from'path';import Pe from'prompts';import {z}from'zod';import Ot,{promises,existsSync,readFileSync,mkdirSync,writeFileSync,statSync}from'fs';import {cosmiconfig}from'cosmiconfig';import {loadConfig,createMatchPath}from'tsconfig-paths';import L from'fs-extra';import nt from'fast-glob';import {createHash}from'crypto';import nr from'deepmerge';import*as U from'fs/promises';import U__default,{writeFile,rm}from'fs/promises';import {homedir,tmpdir}from'os';import {Project,ScriptKind}from'ts-morph';import N from'kleur';import ti from'ora';import {execa}from'execa';import {detect}from'@antfu/ni';import {diffLines}from'diff';import {spawn,execSync}from'child_process';import {Readable}from'stream';import {pipeline}from'stream/promises';import Ct from'pg';import ks from'open';import {x as x$1}from'tar';import Ss from'terminal-link';import Is from'validate-npm-package-name';import Cs from'wait-on';import {builtinModules}from'module';import {generatePluginEntryModule}from'@mercurjs/dashboard-sdk';var Fe={version:"2.2.0-canary.5"};var Lt="MISSING_DIR_OR_EMPTY_PROJECT",S="MISSING_CONFIG",B="BUILD_MISSING_REGISTRY_FILE";var fo=z.enum(["registry:api","registry:vendor","registry:admin"]),Mt=z.object({path:z.string(),content:z.string().optional(),type:fo,target:z.string().optional()}),Ut=z.object({$schema:z.string().optional(),name:z.string(),title:z.string().optional(),author:z.string().min(2).optional(),description:z.string().optional(),dependencies:z.array(z.string()).optional(),devDependencies:z.array(z.string()).optional(),registryDependencies:z.array(z.string()).optional(),meta:z.record(z.string(),z.any()).optional(),docs:z.string().optional(),categories:z.array(z.string()).optional()}),T=Ut.extend({files:z.array(Mt)}),K=z.object({name:z.string(),homepage:z.string(),items:z.array(T)}),un=z.array(Ut),zt=T.pick({dependencies:true,devDependencies:true,files:true,docs:true}),go=z.union([z.string(),z.object({url:z.string(),params:z.record(z.string(),z.string()).optional(),headers:z.record(z.string(),z.string()).optional()})]),Bt=z.record(z.string().refine(e=>e.startsWith("@"),{message:"Registry names must start with @ (e.g., @mercurjs)"}),go);var Oe="https://registry.mercurjs.com/registry.json",Wt="https://registry.mercurjs.com/registry-item.json",he=process.env.REGISTRY_URL??"https://raw.githubusercontent.com/mercurjs/mercur/canary/packages/registry/r",I={"@mercurjs":`${he}/{name}.json`};var $={NOT_FOUND:"NOT_FOUND",UNAUTHORIZED:"UNAUTHORIZED",FORBIDDEN:"FORBIDDEN",FETCH_ERROR:"FETCH_ERROR",NOT_CONFIGURED:"NOT_CONFIGURED",INVALID_CONFIG:"INVALID_CONFIG",MISSING_ENV_VARS:"MISSING_ENV_VARS",LOCAL_FILE_ERROR:"LOCAL_FILE_ERROR",PARSE_ERROR:"PARSE_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",UNKNOWN_ERROR:"UNKNOWN_ERROR"},_=class extends Error{code;statusCode;context;suggestion;timestamp;cause;constructor(t,r={}){super(t),this.name="RegistryError",this.code=r.code||$.UNKNOWN_ERROR,this.statusCode=r.statusCode,this.cause=r.cause,this.context=r.context,this.suggestion=r.suggestion,this.timestamp=new Date,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor);}},ae=class extends _{constructor(r,o){let i=`The item at ${r} was not found. It may not exist at the registry.`;super(i,{code:$.NOT_FOUND,statusCode:404,cause:o,context:{url:r},suggestion:"Check if the item name is correct and the registry URL is accessible."});this.url=r;this.name="RegistryNotFoundError";}url},Ae=class extends _{constructor(r,o){let i=`You are not authorized to access the item at ${r}. If this is a remote registry, you may need to authenticate.`;super(i,{code:$.UNAUTHORIZED,statusCode:401,cause:o,context:{url:r},suggestion:"Check your authentication credentials and environment variables."});this.url=r;this.name="RegistryUnauthorizedError";}url},Le=class extends _{constructor(r,o){let i=`You are not authorized to access the item at ${r}. If this is a remote registry, you may need to authenticate.`;super(i,{code:$.FORBIDDEN,statusCode:403,cause:o,context:{url:r},suggestion:"Check your authentication credentials and environment variables."});this.url=r;this.name="RegistryForbiddenError";}url},Me=class extends _{constructor(r,o,i,s){let n=o?`Failed to fetch from registry (${o}): ${r}`:`Failed to fetch from registry: ${r}`,m=typeof s=="string"&&s?`${n} - ${s}`:n,p="Check your network connection and try again.";o===404?p="The requested resource was not found. Check the URL or item name.":o===500?p="The registry server encountered an error. Try again later.":o&&o>=400&&o<500&&(p="There was a client error. Check your request parameters.");super(m,{code:$.FETCH_ERROR,statusCode:o,cause:s,context:{url:r,responseBody:i},suggestion:p});this.url=r;this.responseBody=i;this.name="RegistryFetchError";}url;responseBody},Z=class extends _{constructor(r){let o=r?`Unknown registry "${r}". Make sure it is defined in agents.json as follows:
2
+ import {Command}from'commander';import*as v from'path';import v__default,{join,basename}from'path';import ft from'prompts';import {z}from'zod';import Et,{promises,existsSync,readFileSync,mkdirSync,writeFileSync,statSync}from'fs';import {cosmiconfig}from'cosmiconfig';import {loadConfig,createMatchPath}from'tsconfig-paths';import ut from'fs-extra';import Qe from'fast-glob';import Ds,{createHash}from'crypto';import Vt from'deepmerge';import*as $ from'fs/promises';import $__default,{writeFile,rm}from'fs/promises';import As,{homedir,tmpdir}from'os';import {Project,ScriptKind}from'ts-morph';import Re from'kleur';import Fo from'ora';import {execa}from'execa';import {detect}from'@antfu/ni';import {diffLines}from'diff';import {execSync}from'child_process';import {builtinModules}from'module';import {generatePluginEntryModule}from'@mercurjs/dashboard-sdk/vite';var vt={version:"2.2.0-canary.50"};var It="MISSING_DIR_OR_EMPTY_PROJECT",C="MISSING_CONFIG",A="BUILD_MISSING_REGISTRY_FILE";var Gr=z.enum(["registry:api","registry:vendor","registry:admin"]),bt=z.object({path:z.string(),content:z.string().optional(),type:Gr,target:z.string().optional()}),St=z.object({$schema:z.string().optional(),name:z.string(),title:z.string().optional(),author:z.string().min(2).optional(),description:z.string().optional(),dependencies:z.array(z.string()).optional(),devDependencies:z.array(z.string()).optional(),registryDependencies:z.array(z.string()).optional(),meta:z.record(z.string(),z.any()).optional(),docs:z.string().optional(),categories:z.array(z.string()).optional()}),T=St.extend({files:z.array(bt)}),Y=z.object({name:z.string(),homepage:z.string(),items:z.array(T)}),Sn=z.array(St),kt=T.pick({dependencies:true,devDependencies:true,files:true,docs:true}),Vr=z.union([z.string(),z.object({url:z.string(),params:z.record(z.string(),z.string()).optional(),headers:z.record(z.string(),z.string()).optional()})]),Ct=z.record(z.string().refine(e=>e.startsWith("@"),{message:"Registry names must start with @ (e.g., @mercurjs)"}),Vr);var _e="https://registry.mercurjs.com/registry.json",Pt="https://registry.mercurjs.com/registry-item.json",ue=process.env.REGISTRY_URL??"https://raw.githubusercontent.com/mercurjs/mercur/main/packages/registry/r",P={"@mercurjs":`${ue}/{name}.json`};var j={NOT_FOUND:"NOT_FOUND",UNAUTHORIZED:"UNAUTHORIZED",FORBIDDEN:"FORBIDDEN",FETCH_ERROR:"FETCH_ERROR",NOT_CONFIGURED:"NOT_CONFIGURED",INVALID_CONFIG:"INVALID_CONFIG",MISSING_ENV_VARS:"MISSING_ENV_VARS",LOCAL_FILE_ERROR:"LOCAL_FILE_ERROR",PARSE_ERROR:"PARSE_ERROR",VALIDATION_ERROR:"VALIDATION_ERROR",UNKNOWN_ERROR:"UNKNOWN_ERROR"},I=class extends Error{code;statusCode;context;suggestion;timestamp;cause;constructor(t,r={}){super(t),this.name="RegistryError",this.code=r.code||j.UNKNOWN_ERROR,this.statusCode=r.statusCode,this.cause=r.cause,this.context=r.context,this.suggestion=r.suggestion,this.timestamp=new Date,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor);}},re=class extends I{constructor(r,o){let s=`The item at ${r} was not found. It may not exist at the registry.`;super(s,{code:j.NOT_FOUND,statusCode:404,cause:o,context:{url:r},suggestion:"Check if the item name is correct and the registry URL is accessible."});this.url=r;this.name="RegistryNotFoundError";}url},Te=class extends I{constructor(r,o){let s=`You are not authorized to access the item at ${r}. If this is a remote registry, you may need to authenticate.`;super(s,{code:j.UNAUTHORIZED,statusCode:401,cause:o,context:{url:r},suggestion:"Check your authentication credentials and environment variables."});this.url=r;this.name="RegistryUnauthorizedError";}url},je=class extends I{constructor(r,o){let s=`You are not authorized to access the item at ${r}. If this is a remote registry, you may need to authenticate.`;super(s,{code:j.FORBIDDEN,statusCode:403,cause:o,context:{url:r},suggestion:"Check your authentication credentials and environment variables."});this.url=r;this.name="RegistryForbiddenError";}url},Fe=class extends I{constructor(r,o,s,n){let i=o?`Failed to fetch from registry (${o}): ${r}`:`Failed to fetch from registry: ${r}`,f=typeof n=="string"&&n?`${i} - ${n}`:i,c="Check your network connection and try again.";o===404?c="The requested resource was not found. Check the URL or item name.":o===500?c="The registry server encountered an error. Try again later.":o&&o>=400&&o<500&&(c="There was a client error. Check your request parameters.");super(f,{code:j.FETCH_ERROR,statusCode:o,cause:n,context:{url:r,responseBody:s},suggestion:c});this.url=r;this.responseBody=s;this.name="RegistryFetchError";}url;responseBody},J=class extends I{constructor(r){let o=r?`Unknown registry "${r}". Make sure it is defined in agents.json as follows:
3
3
  {
4
4
  "registries": {
5
5
  "${r}": "[URL_TO_REGISTRY]"
6
6
  }
7
- }`:'Unknown registry. Make sure it is defined in blocks.json under "registries".';super(o,{code:$.NOT_CONFIGURED,context:{registryName:r},suggestion:"Add the registry configuration to your blocks.json file. Consult the registry documentation for the correct format."});this.registryName=r;this.name="RegistryNotConfiguredError";}registryName},Q=class extends _{constructor(r,o){super(`Failed to read local registry file: ${r}`,{code:$.LOCAL_FILE_ERROR,cause:o,context:{filePath:r},suggestion:"Check if the file exists and you have read permissions."});this.filePath=r;this.name="RegistryLocalFileError";}filePath},C=class extends _{constructor(r,o){let i=`Failed to parse registry item: ${r}`;o instanceof z.ZodError&&(i=`Failed to parse registry item: ${r}
8
- ${o.issues.map(s=>` - ${s.path.join(".")}: ${s.message}`).join(`
9
- `)}`);super(i,{code:$.PARSE_ERROR,cause:o,context:{item:r},suggestion:"The registry item may be corrupted or have an invalid format. Please make sure it returns a valid JSON object."});this.item=r;this.parseError=o,this.name="RegistryParseError";}item;parseError},Ue=class extends _{constructor(r,o){let i=`Registry "${r}" requires the following environment variables:
10
-
11
- `+o.map(s=>` \u2022 ${s}`).join(`
12
- `);super(i,{code:$.MISSING_ENV_VARS,context:{registryName:r,missingVars:o},suggestion:"Set the required environment variables to your .env or .env.local file."});this.registryName=r;this.missingVars=o;this.name="RegistryMissingEnvironmentVariablesError";}registryName;missingVars},ze=class extends _{constructor(r){let o=`Invalid registry namespace: "${r}". Registry names must start with @ (e.g., @mercurjs).`;super(o,{code:$.VALIDATION_ERROR,context:{name:r},suggestion:"Use a valid registry name starting with @ or provide a direct URL to the registry."});this.name=r;this.name="RegistryInvalidNamespaceError";}name};var Be=class extends _{constructor(r,o){let i=`Invalid blocks.json configuration in ${r}.`;o instanceof z.ZodError&&(i=`Invalid blocks.json configuration in ${r}:
13
- ${o.issues.map(s=>` - ${s.path.join(".")}: ${s.message}`).join(`
14
- `)}`);super(i,{code:$.INVALID_CONFIG,cause:o,context:{cwd:r},suggestion:"Check your blocks.json file for syntax errors or invalid configuration. Run '@mercurjs/cli init' to regenerate a valid configuration."});this.cwd=r;this.name="ConfigParseError";}cwd};var W=z.object({$schema:z.string().optional(),aliases:z.object({api:z.string(),vendor:z.string(),admin:z.string()}),registries:Bt.optional()}).strict(),Vt=W.extend({resolvedPaths:z.object({cwd:z.string(),api:z.string(),vendor:z.string(),admin:z.string()})});async function de(e,t){return createMatchPath(t.absoluteBaseUrl,t.paths)(e,void 0,()=>true,[".ts",".tsx"])}var wo="packages/api/src",jo="apps/vendor/src",bo="apps/admin/src",Ro=cosmiconfig("blocks",{searchPlaces:["blocks.json"]});async function b(e){let t=await xo(e);return t?await st(e,t):null}async function st(e,t){t.registries={...t.registries||{},...I};let r=await loadConfig(e);if(r.resultType==="failed")throw new Error(`Failed to load tsconfig.json. ${r.message??""}`.trim());return Vt.parse({...t,resolvedPaths:{cwd:e,api:await de(t.aliases.api,r),vendor:await de(t.aliases.vendor,r),admin:await de(t.aliases.admin,r)}})}async function xo(e){try{let t=await Ro.search(e);if(!t)return null;let r=W.parse(t.config);if(r.registries){for(let o of Object.keys(r.registries))if(o in I)throw new Error(`"${o}" is a built-in registry and cannot be overridden.`)}return r}catch(t){throw t instanceof Error&&t.message.includes("reserved registry")?t:new Be(e,t)}}function G(e){let t={resolvedPaths:{cwd:process.cwd(),api:"",vendor:"",admin:""},aliases:{api:wo,vendor:jo,admin:bo},registries:{...I}};return e?{...t,...e,resolvedPaths:{...t.resolvedPaths,...e.resolvedPaths||{}},aliases:{...t.aliases,...e.aliases||{}},registries:{...t.registries,...e.registries||{}}}:t}var at=["**/node_modules/**","public","dist"];async function k(e){let[t,r,o,i,s,n]=await Promise.all([L.pathExists(R__default.resolve(e,"src")),ko(e),ve(e),Eo(e),So(e),Io(e)]);return {isSrcDir:t,aliasPrefix:r,packageJson:o,medusaConfigFile:i?.file??null,medusaVersion:s,mercurVersion:n}}async function ko(e){let t=loadConfig(e);if(t.resultType==="failed")return null;let r=t.paths||{},o=Object.keys(r);if(o.length===0)return null;let i=o[0];return i?.includes("*")?i.replace("/*",""):i?.replace("/","")??null}function ve(e="",t=true){let r=R__default.join(e,"package.json");return L.readJSONSync(r,{throws:t})}async function Eo(e){let t=await nt.glob("medusa-config.*",{cwd:e,deep:3,ignore:at});if(!t.length)return null;let r=t[0];return {file:r,dir:R__default.resolve(e,R__default.dirname(r))}}async function So(e){let r=ve(e,false)?.dependencies?.["@medusajs/framework"];if(r)return r;let o=await nt.glob("**/package.json",{cwd:e,deep:3,ignore:at});for(let i of o){let n=ve(R__default.join(e,R__default.dirname(i)),false)?.dependencies?.["@medusajs/framework"];if(n)return n}return null}async function Io(e){let r=ve(e,false)?.dependencies?.["@mercurjs/cli"];if(r)return r;let o=await nt.glob("**/package.json",{cwd:e,deep:3,ignore:at});for(let i of o){let n=ve(R__default.join(e,R__default.dirname(i)),false)?.dependencies?.["@mercurjs/cli"];if(n)return n}return null}z.object({cwd:z.string(),blocks:z.array(z.string()).optional(),yes:z.boolean(),overwrite:z.boolean(),silent:z.boolean()});async function qt(e){let t={},r=R__default.resolve(e.cwd);if(!existsSync(r))return t[Lt]=true,{errors:t,config:null};let o=await b(r);if(!o)return t[S]=true,{errors:t,config:null};let i=await k(r);return {errors:t,config:o,projectInfo:i}}var We={headers:{}};function dt(e){We.headers={...We.headers,...e};}function Jt(e){return We.headers[e]||{}}function x(){We.headers={};}function me(e){let t={aliases:{api:"packages/api/src",vendor:"apps/vendor/src",admin:"apps/admin/src"},registries:I};return {...t,...e||{},aliases:{...t.aliases,...e?.aliases||{}},registries:{...e?.registries||{},...I}}}function we(e){return e.replace(/\${(\w+)}/g,(t,r)=>process.env[r]||"")}function je(e){let t=[],r=/\${(\w+)}/g,o=r.exec(e);for(;o!==null;){let i=o[1];i&&t.push(i),o=r.exec(e);}return t}var To=/^(@[a-zA-Z0-9](?:[a-zA-Z0-9-_]*[a-zA-Z0-9])?)\/(.+)$/;function pe(e){if(!e.startsWith("@"))return {registry:null,item:e};let t=e.match(To);return t?{registry:t[1],item:t[2]}:{registry:null,item:e}}var Ht=[".tsx",".ts"],Kt=["lib/utils.ts"],Oo=[/^(react|react-dom)(\/.*)?$/,/^(node|jsr|npm):.*$/],Ao=new Project({compilerOptions:{}});function Lo(e){if(Oo.some(t=>t.test(e)))return null;if(!e.startsWith("@")&&e.includes("/")&&(e=e.split("/")[0]),e.startsWith("@")){let t=e.split("/");t.length>2&&(e=t.slice(0,2).join("/"));}return e}async function mt(e,t,r,o=new Set){let i=R.resolve(t.resolvedPaths.cwd,e),s=R.relative(t.resolvedPaths.cwd,i);if(Kt.includes(s))return {dependencies:[],files:[]};let n=R.extname(e);if(!Ht.includes(n))return {dependencies:[],files:[]};if(o.has(s))return {dependencies:[],files:[]};o.add(s);try{if(!(await U.stat(i)).isFile())return {dependencies:[],files:[]}}catch{return {dependencies:[],files:[]}}let m=await U.readFile(i,"utf-8"),p=await Mo(R.basename(i)),d=Ao.createSourceFile(p,m,{scriptKind:ScriptKind.TSX}),u=await loadConfig(t.resolvedPaths.cwd);if(u.resultType==="failed")return {dependencies:[],files:[]};let c=[],f=new Set,y=Zt(e),h={path:s,type:y,target:"",content:""};c.push(h);let w=d.getImportDeclarations();for(let F of w){let z=F.getModuleSpecifierValue(),$e=z.startsWith(".");if(!(r.aliasPrefix&&z.startsWith(`${r.aliasPrefix}/`))&&!$e){let O=Lo(z);O&&f.add(O);continue}let se=await de(z,u);if($e&&(se=R.resolve(R.dirname(i),z)),!se)continue;if(!R.extname(se))for(let O of Ht){let At=`${se}${O}`;try{await U.access(At),se=At;break}catch{continue}}let De=R.relative(t.resolvedPaths.cwd,se);if(o.has(De)||Kt.includes(De))continue;let co=Zt(z),uo={path:De,type:co,target:"",content:""};c.push(uo);let Ne=await mt(De,t,r,o);if(Ne.files)for(let O of Ne.files)o.has(O.path)||(o.add(O.path),c.push(O));Ne.dependencies&&Ne.dependencies.forEach(O=>f.add(O));}let E=Array.from(new Map(c.map(F=>[F.path,F])).values());return {dependencies:Array.from(f),files:E}}async function Mo(e){let t=await U.mkdtemp(R.join(tmpdir(),"mercur-"));return R.join(t,e)}function Zt(e){return e.includes("/vendor")?"registry:vendor":e.includes("/admin")?"registry:admin":"registry:api"}function q(e){try{return new URL(e),!0}catch{return false}}function ee(e){return e.endsWith(".json")&&!q(e)}function Uo(e){let t=new Set;if(typeof e=="string")for(let r of je(e))t.add(r);else {for(let r of je(e.url))t.add(r);if(e.params)for(let r of Object.values(e.params))for(let o of je(r))t.add(o);if(e.headers)for(let r of Object.values(e.headers))for(let o of je(r))t.add(o);}return Array.from(t)}function Qt(e,t){let o=Uo(t).filter(i=>!process.env[i]);if(o.length>0)throw new Ue(e,o)}var Ge="{name}",zo=`${Ge}.json`,Xt=/\${(\w+)}/g,er="?",Bo="&";function Wo(e){return e.includes(Ge)}function tr(e){return Wo(e)?e:`${e.endsWith("/")?e:`${e}/`}${zo}`}function be(e,t){let{registry:r,item:o}=pe(e);if(!r)return null;let s=(t?.registries||{})[r];if(!s)throw new Z(r);return Qt(r,s),{url:Go(o,s),headers:Vo(s)}}function Go(e,t,r){if(typeof t=="string"){let n=tr(t).replace(Ge,e);return we(n)}let i=tr(t.url).replace(Ge,e);return i=we(i),t.params?Yo(i,t.params):i}function Vo(e){if(typeof e=="string"||!e.headers)return {};let t={};for(let[r,o]of Object.entries(e.headers)){let i=we(o);qo(o,i)&&(t[r]=i);}return t}function Yo(e,t){let r=new URLSearchParams;for(let[s,n]of Object.entries(t)){let m=we(n);m&&r.append(s,m);}let o=r.toString();if(!o)return e;let i=e.includes(er)?Bo:er;return `${e}${i}${o}`}function qo(e,t){let r=t.trim();if(!r)return false;if(e.includes("${")&&e.match(Xt)){let i=e.replace(Xt,"").trim();return r!==i}return true}function rr(e){return q(e)||ee(e)?e:`${he}/${e}`}var Ve=new Map;async function Jo(e){let t=e;t.startsWith("file://")&&(t=t.slice(7)),t.startsWith("~/")&&(t=R__default.join(homedir(),t.slice(2)));let r=R__default.resolve(t);try{let o=await promises.readFile(r,"utf8");return JSON.parse(o)}catch(o){throw o instanceof Error&&(o.message.includes("ENOENT")||o.message.includes("no such file"))?new Q(e,o):new Q(e,o)}}async function te(e){return await Promise.all(e.map(async r=>{let o=rr(r);if(Ve.has(o))return Ve.get(o);if(ee(o)){let s=Jo(o);return Ve.set(o,s),s}let i=(async()=>{let s=Jt(o),n=await fetch(o,{headers:{...s}});if(!n.ok){let m;if(n.headers.get("content-type")?.includes("application/json")){let p=await n.json(),d=z.object({detail:z.string().optional(),title:z.string().optional(),message:z.string().optional(),error:z.string().optional()}).safeParse(p);d.success&&(m=d.data.detail||d.data.message,d.data.error&&(m=`[${d.data.error}] ${m}`));}throw n.status===401?new Ae(o,m):n.status===404?new ae(o,m):n.status===403?new Le(o,m):new Me(o,n.status,m)}return n.json()})();return Ve.set(o,i),i}))}async function sr(e){try{let t=e;e.startsWith("~/")&&(t=R__default.join(homedir(),e.slice(2)));let r=R__default.resolve(t),o=await promises.readFile(r,"utf8"),i=JSON.parse(o);try{return T.parse(i)}catch(s){throw new C(e,s)}}catch(t){throw t instanceof Error&&(t.message.includes("ENOENT")||t.message.includes("no such file"))?new Q(e,t):t instanceof C?t:new Q(e,t)}}T.extend({_source:z.string().optional()});function pt(e,t){let r={},o=[...e];if(!t?.registries)return dt({}),o;for(let i=0;i<o.length;i++){let s=be(o[i],t);s&&(o[i]=s.url,Object.keys(s.headers).length>0&&(r[s.url]=s.headers));}return dt(r),o}async function qe(e,t){return await Promise.all(e.map(async o=>{if(ee(o))return sr(o);if(q(o)){let[n]=await te([o]);try{return T.parse(n)}catch(m){throw new C(o,m)}}if(o.startsWith("@")&&t?.registries){let n=pt([o],t),[m]=await te(n);try{return T.parse(m)}catch(p){throw new C(o,p)}}let i=`${he}/${o}.json`,[s]=await te([i]);try{return T.parse(s)}catch(n){throw new C(o,n)}}))}async function ct(e,t){let r=[],o=[],i=Array.from(new Set(e)),s=await qe(i,t),n=new Map;for(let d=0;d<s.length;d++)s[d]&&n.set(i[d],s[d]);for(let[d,u]of Array.from(n.entries())){let c={...u,_source:d};if(r.push(c),u.registryDependencies){let f=u.registryDependencies;if(t?.registries)f=pt(u.registryDependencies,t);else {let h=u.registryDependencies.filter(w=>w.startsWith("@"));if(h.length>0){let{registry:w}=pe(h[0]);throw new Z(w)}}let{blocks:y}=await dr(f,t,new Set(i));o.push(...y);}}r.push(...o);let m=new Map;for(let d of r){let u=d._source||d.name;m.set(d,u);}return r=Qo(r,m),zt.parse({dependencies:nr.all(r.map(d=>d.dependencies??[])),devDependencies:nr.all(r.map(d=>d.devDependencies??[])),files:Xo(r.map(d=>d.files??[])),docs:r.map(d=>d.docs).filter(Boolean).join(`
15
- `)})}async function dr(e,t,r=new Set){let o=[];for(let i of e){if(r.has(i))continue;if(r.add(i),i.startsWith("@")&&t?.registries){let{registry:n}=pe(i);if(n&&!(n in t.registries))throw new Z(n)}let[s]=await qe([i],t);if(s&&(o.push({...s,_source:i}),s.registryDependencies)){let n=t?.registries?pt(s.registryDependencies,t):s.registryDependencies,m=await dr(n,t,r);o.push(...m.blocks);}}return {blocks:o}}function J(e,t){let r=t||e.name,o=createHash("sha256").update(r).digest("hex").substring(0,8);return `${e.name}::${o}`}function Zo(e){if(q(e)){let o=new URL(e).pathname,i=o.match(/\/([^/]+)\.json$/),s=i?i[1]:R__default.basename(o,".json");return {name:s,hash:J({name:s},e)}}if(ee(e)){let r=e.match(/\/([^/]+)\.json$/),o=r?r[1]:R__default.basename(e,".json");return {name:o,hash:J({name:o},e)}}let{item:t}=pe(e);return {name:t,hash:J({name:t},e)}}function Qo(e,t){let r=new Map,o=new Map,i=new Map,s=new Map;for(let d of e){let u=t.get(d)||d.name,c=J(d,u);r.set(c,d),o.set(c,d),i.set(c,0),s.set(c,[]);}let n=new Map;for(let d of e){let u=t.get(d)||d.name,c=J(d,u);n.has(d.name)||n.set(d.name,[]),n.get(d.name).push(c),u!==d.name&&(n.has(u)||n.set(u,[]),n.get(u).push(c));}for(let d of e){let u=t.get(d)||d.name,c=J(d,u);if(d.registryDependencies)for(let f of d.registryDependencies){let y,h=n.get(f)||[];if(h.length===1)y=h[0];else if(h.length>1)y=h[0];else {let{name:w}=Zo(f),E=n.get(w)||[];E.length>0&&(y=E[0]);}y&&r.has(y)&&(s.get(y).push(c),i.set(c,i.get(c)+1));}}let m=[],p=[];for(let[d,u]of i)u===0&&m.push(d);for(;m.length>0;){let d=m.shift(),u=r.get(d);p.push(u);for(let c of s.get(d)){let f=i.get(c)-1;i.set(c,f),f===0&&m.push(c);}}if(p.length!==e.length){let d=Array.from(r.keys()).filter(u=>!p.some(c=>J(c,t.get(c))===u));console.warn(`Warning: Circular dependencies detected. Some items may not be sorted correctly: ${d.join(", ")}`);for(let[u,c]of r.entries())p.some(f=>J(f,t.get(f))===u)||p.push(c);}return p}function Xo(e){let t=new Map,r=[];for(let o of e)if(o)for(let i of o){let s=i.target||i.path;t.has(s)||(t.set(s,i),r.push(i));}return r}var l={error:e=>N.red(e),warn:e=>N.yellow(e),info:e=>N.blue(e),success:e=>N.green(e),dim:e=>N.cyan(e)};var a={error(...e){console.log(l.error(e.join(" ")));},warn(...e){console.log(l.warn(e.join(" ")));},info(...e){console.log(l.info(e.join(" ")));},success(...e){console.log(l.success(e.join(" ")));},log(...e){console.log(e.join(" "));},break(){console.log("");}};function j(e){if(a.break(),a.error("Something went wrong. Please check the error below for more details."),a.error("If the problem persists, please open an issue on GitHub."),a.error(""),typeof e=="string"&&(a.error(e),a.break(),process.exit(1)),e instanceof _&&(e.message&&(a.error(e.cause?"Error:":"Message:"),a.error(e.message)),e.cause&&(a.error(`
16
- Message:`),a.error(e.cause)),e.suggestion&&(a.error(`
17
- Suggestion:`),a.error(e.suggestion)),a.break(),process.exit(1)),e instanceof z.ZodError){a.error("Validation failed:");for(let t of e.issues){let r=t.path.join(".")||"root";a.error(`- ${l.info(r)}: ${t.message}`);}a.break(),process.exit(1);}e instanceof Error&&(a.error(e.message),a.break(),process.exit(1)),a.break(),process.exit(1);}function v(e,t){return ti({text:e,isSilent:t?.silent??false})}async function A(e){let t=await detect({programmatic:true,cwd:e});if(t?.startsWith("bun"))return "bun";if(t?.startsWith("yarn"))return "yarn";if(t?.startsWith("pnpm"))return "pnpm";if(t?.startsWith("deno"))return "deno";if(t?.startsWith("npm"))return "npm";let r=process.env.npm_config_user_agent||"";return r.startsWith("bun")?"bun":r.startsWith("yarn")?"yarn":r.startsWith("pnpm")?"pnpm":r.startsWith("deno")?"deno":"npm"}async function mr(e,t,r,o={}){if(e=Array.from(new Set(e||[])),t=Array.from(new Set(t||[])),!e?.length&&!t?.length)return;o={silent:false,...o};let i=v("Installing dependencies.",{silent:o.silent})?.start(),s=await A(r.resolvedPaths.cwd);i?.start(),await oi(s,e,t,r.resolvedPaths.cwd),i?.succeed();}async function oi(e,t,r,o){if(e==="npm")return ii(t,r,o);if(e==="deno")return si(t,r,o);t?.length&&await execa(e,["add",...t],{cwd:o}),r?.length&&await execa(e,["add","-D",...r],{cwd:o});}async function ii(e,t,r){e.length&&await execa("npm",["install",...e],{cwd:r}),t.length&&await execa("npm",["install","-D",...t],{cwd:r});}async function si(e,t,r){e?.length&&await execa("deno",["add",...e.map(o=>`npm:${o}`)],{cwd:r}),t?.length&&await execa("deno",["add","-D",...t.map(o=>`npm:${o}`)],{cwd:r});}function pr(e,t,r={}){let{ignoreImports:o=false}=r,i=e.replace(/\r\n/g,`
18
- `).trim(),s=t.replace(/\r\n/g,`
19
- `).trim();if(i===s)return true;if(!o)return false;let n=/^(import\s+(?:type\s+)?(?:\*\s+as\s+\w+|\{[^}]*\}|\w+)?(?:\s*,\s*(?:\{[^}]*\}|\w+))?\s+from\s+["'])([^"']+)(["'])/gm,m=u=>u.replace(n,(c,f,y,h)=>{if(y.startsWith("."))return `${f}${y}${h}`;let w=y.split("/"),E=w[w.length-1];return `${f}@normalized/${E}${h}`}),p=m(i),d=m(s);return p===d}function ni(e,t){if(e.type==="registry:api")return t.resolvedPaths.api;if(e.type==="registry:vendor")return t.resolvedPaths.vendor;if(e.type==="registry:admin")return t.resolvedPaths.admin;throw new Error(`Unknown file type: ${e.type}`)}function Je(e,t,r){let o=ni(e,t);if(e.type==="registry:api"){let n=e.path.replace(/^\/|\/$/g,"").split("/").slice(1).join("/");return R__default.join(o,n)}let i=ai(e.path,o);return R__default.join(o,i)}function ai(e,t){let r=e.replace(/^\/|\/$/g,""),o=t.replace(/^\/|\/$/g,""),i=r.split("/"),s=o.split("/");for(let n=s.length-1;n>=0;n--){let m=i.findIndex(p=>p===s[n]);if(m!==-1)return i.slice(m+1).join("/")}return i[i.length-1]}var ci=new Project({compilerOptions:{}});async function ui(e){let t=await promises.mkdtemp(R__default.join(tmpdir(),"mercurjs-")),r=R__default.basename(e,R__default.extname(e));return R__default.join(t,`${r}.ts`)}function li(e){switch(R__default.extname(e).toLowerCase()){case ".tsx":case ".ts":return ScriptKind.TS;default:return ScriptKind.Unknown}}async function He(e){let t=R__default.extname(e.filename).toLowerCase();if(![".tsx",".ts"].includes(t))return e.raw;let r=li(e.filename),o=await ui(e.filename),i=ci.createSourceFile(o,e.raw,{scriptKind:r});for(let s of i.getImportStringLiterals()){let n=fi(s.getLiteralValue(),e.config);s.setLiteralValue(n);}return i.getText()}function fi(e,t){if(e.startsWith("@/workflows/")){let r=e.replace(/^@\/workflows\//,"");return `${t.aliases.api}/workflows/${r}`}if(e==="@/workflows")return `${t.aliases.api}/workflows`;if(e.startsWith("@/api/")){let r=e.replace(/^@\/api\//,"");return `${t.aliases.api}/api/${r}`}if(e==="@/api")return `${t.aliases.api}/api`;if(e.startsWith("@/links/")){let r=e.replace(/^@\/links\//,"");return `${t.aliases.api}/links/${r}`}if(e==="@/links")return `${t.aliases.api}/links`;if(e.startsWith("@/modules/")){let r=e.replace(/^@\/modules\//,"");return `${t.aliases.api}/modules/${r}`}if(e==="@/modules")return `${t.aliases.api}/modules`;if(e.startsWith("@/lib/")){let r=e.replace(/^@\/lib\//,"");return `${t.aliases.api}/lib/${r}`}if(e==="@/lib")return `${t.aliases.api}/lib`;if(e.startsWith("@/vendor/")){let r=e.replace(/^@\/vendor\//,"");return `${t.aliases.vendor}/${r}`}if(e==="@/vendor")return t.aliases.vendor;if(e.startsWith("@/admin/")){let r=e.replace(/^@\/admin\//,"");return `${t.aliases.admin}/${r}`}return e==="@/admin"?t.aliases.admin:e}async function fr(e,t,r){if(!e?.length)return {filesCreated:[],filesUpdated:[],filesSkipped:[],filesDeclined:[]};r={overwrite:false,silent:false,yes:false,...r};let o=v("Updating files.",{silent:r.silent})?.start(),i=await k(t.resolvedPaths.cwd),s=[],n=[],m=[],p=[];for(let c of e){let f=Je(c,t,{isSrcDir:i?.isSrcDir??false,path:r.path??""}),y=basename(c.path),h=R__default.dirname(f),w=existsSync(f);if(w&&statSync(f).isDirectory())throw new Error(`Cannot write to ${f}: path exists and is a directory. Please provide a file path instead.`);let E=await He({filename:c.path,raw:c.content,config:t});if(w&&!r.overwrite){let F=await promises.readFile(f,"utf-8");if(pr(F,E)){m.push(R__default.relative(t.resolvedPaths.cwd,f));continue}if(!r.yes){o.stop();let z=diffLines(F,E);a.info(`
20
- File: ${l.info(y)}`),bi(z);let{overwrite:$e}=await Pe({type:"confirm",name:"overwrite",message:`The file ${l.info(y)} already exists. Would you like to overwrite?`,initial:false});if(!$e){p.push(R__default.relative(t.resolvedPaths.cwd,f));continue}}}existsSync(h)||await promises.mkdir(h,{recursive:true}),await promises.writeFile(f,E,"utf-8"),w?n.push(R__default.relative(t.resolvedPaths.cwd,f)):s.push(R__default.relative(t.resolvedPaths.cwd,f));}let d=s.length+n.length,u=m.length+p.length;if(d>0){if(o?.succeed(),u>0&&!r.silent){let c=[];d===1?c.push("1 file updated"):c.push(`${d} files updated`),u===1?c.push("1 file skipped"):c.push(`${u} files skipped`),a.info(`${c.join(", ")}.`);}}else p.length?o?.info("No files were updated."):m.length?o?.info("Already up to date."):o?.info("No files to update.");return {filesCreated:s,filesUpdated:n,filesSkipped:m,filesDeclined:p}}var wi=3;function ji(e,t=wi){let r=[],o=new Set;for(let s=0;s<e.length;s++)(e[s]?.added||e[s]?.removed)&&o.add(s);if(o.size===0)return r;let i=new Map;for(let s=0;s<e.length;s++){let n=e[s];if(n)if(n.added||n.removed)i.set(s,"full");else {let m=o.has(s-1),p=o.has(s+1);m&&p?i.set(s,"both"):m?i.set(s,"start"):p&&i.set(s,"end");}}for(let s=0;s<e.length;s++){let n=e[s],m=i.get(s);if(!(!n||!m))if(n.added){let p=n.value.split(`
21
- `);p[p.length-1]===""&&p.pop();for(let d of p)r.push(`+ ${d}`);}else if(n.removed){let p=n.value.split(`
22
- `);p[p.length-1]===""&&p.pop();for(let d of p)r.push(`- ${d}`);}else {let p=n.value.split(`
23
- `);p[p.length-1]===""&&p.pop();let d=[];m==="full"||p.length<=t*2+1?d=p.map(u=>` ${u}`):m==="start"?(d=p.slice(0,t).map(u=>` ${u}`),p.length>t&&d.push(` ... ${p.length-t} lines hidden ...`)):m==="end"?(p.length>t&&d.push(` ... ${p.length-t} lines hidden ...`),d.push(...p.slice(-t).map(u=>` ${u}`))):m==="both"&&(p.length<=t*2+1?d=p.map(u=>` ${u}`):d=[...p.slice(0,t).map(u=>` ${u}`),` ... ${p.length-t*2} lines hidden ...`,...p.slice(-t).map(u=>` ${u}`)]),r.push(...d);}}return r}function bi(e){let t=ji(e);if(t.length!==0)for(let r of t)r.startsWith("+ ")?process.stdout.write(`${l.success(r)}
24
- `):r.startsWith("- ")?process.stdout.write(`${l.error(r)}
25
- `):r.includes("lines hidden")?process.stdout.write(`${l.info(r)}
7
+ }`:'Unknown registry. Make sure it is defined in blocks.json under "registries".';super(o,{code:j.NOT_CONFIGURED,context:{registryName:r},suggestion:"Add the registry configuration to your blocks.json file. Consult the registry documentation for the correct format."});this.registryName=r;this.name="RegistryNotConfiguredError";}registryName},H=class extends I{constructor(r,o){super(`Failed to read local registry file: ${r}`,{code:j.LOCAL_FILE_ERROR,cause:o,context:{filePath:r},suggestion:"Check if the file exists and you have read permissions."});this.filePath=r;this.name="RegistryLocalFileError";}filePath},_=class extends I{constructor(r,o){let s=`Failed to parse registry item: ${r}`;o instanceof z.ZodError&&(s=`Failed to parse registry item: ${r}
8
+ ${o.issues.map(n=>` - ${n.path.join(".")}: ${n.message}`).join(`
9
+ `)}`);super(s,{code:j.PARSE_ERROR,cause:o,context:{item:r},suggestion:"The registry item may be corrupted or have an invalid format. Please make sure it returns a valid JSON object."});this.item=r;this.parseError=o,this.name="RegistryParseError";}item;parseError},Oe=class extends I{constructor(r,o){let s=`Registry "${r}" requires the following environment variables:
10
+
11
+ `+o.map(n=>` \u2022 ${n}`).join(`
12
+ `);super(s,{code:j.MISSING_ENV_VARS,context:{registryName:r,missingVars:o},suggestion:"Set the required environment variables to your .env or .env.local file."});this.registryName=r;this.missingVars=o;this.name="RegistryMissingEnvironmentVariablesError";}registryName;missingVars},Ne=class extends I{constructor(r){let o=`Invalid registry namespace: "${r}". Registry names must start with @ (e.g., @mercurjs).`;super(o,{code:j.VALIDATION_ERROR,context:{name:r},suggestion:"Use a valid registry name starting with @ or provide a direct URL to the registry."});this.name=r;this.name="RegistryInvalidNamespaceError";}name};var $e=class extends I{constructor(r,o){let s=`Invalid blocks.json configuration in ${r}.`;o instanceof z.ZodError&&(s=`Invalid blocks.json configuration in ${r}:
13
+ ${o.issues.map(n=>` - ${n.path.join(".")}: ${n.message}`).join(`
14
+ `)}`);super(s,{code:j.INVALID_CONFIG,cause:o,context:{cwd:r},suggestion:"Check your blocks.json file for syntax errors or invalid configuration. Run '@mercurjs/cli init' to regenerate a valid configuration."});this.cwd=r;this.name="ConfigParseError";}cwd};var M=z.object({$schema:z.string().optional(),aliases:z.object({api:z.string(),vendor:z.string(),admin:z.string()}),registries:Ct.optional()}).strict(),Tt=M.extend({resolvedPaths:z.object({cwd:z.string(),api:z.string(),vendor:z.string(),admin:z.string()})});async function oe(e,t){return createMatchPath(t.absoluteBaseUrl,t.paths)(e,void 0,()=>true,[".ts",".tsx"])}var Kr="packages/api/src",qr="apps/vendor/src",Zr="apps/admin/src",Xr=cosmiconfig("blocks",{searchPlaces:["blocks.json"]});async function E(e){let t=await Qr(e);return t?await Xe(e,t):null}async function Xe(e,t){t.registries={...t.registries||{},...P};let r=await loadConfig(e);if(r.resultType==="failed")throw new Error(`Failed to load tsconfig.json. ${r.message??""}`.trim());return Tt.parse({...t,resolvedPaths:{cwd:e,api:await oe(t.aliases.api,r),vendor:await oe(t.aliases.vendor,r),admin:await oe(t.aliases.admin,r)}})}async function Qr(e){try{let t=await Xr.search(e);if(!t)return null;let r=M.parse(t.config);if(r.registries){for(let o of Object.keys(r.registries))if(o in P)throw new Error(`"${o}" is a built-in registry and cannot be overridden.`)}return r}catch(t){throw t instanceof Error&&t.message.includes("reserved registry")?t:new $e(e,t)}}function L(e){let t={resolvedPaths:{cwd:process.cwd(),api:"",vendor:"",admin:""},aliases:{api:Kr,vendor:qr,admin:Zr},registries:{...P}};return e?{...t,...e,resolvedPaths:{...t.resolvedPaths,...e.resolvedPaths||{}},aliases:{...t.aliases,...e.aliases||{}},registries:{...t.registries,...e.registries||{}}}:t}var et=["**/node_modules/**","public","dist"];async function b(e){let[t,r,o,s,n,i]=await Promise.all([ut.pathExists(v__default.resolve(e,"src")),to(e),ge(e),ro(e),oo(e),so(e)]);return {isSrcDir:t,aliasPrefix:r,packageJson:o,medusaConfigFile:s?.file??null,medusaVersion:n,mercurVersion:i}}async function to(e){let t=loadConfig(e);if(t.resultType==="failed")return null;let r=t.paths||{},o=Object.keys(r);if(o.length===0)return null;let s=o[0];return s?.includes("*")?s.replace("/*",""):s?.replace("/","")??null}function ge(e="",t=true){let r=v__default.join(e,"package.json");return ut.readJSONSync(r,{throws:t})}async function ro(e){let t=await Qe.glob("medusa-config.*",{cwd:e,deep:3,ignore:et});if(!t.length)return null;let r=t[0];return {file:r,dir:v__default.resolve(e,v__default.dirname(r))}}async function oo(e){let r=ge(e,false)?.dependencies?.["@medusajs/framework"];if(r)return r;let o=await Qe.glob("**/package.json",{cwd:e,deep:3,ignore:et});for(let s of o){let i=ge(v__default.join(e,v__default.dirname(s)),false)?.dependencies?.["@medusajs/framework"];if(i)return i}return null}async function so(e){let r=ge(e,false)?.dependencies?.["@mercurjs/cli"];if(r)return r;let o=await Qe.glob("**/package.json",{cwd:e,deep:3,ignore:et});for(let s of o){let i=ge(v__default.join(e,v__default.dirname(s)),false)?.dependencies?.["@mercurjs/cli"];if(i)return i}return null}z.object({cwd:z.string(),blocks:z.array(z.string()).optional(),yes:z.boolean(),overwrite:z.boolean(),silent:z.boolean()});async function Ft(e){let t={},r=v__default.resolve(e.cwd);if(!existsSync(r))return t[It]=true,{errors:t,config:null};let o=await E(r);if(!o)return t[C]=true,{errors:t,config:null};let s=await b(r);return {errors:t,config:o,projectInfo:s}}var De={headers:{}};function tt(e){De.headers={...De.headers,...e};}function Ot(e){return De.headers[e]||{}}function S(){De.headers={};}function se(e){let t={aliases:{api:"packages/api/src",vendor:"apps/vendor/src",admin:"apps/admin/src"},registries:P};return {...t,...e||{},aliases:{...t.aliases,...e?.aliases||{}},registries:{...e?.registries||{},...P}}}function de(e){return e.replace(/\${(\w+)}/g,(t,r)=>process.env[r]||"")}function he(e){let t=[],r=/\${(\w+)}/g,o=r.exec(e);for(;o!==null;){let s=o[1];s&&t.push(s),o=r.exec(e);}return t}var ao=/^(@[a-zA-Z0-9](?:[a-zA-Z0-9-_]*[a-zA-Z0-9])?)\/(.+)$/;function ne(e){if(!e.startsWith("@"))return {registry:null,item:e};let t=e.match(ao);return t?{registry:t[1],item:t[2]}:{registry:null,item:e}}var Nt=[".tsx",".ts"],$t=["lib/utils.ts"],po=[/^(react|react-dom)(\/.*)?$/,/^(node|jsr|npm):.*$/],uo=new Project({compilerOptions:{}});function go(e){if(po.some(t=>t.test(e)))return null;if(!e.startsWith("@")&&e.includes("/")&&(e=e.split("/")[0]),e.startsWith("@")){let t=e.split("/");t.length>2&&(e=t.slice(0,2).join("/"));}return e}async function rt(e,t,r,o=new Set){let s=v.resolve(t.resolvedPaths.cwd,e),n=v.relative(t.resolvedPaths.cwd,s);if($t.includes(n))return {dependencies:[],files:[]};let i=v.extname(e);if(!Nt.includes(i))return {dependencies:[],files:[]};if(o.has(n))return {dependencies:[],files:[]};o.add(n);try{if(!(await $.stat(s)).isFile())return {dependencies:[],files:[]}}catch{return {dependencies:[],files:[]}}let f=await $.readFile(s,"utf-8"),c=await ho(v.basename(s)),a=uo.createSourceFile(c,f,{scriptKind:ScriptKind.TSX}),m=await loadConfig(t.resolvedPaths.cwd);if(m.resultType==="failed")return {dependencies:[],files:[]};let p=[],g=new Set,h=Dt(e),y={path:n,type:h,target:"",content:""};p.push(y);let w=a.getImportDeclarations();for(let O of w){let D=O.getModuleSpecifierValue(),ke=D.startsWith(".");if(!(r.aliasPrefix&&D.startsWith(`${r.aliasPrefix}/`))&&!ke){let N=go(D);N&&g.add(N);continue}let ee=await oe(D,m);if(ke&&(ee=v.resolve(v.dirname(s),D)),!ee)continue;if(!v.extname(ee))for(let N of Nt){let xt=`${ee}${N}`;try{await $.access(xt),ee=xt;break}catch{continue}}let Ce=v.relative(t.resolvedPaths.cwd,ee);if(o.has(Ce)||$t.includes(Ce))continue;let zr=Dt(D),Br={path:Ce,type:zr,target:"",content:""};p.push(Br);let Pe=await rt(Ce,t,r,o);if(Pe.files)for(let N of Pe.files)o.has(N.path)||(o.add(N.path),p.push(N));Pe.dependencies&&Pe.dependencies.forEach(N=>g.add(N));}let k=Array.from(new Map(p.map(O=>[O.path,O])).values());return {dependencies:Array.from(g),files:k}}async function ho(e){let t=await $.mkdtemp(v.join(tmpdir(),"mercur-"));return v.join(t,e)}function Dt(e){return e.includes("/vendor")?"registry:vendor":e.includes("/admin")?"registry:admin":"registry:api"}function B(e){try{return new URL(e),!0}catch{return false}}function q(e){return e.endsWith(".json")&&!B(e)}function yo(e){let t=new Set;if(typeof e=="string")for(let r of he(e))t.add(r);else {for(let r of he(e.url))t.add(r);if(e.params)for(let r of Object.values(e.params))for(let o of he(r))t.add(o);if(e.headers)for(let r of Object.values(e.headers))for(let o of he(r))t.add(o);}return Array.from(t)}function At(e,t){let o=yo(t).filter(s=>!process.env[s]);if(o.length>0)throw new Oe(e,o)}var Ae="{name}",wo=`${Ae}.json`,Mt=/\${(\w+)}/g,Lt="?",Ro="&";function Eo(e){return e.includes(Ae)}function Ut(e){return Eo(e)?e:`${e.endsWith("/")?e:`${e}/`}${wo}`}function ye(e,t){let{registry:r,item:o}=ne(e);if(!r)return null;let n=(t?.registries||{})[r];if(!n)throw new J(r);return At(r,n),{url:xo(o,n),headers:vo(n)}}function xo(e,t,r){if(typeof t=="string"){let i=Ut(t).replace(Ae,e);return de(i)}let s=Ut(t.url).replace(Ae,e);return s=de(s),t.params?Io(s,t.params):s}function vo(e){if(typeof e=="string"||!e.headers)return {};let t={};for(let[r,o]of Object.entries(e.headers)){let s=de(o);bo(o,s)&&(t[r]=s);}return t}function Io(e,t){let r=new URLSearchParams;for(let[n,i]of Object.entries(t)){let f=de(i);f&&r.append(n,f);}let o=r.toString();if(!o)return e;let s=e.includes(Lt)?Ro:Lt;return `${e}${s}${o}`}function bo(e,t){let r=t.trim();if(!r)return false;if(e.includes("${")&&e.match(Mt)){let s=e.replace(Mt,"").trim();return r!==s}return true}function zt(e){return B(e)||q(e)?e:`${ue}/${e}`}var Me=new Map;async function So(e){let t=e;t.startsWith("file://")&&(t=t.slice(7)),t.startsWith("~/")&&(t=v__default.join(homedir(),t.slice(2)));let r=v__default.resolve(t);try{let o=await promises.readFile(r,"utf8");return JSON.parse(o)}catch(o){throw o instanceof Error&&(o.message.includes("ENOENT")||o.message.includes("no such file"))?new H(e,o):new H(e,o)}}async function Z(e){return await Promise.all(e.map(async r=>{let o=zt(r);if(Me.has(o))return Me.get(o);if(q(o)){let n=So(o);return Me.set(o,n),n}let s=(async()=>{let n=Ot(o),i=await fetch(o,{headers:{...n}});if(!i.ok){let f;if(i.headers.get("content-type")?.includes("application/json")){let c=await i.json(),a=z.object({detail:z.string().optional(),title:z.string().optional(),message:z.string().optional(),error:z.string().optional()}).safeParse(c);a.success&&(f=a.data.detail||a.data.message,a.data.error&&(f=`[${a.data.error}] ${f}`));}throw i.status===401?new Te(o,f):i.status===404?new re(o,f):i.status===403?new je(o,f):new Fe(o,i.status,f)}return i.json()})();return Me.set(o,s),s}))}async function Gt(e){try{let t=e;e.startsWith("~/")&&(t=v__default.join(homedir(),e.slice(2)));let r=v__default.resolve(t),o=await promises.readFile(r,"utf8"),s=JSON.parse(o);try{return T.parse(s)}catch(n){throw new _(e,n)}}catch(t){throw t instanceof Error&&(t.message.includes("ENOENT")||t.message.includes("no such file"))?new H(e,t):t instanceof _?t:new H(e,t)}}T.extend({_source:z.string().optional()});function ot(e,t){let r={},o=[...e];if(!t?.registries)return tt({}),o;for(let s=0;s<o.length;s++){let n=ye(o[s],t);n&&(o[s]=n.url,Object.keys(n.headers).length>0&&(r[n.url]=n.headers));}return tt(r),o}async function Ue(e,t){return await Promise.all(e.map(async o=>{if(q(o))return Gt(o);if(B(o)){let[i]=await Z([o]);try{return T.parse(i)}catch(f){throw new _(o,f)}}if(o.startsWith("@")&&t?.registries){let i=ot([o],t),[f]=await Z(i);try{return T.parse(f)}catch(c){throw new _(o,c)}}let s=`${ue}/${o}.json`,[n]=await Z([s]);try{return T.parse(n)}catch(i){throw new _(o,i)}}))}async function st(e,t){let r=[],o=[],s=Array.from(new Set(e)),n=await Ue(s,t),i=new Map;for(let a=0;a<n.length;a++)n[a]&&i.set(s[a],n[a]);for(let[a,m]of Array.from(i.entries())){let p={...m,_source:a};if(r.push(p),m.registryDependencies){let g=m.registryDependencies;if(t?.registries)g=ot(m.registryDependencies,t);else {let y=m.registryDependencies.filter(w=>w.startsWith("@"));if(y.length>0){let{registry:w}=ne(y[0]);throw new J(w)}}let{blocks:h}=await Jt(g,t,new Set(s));o.push(...h);}}r.push(...o);let f=new Map;for(let a of r){let m=a._source||a.name;f.set(a,m);}return r=_o(r,f),kt.parse({dependencies:Vt.all(r.map(a=>a.dependencies??[])),devDependencies:Vt.all(r.map(a=>a.devDependencies??[])),files:To(r.map(a=>a.files??[])),docs:r.map(a=>a.docs).filter(Boolean).join(`
15
+ `)})}async function Jt(e,t,r=new Set){let o=[];for(let s of e){if(r.has(s))continue;if(r.add(s),s.startsWith("@")&&t?.registries){let{registry:i}=ne(s);if(i&&!(i in t.registries))throw new J(i)}let[n]=await Ue([s],t);if(n&&(o.push({...n,_source:s}),n.registryDependencies)){let i=t?.registries?ot(n.registryDependencies,t):n.registryDependencies,f=await Jt(i,t,r);o.push(...f.blocks);}}return {blocks:o}}function W(e,t){let r=t||e.name,o=createHash("sha256").update(r).digest("hex").substring(0,8);return `${e.name}::${o}`}function Po(e){if(B(e)){let o=new URL(e).pathname,s=o.match(/\/([^/]+)\.json$/),n=s?s[1]:v__default.basename(o,".json");return {name:n,hash:W({name:n},e)}}if(q(e)){let r=e.match(/\/([^/]+)\.json$/),o=r?r[1]:v__default.basename(e,".json");return {name:o,hash:W({name:o},e)}}let{item:t}=ne(e);return {name:t,hash:W({name:t},e)}}function _o(e,t){let r=new Map,o=new Map,s=new Map,n=new Map;for(let a of e){let m=t.get(a)||a.name,p=W(a,m);r.set(p,a),o.set(p,a),s.set(p,0),n.set(p,[]);}let i=new Map;for(let a of e){let m=t.get(a)||a.name,p=W(a,m);i.has(a.name)||i.set(a.name,[]),i.get(a.name).push(p),m!==a.name&&(i.has(m)||i.set(m,[]),i.get(m).push(p));}for(let a of e){let m=t.get(a)||a.name,p=W(a,m);if(a.registryDependencies)for(let g of a.registryDependencies){let h,y=i.get(g)||[];if(y.length===1)h=y[0];else if(y.length>1)h=y[0];else {let{name:w}=Po(g),k=i.get(w)||[];k.length>0&&(h=k[0]);}h&&r.has(h)&&(n.get(h).push(p),s.set(p,s.get(p)+1));}}let f=[],c=[];for(let[a,m]of s)m===0&&f.push(a);for(;f.length>0;){let a=f.shift(),m=r.get(a);c.push(m);for(let p of n.get(a)){let g=s.get(p)-1;s.set(p,g),g===0&&f.push(p);}}if(c.length!==e.length){let a=Array.from(r.keys()).filter(m=>!c.some(p=>W(p,t.get(p))===m));console.warn(`Warning: Circular dependencies detected. Some items may not be sorted correctly: ${a.join(", ")}`);for(let[m,p]of r.entries())c.some(g=>W(g,t.get(g))===m)||c.push(p);}return c}function To(e){let t=new Map,r=[];for(let o of e)if(o)for(let s of o){let n=s.target||s.path;t.has(n)||(t.set(n,s),r.push(s));}return r}var u={error:e=>Re.red(e),warn:e=>Re.yellow(e),info:e=>Re.blue(e),success:e=>Re.green(e),dim:e=>Re.cyan(e)};var l={error(...e){console.log(u.error(e.join(" ")));},warn(...e){console.log(u.warn(e.join(" ")));},info(...e){console.log(u.info(e.join(" ")));},success(...e){console.log(u.success(e.join(" ")));},log(...e){console.log(e.join(" "));},break(){console.log("");}};function R(e){if(l.break(),l.error("Something went wrong. Please check the error below for more details."),l.error("If the problem persists, please open an issue on GitHub."),l.error(""),typeof e=="string"&&(l.error(e),l.break(),process.exit(1)),e instanceof I&&(e.message&&(l.error(e.cause?"Error:":"Message:"),l.error(e.message)),e.cause&&(l.error(`
16
+ Message:`),l.error(e.cause)),e.suggestion&&(l.error(`
17
+ Suggestion:`),l.error(e.suggestion)),l.break(),process.exit(1)),e instanceof z.ZodError){l.error("Validation failed:");for(let t of e.issues){let r=t.path.join(".")||"root";l.error(`- ${u.info(r)}: ${t.message}`);}l.break(),process.exit(1);}e instanceof Error&&(l.error(e.message),l.break(),process.exit(1)),l.break(),process.exit(1);}function x(e,t){return Fo({text:e,isSilent:t?.silent??false})}var $o=["bun","yarn","pnpm","deno","npm"];function Kt(e){if(e)return $o.find(t=>e.startsWith(t))}function Do(){return Kt(process.env.npm_config_user_agent)}async function Ht(e){try{return await execa(e,["--version"]),!0}catch{return false}}async function ze(e){let t=Kt(await detect({programmatic:true,cwd:e}));if(t&&await Ht(t))return t;let r=Do();return r&&await Ht(r)?r:"npm"}async function qt(e,t,r,o={}){if(e=Array.from(new Set(e||[])),t=Array.from(new Set(t||[])),!e?.length&&!t?.length)return;o={silent:false,...o};let s=x("Installing dependencies.",{silent:o.silent})?.start(),n=await ze(r.resolvedPaths.cwd);s?.start(),await Ao(n,e,t,r.resolvedPaths.cwd),s?.succeed();}async function Ao(e,t,r,o){if(e==="npm")return Mo(t,r,o);if(e==="deno")return Lo(t,r,o);t?.length&&await execa(e,["add",...t],{cwd:o}),r?.length&&await execa(e,["add","-D",...r],{cwd:o});}async function Mo(e,t,r){e.length&&await execa("npm",["install",...e],{cwd:r}),t.length&&await execa("npm",["install","-D",...t],{cwd:r});}async function Lo(e,t,r){e?.length&&await execa("deno",["add",...e.map(o=>`npm:${o}`)],{cwd:r}),t?.length&&await execa("deno",["add","-D",...t.map(o=>`npm:${o}`)],{cwd:r});}function Zt(e,t,r={}){let{ignoreImports:o=false}=r,s=e.replace(/\r\n/g,`
18
+ `).trim(),n=t.replace(/\r\n/g,`
19
+ `).trim();if(s===n)return true;if(!o)return false;let i=/^(import\s+(?:type\s+)?(?:\*\s+as\s+\w+|\{[^}]*\}|\w+)?(?:\s*,\s*(?:\{[^}]*\}|\w+))?\s+from\s+["'])([^"']+)(["'])/gm,f=m=>m.replace(i,(p,g,h,y)=>{if(h.startsWith("."))return `${g}${h}${y}`;let w=h.split("/"),k=w[w.length-1];return `${g}@normalized/${k}${y}`}),c=f(s),a=f(n);return c===a}function Uo(e,t){if(e.type==="registry:api")return t.resolvedPaths.api;if(e.type==="registry:vendor")return t.resolvedPaths.vendor;if(e.type==="registry:admin")return t.resolvedPaths.admin;throw new Error(`Unknown file type: ${e.type}`)}function Be(e,t,r){let o=Uo(e,t);if(e.type==="registry:api"){let i=e.path.replace(/^\/|\/$/g,"").split("/").slice(1).join("/");return v__default.join(o,i)}let s=zo(e.path,o);return v__default.join(o,s)}function zo(e,t){let r=e.replace(/^\/|\/$/g,""),o=t.replace(/^\/|\/$/g,""),s=r.split("/"),n=o.split("/");for(let i=n.length-1;i>=0;i--){let f=s.findIndex(c=>c===n[i]);if(f!==-1)return s.slice(f+1).join("/")}return s[s.length-1]}var Vo=new Project({compilerOptions:{}});async function Yo(e){let t=await promises.mkdtemp(v__default.join(tmpdir(),"mercurjs-")),r=v__default.basename(e,v__default.extname(e));return v__default.join(t,`${r}.ts`)}function Jo(e){switch(v__default.extname(e).toLowerCase()){case ".tsx":case ".ts":return ScriptKind.TS;default:return ScriptKind.Unknown}}async function We(e){let t=v__default.extname(e.filename).toLowerCase();if(![".tsx",".ts"].includes(t))return e.raw;let r=Jo(e.filename),o=await Yo(e.filename),s=Vo.createSourceFile(o,e.raw,{scriptKind:r});for(let n of s.getImportStringLiterals()){let i=Ho(n.getLiteralValue(),e.config);n.setLiteralValue(i);}return s.getText()}function Ho(e,t){if(e.startsWith("@/workflows/")){let r=e.replace(/^@\/workflows\//,"");return `${t.aliases.api}/workflows/${r}`}if(e==="@/workflows")return `${t.aliases.api}/workflows`;if(e.startsWith("@/api/")){let r=e.replace(/^@\/api\//,"");return `${t.aliases.api}/api/${r}`}if(e==="@/api")return `${t.aliases.api}/api`;if(e.startsWith("@/links/")){let r=e.replace(/^@\/links\//,"");return `${t.aliases.api}/links/${r}`}if(e==="@/links")return `${t.aliases.api}/links`;if(e.startsWith("@/modules/")){let r=e.replace(/^@\/modules\//,"");return `${t.aliases.api}/modules/${r}`}if(e==="@/modules")return `${t.aliases.api}/modules`;if(e.startsWith("@/lib/")){let r=e.replace(/^@\/lib\//,"");return `${t.aliases.api}/lib/${r}`}if(e==="@/lib")return `${t.aliases.api}/lib`;if(e.startsWith("@/vendor/")){let r=e.replace(/^@\/vendor\//,"");return `${t.aliases.vendor}/${r}`}if(e==="@/vendor")return t.aliases.vendor;if(e.startsWith("@/admin/")){let r=e.replace(/^@\/admin\//,"");return `${t.aliases.admin}/${r}`}return e==="@/admin"?t.aliases.admin:e}async function tr(e,t,r){if(!e?.length)return {filesCreated:[],filesUpdated:[],filesSkipped:[],filesDeclined:[]};r={overwrite:false,silent:false,yes:false,...r};let o=x("Updating files.",{silent:r.silent})?.start(),s=await b(t.resolvedPaths.cwd),n=[],i=[],f=[],c=[];for(let p of e){let g=Be(p,t,{isSrcDir:s?.isSrcDir??false,path:r.path??""}),h=basename(p.path),y=v__default.dirname(g),w=existsSync(g);if(w&&statSync(g).isDirectory())throw new Error(`Cannot write to ${g}: path exists and is a directory. Please provide a file path instead.`);let k=await We({filename:p.path,raw:p.content,config:t});if(w&&!r.overwrite){let O=await promises.readFile(g,"utf-8");if(Zt(O,k)){f.push(v__default.relative(t.resolvedPaths.cwd,g));continue}if(!r.yes){o.stop();let D=diffLines(O,k);l.info(`
20
+ File: ${u.info(h)}`),ts(D);let{overwrite:ke}=await ft({type:"confirm",name:"overwrite",message:`The file ${u.info(h)} already exists. Would you like to overwrite?`,initial:false});if(!ke){c.push(v__default.relative(t.resolvedPaths.cwd,g));continue}}}existsSync(y)||await promises.mkdir(y,{recursive:true}),await promises.writeFile(g,k,"utf-8"),w?i.push(v__default.relative(t.resolvedPaths.cwd,g)):n.push(v__default.relative(t.resolvedPaths.cwd,g));}let a=n.length+i.length,m=f.length+c.length;if(a>0){if(o?.succeed(),m>0&&!r.silent){let p=[];a===1?p.push("1 file updated"):p.push(`${a} files updated`),m===1?p.push("1 file skipped"):p.push(`${m} files skipped`),l.info(`${p.join(", ")}.`);}}else c.length?o?.info("No files were updated."):f.length?o?.info("Already up to date."):o?.info("No files to update.");return {filesCreated:n,filesUpdated:i,filesSkipped:f,filesDeclined:c}}var Qo=3;function es(e,t=Qo){let r=[],o=new Set;for(let n=0;n<e.length;n++)(e[n]?.added||e[n]?.removed)&&o.add(n);if(o.size===0)return r;let s=new Map;for(let n=0;n<e.length;n++){let i=e[n];if(i)if(i.added||i.removed)s.set(n,"full");else {let f=o.has(n-1),c=o.has(n+1);f&&c?s.set(n,"both"):f?s.set(n,"start"):c&&s.set(n,"end");}}for(let n=0;n<e.length;n++){let i=e[n],f=s.get(n);if(!(!i||!f))if(i.added){let c=i.value.split(`
21
+ `);c[c.length-1]===""&&c.pop();for(let a of c)r.push(`+ ${a}`);}else if(i.removed){let c=i.value.split(`
22
+ `);c[c.length-1]===""&&c.pop();for(let a of c)r.push(`- ${a}`);}else {let c=i.value.split(`
23
+ `);c[c.length-1]===""&&c.pop();let a=[];f==="full"||c.length<=t*2+1?a=c.map(m=>` ${m}`):f==="start"?(a=c.slice(0,t).map(m=>` ${m}`),c.length>t&&a.push(` ... ${c.length-t} lines hidden ...`)):f==="end"?(c.length>t&&a.push(` ... ${c.length-t} lines hidden ...`),a.push(...c.slice(-t).map(m=>` ${m}`))):f==="both"&&(c.length<=t*2+1?a=c.map(m=>` ${m}`):a=[...c.slice(0,t).map(m=>` ${m}`),` ... ${c.length-t*2} lines hidden ...`,...c.slice(-t).map(m=>` ${m}`)]),r.push(...a);}}return r}function ts(e){let t=es(e);if(t.length!==0)for(let r of t)r.startsWith("+ ")?process.stdout.write(`${u.success(r)}
24
+ `):r.startsWith("- ")?process.stdout.write(`${u.error(r)}
25
+ `):r.includes("lines hidden")?process.stdout.write(`${u.info(r)}
26
26
  `):process.stdout.write(`${r}
27
- `);}async function gr(e,t,r){if(r={overwrite:false,silent:false,yes:false,...r},!e.length)return;let o=v("Checking registry.",{silent:r.silent})?.start(),i=await ct(e,me(t));if(!i)return o?.fail(),j(new Error("Failed to fetch items from registry."));o?.succeed();let{filesCreated:s,filesUpdated:n}=await fr(i.files,t,{overwrite:r.overwrite,silent:r.silent,path:r.path,yes:r.yes});(s.length||n.length)&&await mr(i.dependencies,i.devDependencies,t,{silent:r.silent}),i.docs&&a.info(i.docs);}z.object({cwd:z.string(),yes:z.boolean(),defaults:z.boolean(),silent:z.boolean()});async function yr(e){let t={},r=R__default.resolve(e.cwd);existsSync(r)||(t.MISSING_DIR=true);let o=await k(r);return {errors:t,projectInfo:o}}var vr=join(homedir(),".mercur"),lt=join(vr,"config.json"),ft={telemetry_enabled:true,telemetry_email:null,notice_shown:false},gt=class{get(t){return this.read()[t]}set(t,r){let o=this.read();o[t]=r,this.write(o);}read(){try{if(!existsSync(lt))return {...ft};let t=readFileSync(lt,"utf-8"),r=JSON.parse(t);return {...ft,...r}}catch{return {...ft}}}write(t){try{mkdirSync(vr,{recursive:!0}),writeFileSync(lt,JSON.stringify(t,null,2)+`
28
- `,{mode:384});}catch{}}},M=new gt;var le=e=>Function("mm","return import(mm)")(e);function Ci(){let e=(...t)=>t.some(r=>!!process.env[r]);return e("MEDUSA_CLOUD_ENVIRONMENT_HANDLE","MEDUSA_CLOUD_SANDBOX_HANDLE","MEDUSA_CLOUD_API_KEY")?"medusa-cloud":e("RENDER","RENDER_URL","RENDER_INTERNAL_HOSTNAME","RENDER_SERVICE_ID")?"render":e("FLY_APP_NAME","FLY_REGION","FLY_ALLOC_ID")?"fly-io":e("RAILWAY_STATIC_URL","RAILWAY_ENVIRONMENT_NAME")?"railway":e("DYNO","HEROKU_APP_NAME")?"heroku":e("DO_DEPLOYMENT_ID","DO_APP_NAME","DIGITALOCEAN")?"digitalocean":e("KOYEB","KOYEB_DEPLOYMENT_ID","KOYEB_APP_NAME")?"koyeb":null}async function jr(){try{let e=await le("os"),t=e.cpus();return {deploymentVendor:Ci(),systemPlatform:e.platform(),systemRelease:e.release(),systemArchitecture:e.arch(),cpuCount:t.length,cpuModel:t.length?t[0].model:null,cpuSpeed:t.length?t[0].speed:null,memory:e.totalmem(),isWSL:await Pi(),isDocker:await br(),isTTY:typeof process<"u"&&process.stdout?process.stdout.isTTY:null}}catch{return {systemPlatform:null,systemRelease:null,systemArchitecture:null,cpuCount:null,cpuModel:null,cpuSpeed:null,memory:null,isWSL:null,isDocker:null,isTTY:null}}}async function Pi(){try{if(typeof process>"u"||process?.platform!=="linux")return !1;let e=await le("fs");return (await le("os")).release().toLowerCase().includes("microsoft")?!await wr():e.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")?!await wr():!1}catch{return false}}var Ti=async()=>{try{return (await le("fs")).statSync("/run/.containerenv"),!0}catch{return false}};async function br(){return await $i()||await Di()}async function $i(){try{return (await le("fs")).statSync("/.dockerenv"),!0}catch{return false}}async function Di(){try{return (await le("fs")).readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return false}}async function wr(){return await Ti()||await br()}var yt=e=>createHash("sha256").update(e).digest("base64");var Oi=process.env.MERCUR_TELEMETRY_PROXY_URL||"https://telemetry.mercurjs.com/api/v1/events",Rr=e=>{M.set("telemetry_email",e);},xr=e=>{M.set("telemetry_enabled",e);},Ke="https://docs.mercurjs.com/telemetry",H=()=>{M.get("notice_shown")||(M.set("notice_shown",true),process.env.MERCUR_DISABLE_TELEMETRY!=="true"&&console.error(["","Mercur collects anonymous usage data to improve the CLI experience.",`You can disable this at any time by running: ${l.info("mercurjs telemetry --disable")}`,`Or by setting ${l.info("MERCUR_DISABLE_TELEMETRY=true")}`,`Learn more: ${l.info(Ke)}`,""].join(`
29
- `)));},Ai=()=>M.get("telemetry_enabled")&&process.env.MERCUR_DISABLE_TELEMETRY!=="true",P=async(e,t)=>{try{if(!Ai())return;let r=await k(t.cwd),{projectId:o}=Ui(r.packageJson),i={nodeEnv:Li(),nodeVersion:process.version,mercurVersion:r.mercurVersion,medusaVersion:r.medusaVersion,isSrcDir:r.isSrcDir,aliasPrefix:r.aliasPrefix,config:await b(t.cwd),projectId:o,systemInfo:await jr(),packageManager:await A(t.cwd),email:zi()};await fetch(Oi,{body:JSON.stringify({...i,...e}),headers:{"Content-Type":"application/json"},method:"post"});}catch{}};function Li(){return process.env.NODE_ENV||"development"}var Mi=()=>{try{let e=execSync("git config --local --get remote.origin.url",{stdio:"pipe",timeout:1e3});return String(e).trim()}catch{return null}},Ui=e=>{let t=Mi();if(t)return {projectId:yt(t)};let r=process.cwd();return {projectId:yt(r)}},zi=()=>M.get("telemetry_email")||void 0;var Gi=z.object({cwd:z.string(),yes:z.boolean(),defaults:z.boolean(),silent:z.boolean()}),kr=new Command().name("init").description("initialize your project and install dependencies").option("-y, --yes","skip confirmation prompt.",true).option("-d, --defaults","use default configuration.",false).option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).option("-s, --silent","mute output.",false).action(async e=>{try{H();let t=Gi.parse({cwd:R__default.resolve(e.cwd),...e});await vt(t),a.log(`${l.success("Success!")} Project initialization completed.
30
- You may now add blocks.`),a.break(),await P({type:"init",payload:{outcome:"success"}},{cwd:t.cwd});}catch(t){a.break(),j(t);}finally{x();}});async function vt(e){await yr(e);let t=await b(e.cwd),r=t?await Yi(t,e):await Vi(e);if(!e.yes){let{proceed:s}=await Pe({type:"confirm",name:"proceed",message:`Write configuration to ${l.info("blocks.json")}. Proceed?`,initial:true});s||process.exit(0);}let o=v("Writing blocks.json.").start(),i=R__default.resolve(e.cwd,"blocks.json");return r.registries=Object.fromEntries(Object.entries(r.registries||{}).filter(([s])=>!Object.keys(I).includes(s))),await promises.writeFile(i,`${JSON.stringify(r,null,2)}
31
- `,"utf8"),o.succeed(),await st(e.cwd,r)}async function Vi(e){if(e.defaults)return W.parse({$schema:Oe,aliases:{api:"packages/api/src",vendor:"apps/vendor/src",admin:"apps/admin/src"},registries:I});a.info("");let t=await Pe([{type:"text",name:"api",message:`Configure the import alias for ${l.info("api")}:`,initial:"packages/api/src"},{type:"text",name:"vendor",message:`Configure the import alias for ${l.info("vendor")}:`,initial:"apps/vendor/src"},{type:"text",name:"admin",message:`Configure the import alias for ${l.info("admin")}:`,initial:"apps/admin/src"}],{onCancel:()=>{process.exit(0);}});return W.parse({$schema:Oe,aliases:{api:t.api??"packages/api/src",vendor:t.vendor??"apps/vendor/src",admin:t.admin??"apps/admin/src"},registries:I})}async function Yi(e,t){if(t.defaults)return W.parse({$schema:Oe,aliases:{api:"packages/api/src",vendor:"apps/vendor/src",admin:"apps/admin/src"},registries:I});let r=await Pe([{type:"text",name:"api",message:`Configure the import alias for ${l.info("api")}:`,initial:e.aliases.api},{type:"text",name:"vendor",message:`Configure the import alias for ${l.info("vendor")}:`,initial:e.aliases.vendor},{type:"text",name:"admin",message:`Configure the import alias for ${l.info("admin")}:`,initial:e.aliases.admin}],{onCancel:()=>{process.exit(0);}});return W.parse({$schema:e.$schema,aliases:{api:r.api??e.aliases.api,vendor:r.vendor??e.aliases.vendor,admin:r.admin??e.aliases.admin}})}var Ki=z.object({blocks:z.array(z.string()).optional(),yes:z.boolean(),overwrite:z.boolean(),cwd:z.string(),silent:z.boolean()}),Er=new Command().name("add").description("add blocks to your project").argument("[blocks...]","names of blocks to add").option("-y, --yes","skip confirmation prompt.",false).option("-o, --overwrite","overwrite existing files.",false).option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).option("-s, --silent","mute output.",false).action(async(e,t)=>{try{H();let r=Ki.parse({blocks:e,cwd:R__default.resolve(t.cwd),...t}),o=await b(r.cwd);o||(o=G({resolvedPaths:{cwd:r.cwd}})),r.blocks?.length||(a.error("Please specify at least one item to add."),process.exit(1));let{errors:i}=await qt(r);if(i[S]){let{proceed:s}=await Pe({type:"confirm",name:"proceed",message:`You need to create a ${l.info("blocks.json")} file to add items. Proceed?`,initial:!0});s||(a.break(),process.exit(1)),o=await vt({cwd:r.cwd,yes:!0,defaults:!1,silent:r.silent});}if(!o)throw new Error(`Failed to read config at ${l.info(r.cwd)}.`);await gr(r.blocks,o,{overwrite:r.overwrite,silent:r.silent,yes:r.yes,path:r.cwd}),await P({type:"add",payload:{outcome:"success",blocks:r.blocks}},{cwd:r.cwd});}catch(r){a.break(),j(r);}finally{x();}});async function Sr(e){let t={},r={cwd:e.cwd,registryFile:R__default.resolve(e.cwd,e.registryFile),outputDir:R__default.resolve(e.cwd,e.outputDir)};if(!L.existsSync(r.registryFile))return t[B]=true,{errors:t,resolvePaths:null,config:null};if(!L.existsSync(R__default.resolve(e.cwd,"blocks.json")))return t[S]=true,{errors:t,resolvePaths:null,config:null};await L.mkdir(r.outputDir,{recursive:true});try{let o=await b(e.cwd);return {errors:t,config:o,resolvePaths:r}}catch{a.break(),a.error(`An invalid ${l.info("blocks.json")} file was found at ${l.info(e.cwd)}.
32
- Before you can build the registry, you must create a valid ${l.info("blocks.json")} file by running the ${l.info("init")} command.`),a.break(),process.exit(1);}}var Qi=z.object({cwd:z.string(),registryFile:z.string(),outputDir:z.string(),verbose:z.boolean().optional().default(false)}),Ir=new Command().name("registry:build").description("builds the registry").argument("[registry]","path to registry.json file","./registry.json").option("-o, --output <path>","destination directory for json files","./r").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).option("-v, --verbose","verbose output").action(async(e,t)=>{await Xi({cwd:R.resolve(t.cwd),registryFile:e,outputDir:t.output,verbose:t.verbose});});async function Xi(e){try{H();let t=Qi.parse(e),[{errors:r,resolvePaths:o,config:i},s]=await Promise.all([Sr(t),k(t.cwd)]);(r[S]||!s)&&(a.error(`A ${l.info("blocks.json")} file is required to build the registry. Run ${l.info("mercur init")} to create one.`),a.break(),await P({type:"build",payload:{outcome:"missing_config"}},{cwd:t.cwd}),process.exit(1)),(r[B]||!o)&&(a.error(`We could not find a registry file at ${l.info(R.resolve(t.cwd,t.registryFile))}.`),a.break(),await P({type:"build",payload:{outcome:"missing_registry_file"}},{cwd:t.cwd}),process.exit(1));let n=await U.readFile(o.registryFile,"utf-8"),m=K.safeParse(JSON.parse(n));m.success||(a.error(`Invalid registry file found at ${l.info(o.registryFile)}.`),a.break(),process.exit(1));let p=v("Building registry..."),d=await es(m.data,i,s);for(let u of d.items)u.files=u.files?.filter((c,f,y)=>f===y.findIndex(h=>h.path===c.path)),u.dependencies&&(u.dependencies=u.dependencies.filter((c,f,y)=>f===y.findIndex(h=>h===c)));for(let u of d.items){if(!u.files)continue;p.start(`Building ${u.name}...`),u.$schema=Wt;for(let f of u.files){let y=s.isSrcDir?"src":"",h=R.resolve(o.cwd,y,f.path);try{if(!(await U.stat(h)).isFile())continue;f.content=await U.readFile(h,"utf-8");}catch(w){console.error("Error reading file in registry build:",h,w);continue}}let c=T.safeParse(u);if(!c.success){a.error(`Invalid registry item found for ${l.info(u.name)}.`);continue}await U.writeFile(R.resolve(o.outputDir,`${c.data.name}.json`),JSON.stringify(c.data,null,2));}if(await U.copyFile(o.registryFile,R.resolve(o.outputDir,"registry.json")),p.succeed("Building registry."),t.verbose){v(`The registry has ${l.info(d.items.length.toString())} items:`).succeed();for(let u of d.items){a.log(` - ${u.name}`);for(let c of u.files??[])a.log(` - ${c.path}`);}}await P({type:"build",payload:{outcome:"success"}},{cwd:t.cwd});}catch(t){a.break(),j(t);}}async function es(e,t,r){for(let o of e.items)if(o.files?.length)for(let i of o.files){let s=await mt(i.path,t,r);s.files=s.files?.filter(n=>n.path!==i.path),s.files&&o.files.push(...s.files),s.dependencies&&(o.dependencies=o.dependencies?o.dependencies.concat(s.dependencies):s.dependencies);}return e}var Ze=".mercur",oe=/route\.(ts|js)$/,Cr={"/admin/api-keys":'typeof import("@medusajs/medusa/api/admin/api-keys/route")',"/admin/api-keys/:id":'typeof import("@medusajs/medusa/api/admin/api-keys/[id]/route")',"/admin/api-keys/:id/revoke":'typeof import("@medusajs/medusa/api/admin/api-keys/[id]/revoke/route")',"/admin/api-keys/:id/sales-channels":'typeof import("@medusajs/medusa/api/admin/api-keys/[id]/sales-channels/route")',"/admin/campaigns":'typeof import("@medusajs/medusa/api/admin/campaigns/route")',"/admin/campaigns/:id":'typeof import("@medusajs/medusa/api/admin/campaigns/[id]/route")',"/admin/campaigns/:id/promotions":'typeof import("@medusajs/medusa/api/admin/campaigns/[id]/promotions/route")',"/admin/claims":'typeof import("@medusajs/medusa/api/admin/claims/route")',"/admin/claims/:id":'typeof import("@medusajs/medusa/api/admin/claims/[id]/route")',"/admin/claims/:id/cancel":'typeof import("@medusajs/medusa/api/admin/claims/[id]/cancel/route")',"/admin/claims/:id/claim-items":'typeof import("@medusajs/medusa/api/admin/claims/[id]/claim-items/route")',"/admin/claims/:id/claim-items/:action_id":'typeof import("@medusajs/medusa/api/admin/claims/[id]/claim-items/[action_id]/route")',"/admin/claims/:id/inbound/items":'typeof import("@medusajs/medusa/api/admin/claims/[id]/inbound/items/route")',"/admin/claims/:id/inbound/items/:action_id":'typeof import("@medusajs/medusa/api/admin/claims/[id]/inbound/items/[action_id]/route")',"/admin/claims/:id/inbound/shipping-method":'typeof import("@medusajs/medusa/api/admin/claims/[id]/inbound/shipping-method/route")',"/admin/claims/:id/inbound/shipping-method/:action_id":'typeof import("@medusajs/medusa/api/admin/claims/[id]/inbound/shipping-method/[action_id]/route")',"/admin/claims/:id/outbound/items":'typeof import("@medusajs/medusa/api/admin/claims/[id]/outbound/items/route")',"/admin/claims/:id/outbound/items/:action_id":'typeof import("@medusajs/medusa/api/admin/claims/[id]/outbound/items/[action_id]/route")',"/admin/claims/:id/outbound/shipping-method":'typeof import("@medusajs/medusa/api/admin/claims/[id]/outbound/shipping-method/route")',"/admin/claims/:id/outbound/shipping-method/:action_id":'typeof import("@medusajs/medusa/api/admin/claims/[id]/outbound/shipping-method/[action_id]/route")',"/admin/claims/:id/request":'typeof import("@medusajs/medusa/api/admin/claims/[id]/request/route")',"/admin/collections":'typeof import("@medusajs/medusa/api/admin/collections/route")',"/admin/collections/:id":'typeof import("@medusajs/medusa/api/admin/collections/[id]/route")',"/admin/collections/:id/products":'typeof import("@medusajs/medusa/api/admin/collections/[id]/products/route")',"/admin/currencies":'typeof import("@medusajs/medusa/api/admin/currencies/route")',"/admin/currencies/:code":'typeof import("@medusajs/medusa/api/admin/currencies/[code]/route")',"/admin/customer-groups":'typeof import("@medusajs/medusa/api/admin/customer-groups/route")',"/admin/customer-groups/:id":'typeof import("@medusajs/medusa/api/admin/customer-groups/[id]/route")',"/admin/customer-groups/:id/customers":'typeof import("@medusajs/medusa/api/admin/customer-groups/[id]/customers/route")',"/admin/customers":'typeof import("@medusajs/medusa/api/admin/customers/route")',"/admin/customers/:id":'typeof import("@medusajs/medusa/api/admin/customers/[id]/route")',"/admin/customers/:id/addresses":'typeof import("@medusajs/medusa/api/admin/customers/[id]/addresses/route")',"/admin/customers/:id/addresses/:address_id":'typeof import("@medusajs/medusa/api/admin/customers/[id]/addresses/[address_id]/route")',"/admin/customers/:id/customer-groups":'typeof import("@medusajs/medusa/api/admin/customers/[id]/customer-groups/route")',"/admin/draft-orders":'typeof import("@medusajs/medusa/api/admin/draft-orders/route")',"/admin/draft-orders/:id":'typeof import("@medusajs/medusa/api/admin/draft-orders/[id]/route")',"/admin/draft-orders/:id/convert-to-order":'typeof import("@medusajs/medusa/api/admin/draft-orders/[id]/convert-to-order/route")',"/admin/draft-orders/:id/edit":'typeof import("@medusajs/medusa/api/admin/draft-orders/[id]/edit/route")',"/admin/draft-orders/:id/edit/confirm":'typeof import("@medusajs/medusa/api/admin/draft-orders/[id]/edit/confirm/route")',"/admin/draft-orders/:id/edit/items":'typeof import("@medusajs/medusa/api/admin/draft-orders/[id]/edit/items/route")',"/admin/draft-orders/:id/edit/items/:action_id":'typeof import("@medusajs/medusa/api/admin/draft-orders/[id]/edit/items/[action_id]/route")',"/admin/draft-orders/:id/edit/items/item/:item_id":'typeof import("@medusajs/medusa/api/admin/draft-orders/[id]/edit/items/item/[item_id]/route")',"/admin/draft-orders/:id/edit/promotions":'typeof import("@medusajs/medusa/api/admin/draft-orders/[id]/edit/promotions/route")',"/admin/draft-orders/:id/edit/request":'typeof import("@medusajs/medusa/api/admin/draft-orders/[id]/edit/request/route")',"/admin/draft-orders/:id/edit/shipping-methods":'typeof import("@medusajs/medusa/api/admin/draft-orders/[id]/edit/shipping-methods/route")',"/admin/draft-orders/:id/edit/shipping-methods/:action_id":'typeof import("@medusajs/medusa/api/admin/draft-orders/[id]/edit/shipping-methods/[action_id]/route")',"/admin/draft-orders/:id/edit/shipping-methods/method/:method_id":'typeof import("@medusajs/medusa/api/admin/draft-orders/[id]/edit/shipping-methods/method/[method_id]/route")',"/admin/exchanges":'typeof import("@medusajs/medusa/api/admin/exchanges/route")',"/admin/exchanges/:id":'typeof import("@medusajs/medusa/api/admin/exchanges/[id]/route")',"/admin/exchanges/:id/cancel":'typeof import("@medusajs/medusa/api/admin/exchanges/[id]/cancel/route")',"/admin/exchanges/:id/inbound/items":'typeof import("@medusajs/medusa/api/admin/exchanges/[id]/inbound/items/route")',"/admin/exchanges/:id/inbound/items/:action_id":'typeof import("@medusajs/medusa/api/admin/exchanges/[id]/inbound/items/[action_id]/route")',"/admin/exchanges/:id/inbound/shipping-method":'typeof import("@medusajs/medusa/api/admin/exchanges/[id]/inbound/shipping-method/route")',"/admin/exchanges/:id/inbound/shipping-method/:action_id":'typeof import("@medusajs/medusa/api/admin/exchanges/[id]/inbound/shipping-method/[action_id]/route")',"/admin/exchanges/:id/outbound/items":'typeof import("@medusajs/medusa/api/admin/exchanges/[id]/outbound/items/route")',"/admin/exchanges/:id/outbound/items/:action_id":'typeof import("@medusajs/medusa/api/admin/exchanges/[id]/outbound/items/[action_id]/route")',"/admin/exchanges/:id/outbound/shipping-method":'typeof import("@medusajs/medusa/api/admin/exchanges/[id]/outbound/shipping-method/route")',"/admin/exchanges/:id/outbound/shipping-method/:action_id":'typeof import("@medusajs/medusa/api/admin/exchanges/[id]/outbound/shipping-method/[action_id]/route")',"/admin/exchanges/:id/request":'typeof import("@medusajs/medusa/api/admin/exchanges/[id]/request/route")',"/admin/feature-flags":'typeof import("@medusajs/medusa/api/admin/feature-flags/route")',"/admin/fulfillment-providers":'typeof import("@medusajs/medusa/api/admin/fulfillment-providers/route")',"/admin/fulfillment-providers/:id/options":'typeof import("@medusajs/medusa/api/admin/fulfillment-providers/[id]/options/route")',"/admin/fulfillment-sets/:id":'typeof import("@medusajs/medusa/api/admin/fulfillment-sets/[id]/route")',"/admin/fulfillment-sets/:id/service-zones":'typeof import("@medusajs/medusa/api/admin/fulfillment-sets/[id]/service-zones/route")',"/admin/fulfillment-sets/:id/service-zones/:zone_id":'typeof import("@medusajs/medusa/api/admin/fulfillment-sets/[id]/service-zones/[zone_id]/route")',"/admin/fulfillments":'typeof import("@medusajs/medusa/api/admin/fulfillments/route")',"/admin/fulfillments/:id/cancel":'typeof import("@medusajs/medusa/api/admin/fulfillments/[id]/cancel/route")',"/admin/fulfillments/:id/shipment":'typeof import("@medusajs/medusa/api/admin/fulfillments/[id]/shipment/route")',"/admin/index/details":'typeof import("@medusajs/medusa/api/admin/index/details/route")',"/admin/index/sync":'typeof import("@medusajs/medusa/api/admin/index/sync/route")',"/admin/inventory-items":'typeof import("@medusajs/medusa/api/admin/inventory-items/route")',"/admin/inventory-items/:id":'typeof import("@medusajs/medusa/api/admin/inventory-items/[id]/route")',"/admin/inventory-items/:id/location-levels":'typeof import("@medusajs/medusa/api/admin/inventory-items/[id]/location-levels/route")',"/admin/inventory-items/:id/location-levels/:location_id":'typeof import("@medusajs/medusa/api/admin/inventory-items/[id]/location-levels/[location_id]/route")',"/admin/inventory-items/:id/location-levels/batch":'typeof import("@medusajs/medusa/api/admin/inventory-items/[id]/location-levels/batch/route")',"/admin/inventory-items/location-levels/batch":'typeof import("@medusajs/medusa/api/admin/inventory-items/location-levels/batch/route")',"/admin/invites":'typeof import("@medusajs/medusa/api/admin/invites/route")',"/admin/invites/:id":'typeof import("@medusajs/medusa/api/admin/invites/[id]/route")',"/admin/invites/:id/resend":'typeof import("@medusajs/medusa/api/admin/invites/[id]/resend/route")',"/admin/invites/accept":'typeof import("@medusajs/medusa/api/admin/invites/accept/route")',"/admin/locales":'typeof import("@medusajs/medusa/api/admin/locales/route")',"/admin/locales/:code":'typeof import("@medusajs/medusa/api/admin/locales/[code]/route")',"/admin/notifications":'typeof import("@medusajs/medusa/api/admin/notifications/route")',"/admin/notifications/:id":'typeof import("@medusajs/medusa/api/admin/notifications/[id]/route")',"/admin/order-changes/:id":'typeof import("@medusajs/medusa/api/admin/order-changes/[id]/route")',"/admin/order-edits":'typeof import("@medusajs/medusa/api/admin/order-edits/route")',"/admin/order-edits/:id":'typeof import("@medusajs/medusa/api/admin/order-edits/[id]/route")',"/admin/order-edits/:id/confirm":'typeof import("@medusajs/medusa/api/admin/order-edits/[id]/confirm/route")',"/admin/order-edits/:id/items":'typeof import("@medusajs/medusa/api/admin/order-edits/[id]/items/route")',"/admin/order-edits/:id/items/:action_id":'typeof import("@medusajs/medusa/api/admin/order-edits/[id]/items/[action_id]/route")',"/admin/order-edits/:id/items/item/:item_id":'typeof import("@medusajs/medusa/api/admin/order-edits/[id]/items/item/[item_id]/route")',"/admin/order-edits/:id/request":'typeof import("@medusajs/medusa/api/admin/order-edits/[id]/request/route")',"/admin/order-edits/:id/shipping-method":'typeof import("@medusajs/medusa/api/admin/order-edits/[id]/shipping-method/route")',"/admin/order-edits/:id/shipping-method/:action_id":'typeof import("@medusajs/medusa/api/admin/order-edits/[id]/shipping-method/[action_id]/route")',"/admin/orders":'typeof import("@medusajs/medusa/api/admin/orders/route")',"/admin/orders/:id":'typeof import("@medusajs/medusa/api/admin/orders/[id]/route")',"/admin/orders/:id/archive":'typeof import("@medusajs/medusa/api/admin/orders/[id]/archive/route")',"/admin/orders/:id/cancel":'typeof import("@medusajs/medusa/api/admin/orders/[id]/cancel/route")',"/admin/orders/:id/changes":'typeof import("@medusajs/medusa/api/admin/orders/[id]/changes/route")',"/admin/orders/:id/complete":'typeof import("@medusajs/medusa/api/admin/orders/[id]/complete/route")',"/admin/orders/:id/credit-lines":'typeof import("@medusajs/medusa/api/admin/orders/[id]/credit-lines/route")',"/admin/orders/:id/fulfillments":'typeof import("@medusajs/medusa/api/admin/orders/[id]/fulfillments/route")',"/admin/orders/:id/fulfillments/:fulfillment_id/cancel":'typeof import("@medusajs/medusa/api/admin/orders/[id]/fulfillments/[fulfillment_id]/cancel/route")',"/admin/orders/:id/fulfillments/:fulfillment_id/mark-as-delivered":'typeof import("@medusajs/medusa/api/admin/orders/[id]/fulfillments/[fulfillment_id]/mark-as-delivered/route")',"/admin/orders/:id/fulfillments/:fulfillment_id/shipments":'typeof import("@medusajs/medusa/api/admin/orders/[id]/fulfillments/[fulfillment_id]/shipments/route")',"/admin/orders/:id/line-items":'typeof import("@medusajs/medusa/api/admin/orders/[id]/line-items/route")',"/admin/orders/:id/preview":'typeof import("@medusajs/medusa/api/admin/orders/[id]/preview/route")',"/admin/orders/:id/shipping-options":'typeof import("@medusajs/medusa/api/admin/orders/[id]/shipping-options/route")',"/admin/orders/:id/transfer":'typeof import("@medusajs/medusa/api/admin/orders/[id]/transfer/route")',"/admin/orders/:id/transfer/cancel":'typeof import("@medusajs/medusa/api/admin/orders/[id]/transfer/cancel/route")',"/admin/orders/export":'typeof import("@medusajs/medusa/api/admin/orders/export/route")',"/admin/payment-collections":'typeof import("@medusajs/medusa/api/admin/payment-collections/route")',"/admin/payment-collections/:id":'typeof import("@medusajs/medusa/api/admin/payment-collections/[id]/route")',"/admin/payment-collections/:id/mark-as-paid":'typeof import("@medusajs/medusa/api/admin/payment-collections/[id]/mark-as-paid/route")',"/admin/payments":'typeof import("@medusajs/medusa/api/admin/payments/route")',"/admin/payments/:id":'typeof import("@medusajs/medusa/api/admin/payments/[id]/route")',"/admin/payments/:id/capture":'typeof import("@medusajs/medusa/api/admin/payments/[id]/capture/route")',"/admin/payments/:id/refund":'typeof import("@medusajs/medusa/api/admin/payments/[id]/refund/route")',"/admin/payments/payment-providers":'typeof import("@medusajs/medusa/api/admin/payments/payment-providers/route")',"/admin/plugins":'typeof import("@medusajs/medusa/api/admin/plugins/route")',"/admin/price-lists":'typeof import("@medusajs/medusa/api/admin/price-lists/route")',"/admin/price-lists/:id":'typeof import("@medusajs/medusa/api/admin/price-lists/[id]/route")',"/admin/price-lists/:id/prices":'typeof import("@medusajs/medusa/api/admin/price-lists/[id]/prices/route")',"/admin/price-lists/:id/prices/batch":'typeof import("@medusajs/medusa/api/admin/price-lists/[id]/prices/batch/route")',"/admin/price-lists/:id/products":'typeof import("@medusajs/medusa/api/admin/price-lists/[id]/products/route")',"/admin/price-preferences":'typeof import("@medusajs/medusa/api/admin/price-preferences/route")',"/admin/price-preferences/:id":'typeof import("@medusajs/medusa/api/admin/price-preferences/[id]/route")',"/admin/product-categories":'typeof import("@medusajs/medusa/api/admin/product-categories/route")',"/admin/product-categories/:id":'typeof import("@medusajs/medusa/api/admin/product-categories/[id]/route")',"/admin/product-categories/:id/products":'typeof import("@medusajs/medusa/api/admin/product-categories/[id]/products/route")',"/admin/product-tags":'typeof import("@medusajs/medusa/api/admin/product-tags/route")',"/admin/product-tags/:id":'typeof import("@medusajs/medusa/api/admin/product-tags/[id]/route")',"/admin/product-types":'typeof import("@medusajs/medusa/api/admin/product-types/route")',"/admin/product-types/:id":'typeof import("@medusajs/medusa/api/admin/product-types/[id]/route")',"/admin/product-variants":'typeof import("@medusajs/medusa/api/admin/product-variants/route")',"/admin/products":'typeof import("@medusajs/medusa/api/admin/products/route")',"/admin/products/:id":'typeof import("@medusajs/medusa/api/admin/products/[id]/route")',"/admin/products/:id/images/:image_id/variants/batch":'typeof import("@medusajs/medusa/api/admin/products/[id]/images/[image_id]/variants/batch/route")',"/admin/products/:id/options":'typeof import("@medusajs/medusa/api/admin/products/[id]/options/route")',"/admin/products/:id/options/:option_id":'typeof import("@medusajs/medusa/api/admin/products/[id]/options/[option_id]/route")',"/admin/products/:id/variants":'typeof import("@medusajs/medusa/api/admin/products/[id]/variants/route")',"/admin/products/:id/variants/:variant_id":'typeof import("@medusajs/medusa/api/admin/products/[id]/variants/[variant_id]/route")',"/admin/products/:id/variants/:variant_id/images/batch":'typeof import("@medusajs/medusa/api/admin/products/[id]/variants/[variant_id]/images/batch/route")',"/admin/products/:id/variants/:variant_id/inventory-items":'typeof import("@medusajs/medusa/api/admin/products/[id]/variants/[variant_id]/inventory-items/route")',"/admin/products/:id/variants/:variant_id/inventory-items/:inventory_item_id":'typeof import("@medusajs/medusa/api/admin/products/[id]/variants/[variant_id]/inventory-items/[inventory_item_id]/route")',"/admin/products/:id/variants/batch":'typeof import("@medusajs/medusa/api/admin/products/[id]/variants/batch/route")',"/admin/products/:id/variants/inventory-items/batch":'typeof import("@medusajs/medusa/api/admin/products/[id]/variants/inventory-items/batch/route")',"/admin/products/batch":'typeof import("@medusajs/medusa/api/admin/products/batch/route")',"/admin/products/export":'typeof import("@medusajs/medusa/api/admin/products/export/route")',"/admin/products/import":'typeof import("@medusajs/medusa/api/admin/products/import/route")',"/admin/products/import/:transaction_id/confirm":'typeof import("@medusajs/medusa/api/admin/products/import/[transaction_id]/confirm/route")',"/admin/products/imports":'typeof import("@medusajs/medusa/api/admin/products/imports/route")',"/admin/products/imports/:transaction_id/confirm":'typeof import("@medusajs/medusa/api/admin/products/imports/[transaction_id]/confirm/route")',"/admin/promotions":'typeof import("@medusajs/medusa/api/admin/promotions/route")',"/admin/promotions/:id":'typeof import("@medusajs/medusa/api/admin/promotions/[id]/route")',"/admin/promotions/:id/:rule_type":'typeof import("@medusajs/medusa/api/admin/promotions/[id]/[rule_type]/route")',"/admin/promotions/:id/buy-rules/batch":'typeof import("@medusajs/medusa/api/admin/promotions/[id]/buy-rules/batch/route")',"/admin/promotions/:id/rules/batch":'typeof import("@medusajs/medusa/api/admin/promotions/[id]/rules/batch/route")',"/admin/promotions/:id/target-rules/batch":'typeof import("@medusajs/medusa/api/admin/promotions/[id]/target-rules/batch/route")',"/admin/promotions/rule-attribute-options/:rule_type":'typeof import("@medusajs/medusa/api/admin/promotions/rule-attribute-options/[rule_type]/route")',"/admin/promotions/rule-value-options/:rule_type/:rule_attribute_id":'typeof import("@medusajs/medusa/api/admin/promotions/rule-value-options/[rule_type]/[rule_attribute_id]/route")',"/admin/rbac/policies":'typeof import("@medusajs/medusa/api/admin/rbac/policies/route")',"/admin/rbac/policies/:id":'typeof import("@medusajs/medusa/api/admin/rbac/policies/[id]/route")',"/admin/rbac/roles":'typeof import("@medusajs/medusa/api/admin/rbac/roles/route")',"/admin/rbac/roles/:id":'typeof import("@medusajs/medusa/api/admin/rbac/roles/[id]/route")',"/admin/rbac/roles/:id/policies":'typeof import("@medusajs/medusa/api/admin/rbac/roles/[id]/policies/route")',"/admin/rbac/roles/:id/policies/:policy_id":'typeof import("@medusajs/medusa/api/admin/rbac/roles/[id]/policies/[policy_id]/route")',"/admin/refund-reasons":'typeof import("@medusajs/medusa/api/admin/refund-reasons/route")',"/admin/refund-reasons/:id":'typeof import("@medusajs/medusa/api/admin/refund-reasons/[id]/route")',"/admin/regions":'typeof import("@medusajs/medusa/api/admin/regions/route")',"/admin/regions/:id":'typeof import("@medusajs/medusa/api/admin/regions/[id]/route")',"/admin/reservations":'typeof import("@medusajs/medusa/api/admin/reservations/route")',"/admin/reservations/:id":'typeof import("@medusajs/medusa/api/admin/reservations/[id]/route")',"/admin/return-reasons":'typeof import("@medusajs/medusa/api/admin/return-reasons/route")',"/admin/return-reasons/:id":'typeof import("@medusajs/medusa/api/admin/return-reasons/[id]/route")',"/admin/returns":'typeof import("@medusajs/medusa/api/admin/returns/route")',"/admin/returns/:id":'typeof import("@medusajs/medusa/api/admin/returns/[id]/route")',"/admin/returns/:id/cancel":'typeof import("@medusajs/medusa/api/admin/returns/[id]/cancel/route")',"/admin/returns/:id/dismiss-items":'typeof import("@medusajs/medusa/api/admin/returns/[id]/dismiss-items/route")',"/admin/returns/:id/dismiss-items/:action_id":'typeof import("@medusajs/medusa/api/admin/returns/[id]/dismiss-items/[action_id]/route")',"/admin/returns/:id/receive":'typeof import("@medusajs/medusa/api/admin/returns/[id]/receive/route")',"/admin/returns/:id/receive-items":'typeof import("@medusajs/medusa/api/admin/returns/[id]/receive-items/route")',"/admin/returns/:id/receive-items/:action_id":'typeof import("@medusajs/medusa/api/admin/returns/[id]/receive-items/[action_id]/route")',"/admin/returns/:id/receive/confirm":'typeof import("@medusajs/medusa/api/admin/returns/[id]/receive/confirm/route")',"/admin/returns/:id/request":'typeof import("@medusajs/medusa/api/admin/returns/[id]/request/route")',"/admin/returns/:id/request-items":'typeof import("@medusajs/medusa/api/admin/returns/[id]/request-items/route")',"/admin/returns/:id/request-items/:action_id":'typeof import("@medusajs/medusa/api/admin/returns/[id]/request-items/[action_id]/route")',"/admin/returns/:id/shipping-method":'typeof import("@medusajs/medusa/api/admin/returns/[id]/shipping-method/route")',"/admin/returns/:id/shipping-method/:action_id":'typeof import("@medusajs/medusa/api/admin/returns/[id]/shipping-method/[action_id]/route")',"/admin/sales-channels":'typeof import("@medusajs/medusa/api/admin/sales-channels/route")',"/admin/sales-channels/:id":'typeof import("@medusajs/medusa/api/admin/sales-channels/[id]/route")',"/admin/sales-channels/:id/products":'typeof import("@medusajs/medusa/api/admin/sales-channels/[id]/products/route")',"/admin/shipping-option-types":'typeof import("@medusajs/medusa/api/admin/shipping-option-types/route")',"/admin/shipping-option-types/:id":'typeof import("@medusajs/medusa/api/admin/shipping-option-types/[id]/route")',"/admin/shipping-options":'typeof import("@medusajs/medusa/api/admin/shipping-options/route")',"/admin/shipping-options/:id":'typeof import("@medusajs/medusa/api/admin/shipping-options/[id]/route")',"/admin/shipping-options/:id/rules/batch":'typeof import("@medusajs/medusa/api/admin/shipping-options/[id]/rules/batch/route")',"/admin/shipping-profiles":'typeof import("@medusajs/medusa/api/admin/shipping-profiles/route")',"/admin/shipping-profiles/:id":'typeof import("@medusajs/medusa/api/admin/shipping-profiles/[id]/route")',"/admin/stock-locations":'typeof import("@medusajs/medusa/api/admin/stock-locations/route")',"/admin/stock-locations/:id":'typeof import("@medusajs/medusa/api/admin/stock-locations/[id]/route")',"/admin/stock-locations/:id/fulfillment-providers":'typeof import("@medusajs/medusa/api/admin/stock-locations/[id]/fulfillment-providers/route")',"/admin/stock-locations/:id/fulfillment-sets":'typeof import("@medusajs/medusa/api/admin/stock-locations/[id]/fulfillment-sets/route")',"/admin/stock-locations/:id/sales-channels":'typeof import("@medusajs/medusa/api/admin/stock-locations/[id]/sales-channels/route")',"/admin/stores":'typeof import("@medusajs/medusa/api/admin/stores/route")',"/admin/stores/:id":'typeof import("@medusajs/medusa/api/admin/stores/[id]/route")',"/admin/tax-providers":'typeof import("@medusajs/medusa/api/admin/tax-providers/route")',"/admin/tax-rates":'typeof import("@medusajs/medusa/api/admin/tax-rates/route")',"/admin/tax-rates/:id":'typeof import("@medusajs/medusa/api/admin/tax-rates/[id]/route")',"/admin/tax-rates/:id/rules":'typeof import("@medusajs/medusa/api/admin/tax-rates/[id]/rules/route")',"/admin/tax-rates/:id/rules/:rule_id":'typeof import("@medusajs/medusa/api/admin/tax-rates/[id]/rules/[rule_id]/route")',"/admin/tax-regions":'typeof import("@medusajs/medusa/api/admin/tax-regions/route")',"/admin/tax-regions/:id":'typeof import("@medusajs/medusa/api/admin/tax-regions/[id]/route")',"/admin/translations":'typeof import("@medusajs/medusa/api/admin/translations/route")',"/admin/translations/batch":'typeof import("@medusajs/medusa/api/admin/translations/batch/route")',"/admin/translations/entities":'typeof import("@medusajs/medusa/api/admin/translations/entities/route")',"/admin/translations/settings":'typeof import("@medusajs/medusa/api/admin/translations/settings/route")',"/admin/translations/settings/batch":'typeof import("@medusajs/medusa/api/admin/translations/settings/batch/route")',"/admin/translations/statistics":'typeof import("@medusajs/medusa/api/admin/translations/statistics/route")',"/admin/uploads":'typeof import("@medusajs/medusa/api/admin/uploads/route")',"/admin/uploads/:id":'typeof import("@medusajs/medusa/api/admin/uploads/[id]/route")',"/admin/uploads/presigned-urls":'typeof import("@medusajs/medusa/api/admin/uploads/presigned-urls/route")',"/admin/users":'typeof import("@medusajs/medusa/api/admin/users/route")',"/admin/users/:id":'typeof import("@medusajs/medusa/api/admin/users/[id]/route")',"/admin/users/me":'typeof import("@medusajs/medusa/api/admin/users/me/route")',"/admin/views/:entity/columns":'typeof import("@medusajs/medusa/api/admin/views/[entity]/columns/route")',"/admin/views/:entity/configurations":'typeof import("@medusajs/medusa/api/admin/views/[entity]/configurations/route")',"/admin/views/:entity/configurations/:id":'typeof import("@medusajs/medusa/api/admin/views/[entity]/configurations/[id]/route")',"/admin/views/:entity/configurations/active":'typeof import("@medusajs/medusa/api/admin/views/[entity]/configurations/active/route")',"/admin/workflows-executions":'typeof import("@medusajs/medusa/api/admin/workflows-executions/route")',"/admin/workflows-executions/:id":'typeof import("@medusajs/medusa/api/admin/workflows-executions/[id]/route")',"/admin/workflows-executions/:workflow_id/:transaction_id":'typeof import("@medusajs/medusa/api/admin/workflows-executions/[workflow_id]/[transaction_id]/route")',"/admin/workflows-executions/:workflow_id/:transaction_id/:step_id/subscribe":'typeof import("@medusajs/medusa/api/admin/workflows-executions/[workflow_id]/[transaction_id]/[step_id]/subscribe/route")',"/admin/workflows-executions/:workflow_id/run":'typeof import("@medusajs/medusa/api/admin/workflows-executions/[workflow_id]/run/route")',"/admin/workflows-executions/:workflow_id/steps/failure":'typeof import("@medusajs/medusa/api/admin/workflows-executions/[workflow_id]/steps/failure/route")',"/admin/workflows-executions/:workflow_id/steps/success":'typeof import("@medusajs/medusa/api/admin/workflows-executions/[workflow_id]/steps/success/route")',"/admin/workflows-executions/:workflow_id/subscribe":'typeof import("@medusajs/medusa/api/admin/workflows-executions/[workflow_id]/subscribe/route")',"/auth/:actor_type/:auth_provider":'typeof import("@medusajs/medusa/api/auth/[actor_type]/[auth_provider]/route")',"/auth/:actor_type/:auth_provider/callback":'typeof import("@medusajs/medusa/api/auth/[actor_type]/[auth_provider]/callback/route")',"/auth/:actor_type/:auth_provider/register":'typeof import("@medusajs/medusa/api/auth/[actor_type]/[auth_provider]/register/route")',"/auth/:actor_type/:auth_provider/reset-password":'typeof import("@medusajs/medusa/api/auth/[actor_type]/[auth_provider]/reset-password/route")',"/auth/:actor_type/:auth_provider/update":'typeof import("@medusajs/medusa/api/auth/[actor_type]/[auth_provider]/update/route")',"/auth/session":'typeof import("@medusajs/medusa/api/auth/session/route")',"/auth/token/refresh":'typeof import("@medusajs/medusa/api/auth/token/refresh/route")',"/store/carts":'typeof import("@medusajs/medusa/api/store/carts/route")',"/store/carts/:id":'typeof import("@medusajs/medusa/api/store/carts/[id]/route")',"/store/carts/:id/complete":'typeof import("@medusajs/medusa/api/store/carts/[id]/complete/route")',"/store/carts/:id/customer":'typeof import("@medusajs/medusa/api/store/carts/[id]/customer/route")',"/store/carts/:id/line-items":'typeof import("@medusajs/medusa/api/store/carts/[id]/line-items/route")',"/store/carts/:id/line-items/:line_id":'typeof import("@medusajs/medusa/api/store/carts/[id]/line-items/[line_id]/route")',"/store/carts/:id/promotions":'typeof import("@medusajs/medusa/api/store/carts/[id]/promotions/route")',"/store/carts/:id/shipping-methods":'typeof import("@medusajs/medusa/api/store/carts/[id]/shipping-methods/route")',"/store/carts/:id/taxes":'typeof import("@medusajs/medusa/api/store/carts/[id]/taxes/route")',"/store/collections":'typeof import("@medusajs/medusa/api/store/collections/route")',"/store/collections/:id":'typeof import("@medusajs/medusa/api/store/collections/[id]/route")',"/store/currencies":'typeof import("@medusajs/medusa/api/store/currencies/route")',"/store/currencies/:code":'typeof import("@medusajs/medusa/api/store/currencies/[code]/route")',"/store/customers":'typeof import("@medusajs/medusa/api/store/customers/route")',"/store/customers/me":'typeof import("@medusajs/medusa/api/store/customers/me/route")',"/store/customers/me/addresses":'typeof import("@medusajs/medusa/api/store/customers/me/addresses/route")',"/store/customers/me/addresses/:address_id":'typeof import("@medusajs/medusa/api/store/customers/me/addresses/[address_id]/route")',"/store/locales":'typeof import("@medusajs/medusa/api/store/locales/route")',"/store/orders":'typeof import("@medusajs/medusa/api/store/orders/route")',"/store/orders/:id":'typeof import("@medusajs/medusa/api/store/orders/[id]/route")',"/store/orders/:id/transfer/accept":'typeof import("@medusajs/medusa/api/store/orders/[id]/transfer/accept/route")',"/store/orders/:id/transfer/cancel":'typeof import("@medusajs/medusa/api/store/orders/[id]/transfer/cancel/route")',"/store/orders/:id/transfer/decline":'typeof import("@medusajs/medusa/api/store/orders/[id]/transfer/decline/route")',"/store/orders/:id/transfer/request":'typeof import("@medusajs/medusa/api/store/orders/[id]/transfer/request/route")',"/store/payment-collections":'typeof import("@medusajs/medusa/api/store/payment-collections/route")',"/store/payment-collections/:id/payment-sessions":'typeof import("@medusajs/medusa/api/store/payment-collections/[id]/payment-sessions/route")',"/store/payment-providers":'typeof import("@medusajs/medusa/api/store/payment-providers/route")',"/store/product-categories":'typeof import("@medusajs/medusa/api/store/product-categories/route")',"/store/product-categories/:id":'typeof import("@medusajs/medusa/api/store/product-categories/[id]/route")',"/store/product-tags":'typeof import("@medusajs/medusa/api/store/product-tags/route")',"/store/product-tags/:id":'typeof import("@medusajs/medusa/api/store/product-tags/[id]/route")',"/store/product-types":'typeof import("@medusajs/medusa/api/store/product-types/route")',"/store/product-types/:id":'typeof import("@medusajs/medusa/api/store/product-types/[id]/route")',"/store/product-variants":'typeof import("@medusajs/medusa/api/store/product-variants/route")',"/store/product-variants/:id":'typeof import("@medusajs/medusa/api/store/product-variants/[id]/route")',"/store/products":'typeof import("@medusajs/medusa/api/store/products/route")',"/store/products/:id":'typeof import("@medusajs/medusa/api/store/products/[id]/route")',"/store/regions":'typeof import("@medusajs/medusa/api/store/regions/route")',"/store/regions/:id":'typeof import("@medusajs/medusa/api/store/regions/[id]/route")',"/store/return-reasons":'typeof import("@medusajs/medusa/api/store/return-reasons/route")',"/store/return-reasons/:id":'typeof import("@medusajs/medusa/api/store/return-reasons/[id]/route")',"/store/returns":'typeof import("@medusajs/medusa/api/store/returns/route")',"/store/shipping-options":'typeof import("@medusajs/medusa/api/store/shipping-options/route")',"/store/shipping-options/:id/calculate":'typeof import("@medusajs/medusa/api/store/shipping-options/[id]/calculate/route")'},Pr={"/admin/commission-rates":'typeof import("@mercurjs/core/api/admin/commission-rates/route")',"/admin/commission-rates/:id":'typeof import("@mercurjs/core/api/admin/commission-rates/[id]/route")',"/admin/commission-rates/:id/rules":'typeof import("@mercurjs/core/api/admin/commission-rates/[id]/rules/route")',"/admin/members":'typeof import("@mercurjs/core/api/admin/members/route")',"/admin/offers":'typeof import("@mercurjs/core/api/admin/offers/route")',"/admin/offers/:id":'typeof import("@mercurjs/core/api/admin/offers/[id]/route")',"/admin/offers/batch":'typeof import("@mercurjs/core/api/admin/offers/batch/route")',"/admin/order-groups":'typeof import("@mercurjs/core/api/admin/order-groups/route")',"/admin/order-groups/:id":'typeof import("@mercurjs/core/api/admin/order-groups/[id]/route")',"/admin/orders":'typeof import("@mercurjs/core/api/admin/orders/route")',"/admin/orders/:id/order-group":'typeof import("@mercurjs/core/api/admin/orders/[id]/order-group/route")',"/admin/payouts":'typeof import("@mercurjs/core/api/admin/payouts/route")',"/admin/payouts/:id":'typeof import("@mercurjs/core/api/admin/payouts/[id]/route")',"/admin/product-attributes":'typeof import("@mercurjs/core/api/admin/product-attributes/route")',"/admin/product-attributes/:id":'typeof import("@mercurjs/core/api/admin/product-attributes/[id]/route")',"/admin/product-attributes/:id/values":'typeof import("@mercurjs/core/api/admin/product-attributes/[id]/values/route")',"/admin/product-attributes/:id/values/:value_id":'typeof import("@mercurjs/core/api/admin/product-attributes/[id]/values/[value_id]/route")',"/admin/product-brands":'typeof import("@mercurjs/core/api/admin/product-brands/route")',"/admin/product-brands/:id":'typeof import("@mercurjs/core/api/admin/product-brands/[id]/route")',"/admin/product-brands/:id/sellers":'typeof import("@mercurjs/core/api/admin/product-brands/[id]/sellers/route")',"/admin/product-categories":'typeof import("@mercurjs/core/api/admin/product-categories/route")',"/admin/product-categories/:id":'typeof import("@mercurjs/core/api/admin/product-categories/[id]/route")',"/admin/product-categories/:id/products":'typeof import("@mercurjs/core/api/admin/product-categories/[id]/products/route")',"/admin/product-categories/:id/sellers":'typeof import("@mercurjs/core/api/admin/product-categories/[id]/sellers/route")',"/admin/product-changes/:id/cancel":'typeof import("@mercurjs/core/api/admin/product-changes/[id]/cancel/route")',"/admin/product-changes/:id/confirm":'typeof import("@mercurjs/core/api/admin/product-changes/[id]/confirm/route")',"/admin/products":'typeof import("@mercurjs/core/api/admin/products/route")',"/admin/products/:id":'typeof import("@mercurjs/core/api/admin/products/[id]/route")',"/admin/products/:id/attributes":'typeof import("@mercurjs/core/api/admin/products/[id]/attributes/route")',"/admin/products/:id/attributes/:attribute_id":'typeof import("@mercurjs/core/api/admin/products/[id]/attributes/[attribute_id]/route")',"/admin/products/:id/attributes/batch":'typeof import("@mercurjs/core/api/admin/products/[id]/attributes/batch/route")',"/admin/products/:id/confirm":'typeof import("@mercurjs/core/api/admin/products/[id]/confirm/route")',"/admin/products/:id/preview":'typeof import("@mercurjs/core/api/admin/products/[id]/preview/route")',"/admin/products/:id/reject":'typeof import("@mercurjs/core/api/admin/products/[id]/reject/route")',"/admin/products/:id/request-changes":'typeof import("@mercurjs/core/api/admin/products/[id]/request-changes/route")',"/admin/products/:id/variants":'typeof import("@mercurjs/core/api/admin/products/[id]/variants/route")',"/admin/products/:id/variants/:variant_id":'typeof import("@mercurjs/core/api/admin/products/[id]/variants/[variant_id]/route")',"/admin/products/batch":'typeof import("@mercurjs/core/api/admin/products/batch/route")',"/admin/sellers":'typeof import("@mercurjs/core/api/admin/sellers/route")',"/admin/sellers/:id":'typeof import("@mercurjs/core/api/admin/sellers/[id]/route")',"/admin/sellers/:id/address":'typeof import("@mercurjs/core/api/admin/sellers/[id]/address/route")',"/admin/sellers/:id/approve":'typeof import("@mercurjs/core/api/admin/sellers/[id]/approve/route")',"/admin/sellers/:id/members":'typeof import("@mercurjs/core/api/admin/sellers/[id]/members/route")',"/admin/sellers/:id/members/:member_id":'typeof import("@mercurjs/core/api/admin/sellers/[id]/members/[member_id]/route")',"/admin/sellers/:id/members/invite":'typeof import("@mercurjs/core/api/admin/sellers/[id]/members/invite/route")',"/admin/sellers/:id/members/invites":'typeof import("@mercurjs/core/api/admin/sellers/[id]/members/invites/route")',"/admin/sellers/:id/members/invites/:invite_id":'typeof import("@mercurjs/core/api/admin/sellers/[id]/members/invites/[invite_id]/route")',"/admin/sellers/:id/members/invites/:invite_id/resend":'typeof import("@mercurjs/core/api/admin/sellers/[id]/members/invites/[invite_id]/resend/route")',"/admin/sellers/:id/payment-details":'typeof import("@mercurjs/core/api/admin/sellers/[id]/payment-details/route")',"/admin/sellers/:id/products":'typeof import("@mercurjs/core/api/admin/sellers/[id]/products/route")',"/admin/sellers/:id/professional-details":'typeof import("@mercurjs/core/api/admin/sellers/[id]/professional-details/route")',"/admin/sellers/:id/suspend":'typeof import("@mercurjs/core/api/admin/sellers/[id]/suspend/route")',"/admin/sellers/:id/terminate":'typeof import("@mercurjs/core/api/admin/sellers/[id]/terminate/route")',"/admin/sellers/:id/unsuspend":'typeof import("@mercurjs/core/api/admin/sellers/[id]/unsuspend/route")',"/admin/sellers/:id/unterminate":'typeof import("@mercurjs/core/api/admin/sellers/[id]/unterminate/route")',"/hooks/payout":'typeof import("@mercurjs/core/api/hooks/payout/route")',"/store/carts/:id/complete":'typeof import("@mercurjs/core/api/store/carts/[id]/complete/route")',"/store/carts/:id/line-items":'typeof import("@mercurjs/core/api/store/carts/[id]/line-items/route")',"/store/carts/:id/promotions":'typeof import("@mercurjs/core/api/store/carts/[id]/promotions/route")',"/store/carts/:id/shipping-methods":'typeof import("@mercurjs/core/api/store/carts/[id]/shipping-methods/route")',"/store/order-groups":'typeof import("@mercurjs/core/api/store/order-groups/route")',"/store/order-groups/:id":'typeof import("@mercurjs/core/api/store/order-groups/[id]/route")',"/store/product-attributes":'typeof import("@mercurjs/core/api/store/product-attributes/route")',"/store/product-attributes/:id":'typeof import("@mercurjs/core/api/store/product-attributes/[id]/route")',"/store/product-brands":'typeof import("@mercurjs/core/api/store/product-brands/route")',"/store/product-brands/:id":'typeof import("@mercurjs/core/api/store/product-brands/[id]/route")',"/store/product-categories":'typeof import("@mercurjs/core/api/store/product-categories/route")',"/store/product-categories/:id":'typeof import("@mercurjs/core/api/store/product-categories/[id]/route")',"/store/products":'typeof import("@mercurjs/core/api/store/products/route")',"/store/products/:id":'typeof import("@mercurjs/core/api/store/products/[id]/route")',"/store/sellers":'typeof import("@mercurjs/core/api/store/sellers/route")',"/store/sellers/:id":'typeof import("@mercurjs/core/api/store/sellers/[id]/route")',"/store/shipping-options":'typeof import("@mercurjs/core/api/store/shipping-options/route")',"/vendor/campaigns":'typeof import("@mercurjs/core/api/vendor/campaigns/route")',"/vendor/campaigns/:id":'typeof import("@mercurjs/core/api/vendor/campaigns/[id]/route")',"/vendor/campaigns/:id/promotions":'typeof import("@mercurjs/core/api/vendor/campaigns/[id]/promotions/route")',"/vendor/collections":'typeof import("@mercurjs/core/api/vendor/collections/route")',"/vendor/collections/:id":'typeof import("@mercurjs/core/api/vendor/collections/[id]/route")',"/vendor/collections/:id/products":'typeof import("@mercurjs/core/api/vendor/collections/[id]/products/route")',"/vendor/currencies":'typeof import("@mercurjs/core/api/vendor/currencies/route")',"/vendor/currencies/:code":'typeof import("@mercurjs/core/api/vendor/currencies/[code]/route")',"/vendor/customers":'typeof import("@mercurjs/core/api/vendor/customers/route")',"/vendor/customers/:id":'typeof import("@mercurjs/core/api/vendor/customers/[id]/route")',"/vendor/feature-flags":'typeof import("@mercurjs/core/api/vendor/feature-flags/route")',"/vendor/fulfillment-providers":'typeof import("@mercurjs/core/api/vendor/fulfillment-providers/route")',"/vendor/fulfillment-sets/:id":'typeof import("@mercurjs/core/api/vendor/fulfillment-sets/[id]/route")',"/vendor/fulfillment-sets/:id/service-zones":'typeof import("@mercurjs/core/api/vendor/fulfillment-sets/[id]/service-zones/route")',"/vendor/fulfillment-sets/:id/service-zones/:zone_id":'typeof import("@mercurjs/core/api/vendor/fulfillment-sets/[id]/service-zones/[zone_id]/route")',"/vendor/inventory-items":'typeof import("@mercurjs/core/api/vendor/inventory-items/route")',"/vendor/inventory-items/:id":'typeof import("@mercurjs/core/api/vendor/inventory-items/[id]/route")',"/vendor/inventory-items/:id/location-levels":'typeof import("@mercurjs/core/api/vendor/inventory-items/[id]/location-levels/route")',"/vendor/inventory-items/:id/location-levels/:location_id":'typeof import("@mercurjs/core/api/vendor/inventory-items/[id]/location-levels/[location_id]/route")',"/vendor/inventory-items/:id/location-levels/batch":'typeof import("@mercurjs/core/api/vendor/inventory-items/[id]/location-levels/batch/route")',"/vendor/inventory-items/location-levels/batch":'typeof import("@mercurjs/core/api/vendor/inventory-items/location-levels/batch/route")',"/vendor/members/invites/accept":'typeof import("@mercurjs/core/api/vendor/members/invites/accept/route")',"/vendor/members/me":'typeof import("@mercurjs/core/api/vendor/members/me/route")',"/vendor/offers":'typeof import("@mercurjs/core/api/vendor/offers/route")',"/vendor/offers/:id":'typeof import("@mercurjs/core/api/vendor/offers/[id]/route")',"/vendor/offers/:id/inventory-items/batch":'typeof import("@mercurjs/core/api/vendor/offers/[id]/inventory-items/batch/route")',"/vendor/offers/batch":'typeof import("@mercurjs/core/api/vendor/offers/batch/route")',"/vendor/orders":'typeof import("@mercurjs/core/api/vendor/orders/route")',"/vendor/orders/:id":'typeof import("@mercurjs/core/api/vendor/orders/[id]/route")',"/vendor/orders/:id/cancel":'typeof import("@mercurjs/core/api/vendor/orders/[id]/cancel/route")',"/vendor/orders/:id/changes":'typeof import("@mercurjs/core/api/vendor/orders/[id]/changes/route")',"/vendor/orders/:id/complete":'typeof import("@mercurjs/core/api/vendor/orders/[id]/complete/route")',"/vendor/orders/:id/fulfillments":'typeof import("@mercurjs/core/api/vendor/orders/[id]/fulfillments/route")',"/vendor/orders/:id/fulfillments/:fulfillment_id/cancel":'typeof import("@mercurjs/core/api/vendor/orders/[id]/fulfillments/[fulfillment_id]/cancel/route")',"/vendor/orders/:id/fulfillments/:fulfillment_id/mark-as-delivered":'typeof import("@mercurjs/core/api/vendor/orders/[id]/fulfillments/[fulfillment_id]/mark-as-delivered/route")',"/vendor/orders/:id/fulfillments/:fulfillment_id/shipments":'typeof import("@mercurjs/core/api/vendor/orders/[id]/fulfillments/[fulfillment_id]/shipments/route")',"/vendor/orders/:id/preview":'typeof import("@mercurjs/core/api/vendor/orders/[id]/preview/route")',"/vendor/payments":'typeof import("@mercurjs/core/api/vendor/payments/route")',"/vendor/payments/:id":'typeof import("@mercurjs/core/api/vendor/payments/[id]/route")',"/vendor/payments/:id/capture":'typeof import("@mercurjs/core/api/vendor/payments/[id]/capture/route")',"/vendor/payments/:id/refund":'typeof import("@mercurjs/core/api/vendor/payments/[id]/refund/route")',"/vendor/payments/payment-providers":'typeof import("@mercurjs/core/api/vendor/payments/payment-providers/route")',"/vendor/payout-accounts":'typeof import("@mercurjs/core/api/vendor/payout-accounts/route")',"/vendor/payout-accounts/:id":'typeof import("@mercurjs/core/api/vendor/payout-accounts/[id]/route")',"/vendor/payout-accounts/:id/onboarding":'typeof import("@mercurjs/core/api/vendor/payout-accounts/[id]/onboarding/route")',"/vendor/payouts":'typeof import("@mercurjs/core/api/vendor/payouts/route")',"/vendor/payouts/:id":'typeof import("@mercurjs/core/api/vendor/payouts/[id]/route")',"/vendor/price-lists":'typeof import("@mercurjs/core/api/vendor/price-lists/route")',"/vendor/price-lists/:id":'typeof import("@mercurjs/core/api/vendor/price-lists/[id]/route")',"/vendor/price-lists/:id/prices":'typeof import("@mercurjs/core/api/vendor/price-lists/[id]/prices/route")',"/vendor/price-lists/:id/prices/batch":'typeof import("@mercurjs/core/api/vendor/price-lists/[id]/prices/batch/route")',"/vendor/price-lists/:id/products":'typeof import("@mercurjs/core/api/vendor/price-lists/[id]/products/route")',"/vendor/price-preferences":'typeof import("@mercurjs/core/api/vendor/price-preferences/route")',"/vendor/price-preferences/:id":'typeof import("@mercurjs/core/api/vendor/price-preferences/[id]/route")',"/vendor/product-attributes":'typeof import("@mercurjs/core/api/vendor/product-attributes/route")',"/vendor/product-attributes/:id":'typeof import("@mercurjs/core/api/vendor/product-attributes/[id]/route")',"/vendor/product-brands":'typeof import("@mercurjs/core/api/vendor/product-brands/route")',"/vendor/product-brands/:id":'typeof import("@mercurjs/core/api/vendor/product-brands/[id]/route")',"/vendor/product-categories":'typeof import("@mercurjs/core/api/vendor/product-categories/route")',"/vendor/product-categories/:id":'typeof import("@mercurjs/core/api/vendor/product-categories/[id]/route")',"/vendor/product-tags":'typeof import("@mercurjs/core/api/vendor/product-tags/route")',"/vendor/product-tags/:id":'typeof import("@mercurjs/core/api/vendor/product-tags/[id]/route")',"/vendor/product-types":'typeof import("@mercurjs/core/api/vendor/product-types/route")',"/vendor/product-types/:id":'typeof import("@mercurjs/core/api/vendor/product-types/[id]/route")',"/vendor/product-variants":'typeof import("@mercurjs/core/api/vendor/product-variants/route")',"/vendor/products":'typeof import("@mercurjs/core/api/vendor/products/route")',"/vendor/products/:id":'typeof import("@mercurjs/core/api/vendor/products/[id]/route")',"/vendor/products/:id/attributes":'typeof import("@mercurjs/core/api/vendor/products/[id]/attributes/route")',"/vendor/products/:id/attributes/:attribute_id":'typeof import("@mercurjs/core/api/vendor/products/[id]/attributes/[attribute_id]/route")',"/vendor/products/:id/cancel":'typeof import("@mercurjs/core/api/vendor/products/[id]/cancel/route")',"/vendor/products/:id/preview":'typeof import("@mercurjs/core/api/vendor/products/[id]/preview/route")',"/vendor/products/:id/variants":'typeof import("@mercurjs/core/api/vendor/products/[id]/variants/route")',"/vendor/products/:id/variants/:variant_id":'typeof import("@mercurjs/core/api/vendor/products/[id]/variants/[variant_id]/route")',"/vendor/promotions":'typeof import("@mercurjs/core/api/vendor/promotions/route")',"/vendor/promotions/:id":'typeof import("@mercurjs/core/api/vendor/promotions/[id]/route")',"/vendor/promotions/:id/:rule_type":'typeof import("@mercurjs/core/api/vendor/promotions/[id]/[rule_type]/route")',"/vendor/promotions/:id/buy-rules/batch":'typeof import("@mercurjs/core/api/vendor/promotions/[id]/buy-rules/batch/route")',"/vendor/promotions/:id/rules/batch":'typeof import("@mercurjs/core/api/vendor/promotions/[id]/rules/batch/route")',"/vendor/promotions/:id/target-rules/batch":'typeof import("@mercurjs/core/api/vendor/promotions/[id]/target-rules/batch/route")',"/vendor/promotions/rule-attribute-options/:rule_type":'typeof import("@mercurjs/core/api/vendor/promotions/rule-attribute-options/[rule_type]/route")',"/vendor/promotions/rule-value-options/:rule_type/:rule_attribute_id":'typeof import("@mercurjs/core/api/vendor/promotions/rule-value-options/[rule_type]/[rule_attribute_id]/route")',"/vendor/refund-reasons":'typeof import("@mercurjs/core/api/vendor/refund-reasons/route")',"/vendor/refund-reasons/:id":'typeof import("@mercurjs/core/api/vendor/refund-reasons/[id]/route")',"/vendor/regions":'typeof import("@mercurjs/core/api/vendor/regions/route")',"/vendor/regions/:id":'typeof import("@mercurjs/core/api/vendor/regions/[id]/route")',"/vendor/return-reasons":'typeof import("@mercurjs/core/api/vendor/return-reasons/route")',"/vendor/return-reasons/:id":'typeof import("@mercurjs/core/api/vendor/return-reasons/[id]/route")',"/vendor/returns":'typeof import("@mercurjs/core/api/vendor/returns/route")',"/vendor/returns/:id":'typeof import("@mercurjs/core/api/vendor/returns/[id]/route")',"/vendor/returns/:id/cancel":'typeof import("@mercurjs/core/api/vendor/returns/[id]/cancel/route")',"/vendor/returns/:id/dismiss-items":'typeof import("@mercurjs/core/api/vendor/returns/[id]/dismiss-items/route")',"/vendor/returns/:id/dismiss-items/:action_id":'typeof import("@mercurjs/core/api/vendor/returns/[id]/dismiss-items/[action_id]/route")',"/vendor/returns/:id/receive":'typeof import("@mercurjs/core/api/vendor/returns/[id]/receive/route")',"/vendor/returns/:id/receive-items":'typeof import("@mercurjs/core/api/vendor/returns/[id]/receive-items/route")',"/vendor/returns/:id/receive-items/:action_id":'typeof import("@mercurjs/core/api/vendor/returns/[id]/receive-items/[action_id]/route")',"/vendor/returns/:id/receive/confirm":'typeof import("@mercurjs/core/api/vendor/returns/[id]/receive/confirm/route")',"/vendor/returns/:id/request":'typeof import("@mercurjs/core/api/vendor/returns/[id]/request/route")',"/vendor/returns/:id/request-items":'typeof import("@mercurjs/core/api/vendor/returns/[id]/request-items/route")',"/vendor/returns/:id/request-items/:action_id":'typeof import("@mercurjs/core/api/vendor/returns/[id]/request-items/[action_id]/route")',"/vendor/returns/:id/shipping-method":'typeof import("@mercurjs/core/api/vendor/returns/[id]/shipping-method/route")',"/vendor/returns/:id/shipping-method/:action_id":'typeof import("@mercurjs/core/api/vendor/returns/[id]/shipping-method/[action_id]/route")',"/vendor/sales-channels":'typeof import("@mercurjs/core/api/vendor/sales-channels/route")',"/vendor/sales-channels/:id":'typeof import("@mercurjs/core/api/vendor/sales-channels/[id]/route")',"/vendor/sales-channels/:id/products":'typeof import("@mercurjs/core/api/vendor/sales-channels/[id]/products/route")',"/vendor/sellers":'typeof import("@mercurjs/core/api/vendor/sellers/route")',"/vendor/sellers/:id":'typeof import("@mercurjs/core/api/vendor/sellers/[id]/route")',"/vendor/sellers/:id/address":'typeof import("@mercurjs/core/api/vendor/sellers/[id]/address/route")',"/vendor/sellers/:id/members":'typeof import("@mercurjs/core/api/vendor/sellers/[id]/members/route")',"/vendor/sellers/:id/members/:member_id":'typeof import("@mercurjs/core/api/vendor/sellers/[id]/members/[member_id]/route")',"/vendor/sellers/:id/members/invites":'typeof import("@mercurjs/core/api/vendor/sellers/[id]/members/invites/route")',"/vendor/sellers/:id/members/me":'typeof import("@mercurjs/core/api/vendor/sellers/[id]/members/me/route")',"/vendor/sellers/:id/payment-details":'typeof import("@mercurjs/core/api/vendor/sellers/[id]/payment-details/route")',"/vendor/sellers/:id/professional-details":'typeof import("@mercurjs/core/api/vendor/sellers/[id]/professional-details/route")',"/vendor/sellers/me":'typeof import("@mercurjs/core/api/vendor/sellers/me/route")',"/vendor/sellers/select":'typeof import("@mercurjs/core/api/vendor/sellers/select/route")',"/vendor/shipping-option-types":'typeof import("@mercurjs/core/api/vendor/shipping-option-types/route")',"/vendor/shipping-option-types/:id":'typeof import("@mercurjs/core/api/vendor/shipping-option-types/[id]/route")',"/vendor/shipping-options":'typeof import("@mercurjs/core/api/vendor/shipping-options/route")',"/vendor/shipping-options/:id":'typeof import("@mercurjs/core/api/vendor/shipping-options/[id]/route")',"/vendor/shipping-options/:id/rules/batch":'typeof import("@mercurjs/core/api/vendor/shipping-options/[id]/rules/batch/route")',"/vendor/shipping-profiles":'typeof import("@mercurjs/core/api/vendor/shipping-profiles/route")',"/vendor/shipping-profiles/:id":'typeof import("@mercurjs/core/api/vendor/shipping-profiles/[id]/route")',"/vendor/stock-locations":'typeof import("@mercurjs/core/api/vendor/stock-locations/route")',"/vendor/stock-locations/:id":'typeof import("@mercurjs/core/api/vendor/stock-locations/[id]/route")',"/vendor/stock-locations/:id/fulfillment-providers":'typeof import("@mercurjs/core/api/vendor/stock-locations/[id]/fulfillment-providers/route")',"/vendor/stock-locations/:id/fulfillment-sets":'typeof import("@mercurjs/core/api/vendor/stock-locations/[id]/fulfillment-sets/route")',"/vendor/stock-locations/:id/sales-channels":'typeof import("@mercurjs/core/api/vendor/stock-locations/[id]/sales-channels/route")',"/vendor/stores":'typeof import("@mercurjs/core/api/vendor/stores/route")',"/vendor/uploads":'typeof import("@mercurjs/core/api/vendor/uploads/route")'};async function Rt(e,t={}){let{pathnameFilter:r,ignoreFilter:o,ignorePartFilter:i,sortPathnames:s=true}=t,n=[],m=[e];for(;m.length>0;){let p=await Promise.all(m.map(async d=>{let u={directories:[],pathnames:[]};try{let c=await U__default.readdir(d,{withFileTypes:!0});for(let f of c){if(i&&i(f.name))continue;let y=R__default.join(d,f.name);o&&o(y)||(f.isDirectory()?u.directories.push(y):(!r||r(y))&&u.pathnames.push(y));}}catch(c){if(c.code!=="ENOENT"||d===e)throw c;return null}return u}));m=[];for(let d of p)d&&(m.push(...d.directories),n.push(...d.pathnames));}return s&&n.sort(),n}async function Qe(e){return await U__default.stat(e).catch(()=>null)!==null}async function Xe(e){await Qe(e)||await U__default.mkdir(e,{recursive:true});}function ge(e){return e.replace(/\\/g,"/")}function Ie(e){return e.split("/").reduce((r,o)=>{if(!o||oe.test(o))return r;if(o.startsWith("[")&&o.endsWith("]")){let i=o.slice(1,-1);return `${r}/:${i}`}return `${r}/${o}`},"")||"/"}async function xt(e){return await Qe(e)?(await Rt(e,{pathnameFilter:o=>oe.test(o),ignorePartFilter:o=>o.startsWith("_")||o==="node_modules"})).map(o=>{let i=R__default.relative(e,o);return {filePath:ge(i),route:Ie(ge(i))}}):[]}function _t(e){return e.replace(/[-_]+(.)?/g,(t,r)=>r?r.toUpperCase():"").replace(/^[A-Z]/,t=>t.toLowerCase())}function os(e){return `../../src/api/${e.replace(/\.ts$/,"")}`}function is(e){return e.startsWith(":")?`$${_t(e.slice(1))}`:_t(e)}function Tr(){return {children:new Map}}function ss(e){let t=Tr();for(let[r,o]of e){let i=r.split("/").filter(Boolean),s=t;for(let n of i){let m=is(n);s.children.has(m)||s.children.set(m,Tr()),s=s.children.get(m);}s.importType=o;}return t}function Dr(e,t=" "){let r=[];if(e.importType&&r.push(e.importType),e.children.size>0){let o=[];for(let[i,s]of e.children){let n=Dr(s,t+" ");o.push(`${t} ${i}: ${n}`);}r.push(`{
27
+ `);}async function rr(e,t,r){if(r={overwrite:false,silent:false,yes:false,...r},!e.length)return;let o=x("Checking registry.",{silent:r.silent})?.start(),s=await st(e,se(t));if(!s)return o?.fail(),R(new Error("Failed to fetch items from registry."));o?.succeed();let{filesCreated:n,filesUpdated:i}=await tr(s.files,t,{overwrite:r.overwrite,silent:r.silent,path:r.path,yes:r.yes});(n.length||i.length)&&await qt(s.dependencies,s.devDependencies,t,{silent:r.silent}),s.docs&&l.info(s.docs);}z.object({cwd:z.string(),yes:z.boolean(),defaults:z.boolean(),silent:z.boolean()});async function or(e){let t={},r=v__default.resolve(e.cwd);existsSync(r)||(t.MISSING_DIR=true);let o=await b(r);return {errors:t,projectInfo:o}}var nr=join(homedir(),".mercur"),it=join(nr,"config.json"),at={telemetry_enabled:true,telemetry_email:null,notice_shown:false},ct=class{get(t){return this.read()[t]}set(t,r){let o=this.read();o[t]=r,this.write(o);}read(){try{if(!existsSync(it))return {...at};let t=readFileSync(it,"utf-8"),r=JSON.parse(t);return {...at,...r}}catch{return {...at}}}write(t){try{mkdirSync(nr,{recursive:!0}),writeFileSync(it,JSON.stringify(t,null,2)+`
28
+ `,{mode:384});}catch{}}},G=new ct;var ce=e=>Function("mm","return import(mm)")(e);function ls(){let e=(...t)=>t.some(r=>!!process.env[r]);return e("MEDUSA_CLOUD_ENVIRONMENT_HANDLE","MEDUSA_CLOUD_SANDBOX_HANDLE","MEDUSA_CLOUD_API_KEY")?"medusa-cloud":e("RENDER","RENDER_URL","RENDER_INTERNAL_HOSTNAME","RENDER_SERVICE_ID")?"render":e("FLY_APP_NAME","FLY_REGION","FLY_ALLOC_ID")?"fly-io":e("RAILWAY_STATIC_URL","RAILWAY_ENVIRONMENT_NAME")?"railway":e("DYNO","HEROKU_APP_NAME")?"heroku":e("DO_DEPLOYMENT_ID","DO_APP_NAME","DIGITALOCEAN")?"digitalocean":e("KOYEB","KOYEB_DEPLOYMENT_ID","KOYEB_APP_NAME")?"koyeb":null}async function ar(){try{let e=await ce("os"),t=e.cpus();return {deploymentVendor:ls(),systemPlatform:e.platform(),systemRelease:e.release(),systemArchitecture:e.arch(),cpuCount:t.length,cpuModel:t.length?t[0].model:null,cpuSpeed:t.length?t[0].speed:null,memory:e.totalmem(),isWSL:await fs(),isDocker:await cr(),isTTY:typeof process<"u"&&process.stdout?process.stdout.isTTY:null}}catch{return {systemPlatform:null,systemRelease:null,systemArchitecture:null,cpuCount:null,cpuModel:null,cpuSpeed:null,memory:null,isWSL:null,isDocker:null,isTTY:null}}}async function fs(){try{if(typeof process>"u"||process?.platform!=="linux")return !1;let e=await ce("fs");return (await ce("os")).release().toLowerCase().includes("microsoft")?!await ir():e.readFileSync("/proc/version","utf8").toLowerCase().includes("microsoft")?!await ir():!1}catch{return false}}var ms=async()=>{try{return (await ce("fs")).statSync("/run/.containerenv"),!0}catch{return false}};async function cr(){return await ps()||await us()}async function ps(){try{return (await ce("fs")).statSync("/.dockerenv"),!0}catch{return false}}async function us(){try{return (await ce("fs")).readFileSync("/proc/self/cgroup","utf8").includes("docker")}catch{return false}}async function ir(){return await ms()||await cr()}var lt=e=>createHash("sha256").update(e).digest("base64");var hs=process.env.MERCUR_TELEMETRY_PROXY_URL||"https://telemetry.mercurjs.com/api/v1/events";var lr=e=>{G.set("telemetry_enabled",e);},Ge="https://docs.mercurjs.com/telemetry",le=()=>{G.get("notice_shown")||(G.set("notice_shown",true),process.env.MERCUR_DISABLE_TELEMETRY!=="true"&&console.error(["","Mercur collects anonymous usage data to improve the CLI experience.",`You can disable this at any time by running: ${u.info("mercurjs telemetry --disable")}`,`Or by setting ${u.info("MERCUR_DISABLE_TELEMETRY=true")}`,`Learn more: ${u.info(Ge)}`,""].join(`
29
+ `)));},ys=()=>G.get("telemetry_enabled")&&process.env.MERCUR_DISABLE_TELEMETRY!=="true",V=async(e,t)=>{try{if(!ys())return;let r=await b(t.cwd),{projectId:o}=Es(r.packageJson),s={nodeEnv:ws(),nodeVersion:process.version,mercurVersion:r.mercurVersion,medusaVersion:r.medusaVersion,isSrcDir:r.isSrcDir,aliasPrefix:r.aliasPrefix,config:await E(t.cwd),projectId:o,systemInfo:await ar(),packageManager:await ze(t.cwd),email:xs()};await fetch(hs,{body:JSON.stringify({...s,...e}),headers:{"Content-Type":"application/json"},method:"post"});}catch{}};function ws(){return process.env.NODE_ENV||"development"}var Rs=()=>{try{let e=execSync("git config --local --get remote.origin.url",{stdio:"pipe",timeout:1e3});return String(e).trim()}catch{return null}},Es=e=>{let t=Rs();if(t)return {projectId:lt(t)};let r=process.cwd();return {projectId:lt(r)}},xs=()=>G.get("telemetry_email")||void 0;var bs=z.object({cwd:z.string(),yes:z.boolean(),defaults:z.boolean(),silent:z.boolean()}),mr=new Command().name("init").description("initialize your project and install dependencies").option("-y, --yes","skip confirmation prompt.",true).option("-d, --defaults","use default configuration.",false).option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).option("-s, --silent","mute output.",false).action(async e=>{try{le();let t=bs.parse({cwd:v__default.resolve(e.cwd),...e});await mt(t),l.log(`${u.success("Success!")} Project initialization completed.
30
+ You may now add blocks.`),l.break(),await V({type:"init",payload:{outcome:"success"}},{cwd:t.cwd});}catch(t){l.break(),R(t);}finally{S();}});async function mt(e){await or(e);let t=await E(e.cwd),r=t?await ks(t,e):await Ss(e);if(!e.yes){let{proceed:n}=await ft({type:"confirm",name:"proceed",message:`Write configuration to ${u.info("blocks.json")}. Proceed?`,initial:true});n||process.exit(0);}let o=x("Writing blocks.json.").start(),s=v__default.resolve(e.cwd,"blocks.json");return r.registries=Object.fromEntries(Object.entries(r.registries||{}).filter(([n])=>!Object.keys(P).includes(n))),await promises.writeFile(s,`${JSON.stringify(r,null,2)}
31
+ `,"utf8"),o.succeed(),await Xe(e.cwd,r)}async function Ss(e){if(e.defaults)return M.parse({$schema:_e,aliases:{api:"packages/api/src",vendor:"apps/vendor/src",admin:"apps/admin/src"},registries:P});l.info("");let t=await ft([{type:"text",name:"api",message:`Configure the import alias for ${u.info("api")}:`,initial:"packages/api/src"},{type:"text",name:"vendor",message:`Configure the import alias for ${u.info("vendor")}:`,initial:"apps/vendor/src"},{type:"text",name:"admin",message:`Configure the import alias for ${u.info("admin")}:`,initial:"apps/admin/src"}],{onCancel:()=>{process.exit(0);}});return M.parse({$schema:_e,aliases:{api:t.api??"packages/api/src",vendor:t.vendor??"apps/vendor/src",admin:t.admin??"apps/admin/src"},registries:P})}async function ks(e,t){if(t.defaults)return M.parse({$schema:_e,aliases:{api:"packages/api/src",vendor:"apps/vendor/src",admin:"apps/admin/src"},registries:P});let r=await ft([{type:"text",name:"api",message:`Configure the import alias for ${u.info("api")}:`,initial:e.aliases.api},{type:"text",name:"vendor",message:`Configure the import alias for ${u.info("vendor")}:`,initial:e.aliases.vendor},{type:"text",name:"admin",message:`Configure the import alias for ${u.info("admin")}:`,initial:e.aliases.admin}],{onCancel:()=>{process.exit(0);}});return M.parse({$schema:e.$schema,aliases:{api:r.api??e.aliases.api,vendor:r.vendor??e.aliases.vendor,admin:r.admin??e.aliases.admin}})}var Ts=z.object({blocks:z.array(z.string()).optional(),yes:z.boolean(),overwrite:z.boolean(),cwd:z.string(),silent:z.boolean()}),pr=new Command().name("add").description("add blocks to your project").argument("[blocks...]","names of blocks to add").option("-y, --yes","skip confirmation prompt.",false).option("-o, --overwrite","overwrite existing files.",false).option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).option("-s, --silent","mute output.",false).action(async(e,t)=>{try{le();let r=Ts.parse({blocks:e,cwd:v__default.resolve(t.cwd),...t}),o=await E(r.cwd);o||(o=L({resolvedPaths:{cwd:r.cwd}})),r.blocks?.length||(l.error("Please specify at least one item to add."),process.exit(1));let{errors:s}=await Ft(r);if(s[C]){let{proceed:n}=await ft({type:"confirm",name:"proceed",message:`You need to create a ${u.info("blocks.json")} file to add items. Proceed?`,initial:!0});n||(l.break(),process.exit(1)),o=await mt({cwd:r.cwd,yes:!0,defaults:!1,silent:r.silent});}if(!o)throw new Error(`Failed to read config at ${u.info(r.cwd)}.`);await rr(r.blocks,o,{overwrite:r.overwrite,silent:r.silent,yes:r.yes,path:r.cwd}),await V({type:"add",payload:{outcome:"success",blocks:r.blocks}},{cwd:r.cwd});}catch(r){l.break(),R(r);}finally{S();}});async function ur(e){let t={},r={cwd:e.cwd,registryFile:v__default.resolve(e.cwd,e.registryFile),outputDir:v__default.resolve(e.cwd,e.outputDir)};if(!ut.existsSync(r.registryFile))return t[A]=true,{errors:t,resolvePaths:null,config:null};if(!ut.existsSync(v__default.resolve(e.cwd,"blocks.json")))return t[C]=true,{errors:t,resolvePaths:null,config:null};await ut.mkdir(r.outputDir,{recursive:true});try{let o=await E(e.cwd);return {errors:t,config:o,resolvePaths:r}}catch{l.break(),l.error(`An invalid ${u.info("blocks.json")} file was found at ${u.info(e.cwd)}.
32
+ Before you can build the registry, you must create a valid ${u.info("blocks.json")} file by running the ${u.info("init")} command.`),l.break(),process.exit(1);}}var Fs=z.object({cwd:z.string(),registryFile:z.string(),outputDir:z.string(),verbose:z.boolean().optional().default(false)}),gr=new Command().name("registry:build").description("builds the registry").argument("[registry]","path to registry.json file","./registry.json").option("-o, --output <path>","destination directory for json files","./r").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).option("-v, --verbose","verbose output").action(async(e,t)=>{await Os({cwd:v.resolve(t.cwd),registryFile:e,outputDir:t.output,verbose:t.verbose});});async function Os(e){try{le();let t=Fs.parse(e),[{errors:r,resolvePaths:o,config:s},n]=await Promise.all([ur(t),b(t.cwd)]);(r[C]||!n)&&(l.error(`A ${u.info("blocks.json")} file is required to build the registry. Run ${u.info("mercur init")} to create one.`),l.break(),await V({type:"build",payload:{outcome:"missing_config"}},{cwd:t.cwd}),process.exit(1)),(r[A]||!o)&&(l.error(`We could not find a registry file at ${u.info(v.resolve(t.cwd,t.registryFile))}.`),l.break(),await V({type:"build",payload:{outcome:"missing_registry_file"}},{cwd:t.cwd}),process.exit(1));let i=await $.readFile(o.registryFile,"utf-8"),f=Y.safeParse(JSON.parse(i));f.success||(l.error(`Invalid registry file found at ${u.info(o.registryFile)}.`),l.break(),process.exit(1));let c=x("Building registry..."),a=await Ns(f.data,s,n);for(let m of a.items)m.files=m.files?.filter((p,g,h)=>g===h.findIndex(y=>y.path===p.path)),m.dependencies&&(m.dependencies=m.dependencies.filter((p,g,h)=>g===h.findIndex(y=>y===p)));for(let m of a.items){if(!m.files)continue;c.start(`Building ${m.name}...`),m.$schema=Pt;for(let g of m.files){let h=n.isSrcDir?"src":"",y=v.resolve(o.cwd,h,g.path);try{if(!(await $.stat(y)).isFile())continue;g.content=await $.readFile(y,"utf-8");}catch(w){console.error("Error reading file in registry build:",y,w);continue}}let p=T.safeParse(m);if(!p.success){l.error(`Invalid registry item found for ${u.info(m.name)}.`);continue}await $.writeFile(v.resolve(o.outputDir,`${p.data.name}.json`),JSON.stringify(p.data,null,2));}if(await $.copyFile(o.registryFile,v.resolve(o.outputDir,"registry.json")),c.succeed("Building registry."),t.verbose){x(`The registry has ${u.info(a.items.length.toString())} items:`).succeed();for(let m of a.items){l.log(` - ${m.name}`);for(let p of m.files??[])l.log(` - ${p.path}`);}}await V({type:"build",payload:{outcome:"success"}},{cwd:t.cwd});}catch(t){l.break(),R(t);}}async function Ns(e,t,r){for(let o of e.items)if(o.files?.length)for(let s of o.files){let n=await rt(s.path,t,r);n.files=n.files?.filter(i=>i.path!==s.path),n.files&&o.files.push(...n.files),n.dependencies&&(o.dependencies=o.dependencies?o.dependencies.concat(n.dependencies):n.dependencies);}return e}var Ve=".mercur",Q=/route\.(ts|js)$/;async function dt(e,t={}){let{pathnameFilter:r,ignoreFilter:o,ignorePartFilter:s,sortPathnames:n=true}=t,i=[],f=[e];for(;f.length>0;){let c=await Promise.all(f.map(async a=>{let m={directories:[],pathnames:[]};try{let p=await $__default.readdir(a,{withFileTypes:!0});for(let g of p){if(s&&s(g.name))continue;let h=v__default.join(a,g.name);o&&o(h)||(g.isDirectory()?m.directories.push(h):(!r||r(h))&&m.pathnames.push(h));}}catch(p){if(p.code!=="ENOENT"||a===e)throw p;return null}return m}));f=[];for(let a of c)a&&(f.push(...a.directories),i.push(...a.pathnames));}return n&&i.sort(),i}async function Ye(e){return await $__default.stat(e).catch(()=>null)!==null}async function Je(e){await Ye(e)||await $__default.mkdir(e,{recursive:true});}var Ls="https://raw.githubusercontent.com/mercurjs/mercur/canary/packages/cli/routes-manifest.json",Us=5e3;function zs(e){let t=Ds.createHash("sha256").update(e).digest("hex").slice(0,16);return v__default.join(As.tmpdir(),`mercur-routes-manifest-${t}.json`)}async function He(){let e=process.env.MERCUR_ROUTES_MANIFEST_URL??Ls,t=zs(e);try{let r=new AbortController,o=setTimeout(()=>r.abort(),Us),s=await fetch(e,{signal:r.signal});if(clearTimeout(o),!s.ok)throw new Error(`Request failed with status ${s.status}`);let n=await s.json();return await $__default.writeFile(t,JSON.stringify(n),"utf-8").catch(()=>{}),n}catch{try{return JSON.parse(await $__default.readFile(t,"utf-8"))}catch{throw new Error(`Failed to fetch the routes manifest from ${e} and no cached copy is available. Connect to the network and re-run codegen.`)}}}function me(e){return e.replace(/\\/g,"/")}function be(e){return e.split("/").reduce((r,o)=>{if(!o||Q.test(o))return r;if(o.startsWith("[")&&o.endsWith("]")){let s=o.slice(1,-1);return `${r}/:${s}`}return `${r}/${o}`},"")||"/"}async function ht(e){return await Ye(e)?(await dt(e,{pathnameFilter:o=>Q.test(o),ignorePartFilter:o=>o.startsWith("_")||o==="node_modules"})).map(o=>{let s=v__default.relative(e,o);return {filePath:me(s),route:be(me(s))}}):[]}function yt(e){return e.replace(/[-_]+(.)?/g,(t,r)=>r?r.toUpperCase():"").replace(/^[A-Z]/,t=>t.toLowerCase())}function Ws(e){return `../src/api/${e.replace(/\.ts$/,"")}`}function Gs(e){return e.startsWith(":")?`$${yt(e.slice(1))}`:yt(e)}function hr(){return {children:new Map}}function Vs(e){let t=hr();for(let[r,o]of e){let s=r.split("/").filter(Boolean),n=t;for(let i of s){let f=Gs(i);n.children.has(f)||n.children.set(f,hr()),n=n.children.get(f);}n.importType=o;}return t}function wr(e,t=" "){let r=[];if(e.importType&&r.push(e.importType),e.children.size>0){let o=[];for(let[s,n]of e.children){let i=wr(n,t+" ");o.push(`${t} ${s}: ${i}`);}r.push(`{
33
33
  ${o.join(`;
34
34
  `)};
35
- ${t}}`);}return r.length===0?"{}":r.length===1?r[0]:r.join(" & ")}function Nr(e,t){let r=new Map;for(let[n,m]of Object.entries(Cr))r.set(n,m);for(let[n,m]of Object.entries(Pr))r.set(n,m);let o=t??os;for(let n of e){let m=o(n.filePath);r.set(n.route,`typeof import("${m}")`);}let i=ss(r);return `// This file is generated automatically by Mercur CLI
35
+ ${t}}`);}return r.length===0?"{}":r.length===1?r[0]:r.join(" & ")}function Rr(e,t,r){let o=new Map;for(let[f,c]of Object.entries(t))o.set(f,c);let s=r??Ws;for(let f of e){let c=s(f.filePath);o.set(f.route,`typeof import("${c}")`);}let n=Vs(o);return `// This file is generated automatically by Mercur CLI
36
36
  // Do not edit this file manually
37
37
 
38
- export type Routes = ${Dr(i,"")};
39
- `}async function Fr(e){let t=R__default.join(e,Ze,"routes.d.ts"),r=R__default.join(e,"src","api"),o=R__default.dirname(t);await Xe(o);let i=await xt(r),s=Nr(i);await U__default.writeFile(t,s,"utf-8");}async function Or(e,t){let r=R__default.join(e,Ze,"index.ts"),o=R__default.dirname(r);await Xe(o);let i=t.map(m=>{let p=m.indexOf("/api/"),d=p!==-1?m.slice(p+5):m;return {filePath:m,route:Ie(ge(d))}}),n=Nr(i,m=>`../../src/${m.replace(/\.ts$/,"")}`);await U__default.writeFile(r,n,"utf-8");}async function Mr(e){let t={},r={cwd:e.cwd,registryFile:R__default.resolve(e.cwd,e.registryFile)};if(!L.existsSync(r.registryFile))return t[B]=true,{errors:t,resolvePaths:null,config:null};if(!L.existsSync(R__default.resolve(e.cwd,"blocks.json")))return t[S]=true,{errors:t,resolvePaths:null,config:null};try{let o=await b(e.cwd);return {errors:t,config:o,resolvePaths:r}}catch{a.break(),a.error(`An invalid ${l.info("blocks.json")} file was found at ${l.info(e.cwd)}.
40
- Before you can run registry:codegen, you must create a valid ${l.info("blocks.json")} file by running the ${l.info("init")} command.`),a.break(),process.exit(1);}}var as=z.object({cwd:z.string(),registryFile:z.string()}),zr=new Command().name("registry:codegen").description("generate type definitions for registry block API routes").argument("[registry]","path to registry.json file","./registry.json").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).action(async(e,t)=>{await ds({cwd:R.resolve(t.cwd),registryFile:e});});async function ds(e){try{let t=as.parse(e),{errors:r,resolvePaths:o}=await Mr(t);r[S]&&(a.error(`A ${l.info("blocks.json")} file is required to run registry:codegen. Run ${l.info("mercur init")} to create one.`),a.break(),process.exit(1)),(r[B]||!o)&&(a.error(`Could not find a registry file at ${l.info(R.resolve(t.cwd,t.registryFile))}.`),a.break(),process.exit(1));let i=await U.readFile(o.registryFile,"utf-8"),s=K.safeParse(JSON.parse(i));s.success||(a.error(`Invalid registry file at ${l.info(o.registryFile)}.`),a.break(),process.exit(1));let n=[];for(let p of s.data.items)if(p.files)for(let d of p.files)d.type==="registry:api"&&oe.test(d.path)&&n.push(d.path);if(n.length===0){a.warn("No API route files found in registry.");return}let m=v("Generating registry route types...");await Or(t.cwd,n),m.succeed("Registry route types generated successfully."),a.break();}catch(t){a.break(),j(t);}}var ps=z.object({cwd:z.string()}),Gr=new Command().name("codegen").description("generate type definitions for API routes").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).action(async e=>{await cs({cwd:R.resolve(e.cwd)});});async function cs(e){try{let t=ps.parse(e),r=v("Generating route types...");await Fr(t.cwd),r.succeed("Route types generated successfully."),a.break();}catch(t){a.break(),j(t);}}var It=({contents:e,databaseUri:t})=>{let r=new Set,o=e;return e.includes("DATABASE_URL")||(o+=`
41
- DATABASE_URL=your-connection-string-here`),o.split(`
42
- `).map(s=>{if(s.startsWith("#")||!s.includes("="))return s;let[n]=s.split("=");if(n)return n==="DATABASE_URL"&&(s=`DATABASE_URL=${t||"postgresql://localhost:5432/your-database-name"}`),r.has(n)?null:(r.add(n),s)}).filter(Boolean).join(`
43
- `)},us=[{path:"packages/api"},{path:"apps/vendor"},{path:"apps/admin"}];async function et({projectDir:e,databaseUri:t}){try{await Promise.all(us.map(async({path:r})=>{let o=R__default.join(e,r);if(!L.existsSync(o))return;let i=R__default.join(o,".env.template"),s=R__default.join(o,".env");if(!r.includes("api")){L.existsSync(i)&&!L.existsSync(s)&&await L.copy(i,s);return}let m="";if(L.existsSync(i)){let p=await L.readFile(i,"utf8");m=It({contents:p,databaseUri:t});}if(L.existsSync(s)){let p=await L.readFile(s,"utf8"),d=It({contents:p,databaseUri:t});await L.writeFile(s,d);}else {let p=It({contents:m,databaseUri:t});await L.writeFile(s,p);}}));}catch(r){a.error("Unable to manage environment files"),r instanceof Error&&a.error(r.message),process.exit(1);}}var fs="localhost",qr=5432,Tt="packages/api",gs="admin@mercur-test.com";async function Jr(e){let t=e.projectName.replace(/[^a-zA-Z0-9]/g,"-"),{client:r,dbConnectionString:o}=await ys({dbConnectionString:e.dbConnectionString,dbHost:e.dbHost??fs,dbPort:e.dbPort??qr,dbName:t,spinner:e.spinner});if(!r||!o)return {success:false,dbName:t,connectionString:null};try{return e.spinner&&(e.spinner.text="Checking if database exists..."),await hs(r,t)?(await r.end(),Vr({...e,dbName:t,connectionString:o,alreadyExists:!0})):(e.spinner&&(e.spinner.text=`Creating database "${t}"...`),await r.query(`CREATE DATABASE "${t}"`),await r.end(),Vr({...e,dbName:t,connectionString:o,alreadyExists:!1}))}catch(i){return a.error(`Error creating database${i instanceof Error?`: ${i.message}`:""}.`),await r.end().catch(()=>{}),{success:false,dbName:t,connectionString:null}}}async function Vr(e){let{projectDir:t,spinner:r,dbName:o,connectionString:i,alreadyExists:s}=e;if(await et({projectDir:t,databaseUri:i}),!await vs({projectDir:t,spinner:r}))return {success:false,dbName:o,connectionString:null};if(!await js({projectDir:t,spinner:r}))return {success:false,dbName:o,connectionString:null};let p=await ws({projectDir:t});return {success:true,dbName:o,connectionString:i,alreadyExists:s,inviteToken:p}}async function ys({dbConnectionString:e,dbHost:t,dbPort:r,dbName:o,spinner:i}){if(e)try{let n=new Ct.Client({connectionString:e});return await n.connect(),{client:n,dbConnectionString:e}}catch(n){return a.error(`Invalid database connection string${n instanceof Error?`: ${n.message}`:""}.`),{client:null,dbConnectionString:null}}i&&(i.text=`Trying default connection (postgres@${t}:${r})...`);try{let n=new Ct.Client({user:"postgres",password:"",host:t,port:r,database:"postgres",connectionTimeoutMillis:5e3});return await n.connect(),{client:n,dbConnectionString:Yr({user:"postgres",password:"",host:t,port:r,db:o})}}catch{}i?.stop(),a.break(),a.log(`PostgreSQL is required. Make sure it is installed and running on ${t}:${r}.`),a.break();let s=3;for(let n=1;n<=s;n++){let m=n>1?` (attempt ${n}/${s})`:"",p=await Pe([{type:"text",name:"postgresUsername",message:`Enter your Postgres username${m}`,initial:"postgres"},{type:"password",name:"postgresPassword",message:'Enter your Postgres password (press Enter for "postgres")'}]);if(!p.postgresUsername)return {client:null,dbConnectionString:null};let d=p.postgresUsername,u=p.postgresPassword||"postgres";i?.start("Connecting to database...");try{let c=new Ct.Client({user:d,password:u,host:t,port:r,database:"postgres",connectionTimeoutMillis:5e3});return await c.connect(),{client:c,dbConnectionString:Yr({user:d,password:u,host:t,port:r,db:o})}}catch(c){i?.stop();let f=c instanceof Error?c.message:String(c);n<s?a.warn(`Attempt ${n}/${s} failed: ${f}`):a.error(`Couldn't connect to PostgreSQL: ${f}
44
- \u2192 Is PostgreSQL running? Try: pg_isready -h ${t} -p ${r}
45
- \u2192 Check your username, password, and that the server is accessible.`);}}return {client:null,dbConnectionString:null}}async function hs(e,t){return ((await e.query(`SELECT datname FROM pg_catalog.pg_database WHERE datname='${t}';`)).rowCount??0)>0}function Yr({user:e,password:t,host:r,port:o=qr,db:i}){let s=encodeURIComponent(t);return `postgresql://${e}:${s}@${r}:${o}/${i}`}async function vs({projectDir:e,spinner:t}){let r=R__default.join(e,Tt),o=await A(r),i=t||v("Running migrations...").start(),s=o==="yarn"?["yarn","run","build"]:o==="pnpm"?["pnpm","run","build"]:o==="bun"?["bun","run","build"]:["npm","run","build"],n=o==="pnpm"?["pnpm","dlx"]:o==="bun"?["bunx"]:["npx"];try{return i.text="Building project...",await execa(s[0],s.slice(1),{cwd:r}),i.text="Running database migrations...",await execa(n[0],[...n.slice(1),"medusa","db:migrate"],{cwd:r}),t||i.succeed("Migrations completed successfully."),!0}catch(m){return i.fail("Failed to run migrations."),a.error(`Error running migrations${m instanceof Error?`: ${m.message}`:""}.`),false}}async function ws({projectDir:e}){let t=R__default.join(e,Tt),r=await A(t),o=r==="pnpm"?["pnpm","dlx"]:r==="bun"?["bunx"]:["npx"];try{return (await execa(o[0],[...o.slice(1),"medusa","user","-e",gs,"--invite"],{cwd:t})).stdout.match(/Invite token: (?<token>.+)/)?.groups?.token||null}catch(i){return a.error(`Error creating admin invite${i instanceof Error?`: ${i.message}`:""}.`),null}}async function js({projectDir:e,spinner:t}){let r=R__default.join(e,Tt),o=await A(r),i=t||v("Seeding database...").start();try{let s=o==="yarn"?["yarn","seed"]:o==="pnpm"?["pnpm","run","seed"]:o==="bun"?["bun","run","seed"]:["npm","run","seed"];return i.text="Seeding database with demo data...",await execa(s[0],s.slice(1),{cwd:r}),t||i.succeed("Database seeded successfully."),!0}catch(s){return i.fail("Failed to seed database."),a.error(`Error seeding database${s instanceof Error?`: ${s.message}`:""}.`),false}}var Hr=Fe.version?.includes("-canary")?"canary":"main",$t=20,Zr={basic:{path:"basic",description:"Full marketplace starter \u2014 sellers, products, orders, admin & vendor panels"},plugin:{path:"plugin",description:"MedusaJS plugin template \u2014 for building reusable marketplace extensions"}},Qr=new Command().name("create").description("create a new Mercur project").argument("[name]","the name of your project").option("-t, --template <template>","the template to use. e.g. basic, registry, or plugin").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).option("--no-deps","skip installing dependencies.").option("--skip-db","skip database configuration.",false).option("--skip-email","skip email prompt.",false).option("--db-connection-string <string>","PostgreSQL connection string.").option("--db-host <host>","PostgreSQL host.","localhost").option("--db-port <port>","PostgreSQL port.","5432").action(async(e,t)=>{try{let r=Date.now();Ls(),H();let o=e;if(!o){let{enteredName:c}=await Pe({type:"text",name:"enteredName",message:"What is your project named?",initial:t.template?`${t.template}-app`:"my-mercur",format:f=>f.trim(),validate:f=>Is(R__default.basename(R__default.resolve(f))).validForNewPackages?!0:"Invalid project name. Name should be lowercase, URL-friendly, and not start with a period or underscore."});c||process.exit(0),o=c;}let i=t.template;if(!i){let{selectedTemplate:c}=await Pe({type:"select",name:"selectedTemplate",message:`Which ${l.info("template")} would you like to use?`,choices:Object.entries(Zr).map(([f,y])=>({title:f,value:f,description:y.description}))});c||process.exit(0),i=c;}if(!t.skipEmail){let{wantsEmail:c}=await Pe({type:"confirm",name:"wantsEmail",message:"Mind sharing your email? We reach out for priority support, community events, and invite-only meetups. We never spam.",initial:!1});if(c){let{email:f}=await Pe({type:"text",name:"email",message:"Enter your email:",format:y=>y.trim()});f&&Rr(f);}}let s=R__default.resolve(t.cwd,o);await Ps(s);let n=v("Downloading template...").start();await Ts({projectDir:s,template:i}),n.succeed("Template downloaded successfully.");let m=await A(s);if(await Fs(s,m),!t.deps)v("Dependency installation skipped.").warn();else {let c=v("Installing dependencies...").start(),f=Date.now(),y=await Ds({projectDir:s,packageManager:m}),h=((Date.now()-f)/1e3).toFixed(1);y?c.succeed(`Dependencies installed successfully in ${h}s.`):(c.fail("Failed to install dependencies"),await P({type:"create",payload:{outcome:"dependency_installation_failed",packageManager:m}},{cwd:s}),process.exit(1));}let p=t.dbConnectionString,d;if(t.skipDb)v("Database setup skipped.").warn();else {let c=v("Setting up database...").start();d=await Jr({projectDir:s,projectName:o,dbConnectionString:p,dbHost:t.dbHost,dbPort:parseInt(t.dbPort,10),spinner:c}),d.success?(d.alreadyExists?c.warn(`Database ${l.info(d.dbName)} already exists. Skipping database creation.`):c.succeed(`Database ${l.info(d.dbName)} setup successfully.`),p=d.connectionString):(c.fail("Failed to setup database."),a.log(Dt()),await P({type:"create",payload:{outcome:"database_setup_failed"}},{cwd:s}),process.exit(1));}await et({projectDir:s,databaseUri:p}),await Os(s),await P({type:"create",payload:{outcome:"created"}},{cwd:s});let u=((Date.now()-r)/1e3).toFixed(1);if(v(`Mercur project successfully created! (${u}s)`).succeed(),d?.success){v("Starting development server...").info();let c=d.inviteToken?`http://localhost:9000/dashboard/invite?token=${d.inviteToken}&first_run=true`:"http://localhost:9000/dashboard",h=spawn(m==="npm"?"npm":m,m==="npm"?["run","dev"]:["dev"],{cwd:s,stdio:"inherit",env:process.env}),w=()=>{a.break(),a.log(N.bgGreen(N.black(" Project stopped. To start again: "))),a.log(Kr(s,m)),a.log(Dt()),a.break();};process.on("SIGINT",()=>{}),h.on("close",()=>{w(),process.exit(0);}),Cs({resources:["http://localhost:9000/health"],timeout:6e4}).then(async()=>{a.break(),a.log(Ns());try{await ks(c),v("Admin panel opened in your browser.").succeed();}catch{v("Open this URL in your browser to create your admin account:").info(),a.log(l.info(c));}}).catch(()=>{v("To create your admin account, visit:").info(),a.log(l.info(c));});}else a.log(N.bgGreen(N.black(" Next Steps "))),a.log(Kr(s,m)),a.log(Dt()),a.break();}catch(r){a.break(),j(r);}finally{x();}});async function Ps(e){if(!await L.pathExists(e)){await L.mkdir(e);return}let o=(await L.readdir(e)).filter(i=>!i.startsWith("."));if(o.length>0){let{proceed:i}=await Pe({type:"confirm",name:"proceed",message:`Directory ${l.info(R__default.basename(e))} already exists and contains ${o.length} file(s). Continue and overwrite?`,initial:false});i||process.exit(0);}}async function Ts({projectDir:e,template:t}){let r=`https://codeload.github.com/mercurjs/mercur/tar.gz/${Hr}`,o=Zr[t].path,i=`mercur-${Hr.replace(/^v/,"").replaceAll("/","-")}/templates/${o}/`;await pipeline(await $s(r),x$1({cwd:e,filter:s=>s.includes(i),strip:2+o.split("/").length}));}async function $s(e){let t=await fetch(e);if(!t.body)throw new Error(`Failed to download: ${e}`);return Readable.from(t.body)}async function Ds({projectDir:e,packageManager:t}){let r="npm",o=["install"];t==="yarn"?(r="yarn",o=[]):t==="pnpm"?(r="pnpm",o=["install"]):t==="bun"&&(r="bun",o=["install"]);try{return await execa(r,o,{cwd:R__default.resolve(e),stdin:"inherit",stdout:"inherit",stderr:"inherit",env:{...process.env,npm_config_yes:"true"}}),!0}catch(i){return a.error(`Error installing dependencies${i instanceof Error?`: ${i.message}`:""}.`),false}}function Kr(e,t){let r=R__default.relative(process.cwd(),e),o=i=>N.bold(i);return `
46
- ${o("Launch Application:")}
47
-
48
- - cd ./${r}
49
- - ${t==="npm"?"npm run":t} dev
50
-
51
- ${o("Create your first seller:")}
52
-
53
- Once the server is running, open the Vendor Panel and register at:
54
- ${l.info("http://localhost:9000/seller/register")}
55
-
56
- ${o("Documentation:")}
57
-
58
- - ${Nt("Getting Started","https://docs.mercurjs.com/welcome")}
59
- `}function Ns(){let e=t=>N.bold(t);return `
60
- ${e("Your marketplace is running:")}
61
-
62
- API: ${l.info("http://localhost:9000")}
63
- Admin Panel: ${l.info("http://localhost:9000/dashboard")}
64
- Vendor Panel: ${l.info("http://localhost:9000/seller")}
65
-
66
- ${e("Create your first seller:")}
67
-
68
- Open the Vendor Panel and register a new account at:
69
- ${l.info("http://localhost:9000/seller/register")}
70
- `}function Dt(){return `${N.bgCyan(N.black(" Have feedback? "))} Visit us on ${Nt("GitHub","https://github.com/mercurjs/mercur")}.
71
- ${N.bgMagenta(N.black(" Join the community! "))} Chat with us on ${Nt("Discord","https://discord.gg/hnZBzc4NJU")}.`}function Nt(e,t){return Ss(e,t,{fallback:(r,o)=>`${r}: ${N.cyan().underline(o)}`})}async function Fs(e,t){let r=R__default.join(e,"package.json"),o=await L.readJSON(r),{stdout:i}=await execa(t,["--version"]);o.packageManager=`${t}@${i.trim()}`,await L.writeJSON(r,o,{spaces:2});}async function Os(e){try{await execa("git",["init"],{cwd:e}),a.info("Initialized a git repository.");}catch{throw new Error("Failed to initialize git repository.")}}function As(){let[e]=process.versions.node.split(".").map(Number);return e}function Ls(){let e=As();if(e<$t)throw new Error(`Mercur requires at least v${$t} of Node.js. You're using v${e}. Please install at least v${$t} and try again: https://nodejs.org/en/download`)}async function Xr(e,t){let{config:r}=t||{};if(q(e)){let[n]=await te([e]);try{return K.parse(n)}catch(m){throw new C(e,m)}}if(!e.startsWith("@"))throw new ze(e);let o=e;o.endsWith("/registry")||(o=`${o}/registry`);let i=be(o,me(r));if(!i?.url)throw new ae(o);let[s]=await te([i.url]);try{return K.parse(s)}catch(n){throw new C(o,n)}}async function rt(e,t){let{config:r}=t||{};return x(),qe(e,me(r))}var Gs=z.object({blocks:z.array(z.string()).optional(),cwd:z.string()}),eo=new Command().name("diff").description("check for updates against the registry").argument("[blocks...]","the block names to diff").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).action(async(e,t)=>{try{let r=Gs.parse({blocks:e,cwd:R__default.resolve(t.cwd),type:t.type}),o=await b(r.cwd);o||(o=G({resolvedPaths:{cwd:r.cwd}})),r.blocks?.length||(a.error("Please specify at least one block to diff."),process.exit(1));let i=await rt(r.blocks,{config:o}),s=r.blocks.filter(m=>!i.some(p=>p.name===m));s.length>0&&(a.error(`Blocks ${s.join(", ")} not found in registry.`),process.exit(1));let n=await k(o.resolvedPaths.cwd);for(let m of i)for(let p of m.files){let d=Je(p,o,{isSrcDir:n?.isSrcDir??!1,path:r.cwd});if(!existsSync(d)){a.info(`File ${d} does not exist locally.`);continue}let u=await promises.readFile(d,"utf-8"),c=await He({filename:p.path,raw:p.content,config:o,isRemote:!1}),f=diffLines(u,c);f.length>1&&(a.info(`
72
- File: ${l.info(p.path)}`),Vs(f));}}catch(r){j(r);}finally{x();}});function Vs(e){for(let t of e)t&&(t.added?process.stdout.write(l.success(t.value)):t.removed?process.stdout.write(l.error(t.value)):process.stdout.write(t.value));}var to=new Command().name("info").description("get information about your project").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).action(async e=>{try{a.info("> project info"),console.log(await k(e.cwd)),a.break(),a.info("> blocks.json"),console.log(await b(e.cwd));}catch(t){j(t);}});var Hs=z.object({cwd:z.string(),query:z.string().optional(),registry:z.string().optional()}),ro=new Command().name("search").description("search blocks from registries").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).option("-q, --query <query>","query string").option("-r, --registry <registry>","the registry to search from (default: @mercurjs)","@mercurjs").action(async e=>{try{let t=Hs.parse({cwd:R__default.resolve(e.cwd),query:e.query,type:e.type,registry:e.registry}),r=await b(t.cwd);r||(r=G({resolvedPaths:{cwd:t.cwd}}));let i=(await Xr(t.registry??"@mercurjs",{config:r})).items;if(t.query){let s=t.query.toLowerCase();i=i.filter(n=>n.name.toLowerCase().includes(s)||n.description?.toLowerCase().includes(s));}console.log(JSON.stringify(i,null,2)),process.exit(0);}catch(t){j(t);}finally{x();}});var oo=new Command().name("telemetry").description("manage the collection of anonymous usage data").option("--enable","enable telemetry").option("--disable","disable telemetry").action(async e=>{try{if(e.enable&&e.disable){a.error("Cannot use --enable and --disable together.");return}if(!e.enable&&!e.disable){let r=M.get("telemetry_enabled"),o=process.env.MERCUR_DISABLE_TELEMETRY==="true",i=r&&!o,s=i?"enabled":"disabled";a.log(`Telemetry is currently ${s}.`),o&&r&&a.log("(Disabled via MERCUR_DISABLE_TELEMETRY environment variable)"),a.log(i?'Run "mercurjs telemetry --disable" to opt out.':'Run "mercurjs telemetry --enable" to opt in.'),a.log(`Learn more: ${Ke}`);return}let t=!!e.enable;xr(t),t?a.success(`Telemetry enabled. Learn more: ${Ke}`):a.success("Telemetry disabled. No data will be collected.");}catch(t){j(t);}});var Xs=z.object({cwd:z.string()}),so=new Command().name("view").description("view block details from the registry").argument("<blocks...>","the block names to view").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).action(async(e,t)=>{try{let r=Xs.parse({cwd:R__default.resolve(t.cwd),type:t.type}),o=await b(r.cwd);o||(o=G({resolvedPaths:{cwd:r.cwd}}));let i=await rt(e,{config:o});console.log(JSON.stringify(i,null,2)),process.exit(0);}catch(r){j(r);}finally{x();}});async function ao(e){let t=R__default.resolve(e.root,"src/vendor");if(!Ot.existsSync(t))return true;let r=await import('vite'),o=(await import('@vitejs/plugin-react')).default,i=JSON.parse(readFileSync(R__default.resolve(e.root,"package.json"),"utf-8")),s=new Set([...Object.keys(i.dependencies||{}),...Object.keys(i.peerDependencies||{}),...Object.keys(i.devDependencies||{}),"react","react/jsx-runtime","react-router-dom","react-i18next","@medusajs/js-sdk","@medusajs/admin-sdk","@mercurjs/client","@tanstack/react-query"]),n=R__default.resolve(e.outDir,"src/vendor"),m=R__default.resolve(e.root,"src/vendor/__vendor-extensions__.js");try{let p=generatePluginEntryModule(t);await writeFile(m,p,"utf-8");let d=process.env.NODE_ENV;process.env.NODE_ENV="production",await r.build({build:{lib:{entry:m,formats:["es","cjs"],fileName:"index"},emptyOutDir:!1,minify:!1,outDir:n,rollupOptions:{external:(f,y)=>{let h=f.split("/"),w=h[0]?.startsWith("@")?`${h[0]}/${h[1]}`:h[0],E=[...builtinModules,...builtinModules.map(F=>`node:${F}`)];return y?!!(w&&s.has(w)):!!(w&&s.has(w)||w&&E.includes(w))},output:{preserveModules:!1,interop:"auto",chunkFileNames:()=>"_chunks/[name]-[hash]"}}},plugins:[o()],logLevel:"silent",clearScreen:!1}),process.env.NODE_ENV=d;let u=R__default.join(n,"index.es.js"),c=R__default.join(n,"index.mjs");return Ot.existsSync(u)&&Ot.renameSync(u,c),!0}catch(p){return console.error(p),false}finally{try{await rm(m,{force:!0});}catch{}}}var po=new Command().name("plugin:build").description("build a Medusa plugin").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).action(async e=>{try{let t=R__default.resolve(e.cwd),r=v("Building plugin..."),{Compiler:o}=await import('@medusajs/framework/build-tools'),i=new o(t,a),s=await i.loadTSConfigFile();s||(r.fail("Unable to compile plugin \u2014 tsconfig not found."),process.exit(1));let n=await import('@medusajs/admin-bundler'),m=R__default.resolve(t,".medusa/server");(await Promise.all([i.buildPluginBackend(s),i.buildPluginAdminExtensions(n),ao({root:t,outDir:m})])).every(d=>d===!0)?r.succeed("Plugin built successfully."):(r.fail("Plugin build failed."),process.exit(1));}catch(t){a.break(),j(t);}});process.on("SIGINT",()=>process.exit(0));process.on("SIGTERM",()=>process.exit(0));async function an(){let e=new Command().name("@mercurjs/cli").description("Add blocks from registries to your project").version(Fe.version,"-v, --version","display the version number");e.addCommand(Er).addCommand(Ir).addCommand(zr).addCommand(Gr).addCommand(Qr).addCommand(eo).addCommand(to).addCommand(kr).addCommand(ro).addCommand(oo).addCommand(so).addCommand(po),e.parse();}an();export{go as registryConfigItemSchema,Bt as registryConfigSchema,un as registryIndexSchema,Mt as registryItemFileSchema,T as registryItemSchema,fo as registryItemTypeSchema,zt as registryResolvedItemsTreeSchema,K as registrySchema};//# sourceMappingURL=index.js.map
38
+ export type Routes = ${wr(n,"")};
39
+ `}async function Er(e){let t=v__default.join(e,Ve,"routes.d.ts"),r=v__default.join(e,"src","api"),o=v__default.dirname(t);await Je(o);let s=await He(),n=await ht(r),i=Rr(n,s);await $__default.writeFile(t,i,"utf-8");}async function xr(e,t){let r=v__default.join(e,Ve,"index.d.ts"),o=v__default.dirname(r);await Je(o);let s=t.map(c=>{let a=c.indexOf("/api/"),m=a!==-1?c.slice(a+5):c;return {filePath:c,route:be(me(m))}}),n=c=>`../src/${c.replace(/\.ts$/,"")}`,i=await He(),f=Rr(s,i,n);await $__default.writeFile(r,f,"utf-8");}async function br(e){let t={},r={cwd:e.cwd,registryFile:v__default.resolve(e.cwd,e.registryFile)};if(!ut.existsSync(r.registryFile))return t[A]=true,{errors:t,resolvePaths:null,config:null};if(!ut.existsSync(v__default.resolve(e.cwd,"blocks.json")))return t[C]=true,{errors:t,resolvePaths:null,config:null};try{let o=await E(e.cwd);return {errors:t,config:o,resolvePaths:r}}catch{l.break(),l.error(`An invalid ${u.info("blocks.json")} file was found at ${u.info(e.cwd)}.
40
+ Before you can run registry:codegen, you must create a valid ${u.info("blocks.json")} file by running the ${u.info("init")} command.`),l.break(),process.exit(1);}}var Js=z.object({cwd:z.string(),registryFile:z.string()}),kr=new Command().name("registry:codegen").description("generate type definitions for registry block API routes").argument("[registry]","path to registry.json file","./registry.json").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).action(async(e,t)=>{await Hs({cwd:v.resolve(t.cwd),registryFile:e});});async function Hs(e){try{let t=Js.parse(e),{errors:r,resolvePaths:o}=await br(t);r[C]&&(l.error(`A ${u.info("blocks.json")} file is required to run registry:codegen. Run ${u.info("mercur init")} to create one.`),l.break(),process.exit(1)),(r[A]||!o)&&(l.error(`Could not find a registry file at ${u.info(v.resolve(t.cwd,t.registryFile))}.`),l.break(),process.exit(1));let s=await $.readFile(o.registryFile,"utf-8"),n=Y.safeParse(JSON.parse(s));n.success||(l.error(`Invalid registry file at ${u.info(o.registryFile)}.`),l.break(),process.exit(1));let i=[];for(let c of n.data.items)if(c.files)for(let a of c.files)a.type==="registry:api"&&Q.test(a.path)&&i.push(a.path);if(i.length===0){l.warn("No API route files found in registry.");return}let f=x("Generating registry route types...");await xr(t.cwd,i),f.succeed("Registry route types generated successfully."),l.break();}catch(t){l.break(),R(t);}}var qs=z.object({cwd:z.string()}),_r=new Command().name("codegen").description("generate type definitions for API routes").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).action(async e=>{await Zs({cwd:v.resolve(e.cwd)});});async function Zs(e){try{let t=qs.parse(e),r=x("Generating route types...");await Er(t.cwd),r.succeed("Route types generated successfully."),l.break();}catch(t){l.break(),R(t);}}async function Tr(e,t){let{config:r}=t||{};if(B(e)){let[i]=await Z([e]);try{return Y.parse(i)}catch(f){throw new _(e,f)}}if(!e.startsWith("@"))throw new Ne(e);let o=e;o.endsWith("/registry")||(o=`${o}/registry`);let s=ye(o,se(r));if(!s?.url)throw new re(o);let[n]=await Z([s.url]);try{return Y.parse(n)}catch(i){throw new _(o,i)}}async function Ke(e,t){let{config:r}=t||{};return S(),Ue(e,se(r))}var on=z.object({blocks:z.array(z.string()).optional(),cwd:z.string()}),jr=new Command().name("diff").description("check for updates against the registry").argument("[blocks...]","the block names to diff").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).action(async(e,t)=>{try{let r=on.parse({blocks:e,cwd:v__default.resolve(t.cwd),type:t.type}),o=await E(r.cwd);o||(o=L({resolvedPaths:{cwd:r.cwd}})),r.blocks?.length||(l.error("Please specify at least one block to diff."),process.exit(1));let s=await Ke(r.blocks,{config:o}),n=r.blocks.filter(f=>!s.some(c=>c.name===f));n.length>0&&(l.error(`Blocks ${n.join(", ")} not found in registry.`),process.exit(1));let i=await b(o.resolvedPaths.cwd);for(let f of s)for(let c of f.files){let a=Be(c,o,{isSrcDir:i?.isSrcDir??!1,path:r.cwd});if(!existsSync(a)){l.info(`File ${a} does not exist locally.`);continue}let m=await promises.readFile(a,"utf-8"),p=await We({filename:c.path,raw:c.content,config:o,isRemote:!1}),g=diffLines(m,p);g.length>1&&(l.info(`
41
+ File: ${u.info(c.path)}`),sn(g));}}catch(r){R(r);}finally{S();}});function sn(e){for(let t of e)t&&(t.added?process.stdout.write(u.success(t.value)):t.removed?process.stdout.write(u.error(t.value)):process.stdout.write(t.value));}var Fr=new Command().name("info").description("get information about your project").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).action(async e=>{try{l.info("> project info"),console.log(await b(e.cwd)),l.break(),l.info("> blocks.json"),console.log(await E(e.cwd));}catch(t){R(t);}});var ln=z.object({cwd:z.string(),query:z.string().optional(),registry:z.string().optional()}),Or=new Command().name("search").description("search blocks from registries").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).option("-q, --query <query>","query string").option("-r, --registry <registry>","the registry to search from (default: @mercurjs)","@mercurjs").action(async e=>{try{let t=ln.parse({cwd:v__default.resolve(e.cwd),query:e.query,type:e.type,registry:e.registry}),r=await E(t.cwd);r||(r=L({resolvedPaths:{cwd:t.cwd}}));let s=(await Tr(t.registry??"@mercurjs",{config:r})).items;if(t.query){let n=t.query.toLowerCase();s=s.filter(i=>i.name.toLowerCase().includes(n)||i.description?.toLowerCase().includes(n));}console.log(JSON.stringify(s,null,2)),process.exit(0);}catch(t){R(t);}finally{S();}});var Nr=new Command().name("telemetry").description("manage the collection of anonymous usage data").option("--enable","enable telemetry").option("--disable","disable telemetry").action(async e=>{try{if(e.enable&&e.disable){l.error("Cannot use --enable and --disable together.");return}if(!e.enable&&!e.disable){let r=G.get("telemetry_enabled"),o=process.env.MERCUR_DISABLE_TELEMETRY==="true",s=r&&!o,n=s?"enabled":"disabled";l.log(`Telemetry is currently ${n}.`),o&&r&&l.log("(Disabled via MERCUR_DISABLE_TELEMETRY environment variable)"),l.log(s?'Run "mercurjs telemetry --disable" to opt out.':'Run "mercurjs telemetry --enable" to opt in.'),l.log(`Learn more: ${Ge}`);return}let t=!!e.enable;lr(t),t?l.success(`Telemetry enabled. Learn more: ${Ge}`):l.success("Telemetry disabled. No data will be collected.");}catch(t){R(t);}});var un=z.object({cwd:z.string()}),Dr=new Command().name("view").description("view block details from the registry").argument("<blocks...>","the block names to view").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).action(async(e,t)=>{try{let r=un.parse({cwd:v__default.resolve(t.cwd),type:t.type}),o=await E(r.cwd);o||(o=L({resolvedPaths:{cwd:r.cwd}}));let s=await Ke(e,{config:o});console.log(JSON.stringify(s,null,2)),process.exit(0);}catch(r){R(r);}finally{S();}});async function Mr(e){let t=v__default.resolve(e.root,"src/vendor");if(!Et.existsSync(t))return true;let r=await import('vite'),o=(await import('@vitejs/plugin-react')).default,s=JSON.parse(readFileSync(v__default.resolve(e.root,"package.json"),"utf-8")),n=new Set([...Object.keys(s.dependencies||{}),...Object.keys(s.peerDependencies||{}),...Object.keys(s.devDependencies||{}),"react","react/jsx-runtime","react-router-dom","react-i18next","@medusajs/js-sdk","@medusajs/admin-sdk","@mercurjs/client","@tanstack/react-query"]),i=v__default.resolve(e.outDir,"src/vendor"),f=v__default.resolve(e.root,"src/vendor/__vendor-extensions__.js");try{let c=generatePluginEntryModule(t);await writeFile(f,c,"utf-8");let a=process.env.NODE_ENV;process.env.NODE_ENV="production",await r.build({build:{lib:{entry:f,formats:["es","cjs"],fileName:"index"},emptyOutDir:!1,minify:!1,outDir:i,rollupOptions:{external:(g,h)=>{let y=g.split("/"),w=y[0]?.startsWith("@")?`${y[0]}/${y[1]}`:y[0],k=[...builtinModules,...builtinModules.map(O=>`node:${O}`)];return h?!!(w&&n.has(w)):!!(w&&n.has(w)||w&&k.includes(w))},output:{preserveModules:!1,interop:"auto",chunkFileNames:()=>"_chunks/[name]-[hash]"}}},plugins:[o()],logLevel:"silent",clearScreen:!1}),process.env.NODE_ENV=a;let m=v__default.join(i,"index.es.js"),p=v__default.join(i,"index.mjs");return Et.existsSync(m)&&Et.renameSync(m,p),!0}catch(c){return console.error(c),false}finally{try{await rm(f,{force:!0});}catch{}}}var Ur=new Command().name("plugin:build").description("build a Medusa plugin").option("-c, --cwd <cwd>","the working directory. defaults to the current directory.",process.cwd()).action(async e=>{try{let t=v__default.resolve(e.cwd),r=x("Building plugin..."),{Compiler:o}=await import('@medusajs/framework/build-tools'),s=new o(t,l),n=await s.loadTSConfigFile();n||(r.fail("Unable to compile plugin \u2014 tsconfig not found."),process.exit(1));let i=await import('@medusajs/admin-bundler'),f=v__default.resolve(t,".medusa/server");(await Promise.all([s.buildPluginBackend(n),s.buildPluginAdminExtensions(i),Mr({root:t,outDir:f})])).every(a=>a===!0)?r.succeed("Plugin built successfully."):(r.fail("Plugin build failed."),process.exit(1));}catch(t){l.break(),R(t);}});process.on("SIGINT",()=>process.exit(0));process.on("SIGTERM",()=>process.exit(0));async function En(){let e=new Command().name("@mercurjs/cli").description("Add blocks from registries to your project").version(vt.version,"-v, --version","display the version number");e.addCommand(pr).addCommand(gr).addCommand(kr).addCommand(_r).addCommand(jr).addCommand(Fr).addCommand(mr).addCommand(Or).addCommand(Nr).addCommand(Dr).addCommand(Ur),e.parse();}En();export{Vr as registryConfigItemSchema,Ct as registryConfigSchema,Sn as registryIndexSchema,bt as registryItemFileSchema,T as registryItemSchema,Gr as registryItemTypeSchema,kt as registryResolvedItemsTreeSchema,Y as registrySchema};//# sourceMappingURL=index.js.map
73
42
  //# sourceMappingURL=index.js.map