croct 0.9.0 → 0.9.1
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/index.js +2 -2
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -1847,8 +1847,8 @@ ${this.getPreferences(e.protocol).join(`
|
|
|
1847
1847
|
`)}`;await this.fileSystem.writeTextFile(n,s,{overwrite:true});let p=a.parseHandlers(o);p.schemes[e.protocol]={ask:true,action:2,handlers:[{name:e.name,path:this.configuration.appPath}]},await this.fileSystem.writeTextFile(r,JSON.stringify(p),{overwrite:true});}async unregister(e){if(!await this.isRegistered(e))return;let t=await this.getProfilePath();if(t===null)return;let n=this.getUserPreferencesFilePath(t),r=this.getHandlersFilePath(t),[i,o]=await Promise.all([await this.fileSystem.readTextFile(n).catch(()=>""),this.fileSystem.readTextFile(r).catch(()=>"")]),s=i.split(`
|
|
1848
1848
|
`).filter(c=>!this.getPreferences(e).includes(c)).join(`
|
|
1849
1849
|
`);await this.fileSystem.writeTextFile(n,s,{overwrite:true});let p=a.parseHandlers(o);p.schemes[e]!==void 0&&(delete p.schemes[e],await this.fileSystem.writeTextFile(r,JSON.stringify(p),{overwrite:true}));}getUserPreferencesFilePath(e){return this.fileSystem.joinPaths(e,"user.js")}getHandlersFilePath(e){return this.fileSystem.joinPaths(e,"handlers.json")}async getProfilePath(){let e=this.getPath("profiles.ini");if(!await this.fileSystem.exists(e))return null;let t=Object.values(parse(await this.fileSystem.readTextFile(e))),n=[],r=[];for(let o of t)o.Default!==void 0&&n.push(o.Default),o.Path!==void 0&&(o.Default==="1"?r.unshift(o.Path):r.push(o.Path));if(r.length===0)return null;let i=r[0];for(let o of r)if(n.includes(o)){i=o;break}return this.getPath(i)}getPath(e){return this.fileSystem.joinPaths(this.profileDirectory,e)}getPreferences(e){return a.PREFERENCES.map(t=>t.replace(/%protocol%/g,e))}static parseHandlers(e){let t;try{t=JSON.parse(e);}catch{return {schemes:{}}}return typeof t!="object"||t===null?{schemes:{}}:!("schemes"in t)||typeof t.schemes!="object"||t.schemes===null?{...t,schemes:{}}:t}};var jo=class{constructor(e){this.config=e;}async execute(e){let{protocolRegistryProvider:t,io:{output:n}}=this.config,r=await t.get();if(r===null){["optionally-enable","optionally-update"].includes(e.operation)||n.alert("Deep linking is not available on your platform.");return}try{await this.apply(r,e);}catch(i){n.alert(`Deep link error: ${d.formatCause(i)}`);}}apply(e,t){let{io:{output:n}}=this.config;switch(t.operation){case "optionally-enable":return this.optionallyEnable(e,n);case "optionally-update":return this.optionallyUpdate(e,n);case "disable":return this.disable(e,false,n);case "enable":return this.enable(e,false,n)}}async optionallyEnable(e,t){let{protocolHandler:n,io:{input:r}}=this.config;if(!await e.isRegistered(n.protocol)&&await r?.confirm({message:"Turn on deep links to streamline your experience?",default:false})===true)return this.enable(e,true,t)}async enable(e,t,n){let{cliPackage:r,packageManager:i,protocolHandler:o}=this.config;if(!t&&await e.isRegistered(o.protocol)){n?.inform("Deep links are already enabled");return}let s=n?.notify("Enabling deep links");try{let p=await i.getPackageCommand(r,["open","$url"]);await e.register({...o,command:`${p.name} ${(p.arguments??[]).join(" ")}`}),s?.confirm("Deep links enabled");}finally{s?.stop();}}async disable(e,t,n){let{protocolHandler:r}=this.config;if(!t&&!await e.isRegistered(r.protocol)){n?.inform("Deep links are not enabled");return}let i=n?.notify("Disabling deep links");try{await e.unregister(r.protocol),i?.confirm("Deep links disabled");}finally{i?.stop();}}async optionallyUpdate(e,t){let{protocolHandler:n}=this.config;if(!await e.isRegistered(n.protocol))return this.optionallyEnable(e,t);let r=t?.notify("Updating deep links");try{await this.disable(e,!0),await this.enable(e,!0),r?.confirm("Deep links updated");}finally{r?.stop();}}};var Wo=class a{constructor({fileSystem:e,tsconfigValidator:t}){this.fileSystem=e,this.tsConfigValidator=t;}async load(e,t={}){let{fileNames:n=["tsconfig.json","jsconfig.json"]}=t,r=await this.fileSystem.getRealPath(e),i=await this.locateConfig(e,n,true);if(i===null)return null;let o=await this.resolveConfig({rootDirectory:r,configPath:i,fileNames:n,targetDirectories:(t.sourcePaths??[]).map(s=>this.fileSystem.isAbsolutePath(s)?s:this.fileSystem.joinPaths(r,s))});return o===null?null:{rootConfigPath:o.rootConfigPath,matchedConfigPath:o.matchedConfigPath,baseUrl:this.fileSystem.joinPaths(this.fileSystem.getDirectoryName(o.matchedConfigPath),o.compilerOptions?.baseUrl??"."),paths:o.compilerOptions?.paths??{}}}async locateConfig(e,t,n=false){for(let i of t){let o=this.fileSystem.joinPaths(e,i);if(await this.fileSystem.exists(o))return o}if(!n)return null;let r=this.fileSystem.getDirectoryName(e);return r===e?null:this.locateConfig(r,t)}async resolveConfig(e){let{configPath:t,fileNames:n,rootDirectory:r,targetDirectories:i}=e,o=await this.parseConfig(t);if(o?.extends!==void 0){let s=await this.locateParentConfig(r,this.fileSystem.getDirectoryName(t),o.extends);if(s!==null){let p=await this.resolveConfig({...e,configPath:s});p!==null&&(o=a.mergeConfig(o,p));}}if(o?.references!==void 0&&i.length>0){let{references:s,...p}=o;for(let c of o.references){let l=this.fileSystem.joinPaths(this.fileSystem.getDirectoryName(t),c.path),u=l.endsWith(".json")?l:await this.locateConfig(l,n);if(u===null)continue;let g=await this.resolveConfig({...e,configPath:u});if(g?.include!==void 0)for(let y of i){let C=this.fileSystem.joinPaths("./",this.fileSystem.getRelativePath(this.fileSystem.getDirectoryName(u),y));for(let v of g.include){let M=new Minimatch(v,{partial:true,magicalBraces:true});if(!M.hasMagic()&&!v.includes(".")&&(M=new Minimatch(`${v.replace(/\/?$/,"")}/**/*`,{partial:true})),M.match(C))return a.mergeConfig({...g,rootConfigPath:o.rootConfigPath},p)}}}}return o}async locateParentConfig(e,t,n){let r=n;r.endsWith(".json")||(r+=".json");let i=this.fileSystem.joinPaths(t,r);if(await this.fileSystem.exists(i))return i;let o=this.fileSystem.joinPaths(e,"node_modules",r);return await this.fileSystem.exists(o)?o:null}async parseConfig(e){let t;try{t=JsonParser.parse(await this.fileSystem.readTextFile(e)).toJSON();}catch{return null}let n=await this.tsConfigValidator.validate(t);return n.valid?{rootConfigPath:e,matchedConfigPath:e,...n.data}:null}static mergeConfig(e,t){return {...t,...e,compilerOptions:{...t.compilerOptions,...e.compilerOptions}}}};var Vo=class{constructor({commandExecutor:e,executableLocator:t}){this.executableLocator=t,this.commandExecutor=e;}async run(e,t={}){let n=await this.executableLocator.locate(e.name);if(n===null)throw new Pe(`Unable to locate executable for command \`${e.name}\`.`);return this.commandExecutor.run({...e,name:n},t)}};function gc(a){let e=typeof a=="string"?Ae(a,["jsx","typescript"]):a,t=false;return traverse(e,{enter:n=>{let{node:r}=n;if(_m(r))return t=true,n.stop()}}),t}function _m(a){return isTypeScript(a)||jm(a)}function jm(a){return (isImportSpecifier(a)||isImportDeclaration(a))&&(a.importKind==="type"||a.importKind==="typeof")}var Uo=class{async apply(e){if(!gc(e))return {modified:false,result:e};let t=createConfigItem([Um,{onlyRemoveTypeImports:true}]),n=createConfigItem([qm,{legacy:true}]),r={enter:function(s){let p=s.node.leadingComments??s.node.innerComments??null;if(p===null)return;let c=[];for(let l of p){let u=l.loc?.tokens??[],g=u.findIndex(y=>y.loc?.start===l.loc?.start&&y.loc?.end===l.loc?.end);if(g>=0&&g<u.length-1){let y=u[g],C=u.find((M,_)=>_>g&&!["CommentLine","CommentBlock"].includes(M.type));if(C===void 0)continue;C.loc.start.line-y.loc.end.line>1&&c.push(l);}}if(c.length>0){let l=noop();l.comments=c,s.insertBefore(l);}}},i=await transformFromAstAsync(e,void 0,{plugins:[{name:"comment-remover",visitor:{Program:r,TSTypeAliasDeclaration:r,TSInterfaceDeclaration:r,TSDeclareFunction:r,TSDeclareMethod:r,TSImportType:r,TSModuleDeclaration:r}},t,n],ast:true,configFile:false});return {result:i?.ast??e,modified:(i?.ast??null)!==null}}};var qo=class{constructor({executableLocator:e,command:t}){this.executableLocator=e,this.command=t;}async test(){return await this.executableLocator.locate(this.command)!==null}};var Ko=class{constructor({serverMap:e}){this.serverMap=e;}async execute({id:e},t){let{output:n}=t,r=this.serverMap.get(e);if(r===void 0)throw new d(`No server with id "${e}" found.`);let i=n.notify("Stopping server");try{await r.stop();}finally{i.stop();}this.serverMap.delete(e);}};var Ho=class{constructor({token:e}){this.token=e;}getToken(){return Promise.resolve(this.token.toString())}login(){this.reportUnsupportedOperation("login");}logout(){this.reportUnsupportedOperation("logout");}reportUnsupportedOperation(e){throw new d(`${e==="login"?"Login":"Logout"} is not supported when using an externally provided token.`,{title:"Unsupported operation",reason:"precondition",suggestions:["Do not specify the `--token` option or the `CROCT_TOKEN` environment variable."]})}};var xn=class{constructor(e){this.factory=e;}open(e){return this.instance===void 0&&(this.instance=this.factory()),this.instance.open(e)}};var wn=class{constructor(e){this.output=e;}open(e){let t=e.replace(/([\\`*_{}[\]()#+\-.!])/g,"\\$1");return this.output.log(`[${t}](${t})`),Promise.resolve()}};var Go=class{constructor(e){this.fallbackOpener=e;}async open(e){try{await Km(e);}catch{return this.fallbackOpener.open(e)}}};var Zo=class{constructor({packageManager:e}){this.packageManager=e;}async execute(e,t){let{output:n}=t,r=n?.notify("Installing dependencies");try{await this.packageManager.installDependencies({logger:new oe({status:"Installing dependencies",notifier:r})});}catch(i){throw h.fromCause(i)}finally{r?.stop();}}};var Gm=z.strictObject({}),Jo=class extends I{constructor(){super(Gm);}};var Qo=class{constructor({fileSystem:e}){this.fileSystem=e;}async execute({path:e,destination:t,overwrite:n=false}){let r=this.fileSystem.normalizeSeparators(e);if(!await this.fileSystem.exists(r))throw new h("Cannot move path because source does not exist.",{reason:"invalid_input",details:[`Source: ${r}`]});let i=this.fileSystem.normalizeSeparators(t);if(await this.fileSystem.exists(i)&&!n)throw new h("Cannot move path because destination already exists.",{reason:"precondition",details:[`Destination: ${i}`]});if(this.fileSystem.isSubPath(r,i))throw new h("Cannot move path to a subdirectory of itself.",{reason:"invalid_input",details:[`Source: ${r}`,`Destination: ${i}`]});try{await this.fileSystem.move(r,i,{overwrite:n});}catch(o){throw h.fromCause(o)}}};var Bo=class{constructor({fileSystem:e}){this.fileSystem=e;}async execute(e,t){t.set(e.result,await this.readFile(e));}async readFile({path:e,optional:t=false}){let n=this.fileSystem.normalizeSeparators(e);if(!await this.fileSystem.exists(n)){if(!t)throw new h("Cannot read file because it does not exist.",{reason:"precondition",details:[`Path: ${n}`]});return null}if(await this.fileSystem.isDirectory(n)){if(!t)throw new h("Cannot read file because the specified path is a directory.",{reason:"precondition",details:[`Path: ${n}`]});return null}try{return this.fileSystem.readTextFile(n)}catch(r){throw h.fromCause(r)}}};var Zm=z.strictObject({path:z.string().min(1),destination:z.string().min(1),overwrite:z.boolean().optional()}),Yo=class extends I{constructor(){super(Zm);}};var Jm=z.strictObject({path:z.string().min(1),optional:z.boolean().optional(),result:z.string().min(1)}),ta=class extends I{constructor(){super(Jm);}};var na=class{constructor({fileSystem:e}){this.fileSystem=e;}async execute({path:e}){let t=this.fileSystem.normalizeSeparators(e);if(await this.fileSystem.exists(t)&&!await this.fileSystem.isDirectory(t))throw new h("Cannot create directory because a file with the same name exists.",{reason:"precondition",details:[`Path: ${t}`]});try{await this.fileSystem.createDirectory(t,{recursive:!0});}catch(n){throw h.fromCause(n)}}};var Qm=z.strictObject({path:z.string().min(1)}),ra=class extends I{constructor(){super(Qm);}};var ia=class{constructor({fileSystem:e,input:t}){this.fileSystem=e,this.input=t;}async execute({path:e,content:t,...n}){let r=n.overwrite===true,i=this.fileSystem.normalizeSeparators(e);if(!r&&await this.fileSystem.exists(i)&&(r=this.input===void 0?false:await this.input.confirm({message:`Path \`${i}\` already exists. Do you want to overwrite it?`,default:false}),!r))throw new h("Failed to write file because the specified path already exists.",{reason:"precondition",details:[`File: ${i}`]});r&&await this.fileSystem.isDirectory(i)&&await this.fileSystem.delete(i,{recursive:true});try{await this.fileSystem.writeTextFile(i,t,{overwrite:r});}catch(o){throw h.fromCause(o)}}};var Bm=z.strictObject({path:z.string().min(1),content:z.string(),overwrite:z.boolean().optional()}),aa=class extends I{constructor(){super(Bm);}};var sa=class{constructor(e){this.currentVersion=e.currentVersion,this.packageManager=e.packageManager,this.configurationProvider=e.configurationProvider,this.input=e.input,this.output=e.output,this.checkTimeout=e.checkTimeout,this.checkFrequency=e.checkFrequency;}async checkForUpdates(){let e=await this.configurationProvider.get();if(!this.isCheckEnabled(e))return;let t=await this.getLatestVersion();if(t===null||(await this.configurationProvider.save({...e,lastUpdateCheck:Date.now()}),nm.gte(this.currentVersion,t))||(this.output.announce({semantics:"info",title:"New version",message:`Update your CLI from ${this.currentVersion} \u2192 \`${t}\``}),!(await this.input?.confirm({message:"Would you like to update now?",default:true})??false)))return;let r=this.output.notify("Updating the CLI");try{await this.packageManager.updatePackage("croct",{global:hc,logger:new oe({status:"Updating the CLI",notifier:r})});}catch{let o=await this.packageManager.getPackageUpdateCommand("croct",{global:hc}),s=`${o.name} ${o.arguments?.join(" ")}`;r.alert("Failed to update the CLI automatically"),this.output.log(`Please run the command:
|
|
1850
|
-
\`${s}\``);return}r.confirm("CLI updated successfully!"),this.output.inform("The new version will take effect the next time you run a command");}isCheckEnabled(e){return e.lastUpdateCheck===void 0||Date.now()-e.lastUpdateCheck>this.checkFrequency}getLatestVersion(){let e=new AbortController;return setTimeout(()=>e.abort(),this.checkTimeout),fetch("https://registry.npmjs.org/croct/latest",{signal:e.signal}).then(t=>t.json()).then(t=>t.version).catch(()=>null)}};var pa=class{constructor({fileSystem:e}){this.fileSystem=e;}async execute({path:e,recursive:t=false}){let n=this.fileSystem.normalizeSeparators(e);if(await this.fileSystem.exists(n)){if(!t&&await this.fileSystem.isDirectory(n)&&!await this.fileSystem.isEmptyDirectory(n))throw new h("Cannot delete non-empty directory when `recursive` is false.",{reason:"precondition",details:[`Path: ${n}`]});try{await this.fileSystem.delete(n,{recursive:t});}catch(r){throw h.fromCause(r)}}}};var Ym=z.strictObject({path:z.string().min(1),recursive:z.boolean().optional()}),ca=class extends I{constructor(){super(Ym);}};var la=class{constructor({projectDirectory:e,fileSystem:t,codemod:n,scanFilter:r}){this.projectDirectory=e,this.fileSystem=t,this.codemod=n,this.scanFilter=r;}async execute(e,t){let{output:n}=t,r=n?.notify("Resolving imports");try{await this.resolveImports(e.path);}finally{r?.stop();}}async resolveImports(e){let t=false,n=xt.fromPattern(e);for await(let r of this.fileSystem.list(this.projectDirectory.get(),this.scanFilter))await n.test(r.name)&&r.type==="file"&&(t=true,await this.codemod.apply(await this.fileSystem.getRealPath(r.name)));if(!t)throw new d("No matching files found for resolving imports.",{reason:"unexpected_result",details:[`Pattern: ${e}`]})}};var ed=z.strictObject({path:z.string().min(1)}),ua=class extends I{constructor(){super(ed);}};var ma=class{constructor({configurationManager:e,applicationApi:t}){this.configurationManager=e,this.api=t;}async execute(e,t){let{output:n}=t,r=await this.configurationManager.load(),i=e.environment==="production"?r.applications.production:r.applications.development;if(i===void 0)throw new h("The project has no application configured for the selected environment.",{reason:"precondition"});let o=n?.notify("Creating API key"),s;try{s=await this.api.createApiKey({organizationSlug:r.organization,workspaceSlug:r.workspace,applicationSlug:i,name:e.keyName,permissions:e.permissions});}catch(p){throw h.fromCause(p)}finally{o?.stop();}t.set(e.result,s.secret);}};var td=z.strictObject({keyName:z.string().min(1),environment:z.enum(["development","production"]),permissions:z.array(z.enum(ae.all().flatMap(a=>[a.toUpperCase(),a.toLowerCase()])).transform(ae.fromValue)).min(1),result:z.string().min(1)}),da=class extends I{constructor(){super(td);}};var fa=class a{constructor(e){this.instances=new Map;this.configuration=e,this.initialDirectory=e.directories.current??e.process.getCurrentDirectory(),this.workingDirectory=new ho(this.initialDirectory);}static{this.READ_ONLY_COMMANDS=new Set([bn,Zt,Jt,bt,It,Ht,Gt,Xt,jt]);}static fromDefaults(e){let t=od("com.croct.cli"),n=new Po;return new a({program:e.program??(()=>{throw new d("CLI is running in standalone mode.")}),process:e.process??n,quiet:e.quiet??false,debug:e.debug??false,stateless:e.stateless??es.isCI,interactive:e.interactive??!es.isCI,version:e.version??"0.0.0",apiKey:e.apiKey,token:e.token,dnd:e.dnd??es.isCI,adminTokenDuration:e.adminTokenDuration??7*LocalTime.SECONDS_PER_DAY,apiKeyTokenDuration:e.apiKeyTokenDuration??30*LocalTime.SECONDS_PER_MINUTE,cliTokenDuration:e.cliTokenDuration??90*LocalTime.SECONDS_PER_DAY,cliTokenFreshPeriod:e.cliTokenFreshPeriod??15*LocalTime.SECONDS_PER_DAY,cliTokenIssuer:e.cliTokenIssuer??"croct.com",deepLinkProtocol:e.deepLinkProtocol??"croct",templateRegistryUrl:e.templateRegistryUrl??new URL("github://croct-tech/templates/templates/registry.json5"),adminUrl:e.adminUrl??new URL("https://app.croct.com"),adminTokenParameter:e.adminTokenParameter??"accessToken",adminGraphqlEndpoint:e?.adminGraphqlEndpoint??new URL("https://app.croct.com/graphql"),directories:{current:e.directories?.current??n.getCurrentDirectory(),config:e.directories?.config??t.config(),cache:e.directories?.cache??t.cache(),data:e.directories?.data??t.data(),home:e.directories?.home??homedir()},verificationLinkDestination:{accountActivation:e.verificationLinkDestination?.accountActivation??"./cli",passwordReset:e.verificationLinkDestination?.passwordReset??"./cli"},emailSubject:{passwordReset:e.emailSubject?.passwordReset??"Forgot password",accountActivation:e.emailSubject?.accountActivation??"Welcome to Croct"}})}welcome(e){let t=!this.configuration.interactive||this.configuration.dnd;return this.execute(new bn({cliVersion:this.configuration.version,autoUpdater:new sa({currentVersion:this.configuration.version,input:this.getInput(),configurationProvider:this.getCliConfigurationProvider(),packageManager:this.getNodePackageManager(),output:this.getOutput(),checkFrequency:LocalTime.MILLIS_PER_SECOND*LocalTime.SECONDS_PER_HOUR*6,checkTimeout:500}),configurationProvider:this.getCliConfigurationProvider(),deepLinkInstaller:n=>this.deepLink({operation:n?"optionally-update":"optionally-enable"})}),{skipDeepLinkCheck:t||e.skipDeepLinkCheck===true,skipUpdateCheck:t||e.skipUpdateCheck===true})}deepLink(e){return this.execute(new jo({packageManager:this.getNodePackageManager(),protocolRegistryProvider:this.getProtocolRegistryProvider(),configurationProvider:this.getCliConfigurationProvider(),cliPackage:"croct@latest",protocolHandler:{id:"com.croct.cli",name:"croct-cli",protocol:this.configuration.deepLinkProtocol},io:{input:this.getInput(),output:this.getOutput()}}),e)}open(e){return this.execute(new ro({program:this.configuration.program,protocol:this.configuration.deepLinkProtocol,configurationProvider:this.getCliConfigurationProvider(),workingDirectory:new So(this.configuration.process),fileSystem:this.getFileSystem(),io:{input:this.getInput(),output:this.getOutput()}}),e)}init(e){let{process:t}=this.configuration;return this.execute(new Nn({sdkProvider:this.getSdkProvider(),platformProvider:this.getPlatformProvider(),configurationManager:this.getConfigurationManager(),skipConfirmation:new Bi(new Sn(new Ji(new gn({fileSystem:this.getFileSystem(),files:[".git"]})))),api:{user:this.getUserApi(),organization:this.getOrganizationApi(),workspace:this.getWorkspaceApi()},form:{organization:new _n({input:this.getFormInput(),output:this.getOutput(),userApi:this.getUserApi()}),workspace:new jn({input:this.getFormInput(),output:this.getOutput(),organizationApi:this.getOrganizationApi()}),application:new Wn({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),slot:new _e({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()})},io:{input:this.getInput(),output:this.getOutput()}}),{...e,organization:e.organization??t.getEnvValue("CROCT_ORGANIZATION")??void 0,workspace:e.workspace??t.getEnvValue("CROCT_WORKSPACE")??void 0,devApplication:e.devApplication??t.getEnvValue("CROCT_DEV_APPLICATION")??void 0,prodApplication:e.prodApplication??t.getEnvValue("CROCT_PROD_APPLICATION")??void 0,skipApiKeySetup:e.skipApiKeySetup??t.getEnvValue("CROCT_SKIP_API_KEY_SETUP")!==null})}install(e){let t=!this.configuration.interactive||this.configuration.dnd;return this.execute(new Zt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),io:{input:this.getInput(),output:this.getOutput()}}),{clean:e.clean??false,partialConfiguration:e.partialConfiguration??t})}upgrade(e){return this.execute(new Jt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),form:{slotForm:new _e({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),componentForm:new He({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()})},io:{input:this.getInput(),output:this.getOutput()}}),e)}addSlot(e){return this.execute(new bt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),workspaceApi:this.getWorkspaceApi(),slotForm:new _e({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}removeSlot(e){return this.execute(new Ht({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),slotForm:new _e({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}addComponent(e){return this.execute(new It({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new He({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}removeComponent(e){return this.execute(new Gt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new He({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}login(e){return this.execute(new zn({authenticator:this.getAuthenticator()}),e)}logout(){return this.execute(new jt({authenticator:this.getAuthenticator(),output:this.getOutput()}),{})}admin(e){return this.execute(new Hn({output:this.getOutput(),pageForm:new er({input:this.getFormInput()}),configurationManager:this.getConfigurationManager(),userApi:this.getUserApi(),adminUrl:this.configuration.adminUrl,adminTokenParameter:this.configuration.adminTokenParameter,adminTokenDuration:this.configuration.adminTokenDuration}),e)}createTemplate(e){return this.execute(new Xt({configurationManager:this.getConfigurationManager(),fileSystem:this.getFileSystem(),templateForm:new fr({input:this.getFormInput(),form:{component:new He({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),slot:new _e({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),experience:new yr({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),audience:new hr({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()})}}),io:{input:this.getInput(),output:this.getOutput()}}),e)}useTemplate(e){return this.execute(this.getUseTemplateCommand(),e)}async getTemplateOptions(e){let t=this.getUseTemplateCommand(),r=this.getOutput().notify("Loading template options");try{return await t.getOptions(e)}finally{r.stop();}}getUseTemplateCommand(){return new Sr({templateProvider:new Pt({provider:new tn(this.getTemplateProvider()),validator:new pn}),fileSystem:this.getFileSystem(),action:this.getImportAction(),io:{input:this.getInput(),output:this.getOutput()}})}createApiKey(e){return this.execute(new fo({fileSystem:this.getFileSystem(),configurationManager:this.getConfigurationManager(),api:{user:this.getUserApi(),workspace:this.getWorkspaceApi(),application:this.getApplicationApi()},io:{input:this.getFormInput(),output:this.getOutput()}}),e)}getFormInput(e){return this.getInput()??this.getNonInteractiveInput(e)}getNonInteractiveInput(e){return new hn(new nr(e??{message:"Input is not available in non-interactive mode."}))}getInput(){if(this.configuration.interactive)return this.share(this.getInput,()=>{let e=this.getOutput(),t=new Pn({input:this.configuration.process.getStandardInput(),output:this.configuration.process.getStandardOutput(),onAbort:()=>e.exit(),onInteractionStart:()=>e.suspend(),onInteractionEnd:()=>e.resume()});return this.configuration.dnd?new hn(t):t})}getNonInteractiveOutput(e=false){let{configuration:t}=this,n=new _t({output:t.process.getStandardOutput(),formatter:this.getLogFormatter(),interactive:false,quiet:e,onExit:()=>t.process.exit(),linkOpener:new xn(()=>new wn(n))});return t.process.on("exit",()=>n.stop()),n}getHierarchicalLogger(){return this.share(this.getHierarchicalLogger,()=>new Do(this.getLogger()))}getLogger(){return this.share(this.getLogger,()=>{let e=new Mo(this.getOutput());return this.configuration.debug?e:new FilteredLogger(e,LogLevel.WARNING)})}getOutput(){return this.share(this.getOutput,()=>{let{configuration:e}=this,t=new _t({output:e.process.getStandardOutput(),formatter:this.getLogFormatter(),interactive:this.configuration.interactive,quiet:this.configuration.quiet,onExit:()=>e.process.exit(),linkOpener:new xn(()=>{let n=new wn(t);return this.configuration.dnd?n:new Go(n)})});return e.process.on("exit",()=>t.stop()),t})}getLogFormatter(){return this.share(this.getLogFormatter,()=>new xo)}getTemplateProvider(){return this.share(this.getTemplateProvider,()=>{let e=n=>new Me({providers:["template.json5","template.json"].map(r=>new st({dataProvider:n,registryProvider:new Ot([{pattern:/^(https:\/\/(?:www\.)?github.com\/[^/]+\/[^/]+)\/?$/,destination:`$1/blob/main/${r}`},{pattern:/^(.+?:\/*[^/]+(\/+[^/.]+|\/[^/]+(?=\/))*)\/*$/,destination:`$1/${r}`}])}))}),t=this.traceProvider({provider:this.getHttpProvider()});return this.traceProvider({label:"TemplateProvider",provider:new rn({resourceCache:new AutoSaveCache(new InMemoryCache),errorCache:new InMemoryCache,provider:new Me({providers:[new st({dataProvider:this.traceProvider({label:"ResourceProvider",provider:e(new pt(new Me({providers:[this.traceProvider({provider:this.createGitHubProvider(t)}),this.traceProvider({provider:new Yt(t)})]})))}),registryProvider:this.traceProvider({label:"NpmRegistryProvider",provider:new Ao(new Pt({provider:Eo.json(this.traceProvider({provider:this.getHttpProvider()})),validator:new Oo}))})}),e(new pt(this.getFileProvider()))]})})})})}getFileProvider(){return this.share(this.getFileProvider,()=>{let e=this.traceProvider({provider:this.getHttpProvider()}),t=this.traceProvider({provider:new Mr(this.getFileSystem(),this.getScanFilter())}),n=new Me({providers:[t,this.traceProvider({provider:this.createGitHubProvider(e)}),this.traceProvider({provider:new Yt(e)})]});return this.traceProvider({label:"FileProvider",provider:new Me({providers:[t,this.traceProvider({provider:new st({baseUrl:new URL("./",this.configuration.templateRegistryUrl),dataProvider:this.traceProvider({label:"ResourceProvider",provider:n}),registryProvider:new di({url:this.configuration.templateRegistryUrl,provider:this.traceProvider({label:"GlobalRegistryProvider",provider:new rn({errorCache:new InMemoryCache,resourceCache:new AutoSaveCache(new InMemoryCache),provider:new Pt({provider:new tn(new pt(n)),validator:new jr})})})})})})]})})})}createGitHubProvider(e){let t=Date.now();return new Nr({cache:new AutoSaveCache(new InMemoryCache),provider:new Me({providers:[new Me({providers:[new st({dataProvider:e,registryProvider:new Ot([{pattern:/^https:\/\/raw\.github\.com\/croct-tech\/templates\/(HEAD|master)\/templates\/(.+)$/i,destination:`https://cdn.croct.io/templates/$2?c=${t}`},{pattern:/^https:\/\/api\.github\.com\/repos\/croct-tech\/templates\/git\/trees\/(HEAD|master)\?recursive=true/i,destination:`https://cdn.croct.io/templates/git-tree.json?c=${t}`}])}),e]}),e]})})}traceProvider({provider:e,label:t}){return new To({label:t,provider:e,logger:this.getHierarchicalLogger()})}getImportAction(){return this.share(this.getImportAction,()=>{let e=this.getFileSystem(),t=new Map,n={run:new D({action:new Ge(new we(()=>new wi(n))),validator:new Pi}),try:new D({action:new Ge(new we(()=>new Cr(n.run))),validator:new Kr}),test:new D({action:new Ge(new we(()=>new oi(n.run))),validator:new si}),repeat:new D({action:new Ge(new we(()=>new Xi(n.run))),validator:new Yi}),print:new D({action:new pi,validator:new li}),fail:new D({action:new ui,validator:new mi}),define:new D({action:new Ei,validator:new Ai}),prompt:new D({action:new bi,validator:new Ii}),"change-directory":new D({action:new Mi({fileSystem:e,rootDirectory:this.initialDirectory,currentDirectory:this.workingDirectory}),validator:new Di}),"open-link":new D({action:new Ci,validator:new ki}),"start-server":new D({action:new vi({serverProvider:this.getServerProvider(),serverFactory:this.getServerFactory(),packageManager:this.getPackageManager(),serverMap:t}),validator:new xi}),"stop-server":new D({action:new Ko({serverMap:t}),validator:new Oi}),"check-dependency":new D({action:new Dr({packageManager:this.getPackageManager()}),validator:new Hr}),download:new D({action:new br({fileSystem:e,provider:this.getFileProvider(),codemod:new Mt({codemods:{"**/*.{js,jsx,ts,tsx}":new Nt(this.getNodeImportResolverCodemod(),new Mt({codemods:{"**/*.{js,jsx}":new Nt(new Te({fileSystem:e,codemod:new Oe({codemod:new Uo,languages:["typescript","jsx"]})}))}}),new Re(this.getJavaScriptFormatter()))}})}),validator:new Gr}),"resolve-import":new D({action:new la({projectDirectory:this.workingDirectory,fileSystem:e,scanFilter:this.getScanFilter(),codemod:new Mt({codemods:{"**/*.{js,jsx,ts,tsx}":new Nt(this.getNodeImportResolverCodemod(),new Re(this.getJavaScriptFormatter()))}})}),validator:new ua}),install:new D({action:new Zo({packageManager:this.getPackageManager()}),validator:new Jo}),"add-dependency":new D({action:new Ir({packageManager:this.getPackageManager()}),validator:new Jr}),"execute-package":new D({action:new Ni({processObserver:this.configuration.process,packageManager:this.getPackageManager(),packageManagerProvider:this.getPackageManagerRegistry(),workingDirectory:this.workingDirectory,commandExecutor:this.getAsynchronousCommandExecutor(),commandTimeout:3*60*1e3,sourceChecker:{test:r=>r.protocol==="file:"||`${r}`.startsWith("https://github.com/croct-tech")}}),validator:new zi}),"locate-path":new D({action:new vr({projectDirectory:this.workingDirectory,fileSystem:e,scanFilter:this.getScanFilter()}),validator:new Qr}),"move-path":new D({action:new Qo({fileSystem:e}),validator:new Yo}),"delete-path":new D({action:new pa({fileSystem:e}),validator:new ca}),"read-file":new D({action:new Bo({fileSystem:e}),validator:new ta}),"write-file":new D({action:new ia({fileSystem:e,input:this.getInput()}),validator:new aa}),"replace-file-content":new D({action:new xr({fileSystem:e}),validator:new Br}),"create-directory":new D({action:new na({fileSystem:e}),validator:new ra}),"integrate-croct":new D({action:new Co({callback:async()=>{if(!await this.getConfigurationManager().isInitialized("full"))return this.init({})}}),validator:new ko}),"add-slot":new D({action:new wr({installer:(r,i)=>{let o=this.getNonInteractiveOutput(true);return this.execute(new bt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),workspaceApi:this.getWorkspaceApi(),slotForm:new _e({input:this.getNonInteractiveInput(),output:o,workspaceApi:this.getWorkspaceApi()}),io:{output:o}}),{slots:r,example:i})}}),validator:new Yr}),"add-component":new D({action:new Pr({installer:r=>{let i=this.getNonInteractiveOutput(true);return this.execute(new It({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new He({input:this.getNonInteractiveInput(),output:i,workspaceApi:this.getWorkspaceApi()}),io:{output:i}}),{components:r})}}),validator:new ei}),"create-api-key":new D({action:new ma({applicationApi:this.getApplicationApi(),configurationManager:this.getConfigurationManager()}),validator:new da}),"create-resource":new D({action:new Er({configurationManager:this.getConfigurationManager(),matcher:new Rr({workspaceApi:this.getWorkspaceApi()}),api:{user:this.getUserApi(),workspace:this.getWorkspaceApi(),organization:this.getOrganizationApi()},mappingForm:new Or({input:this.getFormInput({message:"Some resource IDs are in use and interactive mode is required to assign new ones.",suggestions:["Retry in interactive mode"]}),workspaceApi:this.getWorkspaceApi()})}),validator:new ti}),"format-code":new D({action:new ri({formatter:this.getCodeFormatter()}),validator:new ii}),import:new D({action:new Ge(new we(()=>new Vr({runner:n.run,templateProvider:new qr({evaluator:new Wr({functions:Ba}),validator:new pn,templateProvider:this.getTemplateProvider(),fileProvider:new pt(this.getFileProvider())}),variables:this.getActionVariables()}))),validator:new ni})};return n.import})}getActionVariables(){let e=t=>new URL(t,this.configuration.adminUrl).toString();return {packageManager:J.transient(()=>({name:this.getPackageManager().getName()})),project:{features:J.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load(),{features:r}=await this.getWorkspaceApi().getFeatures({organizationSlug:t,workspaceSlug:n})??{};return r??{}}),quotas:J.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load(),{quotas:r}=await this.getWorkspaceApi().getFeatures({organizationSlug:t,workspaceSlug:n})??{};return r??{}}),organization:J.transient(async()=>{let{organization:t}=await this.getConfigurationManager().load();return {slug:t,url:e(`organizations/${t}`)}}),workspace:J.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load();return {slug:n,url:e(`organizations/${t}/workspaces/${n}`)}}),application:J.transient(async()=>{let{organization:t,workspace:n,applications:r}=await this.getConfigurationManager().load(),i=`organizations/${t}/workspaces/${n}/applications/`,o=r.production;return {development:{slug:r.development,url:e(i+r.development),publicId:J.transient(async()=>{let p=await this.getWorkspaceApi().getApplication({organizationSlug:t,workspaceSlug:n,applicationSlug:r.development});if(p===null)throw new N("Development application not found.",{reason:"not_found"});return p.publicId})},production:{slug:r.production,url:e(i+r.production),publicId:o===void 0?o:J.transient(async()=>{let p=await this.getWorkspaceApi().getApplication({organizationSlug:t,workspaceSlug:n,applicationSlug:o});if(p===null)throw new N("Production application not found.",{reason:"not_found"});return p.publicId})}}}),path:J.transient(async()=>{let t=this.getSdk(),n=await this.getConfigurationManager().load();return t.getPaths(n)}),platform:J.transient(async()=>await this.getPlatformProvider().get()??"unknown"),server:J.transient(async()=>{let n=await this.getServerProvider().get();if(n===null)return null;try{let r=await n.getStatus();if(r.running)return {running:!0,url:r.url.toString()}}catch{}return {running:false}})}}}getHttpProvider(){return this.share(this.getHttpProvider,()=>new Tr({retry:{maxAttempts:3,delay:1e3}}))}getAuthenticator(){return this.share(this.getAuthenticator,()=>{if(this.configuration.apiKey!==void 0)return new yo({apiKey:this.configuration.apiKey,clock:this.getClock(),tokenDuration:this.configuration.apiKeyTokenDuration});if(this.configuration.token!==void 0)return new Ho({token:this.configuration.token});let e=this.getFormInput(),t=new Un({input:e,output:this.getOutput(),userApi:this.getUserApi(true),form:{signIn:new qn({input:e,output:this.getOutput(),userApi:this.getUserApi(true),listener:this.getTokenListener(),tokenDuration:this.configuration.cliTokenDuration,emailLinkGenerator:{recovery:this.createEmailLinkGenerator(this.configuration.emailSubject.passwordReset),verification:this.createEmailLinkGenerator(this.configuration.emailSubject.accountActivation)},verificationLinkDestination:{accountActivation:this.configuration.verificationLinkDestination.accountActivation,passwordReset:this.configuration.verificationLinkDestination.passwordReset}}),signUp:new Kn({input:e,output:this.getOutput(),userApi:this.getUserApi(true),listener:this.getTokenListener(),emailLinkGenerator:this.createEmailLinkGenerator(this.configuration.emailSubject.accountActivation),verificationLinkDestination:this.configuration.verificationLinkDestination.accountActivation})}}),n=this.getUserApi(true),r=new bo({cacheKey:"token",cacheProvider:new Io({clock:this.getClock(),clockSkewTolerance:5,tokenFreshPeriod:this.configuration.cliTokenFreshPeriod,tokenIssuer:()=>n.issueToken({duration:this.configuration.cliTokenDuration}),cacheProvider:this.selectCacheProvider(()=>new nn({fileSystem:this.getFileSystem(),directory:this.configuration.directories.config,useKeyAsFileName:true}))}),authenticator:new rr({default:this.configuration.interactive?t:new tr({authenticator:t,instruction:{message:"Authentication required.",suggestions:["Run `login` to authenticate"],reason:"precondition"}}),credentials:t})});return this.configuration.interactive?new uo({authenticator:r,invitationForm:new lo({output:this.getOutput(),input:e,userApi:this.getUserApi(true)})}):r})}getSdk(){return this.share(this.getSdk,()=>{let e=new Tt(this.getSdkProvider(),new we(()=>{throw new j("No suitable SDK detected.",{reason:"not_supported",suggestions:["Make sure you are running the command in the project root directory."]})}));return new Zi(e)})}getSdkProvider(){return this.share(this.getSdkProvider,()=>{let e=this.getJavaScriptFormatter(),t=this.getFileSystem(),n=this.getNodeImportResolver(),r={projectDirectory:this.workingDirectory,packageManager:this.getNodePackageManager(),fileSystem:t,formatter:e,workspaceApi:this.getWorkspaceApi(),tsConfigLoader:this.getTsConfigLoader()},i=Symbol("unknown");return new Et({discriminator:async()=>await this.getPlatformProvider().get()??i,mapping:{javascript:()=>new On({...r,bundlers:["vite","parcel","tsup","rollup"]}),react:()=>new Rn({...r,importResolver:n,codemod:{provider:new Re(e,new Te({fileSystem:this.getFileSystem(),codemod:new Oe({languages:["typescript","jsx"],codemod:new nt({fallbackToNamedExports:true,wrapper:{module:"@croct/plug-react",component:"CroctProvider"},targets:{variable:"children"}})})}))},bundlers:[{package:"react-scripts",prefix:"process.env.REACT_APP_"},{package:"vite",prefix:"import.meta.env.VITE_"},{package:"parcel",prefix:"process.env."}]}),nextjs:()=>{let o={appId:{type:"reference",path:["process","env","NEXT_PUBLIC_CROCT_APP_ID"]},debug:{type:"comparison",operator:"===",left:{type:"reference",path:["process","env","NEXT_PUBLIC_CROCT_DEBUG"]},right:{type:"literal",value:"true"}}};return new Mn({...r,userApi:this.getUserApi(),applicationApi:this.getApplicationApi(),importResolver:n,codemod:{middleware:new Re(e,new Te({fileSystem:this.getFileSystem(),codemod:new Oe({languages:["typescript","jsx"],codemod:new Jn({matcherPattern:"/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",import:{module:"@croct/plug-next/middleware",middlewareName:"middleware",middlewareFactoryName:"withCroct"}})})})),appRouterProvider:new Re(e,new Te({fileSystem:this.getFileSystem(),codemod:new Oe({languages:["typescript","jsx"],codemod:new nt({fallbackToNamedExports:false,fallbackCodemod:new Qn({provider:{component:"CroctProvider",module:"@croct/plug-next/CroctProvider"}}),wrapper:{module:"@croct/plug-next/CroctProvider",component:"CroctProvider"},targets:{variable:"children"}})})})),pageRouterProvider:new Re(e,new Te({fileSystem:this.getFileSystem(),codemod:new Oe({languages:["typescript","jsx"],codemod:new nt({fallbackToNamedExports:false,fallbackCodemod:new Kt({provider:{component:"CroctProvider",module:"@croct/plug-next/CroctProvider"}}),wrapper:{module:"@croct/plug-next/CroctProvider",component:"CroctProvider"},targets:{component:"Component"}})})})),fallbackProvider:new Re(e,new Te({fileSystem:this.getFileSystem(),codemod:new Oe({languages:["typescript","jsx"],codemod:new nt({fallbackToNamedExports:false,fallbackCodemod:new Kt({provider:{component:"CroctProvider",module:"@croct/plug-react",props:o}}),wrapper:{module:"@croct/plug-react",component:"CroctProvider",props:o},targets:{component:"Component"}})})}))}})},[i]:()=>null}})})}getCodeFormatter(){return this.share(this.getCodeFormatter,()=>{let e=Symbol("unknown");return new Gi(new Et({discriminator:async()=>await this.getPlatformProvider().get()??e,mapping:{javascript:()=>this.getJavaScriptFormatter(),react:()=>this.getJavaScriptFormatter(),nextjs:()=>this.getJavaScriptFormatter(),[e]:()=>{throw new j("No code formatter detected.",{reason:"not_supported",suggestions:["Make sure you are running the command in the project root directory."]})}}}))})}share(e,t){let n=this.instances.get(e);if(n===void 0){let r=t();return this.instances.set(e,r),r}return n}getPackageManagerRegistry(){return this.share(this.getPackageManagerRegistry,()=>new Vi(new Map(Object.entries(this.getPackageManagers()))))}getPackageManagers(){return this.getNodePackageManagers()}getPackageManager(){return this.share(this.getPackageManager,()=>new dn(new Tt(this.getNodePackageManagerProvider(),new we(()=>{throw new j("No package manager detected.",{reason:"not_supported",suggestions:["Make sure you are running the command in the project root directory.","Initialize your project and retry the command."]})}))))}getNodePackageManager(){return this.share(this.getNodePackageManager,()=>{let e=this.getNodePackageManagers();return new dn(new Tt(this.getNodePackageManagerProvider(),new Ot(e.npm)))})}getNodePackageManagerProvider(){return this.share(this.getNodePackageManagerProvider,()=>{let e=this.getNodePackageManagers(),t=this.getFileSystem(),n={npm:["package-lock.json"],yarn:["yarn.lock"],bun:["bun.lock","bun.lockb"],pnpm:["pnpm-lock.yaml"]};return new yn(new co(new lt({candidates:Object.entries(e).map(([r,i])=>({value:i,condition:new po({process:this.configuration.process,variable:"npm_config_user_agent",value:new RegExp(`^${r}`)})}))}),new lt({candidates:Object.entries(e).map(([r,i])=>({value:i,condition:new Sn(new so({packageManager:r,fileSystem:t,projectDirectory:this.workingDirectory}),new gn({fileSystem:t,files:n[r]}))}))}),new lt({candidates:Object.entries(e).map(([r,i])=>({value:i,condition:new qo({executableLocator:this.getExecutableLocator(),command:r})}))})),this.workingDirectory)})}getNodePackageManagers(){return this.share(this.getNodePackageManagers,()=>{let e=this.getFileSystem(),t={projectDirectory:this.workingDirectory,fileSystem:e,commandExecutor:this.getAsynchronousCommandExecutor(),executableLocator:this.getExecutableLocator()},n=new en,r={fileSystem:e,projectDirectory:this.workingDirectory,packageValidator:n};return {npm:new Je({...r,agent:new $i(t)}),yarn:new Je({...r,agent:new Fi(t)}),bun:new Je({...r,agent:new Li(t)}),pnpm:new Je({...r,agent:new _i(t)})}})}getServerProvider(){return this.share(this.getServerProvider,()=>{let e=Symbol("unknown");return new Et({discriminator:async()=>await this.getPlatformProvider().get()??e,mapping:{javascript:()=>this.getNodeServerProvider().get(),react:()=>this.getNodeServerProvider().get(),nextjs:()=>this.getNodeServerProvider().get(),[e]:()=>null}})})}getNodeServerProvider(){return this.share(this.getNodeServerProvider,()=>new gi({packageManager:this.getNodePackageManager(),factory:this.getServerFactory(),parsers:[new fi,new yi,new hi,new Si]}))}getServerFactory(){return this.share(this.getServerFactory,()=>new Ti({commandExecutor:this.getAsynchronousCommandExecutor(),workingDirectory:this.workingDirectory,startupTimeout:60*1e3,startupCheckDelay:1.5*1e3,lookupMaxPorts:30,lookupTimeout:2*1e3,processObserver:this.configuration.process}))}getJavaScriptFormatter(){return this.share(this.getJavaScriptFormatter,()=>new Xn({commandExecutor:this.getAsynchronousCommandExecutor(),workingDirectory:this.workingDirectory,packageManager:this.getNodePackageManager(),fileSystem:this.getFileSystem(),timeout:1e4,tools:[{package:"eslint",bin:"eslint",args:e=>["--fix",...e]},{package:"prettier",args:e=>["--write",...e]},{package:"@biomejs/biome",bin:"biome",args:e=>["format","--write",...e]}]}))}getNodeImportResolver(){return this.share(this.getNodeImportResolver,()=>new ji({fileSystem:this.getFileSystem(),tsConfigLoader:this.getTsConfigLoader(),projectDirectory:this.workingDirectory}))}getTsConfigLoader(){return this.share(this.getTsConfigLoader,()=>new Wo({fileSystem:this.getFileSystem(),tsconfigValidator:new Wi}))}getAsynchronousCommandExecutor(){return this.share(this.getAsynchronousCommandExecutor,()=>new Vo({executableLocator:this.getExecutableLocator(),commandExecutor:this.getCommandExecutor()}))}getSynchronousCommandExecutor(){return this.getCommandExecutor()}getCommandExecutor(){return this.share(this.getCommandExecutor,()=>new Hi({currentDirectory:this.workingDirectory,windows:this.configuration.process.getPlatform()==="win32"}))}getExecutableLocator(){return this.share(this.getExecutableLocator,()=>{let{process:e}=this.configuration;return new ao({fileSystem:this.getFileSystem(),cache:new AutoSaveCache(new InMemoryCache),executablePaths:e.getEnvList("PATH")??[],executableExtensions:e.getEnvList("PATHEXT")??[]})})}getPlatformProvider(){return this.share(this.getPlatformProvider,()=>{let e=new Je({projectDirectory:this.workingDirectory,packageValidator:new en,fileSystem:this.getFileSystem(),agent:new Ui});return new yn(new lt({candidates:[{value:"nextjs",condition:new fn({packageManager:e,dependencies:["next"]})},{value:"react",condition:new fn({packageManager:e,dependencies:["react"]})},{value:"javascript",condition:new qi({packageManager:e})}]}),this.workingDirectory)})}getConfigurationManager(){return this.share(this.getConfigurationManager,()=>{let e=new $n({fileSystem:this.getFileSystem(),fullValidator:new Fr,partialValidator:new Lr,projectDirectory:this.workingDirectory});return new oo({workingDirectory:this.workingDirectory,configurationProvider:this.getCliConfigurationProvider(),manager:new kr(this.configuration.interactive&&!this.isReadOnlyMode()?new Yn({manager:e,initializer:{initialize:()=>this.init({})}}):e)})})}getNodeImportResolverCodemod(){return this.share(this.getNodeImportResolverCodemod,()=>{let e=this.getFileSystem(),t=this.getScanFilter();return new No({fileSystem:e,rootPath:this.workingDirectory,filter:(n,r)=>r<=10&&t(n,r),importResolver:this.getNodeImportResolver(),importCodemod:new Te({fileSystem:e,codemod:new Oe({languages:["typescript","jsx"],codemod:new $o})}),exportMatcher:{test:(n,{names:r})=>r.length===0?true:uc(n).some(i=>r.includes(i))}})})}getScanFilter(){return this.share(this.getScanFilter,()=>{let e=new Qi({fileSystem:this.getFileSystem(),workingDirectory:this.workingDirectory});return async t=>!await e.test(t)})}getUserApi(e=false){return e?new Ut(this.getGraphqlClient(true)):this.share(this.getUserApi,()=>new Ut(this.getGraphqlClient()))}getOrganizationApi(){return this.share(this.getOrganizationApi,()=>new Fn(this.getGraphqlClient(),this.getHierarchyResolver()))}getWorkspaceApi(){return this.share(this.getWorkspaceApi,()=>new Ln(this.getGraphqlClient(),this.getHierarchyResolver()))}getApplicationApi(){return this.share(this.getApplicationApi,()=>new Vn(this.getGraphqlClient(),this.getHierarchyResolver()))}getHierarchyResolver(){return this.share(this.getHierarchyResolver,()=>new Fo(this.getGraphqlClient(),new InMemoryCache))}getGraphqlClient(e=false){return e?new Wt({endpoint:this.configuration.adminGraphqlEndpoint,tokenProvider:{getToken:()=>this.getAuthenticator().getToken()}}):this.share(this.getGraphqlClient,()=>{let t=this.getAuthenticator();return new Wt({endpoint:this.configuration.adminGraphqlEndpoint,tokenProvider:{getToken:async()=>await t.getToken()??t.login({method:"default"})}})})}getTokenListener(){return this.share(this.getTokenListener,()=>{let{configuration:e}=this;return new or({platform:e.process.getPlatform(),commandExecutor:this.getSynchronousCommandExecutor(),timeout:2e3,listener:new vo({api:this.getUserApi(true),pollingInterval:1e3})})})}getFileSystem(){return this.share(this.getFileSystem,()=>new ir({workingDirectory:this.workingDirectory,defaultEncoding:"utf-8"}))}createEmailLinkGenerator(e){let t=this.getEmailLinkGenerator(),n=this.getClock();return r=>t.generate({recipient:r,sender:"croct.com",subject:e,timestamp:Instant.now(n).getSeconds()})}getEmailLinkGenerator(){return this.share(this.getEmailLinkGenerator,()=>new ar({detector:new sr(new pr,new cr),templates:{google:new lr,icloud:new ur,microsoft:new mr,proton:new dr,yahoo:new gr}}))}getClock(){return SystemClock.UTC}getProtocolRegistryProvider(){return this.share(this.getProtocolRegistryProvider,()=>new we(()=>{let e=this.getFileSystem(),{process:t}=this.configuration;switch(t.getPlatform()){case "darwin":{let n=e.joinPaths(this.configuration.directories.data,"apps");return new Lo({output:this.getOutput(),macOsRegistry:new eo({fileSystem:e,appDirectory:n,commandExecutor:this.getAsynchronousCommandExecutor()}),firefoxRegistry:_o.macOs({fileSystem:e,homeDirectory:this.configuration.directories.home,appPath:e.joinPaths(n,`${this.configuration.deepLinkProtocol}.app`)})})}case "win32":return new to({commandExecutor:this.getAsynchronousCommandExecutor()});case "linux":return new no({fileSystem:e,homeDirectory:this.configuration.directories.home,commandExecutor:this.getAsynchronousCommandExecutor()});default:return null}}))}selectCacheProvider(e){return this.configuration.stateless?new InMemoryCache:e()}getCliConfigurationProvider(){return this.share(this.getCliConfigurationProvider,()=>{let e=this.getFileSystem();return new go({fileSystem:e,configurationProvider:new mo({cacheKey:"config.json",cache:this.selectCacheProvider(()=>new nn({fileSystem:e,directory:this.configuration.directories.config,useKeyAsFileName:true})),validator:new io})})})}async execute(e,t){if(this.isReadOnlyMode()&&!a.READ_ONLY_COMMANDS.has(e.constructor))return this.reportError(new d("This command does not support API key authentication.",{reason:"precondition",suggestions:["Run the command without specifying an API key."]}));try{await e.execute(t);}catch(n){let r=a.handleError(n);return n instanceof Error&&r instanceof Error&&(r.stack=n.stack),this.reportError(r)}}isReadOnlyMode(){return this.configuration.apiKey!==void 0}reportError(e){let t=this.getOutput();return t.report(a.handleError(e)),t.exit()}static handleError(e){switch(true){case e instanceof $:return new d(e.message,{...e.help,details:[`URL: ${e.url}`,...e.help.details??[]]});case e instanceof ee:if(e.isAccessDenied())return new d("Your user lacks the necessary permissions to complete this operation.",{reason:"access_denied",details:e.problems.map(t=>t.detail??t.title),suggestions:["Contact your organization or workspace administrator for assistance."],cause:e});break;case e instanceof h:if(e.tracing.length>0){let t=e.tracing.map(({name:n,source:r},i)=>{let o=r!==void 0?` at ${a.getSourceLocation(r)}`:"";return `${" ".repeat(i+1)}\u21B3 \`${n}\`${o}`}).join(`
|
|
1850
|
+
\`${s}\``);return}r.confirm("CLI updated successfully!"),this.output.inform("The new version will take effect the next time you run a command");}isCheckEnabled(e){return e.lastUpdateCheck===void 0||Date.now()-e.lastUpdateCheck>this.checkFrequency}getLatestVersion(){let e=new AbortController;return setTimeout(()=>e.abort(),this.checkTimeout),fetch("https://registry.npmjs.org/croct/latest",{signal:e.signal}).then(t=>t.json()).then(t=>t.version).catch(()=>null)}};var pa=class{constructor({fileSystem:e}){this.fileSystem=e;}async execute({path:e,recursive:t=false}){let n=this.fileSystem.normalizeSeparators(e);if(await this.fileSystem.exists(n)){if(!t&&await this.fileSystem.isDirectory(n)&&!await this.fileSystem.isEmptyDirectory(n))throw new h("Cannot delete non-empty directory when `recursive` is false.",{reason:"precondition",details:[`Path: ${n}`]});try{await this.fileSystem.delete(n,{recursive:t});}catch(r){throw h.fromCause(r)}}}};var Ym=z.strictObject({path:z.string().min(1),recursive:z.boolean().optional()}),ca=class extends I{constructor(){super(Ym);}};var la=class{constructor({projectDirectory:e,fileSystem:t,codemod:n,scanFilter:r}){this.projectDirectory=e,this.fileSystem=t,this.codemod=n,this.scanFilter=r;}async execute(e,t){let{output:n}=t,r=n?.notify("Resolving imports");try{await this.resolveImports(e.path);}finally{r?.stop();}}async resolveImports(e){let t=false,n=xt.fromPattern(e);for await(let r of this.fileSystem.list(this.projectDirectory.get(),this.scanFilter))await n.test(r.name)&&r.type==="file"&&(t=true,await this.codemod.apply(await this.fileSystem.getRealPath(r.name)));if(!t)throw new d("No matching files found for resolving imports.",{reason:"unexpected_result",details:[`Pattern: ${e}`]})}};var ed=z.strictObject({path:z.string().min(1)}),ua=class extends I{constructor(){super(ed);}};var ma=class{constructor({configurationManager:e,applicationApi:t}){this.configurationManager=e,this.api=t;}async execute(e,t){let{output:n}=t,r=await this.configurationManager.load(),i=e.environment==="production"?r.applications.production:r.applications.development;if(i===void 0)throw new h("The project has no application configured for the selected environment.",{reason:"precondition"});let o=n?.notify("Creating API key"),s;try{s=await this.api.createApiKey({organizationSlug:r.organization,workspaceSlug:r.workspace,applicationSlug:i,name:e.keyName,permissions:e.permissions});}catch(p){throw h.fromCause(p)}finally{o?.stop();}t.set(e.result,s.secret);}};var td=z.strictObject({keyName:z.string().min(1),environment:z.enum(["development","production"]),permissions:z.array(z.enum(ae.all().flatMap(a=>[a.toUpperCase(),a.toLowerCase()])).transform(ae.fromValue)).min(1),result:z.string().min(1)}),da=class extends I{constructor(){super(td);}};var fa=class a{constructor(e){this.instances=new Map;this.configuration=e,this.initialDirectory=e.directories.current??e.process.getCurrentDirectory(),this.workingDirectory=new ho(this.initialDirectory);}static{this.READ_ONLY_COMMANDS=new Set([bn,Zt,Jt,bt,It,Ht,Gt,Xt,jt]);}static fromDefaults(e){let t=od("com.croct.cli"),n=new Po;return new a({program:e.program??(()=>{throw new d("CLI is running in standalone mode.")}),process:e.process??n,quiet:e.quiet??false,debug:e.debug??false,stateless:e.stateless??es.isCI,interactive:e.interactive??!es.isCI,version:e.version??"0.0.0",apiKey:e.apiKey,token:e.token,dnd:e.dnd??es.isCI,adminTokenDuration:e.adminTokenDuration??7*LocalTime.SECONDS_PER_DAY,apiKeyTokenDuration:e.apiKeyTokenDuration??30*LocalTime.SECONDS_PER_MINUTE,cliTokenDuration:e.cliTokenDuration??90*LocalTime.SECONDS_PER_DAY,cliTokenFreshPeriod:e.cliTokenFreshPeriod??15*LocalTime.SECONDS_PER_DAY,cliTokenIssuer:e.cliTokenIssuer??"croct.com",deepLinkProtocol:e.deepLinkProtocol??"croct",templateRegistryUrl:e.templateRegistryUrl??new URL("github://croct-tech/templates/templates/registry.json5"),adminUrl:e.adminUrl??new URL("https://app.croct.com"),adminTokenParameter:e.adminTokenParameter??"accessToken",adminGraphqlEndpoint:e?.adminGraphqlEndpoint??new URL("https://app.croct.com/graphql"),directories:{current:e.directories?.current??n.getCurrentDirectory(),config:e.directories?.config??t.config(),cache:e.directories?.cache??t.cache(),data:e.directories?.data??t.data(),home:e.directories?.home??homedir()},verificationLinkDestination:{accountActivation:e.verificationLinkDestination?.accountActivation??"./cli",passwordReset:e.verificationLinkDestination?.passwordReset??"./cli"},emailSubject:{passwordReset:e.emailSubject?.passwordReset??"Forgot password",accountActivation:e.emailSubject?.accountActivation??"Welcome to Croct"}})}welcome(e){let t=!this.configuration.interactive||this.configuration.dnd;return this.execute(new bn({cliVersion:this.configuration.version,autoUpdater:new sa({currentVersion:this.configuration.version,input:this.getInput(),configurationProvider:this.getCliConfigurationProvider(),packageManager:this.getNodePackageManager(),output:this.getOutput(),checkFrequency:LocalTime.MILLIS_PER_SECOND*LocalTime.SECONDS_PER_HOUR*6,checkTimeout:500}),configurationProvider:this.getCliConfigurationProvider(),deepLinkInstaller:n=>this.deepLink({operation:n?"optionally-update":"optionally-enable"})}),{skipDeepLinkCheck:t||e.skipDeepLinkCheck===true,skipUpdateCheck:t||e.skipUpdateCheck===true})}deepLink(e){return this.execute(new jo({packageManager:this.getNodePackageManager(),protocolRegistryProvider:this.getProtocolRegistryProvider(),configurationProvider:this.getCliConfigurationProvider(),cliPackage:"croct@latest",protocolHandler:{id:"com.croct.cli",name:"croct-cli",protocol:this.configuration.deepLinkProtocol},io:{input:this.getInput(),output:this.getOutput()}}),e)}open(e){return this.execute(new ro({program:this.configuration.program,protocol:this.configuration.deepLinkProtocol,configurationProvider:this.getCliConfigurationProvider(),workingDirectory:new So(this.configuration.process),fileSystem:this.getFileSystem(),io:{input:this.getInput(),output:this.getOutput()}}),e)}init(e){let{process:t}=this.configuration;return this.execute(new Nn({sdkProvider:this.getSdkProvider(),platformProvider:this.getPlatformProvider(),configurationManager:this.getConfigurationManager(),skipConfirmation:new Bi(new Sn(new Ji(new gn({fileSystem:this.getFileSystem(),files:[".git"]})))),api:{user:this.getUserApi(),organization:this.getOrganizationApi(),workspace:this.getWorkspaceApi()},form:{organization:new _n({input:this.getFormInput(),output:this.getOutput(),userApi:this.getUserApi()}),workspace:new jn({input:this.getFormInput(),output:this.getOutput(),organizationApi:this.getOrganizationApi()}),application:new Wn({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),slot:new _e({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()})},io:{input:this.getInput(),output:this.getOutput()}}),{...e,organization:e.organization??t.getEnvValue("CROCT_ORGANIZATION")??void 0,workspace:e.workspace??t.getEnvValue("CROCT_WORKSPACE")??void 0,devApplication:e.devApplication??t.getEnvValue("CROCT_DEV_APPLICATION")??void 0,prodApplication:e.prodApplication??t.getEnvValue("CROCT_PROD_APPLICATION")??void 0,skipApiKeySetup:e.skipApiKeySetup??t.getEnvValue("CROCT_SKIP_API_KEY_SETUP")!==null})}install(e){let t=!this.configuration.interactive||this.configuration.dnd;return this.execute(new Zt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),io:{input:this.getInput(),output:this.getOutput()}}),{clean:e.clean??false,partialConfiguration:e.partialConfiguration??t})}upgrade(e){return this.execute(new Jt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),form:{slotForm:new _e({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),componentForm:new He({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()})},io:{input:this.getInput(),output:this.getOutput()}}),e)}addSlot(e){return this.execute(new bt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),workspaceApi:this.getWorkspaceApi(),slotForm:new _e({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}removeSlot(e){return this.execute(new Ht({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),slotForm:new _e({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}addComponent(e){return this.execute(new It({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new He({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}removeComponent(e){return this.execute(new Gt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new He({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}login(e){return this.execute(new zn({authenticator:this.getAuthenticator()}),e)}logout(){return this.execute(new jt({authenticator:this.getAuthenticator(),output:this.getOutput()}),{})}admin(e){return this.execute(new Hn({output:this.getOutput(),pageForm:new er({input:this.getFormInput()}),configurationManager:this.getConfigurationManager(),userApi:this.getUserApi(),adminUrl:this.configuration.adminUrl,adminTokenParameter:this.configuration.adminTokenParameter,adminTokenDuration:this.configuration.adminTokenDuration}),e)}createTemplate(e){return this.execute(new Xt({configurationManager:this.getConfigurationManager(),fileSystem:this.getFileSystem(),templateForm:new fr({input:this.getFormInput(),form:{component:new He({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),slot:new _e({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),experience:new yr({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),audience:new hr({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()})}}),io:{input:this.getInput(),output:this.getOutput()}}),e)}useTemplate(e){return this.execute(this.getUseTemplateCommand(),e)}async getTemplateOptions(e){let t=this.getUseTemplateCommand(),r=this.getOutput().notify("Loading template options");try{return await t.getOptions(e)}finally{r.stop();}}getUseTemplateCommand(){return new Sr({templateProvider:new Pt({provider:new tn(this.getTemplateProvider()),validator:new pn}),fileSystem:this.getFileSystem(),action:this.getImportAction(),io:{input:this.getInput(),output:this.getOutput()}})}createApiKey(e){return this.execute(new fo({fileSystem:this.getFileSystem(),configurationManager:this.getConfigurationManager(),api:{user:this.getUserApi(),workspace:this.getWorkspaceApi(),application:this.getApplicationApi()},io:{input:this.getFormInput(),output:this.getOutput()}}),e)}getFormInput(e){return this.getInput()??this.getNonInteractiveInput(e)}getNonInteractiveInput(e){return new hn(new nr(e??{message:"Input is not available in non-interactive mode."}))}getInput(){if(this.configuration.interactive)return this.share(this.getInput,()=>{let e=this.getOutput(),t=new Pn({input:this.configuration.process.getStandardInput(),output:this.configuration.process.getStandardOutput(),onAbort:()=>e.exit(),onInteractionStart:()=>e.suspend(),onInteractionEnd:()=>e.resume()});return this.configuration.dnd?new hn(t):t})}getNonInteractiveOutput(e=false){let{configuration:t}=this,n=new _t({output:t.process.getStandardOutput(),formatter:this.getLogFormatter(),interactive:false,quiet:e,onExit:()=>t.process.exit(),linkOpener:new xn(()=>new wn(n))});return t.process.on("exit",()=>n.stop()),n}getHierarchicalLogger(){return this.share(this.getHierarchicalLogger,()=>new Do(this.getLogger()))}getLogger(){return this.share(this.getLogger,()=>{let e=new Mo(this.getOutput());return this.configuration.debug?e:new FilteredLogger(e,LogLevel.WARNING)})}getOutput(){return this.share(this.getOutput,()=>{let{configuration:e}=this,t=new _t({output:e.process.getStandardOutput(),formatter:this.getLogFormatter(),interactive:this.configuration.interactive,quiet:this.configuration.quiet,onExit:()=>e.process.exit(),linkOpener:new xn(()=>{let n=new wn(t);return this.configuration.dnd?n:new Go(n)})});return e.process.on("exit",()=>t.stop()),t})}getLogFormatter(){return this.share(this.getLogFormatter,()=>new xo)}getTemplateProvider(){return this.share(this.getTemplateProvider,()=>{let e=n=>new Me({providers:["template.json5","template.json"].map(r=>new st({dataProvider:n,registryProvider:new Ot([{pattern:/^(https:\/\/(?:www\.)?github.com\/[^/]+\/[^/]+)\/?$/,destination:`$1/blob/main/${r}`},{pattern:/^(.+?:\/*[^/]+(\/+[^/.]+|\/[^/]+(?=\/))*)\/*$/,destination:`$1/${r}`}])}))}),t=this.traceProvider({provider:this.getHttpProvider()});return this.traceProvider({label:"TemplateProvider",provider:new rn({resourceCache:new AutoSaveCache(new InMemoryCache),errorCache:new InMemoryCache,provider:new Me({providers:[new st({dataProvider:this.traceProvider({label:"ResourceProvider",provider:e(new pt(new Me({providers:[this.traceProvider({provider:this.createGitHubProvider(t)}),this.traceProvider({provider:new Yt(t)})]})))}),registryProvider:this.traceProvider({label:"NpmRegistryProvider",provider:new Ao(new Pt({provider:Eo.json(this.traceProvider({provider:this.getHttpProvider()})),validator:new Oo}))})}),e(new pt(this.getFileProvider()))]})})})})}getFileProvider(){return this.share(this.getFileProvider,()=>{let e=this.traceProvider({provider:this.getHttpProvider()}),t=this.traceProvider({provider:new Mr(this.getFileSystem(),this.getScanFilter())}),n=new Me({providers:[t,this.traceProvider({provider:this.createGitHubProvider(e)}),this.traceProvider({provider:new Yt(e)})]});return this.traceProvider({label:"FileProvider",provider:new Me({providers:[t,this.traceProvider({provider:new st({baseUrl:new URL("./",this.configuration.templateRegistryUrl),dataProvider:this.traceProvider({label:"ResourceProvider",provider:n}),registryProvider:new di({url:this.configuration.templateRegistryUrl,provider:this.traceProvider({label:"GlobalRegistryProvider",provider:new rn({errorCache:new InMemoryCache,resourceCache:new AutoSaveCache(new InMemoryCache),provider:new Pt({provider:new tn(new pt(n)),validator:new jr})})})})})})]})})})}createGitHubProvider(e){let t=Date.now();return new Nr({cache:new AutoSaveCache(new InMemoryCache),provider:new Me({providers:[new Me({providers:[new st({dataProvider:e,registryProvider:new Ot([{pattern:/^https:\/\/raw\.github\.com\/croct-tech\/templates\/(HEAD|master)\/templates\/(.+)$/i,destination:`https://cdn.croct.io/templates/$2?c=${t}`},{pattern:/^https:\/\/api\.github\.com\/repos\/croct-tech\/templates\/git\/trees\/(HEAD|master)\?recursive=true/i,destination:`https://cdn.croct.io/templates/git-tree.json?c=${t}`}])}),e]}),e]})})}traceProvider({provider:e,label:t}){return new To({label:t,provider:e,logger:this.getHierarchicalLogger()})}getImportAction(){return this.share(this.getImportAction,()=>{let e=this.getFileSystem(),t=new Map,n={run:new D({action:new Ge(new we(()=>new wi(n))),validator:new Pi}),try:new D({action:new Ge(new we(()=>new Cr(n.run))),validator:new Kr}),test:new D({action:new Ge(new we(()=>new oi(n.run))),validator:new si}),repeat:new D({action:new Ge(new we(()=>new Xi(n.run))),validator:new Yi}),print:new D({action:new pi,validator:new li}),fail:new D({action:new ui,validator:new mi}),define:new D({action:new Ei,validator:new Ai}),prompt:new D({action:new bi,validator:new Ii}),"change-directory":new D({action:new Mi({fileSystem:e,rootDirectory:this.initialDirectory,currentDirectory:this.workingDirectory}),validator:new Di}),"open-link":new D({action:new Ci,validator:new ki}),"start-server":new D({action:new vi({serverProvider:this.getServerProvider(),serverFactory:this.getServerFactory(),packageManager:this.getPackageManager(),serverMap:t}),validator:new xi}),"stop-server":new D({action:new Ko({serverMap:t}),validator:new Oi}),"check-dependency":new D({action:new Dr({packageManager:this.getPackageManager()}),validator:new Hr}),download:new D({action:new br({fileSystem:e,provider:this.getFileProvider(),codemod:new Mt({codemods:{"**/*.{js,jsx,ts,tsx}":new Nt(this.getNodeImportResolverCodemod(),new Mt({codemods:{"**/*.{js,jsx}":new Nt(new Te({fileSystem:e,codemod:new Oe({codemod:new Uo,languages:["typescript","jsx"]})}))}}),new Re(this.getJavaScriptFormatter()))}})}),validator:new Gr}),"resolve-import":new D({action:new la({projectDirectory:this.workingDirectory,fileSystem:e,scanFilter:this.getScanFilter(),codemod:new Mt({codemods:{"**/*.{js,jsx,ts,tsx}":new Nt(this.getNodeImportResolverCodemod(),new Re(this.getJavaScriptFormatter()))}})}),validator:new ua}),install:new D({action:new Zo({packageManager:this.getPackageManager()}),validator:new Jo}),"add-dependency":new D({action:new Ir({packageManager:this.getPackageManager()}),validator:new Jr}),"execute-package":new D({action:new Ni({processObserver:this.configuration.process,packageManager:this.getPackageManager(),packageManagerProvider:this.getPackageManagerRegistry(),workingDirectory:this.workingDirectory,commandExecutor:this.getAsynchronousCommandExecutor(),commandTimeout:3*60*1e3,sourceChecker:{test:r=>r.protocol==="file:"||`${r}`.startsWith("https://github.com/croct-tech")}}),validator:new zi}),"locate-path":new D({action:new vr({projectDirectory:this.workingDirectory,fileSystem:e,scanFilter:this.getScanFilter()}),validator:new Qr}),"move-path":new D({action:new Qo({fileSystem:e}),validator:new Yo}),"delete-path":new D({action:new pa({fileSystem:e}),validator:new ca}),"read-file":new D({action:new Bo({fileSystem:e}),validator:new ta}),"write-file":new D({action:new ia({fileSystem:e,input:this.getInput()}),validator:new aa}),"replace-file-content":new D({action:new xr({fileSystem:e}),validator:new Br}),"create-directory":new D({action:new na({fileSystem:e}),validator:new ra}),"integrate-croct":new D({action:new Co({callback:async()=>{if(!await this.getConfigurationManager().isInitialized("full"))return this.init({})}}),validator:new ko}),"add-slot":new D({action:new wr({installer:(r,i)=>{let o=this.getNonInteractiveOutput(true);return this.execute(new bt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),workspaceApi:this.getWorkspaceApi(),slotForm:new _e({input:this.getNonInteractiveInput(),output:o,workspaceApi:this.getWorkspaceApi()}),io:{output:o}}),{slots:r,example:i})}}),validator:new Yr}),"add-component":new D({action:new Pr({installer:r=>{let i=this.getNonInteractiveOutput(true);return this.execute(new It({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new He({input:this.getNonInteractiveInput(),output:i,workspaceApi:this.getWorkspaceApi()}),io:{output:i}}),{components:r})}}),validator:new ei}),"create-api-key":new D({action:new ma({applicationApi:this.getApplicationApi(),configurationManager:this.getConfigurationManager()}),validator:new da}),"create-resource":new D({action:new Er({configurationManager:this.getConfigurationManager(),matcher:new Rr({workspaceApi:this.getWorkspaceApi()}),api:{user:this.getUserApi(),workspace:this.getWorkspaceApi(),organization:this.getOrganizationApi()},mappingForm:new Or({input:this.getFormInput({message:"Some resource IDs are in use and interactive mode is required to assign new ones.",suggestions:["Retry in interactive mode"]}),workspaceApi:this.getWorkspaceApi()})}),validator:new ti}),"format-code":new D({action:new ri({formatter:this.getCodeFormatter()}),validator:new ii}),import:new D({action:new Ge(new we(()=>new Vr({runner:n.run,templateProvider:new qr({evaluator:new Wr({functions:Ba}),validator:new pn,templateProvider:this.getTemplateProvider(),fileProvider:new pt(this.getFileProvider())}),variables:this.getActionVariables()}))),validator:new ni})};return n.import})}getActionVariables(){let e=t=>new URL(t,this.configuration.adminUrl).toString();return {packageManager:J.transient(()=>({name:this.getPackageManager().getName()})),project:{features:J.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load(),{features:r}=await this.getWorkspaceApi().getFeatures({organizationSlug:t,workspaceSlug:n})??{};return r??{}}),quotas:J.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load(),{quotas:r}=await this.getWorkspaceApi().getFeatures({organizationSlug:t,workspaceSlug:n})??{};return r??{}}),organization:J.transient(async()=>{let{organization:t}=await this.getConfigurationManager().load();return {slug:t,url:e(`organizations/${t}`)}}),workspace:J.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load();return {slug:n,url:e(`organizations/${t}/workspaces/${n}`)}}),application:J.transient(async()=>{let{organization:t,workspace:n,applications:r}=await this.getConfigurationManager().load(),i=`organizations/${t}/workspaces/${n}/applications/`,o=r.production;return {development:{slug:r.development,url:e(i+r.development),publicId:J.transient(async()=>{let p=await this.getWorkspaceApi().getApplication({organizationSlug:t,workspaceSlug:n,applicationSlug:r.development});if(p===null)throw new N("Development application not found.",{reason:"not_found"});return p.publicId})},production:{slug:r.production,url:e(i+r.production),publicId:o===void 0?o:J.transient(async()=>{let p=await this.getWorkspaceApi().getApplication({organizationSlug:t,workspaceSlug:n,applicationSlug:o});if(p===null)throw new N("Production application not found.",{reason:"not_found"});return p.publicId})}}}),path:J.transient(async()=>{let t=this.getSdk(),n=await this.getConfigurationManager().load();return t.getPaths(n)}),platform:J.transient(async()=>await this.getPlatformProvider().get()??"unknown"),server:J.transient(async()=>{let n=await this.getServerProvider().get();if(n===null)return null;try{let r=await n.getStatus();if(r.running)return {running:!0,url:r.url.toString()}}catch{}return {running:false}})}}}getHttpProvider(){return this.share(this.getHttpProvider,()=>new Tr({retry:{maxAttempts:3,delay:1e3}}))}getAuthenticator(){return this.share(this.getAuthenticator,()=>{if(this.configuration.apiKey!==void 0)return new yo({apiKey:this.configuration.apiKey,clock:this.getClock(),tokenDuration:this.configuration.apiKeyTokenDuration});if(this.configuration.token!==void 0)return new Ho({token:this.configuration.token});let e=this.getFormInput(),t=new Un({input:e,output:this.getOutput(),userApi:this.getUserApi(true),form:{signIn:new qn({input:e,output:this.getOutput(),userApi:this.getUserApi(true),listener:this.getTokenListener(),tokenDuration:this.configuration.cliTokenDuration,emailLinkGenerator:{recovery:this.createEmailLinkGenerator(this.configuration.emailSubject.passwordReset),verification:this.createEmailLinkGenerator(this.configuration.emailSubject.accountActivation)},verificationLinkDestination:{accountActivation:this.configuration.verificationLinkDestination.accountActivation,passwordReset:this.configuration.verificationLinkDestination.passwordReset}}),signUp:new Kn({input:e,output:this.getOutput(),userApi:this.getUserApi(true),listener:this.getTokenListener(),emailLinkGenerator:this.createEmailLinkGenerator(this.configuration.emailSubject.accountActivation),verificationLinkDestination:this.configuration.verificationLinkDestination.accountActivation})}}),n=this.getUserApi(true),r=new bo({cacheKey:"token",cacheProvider:new Io({clock:this.getClock(),clockSkewTolerance:5,tokenFreshPeriod:this.configuration.cliTokenFreshPeriod,tokenIssuer:()=>n.issueToken({duration:this.configuration.cliTokenDuration}),cacheProvider:this.selectCacheProvider(()=>new nn({fileSystem:this.getFileSystem(),directory:this.configuration.directories.config,useKeyAsFileName:true}))}),authenticator:new rr({default:this.configuration.interactive?t:new tr({authenticator:t,instruction:{message:"Authentication required.",suggestions:["Run `login` to authenticate"],reason:"precondition"}}),credentials:t})});return this.configuration.interactive?new uo({authenticator:r,invitationForm:new lo({output:this.getOutput(),input:e,userApi:this.getUserApi(true)})}):r})}getSdk(){return this.share(this.getSdk,()=>{let e=new Tt(this.getSdkProvider(),new we(()=>{throw new j("No suitable SDK detected.",{reason:"not_supported",suggestions:["Make sure you are running the command in the project root directory."]})}));return new Zi(e)})}getSdkProvider(){return this.share(this.getSdkProvider,()=>{let e=this.getJavaScriptFormatter(),t=this.getFileSystem(),n=this.getNodeImportResolver(),r={projectDirectory:this.workingDirectory,packageManager:this.getNodePackageManager(),fileSystem:t,formatter:e,workspaceApi:this.getWorkspaceApi(),tsConfigLoader:this.getTsConfigLoader()},i=Symbol("unknown");return new Et({discriminator:async()=>await this.getPlatformProvider().get()??i,mapping:{javascript:()=>new On({...r,bundlers:["vite","parcel","tsup","rollup"]}),react:()=>new Rn({...r,importResolver:n,codemod:{provider:new Re(e,new Te({fileSystem:this.getFileSystem(),codemod:new Oe({languages:["typescript","jsx"],codemod:new nt({fallbackToNamedExports:true,wrapper:{module:"@croct/plug-react",component:"CroctProvider"},targets:{variable:"children"}})})}))},bundlers:[{package:"react-scripts",prefix:"process.env.REACT_APP_"},{package:"vite",prefix:"import.meta.env.VITE_"},{package:"parcel",prefix:"process.env."}]}),nextjs:()=>{let o={appId:{type:"reference",path:["process","env","NEXT_PUBLIC_CROCT_APP_ID"]},debug:{type:"comparison",operator:"===",left:{type:"reference",path:["process","env","NEXT_PUBLIC_CROCT_DEBUG"]},right:{type:"literal",value:"true"}}};return new Mn({...r,userApi:this.getUserApi(),applicationApi:this.getApplicationApi(),importResolver:n,codemod:{middleware:new Re(e,new Te({fileSystem:this.getFileSystem(),codemod:new Oe({languages:["typescript","jsx"],codemod:new Jn({matcherPattern:"/((?!api|_next/static|_next/image|favicon.ico|sitemap.xml|robots.txt).*)",import:{module:"@croct/plug-next/middleware",middlewareName:"middleware",middlewareFactoryName:"withCroct"}})})})),appRouterProvider:new Re(e,new Te({fileSystem:this.getFileSystem(),codemod:new Oe({languages:["typescript","jsx"],codemod:new nt({fallbackToNamedExports:false,fallbackCodemod:new Qn({provider:{component:"CroctProvider",module:"@croct/plug-next/CroctProvider"}}),wrapper:{module:"@croct/plug-next/CroctProvider",component:"CroctProvider"},targets:{variable:"children"}})})})),pageRouterProvider:new Re(e,new Te({fileSystem:this.getFileSystem(),codemod:new Oe({languages:["typescript","jsx"],codemod:new nt({fallbackToNamedExports:false,fallbackCodemod:new Kt({provider:{component:"CroctProvider",module:"@croct/plug-next/CroctProvider"}}),wrapper:{module:"@croct/plug-next/CroctProvider",component:"CroctProvider"},targets:{component:"Component"}})})})),fallbackProvider:new Re(e,new Te({fileSystem:this.getFileSystem(),codemod:new Oe({languages:["typescript","jsx"],codemod:new nt({fallbackToNamedExports:false,fallbackCodemod:new Kt({provider:{component:"CroctProvider",module:"@croct/plug-react",props:o}}),wrapper:{module:"@croct/plug-react",component:"CroctProvider",props:o},targets:{component:"Component"}})})}))}})},[i]:()=>null}})})}getCodeFormatter(){return this.share(this.getCodeFormatter,()=>{let e=Symbol("unknown");return new Gi(new Et({discriminator:async()=>await this.getPlatformProvider().get()??e,mapping:{javascript:()=>this.getJavaScriptFormatter(),react:()=>this.getJavaScriptFormatter(),nextjs:()=>this.getJavaScriptFormatter(),[e]:()=>{throw new j("No code formatter detected.",{reason:"not_supported",suggestions:["Make sure you are running the command in the project root directory."]})}}}))})}share(e,t){let n=this.instances.get(e);if(n===void 0){let r=t();return this.instances.set(e,r),r}return n}getPackageManagerRegistry(){return this.share(this.getPackageManagerRegistry,()=>new Vi(new Map(Object.entries(this.getPackageManagers()))))}getPackageManagers(){return this.getNodePackageManagers()}getPackageManager(){return this.share(this.getPackageManager,()=>new dn(new Tt(this.getNodePackageManagerProvider(),new we(()=>{throw new j("No package manager detected.",{reason:"not_supported",suggestions:["Make sure you are running the command in the project root directory.","Initialize your project and retry the command."]})}))))}getNodePackageManager(){return this.share(this.getNodePackageManager,()=>{let e=this.getNodePackageManagers();return new dn(new Tt(this.getNodePackageManagerProvider(),new Ot(e.npm)))})}getNodePackageManagerProvider(){return this.share(this.getNodePackageManagerProvider,()=>{let e=this.getNodePackageManagers(),t=this.getFileSystem(),n={npm:["package-lock.json"],yarn:["yarn.lock"],bun:["bun.lock","bun.lockb"],pnpm:["pnpm-lock.yaml"]};return new yn(new co(new lt({candidates:Object.entries(e).map(([r,i])=>({value:i,condition:new po({process:this.configuration.process,variable:"npm_config_user_agent",value:new RegExp(`^${r}`)})}))}),new lt({candidates:Object.entries(e).map(([r,i])=>({value:i,condition:new Sn(new so({packageManager:r,fileSystem:t,projectDirectory:this.workingDirectory}),new gn({fileSystem:t,files:n[r]}))}))}),new lt({candidates:Object.entries(e).map(([r,i])=>({value:i,condition:new qo({executableLocator:this.getExecutableLocator(),command:r})}))})),this.workingDirectory)})}getNodePackageManagers(){return this.share(this.getNodePackageManagers,()=>{let e=this.getFileSystem(),t={projectDirectory:this.workingDirectory,fileSystem:e,commandExecutor:this.getAsynchronousCommandExecutor(),executableLocator:this.getExecutableLocator()},n=new en,r={fileSystem:e,projectDirectory:this.workingDirectory,packageValidator:n};return {npm:new Je({...r,agent:new $i(t)}),yarn:new Je({...r,agent:new Fi(t)}),bun:new Je({...r,agent:new Li(t)}),pnpm:new Je({...r,agent:new _i(t)})}})}getServerProvider(){return this.share(this.getServerProvider,()=>{let e=Symbol("unknown");return new Et({discriminator:async()=>await this.getPlatformProvider().get()??e,mapping:{javascript:()=>this.getNodeServerProvider().get(),react:()=>this.getNodeServerProvider().get(),nextjs:()=>this.getNodeServerProvider().get(),[e]:()=>null}})})}getNodeServerProvider(){return this.share(this.getNodeServerProvider,()=>new gi({packageManager:this.getNodePackageManager(),factory:this.getServerFactory(),parsers:[new fi,new yi,new hi,new Si]}))}getServerFactory(){return this.share(this.getServerFactory,()=>new Ti({commandExecutor:this.getAsynchronousCommandExecutor(),workingDirectory:this.workingDirectory,startupTimeout:60*1e3,startupCheckDelay:1.5*1e3,lookupMaxPorts:30,lookupTimeout:2*1e3,processObserver:this.configuration.process}))}getJavaScriptFormatter(){return this.share(this.getJavaScriptFormatter,()=>new Xn({commandExecutor:this.getAsynchronousCommandExecutor(),workingDirectory:this.workingDirectory,packageManager:this.getNodePackageManager(),fileSystem:this.getFileSystem(),timeout:1e4,tools:[{package:"eslint",bin:"eslint",args:e=>["--fix",...e]},{package:"prettier",args:e=>["--write",...e]},{package:"@biomejs/biome",bin:"biome",args:e=>["format","--write",...e]}]}))}getNodeImportResolver(){return this.share(this.getNodeImportResolver,()=>new ji({fileSystem:this.getFileSystem(),tsConfigLoader:this.getTsConfigLoader(),projectDirectory:this.workingDirectory}))}getTsConfigLoader(){return this.share(this.getTsConfigLoader,()=>new Wo({fileSystem:this.getFileSystem(),tsconfigValidator:new Wi}))}getAsynchronousCommandExecutor(){return this.share(this.getAsynchronousCommandExecutor,()=>new Vo({executableLocator:this.getExecutableLocator(),commandExecutor:this.getCommandExecutor()}))}getSynchronousCommandExecutor(){return this.getCommandExecutor()}getCommandExecutor(){return this.share(this.getCommandExecutor,()=>new Hi({currentDirectory:this.workingDirectory,windows:this.configuration.process.getPlatform()==="win32"}))}getExecutableLocator(){return this.share(this.getExecutableLocator,()=>{let{process:e}=this.configuration;return new ao({fileSystem:this.getFileSystem(),cache:new AutoSaveCache(new InMemoryCache),executablePaths:e.getEnvList("PATH")??[],executableExtensions:e.getEnvList("PATHEXT")??[]})})}getPlatformProvider(){return this.share(this.getPlatformProvider,()=>{let e=new Je({projectDirectory:this.workingDirectory,packageValidator:new en,fileSystem:this.getFileSystem(),agent:new Ui});return new yn(new lt({candidates:[{value:"nextjs",condition:new fn({packageManager:e,dependencies:["next"]})},{value:"react",condition:new fn({packageManager:e,dependencies:["react"]})},{value:"javascript",condition:new qi({packageManager:e})}]}),this.workingDirectory)})}getConfigurationManager(){return this.share(this.getConfigurationManager,()=>{let e=new $n({fileSystem:this.getFileSystem(),fullValidator:new Fr,partialValidator:new Lr,projectDirectory:this.workingDirectory});return new oo({workingDirectory:this.workingDirectory,configurationProvider:this.getCliConfigurationProvider(),manager:new kr(this.isReadOnlyMode()?e:new Yn({manager:e,initializer:{initialize:()=>this.init({})}}))})})}getNodeImportResolverCodemod(){return this.share(this.getNodeImportResolverCodemod,()=>{let e=this.getFileSystem(),t=this.getScanFilter();return new No({fileSystem:e,rootPath:this.workingDirectory,filter:(n,r)=>r<=10&&t(n,r),importResolver:this.getNodeImportResolver(),importCodemod:new Te({fileSystem:e,codemod:new Oe({languages:["typescript","jsx"],codemod:new $o})}),exportMatcher:{test:(n,{names:r})=>r.length===0?true:uc(n).some(i=>r.includes(i))}})})}getScanFilter(){return this.share(this.getScanFilter,()=>{let e=new Qi({fileSystem:this.getFileSystem(),workingDirectory:this.workingDirectory});return async t=>!await e.test(t)})}getUserApi(e=false){return e?new Ut(this.getGraphqlClient(true)):this.share(this.getUserApi,()=>new Ut(this.getGraphqlClient()))}getOrganizationApi(){return this.share(this.getOrganizationApi,()=>new Fn(this.getGraphqlClient(),this.getHierarchyResolver()))}getWorkspaceApi(){return this.share(this.getWorkspaceApi,()=>new Ln(this.getGraphqlClient(),this.getHierarchyResolver()))}getApplicationApi(){return this.share(this.getApplicationApi,()=>new Vn(this.getGraphqlClient(),this.getHierarchyResolver()))}getHierarchyResolver(){return this.share(this.getHierarchyResolver,()=>new Fo(this.getGraphqlClient(),new InMemoryCache))}getGraphqlClient(e=false){return e?new Wt({endpoint:this.configuration.adminGraphqlEndpoint,tokenProvider:{getToken:()=>this.getAuthenticator().getToken()}}):this.share(this.getGraphqlClient,()=>{let t=this.getAuthenticator();return new Wt({endpoint:this.configuration.adminGraphqlEndpoint,tokenProvider:{getToken:async()=>await t.getToken()??t.login({method:"default"})}})})}getTokenListener(){return this.share(this.getTokenListener,()=>{let{configuration:e}=this;return new or({platform:e.process.getPlatform(),commandExecutor:this.getSynchronousCommandExecutor(),timeout:2e3,listener:new vo({api:this.getUserApi(true),pollingInterval:1e3})})})}getFileSystem(){return this.share(this.getFileSystem,()=>new ir({workingDirectory:this.workingDirectory,defaultEncoding:"utf-8"}))}createEmailLinkGenerator(e){let t=this.getEmailLinkGenerator(),n=this.getClock();return r=>t.generate({recipient:r,sender:"croct.com",subject:e,timestamp:Instant.now(n).getSeconds()})}getEmailLinkGenerator(){return this.share(this.getEmailLinkGenerator,()=>new ar({detector:new sr(new pr,new cr),templates:{google:new lr,icloud:new ur,microsoft:new mr,proton:new dr,yahoo:new gr}}))}getClock(){return SystemClock.UTC}getProtocolRegistryProvider(){return this.share(this.getProtocolRegistryProvider,()=>new we(()=>{let e=this.getFileSystem(),{process:t}=this.configuration;switch(t.getPlatform()){case "darwin":{let n=e.joinPaths(this.configuration.directories.data,"apps");return new Lo({output:this.getOutput(),macOsRegistry:new eo({fileSystem:e,appDirectory:n,commandExecutor:this.getAsynchronousCommandExecutor()}),firefoxRegistry:_o.macOs({fileSystem:e,homeDirectory:this.configuration.directories.home,appPath:e.joinPaths(n,`${this.configuration.deepLinkProtocol}.app`)})})}case "win32":return new to({commandExecutor:this.getAsynchronousCommandExecutor()});case "linux":return new no({fileSystem:e,homeDirectory:this.configuration.directories.home,commandExecutor:this.getAsynchronousCommandExecutor()});default:return null}}))}selectCacheProvider(e){return this.configuration.stateless?new InMemoryCache:e()}getCliConfigurationProvider(){return this.share(this.getCliConfigurationProvider,()=>{let e=this.getFileSystem();return new go({fileSystem:e,configurationProvider:new mo({cacheKey:"config.json",cache:this.selectCacheProvider(()=>new nn({fileSystem:e,directory:this.configuration.directories.config,useKeyAsFileName:true})),validator:new io})})})}async execute(e,t){if(this.isReadOnlyMode()&&!a.READ_ONLY_COMMANDS.has(e.constructor))return this.reportError(new d("This command does not support API key authentication.",{reason:"precondition",suggestions:["Run the command without specifying an API key."]}));try{await e.execute(t);}catch(n){let r=a.handleError(n);return n instanceof Error&&r instanceof Error&&(r.stack=n.stack),this.reportError(r)}}isReadOnlyMode(){return this.configuration.apiKey!==void 0}reportError(e){let t=this.getOutput();return t.report(a.handleError(e)),t.exit()}static handleError(e){switch(true){case e instanceof $:return new d(e.message,{...e.help,details:[`URL: ${e.url}`,...e.help.details??[]]});case e instanceof ee:if(e.isAccessDenied())return new d("Your user lacks the necessary permissions to complete this operation.",{reason:"access_denied",details:e.problems.map(t=>t.detail??t.title),suggestions:["Contact your organization or workspace administrator for assistance."],cause:e});break;case e instanceof h:if(e.tracing.length>0){let t=e.tracing.map(({name:n,source:r},i)=>{let o=r!==void 0?` at ${a.getSourceLocation(r)}`:"";return `${" ".repeat(i+1)}\u21B3 \`${n}\`${o}`}).join(`
|
|
1851
1851
|
`);return new d(`${e.message}
|
|
1852
1852
|
|
|
1853
1853
|
\u25B6\uFE0F **Trace**
|
|
1854
|
-
${t}`,e.help)}break;case e instanceof Ie:return new d(e.message,{...e.help,suggestions:["Run `init` to create a new configuration."]})}return e}static getSourceLocation(e){return e.url.protocol==="file:"?`${e.url}:${e.start.line}:${e.start.column}`:e.url.hostname==="github.com"?`${e.url}#L${e.start.line}-L${e.end.line}`:`${e.url}#${e.start.line}:${e.start.column}-${e.end.line}:${e.end.column}`}};var ts={version:"0.9.
|
|
1854
|
+
${t}`,e.help)}break;case e instanceof Ie:return new d(e.message,{...e.help,suggestions:["Run `init` to create a new configuration."]})}return e}static getSourceLocation(e){return e.url.protocol==="file:"?`${e.url}:${e.start.line}:${e.start.column}`:e.url.hostname==="github.com"?`${e.url}#L${e.start.line}-L${e.end.line}`:`${e.url}#${e.start.line}:${e.start.column}-${e.end.line}:${e.end.column}`}};var ts={version:"0.9.1"};function bc(a){let e=new Command().name("croct").description("Manage your Croct projects").enablePositionalOptions().option("--cwd <path>","The working directory.",S=>{try{return realpathSync(S)}catch{throw new InvalidOptionArgumentError("The path does not exist.")}}).addOption(new Option("--api-key <key>","The API key to use for authentication.").env("CROCT_API_KEY").argParser(S=>{try{return ApiKey.parse(S)}catch{throw new InvalidOptionArgumentError("The API key is malformed.")}}).conflicts("token")).addOption(new Option("--token <token>","The JWT-formatted token to use for authentication.").env("CROCT_TOKEN").argParser(S=>{let P;try{P=Token.parse(S);}catch{throw new InvalidOptionArgumentError("The token is malformed.")}if(!P.isValidNow())throw new InvalidOptionArgumentError("The token is expired.");return P})).option("--registry <url>","The template registry.",S=>{if(!URL.canParse(S))throw new InvalidOptionArgumentError("Malformed URL.");return S}).option("--no-interaction","Run the CLI in non-interactive mode.").addOption(new Option("--stateless","Run the CLI without saving any state locally.").env("CROCT_STATELESS").default(false)).addOption(new Option("--dnd","Run the CLI with minimal interaction and interruption.").env("CROCT_DND").default(false)).addOption(new Option("-q, --quiet","Disable output messages.").default(false).implies({interaction:false})).option("--debug","Enable debug mode.").version(ts.version,"-v, --version","Display the version number.").helpOption("-h, --help","Display help for a command.").helpCommand("help [command]","Display help for a command.");e.command("open <url>").description("Open a deep link.").action(async S=>{await a.cli?.open({url:S});});let t=e.command("login").description("Authenticate your user."),n=new Option("-u, --username <username>","The email."),r=new Option("-p, --password <password>","The password.");t.command("credentials",{isDefault:true}).description("Authenticate using credentials.").addOption(a.interactive?n:n.makeOptionMandatory()).addOption(a.interactive?r:r.makeOptionMandatory()).action(async S=>{await a.cli?.login({method:"credentials",username:S.username,password:S.password});}),e.command("logout").description("Logout the current user.").action(async()=>{await a.cli?.logout();}),e.command("admin").argument("[page...]","The name of the page or path to open.").description("Log in and open the admin panel.").action(async S=>{await a.cli?.admin({page:S!==void 0?S.join(" "):a.interactive?void 0:"/"});});let i=new Option("--wor <workspace-slug>","The workspace slug."),o=new Option("--org <organization-slug>","The organization slug."),s=new Option("--dev-app <application-slug>","The development application slug."),p=new Option("--prod-app <application-slug>","The production application slug.");e.command("init").description("Configure the project.").option("-o, --override","Override any existing configuration.").addOption(new Option("-n, --new <resource>","The resources to create.").choices(["organization","org","workspace","wor","application","app"])).addOption(new Option("-s, --sdk <platform>","The SDK to use.").choices(["javascript","react","next"])).addOption(new Option("--skip-api-key-setup","Opt-out of API key setup.").default(false).env("CROCT_SKIP_API_KEY_SETUP")).addOption(a.interactive?o:o.makeOptionMandatory()).addOption(a.interactive?i:i.makeOptionMandatory()).addOption(a.interactive?s:s.makeOptionMandatory()).addOption(p).action(async S=>{await a.cli?.init({override:S.override,new:(()=>{switch(S.new){case "organization":case "org":return "organization";case "workspace":case "wor":return "workspace";case "application":case "app":return "application";default:return}})(),sdk:S.sdk,organization:S.org,workspace:S.wor,devApplication:S.devApp,prodApplication:S.prodApp,skipApiKeySetup:S.skipApiKeySetup});}),e.command("install").description("Install content and types.").action(async()=>{await a.cli?.install({});}),e.command("update").description("Update content and types.").action(async()=>{await a.cli?.install({clean:true});}),e.command("upgrade").description("Upgrade components and slots to the latest version.").option("-s, --slots <slots...>","The slots to upgrade.").option("-c, --components <components...>","The components to upgrade.").action(async S=>{await a.cli?.upgrade({slots:S.slots??(S.components!==void 0?[]:void 0),components:S.components??(S.slots!==void 0?[]:void 0)});});let c=e.command("add").description("Add a resource to your project.");c.command("slot").description("Add a slot to your project.").argument(a.interactive?"[slots...]":"<slots...>").option("-e, --example","Generate an implementation example.").action(async(S,P)=>{await a.cli?.addSlot({slots:S,example:P.example});}),c.command("component").description("Add a component to your project.").argument(a.interactive?"[components...]":"<components...>").action(async S=>{await a.cli?.addComponent({components:S});});let l=e.command("remove").description("Remove a resource from your project.");l.command("slot").description("Remove a slot from your project.").argument(a.interactive?"[slots...]":"<slots...>").action(async S=>{await a.cli?.removeSlot({slots:S});}),l.command("component").description("Remove a component from your project.").argument(a.interactive?"[components...]":"<components...>").action(async S=>{await a.cli?.removeComponent({components:S});});let u=e.command("create").description("Create a resource in your project.");u.command("template").description("Create a template from your project.").addArgument(new Argument("<path>","The path to the file.").argOptional()).option("-e, --empty","Create an empty template.").action(async(S,P)=>{await a.cli?.createTemplate({file:S,empty:P.empty});});let g=new Option("--permissions <permissions...>","The permissions of the API key.").argParser(S=>S.split(",").map(P=>{try{return ae.fromValue(P)}catch{throw new InvalidOptionArgumentError(`Unknown permission "${P}".`)}})),y=new Option("--env <environment>","The environment of the API key.").choices(["prod","dev"]).argParser(S=>S==="prod"?"PRODUCTION":"DEVELOPMENT");u.command("api-key").description("Create an API key.").option("--name <name>","The name of the API key.").addOption(a.interactive?g:g.makeOptionMandatory()).addOption(a.interactive?y:y.makeOptionMandatory()).option("-c, --copy","Copy the API key to the clipboard.").action(async S=>{await a.cli?.createApiKey({name:S.name,permissions:S.permissions,environment:S.env,copy:S.copy});});let C={},v=e.command("use").description("Use a template.").argument("template","The path to the template.").passThroughOptions(a.cli===void 0).allowUnknownOption(a.cli===void 0||a.template===null).action(async(S,P)=>{await a.cli?.useTemplate({template:S,options:Object.fromEntries(Object.entries(P).map(([H,ce])=>[C[H],ce]))});});for(let[S,P]of Object.entries(a.template??{})){let H=`--${S}${P.type!=="boolean"?" <value>":""}`,ce=new Option(H,P.description).makeOptionMandatory(P.required===true);switch(P.type){case "string":P.choices!==void 0&&P.choices.length>0&&ce.choices(P.choices);break;case "number":ce.argParser(V=>{let ie=Number.parseFloat(V);if(Number.isNaN(ie))throw new InvalidOptionArgumentError("The value must be a number.");return ie});break;case "array":ce.argParser(V=>{let ie;try{ie=JSON.parse(V);}catch{}if(ie===void 0||!Array.isArray(ie))throw new InvalidOptionArgumentError("The value must be a JSON array.");return ie});break;case "object":ce.argParser(V=>{let ie;try{ie=JSON.parse(V);}catch{throw new InvalidOptionArgumentError("The JSON is malformed.")}if(typeof ie!="object"||ie===null)throw new InvalidOptionArgumentError("The value must be a JSON object.")});break}C[ce.attributeName()]=S,v.addOption(ce);}return e.command("enable").description("Enable a feature.").command("deep-link").description("Enable deep link support.").action(async()=>{await a.cli?.deepLink({operation:"enable"});}),e.command("disable").description("Disable a feature.").command("deep-link").description("Disable deep link support.").action(async()=>{await a.cli?.deepLink({operation:"disable"});}),e}function gd(a){let e=["use","help use"];for(let t of e){let n=t.split(" ").length;if(a.length>n&&a.slice(0,n).join(" ")===t&&(a[n]??"")!=="")return a[n]}return null}function fd(a){return a.length>=2&&["enable","disable"].includes(a[0])&&a[1]==="deep-link"}async function ns(a=process.argv,e=true){let t=bc({interactive:true}).parse(a),n=t.opts(),r=fa.fromDefaults({program:p=>ns(t.args.slice(0,2).concat(p)),version:ts.version,quiet:n.quiet,debug:n.debug,interactive:n.interaction?void 0:false,stateless:n.stateless,apiKey:n.apiKey,token:n.token,dnd:n.dnd,templateRegistryUrl:n.registry===void 0?void 0:new URL(n.registry)}),i=gd(t.args),o=i!==null?await r.getTemplateOptions(i).catch(()=>null):void 0,s=bc({cli:r,interactive:n.interaction,template:o});e&&await r.welcome({skipDeepLinkCheck:fd(t.args)}),await s.parseAsync(a);}ns();
|