croct 0.10.0 → 0.11.0

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.
Files changed (2) hide show
  1. package/index.js +11 -11
  2. package/package.json +28 -28
package/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import {createRequire}from'module';import {Command,InvalidOptionArgumentError,Option,Argument}from'@commander-js/extra-typings';import {createReadStream,realpathSync}from'fs';import {ApiKey}from'@croct/sdk/apiKey';import {Token}from'@croct/sdk/token';import {NoopCache,InMemoryCache,AutoSaveCache}from'@croct/cache';import {LocalTime,Instant,TimeZone,LocalDateTime}from'@croct/time';import {SystemClock}from'@croct/time/clock/systemClock.js';import {homedir}from'os';import od from'xdg-app-paths';import es from'ci-info';import {LogLevel,FilteredLogger}from'@croct/logging';import wc from'prompts';import {Readable,PassThrough}from'stream';import Sa from'cli-cursor';import Qe from'chalk';import ba from'node:readline';import {WriteStream}from'tty';import Mc from'strip-ansi';import Pc from'is-unicode-supported';import {render}from'@croct/md-lite/rendering.js';import kc from'terminal-link';import {unescape}from'@croct/md-lite/parsing.js';import {strip}from'node-emoji';import {JsonParser as JsonParser$1,JsonObjectNode as JsonObjectNode$1,JsonArrayNode as JsonArrayNode$1}from'@croct/json5-parser/index.js';import {JsonObjectNode,JsonParser,JsonArrayNode,JsonPrimitiveNode,JsonIdentifierNode,JsonTokenNode,JsonTokenType,JsonParseError,isIdentifier}from'@croct/json5-parser';import*as f from'@babel/types';import {traverseFast,noop,isTypeScript,isImportSpecifier,isImportDeclaration}from'@babel/types';import {createConfigItem,transformFromAstAsync,traverse}from'@babel/core';import {parse as parse$1}from'@babel/parser';import {createHash,randomUUID as randomUUID$1}from'crypto';import {parse,print}from'recast';import Ra from'recast/parsers/_babel_options.js';import {stringSimilarity}from'string-similarity-js';import {realpath,lstat,readdir,symlink,link,mkdir,writeFile,rm,rename,readFile,mkdtemp,cp as cp$1}from'fs/promises';import {tmpdir}from'node:os';import {sep,basename,dirname,relative,isAbsolute,join,delimiter}from'path';import {minimatch,Minimatch}from'minimatch';import {deepEqual}from'fast-equals';import {z,ZodPromise,ZodOptional,ZodTuple,ZodArray,ZodRecord,ZodObject,ZodEffects,ZodAny,ZodPipeline,ZodUnion,ZodDiscriminatedUnion}from'zod';import Ne from'jsep';import Ol from'@jsep-plugin/object';import Rl from'@jsep-plugin/spread';import Tl from'@jsep-plugin/regex';import qp from'is-plain-obj';import {randomUUID}from'node:crypto';import nm from'semver';import {spawn,spawnSync}from'child_process';import sm from'ignore';import ym from'clipboardy';import lc from'boxen';import Ce from'node:process';import {AsyncLocalStorage}from'node:async_hooks';import {parse as parse$2}from'ini';import Wm from'@babel/plugin-transform-typescript';import qm from'@babel/plugin-syntax-decorators';import Km from'open';import hc from'is-installed-globally';createRequire(import.meta.url);
2
+ import {createRequire}from'module';import {Command,InvalidOptionArgumentError,Option,Argument}from'@commander-js/extra-typings';import {createReadStream,realpathSync}from'fs';import {ApiKey}from'@croct/sdk/apiKey';import {Token}from'@croct/sdk/token';import {NoopCache,InMemoryCache,AutoSaveCache}from'@croct/cache';import {LocalTime,Instant,TimeZone,LocalDateTime}from'@croct/time';import {SystemClock}from'@croct/time/clock/systemClock.js';import {tmpdir,homedir}from'os';import od from'xdg-app-paths';import es from'ci-info';import {FilteredLogger,LogLevel}from'@croct/logging';import wc from'prompts';import {Readable,PassThrough}from'stream';import Sa from'cli-cursor';import Qe from'chalk';import ba from'readline';import {WriteStream}from'tty';import Mc from'strip-ansi';import Pc from'is-unicode-supported';import {render}from'@croct/md-lite/rendering.js';import kc from'terminal-link';import {unescape}from'@croct/md-lite/parsing.js';import {strip}from'node-emoji';import {JsonParser,JsonObjectNode,JsonArrayNode}from'@croct/json5-parser/index.js';import {JsonParser as JsonParser$1,JsonObjectNode as JsonObjectNode$1,JsonArrayNode as JsonArrayNode$1,JsonPrimitiveNode,JsonIdentifierNode,JsonTokenNode,JsonTokenType,JsonParseError,isIdentifier}from'@croct/json5-parser';import*as f from'@babel/types';import {traverseFast,noop,isTypeScript,isImportSpecifier,isImportDeclaration}from'@babel/types';import {createConfigItem,transformFromAstAsync,traverse}from'@babel/core';import {parse as parse$1}from'@babel/parser';import {randomUUID,createHash}from'crypto';import {parse,print}from'recast';import Ra from'recast/parsers/_babel_options.js';import {stringSimilarity}from'string-similarity-js';import {realpath,lstat,readdir,symlink,link,mkdir,writeFile,rm,rename,readFile,mkdtemp,cp as cp$1}from'fs/promises';import {sep,basename,dirname,relative,isAbsolute,join,delimiter}from'path';import {minimatch,Minimatch}from'minimatch';import {deepEqual}from'fast-equals';import {z,ZodPromise,ZodOptional,ZodTuple,ZodArray,ZodRecord,ZodObject,ZodEffects,ZodAny,ZodPipeline,ZodUnion,ZodDiscriminatedUnion}from'zod';import Ne from'jsep';import Ol from'@jsep-plugin/object';import Rl from'@jsep-plugin/spread';import Tl from'@jsep-plugin/regex';import qp from'is-plain-obj';import nm from'semver';import {spawn,spawnSync}from'child_process';import sm from'ignore';import ym from'clipboardy';import lc from'boxen';import Ce from'process';import {AsyncLocalStorage}from'async_hooks';import {parse as parse$2}from'ini';import Wm from'@babel/plugin-transform-typescript';import qm from'@babel/plugin-syntax-decorators';import Km from'open';import hc from'is-installed-globally';createRequire(import.meta.url);
3
3
  var vc=Object.defineProperty;var xc=(a,e)=>{for(var t in e)vc(a,t,{get:e[t],enumerable:true});};var Pn=class{constructor(e){this.configuration=e;}prompt(e){return this.interact({type:e.type==="password"?"invisible":"text",message:e.message,initial:e.default??e.initial,validate:e.validate})}select(e){let t=e.default!==void 0?e.options.findIndex(n=>n.value===e.default):-1;return this.interact({type:e.options.length>10?"autocomplete":"select",instructions:false,message:e.message,choices:e.options.map((n,r)=>({title:n.label,value:`${r}`,disabled:n.disabled})),initial:t===-1?void 0:t}).then(n=>e.options[Number.parseInt(n,10)].value)}selectMultiple(e){return this.interact({type:e.options.length>10?"autocompleteMultiselect":"multiselect",hint:"<space> to select. <a> to toggle all. <enter> to submit.",message:e.message,instructions:false,min:e.min,max:e.max,choices:e.options.map((t,n)=>({title:t.label,value:`${n}`,disabled:t.disabled,selected:t.selected}))}).then(t=>t.map(n=>e.options[Number.parseInt(n,10)].value))}confirm(e){return this.interact({type:"confirm",message:e.message,initial:e.default??false})}wait(e){let t={enter:"[enter]",space:"[space]"},n={[t.enter]:"",[t.space]:" "},r=`Press <${e.key}> to continue`,i=e.key!==void 0?n[e.key]??e.key:void 0,o=false;return this.interact({type:"invisible",message:e.message,validate:s=>i===void 0||s===i?true:r,onState:function(p){if(!o){if(p.value===""){this.error&&e.key!==t.enter&&this.bell();return}i===void 0||p.value===i?(o=true,this.submit()):(this.bell(),this.reset(),i!==void 0&&(this.error=true,this.errorMsg=r));}}})}async interact(e,t){this.configuration.onInteractionStart?.();let{output:n,onAbort:r}=this.configuration,i,o={name:"value",...e,stdin:this.configuration.input,stdout:this.configuration.output,onState:function(p){e.onState?.apply(this,[p]),p.aborted&&(n.write("\x1B[?25h"),n.write(`
4
4
  `),i=r());}};try{return await wc(o,t).then(s=>s.value??i)}finally{this.configuration.onInteractionEnd?.();}}};var Ue=Pc(),Lt={neutral:"cyan",info:"blue",error:"red",warning:"yellow",success:"green",secondary:"grey"},Oc={neutral:Ue?"\u279C":">",info:Ue?"\u2139":"i",error:Ue?"\u2718":"\xD7",warning:Ue?"\u26A0":"\u203C",success:Ue?"\u2714":"\u221A",secondary:Ue?"\u21B3":"\u203A"};function Q(a,e={}){let t=e.basic===true?a:Rc(a);if(Ue||(t=strip(t)),e.text!==void 0&&(t=Qe[Lt[e.text]](t)),e.icon!==void 0){let{semantics:n,symbol:r}=e.icon;t=r!==void 0?`${Qe[Lt[n]](r[Ue?"unicode":"ascii"])} ${t}`:`${Qe[Lt[n]](Oc[n])} ${t}`;}return t}function Rc(a){return render(a,{fragment:e=>e.children.join(""),text:e=>e.content,bold:e=>Qe.bold(e.children),italic:e=>Qe.italic(e.children),strike:e=>Qe.strikethrough(e.children),code:e=>Qe.cyan(e.content),link:e=>kc(e.children,e.href,{fallback:(t,n)=>t.includes(n)?t:`${t} (${n})`}),image:e=>unescape(e.source),paragraph:e=>`${e.children.join("")}
5
5
 
@@ -98,12 +98,12 @@ ${y}`+Y`
98
98
  // module
99
99
 
100
100
  export {};
101
- `.replace("// module",s),await this.fileSystem.writeTextFile(o,s,{overwrite:true});}i.confirm("Types updated");}async generateTypes(e){let{organization:t,workspace:n,components:r,slots:i}=await this.resolveVersions(e);return this.workspaceApi.generateTypes({organizationSlug:t,workspaceSlug:n,target:"PLUG_JS",components:Object.entries(r).map(([o,s])=>({id:o,version:s})),slots:Object.entries(i).map(([o,s])=>({id:o,version:s}))})}async registerTypeFile(e,t){let n=await this.getPaths(e.configuration),r=await this.getTypeScriptConfigPath([n.components,n.examples]),i=t??e.output.notify("Registering type file");if(r===null)throw new X("TypeScript configuration not found");let o=this.projectDirectory.get();if(!this.fileSystem.isSubPath(o,r)){let l=this.fileSystem.getRelativePath(o,r);throw new X(`TypeScript configuration is outside the project directory: \`${l}\``)}let s=e.configuration.paths?.content??this.projectDirectory.get(),p=this.fileSystem.getRelativePath(this.fileSystem.getDirectoryName(r),this.getTypeFile(s)).replace(/\\/g,"/"),c=JsonParser$1.parse(await this.fileSystem.readTextFile(r),JsonObjectNode$1);if(c.has("files")){let l=c.get("files",JsonArrayNode$1).toJSON();if(l.includes(p))return i.confirm("Type file already registered");let u=this.getTypeFile(".");for(let g=0;g<l.length;g++){let y=`${l[g]}`;y!==p&&y.endsWith(u)&&l.splice(g,1);}l.push(p),c.set("files",l);}else c.set("files",[p]);await this.fileSystem.writeTextFile(r,c.toString(),{overwrite:true}),i.confirm("Type file registered");}async resolveVersions(e){let t=Object.keys(e.components),n=Object.keys(e.slots);if(t.length===0&&n.length===0)return e;let[r,i]=await Promise.all([Promise.all(n.map(o=>this.workspaceApi.getSlot({organizationSlug:e.organization,workspaceSlug:e.workspace,slotSlug:o}))).then(o=>o.filter(s=>s!==null)),Promise.all(t.map(o=>this.workspaceApi.getComponent({organizationSlug:e.organization,workspaceSlug:e.workspace,componentSlug:o}))).then(o=>o.filter(s=>s!==null))]);return {...e,components:Object.fromEntries(Object.entries(e.components).flatMap(([o,s])=>{let p=T.parse(s).getVersions().filter(c=>i.some(l=>l.slug===o&&c<=l.version.major));return p.length===0?[]:[[o,T.either(...p).toString()]]})),slots:Object.fromEntries(Object.entries(e.slots).flatMap(([o,s])=>{let p=T.parse(s).getVersions().filter(c=>r.some(l=>l.slug===o&&c<=l.version.major));return p.length===0?[]:[[o,T.either(...p).toString()]]}))}}async mountContentPackageFolder(){let e=await this.packageManager.getDependency(a.CONTENT_PACKAGE);if(e===null)return null;if(await this.fileSystem.isSymbolicLink(e.directory)){let t=await this.fileSystem.getRealPath(e.directory);await this.fileSystem.delete(e.directory),await this.fileSystem.copy(t,e.directory);}return e}async locateFile(...e){let t=this.projectDirectory.get();for(let n of e){if(this.fileSystem.isAbsolutePath(n))throw new X("The file path must be relative");let r=this.fileSystem.joinPaths(t,n);if(await this.fileSystem.exists(r))return n}return null}async readFile(...e){let t=await this.locateFile(...e);return t===null?null:this.fileSystem.readTextFile(this.fileSystem.joinPaths(this.projectDirectory.get(),t))}getTypeFile(e){return this.fileSystem.joinPaths(e,"slots.d.ts")}isTypeScriptProject(){return this.packageManager.hasDirectDependency("typescript")}async getTypeScriptConfigPath(e=[]){let t=this.projectDirectory.get(),n=await this.importConfigLoader.load(t,{fileNames:["tsconfig.json"],sourcePaths:e.length===0?[t]:e});return n===null?null:n.matchedConfigPath}};var ke=class a{constructor(e=2){this.code="";this.indentationLevel=0;this.indentationSize=e;}indent(){return this.indentationLevel++,this}outdent(){return this.indentationLevel>0&&this.indentationLevel--,this}newLine(e=1){return this.code+=`
101
+ `.replace("// module",s),await this.fileSystem.writeTextFile(o,s,{overwrite:true});}i.confirm("Types updated");}async generateTypes(e){let{organization:t,workspace:n,components:r,slots:i}=await this.resolveVersions(e);return this.workspaceApi.generateTypes({organizationSlug:t,workspaceSlug:n,target:"PLUG_JS",components:Object.entries(r).map(([o,s])=>({id:o,version:s})),slots:Object.entries(i).map(([o,s])=>({id:o,version:s}))})}async registerTypeFile(e,t){let n=await this.getPaths(e.configuration),r=await this.getTypeScriptConfigPath([n.components,n.examples]),i=t??e.output.notify("Registering type file");if(r===null)throw new X("TypeScript configuration not found");let o=this.projectDirectory.get();if(!this.fileSystem.isSubPath(o,r)){let l=this.fileSystem.getRelativePath(o,r);throw new X(`TypeScript configuration is outside the project directory: \`${l}\``)}let s=e.configuration.paths?.content??this.projectDirectory.get(),p=this.fileSystem.getRelativePath(this.fileSystem.getDirectoryName(r),this.getTypeFile(s)).replace(/\\/g,"/"),c=JsonParser.parse(await this.fileSystem.readTextFile(r),JsonObjectNode);if(c.has("files")){let l=c.get("files",JsonArrayNode).toJSON();if(l.includes(p))return i.confirm("Type file already registered");let u=this.getTypeFile(".");for(let g=0;g<l.length;g++){let y=`${l[g]}`;y!==p&&y.endsWith(u)&&l.splice(g,1);}l.push(p),c.set("files",l);}else c.set("files",[p]);await this.fileSystem.writeTextFile(r,c.toString(),{overwrite:true}),i.confirm("Type file registered");}async resolveVersions(e){let t=Object.keys(e.components),n=Object.keys(e.slots);if(t.length===0&&n.length===0)return e;let[r,i]=await Promise.all([Promise.all(n.map(o=>this.workspaceApi.getSlot({organizationSlug:e.organization,workspaceSlug:e.workspace,slotSlug:o}))).then(o=>o.filter(s=>s!==null)),Promise.all(t.map(o=>this.workspaceApi.getComponent({organizationSlug:e.organization,workspaceSlug:e.workspace,componentSlug:o}))).then(o=>o.filter(s=>s!==null))]);return {...e,components:Object.fromEntries(Object.entries(e.components).flatMap(([o,s])=>{let p=T.parse(s).getVersions().filter(c=>i.some(l=>l.slug===o&&c<=l.version.major));return p.length===0?[]:[[o,T.either(...p).toString()]]})),slots:Object.fromEntries(Object.entries(e.slots).flatMap(([o,s])=>{let p=T.parse(s).getVersions().filter(c=>r.some(l=>l.slug===o&&c<=l.version.major));return p.length===0?[]:[[o,T.either(...p).toString()]]}))}}async mountContentPackageFolder(){let e=await this.packageManager.getDependency(a.CONTENT_PACKAGE);if(e===null)return null;if(await this.fileSystem.isSymbolicLink(e.directory)){let t=await this.fileSystem.getRealPath(e.directory);await this.fileSystem.delete(e.directory),await this.fileSystem.copy(t,e.directory);}return e}async locateFile(...e){let t=this.projectDirectory.get();for(let n of e){if(this.fileSystem.isAbsolutePath(n))throw new X("The file path must be relative");let r=this.fileSystem.joinPaths(t,n);if(await this.fileSystem.exists(r))return n}return null}async readFile(...e){let t=await this.locateFile(...e);return t===null?null:this.fileSystem.readTextFile(this.fileSystem.joinPaths(this.projectDirectory.get(),t))}getTypeFile(e){return this.fileSystem.joinPaths(e,"slots.d.ts")}isTypeScriptProject(){return this.packageManager.hasDirectDependency("typescript")}async getTypeScriptConfigPath(e=[]){let t=this.projectDirectory.get(),n=await this.importConfigLoader.load(t,{fileNames:["tsconfig.json"],sourcePaths:e.length===0?[t]:e});return n===null?null:n.matchedConfigPath}};var ke=class a{constructor(e=2){this.code="";this.indentationLevel=0;this.indentationSize=e;}indent(){return this.indentationLevel++,this}outdent(){return this.indentationLevel>0&&this.indentationLevel--,this}newLine(e=1){return this.code+=`
102
102
  `.repeat(e),this}write(e,t=true){return this.code+=this.indentCode(`${e}`)+(t?`
103
103
  `:""),this}appendString(e,t){return this.append(t+e.replace(new RegExp(t,"g"),`\\${t}`)+t)}appendIndentation(){return this.write("",false)}appendName(e,t=true){return this.code+=a.formatName(e,t),this}writeValue(e,t){return this.appendIndentation().appendValue(e,t)}append(e){return this.code+=this.indentCode(e,false),this}appendValue(e,t){let{delimiter:n,stringKeys:r=false}=t;switch(typeof e){case "string":{let i=e.replace(new RegExp(n,"g"),`\\${n}`);return this.append(`${n}${i}${n}`)}case "number":case "boolean":return this.append(`${e}`);case "object":{if(e===null)return this.append("null");if(Array.isArray(e)){if(e.length===0)return this.append("[]");this.append("[").newLine().indent();for(let o=0;o<e.length;o++)this.appendIndentation().appendValue(e[o],t),o<e.length-1&&this.append(", ").newLine();return this.outdent().newLine().write("]",false)}let i=Object.entries(e);if(i.length===0)return this.append("{}");this.append("{").newLine().indent();for(let o=0;o<i.length;o++){let[s,p]=i[o];this.appendIndentation(),r||!isIdentifier(s)?this.appendValue(s,t):this.append(s),this.append(": ").appendValue(p,t),o<i.length-1&&this.append(", ").newLine();}return this.outdent().newLine().write("}",false)}default:return this.append("undefined")}}indentCode(e,t=true){let n=" ".repeat(this.indentationLevel*this.indentationSize);return (t?n:"")+e.replace(/\n/g,`
104
104
  ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/[^a-z0-9]/gi,"_");return e.includes("_")?t?n[0].toUpperCase()+n.slice(1):n:n.replace(/(^[a-z_])|_([a-z])/gi,(r,i,o,s)=>t||s>0?(i??o).toUpperCase():(i??o).toLowerCase())}};function An(a){let e=a.split(/(?<![A-Z])(?=[A-Z])|_/),t=e[0];return [t[0].toUpperCase()+t.slice(1).toLowerCase(),...e.slice(1).map(i=>i.toLowerCase())].join(" ")}function is(a){return a.normalize("NFD").toLocaleLowerCase().replace(/(^[^a-z]+|[^a-z0-9_ &-]+)/ig,"").split(/[^a-z0-9]+/i).filter(e=>e!=="").join("-")}function mt(a){return Object.entries(a).sort(([,e],[,t])=>{let n=e.position??Number.MAX_SAFE_INTEGER,r=t.position??Number.MAX_SAFE_INTEGER;return n-r})}var En=class a{constructor({fileSystem:e,...t}){this.options=t,this.fileSystem=e;}generate(e){let t=this.generateSlotFile(e);return {files:[this.generatePageFile(e,t.path),t]}}generatePageFile(e,t){let n=this.createWriter();return this.writePageSnippet(n,e.definition.title??"Croct example",this.fileSystem.getRelativePath(this.fileSystem.getDirectoryName(this.options.pagePath),t).replace(/\\/g,"/")),{path:this.options.pagePath,language:"html",code:n.toString()}}writePageSnippet(e,t,n){e.write('<html lang="en">').write("<head>").indent().write('<meta charset="UTF-8">').write(`<title>${a.escapeEntities(t)}</title>`).write(`<script type="module" src="${n}"></script>`).outdent().write("</head>").write("<body>").indent().write(`<div id="${this.options.containerId}"></div>`).outdent().write("</body>").write("</html>",false);}generateSlotFile(e){let t=this.createWriter();return this.writeSlotSnippet(t,e),{path:this.options.slotPath,language:this.options.language,code:t.toString()}}writeSlotSnippet(e,t){e.write("import croct from '@croct/plug';"),e.newLine().write(`croct.plug({appId: '${this.options.appId}'});`).newLine(),this.renderListener(e,t);}renderListener(e,t){e.write("document.addEventListener('DOMContentLoaded', async () => {").indent(),e.write("const {content} = ",false).append(`await croct.fetch('${t.id}@${t.version}'`),this.options.fallbackContent!==void 0&&e.append(", {").indent().newLine().write("fallback: ",false).appendValue(this.options.fallbackContent,{delimiter:"'"}).newLine().outdent().write("}",false),e.append(");"),e.newLine(2).write(`document.querySelector('#${this.options.containerId}')`,false),this.options.language==="typescript"&&e.append("!"),e.append(".innerHTML = `").newLine().indent(),this.writeContentSnippet(e,t.definition,"content"),e.outdent().write("`;").outdent().write("});");}writeContentSnippet(e,t,n){switch(t.type){case "text":case "number":e.append(`\${${n}}`);break;case "boolean":t.label!==void 0?e.append(`\${${n} ? `).appendValue(t.label.true??"Yes",{delimiter:"'"}).append(" : ").appendValue(t.label.false??"No",{delimiter:"'"}).append("}"):e.append(`\${${n} ? 'Yes' : 'No'}`);break;case "list":{let r=t.itemLabel!==void 0?ut(t.itemLabel):"item";e.write("<ol>").indent().write(`\${${n}.map(${r} => \``).indent().write("<li>").indent();let i=a.isInline(t.items);i&&e.appendIndentation(),this.writeContentSnippet(e,t.items,r),i&&e.newLine(),e.outdent().write("</li>").outdent().write("`).join('')}").outdent().write("</ol>");break}case "structure":e.write("<ul>").indent();for(let[r,i]of mt(t.attributes))i.private!==true&&(i.optional===true&&(e.write(`\${${n}.${r} && \``),e.indent()),this.writeAttributeSnippet(e,i,`${n}.${r}`),i.optional===true&&(e.outdent(),e.write("`}")));e.outdent().write("</ul>");break;case "union":for(let[r,i]of Object.entries(t.types))e.write(`\${${n}._type === '${r}' && \``).indent(),this.writeContentSnippet(e,i,n),e.outdent().write("`}");break}}writeAttributeSnippet(e,t,n){let r=t.type,i=t.label!==void 0?a.escapeEntities(t.label).replace(/`/g,"\\`"):An(n.split(".").pop());switch(r.type){case "boolean":case "text":case "number":{e.write("<li>",false).append(`<strong>${i}:</strong> `),this.writeContentSnippet(e,r,n),e.append("</li>").newLine();break}default:e.write("<li>").indent().write(`<strong>${i}</strong>`),this.writeContentSnippet(e,r,n),e.outdent().write("</li>");break}}static isInline(e){return ["number","text","boolean"].includes(e.type)}static escapeEntities(e){return e.replace(/([&<>])/g,t=>({"&":"&amp;","<":"&lt;",">":"&gt;"})[t]??t)}createWriter(){return new ke(this.options.indentationSize)}};var On=class a extends Ve{constructor({bundlers:e,...t}){super(t),this.bundlers=e;}async generateSlotExampleFiles(e,t){let{configuration:n}=t,[r,i,o]=await Promise.all([this.isTypeScriptProject(),this.detectBundler(),this.workspaceApi.getApplication({organizationSlug:n.organization,workspaceSlug:n.workspace,applicationSlug:n.applications.development})]);if(o===null)throw new X(`Development application ${n.applications.development} not found.`,{reason:"not_found"});let s=await this.getPaths(n),p=this.fileSystem.joinPaths(s.examples,e.slug),l=new En({fileSystem:this.fileSystem,language:r?"typescript":"javascript",appId:o.publicId,fallbackContent:i===null?a.extractFallbackContent(e.content[t.configuration.defaultLocale],e.resolvedDefinition):void 0,containerId:"slot",slotPath:this.fileSystem.joinPaths(p,`slot.${r?"ts":"js"}`),pagePath:this.fileSystem.joinPaths(p,"index.html")}).generate({id:e.slug,version:e.version.major,definition:e.resolvedDefinition});return Promise.resolve(l.files)}static extractFallbackContent(e,t){switch(e.type){case "text":case "boolean":case "number":return e.value.type==="static"?e.value.value:e.value.default!==void 0?e.value.default:null;case "list":return e.items.map(n=>a.extractFallbackContent(n,t.items));case "structure":{let n=t,r={};for(let[i,o]of mt(n.attributes)){if(o.private===true)continue;let s=a.extractFallbackContent(e.attributes[i],n.attributes[i].type);(o.optional!==true||s!==null)&&(r[i]=s);}return r}}}async detectBundler(){for(let e of this.bundlers)if(await this.packageManager.hasDirectDependency(e))return Promise.resolve(e);return Promise.resolve(null)}getInstallationPlan(e){return Promise.resolve({tasks:[],dependencies:["@croct/plug"],configuration:e.configuration})}};var Le=class a{constructor(e,t){this.fileSystem=e,this.path=t;}getName(){return this.fileSystem.getBaseName(this.path)}exists(){return this.fileSystem.exists(this.path)}async hasVariable(e){let t=await this.read();if(t==="")return false;let n=a.escapeRegex(e);return new RegExp(`^${n}\\s*=`,"m").test(t)}async setVariables(e){let t=await this.read();try{for(let[n,r]of Object.entries(e))await this.setVariable(n,r);}catch(n){throw await this.write(t),n}}async setVariable(e,t){let n=await this.read(),r=a.escapeRegex(e);if(n==="")return this.write(`${e}=${t}`);let i=`${e}=${t}`,o=n.replace(new RegExp(`${r}\\s*=\\s*((?!['"\`]).*$|\`(?:\\.|[^\`])*\`|'(?:\\.|[^'])*'|"(?:\\.|[^"])*")`,"m"),i);return o!==n||o.includes(i)?this.write(o):this.write(`${n}${n.endsWith(`
105
105
  `)?"":`
106
- `}${e}=${t}`)}async write(e){await this.fileSystem.writeTextFile(this.path,e,{overwrite:true});}async read(){return await this.exists()?this.fileSystem.readTextFile(this.path):""}static escapeRegex(e){return e.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&")}};var gt=class a{constructor({fileSystem:e,...t}){this.options=t,this.fileSystem=e;}generate(e){let t=a.replaceVariables(this.options.slotFilePath,e.id),n=a.replaceVariables(this.options.slotComponentName,e.id);return {files:[this.generatePageFile(e,{name:n,path:t,importPath:a.replaceVariables(this.options.slotImportPath,e.id),definition:e}),this.generateSlotFile(e,t,n)]}}generatePageFile(e,t){let n=this.createWriter(),r=a.replaceVariables(this.options.pageFilePath,e.id),i=a.replaceVariables(this.options.pageComponentName,e.id);return this.writePageSnippet(n,i,t),{path:r,language:this.options.language,code:n.toString()}}generateSlotFile(e,t,n){let r=this.createWriter();return this.writeSlotSnippet(r,e,n),{path:t,language:this.options.language,code:r.toString()}}writePageSnippet(e,t,n){this.writePageHeader(e,n),e.newLine(),this.writePageSignature(e,t),e.indent().write("return (").indent(),this.hasSuspenseBoundary()&&e.write('<Suspense fallback="\u2728 Personalizing...">').indent(),this.writeSlotRendering(e,n.name),this.hasSuspenseBoundary()&&e.outdent().write("</Suspense>"),e.outdent().write(");").outdent().write("}",false);}writeSlotRendering(e,t){e.write(`<${t} />`);}writePageSignature(e,t){e.write(this.options.language==="tsx"?`export default function ${t}(): ReactElement {`:`export default function ${t}() {`);}writePageHeader(e,t){switch(this.options.language){case "jsx":this.hasSuspenseBoundary()&&e.write("import {Suspense} from 'react';");break;case "tsx":e.write(this.hasSuspenseBoundary()?"import {type ReactElement, Suspense} from 'react';":"import type {ReactElement} from 'react';");break}e.write(`import ${t.name} from '${t.importPath}';`);}writeSlotSnippet(e,t,n){this.writeSlotHeader(e,t),this.writeSlotSignature(e,t,n),e.indent(),this.writeSlotFetch(e,t),e.write("return (").indent(),this.writeRenderingSnippet(e,t.definition,this.options.contentVariable),e.outdent().write(");").outdent().write("};");}writeSlotSignature(e,t,n){e.write(`export default ${this.isSlotFetchAsync()?"async ":""}function ${n}`,false),this.appendSlotParams(e,t),this.options.language==="tsx"&&e.append(`: ${this.isSlotFetchBlocking()?"Promise<ReactElement>":"ReactElement"}`),e.write(" {");}appendSlotParams(e,t){e.append("()");}writeRenderingSnippet(e,t,n){switch(t.type){case "number":case "text":e.append(`{${n}}`);break;case "boolean":t.label!==void 0?e.append(`{${n} ? `).appendValue(t.label.true??"Yes",{delimiter:"'"}).append(" : ").appendValue(t.label.false??"No",{delimiter:"'"}).append("}"):e.append(`{${n} ? 'Yes' : 'No'}`);break;case "list":{let r=t.itemLabel!==void 0?ut(t.itemLabel):"item";e.write("<ol>").indent().write(`{${n}.map((${r}, index) => (`).indent().write("<li key={index}>").indent();let i=a.isInline(t.items);i&&e.appendIndentation(),this.writeRenderingSnippet(e,t.items,r),i&&e.newLine(),e.outdent().write("</li>").outdent().write("))}").outdent().write("</ol>");break}case "structure":e.write("<ul>").indent();for(let[r,i]of mt(t.attributes))i.private!==true&&(i.optional===true&&(e.write(`{${n}.${r} && (`),e.indent()),this.writeAttributeSnippet(e,{name:r,...i},n),i.optional===true&&(e.outdent(),e.write(")}")));e.outdent().write("</ul>");break;case "union":{let r=!n.includes(".");r&&e.write("<>").indent();for(let[i,o]of Object.entries(t.types))e.write(`{${n}._type === '${i}' && (`).indent(),this.writeRenderingSnippet(e,o,n),e.outdent().write(")}");r&&e.outdent().write("</>");break}}}writeAttributeSnippet(e,t,n){let r=t.type,i=a.escapeEntities(t.label??An(t.name));switch(r.type){case "boolean":case "text":case "number":{e.write("<li>",false).append(`<strong>${i}:</strong> `),this.writeRenderingSnippet(e,r,`${n}.${t.name}`),e.append("</li>").newLine();break}default:e.write("<li>").indent().write(`<strong>${i}</strong>`),this.writeRenderingSnippet(e,r,`${n}.${t.name}`),e.outdent().write("</li>");break}}static escapeEntities(e){return e.replace(/([&"<>])/g,t=>({"&":"&amp;",'"':"&quot;","<":"&lt;",">":"&gt;"})[t]??t)}createWriter(){return new ke(this.options.indentationSize)}static replaceVariables(e,t){return e.replace(/%name%/g,a.formatName(t,true)).replace(/%slug%/g,is(t))}static formatName(e,t=false){return ke.formatName(e,t)}static isInline(e){return ["number","text","boolean"].includes(e.type)}};var ft=class extends gt{writeSlotHeader(e){switch(this.options.language){case "jsx":e.write("import {useContent} from '@croct/plug-react';");break;case "tsx":e.write("import type {ReactElement} from 'react';"),e.write("import {useContent} from '@croct/plug-react';");break}e.newLine();}writeSlotFetch(e,t){let n=this.options.contentVariable;e.write(`const ${n} = useContent('${t.id}@${t.version}');`).newLine();}isSlotFetchAsync(){return false}isSlotFetchBlocking(){return false}hasSuspenseBoundary(){return false}};var Rn=class a extends Ve{constructor(e){super(e),this.codemod=e.codemod,this.bundlers=e.bundlers,this.importResolver=e.importResolver;}async generateSlotExampleFiles(e,t){let n=await this.isTypeScriptProject(),r=await this.getPaths(t.configuration),i=this.fileSystem.joinPaths(r.components,`%slug%${n?".tsx":".jsx"}`),o=this.fileSystem.joinPaths(r.examples,`%slug%-example${n?".tsx":".jsx"}`);return new ft({fileSystem:this.fileSystem,language:await this.isTypeScriptProject()?"tsx":"jsx",contentVariable:"content",slotImportPath:await this.importResolver.getImportPath(i,this.fileSystem.getDirectoryName(o)),slotFilePath:i,slotComponentName:"%name%",pageFilePath:o,pageComponentName:"%name%Example"}).generate({id:e.slug,version:e.version.major,definition:e.resolvedDefinition}).files}async getInstallationPlan(e){let{configuration:t}=e,n=await this.getProjectInfo();return {dependencies:["@croct/plug-react"],tasks:this.getInstallationTasks({...e,project:n}),configuration:t}}async getProjectInfo(){let e="src",t=await this.getEnvVarProperty(),n=this.projectDirectory.get();return {typescript:await this.isTypeScriptProject(),sourceDirectory:e,provider:{file:await this.locateFile(...["App","main","index"].flatMap(r=>["js","jsx","ts","tsx"].map(i=>`${r}.${i}`)).map(r=>this.fileSystem.joinPaths(e,r)))},env:t===null?void 0:{property:t,productionFile:new Le(this.fileSystem,this.fileSystem.joinPaths(n,".env.production")),developmentFile:new Le(this.fileSystem,this.fileSystem.joinPaths(n,".env.development"))}}}getInstallationTasks(e){let t=[],n=e.project.env,{configuration:r}=e,i=null,o=()=>(i===null&&(i=Promise.all([this.workspaceApi.getApplication({organizationSlug:r.organization,workspaceSlug:r.workspace,applicationSlug:r.applications.development}),r.applications.production===void 0?null:this.workspaceApi.getApplication({organizationSlug:r.organization,workspaceSlug:r.workspace,applicationSlug:r.applications.production})]).then(([s,p])=>s===null?Promise.reject(new X(`Development application ${r.applications.development} not found`,{reason:"not_found"})):{development:s.publicId,production:p?.publicId})),i);if(n!==void 0){let{developmentFile:s,productionFile:p,property:c}=n,l=c.split(".").pop();t.push({title:"Setup environment variables",task:async u=>{u.update("Setting up environment variables");try{let g=await o();await Promise.all([s.setVariable(l,g.development),g.production===void 0?Promise.resolve():p.setVariable(l,g.production)]),u.confirm("Environment variables updated");}catch(g){u.alert("Failed to update environment variables",d.formatMessage(g));}}});}return t.push({title:"Configure provider",task:async s=>{s.update("Configuring provider");let p=e.project.provider.file;try{p===null?s.alert("No root component found"):(s.update("Configuring provider"),await this.installProvider(p,{props:{appId:a.getAppIdProperty(await o(),n?.property)}}),s.confirm("Provider configured"));}catch(c){s.alert("Failed to install provider",d.formatMessage(c));}}}),t}async installProvider(e,t){await this.codemod.provider.apply(this.fileSystem.joinPaths(this.projectDirectory.get(),e),t);}async getEnvVarProperty(){for(let e of this.bundlers)if(await this.packageManager.hasDirectDependency(e.package))return `${e.prefix}CROCT_APP_ID`;return null}static getAppIdProperty(e,t){return t!==void 0?{type:"reference",path:t.split(".")}:e.production===void 0?{type:"literal",value:e.development}:{type:"ternary",condition:{operator:"===",left:{type:"reference",path:["process","env","NODE_ENV"]},right:{type:"literal",value:"production"}},consequent:{type:"literal",value:e.production},alternate:{type:"literal",value:e.development}}}};var We=class a extends d{constructor(e,t={}){super(e,t),Object.setPrototypeOf(this,a.prototype);}},Tn=class a extends We{constructor(e){super(e),Object.setPrototypeOf(this,a.prototype);}};function Ae(a,e,t){try{return parse$1(a,{...t,sourceType:"module",plugins:[...e,...t?.plugins??[]]})}catch{throw new Tn("The source code contains syntax errors.")}}function os(a){let e={locales:Array()},t;try{t=Ae(a,["jsx","typescript"]);}catch{return {i18n:e}}return traverse(t,{ObjectProperty:n=>{if(va(n.node.key)!=="i18n")return n.skip();let r=n.node.value;if(!f.isObjectExpression(r))return n.stop();for(let i of r.properties)if(f.isObjectProperty(i)&&va(i.key)==="locales"){let o=i.value;if(f.isArrayExpression(o))for(let s of o.elements)s!==null&&f.isStringLiteral(s)&&e.locales.push(s.value);}else if(f.isObjectProperty(i)&&va(i.key)==="defaultLocale"){let o=i.value;o!==null&&f.isStringLiteral(o)&&(e.defaultLocale=o.value);}return n.stop()}}),{i18n:e}}function va(a){return f.isIdentifier(a)?a.name:f.isStringLiteral(a)?a.value:null}var Dn=class extends gt{constructor({fileSystem:e,router:t,...n}){super({fileSystem:e,contentVariable:t==="app"?"content":"props",...n}),this.nextOptions={router:t};}writeSlotHeader(e,t){switch(this.options.language){case "jsx":this.nextOptions.router==="app"&&(e.write("import {fetchContent} from '@croct/plug-next/server';"),e.newLine());break;case "tsx":if(e.write("import type {ReactElement} from 'react';"),this.nextOptions.router==="app"&&e.write("import {fetchContent} from '@croct/plug-next/server';"),this.nextOptions.router==="page"){e.write("import type {SlotContent} from '@croct/plug-next';"),e.newLine();let n=ke.formatName(t.id,true);e.write(`export type ${n}Props = SlotContent<'${t.id}@${t.version}'>;`);}e.newLine();break}}writeSlotFetch(e,t){if(this.nextOptions.router==="app"){let n=this.options.contentVariable;e.write(`const {${n}} = await fetchContent('${t.id}@${t.version}');`).newLine();}}writePageHeader(e,t){if(this.nextOptions.router==="app")return super.writePageHeader(e,t);let n=`${t.definition.id}@${t.definition.version}`;switch(this.options.language){case "jsx":e.write("import {fetchContent} from '@croct/plug-next/server';").write(`import ${t.name} from '${t.importPath}';`),e.newLine().write("export async function getServerSideProps(context) {").indent().write("return {").indent().write(`props: await fetchContent('${n}', {`).indent().write("route: context,").outdent().write("}),").outdent().write("}").outdent().write("}");break;case "tsx":e.write("import type {ReactElement} from 'react';"),e.write("import type {GetServerSideProps} from 'next';"),e.write("import {fetchContent} from '@croct/plug-next/server';"),e.write(`import ${t.name}, {type ${t.name}Props} from '${t.importPath}';`),e.newLine().write("type PageProps = {").indent().write(`content: ${t.name}Props,`).outdent().write("};").newLine().write("export const getServerSideProps: ",false).write("GetServerSideProps<PageProps> = async context => ({").indent().write(`props: await fetchContent('${n}', {`).indent().write("route: context,").outdent().write("}),").outdent().write("});");break}}writePageSignature(e,t){switch(this.nextOptions.router){case "app":super.writePageSignature(e,t);break;case "page":{e.write(this.options.language==="tsx"?"export default function Page({content}: PageProps): ReactElement {":"export default function Page({content}) {");break}}}appendSlotParams(e,t){if(this.nextOptions.router!=="page")return super.appendSlotParams(e,t);let n=ke.formatName(t.id,true),r=this.options.contentVariable;if(this.options.language==="jsx"){e.append(`(${r})`);return}e.append(`(${r}: ${n}Props)`);}writeSlotRendering(e,t){switch(this.nextOptions.router){case "app":super.writeSlotRendering(e,t);break;case "page":{e.write(`<${t} {...content} />`);break}}}isSlotFetchAsync(){return this.nextOptions.router==="app"}isSlotFetchBlocking(){return this.nextOptions.router==="app"}hasSuspenseBoundary(){return false}};var ee=class a extends d{constructor(e,t=[],n={}){super(e,{...n,details:n.details??t.map(r=>r.detail??r.title)}),Object.setPrototypeOf(this,a.prototype),this.problems=t;}isErrorType(e){return this.problems.some(t=>t.type===e)}isAccessDenied(e){return this.problems.some(t=>t.type==="https://croct.help/api/admin#access-denied"&&(e===void 0||t.reason===e))}};var ge=(t=>(t.DEVELOPMENT="DEVELOPMENT",t.PRODUCTION="PRODUCTION",t))(ge||{});(n=>{function a(r){switch(r){case "DEVELOPMENT":return "Development";case "PRODUCTION":return "Production"}}n.getLabel=a;function e(){return Object.values(n).filter(r=>typeof r=="string")}n.all=e;function t(r){let i=r.toUpperCase();if(!n.all().includes(i))throw new Error(`Invalid environment value "${r}".`);return i}n.fromValue=t;})(ge||={});var ae=(n=>(n.READ_RESOURCES="RESOURCE_READ_ACCESS",n.ISSUE_TOKEN="TOKEN_ISSUE",n.EXPORT_DATA="DATA_EXPORT",n))(ae||{});(n=>{function a(r){switch(r){case "RESOURCE_READ_ACCESS":return "Read resources";case "TOKEN_ISSUE":return "Issue tokens";case "DATA_EXPORT":return "Export data"}}n.getLabel=a;function e(){return Object.values(n).filter(r=>typeof r=="string")}n.all=e;function t(r){let i=r.toUpperCase();if(!n.all().includes(i))throw new Error(`Invalid permission value "${r}".`);return i}n.fromValue=t;})(ae||={});var Mn=class extends Ve{constructor(e){super(e),this.codemod=e.codemod,this.importResolver=e.importResolver,this.userApi=e.userApi,this.applicationApi=e.applicationApi;}async generateSlotExampleFiles(e,t){let[n,r,i]=await Promise.all([this.detectRouter(),this.isTypeScriptProject(),this.isFallbackMode()]),o=await this.isTypeScriptProject(),s=await this.getPaths(t.configuration),p=this.fileSystem.joinPaths(s.components,`%slug%${o?".tsx":".jsx"}`),c=this.fileSystem.joinPaths(s.examples,"%slug%"),l=await this.importResolver.getImportPath(p,c),u=r?"tsx":"jsx";return (i?new ft({fileSystem:this.fileSystem,language:u,contentVariable:"content",slotImportPath:l,slotFilePath:p,slotComponentName:"%name%",pageFilePath:this.fileSystem.joinPaths(c,`index${o?".tsx":".jsx"}`),pageComponentName:"Page"}):new Dn({fileSystem:this.fileSystem,router:n==="page"?"page":"app",language:u,slotImportPath:l,slotFilePath:p,slotComponentName:"%name%",pageFilePath:this.fileSystem.joinPaths(c,`${n==="page"?"index":"page"}${r?".tsx":".jsx"}`),pageComponentName:"Page"})).generate({id:e.slug,version:e.version.major,definition:e.resolvedDefinition}).files}async getInstallationPlan(e){let{configuration:t,output:n}=e,[{i18n:r},i]=await Promise.all([this.getConfig(),this.getProjectInfo()]);i.fallbackMode&&n.announce({semantics:"warning",title:"Fallback mode",message:"Next.js SDK requires version 13 or newer, so React SDK will be installed instead."});let o=t.locales.filter(c=>r.locales.includes(c)||c===t.defaultLocale),s=o.length>0?o:r.locales,p=r.defaultLocale!==void 0&&s.includes(r.defaultLocale)?r.defaultLocale:t.defaultLocale;return {dependencies:[i.fallbackMode?"@croct/plug-react":"@croct/plug-next"],tasks:this.getInstallationTasks({...e,project:i}),configuration:{...t,locales:s,defaultLocale:p,paths:{...t.paths,examples:i.pageDirectory}}}}async getProjectInfo(){let[e,t,n]=await Promise.all([this.isTypeScriptProject(),this.getPageDirectory(),this.isFallbackMode()]),r={typescript:e,router:await this.detectRouter(t),sourceDirectory:t.startsWith("src")?"src":".",pageDirectory:t},[i,o]=await Promise.all([this.locateFile(...["middleware.js","middleware.ts"].map(c=>this.fileSystem.joinPaths(r.sourceDirectory,c))),this.locateFile(...(r.router==="app"?[this.fileSystem.joinPaths("app","layout"),this.fileSystem.joinPaths("app","layout")]:[this.fileSystem.joinPaths("pages","_app"),this.fileSystem.joinPaths("pages","_app")]).flatMap(c=>["js","jsx","ts","tsx"].map(l=>this.fileSystem.joinPaths(r.sourceDirectory,`${c}.${l}`))))]),s=r.typescript?"ts":"js",p=this.projectDirectory.get();return {...r,fallbackMode:n,env:{localFile:new Le(this.fileSystem,this.fileSystem.joinPaths(p,".env.local")),developmentFile:new Le(this.fileSystem,this.fileSystem.joinPaths(p,".env.development")),productionFile:new Le(this.fileSystem,this.fileSystem.joinPaths(p,".env.production"))},middleware:{file:i??this.fileSystem.joinPaths(r.sourceDirectory,`middleware.${s}`)},provider:{file:o??(r.router==="app"?this.fileSystem.joinPaths(r.sourceDirectory,"app",`layout.${s}x`):this.fileSystem.joinPaths(r.sourceDirectory,"pages",`_app.${s}x`))}}}getInstallationTasks(e){let t=[];return e.project.fallbackMode||t.push({title:"Configure middleware",task:async n=>{n.update("Configuring middleware");try{await this.updateCode(this.codemod.middleware,e.project.middleware.file),n.confirm("Middleware configured");}catch(r){n.alert("Failed to install middleware",d.formatMessage(r));}}}),t.push({title:"Configure provider",task:async n=>{n.update("Configuring provider");try{await this.installProvider({...e,notifier:n}),n.confirm("Provider configured");}catch(r){n.alert("Failed to install provider",d.formatMessage(r));}}}),t.push({title:"Setup environment variables",task:async n=>{n.update("Setting up environment variables");try{await this.updateEnvVariables({...e,notifier:n}),n.confirm("Environment variables updated");}catch(r){n.alert("Failed to update .env.local",d.formatMessage(r));}}}),t}installProvider(e){return this.updateCode(this.getProviderCodemod(e),e.project.provider.file,{typescript:e.project.typescript})}getProviderCodemod(e){return e.project.fallbackMode?this.codemod.fallbackProvider:e.project.router==="app"?this.codemod.appRouterProvider:this.codemod.pageRouterProvider}async updateCode(e,t,n){await e.apply(this.fileSystem.joinPaths(this.projectDirectory.get(),t),n);}async updateEnvVariables(e){let{project:{env:t},configuration:n,notifier:r}=e;r.update("Loading information");let[i,o]=await Promise.all([this.workspaceApi.getApplication({organizationSlug:n.organization,workspaceSlug:n.workspace,applicationSlug:n.applications.development}),n.applications.production===void 0?null:this.workspaceApi.getApplication({organizationSlug:n.organization,workspaceSlug:n.workspace,applicationSlug:n.applications.production})]);if(i===null)throw new X(`Development application \`${n.applications.development}\` not found.`,{reason:"not_found"});if(!await t.localFile.hasVariable("CROCT_API_KEY")&&e.skipApiKeySetup!==true){let s=await this.userApi.getUser();r.update("Creating API key");let p;try{p=await this.applicationApi.createApiKey({organizationSlug:n.organization,workspaceSlug:n.workspace,applicationSlug:i.slug,name:`${s.username} CLI`,permissions:["TOKEN_ISSUE"]});}catch(c){throw c instanceof d?new X(c instanceof ee&&c.isAccessDenied()?"Your user does not have permission to create an API key":c.message,c.help):c}await t.localFile.setVariables({CROCT_API_KEY:p.secret});}await Promise.all([t.developmentFile.setVariables({NEXT_PUBLIC_CROCT_APP_ID:i.publicId}),o===null?Promise.resolve():t.productionFile.setVariables({NEXT_PUBLIC_CROCT_APP_ID:o.publicId})]);}async detectRouter(e){return (e??await this.getPageDirectory()).endsWith("pages")?"page":"app"}async getPageDirectory(){return await this.locateFile("app",this.fileSystem.joinPaths("src","app"),"pages",this.fileSystem.joinPaths("src","pages"))??"app"}async getConfig(){let e=["js","mjs","ts","mts"].map(n=>`next.config.${n}`),t=await this.readFile(...e).catch(()=>null);return t===null?{i18n:{locales:[],defaultLocale:""}}:os(t)}isFallbackMode(){return this.packageManager.hasDirectDependency("next","<=13")}};var Xe=(n=>(n.NEXTJS="nextjs",n.REACT="react",n.JAVASCRIPT="javascript",n))(Xe||{});(e=>{function a(t){switch(t){case "nextjs":return "Next.js";case "react":return "React";case "javascript":return "JavaScript"}}e.getName=a;})(Xe||={});var Nn=class a{constructor(e){this.config=e;}async execute(e){let{configurationManager:t,platformProvider:n,sdkProvider:r,io:{output:i}}=this.config,o=e.override!==true&&await t.isInitialized()?{...await t.loadPartial()}:null,s=await n.get(),p=s!==null?`${Xe.getName(s)} project`:"project";i.break(),i.announce({semantics:"neutral",title:"\u{1F44B} Welcome to Croct",alignment:"center",message:`Let's configure your ${p} to get started!`}),i.break();let c=await this.getOrganization({new:e.new==="organization"},e.new==="organization"?void 0:e.organization??o?.organization),l=await this.getWorkspace({organization:c,new:c.new!==true&&e.new==="workspace"},e.new==="workspace"||c.new===true?void 0:e.workspace??o?.workspace),u={organization:c,workspace:l,platform:s??"javascript",new:l.new!==true&&e.new==="application"},g=await this.getApplication({...u,environment:"DEVELOPMENT"},e.new!==void 0||l.new===true?void 0:e.devApplication??o?.applications?.development),y={organization:c.slug,workspace:l.slug,applications:{development:g.slug},defaultLocale:l.defaultLocale,locales:[...new Set([...o?.locales??[],...l.locales])],slots:o?.slots??{},components:o?.components??{},paths:o?.paths??{}},v=await this.resolveApplication({...u,environment:"PRODUCTION"},e.new!==void 0?void 0:e.prodApplication??o?.applications?.production);if(v!==null&&(y.applications.production=v.slug),o!==null){await t.update(y),i.confirm("Project configuration updated");return}let A=await r.get();if(A===null){await t.update(y),i.warn("No suitable SDK found, skipping project configuration");return}await t.update(await this.configure(A,y,e.skipApiKeySetup===true));}async getOrganization(e,t){let{form:n,api:r}=this.config,i=t===void 0?await n.organization.handle(e):await r.user.getOrganization(t).catch(o=>{if(o instanceof ee&&o.isAccessDenied())return null;throw o});if(i===null)throw new d(`No organization found with slug "${t}".`,{reason:"invalid_input"});return i}async getWorkspace(e,t){let{form:n,api:r}=this.config,i=t===void 0?await n.workspace.handle(e):await r.organization.getWorkspace({organizationSlug:e.organization.slug,workspaceSlug:t}).catch(o=>{if(o instanceof ee&&o.isAccessDenied())return null;throw o});if(i===null)throw new d(`No workspace found with slug "${t}".`,{reason:"invalid_input"});return i}async resolveApplication(e,t){let{api:n}=this.config,r=e.workspace.website??e.organization.website??void 0,i=r!==void 0&&new URL(r).hostname!=="localhost";if(e.environment==="DEVELOPMENT"||i||t!==void 0||e.new===true)return this.getApplication(e,t);let o=n.workspace.getApplications({organizationSlug:e.organization.slug,workspaceSlug:e.workspace.slug});for(let s of await o)if(s.environment===e.environment)return this.getApplication(e,t);return null}async getApplication(e,t){let{form:n,api:r}=this.config,i=t===void 0?await n.application.handle(e):await r.workspace.getApplication({organizationSlug:e.organization.slug,workspaceSlug:e.workspace.slug,applicationSlug:t}).catch(o=>{if(o instanceof ee&&o.isAccessDenied())return null;throw o});if(i===null)throw new d(`No application found with slug "${t}".`,{reason:"invalid_input"});if(i.environment!==e.environment)throw new d(`No ${ge.getLabel(e.environment).toUpperCase()} application found with slug "${t}".`,{reason:"invalid_input"});return i}async configure(e,t,n){let{skipConfirmation:r}=this.config,i=await e.setup({input:this.config.io.input===void 0||await r.get()?void 0:this.config.io.input,output:this.config.io.output,skipApiKeySetup:n,configuration:t});return a.canonicalizePaths(i)}static canonicalizePaths(e){return e.paths===void 0?e:{...e,paths:Object.fromEntries(Object.entries(e.paths).map(([t,n])=>[t,a.canonicalizePath(n)]))}}static canonicalizePath(e){return e.replace(/\\/g,"/")}};var zn=class{constructor(e){this.authenticator=e.authenticator;}async execute(e){await this.authenticator.logout(),await this.authenticator.login(e);}};var jt=class{constructor({output:e,authenticator:t}){this.authenticator=t,this.output=e;}async execute(){await this.authenticator.logout(),this.output.confirm("Logged out");}};var Ie=class a extends d{constructor(e,t={}){super(e,{...t,reason:t.reason??"invalid_configuration"}),Object.setPrototypeOf(this,a.prototype);}};var $n=class a{static{this.CONFIGURATION_SCHEMA="https://schema.croct.com/json/v1/project.json";}constructor({fileSystem:e,projectDirectory:t,fullValidator:n,partialValidator:r}){this.fileSystem=e,this.projectDirectory=t,this.fullValidator=n,this.partialValidator=r;}async isInitialized(e="any"){if(e==="any")return this.fileSystem.exists(this.getConfigurationFilePath());let t=e==="full"?this.fullValidator:this.partialValidator;try{return (await this.loadConfigurationFile(t)).configuration!==null}catch(n){if(n instanceof Ie)return false;throw n}}async load(){let{configuration:e}=await this.loadConfigurationFile(this.fullValidator);if(e===null)throw new Ie("Project configuration not found.",{reason:"not_found",suggestions:["Run `init` command to initialize the project"]});return e}async loadPartial(){let e={};try{e=(await this.loadConfigurationFile(this.partialValidator)).configuration??{};}catch(t){if(!(t instanceof Ie))throw t}return e}async update(e){return this.updateConfigurationFile(await this.validateConfiguration(this.fullValidator,e))}async updateConfigurationFile(e){let t=await this.loadConfigurationFile(this.partialValidator),r=this.applyConfigurationChanges(t,e).toString({indentationCharacter:"space",object:{indentationSize:2,leadingIndentation:true,trailingIndentation:true,entryIndentation:true,colonSpacing:true,commaSpacing:true},array:{indentationSize:2,entryIndentation:true,leadingIndentation:true,trailingIndentation:true,colonSpacing:true,commaSpacing:true}});try{await this.fileSystem.writeTextFile(t.path,r,{overwrite:!0});}catch{throw new Error(`Unable to write configuration file ${t.path}.`)}return e}applyConfigurationChanges(e,t){if(e.configuration===null||e.source===null)return JsonObjectNode.of({$schema:a.CONFIGURATION_SCHEMA,...t});let n=JsonParser.parse(e.source,JsonObjectNode);return n.update({$schema:n.has("$schema")?n.get("$schema").toJSON():void 0,...t}).cast(JsonObjectNode)}async loadConfigurationFile(e){let t={path:this.getConfigurationFilePath(),source:null,configuration:null},n;try{t.source=await this.fileSystem.readTextFile(t.path),n=JsonParser.parse(t.source).toJSON();}catch{return t}return n!==null&&(t.configuration=await this.validateConfiguration(e,n,t),t.configuration?.$schema!==void 0&&delete t.configuration?.$schema),t}getConfigurationFilePath(){return this.fileSystem.joinPaths(this.projectDirectory.get(),"croct.json")}async validateConfiguration(e,t,n){let r=await e.validate(t);if(!r.valid){let i=r.violations[0];throw new Ie("The project configuration is invalid.",{details:[...n!==void 0?[`File: file://${n.path.replace(/\\/g,"/")}`]:[],`Cause: ${i.message}`,`Violation path: ${i.path}`]})}return r.data}};var Ut=class{constructor(e){this.configuration=e;}async execute(e,...[t]){let{tokenProvider:n,endpoint:r}=this.configuration,i=n!==void 0?await n.getToken():null,o=await fetch(r,{method:"POST",headers:{accept:"application/json","content-type":"application/json",...i!==null?{Authorization:`Bearer ${i}`}:{}},body:JSON.stringify({query:e,variables:t})});return o.json().then(s=>{let{data:p,errors:c}=s;if(c!==void 0)throw new ee(c[0].message.replace(/"/g,"`"),c.map(({extensions:l})=>({...l,detail:l.detail?.replace(/"/g,"`")})));return {data:p,headers:o.headers}})}};function Pa(a,e){return a.slice(0,a.indexOf("-",e-1)===e-1?e-1:e)}function*Vt({baseName:a,alwaysSuffixed:e=false}){let t=a.normalize("NFD").toLowerCase().replace(/[^a-z ]/g,"").trim().split(/\s+/);t.length===0&&t.push(String.fromCharCode(97+Math.floor(Math.random()*26))+Math.random().toString(36).substring(2,14));let n=t.slice(0,2).join("-");for(e||(yield Pa(n,30),n.length<29&&t.length>2&&(yield Pa(t.join("-"),30)));;){let r=Math.floor(Math.random()*1e4).toString();yield `${Pa(n,30-r.length-1)}-${r}`;}}function Ye(a){let{baseName:e,query:t,client:n,alwaysSuffixed:r}=a;return Vc({baseName:e,alwaysSuffixed:r},async i=>{let o=[i.next().value,i.next().value,i.next().value],{data:{checkAvailability:s}}=await n.execute(t,{...a.variables??{},slugFirstOption:o[0],slugSecondOption:o[1],slugThirdOption:o[2]}),p=[s.slugFirstOption,s.slugSecondOption,s.slugThirdOption];return o.find((c,l)=>p[l])??null})}async function Vc(a,e){let t=Vt(a),n;do n=await e(t);while(n===null);return n}var E=class extends String{constructor(e,t){super(e),this.value=e,this.__meta__=t;}toString(){return this.value}},ss=new E(`
106
+ `}${e}=${t}`)}async write(e){await this.fileSystem.writeTextFile(this.path,e,{overwrite:true});}async read(){return await this.exists()?this.fileSystem.readTextFile(this.path):""}static escapeRegex(e){return e.replace(/[-/\\^$*+?.()|[\]{}]/g,"\\$&")}};var gt=class a{constructor({fileSystem:e,...t}){this.options=t,this.fileSystem=e;}generate(e){let t=a.replaceVariables(this.options.slotFilePath,e.id),n=a.replaceVariables(this.options.slotComponentName,e.id);return {files:[this.generatePageFile(e,{name:n,path:t,importPath:a.replaceVariables(this.options.slotImportPath,e.id),definition:e}),this.generateSlotFile(e,t,n)]}}generatePageFile(e,t){let n=this.createWriter(),r=a.replaceVariables(this.options.pageFilePath,e.id),i=a.replaceVariables(this.options.pageComponentName,e.id);return this.writePageSnippet(n,i,t),{path:r,language:this.options.language,code:n.toString()}}generateSlotFile(e,t,n){let r=this.createWriter();return this.writeSlotSnippet(r,e,n),{path:t,language:this.options.language,code:r.toString()}}writePageSnippet(e,t,n){this.writePageHeader(e,n),e.newLine(),this.writePageSignature(e,t),e.indent().write("return (").indent(),this.hasSuspenseBoundary()&&e.write('<Suspense fallback="\u2728 Personalizing...">').indent(),this.writeSlotRendering(e,n.name),this.hasSuspenseBoundary()&&e.outdent().write("</Suspense>"),e.outdent().write(");").outdent().write("}",false);}writeSlotRendering(e,t){e.write(`<${t} />`);}writePageSignature(e,t){e.write(this.options.language==="tsx"?`export default function ${t}(): ReactElement {`:`export default function ${t}() {`);}writePageHeader(e,t){switch(this.options.language){case "jsx":this.hasSuspenseBoundary()&&e.write("import {Suspense} from 'react';");break;case "tsx":e.write(this.hasSuspenseBoundary()?"import {type ReactElement, Suspense} from 'react';":"import type {ReactElement} from 'react';");break}e.write(`import ${t.name} from '${t.importPath}';`);}writeSlotSnippet(e,t,n){this.writeSlotHeader(e,t),this.writeSlotSignature(e,t,n),e.indent(),this.writeSlotFetch(e,t),e.write("return (").indent(),this.writeRenderingSnippet(e,t.definition,this.options.contentVariable),e.outdent().write(");").outdent().write("};");}writeSlotSignature(e,t,n){e.write(`export default ${this.isSlotFetchAsync()?"async ":""}function ${n}`,false),this.appendSlotParams(e,t),this.options.language==="tsx"&&e.append(`: ${this.isSlotFetchBlocking()?"Promise<ReactElement>":"ReactElement"}`),e.write(" {");}appendSlotParams(e,t){e.append("()");}writeRenderingSnippet(e,t,n){switch(t.type){case "number":case "text":e.append(`{${n}}`);break;case "boolean":t.label!==void 0?e.append(`{${n} ? `).appendValue(t.label.true??"Yes",{delimiter:"'"}).append(" : ").appendValue(t.label.false??"No",{delimiter:"'"}).append("}"):e.append(`{${n} ? 'Yes' : 'No'}`);break;case "list":{let r=t.itemLabel!==void 0?ut(t.itemLabel):"item";e.write("<ol>").indent().write(`{${n}.map((${r}, index) => (`).indent().write("<li key={index}>").indent();let i=a.isInline(t.items);i&&e.appendIndentation(),this.writeRenderingSnippet(e,t.items,r),i&&e.newLine(),e.outdent().write("</li>").outdent().write("))}").outdent().write("</ol>");break}case "structure":e.write("<ul>").indent();for(let[r,i]of mt(t.attributes))i.private!==true&&(i.optional===true&&(e.write(`{${n}.${r} && (`),e.indent()),this.writeAttributeSnippet(e,{name:r,...i},n),i.optional===true&&(e.outdent(),e.write(")}")));e.outdent().write("</ul>");break;case "union":{let r=!n.includes(".");r&&e.write("<>").indent();for(let[i,o]of Object.entries(t.types))e.write(`{${n}._type === '${i}' && (`).indent(),this.writeRenderingSnippet(e,o,n),e.outdent().write(")}");r&&e.outdent().write("</>");break}}}writeAttributeSnippet(e,t,n){let r=t.type,i=a.escapeEntities(t.label??An(t.name));switch(r.type){case "boolean":case "text":case "number":{e.write("<li>",false).append(`<strong>${i}:</strong> `),this.writeRenderingSnippet(e,r,`${n}.${t.name}`),e.append("</li>").newLine();break}default:e.write("<li>").indent().write(`<strong>${i}</strong>`),this.writeRenderingSnippet(e,r,`${n}.${t.name}`),e.outdent().write("</li>");break}}static escapeEntities(e){return e.replace(/([&"<>])/g,t=>({"&":"&amp;",'"':"&quot;","<":"&lt;",">":"&gt;"})[t]??t)}createWriter(){return new ke(this.options.indentationSize)}static replaceVariables(e,t){return e.replace(/%name%/g,a.formatName(t,true)).replace(/%slug%/g,is(t))}static formatName(e,t=false){return ke.formatName(e,t)}static isInline(e){return ["number","text","boolean"].includes(e.type)}};var ft=class extends gt{writeSlotHeader(e){switch(this.options.language){case "jsx":e.write("import {useContent} from '@croct/plug-react';");break;case "tsx":e.write("import type {ReactElement} from 'react';"),e.write("import {useContent} from '@croct/plug-react';");break}e.newLine();}writeSlotFetch(e,t){let n=this.options.contentVariable;e.write(`const ${n} = useContent('${t.id}@${t.version}');`).newLine();}isSlotFetchAsync(){return false}isSlotFetchBlocking(){return false}hasSuspenseBoundary(){return false}};var Rn=class a extends Ve{constructor(e){super(e),this.codemod=e.codemod,this.bundlers=e.bundlers,this.importResolver=e.importResolver;}async generateSlotExampleFiles(e,t){let n=await this.isTypeScriptProject(),r=await this.getPaths(t.configuration),i=this.fileSystem.joinPaths(r.components,`%slug%${n?".tsx":".jsx"}`),o=this.fileSystem.joinPaths(r.examples,`%slug%-example${n?".tsx":".jsx"}`);return new ft({fileSystem:this.fileSystem,language:await this.isTypeScriptProject()?"tsx":"jsx",contentVariable:"content",slotImportPath:await this.importResolver.getImportPath(i,this.fileSystem.getDirectoryName(o)),slotFilePath:i,slotComponentName:"%name%",pageFilePath:o,pageComponentName:"%name%Example"}).generate({id:e.slug,version:e.version.major,definition:e.resolvedDefinition}).files}async getInstallationPlan(e){let{configuration:t}=e,n=await this.getProjectInfo();return {dependencies:["@croct/plug-react"],tasks:this.getInstallationTasks({...e,project:n}),configuration:t}}async getProjectInfo(){let e="src",t=await this.getEnvVarProperty(),n=this.projectDirectory.get();return {typescript:await this.isTypeScriptProject(),sourceDirectory:e,provider:{file:await this.locateFile(...["App","main","index"].flatMap(r=>["js","jsx","ts","tsx"].map(i=>`${r}.${i}`)).map(r=>this.fileSystem.joinPaths(e,r)))},env:t===null?void 0:{property:t,productionFile:new Le(this.fileSystem,this.fileSystem.joinPaths(n,".env.production")),developmentFile:new Le(this.fileSystem,this.fileSystem.joinPaths(n,".env.development"))}}}getInstallationTasks(e){let t=[],n=e.project.env,{configuration:r}=e,i=null,o=()=>(i===null&&(i=Promise.all([this.workspaceApi.getApplication({organizationSlug:r.organization,workspaceSlug:r.workspace,applicationSlug:r.applications.development}),r.applications.production===void 0?null:this.workspaceApi.getApplication({organizationSlug:r.organization,workspaceSlug:r.workspace,applicationSlug:r.applications.production})]).then(([s,p])=>s===null?Promise.reject(new X(`Development application ${r.applications.development} not found`,{reason:"not_found"})):{development:s.publicId,production:p?.publicId})),i);if(n!==void 0){let{developmentFile:s,productionFile:p,property:c}=n,l=c.split(".").pop();t.push({title:"Setup environment variables",task:async u=>{u.update("Setting up environment variables");try{let g=await o();await Promise.all([s.setVariable(l,g.development),g.production===void 0?Promise.resolve():p.setVariable(l,g.production)]),u.confirm("Environment variables updated");}catch(g){u.alert("Failed to update environment variables",d.formatMessage(g));}}});}return t.push({title:"Configure provider",task:async s=>{s.update("Configuring provider");let p=e.project.provider.file;try{p===null?s.alert("No root component found"):(s.update("Configuring provider"),await this.installProvider(p,{props:{appId:a.getAppIdProperty(await o(),n?.property)}}),s.confirm("Provider configured"));}catch(c){s.alert("Failed to install provider",d.formatMessage(c));}}}),t}async installProvider(e,t){await this.codemod.provider.apply(this.fileSystem.joinPaths(this.projectDirectory.get(),e),t);}async getEnvVarProperty(){for(let e of this.bundlers)if(await this.packageManager.hasDirectDependency(e.package))return `${e.prefix}CROCT_APP_ID`;return null}static getAppIdProperty(e,t){return t!==void 0?{type:"reference",path:t.split(".")}:e.production===void 0?{type:"literal",value:e.development}:{type:"ternary",condition:{operator:"===",left:{type:"reference",path:["process","env","NODE_ENV"]},right:{type:"literal",value:"production"}},consequent:{type:"literal",value:e.production},alternate:{type:"literal",value:e.development}}}};var We=class a extends d{constructor(e,t={}){super(e,t),Object.setPrototypeOf(this,a.prototype);}},Tn=class a extends We{constructor(e){super(e),Object.setPrototypeOf(this,a.prototype);}};function Ae(a,e,t){try{return parse$1(a,{...t,sourceType:"module",plugins:[...e,...t?.plugins??[]]})}catch{throw new Tn("The source code contains syntax errors.")}}function os(a){let e={locales:Array()},t;try{t=Ae(a,["jsx","typescript"]);}catch{return {i18n:e}}return traverse(t,{ObjectProperty:n=>{if(va(n.node.key)!=="i18n")return n.skip();let r=n.node.value;if(!f.isObjectExpression(r))return n.stop();for(let i of r.properties)if(f.isObjectProperty(i)&&va(i.key)==="locales"){let o=i.value;if(f.isArrayExpression(o))for(let s of o.elements)s!==null&&f.isStringLiteral(s)&&e.locales.push(s.value);}else if(f.isObjectProperty(i)&&va(i.key)==="defaultLocale"){let o=i.value;o!==null&&f.isStringLiteral(o)&&(e.defaultLocale=o.value);}return n.stop()}}),{i18n:e}}function va(a){return f.isIdentifier(a)?a.name:f.isStringLiteral(a)?a.value:null}var Dn=class extends gt{constructor({fileSystem:e,router:t,...n}){super({fileSystem:e,contentVariable:t==="app"?"content":"props",...n}),this.nextOptions={router:t};}writeSlotHeader(e,t){switch(this.options.language){case "jsx":this.nextOptions.router==="app"&&(e.write("import {fetchContent} from '@croct/plug-next/server';"),e.newLine());break;case "tsx":if(e.write("import type {ReactElement} from 'react';"),this.nextOptions.router==="app"&&e.write("import {fetchContent} from '@croct/plug-next/server';"),this.nextOptions.router==="page"){e.write("import type {SlotContent} from '@croct/plug-next';"),e.newLine();let n=ke.formatName(t.id,true);e.write(`export type ${n}Props = SlotContent<'${t.id}@${t.version}'>;`);}e.newLine();break}}writeSlotFetch(e,t){if(this.nextOptions.router==="app"){let n=this.options.contentVariable;e.write(`const {${n}} = await fetchContent('${t.id}@${t.version}');`).newLine();}}writePageHeader(e,t){if(this.nextOptions.router==="app")return super.writePageHeader(e,t);let n=`${t.definition.id}@${t.definition.version}`;switch(this.options.language){case "jsx":e.write("import {fetchContent} from '@croct/plug-next/server';").write(`import ${t.name} from '${t.importPath}';`),e.newLine().write("export async function getServerSideProps(context) {").indent().write("return {").indent().write(`props: await fetchContent('${n}', {`).indent().write("route: context,").outdent().write("}),").outdent().write("}").outdent().write("}");break;case "tsx":e.write("import type {ReactElement} from 'react';"),e.write("import type {GetServerSideProps} from 'next';"),e.write("import {fetchContent} from '@croct/plug-next/server';"),e.write(`import ${t.name}, {type ${t.name}Props} from '${t.importPath}';`),e.newLine().write("type PageProps = {").indent().write(`content: ${t.name}Props,`).outdent().write("};").newLine().write("export const getServerSideProps: ",false).write("GetServerSideProps<PageProps> = async context => ({").indent().write(`props: await fetchContent('${n}', {`).indent().write("route: context,").outdent().write("}),").outdent().write("});");break}}writePageSignature(e,t){switch(this.nextOptions.router){case "app":super.writePageSignature(e,t);break;case "page":{e.write(this.options.language==="tsx"?"export default function Page({content}: PageProps): ReactElement {":"export default function Page({content}) {");break}}}appendSlotParams(e,t){if(this.nextOptions.router!=="page")return super.appendSlotParams(e,t);let n=ke.formatName(t.id,true),r=this.options.contentVariable;if(this.options.language==="jsx"){e.append(`(${r})`);return}e.append(`(${r}: ${n}Props)`);}writeSlotRendering(e,t){switch(this.nextOptions.router){case "app":super.writeSlotRendering(e,t);break;case "page":{e.write(`<${t} {...content} />`);break}}}isSlotFetchAsync(){return this.nextOptions.router==="app"}isSlotFetchBlocking(){return this.nextOptions.router==="app"}hasSuspenseBoundary(){return false}};var ee=class a extends d{constructor(e,t=[],n={}){super(e,{...n,details:n.details??t.map(r=>r.detail??r.title)}),Object.setPrototypeOf(this,a.prototype),this.problems=t;}isErrorType(e){return this.problems.some(t=>t.type===e)}isAccessDenied(e){return this.problems.some(t=>t.type==="https://croct.help/api/admin#access-denied"&&(e===void 0||t.reason===e))}};var ge=(t=>(t.DEVELOPMENT="DEVELOPMENT",t.PRODUCTION="PRODUCTION",t))(ge||{});(n=>{function a(r){switch(r){case "DEVELOPMENT":return "Development";case "PRODUCTION":return "Production"}}n.getLabel=a;function e(){return Object.values(n).filter(r=>typeof r=="string")}n.all=e;function t(r){let i=r.toUpperCase();if(!n.all().includes(i))throw new Error(`Invalid environment value "${r}".`);return i}n.fromValue=t;})(ge||={});var ae=(n=>(n.READ_RESOURCES="RESOURCE_READ_ACCESS",n.ISSUE_TOKEN="TOKEN_ISSUE",n.EXPORT_DATA="DATA_EXPORT",n))(ae||{});(n=>{function a(r){switch(r){case "RESOURCE_READ_ACCESS":return "Read resources";case "TOKEN_ISSUE":return "Issue tokens";case "DATA_EXPORT":return "Export data"}}n.getLabel=a;function e(){return Object.values(n).filter(r=>typeof r=="string")}n.all=e;function t(r){let i=r.toUpperCase();if(!n.all().includes(i))throw new Error(`Invalid permission value "${r}".`);return i}n.fromValue=t;})(ae||={});var Mn=class extends Ve{constructor(e){super(e),this.codemod=e.codemod,this.importResolver=e.importResolver,this.userApi=e.userApi,this.applicationApi=e.applicationApi;}async generateSlotExampleFiles(e,t){let[n,r,i]=await Promise.all([this.detectRouter(),this.isTypeScriptProject(),this.isFallbackMode()]),o=await this.isTypeScriptProject(),s=await this.getPaths(t.configuration),p=this.fileSystem.joinPaths(s.components,`%slug%${o?".tsx":".jsx"}`),c=this.fileSystem.joinPaths(s.examples,"%slug%"),l=await this.importResolver.getImportPath(p,c),u=r?"tsx":"jsx";return (i?new ft({fileSystem:this.fileSystem,language:u,contentVariable:"content",slotImportPath:l,slotFilePath:p,slotComponentName:"%name%",pageFilePath:this.fileSystem.joinPaths(c,`index${o?".tsx":".jsx"}`),pageComponentName:"Page"}):new Dn({fileSystem:this.fileSystem,router:n==="page"?"page":"app",language:u,slotImportPath:l,slotFilePath:p,slotComponentName:"%name%",pageFilePath:this.fileSystem.joinPaths(c,`${n==="page"?"index":"page"}${r?".tsx":".jsx"}`),pageComponentName:"Page"})).generate({id:e.slug,version:e.version.major,definition:e.resolvedDefinition}).files}async getInstallationPlan(e){let{configuration:t,output:n}=e,[{i18n:r},i]=await Promise.all([this.getConfig(),this.getProjectInfo()]);i.fallbackMode&&n.announce({semantics:"warning",title:"Fallback mode",message:"Next.js SDK requires version 13 or newer, so React SDK will be installed instead."});let o=t.locales.filter(c=>r.locales.includes(c)||c===t.defaultLocale),s=o.length>0?o:r.locales,p=r.defaultLocale!==void 0&&s.includes(r.defaultLocale)?r.defaultLocale:t.defaultLocale;return {dependencies:[i.fallbackMode?"@croct/plug-react":"@croct/plug-next"],tasks:this.getInstallationTasks({...e,project:i}),configuration:{...t,locales:s,defaultLocale:p,paths:{...t.paths,examples:i.pageDirectory}}}}async getProjectInfo(){let[e,t,n]=await Promise.all([this.isTypeScriptProject(),this.getPageDirectory(),this.isFallbackMode()]),r={typescript:e,router:await this.detectRouter(t),sourceDirectory:t.startsWith("src")?"src":".",pageDirectory:t},[i,o]=await Promise.all([this.locateFile(...["middleware.js","middleware.ts"].map(c=>this.fileSystem.joinPaths(r.sourceDirectory,c))),this.locateFile(...(r.router==="app"?[this.fileSystem.joinPaths("app","layout"),this.fileSystem.joinPaths("app","layout")]:[this.fileSystem.joinPaths("pages","_app"),this.fileSystem.joinPaths("pages","_app")]).flatMap(c=>["js","jsx","ts","tsx"].map(l=>this.fileSystem.joinPaths(r.sourceDirectory,`${c}.${l}`))))]),s=r.typescript?"ts":"js",p=this.projectDirectory.get();return {...r,fallbackMode:n,env:{localFile:new Le(this.fileSystem,this.fileSystem.joinPaths(p,".env.local")),developmentFile:new Le(this.fileSystem,this.fileSystem.joinPaths(p,".env.development")),productionFile:new Le(this.fileSystem,this.fileSystem.joinPaths(p,".env.production"))},middleware:{file:i??this.fileSystem.joinPaths(r.sourceDirectory,`middleware.${s}`)},provider:{file:o??(r.router==="app"?this.fileSystem.joinPaths(r.sourceDirectory,"app",`layout.${s}x`):this.fileSystem.joinPaths(r.sourceDirectory,"pages",`_app.${s}x`))}}}getInstallationTasks(e){let t=[];return e.project.fallbackMode||t.push({title:"Configure middleware",task:async n=>{n.update("Configuring middleware");try{await this.updateCode(this.codemod.middleware,e.project.middleware.file),n.confirm("Middleware configured");}catch(r){n.alert("Failed to install middleware",d.formatMessage(r));}}}),t.push({title:"Configure provider",task:async n=>{n.update("Configuring provider");try{await this.installProvider({...e,notifier:n}),n.confirm("Provider configured");}catch(r){n.alert("Failed to install provider",d.formatMessage(r));}}}),t.push({title:"Setup environment variables",task:async n=>{n.update("Setting up environment variables");try{await this.updateEnvVariables({...e,notifier:n}),n.confirm("Environment variables updated");}catch(r){n.alert("Failed to update .env.local",d.formatMessage(r));}}}),t}installProvider(e){return this.updateCode(this.getProviderCodemod(e),e.project.provider.file,{typescript:e.project.typescript})}getProviderCodemod(e){return e.project.fallbackMode?this.codemod.fallbackProvider:e.project.router==="app"?this.codemod.appRouterProvider:this.codemod.pageRouterProvider}async updateCode(e,t,n){await e.apply(this.fileSystem.joinPaths(this.projectDirectory.get(),t),n);}async updateEnvVariables(e){let{project:{env:t},configuration:n,notifier:r}=e;r.update("Loading information");let[i,o]=await Promise.all([this.workspaceApi.getApplication({organizationSlug:n.organization,workspaceSlug:n.workspace,applicationSlug:n.applications.development}),n.applications.production===void 0?null:this.workspaceApi.getApplication({organizationSlug:n.organization,workspaceSlug:n.workspace,applicationSlug:n.applications.production})]);if(i===null)throw new X(`Development application \`${n.applications.development}\` not found.`,{reason:"not_found"});if(!await t.localFile.hasVariable("CROCT_API_KEY")&&e.skipApiKeySetup!==true){let s=await this.userApi.getUser();r.update("Creating API key");let p;try{p=await this.applicationApi.createApiKey({organizationSlug:n.organization,workspaceSlug:n.workspace,applicationSlug:i.slug,name:`${s.username} CLI`,permissions:["TOKEN_ISSUE"]});}catch(c){throw c instanceof d?new X(c instanceof ee&&c.isAccessDenied()?"Your user does not have permission to create an API key":c.message,c.help):c}await t.localFile.setVariables({CROCT_API_KEY:p.secret});}await Promise.all([t.developmentFile.setVariables({NEXT_PUBLIC_CROCT_APP_ID:i.publicId}),o===null?Promise.resolve():t.productionFile.setVariables({NEXT_PUBLIC_CROCT_APP_ID:o.publicId})]);}async detectRouter(e){return (e??await this.getPageDirectory()).endsWith("pages")?"page":"app"}async getPageDirectory(){return await this.locateFile("app",this.fileSystem.joinPaths("src","app"),"pages",this.fileSystem.joinPaths("src","pages"))??"app"}async getConfig(){let e=["js","mjs","ts","mts"].map(n=>`next.config.${n}`),t=await this.readFile(...e).catch(()=>null);return t===null?{i18n:{locales:[],defaultLocale:""}}:os(t)}isFallbackMode(){return this.packageManager.hasDirectDependency("next","<=13")}};var Xe=(n=>(n.NEXTJS="nextjs",n.REACT="react",n.JAVASCRIPT="javascript",n))(Xe||{});(e=>{function a(t){switch(t){case "nextjs":return "Next.js";case "react":return "React";case "javascript":return "JavaScript"}}e.getName=a;})(Xe||={});var Nn=class a{constructor(e){this.config=e;}async execute(e){let{configurationManager:t,platformProvider:n,sdkProvider:r,io:{output:i}}=this.config,o=e.override!==true&&await t.isInitialized()?{...await t.loadPartial()}:null,s=await n.get(),p=s!==null?`${Xe.getName(s)} project`:"project";i.break(),i.announce({semantics:"neutral",title:"\u{1F44B} Welcome to Croct",alignment:"center",message:`Let's configure your ${p} to get started!`}),i.break();let c=await this.getOrganization({new:e.new==="organization"},e.new==="organization"?void 0:e.organization??o?.organization),l=await this.getWorkspace({organization:c,new:c.new!==true&&e.new==="workspace"},e.new==="workspace"||c.new===true?void 0:e.workspace??o?.workspace),u={organization:c,workspace:l,platform:s??"javascript",new:l.new!==true&&e.new==="application"},g=await this.getApplication({...u,environment:"DEVELOPMENT"},e.new!==void 0||l.new===true?void 0:e.devApplication??o?.applications?.development),y={organization:c.slug,workspace:l.slug,applications:{development:g.slug},defaultLocale:l.defaultLocale,locales:[...new Set([...o?.locales??[],...l.locales])],slots:o?.slots??{},components:o?.components??{},paths:o?.paths??{}},v=await this.resolveApplication({...u,environment:"PRODUCTION"},e.new!==void 0?void 0:e.prodApplication??o?.applications?.production);if(v!==null&&(y.applications.production=v.slug),o!==null){await t.update(y),i.confirm("Project configuration updated");return}let A=await r.get();if(A===null){await t.update(y),i.warn("No suitable SDK found, skipping project configuration");return}await t.update(await this.configure(A,y,e.skipApiKeySetup===true));}async getOrganization(e,t){let{form:n,api:r}=this.config,i=t===void 0?await n.organization.handle(e):await r.user.getOrganization(t).catch(o=>{if(o instanceof ee&&o.isAccessDenied())return null;throw o});if(i===null)throw new d(`No organization found with slug "${t}".`,{reason:"invalid_input"});return i}async getWorkspace(e,t){let{form:n,api:r}=this.config,i=t===void 0?await n.workspace.handle(e):await r.organization.getWorkspace({organizationSlug:e.organization.slug,workspaceSlug:t}).catch(o=>{if(o instanceof ee&&o.isAccessDenied())return null;throw o});if(i===null)throw new d(`No workspace found with slug "${t}".`,{reason:"invalid_input"});return i}async resolveApplication(e,t){let{api:n}=this.config,r=e.workspace.website??e.organization.website??void 0,i=r!==void 0&&new URL(r).hostname!=="localhost";if(e.environment==="DEVELOPMENT"||i||t!==void 0||e.new===true)return this.getApplication(e,t);let o=n.workspace.getApplications({organizationSlug:e.organization.slug,workspaceSlug:e.workspace.slug});for(let s of await o)if(s.environment===e.environment)return this.getApplication(e,t);return null}async getApplication(e,t){let{form:n,api:r}=this.config,i=t===void 0?await n.application.handle(e):await r.workspace.getApplication({organizationSlug:e.organization.slug,workspaceSlug:e.workspace.slug,applicationSlug:t}).catch(o=>{if(o instanceof ee&&o.isAccessDenied())return null;throw o});if(i===null)throw new d(`No application found with slug "${t}".`,{reason:"invalid_input"});if(i.environment!==e.environment)throw new d(`No ${ge.getLabel(e.environment).toUpperCase()} application found with slug "${t}".`,{reason:"invalid_input"});return i}async configure(e,t,n){let{skipConfirmation:r}=this.config,i=await e.setup({input:this.config.io.input===void 0||await r.get()?void 0:this.config.io.input,output:this.config.io.output,skipApiKeySetup:n,configuration:t});return a.canonicalizePaths(i)}static canonicalizePaths(e){return e.paths===void 0?e:{...e,paths:Object.fromEntries(Object.entries(e.paths).map(([t,n])=>[t,a.canonicalizePath(n)]))}}static canonicalizePath(e){return e.replace(/\\/g,"/")}};var zn=class{constructor(e){this.authenticator=e.authenticator;}async execute(e){await this.authenticator.logout(),await this.authenticator.login(e);}};var jt=class{constructor({output:e,authenticator:t}){this.authenticator=t,this.output=e;}async execute(){await this.authenticator.logout(),this.output.confirm("Logged out");}};var Ie=class a extends d{constructor(e,t={}){super(e,{...t,reason:t.reason??"invalid_configuration"}),Object.setPrototypeOf(this,a.prototype);}};var $n=class a{static{this.CONFIGURATION_SCHEMA="https://schema.croct.com/json/v1/project.json";}constructor({fileSystem:e,projectDirectory:t,fullValidator:n,partialValidator:r}){this.fileSystem=e,this.projectDirectory=t,this.fullValidator=n,this.partialValidator=r;}async isInitialized(e="any"){if(e==="any")return this.fileSystem.exists(this.getConfigurationFilePath());let t=e==="full"?this.fullValidator:this.partialValidator;try{return (await this.loadConfigurationFile(t)).configuration!==null}catch(n){if(n instanceof Ie)return false;throw n}}async load(){let{configuration:e}=await this.loadConfigurationFile(this.fullValidator);if(e===null)throw new Ie("Project configuration not found.",{reason:"not_found",suggestions:["Run `init` command to initialize the project"]});return e}async loadPartial(){let e={};try{e=(await this.loadConfigurationFile(this.partialValidator)).configuration??{};}catch(t){if(!(t instanceof Ie))throw t}return e}async update(e){return this.updateConfigurationFile(await this.validateConfiguration(this.fullValidator,e))}async updateConfigurationFile(e){let t=await this.loadConfigurationFile(this.partialValidator),r=this.applyConfigurationChanges(t,e).toString({indentationCharacter:"space",object:{indentationSize:2,leadingIndentation:true,trailingIndentation:true,entryIndentation:true,colonSpacing:true,commaSpacing:true},array:{indentationSize:2,entryIndentation:true,leadingIndentation:true,trailingIndentation:true,colonSpacing:true,commaSpacing:true}});try{await this.fileSystem.writeTextFile(t.path,r,{overwrite:!0});}catch{throw new Error(`Unable to write configuration file ${t.path}.`)}return e}applyConfigurationChanges(e,t){if(e.configuration===null||e.source===null)return JsonObjectNode$1.of({$schema:a.CONFIGURATION_SCHEMA,...t});let n=JsonParser$1.parse(e.source,JsonObjectNode$1);return n.update({$schema:n.has("$schema")?n.get("$schema").toJSON():void 0,...t}).cast(JsonObjectNode$1)}async loadConfigurationFile(e){let t={path:this.getConfigurationFilePath(),source:null,configuration:null},n;try{t.source=await this.fileSystem.readTextFile(t.path),n=JsonParser$1.parse(t.source).toJSON();}catch{return t}return n!==null&&(t.configuration=await this.validateConfiguration(e,n,t),t.configuration?.$schema!==void 0&&delete t.configuration?.$schema),t}getConfigurationFilePath(){return this.fileSystem.joinPaths(this.projectDirectory.get(),"croct.json")}async validateConfiguration(e,t,n){let r=await e.validate(t);if(!r.valid){let i=r.violations[0];throw new Ie("The project configuration is invalid.",{details:[...n!==void 0?[`File: file://${n.path.replace(/\\/g,"/")}`]:[],`Cause: ${i.message}`,`Violation path: ${i.path}`]})}return r.data}};var Ut=class{constructor(e){this.configuration=e;}async execute(e,...[t]){let{tokenProvider:n,endpoint:r}=this.configuration,i=n!==void 0?await n.getToken():null,o=await fetch(r,{method:"POST",headers:{accept:"application/json","content-type":"application/json",...i!==null?{Authorization:`Bearer ${i}`}:{}},body:JSON.stringify({query:e,variables:t})});return o.json().then(s=>{let{data:p,errors:c}=s;if(c!==void 0)throw new ee(c[0].message.replace(/"/g,"`"),c.map(({extensions:l})=>({...l,detail:l.detail?.replace(/"/g,"`")})));return {data:p,headers:o.headers}})}};function Pa(a,e){return a.slice(0,a.indexOf("-",e-1)===e-1?e-1:e)}function*Vt({baseName:a,alwaysSuffixed:e=false}){let t=a.normalize("NFD").toLowerCase().replace(/[^a-z ]/g,"").trim().split(/\s+/);t.length===0&&t.push(String.fromCharCode(97+Math.floor(Math.random()*26))+Math.random().toString(36).substring(2,14));let n=t.slice(0,2).join("-");for(e||(yield Pa(n,30),n.length<29&&t.length>2&&(yield Pa(t.join("-"),30)));;){let r=Math.floor(Math.random()*1e4).toString();yield `${Pa(n,30-r.length-1)}-${r}`;}}function Ye(a){let{baseName:e,query:t,client:n,alwaysSuffixed:r}=a;return Vc({baseName:e,alwaysSuffixed:r},async i=>{let o=[i.next().value,i.next().value,i.next().value],{data:{checkAvailability:s}}=await n.execute(t,{...a.variables??{},slugFirstOption:o[0],slugSecondOption:o[1],slugThirdOption:o[2]}),p=[s.slugFirstOption,s.slugSecondOption,s.slugThirdOption];return o.find((c,l)=>p[l])??null})}async function Vc(a,e){let t=Vt(a),n;do n=await e(t);while(n===null);return n}var E=class extends String{constructor(e,t){super(e),this.value=e,this.__meta__=t;}toString(){return this.value}},ss=new E(`
107
107
  query ApplicationSlugAvailability($workspaceId: WorkspaceId!, $slugFirstOption: ReadableId!, $slugSecondOption: ReadableId!, $slugThirdOption: ReadableId!) {
108
108
  checkAvailability {
109
109
  slugFirstOption: applicationSlug(
@@ -1723,7 +1723,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
1723
1723
  mutation GenerateTyping($workspaceId: WorkspaceId!, $payload: GenerateTypingPayload!) {
1724
1724
  generateTyping(workspaceId: $workspaceId, payload: $payload)
1725
1725
  }
1726
- `);function yt(a){return {model:a,api:Object.fromEntries(Object.entries(a).map(([e,t])=>[t,e]))}}var ka=yt({javascript:"JAVASCRIPT",react:"REACT",nextjs:"NEXT"}),Aa=yt({DEVELOPMENT:"DEVELOPMENT",PRODUCTION:"PRODUCTION"}),Mp=yt({NEVER_RECEIVED_TRAFFIC:"NEVER_RECEIVED_TRAFFIC",NOT_RECEIVING_TRAFFIC:"NOT_RECEIVING_TRAFFIC",RECEIVING_TRAFFIC:"RECEIVING_TRAFFIC"}),Gc=yt({PLUG_JS:"PLUG_JS"}),Ea=yt({DRAFT:"DRAFT",ACTIVE:"ACTIVE",SCHEDULED:"SCHEDULED",PAUSED:"PAUSED",ARCHIVED:"ARCHIVED"}),Bc=yt({DRAFT:"DRAFT",ACTIVE:"ACTIVE",SCHEDULED:"SCHEDULED",PAUSED:"PAUSED",FINISHED:"FINISHED",INDIRECTLY_PAUSED:"INDIRECTLY_PAUSED"}),Ln=class a{constructor(e,t){this.client=e,this.hierarchyResolver=t;}async getFeatures(e){let{data:t}=await this.client.execute(yp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug}),n=t.organization?.workspace??null;if(n===null)return null;let{quotas:r,capabilities:{features:i}}=n;return {quotas:{audiences:r.audience,remainingAudiences:r.remainingAudiences,components:r.component,remainingComponents:r.remainingComponents,slots:r.slot,remainingSlots:r.remainingSlots,experiences:r.experience,remainingExperiences:r.remainingExperiences,dynamicAttributesPerContent:r.dynamicAttributesPerContent,audiencesPerExperience:r.audiencesPerExperience},features:{crossDevice:i.includes("CROSS_DEVICE_EXPERIMENT"),dataExport:i.includes("API_DATA_EXPORT")}}}async getApplications(e){let{data:t}=await this.client.execute(Pp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return (t.organization?.workspace?.applications.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[a.normalizeApplication(i)]})}async getApplication(e){let{data:t}=await this.client.execute(Cp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,applicationSlug:e.applicationSlug}),n=t.organization?.workspace?.application??null;return n===null?null:a.normalizeApplication(n)}static normalizeApplication(e){let{logo:t=null}=e;return {id:e.id,name:e.name,slug:e.slug,timeZone:e.settings.timeZone,website:e.website,environment:Aa.api[e.environment],platform:ka.api[e.platform??"JAVASCRIPT"],publicId:e.publicId,trafficStatus:Mp.api[e.applicationStatus],...t!==null?{logo:t}:{}}}async createApplication(e){let t=await this.hierarchyResolver.getHierarchy({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug}),{data:n}=await this.client.execute(kp,{workspaceId:t.workspaceId,payload:{name:e.name,website:e.website,environment:Aa.model[e.environment],platform:ka.model[e.platform],timeZone:e.timeZone,slug:await this.generateApplicationSlug(t.workspaceId,e.name,e.environment)}}),r=n.createWebApplication,{logo:i=null}=r;return {id:r.id,name:r.name,slug:r.slug,timeZone:r.settings.timeZone,website:r.website,environment:Aa.api[r.environment],platform:ka.api[r.platform??"JAVASCRIPT"],publicId:r.publicId,trafficStatus:Mp.api[r.applicationStatus],...i!==null?{logo:i}:{}}}async getAudiences(e){let{data:t}=await this.client.execute(Sp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return (t.organization?.workspace?.audiences.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[a.normalizeAudience(i)]})}async getAudience(e){let{data:t}=await this.client.execute(bp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,audienceSlug:e.audienceSlug}),n=t.organization?.workspace?.audience??null;return n===null?null:a.normalizeAudience(n)}static normalizeAudience(e){return {id:e.id,name:e.name,slug:e.customId,criteria:e.criteria}}async getComponents(e){let{data:t}=await this.client.execute(Ep,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return (t.organization?.workspace?.components.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[a.normalizeComponent(i)]})}async getComponent(e){let{data:t}=await this.client.execute(Op,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,componentSlug:e.componentSlug,majorVersion:e.majorVersion}),n=t.organization?.workspace?.component??null;return n===null?null:a.normalizeComponent(n)}static normalizeComponent(e){let{definition:t,metadata:{directReferences:n,indirectReferences:r,referenceMetadata:i}}=e.definition,o=e.description??null;return {id:e.id,name:e.name,slug:e.customId,...o!==null?{description:o}:{},definition:t,version:{major:e.definition.version.major,minor:e.definition.version.minor},metadata:{directReferences:n.map(s=>i.find(({componentId:p})=>p===s)?.referenceName??s),indirectReferences:r.map(s=>i.find(({componentId:p})=>p===s)?.referenceName??s)}}}async getSlots(e){let{data:t}=await this.client.execute(Ip,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return (t.organization?.workspace?.slots.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[a.normalizeSlot(i)]})}async getSlot(e){let{data:t}=await this.client.execute(vp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,slotSlug:e.slotSlug,majorVersion:e.majorVersion}),n=t.organization?.workspace?.slot??null;return n===null?null:a.normalizeSlot(n)}static normalizeSlot(e){let{component:t=null}=e.content,n=t?.definition.metadata??null;return {id:e.id,name:e.name,slug:e.customId,...t!==null&&n!==null?{component:{slug:t.customId,version:{major:t.definition.version.major,minor:t.definition.version.minor},metadata:{directReferences:n.directReferences.map(r=>n.referenceMetadata.find(({componentId:i})=>i===r)?.referenceName??r),indirectReferences:n.indirectReferences.map(r=>n.referenceMetadata.find(({componentId:i})=>i===r)?.referenceName??r)}}}:{},version:{major:e.content.version.major,minor:e.content.version.minor},resolvedDefinition:e.content.componentDefinition.resolvedDefinition,content:Object.fromEntries(e.content.default.map(({locale:r,content:i})=>[r,i]))}}async getSlotStaticContent(e,t){let{data:n}=await this.client.execute(xp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,slotSlug:e.slotSlug,majorVersion:t});return (n.organization?.workspace?.slot?.staticContent??[]).map(i=>({locale:i.locale,content:i.content}))}async generateTypes(e){let t=await this.hierarchyResolver.getHierarchy({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug}),{data:n}=await this.client.execute(Dp,{workspaceId:t.workspaceId,payload:{target:Gc.model[e.target],components:e.components,slots:e.slots}});return n.generateTyping}async getExperiences(e){let{data:t}=await this.client.execute(Tp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,status:e.status===void 0?void 0:(Array.isArray(e.status)?e.status:[e.status]).map(r=>Ea.model[r])});return (t.organization?.workspace?.experiences.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[a.normalizeExperience(i)]})}async getExperience(e){let{data:t}=await this.client.execute(Rp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,experienceId:e.experienceId}),n=t.organization?.workspace?.experience??null;return n===null?null:a.normalizeExperienceDetails(n)}static normalizeExperience(e){let t=e.settings?.audiences??e.draft?.audiences??[],n=e.settings?.slots??e.draft?.slots??[],r=e.currentExperiment?.name??e.draft?.experiment?.name??null;return {id:e.id,name:e.name,priority:e.priority??e.draft?.priority??0,status:Ea.api[e.status],audiences:t.map(i=>i.customId),slots:n.flatMap(({slot:i=null})=>i===null?[]:[i.customId]),...r!==null?{experiment:{name:r}}:{}}}static normalizeExperienceDetails(e){let t=e.settings?.audiences??e.draft?.audiences??[],n=e.settings?.slots??e.draft?.slots??[],r=e.currentExperiment??e.draft?.experiment??null,{name:i=null,goalId:o=null,crossDevice:s=null,traffic:p=null}=r??{},c=Object.fromEntries(n.flatMap(({slot:l=null})=>l===null?[]:[[l.id,l.customId]]));return {id:e.id,name:e.name,priority:e.priority??e.draft?.priority??0,status:Ea.api[e.status],hasExperiments:e.hasExperiments,audiences:t.map(l=>l.customId),slots:Object.values(c),...r!==null?{experiment:{...i!==null?{name:i}:{},...o!==null?{goalId:o}:{},...s!==null?{crossDevice:s}:{},...p!==null?{traffic:p}:{},..."status"in r?{status:Bc.api[r.status]}:{},variants:(r.variants??[]).map(l=>{let u=l.variantId,g=l.name??null,y=l.allocation??null;return {...u!==null?{id:u}:{},...g!==null?{name:g}:{},...y!==null?{allocation:y}:{},baseline:l.baseline===true,content:{default:a.normalizeLocalizedContent(l.content?.default.contents??[],c),segmented:(l.content?.segmented??[]).map(v=>({id:v.groupId,audiences:v.audiences.map(A=>A.audienceId),content:a.normalizeLocalizedContent(v.contents,c)}))}}})}}:{},content:{default:a.normalizeLocalizedContent(e.settings?.content.default.contents??e.draft?.content?.default.contents??[],c),segmented:(e.settings?.content.segmented??e.draft?.content?.segmented??[]).map(l=>({id:l.groupId,audiences:l.audiences.map(({audienceId:u})=>t.find(({id:g})=>g===u)?.customId??u),content:a.normalizeLocalizedContent(l.contents,c)}))}}}static normalizeLocalizedContent(e,t){let n={};for(let r of e){let{locale:i,slotId:o}=r,s=t[o];s!==void 0&&(n[s]===void 0&&(n[s]={}),n[s][i]=r.content);}return n}async createResources(e){let t=await this.hierarchyResolver.getHierarchy({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug}),n={components:Object.entries(e.components??{}).map(([i,o])=>({customId:i,name:o.name,description:o.description,definition:o.schema})),slots:Object.entries(e.slots??{}).map(([i,o])=>({customId:i,name:o.name,component:o.component,defaultContent:Object.entries(o.content).map(([s,p])=>({locale:s,content:p}))})),audiences:Object.entries(e.audiences??{}).map(([i,o])=>({customId:i,name:o.name,criteria:o.criteria})),experiences:(e.experiences??[]).map(i=>{let o=i.experiment??null;return {name:i.name,audiences:i.audiences,slots:i.slots,experiment:o!==null?{name:o.name,goalId:o.goalId,traffic:o.traffic,crossDevice:o.crossDevice===true,variants:o.variants.map(s=>({id:randomUUID$1(),name:s.name??"",baseline:s.baseline===true,allocation:s.allocation??0,content:a.createContentVariantGroup(s.content)}))}:void 0,content:a.createContentVariantGroup(i.content),validate:true,publish:i.draft!==true}})},{data:{createWorkspaceResources:r}}=await this.client.execute(hp,{workspaceId:t.workspaceId,payload:n});return {components:Object.fromEntries(n.components.map(({customId:i},o)=>[i,r.components[o]])),slots:Object.fromEntries(n.slots.map(({customId:i},o)=>[i,r.slots[o]])),audiences:Object.fromEntries(n.audiences.map(({customId:i},o)=>[i,r.audiences[o]])),experiences:r.experiences.map(i=>{let o=i.experimentId??null;return {experienceId:i.id,...o!==null?{experimentId:o}:{}}})}}static createContentVariantGroup(e){return {default:{id:randomUUID$1(),contents:a.createSlotContentMap(e.default??{})},segmented:(e.segmented??[]).map(t=>({id:randomUUID$1(),audiences:t.audiences,contents:a.createSlotContentMap(t.content)}))}}static createSlotContentMap(e){return Object.entries(e).flatMap(([t,n])=>Object.entries(n).map(([r,i])=>({slot:t,locale:r,content:i})))}generateApplicationSlug(e,t,n){return Ye({query:wp,baseName:`${t} ${n==="DEVELOPMENT"?"dev":"prod"}`,client:this.client,variables:{workspaceId:e}})}};var et;(t=>{function a(){return Intl.DateTimeFormat().resolvedOptions().locale.toLowerCase()}t.getLocale=a;function e(){return Intl.DateTimeFormat().resolvedOptions().timeZone}t.getTimeZone=e;})(et||={});var ht=class a{constructor(e){this.config=e;}static prompt(e){return new a(e).handle()}handle(){let{input:e,validate:t}=this.config;return e.prompt({message:this.config.label,default:this.config.default,initial:this.config.initial??"https://",validate:n=>URL.canParse(n)?t!==void 0?t(n):true:"Invalid URL"})}};var Fn=class{constructor(e){this.config=e;}async handle(e={}){let{userApi:t,output:n,input:r}=this.config;if(e.new!==true){let c=n.notify("Loading organizations"),l=[];if(e.default!==void 0){let u=await t.getOrganization(e.default);u!==null&&l.push(u);}if(l.length===0&&l.push(...await t.getOrganizations()),l.length===1){let u=l[0];return c.confirm(`Organization: ${u.name}`),u}if(c.stop(),l.length>0)return r.select({message:"Select organization",options:l.map(u=>({value:u,label:u.name}))})}let i=et.getTimeZone(),o=et.getLocale();n.inform("Setting up a new organization"),n.inform("*By continuing, you agree to our [Terms of Service](https://croct.link/terms-of-service)*");let s=await ht.prompt({input:r,label:"Organization website"}),p=this.notify("Setting up organization");try{let c=await t.setupOrganization({website:s,locale:o,timeZone:i});return p.confirm(`Organization: ${c.name}`),{...c,new:!0}}finally{p.stop();}}notify(e){let{output:t}=this.config,n=["Visiting website","Detecting tech stack","Configuring organization","Creating workspace","Configuring applications","Setting up organization"],r=t.notify(e),i=0,o=setInterval(()=>{i>=n.length?clearInterval(o):r.update(n[i++]);},3e3);return o.unref(),{confirm:(s,p)=>{clearInterval(o),r.confirm(s,p);},stop:s=>{clearInterval(o),r.stop(s);}}}};var Ee=class a{constructor(e){this.config=e;}static prompt(e){return new a(e).handle()}handle(){let{input:e,validator:t,minimumLength:n=2,maximumLength:r=30}=this.config;return e.prompt({message:this.config.label,default:this.config.default,initial:this.config.initial,validate:i=>/(^\s|\s$|\s{2,})/.test(i)?"No leading, trailing, or multiple spaces.":i.length<n?`Minimum of ${n} characters`:i.length>r?`Maximum of ${r} characters`:t?.(i)??true})}};var jn=class a{constructor(e){this.config=e;}async handle(e){let{organizationApi:t,output:n,input:r}=this.config,{organization:i}=e;if(e.new===false){let o=n.notify("Loading workspaces"),s=await t.getWorkspaces({organizationSlug:i.slug}),p=a.getDefaultWorkspace(s,e.default);if(p!==null)return o.confirm(`Workspace: ${p.name}`),p;if(o.stop(),s.length>0)return r.select({message:"Select workspace",options:s.map(c=>({value:c,label:c.name}))})}return this.setupWorkspace(i,e.new===true)}async setupWorkspace(e,t){let{organizationApi:n,input:r,output:i}=this.config,o=t?await Ee.prompt({input:r,label:"Workspace name",default:e.name}):e.name,s=et.getLocale(),p=et.getTimeZone(),c=i.notify("Creating workspace");try{let l=await n.createWorkspace({organizationSlug:e.slug,name:o,website:e.website,defaultLocale:s,timeZone:p});return c.confirm(`Workspace: ${l.name}`),{...l,new:t}}finally{c.stop();}}static getDefaultWorkspace(e,t){return e.length===1?e[0]:t!==void 0?e.find(({slug:n})=>n===t)??null:null}};var Un=class a{constructor(e){this.config=e;}async handle(e){let{workspaceApi:t,output:n,input:r}=this.config,{organization:i,workspace:o,environment:s}=e,p=n.notify("Loading applications"),c=await t.getApplications({workspaceSlug:o.slug,organizationSlug:i.slug}),l=c.filter(u=>u.environment===s&&(e.default??u.slug)===u.slug);if(p.stop(),l.length===0||e.new===true)return this.setupApplication(e,c);if(l.length===1){let u=l[0];return n.confirm(a.formatSelection(u)),u}return r.select({message:s==="DEVELOPMENT"?"Select development application":"Select production application",options:l.map(u=>({value:u,label:u.name}))})}async setupApplication(e,t){let{workspaceApi:n,output:r,input:i}=this.config,{organization:o,workspace:s,platform:p,environment:c}=e,l=e.new===true,u=l?await Ee.prompt({input:i,label:c==="DEVELOPMENT"?"Development application name":"Production application name",default:"Website",validator:A=>t.every(M=>M.name.toLowerCase()!==A.toLowerCase()||M.environment!==c)||"Name already in use"}):"Website",g=s.website??o.website??void 0,y=l||!a.isValidUrl(g,c)?await ht.prompt({input:i,label:c==="DEVELOPMENT"?"Development application URL":"Production application URL",default:g,validate:A=>URL.canParse(A)?a.isValidUrl(A,c)?true:"Production URL must not be localhost":"Invalid URL"}):g,v=r.notify("Configuring application");try{let A=await n.createApplication({organizationSlug:o.slug,workspaceSlug:s.slug,name:u,website:y,environment:c,platform:p,timeZone:s.timeZone});return v.confirm(a.formatSelection(A)),{...A,new:!0}}finally{v.stop();}}static isValidUrl(e,t){return e===void 0||!URL.canParse(e)?false:t!=="PRODUCTION"||new URL(e).hostname!=="localhost"}static formatSelection(e){return e.environment==="DEVELOPMENT"?`Development application: ${e.name} (${e.slug})`:`Production application: ${e.name} (${e.slug})`}};var Vn=class{constructor(e,t){this.client=e,this.hierarchyResolver=t;}async createApiKey(e){let t=await this.hierarchyResolver.getHierarchy({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,applicationSlug:e.applicationSlug}),{data:n}=await this.client.execute(Ap,{applicationId:t.applicationId,payload:{name:e.name,permissions:e.permissions}}),{apiKey:r}=n.createApiKey;return {id:r.id,name:r.name,permissions:r.permissions.map(ae.fromValue),secret:n.createApiKey.apiKeyValue}}};var qe=class a{constructor(e){this.config=e;}static prompt(e){return new a(e).handle()}handle(){let{input:e}=this.config;return e.prompt({message:this.config.label,validate:t=>t.length>255?"The email must be less than 255 characters":/^([A-Z0-9_+-]+\.?)*[A-Z0-9_+-]@([A-Z0-9][A-Z0-9-]*\.)+[A-Z]{2,}$/i.test(t)?true:"Please enter a valid email"})}};var Wn=class{constructor(e){this.config=e;}getToken(){return Promise.resolve(null)}login(e={}){if(e.username===void 0||e.password===void 0)return this.loginInteractively(e);let{form:t}=this.config;return t.signIn.handle({email:e.username,password:e.password})}async loginInteractively(e){let{input:t,output:n,userApi:r,form:i}=this.config,o=e.username??await qe.prompt({input:t,label:"Enter your email"}),s=n.notify("Finding account"),p=await r.isEmailRegistered(o);return s.stop(),p?(e.password===void 0&&n.inform("Account found, please sign in"),i.signIn.handle({email:o,password:e.password,retry:true})):(n.inform("New account, please sign up"),i.signUp.handle({email:o}))}logout(){return Promise.resolve()}};var Ke=class a{constructor(e){this.config=e;}static prompt(e){return new a(e).handle()}handle(){let{input:e}=this.config;return e.prompt({message:this.config.label,type:"password",validate:this.config.validator??(t=>t.length>0?true:"Please enter your password")})}};var qn=class{constructor(e){this.config=e;}handle(e){return this.login(e.email,e.password,e.retry)}async login(e,t,n=false){let{input:r,output:i,userApi:o}=this.config,s=e??await qe.prompt({input:this.config.input,label:"Enter your email"}),p=t,c="retry-password";for(;c==="retry-password";){let l=p??await Ke.prompt({input:r,label:"Password"});p=void 0;let u=i.notify("Checking credentials");try{let g=await o.signIn({email:s,password:l,duration:this.config.tokenDuration});return u.confirm("Logged in"),g}catch(g){if(g instanceof ee){if(g.isAccessDenied("UNVERIFIED_USER")){if(!n)throw new d("Email not verified.",{reason:"access_denied",cause:g,suggestions:["Access your email and click on the activation link"]});u.warn("Email not verified"),c=await r.confirm({message:"Resend activation link?",default:true})?"retry-activation":"cancel";continue}if(g.isAccessDenied("BAD_CREDENTIALS")){if(!n)throw new d("Username or password is incorrect.",{reason:"access_denied",cause:g,suggestions:["Check your credentials or reset your password"]});u.alert("Wrong password"),c=await r.select({message:"What would you like to do?",default:"retry-password",options:[{label:"Try again",value:"retry-password"},{label:"Recover password",value:"reset-password"},...e===void 0?[{label:"Enter a different email",value:"change-email"}]:[],{label:"Cancel",value:"cancel"}]});continue}}throw u.stop(),g}}switch(c){case "change-email":return this.login();case "retry-activation":return this.retryActivation(s);case "reset-password":return this.resetPassword(s);case "cancel":default:return i.exit()}}async retryActivation(e){let{output:t,userApi:n,emailLinkGenerator:{verification:r}}=this.config,i=t.notify("Sending email"),o=await n.createSession({destination:this.config.verificationLinkDestination.accountActivation});await n.retryActivation({email:e,sessionId:o}),i.confirm(`Link sent to \`${e}\``);let s=await this.getInboxLink(r,e),p=this.waitToken(o);return s!==null&&await t.open(s),p}async resetPassword(e){let{output:t,userApi:n,emailLinkGenerator:{recovery:r}}=this.config,i=t.notify("Sending link to reset password"),o=await n.createSession({destination:this.config.verificationLinkDestination.passwordReset});await n.requestPasswordReset({email:e,sessionId:o}),i.confirm(`Link sent to \`${e}\``);let s=await this.getInboxLink(r,e),p=this.waitToken(o);return s!==null&&await t.open(s),n.resetPassword({token:await p,password:await this.createPassword()})}async createPassword(){let{input:e,output:t}=this.config,n=null;for(;n===null;){let r=await Ke.prompt({input:e,label:"Enter your new password"}),i=await Ke.prompt({input:e,label:"Confirm your new password"});if(r!==i){t.warn("Passwords do not match, please try again");continue}n=r;}return n}async getInboxLink(e,t){let{input:n}=this.config,r=await e(t);return r!==null&&await n.confirm({message:"Open your inbox?",default:true})?r.toString():null}async waitToken(e){let{output:t,listener:n}=this.config,r=t.notify("Waiting for confirmation"),i=await n.wait(e);return r.confirm("Login completed"),i}};var Kn=class{constructor(e){this.config=e;}async handle(e){let{input:t,output:n,listener:r,userApi:i}=this.config;n.inform("*By continuing, you agree to our [Terms of Use](https://croct.link/terms-of-use) and [Privacy Policy](https://croct.link/privacy)*");let o=await Ee.prompt({input:t,minimumLength:2,maximumLength:30,label:"Name"}),[s,p]=o.replace(/\s+/g," ").trim().split(" "),c=e.email??await qe.prompt({input:t,label:"Email"}),l=await Ke.prompt({input:t,label:"Password",validator:M=>/[A-Z]/.test(M)?/[a-z]/.test(M)?/[^A-Za-z]/.test(M)?M.length<8?"Minimum of 8 characters":M.length>256?"Maximum of 256 characters":true:"Must contain a special character":"Must contain a lowercase letter":"Must contain an uppercase letter"}),u=i.createSession({destination:this.config.verificationLinkDestination}),g=n.notify("Creating account");await i.registerUser({sessionId:await u,email:c,password:l,firstName:s,lastName:p,expertise:e.expertise??"ENGINEERING"}),g.confirm(`Link to verify sent to \`${c}\``);let y=await this.config.emailLinkGenerator(c).then(async M=>M!==null&&await t.confirm({message:"Open your inbox?",default:true})?M.toString():null);g=n.notify("Waiting for account activation");let v=r.wait(await u);y!==null&&await n.open(y);let A=await v;return g.confirm("Account activated"),A}};var Hn=class{constructor(e){this.config=e;}async execute(e){let{output:t,pageForm:n,userApi:r}=this.config,i=await this.config.configurationManager.load(),o=await n.handle({page:e.page,organizationSlug:i.organization,workspaceSlug:i.workspace,devApplicationSlug:i.applications.development,prodApplicationSlug:i.applications.production}),s=t.notify("Logging in..."),p=await r.issueToken({duration:this.config.adminTokenDuration});s.stop();let c=new URL(o.startsWith("/")?o.slice(1):o,this.config.adminUrl);c.searchParams.set(this.config.adminTokenParameter,p),await t.open(c.toString());}};function fe(a,e){let t=[],n=null;if(traverse(a,{ImportDeclaration:i=>{let{node:o}=i;if(o.source.value!==e.moduleName)return i.skip();t.push({declaration:o});let s=o.importKind??"value";for(let p of o.specifiers)if(!(!f.isImportSpecifier(p)||Jc(p.imported)!==e.importName)){if(s==="value"&&(p.importKind===null||p.importKind===e.type)||s==="type"&&e.type==="type")return n=p.local.name,i.stop();t.unshift({declaration:o,specifier:p,localName:p.local.name});}return i.skip()}}),n!==null)return {modified:false,localName:n};if(t.length>0){for(let i of t){let{declaration:o}=i;if(o.importKind==="type"&&e.type==="value"){o.importKind="value";for(let s of o.specifiers)f.isImportSpecifier(s)&&s!==i.specifier&&(s.importKind="type");if(i.localName===void 0){let s=f.importSpecifier(f.identifier(e.localName??e.importName),f.identifier(e.importName));s.importKind=e.type,o.specifiers.push(s);}return {modified:true,localName:i.localName??e.importName}}if(i.specifier!==void 0&&i.specifier.importKind==="type"&&e.type==="value")return i.specifier.importKind="value",{modified:true,localName:i.localName}}for(let{declaration:i}of t){let o=i.importKind??"value";if(o==="value"||o===e.type){let s=f.importSpecifier(f.identifier(e.localName??e.importName),f.identifier(e.importName));return o!==e.type&&(s.importKind="type"),i.specifiers.push(s),{modified:true,localName:e.localName??e.importName}}}}let r=f.importDeclaration([f.importSpecifier(f.identifier(e.localName??e.importName),f.identifier(e.importName))],f.stringLiteral(e.moduleName));return e.type==="type"&&(r.importKind="type"),a.program.body.unshift(r),{modified:true,localName:e.localName??e.importName}}function Jc(a){return f.isIdentifier(a)?a.name:a.value}function qt(a,e){let t=typeof a=="string"?Ae(a,["jsx","typescript"]):a,n=null;return traverse(t,{ImportDeclaration:r=>{let{node:i}=r;if(!Gn(i.source.value,e.moduleName))return r.skip();for(let o of i.specifiers??[]){if(f.isImportDefaultSpecifier(o)){Gn("default",e.importName)&&(n=o.local.name);continue}if(f.isImportSpecifier(o)&&Gn(o.imported,e.importName))return n=o.local.name,r.skip()}return r.skip()}}),n}function Gn(a,e){return typeof a!="string"?Gn(f.isIdentifier(a)?a.name:a.value,e):typeof e=="string"?a===e:e.test(a)}function Bn(a){let e=[];for(let[t,n]of Object.entries(a))e.push(f.jsxAttribute(f.jsxIdentifier(t),f.jsxExpressionContainer(tt(n))));return e}function tt(a){switch(a.type){case "reference":return a.path.length<2?f.identifier(a.path[0]):a.path.slice(2).reduce((e,t)=>f.memberExpression(e,f.identifier(t)),f.memberExpression(f.identifier(a.path[0]),f.identifier(a.path[1])));case "literal":return typeof a.value=="string"?f.stringLiteral(a.value):typeof a.value=="number"?f.numericLiteral(a.value):typeof a.value=="boolean"?f.booleanLiteral(a.value):f.nullLiteral();case "comparison":return f.binaryExpression(a.operator,tt(a.left),tt(a.right));case "ternary":return f.conditionalExpression(f.binaryExpression(a.condition.operator,tt(a.condition.left),tt(a.condition.right)),tt(a.consequent),tt(a.alternate))}}var nt=class a{constructor(e){this.configuration=e;}apply(e,t){let n=qt(e,{importName:this.configuration.wrapper.component,moduleName:this.configuration.wrapper.module}),r=n??this.configuration.wrapper.component,i=[],o=1;if(traverse(e,{ExportDefaultDeclaration:p=>(o=this.wrapDeclaration(p.node.declaration,r,e,t),p.stop()),ExportNamedDeclaration:p=>(i.push(p.node),p.skip())}),o===1&&this.configuration?.fallbackToNamedExports===true)for(let p of i){if(f.isFunctionDeclaration(p.declaration)&&(o=this.wrapBlockStatement(p.declaration.body,r,e,t),o===0))break;if(f.isVariableDeclaration(p.declaration)){let{declarations:c}=p.declaration;if(c.some(u=>f.isIdentifier(u.init)||f.isArrowFunctionExpression(u.init)||f.isFunctionExpression(u.init)?this.wrapDeclaration(u.init,r,e,t)===0:false)){o=0;break}}for(let c of p.specifiers??[])if(f.isExportSpecifier(c)){let l=this.findComponentDeclaration(e,c.local.name);if(l!==null&&f.isVariableDeclarator(l)&&f.isExpression(l.init)&&(o=this.wrapDeclaration(l.init,r,e,t),o===0))break}if(o===0)break}if(o===0&&n===null){let{body:p}=e.program;f.isImportDeclaration(p[0])||p.unshift(f.emptyStatement()),fe(e,{type:"value",moduleName:this.configuration.wrapper.module,importName:this.configuration.wrapper.component});}let s=this.configuration?.fallbackCodemod;return o===1&&s!==void 0?s.apply(e,t):Promise.resolve({modified:o===0,result:e})}wrapDeclaration(e,t,n,r){if(f.isArrowFunctionExpression(e)){if(f.isBlockStatement(e.body))return this.wrapBlockStatement(e.body,t,n,r);let i=this.insertWrapper(e.body,t,n,r);return i.result!==0?i.result:(e.body=i.node,0)}if(f.isFunctionExpression(e)||f.isFunctionDeclaration(e))return this.wrapBlockStatement(e.body,t,n,r);if(f.isIdentifier(e)){let i=this.findComponentDeclaration(n,e.name);if(i!==null)if(f.isVariableDeclarator(i)){let o=i.init??null;if(o!==null)return this.wrapDeclaration(o,t,n,r)}else return this.wrapBlockStatement(i.body,t,n,r)}return 1}wrapBlockStatement(e,t,n,r){let i=a.findReturnStatement(e),o=i?.argument??null;if(i!==null&&o!==null){let s=this.insertWrapper(o,t,n,r);return s.result!==0?s.result:(i.argument=f.parenthesizedExpression(s.node),0)}return 1}insertWrapper(e,t,n,r){if(this.containsElement(e,t))return {result:2,node:e};let i=this.findTargetChildren(n,e);if(i!==null){let{parent:o,index:s}=i,p=[...o.children??[]],c=p.splice(s,1)[0];return i.parent.children=p.length===0?[f.jsxText(`
1726
+ `);function yt(a){return {model:a,api:Object.fromEntries(Object.entries(a).map(([e,t])=>[t,e]))}}var ka=yt({javascript:"JAVASCRIPT",react:"REACT",nextjs:"NEXT"}),Aa=yt({DEVELOPMENT:"DEVELOPMENT",PRODUCTION:"PRODUCTION"}),Mp=yt({NEVER_RECEIVED_TRAFFIC:"NEVER_RECEIVED_TRAFFIC",NOT_RECEIVING_TRAFFIC:"NOT_RECEIVING_TRAFFIC",RECEIVING_TRAFFIC:"RECEIVING_TRAFFIC"}),Gc=yt({PLUG_JS:"PLUG_JS"}),Ea=yt({DRAFT:"DRAFT",ACTIVE:"ACTIVE",SCHEDULED:"SCHEDULED",PAUSED:"PAUSED",ARCHIVED:"ARCHIVED"}),Bc=yt({DRAFT:"DRAFT",ACTIVE:"ACTIVE",SCHEDULED:"SCHEDULED",PAUSED:"PAUSED",FINISHED:"FINISHED",INDIRECTLY_PAUSED:"INDIRECTLY_PAUSED"}),Ln=class a{constructor(e,t){this.client=e,this.hierarchyResolver=t;}async getFeatures(e){let{data:t}=await this.client.execute(yp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug}),n=t.organization?.workspace??null;if(n===null)return null;let{quotas:r,capabilities:{features:i}}=n;return {quotas:{audiences:r.audience,remainingAudiences:r.remainingAudiences,components:r.component,remainingComponents:r.remainingComponents,slots:r.slot,remainingSlots:r.remainingSlots,experiences:r.experience,remainingExperiences:r.remainingExperiences,dynamicAttributesPerContent:r.dynamicAttributesPerContent,audiencesPerExperience:r.audiencesPerExperience},features:{crossDevice:i.includes("CROSS_DEVICE_EXPERIMENT"),dataExport:i.includes("API_DATA_EXPORT")}}}async getApplications(e){let{data:t}=await this.client.execute(Pp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return (t.organization?.workspace?.applications.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[a.normalizeApplication(i)]})}async getApplication(e){let{data:t}=await this.client.execute(Cp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,applicationSlug:e.applicationSlug}),n=t.organization?.workspace?.application??null;return n===null?null:a.normalizeApplication(n)}static normalizeApplication(e){let{logo:t=null}=e;return {id:e.id,name:e.name,slug:e.slug,timeZone:e.settings.timeZone,website:e.website,environment:Aa.api[e.environment],platform:ka.api[e.platform??"JAVASCRIPT"],publicId:e.publicId,trafficStatus:Mp.api[e.applicationStatus],...t!==null?{logo:t}:{}}}async createApplication(e){let t=await this.hierarchyResolver.getHierarchy({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug}),{data:n}=await this.client.execute(kp,{workspaceId:t.workspaceId,payload:{name:e.name,website:e.website,environment:Aa.model[e.environment],platform:ka.model[e.platform],timeZone:e.timeZone,slug:await this.generateApplicationSlug(t.workspaceId,e.name,e.environment)}}),r=n.createWebApplication,{logo:i=null}=r;return {id:r.id,name:r.name,slug:r.slug,timeZone:r.settings.timeZone,website:r.website,environment:Aa.api[r.environment],platform:ka.api[r.platform??"JAVASCRIPT"],publicId:r.publicId,trafficStatus:Mp.api[r.applicationStatus],...i!==null?{logo:i}:{}}}async getAudiences(e){let{data:t}=await this.client.execute(Sp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return (t.organization?.workspace?.audiences.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[a.normalizeAudience(i)]})}async getAudience(e){let{data:t}=await this.client.execute(bp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,audienceSlug:e.audienceSlug}),n=t.organization?.workspace?.audience??null;return n===null?null:a.normalizeAudience(n)}static normalizeAudience(e){return {id:e.id,name:e.name,slug:e.customId,criteria:e.criteria}}async getComponents(e){let{data:t}=await this.client.execute(Ep,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return (t.organization?.workspace?.components.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[a.normalizeComponent(i)]})}async getComponent(e){let{data:t}=await this.client.execute(Op,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,componentSlug:e.componentSlug,majorVersion:e.majorVersion}),n=t.organization?.workspace?.component??null;return n===null?null:a.normalizeComponent(n)}static normalizeComponent(e){let{definition:t,metadata:{directReferences:n,indirectReferences:r,referenceMetadata:i}}=e.definition,o=e.description??null;return {id:e.id,name:e.name,slug:e.customId,...o!==null?{description:o}:{},definition:t,version:{major:e.definition.version.major,minor:e.definition.version.minor},metadata:{directReferences:n.map(s=>i.find(({componentId:p})=>p===s)?.referenceName??s),indirectReferences:r.map(s=>i.find(({componentId:p})=>p===s)?.referenceName??s)}}}async getSlots(e){let{data:t}=await this.client.execute(Ip,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return (t.organization?.workspace?.slots.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[a.normalizeSlot(i)]})}async getSlot(e){let{data:t}=await this.client.execute(vp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,slotSlug:e.slotSlug,majorVersion:e.majorVersion}),n=t.organization?.workspace?.slot??null;return n===null?null:a.normalizeSlot(n)}static normalizeSlot(e){let{component:t=null}=e.content,n=t?.definition.metadata??null;return {id:e.id,name:e.name,slug:e.customId,...t!==null&&n!==null?{component:{slug:t.customId,version:{major:t.definition.version.major,minor:t.definition.version.minor},metadata:{directReferences:n.directReferences.map(r=>n.referenceMetadata.find(({componentId:i})=>i===r)?.referenceName??r),indirectReferences:n.indirectReferences.map(r=>n.referenceMetadata.find(({componentId:i})=>i===r)?.referenceName??r)}}}:{},version:{major:e.content.version.major,minor:e.content.version.minor},resolvedDefinition:e.content.componentDefinition.resolvedDefinition,content:Object.fromEntries(e.content.default.map(({locale:r,content:i})=>[r,i]))}}async getSlotStaticContent(e,t){let{data:n}=await this.client.execute(xp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,slotSlug:e.slotSlug,majorVersion:t});return (n.organization?.workspace?.slot?.staticContent??[]).map(i=>({locale:i.locale,content:i.content}))}async generateTypes(e){let t=await this.hierarchyResolver.getHierarchy({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug}),{data:n}=await this.client.execute(Dp,{workspaceId:t.workspaceId,payload:{target:Gc.model[e.target],components:e.components,slots:e.slots}});return n.generateTyping}async getExperiences(e){let{data:t}=await this.client.execute(Tp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,status:e.status===void 0?void 0:(Array.isArray(e.status)?e.status:[e.status]).map(r=>Ea.model[r])});return (t.organization?.workspace?.experiences.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[a.normalizeExperience(i)]})}async getExperience(e){let{data:t}=await this.client.execute(Rp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,experienceId:e.experienceId}),n=t.organization?.workspace?.experience??null;return n===null?null:a.normalizeExperienceDetails(n)}static normalizeExperience(e){let t=e.settings?.audiences??e.draft?.audiences??[],n=e.settings?.slots??e.draft?.slots??[],r=e.currentExperiment?.name??e.draft?.experiment?.name??null;return {id:e.id,name:e.name,priority:e.priority??e.draft?.priority??0,status:Ea.api[e.status],audiences:t.map(i=>i.customId),slots:n.flatMap(({slot:i=null})=>i===null?[]:[i.customId]),...r!==null?{experiment:{name:r}}:{}}}static normalizeExperienceDetails(e){let t=e.settings?.audiences??e.draft?.audiences??[],n=e.settings?.slots??e.draft?.slots??[],r=e.currentExperiment??e.draft?.experiment??null,{name:i=null,goalId:o=null,crossDevice:s=null,traffic:p=null}=r??{},c=Object.fromEntries(n.flatMap(({slot:l=null})=>l===null?[]:[[l.id,l.customId]]));return {id:e.id,name:e.name,priority:e.priority??e.draft?.priority??0,status:Ea.api[e.status],hasExperiments:e.hasExperiments,audiences:t.map(l=>l.customId),slots:Object.values(c),...r!==null?{experiment:{...i!==null?{name:i}:{},...o!==null?{goalId:o}:{},...s!==null?{crossDevice:s}:{},...p!==null?{traffic:p}:{},..."status"in r?{status:Bc.api[r.status]}:{},variants:(r.variants??[]).map(l=>{let u=l.variantId,g=l.name??null,y=l.allocation??null;return {...u!==null?{id:u}:{},...g!==null?{name:g}:{},...y!==null?{allocation:y}:{},baseline:l.baseline===true,content:{default:a.normalizeLocalizedContent(l.content?.default.contents??[],c),segmented:(l.content?.segmented??[]).map(v=>({id:v.groupId,audiences:v.audiences.map(A=>A.audienceId),content:a.normalizeLocalizedContent(v.contents,c)}))}}})}}:{},content:{default:a.normalizeLocalizedContent(e.settings?.content.default.contents??e.draft?.content?.default.contents??[],c),segmented:(e.settings?.content.segmented??e.draft?.content?.segmented??[]).map(l=>({id:l.groupId,audiences:l.audiences.map(({audienceId:u})=>t.find(({id:g})=>g===u)?.customId??u),content:a.normalizeLocalizedContent(l.contents,c)}))}}}static normalizeLocalizedContent(e,t){let n={};for(let r of e){let{locale:i,slotId:o}=r,s=t[o];s!==void 0&&(n[s]===void 0&&(n[s]={}),n[s][i]=r.content);}return n}async createResources(e){let t=await this.hierarchyResolver.getHierarchy({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug}),n={components:Object.entries(e.components??{}).map(([i,o])=>({customId:i,name:o.name,description:o.description,definition:o.schema})),slots:Object.entries(e.slots??{}).map(([i,o])=>({customId:i,name:o.name,component:o.component,defaultContent:Object.entries(o.content).map(([s,p])=>({locale:s,content:p}))})),audiences:Object.entries(e.audiences??{}).map(([i,o])=>({customId:i,name:o.name,criteria:o.criteria})),experiences:(e.experiences??[]).map(i=>{let o=i.experiment??null;return {name:i.name,audiences:i.audiences,slots:i.slots,experiment:o!==null?{name:o.name,goalId:o.goalId,traffic:o.traffic,crossDevice:o.crossDevice===true,variants:o.variants.map(s=>({id:randomUUID(),name:s.name??"",baseline:s.baseline===true,allocation:s.allocation??0,content:a.createContentVariantGroup(s.content)}))}:void 0,content:a.createContentVariantGroup(i.content),validate:true,publish:i.draft!==true}})},{data:{createWorkspaceResources:r}}=await this.client.execute(hp,{workspaceId:t.workspaceId,payload:n});return {components:Object.fromEntries(n.components.map(({customId:i},o)=>[i,r.components[o]])),slots:Object.fromEntries(n.slots.map(({customId:i},o)=>[i,r.slots[o]])),audiences:Object.fromEntries(n.audiences.map(({customId:i},o)=>[i,r.audiences[o]])),experiences:r.experiences.map(i=>{let o=i.experimentId??null;return {experienceId:i.id,...o!==null?{experimentId:o}:{}}})}}static createContentVariantGroup(e){return {default:{id:randomUUID(),contents:a.createSlotContentMap(e.default??{})},segmented:(e.segmented??[]).map(t=>({id:randomUUID(),audiences:t.audiences,contents:a.createSlotContentMap(t.content)}))}}static createSlotContentMap(e){return Object.entries(e).flatMap(([t,n])=>Object.entries(n).map(([r,i])=>({slot:t,locale:r,content:i})))}generateApplicationSlug(e,t,n){return Ye({query:wp,baseName:`${t} ${n==="DEVELOPMENT"?"dev":"prod"}`,client:this.client,variables:{workspaceId:e}})}};var et;(t=>{function a(){return Intl.DateTimeFormat().resolvedOptions().locale.toLowerCase()}t.getLocale=a;function e(){return Intl.DateTimeFormat().resolvedOptions().timeZone}t.getTimeZone=e;})(et||={});var ht=class a{constructor(e){this.config=e;}static prompt(e){return new a(e).handle()}handle(){let{input:e,validate:t}=this.config;return e.prompt({message:this.config.label,default:this.config.default,initial:this.config.initial??"https://",validate:n=>URL.canParse(n)?t!==void 0?t(n):true:"Invalid URL"})}};var Fn=class{constructor(e){this.config=e;}async handle(e={}){let{userApi:t,output:n,input:r}=this.config;if(e.new!==true){let c=n.notify("Loading organizations"),l=[];if(e.default!==void 0){let u=await t.getOrganization(e.default);u!==null&&l.push(u);}if(l.length===0&&l.push(...await t.getOrganizations()),l.length===1){let u=l[0];return c.confirm(`Organization: ${u.name}`),u}if(c.stop(),l.length>0)return r.select({message:"Select organization",options:l.map(u=>({value:u,label:u.name}))})}let i=et.getTimeZone(),o=et.getLocale();n.inform("Setting up a new organization"),n.inform("*By continuing, you agree to our [Terms of Service](https://croct.link/terms-of-service)*");let s=await ht.prompt({input:r,label:"Organization website"}),p=this.notify("Setting up organization");try{let c=await t.setupOrganization({website:s,locale:o,timeZone:i});return p.confirm(`Organization: ${c.name}`),{...c,new:!0}}finally{p.stop();}}notify(e){let{output:t}=this.config,n=["Visiting website","Detecting tech stack","Configuring organization","Creating workspace","Configuring applications","Setting up organization"],r=t.notify(e),i=0,o=setInterval(()=>{i>=n.length?clearInterval(o):r.update(n[i++]);},3e3);return o.unref(),{confirm:(s,p)=>{clearInterval(o),r.confirm(s,p);},stop:s=>{clearInterval(o),r.stop(s);}}}};var Ee=class a{constructor(e){this.config=e;}static prompt(e){return new a(e).handle()}handle(){let{input:e,validator:t,minimumLength:n=2,maximumLength:r=30}=this.config;return e.prompt({message:this.config.label,default:this.config.default,initial:this.config.initial,validate:i=>/(^\s|\s$|\s{2,})/.test(i)?"No leading, trailing, or multiple spaces.":i.length<n?`Minimum of ${n} characters`:i.length>r?`Maximum of ${r} characters`:t?.(i)??true})}};var jn=class a{constructor(e){this.config=e;}async handle(e){let{organizationApi:t,output:n,input:r}=this.config,{organization:i}=e;if(e.new===false){let o=n.notify("Loading workspaces"),s=await t.getWorkspaces({organizationSlug:i.slug}),p=a.getDefaultWorkspace(s,e.default);if(p!==null)return o.confirm(`Workspace: ${p.name}`),p;if(o.stop(),s.length>0)return r.select({message:"Select workspace",options:s.map(c=>({value:c,label:c.name}))})}return this.setupWorkspace(i,e.new===true)}async setupWorkspace(e,t){let{organizationApi:n,input:r,output:i}=this.config,o=t?await Ee.prompt({input:r,label:"Workspace name",default:e.name}):e.name,s=et.getLocale(),p=et.getTimeZone(),c=i.notify("Creating workspace");try{let l=await n.createWorkspace({organizationSlug:e.slug,name:o,website:e.website,defaultLocale:s,timeZone:p});return c.confirm(`Workspace: ${l.name}`),{...l,new:t}}finally{c.stop();}}static getDefaultWorkspace(e,t){return e.length===1?e[0]:t!==void 0?e.find(({slug:n})=>n===t)??null:null}};var Un=class a{constructor(e){this.config=e;}async handle(e){let{workspaceApi:t,output:n,input:r}=this.config,{organization:i,workspace:o,environment:s}=e,p=n.notify("Loading applications"),c=await t.getApplications({workspaceSlug:o.slug,organizationSlug:i.slug}),l=c.filter(u=>u.environment===s&&(e.default??u.slug)===u.slug);if(p.stop(),l.length===0||e.new===true)return this.setupApplication(e,c);if(l.length===1){let u=l[0];return n.confirm(a.formatSelection(u)),u}return r.select({message:s==="DEVELOPMENT"?"Select development application":"Select production application",options:l.map(u=>({value:u,label:u.name}))})}async setupApplication(e,t){let{workspaceApi:n,output:r,input:i}=this.config,{organization:o,workspace:s,platform:p,environment:c}=e,l=e.new===true,u=l?await Ee.prompt({input:i,label:c==="DEVELOPMENT"?"Development application name":"Production application name",default:"Website",validator:A=>t.every(M=>M.name.toLowerCase()!==A.toLowerCase()||M.environment!==c)||"Name already in use"}):"Website",g=s.website??o.website??void 0,y=l||!a.isValidUrl(g,c)?await ht.prompt({input:i,label:c==="DEVELOPMENT"?"Development application URL":"Production application URL",default:g,validate:A=>URL.canParse(A)?a.isValidUrl(A,c)?true:"Production URL must not be localhost":"Invalid URL"}):g,v=r.notify("Configuring application");try{let A=await n.createApplication({organizationSlug:o.slug,workspaceSlug:s.slug,name:u,website:y,environment:c,platform:p,timeZone:s.timeZone});return v.confirm(a.formatSelection(A)),{...A,new:!0}}finally{v.stop();}}static isValidUrl(e,t){return e===void 0||!URL.canParse(e)?false:t!=="PRODUCTION"||new URL(e).hostname!=="localhost"}static formatSelection(e){return e.environment==="DEVELOPMENT"?`Development application: ${e.name} (${e.slug})`:`Production application: ${e.name} (${e.slug})`}};var Vn=class{constructor(e,t){this.client=e,this.hierarchyResolver=t;}async createApiKey(e){let t=await this.hierarchyResolver.getHierarchy({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,applicationSlug:e.applicationSlug}),{data:n}=await this.client.execute(Ap,{applicationId:t.applicationId,payload:{name:e.name,permissions:e.permissions}}),{apiKey:r}=n.createApiKey;return {id:r.id,name:r.name,permissions:r.permissions.map(ae.fromValue),secret:n.createApiKey.apiKeyValue}}};var qe=class a{constructor(e){this.config=e;}static prompt(e){return new a(e).handle()}handle(){let{input:e}=this.config;return e.prompt({message:this.config.label,validate:t=>t.length>255?"The email must be less than 255 characters":/^([A-Z0-9_+-]+\.?)*[A-Z0-9_+-]@([A-Z0-9][A-Z0-9-]*\.)+[A-Z]{2,}$/i.test(t)?true:"Please enter a valid email"})}};var Wn=class{constructor(e){this.config=e;}getToken(){return Promise.resolve(null)}login(e={}){if(e.username===void 0||e.password===void 0)return this.loginInteractively(e);let{form:t}=this.config;return t.signIn.handle({email:e.username,password:e.password})}async loginInteractively(e){let{input:t,output:n,userApi:r,form:i}=this.config,o=e.username??await qe.prompt({input:t,label:"Enter your email"}),s=n.notify("Finding account"),p=await r.isEmailRegistered(o);return s.stop(),p?(e.password===void 0&&n.inform("Account found, please sign in"),i.signIn.handle({email:o,password:e.password,retry:true})):(n.inform("New account, please sign up"),i.signUp.handle({email:o}))}logout(){return Promise.resolve()}};var Ke=class a{constructor(e){this.config=e;}static prompt(e){return new a(e).handle()}handle(){let{input:e}=this.config;return e.prompt({message:this.config.label,type:"password",validate:this.config.validator??(t=>t.length>0?true:"Please enter your password")})}};var qn=class{constructor(e){this.config=e;}handle(e){return this.login(e.email,e.password,e.retry)}async login(e,t,n=false){let{input:r,output:i,userApi:o}=this.config,s=e??await qe.prompt({input:this.config.input,label:"Enter your email"}),p=t,c="retry-password";for(;c==="retry-password";){let l=p??await Ke.prompt({input:r,label:"Password"});p=void 0;let u=i.notify("Checking credentials");try{let g=await o.signIn({email:s,password:l,duration:this.config.tokenDuration});return u.confirm("Logged in"),g}catch(g){if(g instanceof ee){if(g.isAccessDenied("UNVERIFIED_USER")){if(!n)throw new d("Email not verified.",{reason:"access_denied",cause:g,suggestions:["Access your email and click on the activation link"]});u.warn("Email not verified"),c=await r.confirm({message:"Resend activation link?",default:true})?"retry-activation":"cancel";continue}if(g.isAccessDenied("BAD_CREDENTIALS")){if(!n)throw new d("Username or password is incorrect.",{reason:"access_denied",cause:g,suggestions:["Check your credentials or reset your password"]});u.alert("Wrong password"),c=await r.select({message:"What would you like to do?",default:"retry-password",options:[{label:"Try again",value:"retry-password"},{label:"Recover password",value:"reset-password"},...e===void 0?[{label:"Enter a different email",value:"change-email"}]:[],{label:"Cancel",value:"cancel"}]});continue}}throw u.stop(),g}}switch(c){case "change-email":return this.login();case "retry-activation":return this.retryActivation(s);case "reset-password":return this.resetPassword(s);case "cancel":default:return i.exit()}}async retryActivation(e){let{output:t,userApi:n,emailLinkGenerator:{verification:r}}=this.config,i=t.notify("Sending email"),o=await n.createSession({destination:this.config.verificationLinkDestination.accountActivation});await n.retryActivation({email:e,sessionId:o}),i.confirm(`Link sent to \`${e}\``);let s=await this.getInboxLink(r,e),p=this.waitToken(o);return s!==null&&await t.open(s),p}async resetPassword(e){let{output:t,userApi:n,emailLinkGenerator:{recovery:r}}=this.config,i=t.notify("Sending link to reset password"),o=await n.createSession({destination:this.config.verificationLinkDestination.passwordReset});await n.requestPasswordReset({email:e,sessionId:o}),i.confirm(`Link sent to \`${e}\``);let s=await this.getInboxLink(r,e),p=this.waitToken(o);return s!==null&&await t.open(s),n.resetPassword({token:await p,password:await this.createPassword()})}async createPassword(){let{input:e,output:t}=this.config,n=null;for(;n===null;){let r=await Ke.prompt({input:e,label:"Enter your new password"}),i=await Ke.prompt({input:e,label:"Confirm your new password"});if(r!==i){t.warn("Passwords do not match, please try again");continue}n=r;}return n}async getInboxLink(e,t){let{input:n}=this.config,r=await e(t);return r!==null&&await n.confirm({message:"Open your inbox?",default:true})?r.toString():null}async waitToken(e){let{output:t,listener:n}=this.config,r=t.notify("Waiting for confirmation"),i=await n.wait(e);return r.confirm("Login completed"),i}};var Kn=class{constructor(e){this.config=e;}async handle(e){let{input:t,output:n,listener:r,userApi:i}=this.config;n.inform("*By continuing, you agree to our [Terms of Use](https://croct.link/terms-of-use) and [Privacy Policy](https://croct.link/privacy)*");let o=await Ee.prompt({input:t,minimumLength:2,maximumLength:30,label:"Name"}),[s,p]=o.replace(/\s+/g," ").trim().split(" "),c=e.email??await qe.prompt({input:t,label:"Email"}),l=await Ke.prompt({input:t,label:"Password",validator:M=>/[A-Z]/.test(M)?/[a-z]/.test(M)?/[^A-Za-z]/.test(M)?M.length<8?"Minimum of 8 characters":M.length>256?"Maximum of 256 characters":true:"Must contain a special character":"Must contain a lowercase letter":"Must contain an uppercase letter"}),u=i.createSession({destination:this.config.verificationLinkDestination}),g=n.notify("Creating account");await i.registerUser({sessionId:await u,email:c,password:l,firstName:s,lastName:p,expertise:e.expertise??"ENGINEERING"}),g.confirm(`Link to verify sent to \`${c}\``);let y=await this.config.emailLinkGenerator(c).then(async M=>M!==null&&await t.confirm({message:"Open your inbox?",default:true})?M.toString():null);g=n.notify("Waiting for account activation");let v=r.wait(await u);y!==null&&await n.open(y);let A=await v;return g.confirm("Account activated"),A}};var Hn=class{constructor(e){this.config=e;}async execute(e){let{output:t,pageForm:n,userApi:r}=this.config,i=await this.config.configurationManager.load(),o=await n.handle({page:e.page,organizationSlug:i.organization,workspaceSlug:i.workspace,devApplicationSlug:i.applications.development,prodApplicationSlug:i.applications.production}),s=t.notify("Logging in..."),p=await r.issueToken({duration:this.config.adminTokenDuration});s.stop();let c=new URL(o.startsWith("/")?o.slice(1):o,this.config.adminUrl);c.searchParams.set(this.config.adminTokenParameter,p),await t.open(c.toString());}};function fe(a,e){let t=[],n=null;if(traverse(a,{ImportDeclaration:i=>{let{node:o}=i;if(o.source.value!==e.moduleName)return i.skip();t.push({declaration:o});let s=o.importKind??"value";for(let p of o.specifiers)if(!(!f.isImportSpecifier(p)||Jc(p.imported)!==e.importName)){if(s==="value"&&(p.importKind===null||p.importKind===e.type)||s==="type"&&e.type==="type")return n=p.local.name,i.stop();t.unshift({declaration:o,specifier:p,localName:p.local.name});}return i.skip()}}),n!==null)return {modified:false,localName:n};if(t.length>0){for(let i of t){let{declaration:o}=i;if(o.importKind==="type"&&e.type==="value"){o.importKind="value";for(let s of o.specifiers)f.isImportSpecifier(s)&&s!==i.specifier&&(s.importKind="type");if(i.localName===void 0){let s=f.importSpecifier(f.identifier(e.localName??e.importName),f.identifier(e.importName));s.importKind=e.type,o.specifiers.push(s);}return {modified:true,localName:i.localName??e.importName}}if(i.specifier!==void 0&&i.specifier.importKind==="type"&&e.type==="value")return i.specifier.importKind="value",{modified:true,localName:i.localName}}for(let{declaration:i}of t){let o=i.importKind??"value";if(o==="value"||o===e.type){let s=f.importSpecifier(f.identifier(e.localName??e.importName),f.identifier(e.importName));return o!==e.type&&(s.importKind="type"),i.specifiers.push(s),{modified:true,localName:e.localName??e.importName}}}}let r=f.importDeclaration([f.importSpecifier(f.identifier(e.localName??e.importName),f.identifier(e.importName))],f.stringLiteral(e.moduleName));return e.type==="type"&&(r.importKind="type"),a.program.body.unshift(r),{modified:true,localName:e.localName??e.importName}}function Jc(a){return f.isIdentifier(a)?a.name:a.value}function qt(a,e){let t=typeof a=="string"?Ae(a,["jsx","typescript"]):a,n=null;return traverse(t,{ImportDeclaration:r=>{let{node:i}=r;if(!Gn(i.source.value,e.moduleName))return r.skip();for(let o of i.specifiers??[]){if(f.isImportDefaultSpecifier(o)){Gn("default",e.importName)&&(n=o.local.name);continue}if(f.isImportSpecifier(o)&&Gn(o.imported,e.importName))return n=o.local.name,r.skip()}return r.skip()}}),n}function Gn(a,e){return typeof a!="string"?Gn(f.isIdentifier(a)?a.name:a.value,e):typeof e=="string"?a===e:e.test(a)}function Bn(a){let e=[];for(let[t,n]of Object.entries(a))e.push(f.jsxAttribute(f.jsxIdentifier(t),f.jsxExpressionContainer(tt(n))));return e}function tt(a){switch(a.type){case "reference":return a.path.length<2?f.identifier(a.path[0]):a.path.slice(2).reduce((e,t)=>f.memberExpression(e,f.identifier(t)),f.memberExpression(f.identifier(a.path[0]),f.identifier(a.path[1])));case "literal":return typeof a.value=="string"?f.stringLiteral(a.value):typeof a.value=="number"?f.numericLiteral(a.value):typeof a.value=="boolean"?f.booleanLiteral(a.value):f.nullLiteral();case "comparison":return f.binaryExpression(a.operator,tt(a.left),tt(a.right));case "ternary":return f.conditionalExpression(f.binaryExpression(a.condition.operator,tt(a.condition.left),tt(a.condition.right)),tt(a.consequent),tt(a.alternate))}}var nt=class a{constructor(e){this.configuration=e;}apply(e,t){let n=qt(e,{importName:this.configuration.wrapper.component,moduleName:this.configuration.wrapper.module}),r=n??this.configuration.wrapper.component,i=[],o=1;if(traverse(e,{ExportDefaultDeclaration:p=>(o=this.wrapDeclaration(p.node.declaration,r,e,t),p.stop()),ExportNamedDeclaration:p=>(i.push(p.node),p.skip())}),o===1&&this.configuration?.fallbackToNamedExports===true)for(let p of i){if(f.isFunctionDeclaration(p.declaration)&&(o=this.wrapBlockStatement(p.declaration.body,r,e,t),o===0))break;if(f.isVariableDeclaration(p.declaration)){let{declarations:c}=p.declaration;if(c.some(u=>f.isIdentifier(u.init)||f.isArrowFunctionExpression(u.init)||f.isFunctionExpression(u.init)?this.wrapDeclaration(u.init,r,e,t)===0:false)){o=0;break}}for(let c of p.specifiers??[])if(f.isExportSpecifier(c)){let l=this.findComponentDeclaration(e,c.local.name);if(l!==null&&f.isVariableDeclarator(l)&&f.isExpression(l.init)&&(o=this.wrapDeclaration(l.init,r,e,t),o===0))break}if(o===0)break}if(o===0&&n===null){let{body:p}=e.program;f.isImportDeclaration(p[0])||p.unshift(f.emptyStatement()),fe(e,{type:"value",moduleName:this.configuration.wrapper.module,importName:this.configuration.wrapper.component});}let s=this.configuration?.fallbackCodemod;return o===1&&s!==void 0?s.apply(e,t):Promise.resolve({modified:o===0,result:e})}wrapDeclaration(e,t,n,r){if(f.isArrowFunctionExpression(e)){if(f.isBlockStatement(e.body))return this.wrapBlockStatement(e.body,t,n,r);let i=this.insertWrapper(e.body,t,n,r);return i.result!==0?i.result:(e.body=i.node,0)}if(f.isFunctionExpression(e)||f.isFunctionDeclaration(e))return this.wrapBlockStatement(e.body,t,n,r);if(f.isIdentifier(e)){let i=this.findComponentDeclaration(n,e.name);if(i!==null)if(f.isVariableDeclarator(i)){let o=i.init??null;if(o!==null)return this.wrapDeclaration(o,t,n,r)}else return this.wrapBlockStatement(i.body,t,n,r)}return 1}wrapBlockStatement(e,t,n,r){let i=a.findReturnStatement(e),o=i?.argument??null;if(i!==null&&o!==null){let s=this.insertWrapper(o,t,n,r);return s.result!==0?s.result:(i.argument=f.parenthesizedExpression(s.node),0)}return 1}insertWrapper(e,t,n,r){if(this.containsElement(e,t))return {result:2,node:e};let i=this.findTargetChildren(n,e);if(i!==null){let{parent:o,index:s}=i,p=[...o.children??[]],c=p.splice(s,1)[0];return i.parent.children=p.length===0?[f.jsxText(`
1727
1727
  `),this.wrapElement(c,t,r),f.jsxText(`
1728
1728
  `)]:[...p.slice(0,s),this.wrapElement(c,t,r),...p.slice(s)],{result:0,node:e}}return f.isJSXText(e)||f.isJSXExpressionContainer(e)||f.isJSXSpreadChild(e)||f.isJSXElement(e)||f.isJSXFragment(e)?{result:0,node:this.wrapElement(e,t,r)}:{result:1,node:e}}wrapElement(e,t,n){return e.extra?.parenthesized===true&&(e.extra.parenthesized=false),f.jsxElement(f.jsxOpeningElement(f.jsxIdentifier(t??this.configuration.wrapper.component),this.getProviderProps(n)),f.jsxClosingElement(f.jsxIdentifier(t??this.configuration.wrapper.component)),[f.jsxText(`
1729
1729
  `),e,f.jsxText(`
@@ -1759,18 +1759,18 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
1759
1759
 
1760
1760
  `);throw new $(`The response data is invalid:
1761
1761
 
1762
- ${i}`,{reason:"invalid_input",url:e})}return {...n,value:r.data}}};var pt=class{constructor(e){this.provider=e;}async get(e){let{value:t,...n}=await this.provider.get(e),r=await t.next();if(r.done===true||r.value.type!=="file")throw new De("File not found.",{url:e});return {...n,value:await new Response(r.value.content).text()}}};var tn=class{constructor(e){this.provider=e;}async get(e){let{value:t,...n}=await this.provider.get(e);try{return {...n,value:JsonParser.parse(t).toJSON()}}catch(r){throw new $("Malformed JSON.",{reason:"precondition",url:e,cause:r})}}};var kl=z.strictObject({pattern:z.string().refine(a=>{try{return new RegExp(a),!0}catch{return {message:"Invalid regular expression."}}}),destination:z.string()}),Al=z.array(kl),jr=class extends G{constructor(){super(Al);}};var nn=class{constructor({fileSystem:e,directory:t,useKeyAsFileName:n}){this.fileSystem=e,this.directory=t,this.useKeyAsFileName=n??false;}async delete(e){await this.fileSystem.delete(this.getCacheFile(e));}async get(e,t){try{return await this.fileSystem.readTextFile(this.getCacheFile(e))}catch{return t(e)}}async set(e,t){return await this.fileSystem.exists(this.directory)||await this.fileSystem.createDirectory(this.directory,{recursive:true}),this.fileSystem.writeTextFile(this.getCacheFile(e),t,{overwrite:true})}getCacheFile(e){return this.fileSystem.joinPaths(this.directory,this.useKeyAsFileName?e:createHash("md5").update(e).digest("hex"))}};var rn=class{constructor({provider:e,resourceCache:t,errorCache:n}){this.provider=e,this.resourceCache=t,this.errorCache=n;}async get(e){let t=await this.errorCache?.get(e.toString(),()=>Promise.resolve());return t!==void 0?Promise.reject(t):this.resourceCache.get(e.toString(),async()=>{try{return await this.provider.get(e)}catch(n){throw this.errorCache?.set(e.toString(),n),n}})}};var Ct;(e=>{function a(...t){return t.reduce((n,r)=>Object.defineProperties(n,Object.getOwnPropertyDescriptors(r)),{})}e.merge=a;})(Ct||={});var N=class a extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,a.prototype);}};var an=class a extends N{constructor(e,t){super(e,t),Object.setPrototypeOf(this,a.prototype);}},ja=Symbol("regex"),Ur=class a{constructor(e={}){this.cache=new Map;this.configuration=e;}static{this.ALLOWED_ARRAY_PROPERTIES=["length"];}static{this.ALLOWED_ARRAY_METHODS=["slice","join","includes","indexOf"];}static{this.ALLOWED_STRING_PROPERTIES=["length"];}static{this.ALLOWED_STRING_METHODS=["slice","indexOf","match","matchAll","replace","replaceAll","includes","startsWith","endsWith","toLowerCase","toUpperCase","repeat","split"];}static{this.ALLOWED_REGEX_PROPERTIES=["source"];}static{this.ALLOWED_REGEX_METHODS=["test"];}static{this.LITERALS={true:true,false:false,null:null};}static{this.UNARY_OPERATORS={"!":{evaluate:async e=>!await on(e)},"-":{evaluate:async e=>-await q(e)},"+":{evaluate:async e=>+await q(e)}};}static{this.BINARY_OPERATORS={"||":{precedence:1,evaluate:async(e,t)=>await on(e)||on(t)},"??":{precedence:1,evaluate:async(e,t)=>{let n=null;try{n=await e();}catch(r){if(!(r instanceof an))throw r}return n??t()}},"&&":{precedence:2,evaluate:async(e,t)=>await on(e)&&on(t)},"==":{precedence:6,evaluate:async(e,t)=>await e()==await t()},"===":{precedence:6,evaluate:async(e,t)=>await e()===await t()},"!=":{precedence:6,evaluate:async(e,t)=>await e()!=await t()},"!==":{precedence:6,evaluate:async(e,t)=>await e()!==await t()},"<":{precedence:7,evaluate:async(e,t)=>await q(e)<await q(t)},">":{precedence:7,evaluate:async(e,t)=>await q(e)>await q(t)},"<=":{precedence:7,evaluate:async(e,t)=>await q(e)<=await q(t)},">=":{precedence:7,evaluate:async(e,t)=>await q(e)>=await q(t)},"+":{precedence:9,evaluate:async(e,t)=>{let[n,r]=await Promise.all([e(),t()]);if(typeof n=="string"||typeof r=="string")return `${n}${r}`;if(typeof n!="number"||typeof r!="number")throw new N(`Operands must be numbers or strings, got ${d.describeType(n)} and ${d.describeType(r)}.`);return n+r}},"-":{precedence:9,evaluate:async(e,t)=>await q(e)-await q(t)},"*":{precedence:10,evaluate:async(e,t)=>await q(e)*await q(t)},"/":{precedence:10,evaluate:async(e,t)=>await q(e)/await q(t)},"%":{precedence:10,evaluate:async(e,t)=>await q(e)%await q(t)},"**":{precedence:11,evaluate:async(e,t)=>(await q(e))**await q(t)}};}evaluate(e,t){return this.evaluateExpression(this.parse(e),t)}parse(e){let t=this.cache.get(e);if(t!==void 0)return t;Ne.plugins.register(Ol),Ne.plugins.register(Rl),Ne.plugins.register(Tl),Ne.removeAllUnaryOps();for(let r of Object.keys(a.UNARY_OPERATORS))Ne.addUnaryOp(r);Ne.removeAllBinaryOps();for(let[r,{precedence:i}]of Object.entries(a.BINARY_OPERATORS))Ne.addBinaryOp(r,i);Ne.removeAllLiterals();for(let[r,i]of Object.entries(a.LITERALS))Ne.addLiteral(r,i);let n;try{n=Ne(e);}catch(r){throw new N("Malformed expression.",{cause:r,details:[`Expression: ${e}`]})}return this.cache.set(e,n),n}async evaluateExpression(e,t){switch(true){case B(e,"Literal"):if(e.raw.startsWith("/")){let n=e.raw.lastIndexOf("/"),r=e.raw.slice(n+1),i=e.raw.slice(1,n),o=new String(e.raw);return Object.assign(o,{[ja]:new RegExp(i,r)}),o}return e.value;case B(e,"ThisExpression"):case B(e,"Identifier"):{let n=e.type==="ThisExpression"?"this":e.name,r=t?.variables?.[n];if(r===void 0)throw new N(`Variable \`${n}\` is unknown.`);return r}case B(e,"ArrayExpression"):return (await Promise.all(e.elements.map(async r=>{if(r===null)return [];if(B(r,"SpreadElement")){let i=await this.evaluateExpression(r.argument,t);if(!Array.isArray(i))throw new N(`Spread expression must evaluate to an array, got ${d.describeType(i)}.`);return i}return [await this.evaluateExpression(r,t)]}))).flat();case B(e,"ObjectExpression"):{let n=await Promise.all(e.properties.map(async r=>{if(B(r,"SpreadElement")){let o=await this.evaluateExpression(r.argument,t);if(typeof o!="object"||o===null)throw new N(`Spread expression must evaluate to an object, got ${d.describeType(o)}.`);return Object.entries(o)}return r.value===void 0&&B(r.key,"Identifier")?[[r.key.name,await this.evaluateExpression(r.key,t)]]:[[B(r.key,"Identifier")?r.key.name:await this.evaluateExpression(r.key,t).then(o=>{if(typeof o!="string"&&typeof o!="number")throw new N(`Property name must be a string or a number, got ${d.describeType(o)}.`);return o}),await this.evaluateExpression(r.value,t)]]}));return Object.fromEntries(n.flat())}case B(e,"UnaryExpression"):return a.UNARY_OPERATORS[e.operator].evaluate(()=>this.evaluateExpression(e.argument,t));case B(e,"BinaryExpression"):return a.BINARY_OPERATORS[e.operator].evaluate(()=>this.evaluateExpression(e.left,t),()=>this.evaluateExpression(e.right,t));case B(e,"MemberExpression"):{let n=await this.evaluateExpression(e.object,t).then(a.unbox);if(typeof n!="object"||n===null)throw new N("Cannot access property of a non-object.");let r=B(e.property,"Identifier")?e.property.name:await this.evaluateExpression(e.property,t);if(typeof r=="number"){if(!Array.isArray(n))throw new N("Cannot access array index of a non-array.");if(r<0||r>=n.length)throw new an("Array index is out of bounds.");return n[r]}if(typeof r!="string")throw new N(`Property name must be a string, got ${d.describeType(r)}.`);if(!a.isPropertyAllowed(n,r))throw new an(`Property \`${r}\` does not exist or is not accessible.`);return n[r]}case B(e,"CallExpression"):{let[n,r]=await Promise.all([this.getCallee(e.callee,t),Promise.all(e.arguments.map(i=>this.resolve(this.evaluateExpression(i,t))))]);return n(...e.arguments.flatMap((i,o)=>{let s=r[o];if(B(i,"SpreadElement")){if(!Array.isArray(s))throw new N(`Spread argument must evaluate to an array, got ${d.describeType(s)}.`);return s}return [s]}))}case B(e,"ConditionalExpression"):return await this.evaluateExpression(e.test,t)?this.evaluateExpression(e.consequent,t):this.evaluateExpression(e.alternate,t);default:throw new N(`Unexpected expression type \`${e.type}\`.`)}}async getCallee(e,t){if(B(e,"Identifier")){let n=t?.functions?.[e.name]??this.configuration.functions?.[e.name];if(n===void 0)throw new N(`Function \`${e.name}\` does not exist.`);return n}if(B(e,"MemberExpression")){let n=await this.resolve(this.evaluateExpression(e.object,t)).then(a.unbox),r=B(e.property,"Identifier")?e.property.name:await this.evaluateExpression(e.property,t);if(typeof r!="string")throw new N(`Method name must be a string, got ${d.describeType(r)}.`);if(!a.isMethodAllowed(n,r))throw new N(`Method \`${r}\` does not exist or is not accessible.`);let i=n[r].bind(n);return (...o)=>i(...o.map(a.unbox))}throw new N("Callee is not callable.")}static isMethodAllowed(e,t){return typeof e=="string"?a.ALLOWED_STRING_METHODS.includes(t):Array.isArray(e)?a.ALLOWED_ARRAY_METHODS.includes(t):e instanceof RegExp?a.ALLOWED_REGEX_METHODS.includes(t):false}static isPropertyAllowed(e,t){return typeof e=="string"?a.ALLOWED_STRING_PROPERTIES.includes(t):Array.isArray(e)?a.ALLOWED_ARRAY_PROPERTIES.includes(t):e instanceof RegExp?a.ALLOWED_REGEX_PROPERTIES.includes(t):typeof e=="object"&&e!==null&&Object.hasOwn(e,t)&&e[t]!==void 0}async resolve(e){if(!(e instanceof Promise)&&(a.isBoxed(e)||typeof e!="object"||e===null))return e;let t=await e;if(a.isBoxed(t))return t;if(Array.isArray(t))return Promise.all(t.map(n=>this.resolve(n)));if(typeof t=="object"&&t!==null){let n=Object.fromEntries(await Promise.all(Object.entries(t).flatMap(([r,i])=>i===void 0?[]:[[r,this.resolve(i)]])));return Object.isFrozen(t)?Object.freeze(n):Object.isSealed(t)&&Object.seal(n),n}return t}static unbox(e){return e instanceof String&&ja in e?e[ja]:e}static isBoxed(e){return e instanceof String||e instanceof Number||e instanceof Boolean}};function B(a,e){return a.type===e}async function q(a){let e=await a();if(typeof e!="number")throw new N(`Number expected, got ${d.describeType(e)}.`);return e}async function on(a){let e=await a();if(typeof e!="boolean")throw new N(`Boolean expected, got ${d.describeType(e)}.`);return e}var kt=z.strictObject({description:z.string(),required:z.boolean().optional()}),Dl=z.union([z.string(),z.number(),z.boolean(),z.null()]),sn=z.lazy(()=>z.union([Dl,z.array(sn),z.record(sn)])),Ml=z.discriminatedUnion("type",[kt.extend({type:z.literal("reference"),default:z.string().optional()}),kt.extend({type:z.literal("string"),choices:z.array(z.string()).optional(),default:z.string().optional()}),kt.extend({type:z.literal("number"),default:z.number().optional()}),kt.extend({type:z.literal("boolean"),default:z.boolean().optional()}),kt.extend({type:z.literal("array"),default:z.array(sn).optional()}),kt.extend({type:z.literal("object"),default:z.record(z.string(),sn).optional()})]),Nl=z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/).min(1),zl=z.strictObject({$schema:z.string().optional(),title:z.string().min(1),description:z.string().min(1),metadata:z.record(z.string(),sn).optional(),options:z.record(Nl,Ml).optional(),actions:z.array(z.any())}),pn=class extends G{constructor(){super(zl);}};var Vr=class a{constructor(e){this.resolving=[];this.config=e;}async execute(e,t){await this.importTemplate(e,t);}async importTemplate(e,t){let{url:n,value:r}=await this.loadTemplate(e.template,t.baseUrl,t.output),i=await this.getInputValues(r,e.options);if(this.resolving.includes(n.href)){let s=[...this.resolving,n.href].map((p,c)=>` ${c+1}. ${p}`).join(`
1762
+ ${i}`,{reason:"invalid_input",url:e})}return {...n,value:r.data}}};var pt=class{constructor(e){this.provider=e;}async get(e){let{value:t,...n}=await this.provider.get(e),r=await t.next();if(r.done===true||r.value.type!=="file")throw new De("File not found.",{url:e});return {...n,value:await new Response(r.value.content).text()}}};var tn=class{constructor(e){this.provider=e;}async get(e){let{value:t,...n}=await this.provider.get(e);try{return {...n,value:JsonParser$1.parse(t).toJSON()}}catch(r){throw new $("Malformed JSON.",{reason:"precondition",url:e,cause:r})}}};var kl=z.strictObject({pattern:z.string().refine(a=>{try{return new RegExp(a),!0}catch{return {message:"Invalid regular expression."}}}),destination:z.string()}),Al=z.array(kl),jr=class extends G{constructor(){super(Al);}};var nn=class{constructor({fileSystem:e,directory:t,useKeyAsFileName:n}){this.fileSystem=e,this.directory=t,this.useKeyAsFileName=n??false;}async delete(e){await this.fileSystem.delete(this.getCacheFile(e));}async get(e,t){try{return await this.fileSystem.readTextFile(this.getCacheFile(e))}catch{return t(e)}}async set(e,t){return await this.fileSystem.exists(this.directory)||await this.fileSystem.createDirectory(this.directory,{recursive:true}),this.fileSystem.writeTextFile(this.getCacheFile(e),t,{overwrite:true})}getCacheFile(e){return this.fileSystem.joinPaths(this.directory,this.useKeyAsFileName?e:createHash("md5").update(e).digest("hex"))}};var rn=class{constructor({provider:e,resourceCache:t,errorCache:n}){this.provider=e,this.resourceCache=t,this.errorCache=n;}async get(e){let t=await this.errorCache?.get(e.toString(),()=>Promise.resolve());return t!==void 0?Promise.reject(t):this.resourceCache.get(e.toString(),async()=>{try{return await this.provider.get(e)}catch(n){throw this.errorCache?.set(e.toString(),n),n}})}};var Ct;(e=>{function a(...t){return t.reduce((n,r)=>Object.defineProperties(n,Object.getOwnPropertyDescriptors(r)),{})}e.merge=a;})(Ct||={});var N=class a extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,a.prototype);}};var an=class a extends N{constructor(e,t){super(e,t),Object.setPrototypeOf(this,a.prototype);}},ja=Symbol("regex"),Ur=class a{constructor(e={}){this.cache=new Map;this.configuration=e;}static{this.ALLOWED_ARRAY_PROPERTIES=["length"];}static{this.ALLOWED_ARRAY_METHODS=["slice","join","includes","indexOf"];}static{this.ALLOWED_STRING_PROPERTIES=["length"];}static{this.ALLOWED_STRING_METHODS=["slice","indexOf","match","matchAll","replace","replaceAll","includes","startsWith","endsWith","toLowerCase","toUpperCase","repeat","split"];}static{this.ALLOWED_REGEX_PROPERTIES=["source"];}static{this.ALLOWED_REGEX_METHODS=["test"];}static{this.LITERALS={true:true,false:false,null:null};}static{this.UNARY_OPERATORS={"!":{evaluate:async e=>!await on(e)},"-":{evaluate:async e=>-await q(e)},"+":{evaluate:async e=>+await q(e)}};}static{this.BINARY_OPERATORS={"||":{precedence:1,evaluate:async(e,t)=>await on(e)||on(t)},"??":{precedence:1,evaluate:async(e,t)=>{let n=null;try{n=await e();}catch(r){if(!(r instanceof an))throw r}return n??t()}},"&&":{precedence:2,evaluate:async(e,t)=>await on(e)&&on(t)},"==":{precedence:6,evaluate:async(e,t)=>await e()==await t()},"===":{precedence:6,evaluate:async(e,t)=>await e()===await t()},"!=":{precedence:6,evaluate:async(e,t)=>await e()!=await t()},"!==":{precedence:6,evaluate:async(e,t)=>await e()!==await t()},"<":{precedence:7,evaluate:async(e,t)=>await q(e)<await q(t)},">":{precedence:7,evaluate:async(e,t)=>await q(e)>await q(t)},"<=":{precedence:7,evaluate:async(e,t)=>await q(e)<=await q(t)},">=":{precedence:7,evaluate:async(e,t)=>await q(e)>=await q(t)},"+":{precedence:9,evaluate:async(e,t)=>{let[n,r]=await Promise.all([e(),t()]);if(typeof n=="string"||typeof r=="string")return `${n}${r}`;if(typeof n!="number"||typeof r!="number")throw new N(`Operands must be numbers or strings, got ${d.describeType(n)} and ${d.describeType(r)}.`);return n+r}},"-":{precedence:9,evaluate:async(e,t)=>await q(e)-await q(t)},"*":{precedence:10,evaluate:async(e,t)=>await q(e)*await q(t)},"/":{precedence:10,evaluate:async(e,t)=>await q(e)/await q(t)},"%":{precedence:10,evaluate:async(e,t)=>await q(e)%await q(t)},"**":{precedence:11,evaluate:async(e,t)=>(await q(e))**await q(t)}};}evaluate(e,t){return this.evaluateExpression(this.parse(e),t)}parse(e){let t=this.cache.get(e);if(t!==void 0)return t;Ne.plugins.register(Ol),Ne.plugins.register(Rl),Ne.plugins.register(Tl),Ne.removeAllUnaryOps();for(let r of Object.keys(a.UNARY_OPERATORS))Ne.addUnaryOp(r);Ne.removeAllBinaryOps();for(let[r,{precedence:i}]of Object.entries(a.BINARY_OPERATORS))Ne.addBinaryOp(r,i);Ne.removeAllLiterals();for(let[r,i]of Object.entries(a.LITERALS))Ne.addLiteral(r,i);let n;try{n=Ne(e);}catch(r){throw new N("Malformed expression.",{cause:r,details:[`Expression: ${e}`]})}return this.cache.set(e,n),n}async evaluateExpression(e,t){switch(true){case B(e,"Literal"):if(e.raw.startsWith("/")){let n=e.raw.lastIndexOf("/"),r=e.raw.slice(n+1),i=e.raw.slice(1,n),o=new String(e.raw);return Object.assign(o,{[ja]:new RegExp(i,r)}),o}return e.value;case B(e,"ThisExpression"):case B(e,"Identifier"):{let n=e.type==="ThisExpression"?"this":e.name,r=t?.variables?.[n];if(r===void 0)throw new N(`Variable \`${n}\` is unknown.`);return r}case B(e,"ArrayExpression"):return (await Promise.all(e.elements.map(async r=>{if(r===null)return [];if(B(r,"SpreadElement")){let i=await this.evaluateExpression(r.argument,t);if(!Array.isArray(i))throw new N(`Spread expression must evaluate to an array, got ${d.describeType(i)}.`);return i}return [await this.evaluateExpression(r,t)]}))).flat();case B(e,"ObjectExpression"):{let n=await Promise.all(e.properties.map(async r=>{if(B(r,"SpreadElement")){let o=await this.evaluateExpression(r.argument,t);if(typeof o!="object"||o===null)throw new N(`Spread expression must evaluate to an object, got ${d.describeType(o)}.`);return Object.entries(o)}return r.value===void 0&&B(r.key,"Identifier")?[[r.key.name,await this.evaluateExpression(r.key,t)]]:[[B(r.key,"Identifier")?r.key.name:await this.evaluateExpression(r.key,t).then(o=>{if(typeof o!="string"&&typeof o!="number")throw new N(`Property name must be a string or a number, got ${d.describeType(o)}.`);return o}),await this.evaluateExpression(r.value,t)]]}));return Object.fromEntries(n.flat())}case B(e,"UnaryExpression"):return a.UNARY_OPERATORS[e.operator].evaluate(()=>this.evaluateExpression(e.argument,t));case B(e,"BinaryExpression"):return a.BINARY_OPERATORS[e.operator].evaluate(()=>this.evaluateExpression(e.left,t),()=>this.evaluateExpression(e.right,t));case B(e,"MemberExpression"):{let n=await this.evaluateExpression(e.object,t).then(a.unbox);if(typeof n!="object"||n===null)throw new N("Cannot access property of a non-object.");let r=B(e.property,"Identifier")?e.property.name:await this.evaluateExpression(e.property,t);if(typeof r=="number"){if(!Array.isArray(n))throw new N("Cannot access array index of a non-array.");if(r<0||r>=n.length)throw new an("Array index is out of bounds.");return n[r]}if(typeof r!="string")throw new N(`Property name must be a string, got ${d.describeType(r)}.`);if(!a.isPropertyAllowed(n,r))throw new an(`Property \`${r}\` does not exist or is not accessible.`);return n[r]}case B(e,"CallExpression"):{let[n,r]=await Promise.all([this.getCallee(e.callee,t),Promise.all(e.arguments.map(i=>this.resolve(this.evaluateExpression(i,t))))]);return n(...e.arguments.flatMap((i,o)=>{let s=r[o];if(B(i,"SpreadElement")){if(!Array.isArray(s))throw new N(`Spread argument must evaluate to an array, got ${d.describeType(s)}.`);return s}return [s]}))}case B(e,"ConditionalExpression"):return await this.evaluateExpression(e.test,t)?this.evaluateExpression(e.consequent,t):this.evaluateExpression(e.alternate,t);default:throw new N(`Unexpected expression type \`${e.type}\`.`)}}async getCallee(e,t){if(B(e,"Identifier")){let n=t?.functions?.[e.name]??this.configuration.functions?.[e.name];if(n===void 0)throw new N(`Function \`${e.name}\` does not exist.`);return n}if(B(e,"MemberExpression")){let n=await this.resolve(this.evaluateExpression(e.object,t)).then(a.unbox),r=B(e.property,"Identifier")?e.property.name:await this.evaluateExpression(e.property,t);if(typeof r!="string")throw new N(`Method name must be a string, got ${d.describeType(r)}.`);if(!a.isMethodAllowed(n,r))throw new N(`Method \`${r}\` does not exist or is not accessible.`);let i=n[r].bind(n);return (...o)=>i(...o.map(a.unbox))}throw new N("Callee is not callable.")}static isMethodAllowed(e,t){return typeof e=="string"?a.ALLOWED_STRING_METHODS.includes(t):Array.isArray(e)?a.ALLOWED_ARRAY_METHODS.includes(t):e instanceof RegExp?a.ALLOWED_REGEX_METHODS.includes(t):false}static isPropertyAllowed(e,t){return typeof e=="string"?a.ALLOWED_STRING_PROPERTIES.includes(t):Array.isArray(e)?a.ALLOWED_ARRAY_PROPERTIES.includes(t):e instanceof RegExp?a.ALLOWED_REGEX_PROPERTIES.includes(t):typeof e=="object"&&e!==null&&Object.hasOwn(e,t)&&e[t]!==void 0}async resolve(e){if(!(e instanceof Promise)&&(a.isBoxed(e)||typeof e!="object"||e===null))return e;let t=await e;if(a.isBoxed(t))return t;if(Array.isArray(t))return Promise.all(t.map(n=>this.resolve(n)));if(typeof t=="object"&&t!==null){let n=Object.fromEntries(await Promise.all(Object.entries(t).flatMap(([r,i])=>i===void 0?[]:[[r,this.resolve(i)]])));return Object.isFrozen(t)?Object.freeze(n):Object.isSealed(t)&&Object.seal(n),n}return t}static unbox(e){return e instanceof String&&ja in e?e[ja]:e}static isBoxed(e){return e instanceof String||e instanceof Number||e instanceof Boolean}};function B(a,e){return a.type===e}async function q(a){let e=await a();if(typeof e!="number")throw new N(`Number expected, got ${d.describeType(e)}.`);return e}async function on(a){let e=await a();if(typeof e!="boolean")throw new N(`Boolean expected, got ${d.describeType(e)}.`);return e}var kt=z.strictObject({description:z.string(),required:z.boolean().optional()}),Dl=z.union([z.string(),z.number(),z.boolean(),z.null()]),sn=z.lazy(()=>z.union([Dl,z.array(sn),z.record(sn)])),Ml=z.discriminatedUnion("type",[kt.extend({type:z.literal("reference"),default:z.string().optional()}),kt.extend({type:z.literal("string"),choices:z.array(z.string()).optional(),default:z.string().optional()}),kt.extend({type:z.literal("number"),default:z.number().optional()}),kt.extend({type:z.literal("boolean"),default:z.boolean().optional()}),kt.extend({type:z.literal("array"),default:z.array(sn).optional()}),kt.extend({type:z.literal("object"),default:z.record(z.string(),sn).optional()})]),Nl=z.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9_-]*$/).min(1),zl=z.strictObject({$schema:z.string().optional(),title:z.string().min(1),description:z.string().min(1),metadata:z.record(z.string(),sn).optional(),options:z.record(Nl,Ml).optional(),actions:z.array(z.any())}),pn=class extends G{constructor(){super(zl);}};var Vr=class a{constructor(e){this.resolving=[];this.config=e;}async execute(e,t){await this.importTemplate(e,t);}async importTemplate(e,t){let{url:n,value:r}=await this.loadTemplate(e.template,t.baseUrl,t.output),i=await this.getInputValues(r,e.options);if(this.resolving.includes(n.href)){let s=[...this.resolving,n.href].map((p,c)=>` ${c+1}. ${p}`).join(`
1763
1763
  `);throw new h(`Circular dependency detected while loading templates:
1764
1764
 
1765
1765
  ${s}`,{reason:"invalid_input"})}this.resolving.push(n.toString());let o=new vt({input:t.input,output:t.output,baseUrl:n});a.shareVariables(i.references,t,o);try{await this.run(r,i.values,o);}finally{this.resolving.pop();}a.shareVariables(i.references,o,t);}async getInputValues(e,t={}){let n={},r=[];for(let[i,o]of Object.entries(e.options??{})){let s=t[i];if(s===void 0&&o.required===true)throw new h(`Missing required option \`${i}\`.`,{reason:"invalid_input"});let p=await(s??o.resolveDefault?.(this.config.variables));p===void 0?n[i]=null:(o.type==="reference"?(a.checkOptionValue(i,p,{...o,type:"string"}),r.push(p)):a.checkOptionValue(i,p,o),n[i]=p);}return {values:n,references:r}}async run(e,t,n){let{runner:r,variables:i}=this.config,{output:o}=n;for(let{resolve:s}of e.actions){let p=o.notify("Resolving options"),c;try{c=await s(Ct.merge(i,{options:t,get this(){return n.getVariables()}}));}catch(l){throw h.fromCause(l,{message:"Unable to resolve action definition."})}finally{p.stop();}await r.execute({actions:[c]},n);}}async loadTemplate(e,t,n){let r=this.config.templateProvider,i=ot(e,t),o=n.notify("Loading template");try{return await r.get(i)}catch(s){throw s instanceof De?new d(`No template found at \`${decodeURIComponent(i.toString())}\`.`,{cause:s,reason:"invalid_input",suggestions:["Check if the template path or URL is correct and try again."]}):s}finally{o.stop();}}static checkOptionValue(e,t,n){switch(n.type){case "number":case "string":case "boolean":{if(typeof t!==n.type)throw new h(`Expected value of type ${n.type} for option \`${e}\`, but got ${d.describeType(t)}.`,{reason:"invalid_input"});if(n.type==="string"&&n.choices!==void 0&&!n.choices.includes(t))throw new h(`Invalid value for option \`${e}\`.`,{reason:"invalid_input",details:[`Allowed values: \`${n.choices.join("`, `")}\`.`]});break}case "array":{if(!Array.isArray(t))throw new h(`Expected value of type ${n.type} for option \`${e}\`,but got ${d.describeType(t)}.`,{reason:"invalid_input"});break}case "object":{if(typeof t!="object"||t===null)throw new h(`Expected value of type ${n.type} for option \`${e}\`,but got ${d.describeType(t)}.`,{reason:"invalid_input"});break}}}static shareVariables(e,t,n){let r=t.getVariables();for(let i of e)r[i]!==void 0&&n.set(i,r[i]);}};var D=class{constructor(e){this.configuration=e;}async execute(e,t){let{action:n,validator:r}=this.configuration,i=await r.validate(e);if(!i.valid){let o=i.violations.map(s=>(s.path===""?s.message:`**${s.path}**: ${s.message}`).replace(/'/g,"`"));throw new h("Invalid action options.",{reason:"invalid_input",details:o})}await n.execute(i.data,t);}};var cn;(n=>{let a=Symbol("source");function e(r){return r[a]??null}n.get=e;function t(r,i){r[a]=i;}n.set=t;})(cn||={});var Wr=class a{constructor(e,t){this.cursor=0;this.chars=[...e],this.index=t.index,this.line=t.line,this.column=t.column;}static parse(e,t){return [...a.from(e,t)]}static from(e,t){return new a(a.getExpression(e),t??(e instanceof JsonPrimitiveNode?e.location.start:{index:0,line:1,column:1}))}static getExpression(e){return typeof e=="string"?e:e instanceof JsonPrimitiveNode?e.value:e.token.value}get position(){return {index:this.index,line:this.line,column:this.column}}done(){return this.cursor>=this.chars.length}[Symbol.iterator](){return this}next(){return {done:this.done(),value:this.consume()}}consume(){if(this.done())return this.createLiteralFragment("",this.position);let e=this.position,t=0,n=0,r=0,i="";for(;this.cursor<this.chars.length;){let o=this.chars[this.cursor],s=o==="$"&&this.chars[this.cursor+1]==="{";if(!(r+t+n>0)&&s&&i.length>0)return this.createLiteralFragment(i,e);if(this.cursor++,this.index++,o===`
1766
- `?(this.line++,this.column=1):this.column++,i+=o,t>0||n>0)o==="\\"?(i+=this.chars[this.cursor],this.cursor++,this.index++,this.column++):t>0&&o==="'"?t--:n>0&&o==='"'&&n--;else if(r>0){if(o==="'"?t++:o==='"'?n++:o==="{"?r++:o==="}"&&r--,r===0)return this.createExpressionFragment(i,e)}else s&&(i+=this.chars[this.cursor],r++,this.cursor++,this.index++,this.column++);}if(t>0||n>0)throw new d("Unbalanced quotes in template string.",{details:[`Location: line ${e.line}, column ${e.column}`]});if(r>0)throw new d("Unbalanced braces in template string.",{details:[`Location: line ${e.line}, column ${e.column}`]});return this.createLiteralFragment(i,e)}createLiteralFragment(e,t){return {type:"literal",source:e,location:{start:t,end:this.position}}}createExpressionFragment(e,t){return {type:"expression",source:e,expression:e.slice(2,-1).trim(),location:{start:t,end:this.position}}}};var Z=class a extends Promise{#t;#n;#e;constructor(e,t=false){super(()=>{}),this.#t=e,this.#n=t;}static from(e){return new a(e)}static transient(e){return new a(e,true)}get promise(){if(this.#e!==void 0)return this.#e;let e=new Promise(t=>{t(this.#t());});return this.#n||(this.#e=e),e}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e)}};var se=class a extends ${constructor(e,{violations:t,...n}){super(e,n),this.violations=t,Object.setPrototypeOf(this,a.prototype);}},qr=class a{constructor({evaluator:e,validator:t,templateProvider:n,fileProvider:r}){this.loading=[];this.evaluator=e,this.validator=t,this.templateProvider=n,this.fileProvider=r;}async get(e){let{url:t,value:n}=await this.templateProvider.get(e),r;try{r=a.cleanJson(JsonParser.parse(n,JsonObjectNode));}catch(g){throw new se("Failed to parse the JSON template.",{reason:"invalid_input",url:t,cause:g,violations:[{path:"",message:d.formatMessage(g)}]})}let i=r.toJSON(),o=await this.validator.validate(i);if(!o.valid){let g=o.violations.map(y=>` \u2022 **${y.path}**: ${y.message}`).join(`
1766
+ `?(this.line++,this.column=1):this.column++,i+=o,t>0||n>0)o==="\\"?(i+=this.chars[this.cursor],this.cursor++,this.index++,this.column++):t>0&&o==="'"?t--:n>0&&o==='"'&&n--;else if(r>0){if(o==="'"?t++:o==='"'?n++:o==="{"?r++:o==="}"&&r--,r===0)return this.createExpressionFragment(i,e)}else s&&(i+=this.chars[this.cursor],r++,this.cursor++,this.index++,this.column++);}if(t>0||n>0)throw new d("Unbalanced quotes in template string.",{details:[`Location: line ${e.line}, column ${e.column}`]});if(r>0)throw new d("Unbalanced braces in template string.",{details:[`Location: line ${e.line}, column ${e.column}`]});return this.createLiteralFragment(i,e)}createLiteralFragment(e,t){return {type:"literal",source:e,location:{start:t,end:this.position}}}createExpressionFragment(e,t){return {type:"expression",source:e,expression:e.slice(2,-1).trim(),location:{start:t,end:this.position}}}};var Z=class a extends Promise{#t;#n;#e;constructor(e,t=false){super(()=>{}),this.#t=e,this.#n=t;}static from(e){return new a(e)}static transient(e){return new a(e,true)}get promise(){if(this.#e!==void 0)return this.#e;let e=new Promise(t=>{t(this.#t());});return this.#n||(this.#e=e),e}then(e,t){return this.promise.then(e,t)}catch(e){return this.promise.catch(e)}finally(e){return this.promise.finally(e)}};var se=class a extends ${constructor(e,{violations:t,...n}){super(e,n),this.violations=t,Object.setPrototypeOf(this,a.prototype);}},qr=class a{constructor({evaluator:e,validator:t,templateProvider:n,fileProvider:r}){this.loading=[];this.evaluator=e,this.validator=t,this.templateProvider=n,this.fileProvider=r;}async get(e){let{url:t,value:n}=await this.templateProvider.get(e),r;try{r=a.cleanJson(JsonParser$1.parse(n,JsonObjectNode$1));}catch(g){throw new se("Failed to parse the JSON template.",{reason:"invalid_input",url:t,cause:g,violations:[{path:"",message:d.formatMessage(g)}]})}let i=r.toJSON(),o=await this.validator.validate(i);if(!o.valid){let g=o.violations.map(y=>` \u2022 **${y.path}**: ${y.message}`).join(`
1767
1767
 
1768
1768
  `);throw new se(`The template contains errors:
1769
1769
 
1770
- ${g}`,{reason:"invalid_input",url:t,violations:o.violations})}let{options:s,actions:p,...c}=o.data,l=r.get("actions",JsonArrayNode),u=this.parseOptions(r,s,t);return {url:t,value:{...c,...u!==void 0?{options:u}:{},actions:l.elements.map(g=>({resolve:y=>this.resolve(g,y,t)}))}}}parseOptions(e,t,n){if(t===void 0)return;let r=e.get("options",JsonObjectNode);return Object.fromEntries(Object.entries(t).map(([i,o])=>{if(o.default===void 0)return [i,o];let s=r.get(i,JsonObjectNode).get("default");return [i,{...o,resolveDefault:p=>this.resolve(s,p,n)}]}))}resolve(e,t,n,r=""){return e instanceof JsonArrayNode?e.elements.map((i,o)=>this.resolve(i,t,n,`${r}[${o}]`)):e instanceof JsonObjectNode?Z.transient(async()=>{let i=Object.fromEntries(await Promise.all(e.properties.map(async o=>{let s=await this.interpolate(o.key,t,n,r);if(typeof s!="string"&&typeof s!="number"){let c=o.key.location.start;throw new se("Unexpected object key type.",{url:n,reason:"invalid_input",violations:[{path:r,message:`Expected object key to resolve to string or number at line ${c.line}, column ${c.column} but got ${d.describeType(s)}.`}]})}let p=r===""?`${s}`:`${r}.${s}`;return [s,Z.transient(()=>this.resolve(o.value,t,n,p))]})));return cn.set(i,{url:n,start:e.location.start,end:e.location.end}),i}):e instanceof JsonPrimitiveNode&&typeof e.value=="string"?Z.transient(()=>this.interpolate(e,t,n,r)):e.toJSON()}interpolate(e,t,n,r){let i=Wr.parse(e);if(i.length===1){let o=i[0];return o.type==="literal"?o.source:this.evaluate(a.createExpressionNode(o),t,n,r)}return Promise.all(i.map(async o=>{if(o.type==="literal")return o.source;let s=a.createExpressionNode(o),p=await this.evaluate(s,t,n,r);if(p!==null&&!["string","number","boolean"].includes(typeof p)){let c=e.location.start;throw new se("Unexpected expression result.",{reason:"invalid_input",url:n,violations:[{path:r,message:`Expected expression \`${o.expression}\` to resolve to null, string, number, or boolean value at line ${c.line}, column ${c.column}, but got ${d.describeType(p)}.`}]})}return `${p??""}`})).then(o=>o.join(""))}async evaluate(e,t,n,r){let i=(e instanceof JsonIdentifierNode?e.token.value:e.value).trim();try{return await this.evaluator.evaluate(i,{variables:t,functions:{url:(o="")=>{if(typeof o!="string"){let s=e.location.start;throw new N("Invalid argument for function `url`.",{reason:"invalid_input",details:[`The \`url\` argument of the \`url\` function must be a string, but got ${d.describeType(o)} at line ${s.line}, column ${s.column}.`]})}return ot(o,n).toString()},import:(o,s)=>{if(typeof o!="string"){let p=e.location.start;throw new N("Invalid argument for function `import`.",{reason:"invalid_input",details:[`The \`url\` argument of the \`import\` function must be a string, but got ${d.describeType(o)} at line ${p.line}, column ${p.column}.`]})}if(s!==void 0&&(typeof s!="object"||s===null||Array.isArray(s))){let p=e.location.start;throw new N("Invalid argument for function `import`.",{reason:"invalid_input",details:[`The \`properties\` argument of the \`import\` function must be an object, but got ${d.describeType(o)} at line ${p.line}, column ${p.column}.`]})}return this.import(ot(o,n),s===void 0?t:Ct.merge(t,{this:Promise.resolve(t.this).then(p=>typeof p=="object"&&p!==null&&!Array.isArray(p)?Ct.merge(p,s):s)}),n,r)}}})}catch(o){let s=e.location.start;throw new se("Failed to evaluate expression.",{reason:"invalid_input",url:n,cause:o,violations:[{path:r,message:`Evaluation of \`${i}\` at line ${s.line}, column ${s.column} failed because ${d.formatCause(o)}`}]})}}async import(e,t,n,r){if(e.protocol==="file:"&&n.protocol!=="file:")throw new se("Unsafe import URL.",{reason:"precondition",url:e,violations:[{path:r,message:"File URL is not allowed from remote sources for security reasons."}]});if(this.loading.includes(e.toString())){let p=[...this.loading,e.href].map((c,l)=>` ${l+1}. ${c}`).join(`
1770
+ ${g}`,{reason:"invalid_input",url:t,violations:o.violations})}let{options:s,actions:p,...c}=o.data,l=r.get("actions",JsonArrayNode$1),u=this.parseOptions(r,s,t);return {url:t,value:{...c,...u!==void 0?{options:u}:{},actions:l.elements.map(g=>({resolve:y=>this.resolve(g,y,t)}))}}}parseOptions(e,t,n){if(t===void 0)return;let r=e.get("options",JsonObjectNode$1);return Object.fromEntries(Object.entries(t).map(([i,o])=>{if(o.default===void 0)return [i,o];let s=r.get(i,JsonObjectNode$1).get("default");return [i,{...o,resolveDefault:p=>this.resolve(s,p,n)}]}))}resolve(e,t,n,r=""){return e instanceof JsonArrayNode$1?e.elements.map((i,o)=>this.resolve(i,t,n,`${r}[${o}]`)):e instanceof JsonObjectNode$1?Z.transient(async()=>{let i=Object.fromEntries(await Promise.all(e.properties.map(async o=>{let s=await this.interpolate(o.key,t,n,r);if(typeof s!="string"&&typeof s!="number"){let c=o.key.location.start;throw new se("Unexpected object key type.",{url:n,reason:"invalid_input",violations:[{path:r,message:`Expected object key to resolve to string or number at line ${c.line}, column ${c.column} but got ${d.describeType(s)}.`}]})}let p=r===""?`${s}`:`${r}.${s}`;return [s,Z.transient(()=>this.resolve(o.value,t,n,p))]})));return cn.set(i,{url:n,start:e.location.start,end:e.location.end}),i}):e instanceof JsonPrimitiveNode&&typeof e.value=="string"?Z.transient(()=>this.interpolate(e,t,n,r)):e.toJSON()}interpolate(e,t,n,r){let i=Wr.parse(e);if(i.length===1){let o=i[0];return o.type==="literal"?o.source:this.evaluate(a.createExpressionNode(o),t,n,r)}return Promise.all(i.map(async o=>{if(o.type==="literal")return o.source;let s=a.createExpressionNode(o),p=await this.evaluate(s,t,n,r);if(p!==null&&!["string","number","boolean"].includes(typeof p)){let c=e.location.start;throw new se("Unexpected expression result.",{reason:"invalid_input",url:n,violations:[{path:r,message:`Expected expression \`${o.expression}\` to resolve to null, string, number, or boolean value at line ${c.line}, column ${c.column}, but got ${d.describeType(p)}.`}]})}return `${p??""}`})).then(o=>o.join(""))}async evaluate(e,t,n,r){let i=(e instanceof JsonIdentifierNode?e.token.value:e.value).trim();try{return await this.evaluator.evaluate(i,{variables:t,functions:{url:(o="")=>{if(typeof o!="string"){let s=e.location.start;throw new N("Invalid argument for function `url`.",{reason:"invalid_input",details:[`The \`url\` argument of the \`url\` function must be a string, but got ${d.describeType(o)} at line ${s.line}, column ${s.column}.`]})}return ot(o,n).toString()},import:(o,s)=>{if(typeof o!="string"){let p=e.location.start;throw new N("Invalid argument for function `import`.",{reason:"invalid_input",details:[`The \`url\` argument of the \`import\` function must be a string, but got ${d.describeType(o)} at line ${p.line}, column ${p.column}.`]})}if(s!==void 0&&(typeof s!="object"||s===null||Array.isArray(s))){let p=e.location.start;throw new N("Invalid argument for function `import`.",{reason:"invalid_input",details:[`The \`properties\` argument of the \`import\` function must be an object, but got ${d.describeType(o)} at line ${p.line}, column ${p.column}.`]})}return this.import(ot(o,n),s===void 0?t:Ct.merge(t,{this:Promise.resolve(t.this).then(p=>typeof p=="object"&&p!==null&&!Array.isArray(p)?Ct.merge(p,s):s)}),n,r)}}})}catch(o){let s=e.location.start;throw new se("Failed to evaluate expression.",{reason:"invalid_input",url:n,cause:o,violations:[{path:r,message:`Evaluation of \`${i}\` at line ${s.line}, column ${s.column} failed because ${d.formatCause(o)}`}]})}}async import(e,t,n,r){if(e.protocol==="file:"&&n.protocol!=="file:")throw new se("Unsafe import URL.",{reason:"precondition",url:e,violations:[{path:r,message:"File URL is not allowed from remote sources for security reasons."}]});if(this.loading.includes(e.toString())){let p=[...this.loading,e.href].map((c,l)=>` ${l+1}. ${c}`).join(`
1771
1771
  `);throw new se(`Circular dependency detected while loading templates:
1772
1772
 
1773
- ${p}`,{reason:"invalid_input",url:e,violations:[{path:r,message:"Imported template creates a circular dependency."}]})}let{url:i,value:o}=await this.fileProvider.get(e),s;try{s=a.cleanJson(JsonParser.parse(o));}catch(p){throw new se("Failed to parse referenced JSON.",{reason:"invalid_input",cause:p,url:i,violations:[{path:r,message:d.formatMessage(p)}]})}this.loading.push(i.toString());try{return this.resolve(s,t,i,r)}finally{this.loading.pop();}}static createExpressionNode(e){return new JsonPrimitiveNode({value:e.expression,location:e.location,token:new JsonTokenNode({type:JsonTokenType.STRING,value:e.source,location:e.location})})}static cleanJson(e){if(e instanceof JsonPrimitiveNode)return e;if(e instanceof JsonArrayNode){for(let t of e.elements)this.cleanJson(t);return e}if(e instanceof JsonObjectNode)for(let t of e.properties){let n=t.key.toJSON();n==="$schema"?e.delete(n):this.cleanJson(t.value);}return e}};var Wa=Symbol("any-property"),Kp=Symbol("any-index"),un=Symbol("passthrough"),At=Symbol("resolve"),I=class a extends G{async validate(e){let t=this.findPassthroughPaths(this.schema),n;try{n=await this.resolveOptions(e,t);}catch(r){if(r instanceof se)return {valid:false,violations:r.violations};throw r}return super.validate(n).then(r=>(r.valid&&a.restoreSymbols(n,r.data),r))}async resolveOptions(e,t,n=[]){if(typeof e!="object"||e===null||a.isPassthroughPath(n,t))return e;if(e instanceof Promise)return this.resolveOptions(await e,t,n);if(Array.isArray(e)){let r=new Array(e.length),i=new Array(e.length);for(let[o,s]of e.entries()){let p=[...n,o];a.isPassthroughPath(p,t)?i[o]=s:r[o]=this.resolveOptions(await s,t,p);}for(let[o,s]of (await Promise.all(r)).entries())s!==void 0&&(i[o]=s);return i}return {...e,...Object.fromEntries(await Promise.all(Object.entries(e).map(async([r,i])=>{let o=[...n,r];return a.isPassthroughPath(o,t)?[r,i]:[r,await this.resolveOptions(await i,t,o)]})))}}static isPassthroughPath(e,t){for(let n of t)if(n.length===e.length+1)for(let[r,i]of n.entries()){let o=typeof e[r]=="number"?Kp:Wa;if(r<e.length?i!==e[r]&&i!==o:i!==At&&i!==un)break;if(r===n.length-1)return i===un}return false}findPassthroughPaths(e,t=[]){if(e instanceof ZodPromise)return [[...t,un]];if(e instanceof ZodOptional)return this.findPassthroughPaths(e.unwrap(),t);if(e instanceof ZodTuple)return [[...t,At],...e.items.flatMap((n,r)=>this.findPassthroughPaths(n,[...t,r]))];if(e instanceof ZodArray)return [[...t,At],...this.findPassthroughPaths(e.element,[...t,Kp])];if(e instanceof ZodRecord)return [[...t,At],...this.findPassthroughPaths(e.valueSchema,[...t,Wa])];if(e instanceof ZodObject){let n=[[...t,At],...Object.entries(e.shape).flatMap(([r,i])=>this.findPassthroughPaths(i,[...t,r]))];return e._def.unknownKeys==="passthrough"&&n.push([...t,Wa,un]),n}if(e instanceof ZodEffects){let n=e.innerType();return n instanceof ZodAny?[[...t,un]]:this.findPassthroughPaths(n,t)}return e instanceof ZodPipeline?this.findPassthroughPaths(e._def.out,t):e instanceof ZodUnion||e instanceof ZodDiscriminatedUnion?e.options.flatMap(n=>this.findPassthroughPaths(n,t)):[[...t,At]]}static restoreSymbols(e,t){if(Array.isArray(e)&&Array.isArray(t)){for(let[n,r]of e.entries())n<t.length&&a.restoreSymbols(r,t[n]);return}if(!(!qp(e)||!qp(t))){for(let n of Object.getOwnPropertySymbols(e))Object.assign(t,{[n]:e[n]});for(let[n,r]of Object.entries(e))n in t&&a.restoreSymbols(r,t[n]);}}};var Jl=z.strictObject({action:z.instanceof(Promise),else:z.instanceof(Promise).optional(),finally:z.instanceof(Promise).optional(),help:z.strictObject({message:z.string().min(1).optional(),links:z.array(z.strictObject({url:z.string().url(),label:z.string().min(1)})).optional(),suggestions:z.array(z.string().min(1)).optional()}).optional()}),Kr=class extends I{constructor(){super(Jl);}};var Ql=z.strictObject({name:z.string().min(1),version:z.string().min(1).optional(),optional:z.boolean().optional()}),Xl=z.strictObject({dependencies:z.array(Ql),help:z.strictObject({message:z.string().min(1).optional(),links:z.array(z.strictObject({url:z.string().url(),label:z.string().min(1)})).optional(),suggestions:z.array(z.string().min(1)).optional()}).optional(),result:z.record(z.string().min(1)).optional()}),Hr=class extends I{constructor(){super(Xl);}};var Yl=z.strictObject({source:z.string().min(1),filter:z.string().min(1).optional(),destination:z.string().min(1),mapping:z.record(z.string().min(1),z.string().min(1)).optional(),overwrite:z.boolean().optional(),result:z.strictObject({destination:z.string().min(1).optional()}).optional()}),Gr=class extends I{constructor(){super(Yl);}};var eu=z.strictObject({dependencies:z.array(z.string().min(1)).min(1),development:z.boolean().optional()}),Zr=class extends I{constructor(){super(eu);}};var tu=z.strictObject({pattern:z.string().min(1),caseSensitive:z.boolean().optional()}),Hp=z.union([tu,z.strictObject({type:z.enum(["and","or"]),matchers:z.array(z.lazy(()=>Hp)).min(1)})]),nu=z.strictObject({path:z.string().min(1),matcher:Hp.optional(),limit:z.number().int().positive().optional(),depth:z.number().int().nonnegative().optional(),result:z.string()}),Jr=class extends I{constructor(){super(nu);}};var ru=z.strictObject({files:z.array(z.strictObject({path:z.string(),replacements:z.array(z.strictObject({pattern:z.string().refine(a=>{try{return new RegExp(a),!0}catch{return {message:"Invalid regular expression pattern"}}}),caseSensitive:z.boolean().optional(),value:z.union([z.string(),z.number()])})).min(1)})).min(1)}),Qr=class extends I{constructor(){super(ru);}};var iu=z.strictObject({slots:z.array(z.string().min(1)).min(1),example:z.boolean().optional()}),Yr=class extends I{constructor(){super(iu);}};var ou=z.strictObject({components:z.array(z.string().min(1)).min(1)}),ei=class extends I{constructor(){super(ou);}};var au=z.strictObject({name:z.string().min(1),criteria:z.string().min(1)}),ct=z.strictObject({title:z.string().optional(),description:z.string().optional()}),su=ct.extend({type:z.literal("boolean"),label:z.strictObject({true:z.string(),false:z.string()}).optional(),default:z.boolean().optional()}),pu=z.strictObject({label:z.string().optional(),description:z.string().optional(),default:z.boolean().optional(),position:z.number().optional()}),cu=ct.extend({type:z.literal("text"),minimumLength:z.number().optional(),maximumLength:z.number().optional(),format:z.string().optional(),pattern:z.string().optional(),choices:z.record(pu).optional()}),lu=ct.extend({type:z.literal("number"),integer:z.boolean().optional(),minimum:z.number().optional(),maximum:z.number().optional()}),uu=z.lazy(()=>z.strictObject({type:z.lazy(()=>Qp),label:z.string().optional(),description:z.string().optional(),optional:z.boolean().optional(),private:z.boolean().optional(),position:z.number().optional()})),Ha=ct.extend({type:z.literal("structure"),attributes:z.record(z.string(),uu)}),mu=ct.extend({type:z.literal("list"),items:z.lazy(()=>Qp),itemLabel:z.string().optional(),minimumLength:z.number().optional(),maximumLength:z.number().optional()}),du=z.union([z.string(),z.number(),z.boolean(),z.null()]),Ka=z.lazy(()=>z.union([du,z.array(Ka),z.record(Ka)])),Zp=ct.extend({type:z.literal("reference"),id:z.string(),properties:z.record(z.string(),Ka).optional()}),Jp=ct.extend({type:z.literal("union"),types:z.record(z.string(),z.discriminatedUnion("type",[Ha,Zp]))}),Qp=z.discriminatedUnion("type",[su,cu,lu,Ha,mu,Jp,Zp]),gu=z.discriminatedUnion("type",[Ha,Jp]),fu=z.strictObject({name:z.string().min(1),description:z.string().min(1).optional(),schema:gu}),yu=z.union([z.strictObject({type:z.literal("static"),value:z.string()}),z.strictObject({type:z.literal("dynamic"),expression:z.string(),nullable:z.literal(false),default:z.string()}),z.strictObject({type:z.literal("dynamic"),expression:z.string(),nullable:z.literal(true),default:z.string().optional()})]),hu=z.union([z.strictObject({type:z.literal("static"),value:z.number()}),z.strictObject({type:z.literal("dynamic"),nullable:z.literal(false),default:z.number(),expression:z.string()}),z.strictObject({type:z.literal("dynamic"),nullable:z.literal(true),default:z.number().optional(),expression:z.string()})]),Su=z.union([z.strictObject({type:z.literal("static"),value:z.boolean()}),z.strictObject({type:z.literal("dynamic"),nullable:z.literal(false),default:z.boolean(),expression:z.string()}),z.strictObject({type:z.literal("dynamic"),nullable:z.literal(true),default:z.boolean().optional(),expression:z.string()})]),bu=z.strictObject({type:z.literal("text"),value:yu}),Iu=z.strictObject({type:z.literal("number"),value:hu}),vu=z.strictObject({type:z.literal("boolean"),value:Su}),Xp=z.strictObject({type:z.literal("structure"),name:z.string().optional(),attributes:z.record(z.string(),z.lazy(()=>Yp))}),xu=z.strictObject({type:z.literal("list"),items:z.array(z.lazy(()=>Yp))}),Yp=z.discriminatedUnion("type",[bu,Iu,vu,Xp,xu]),ec=z.record(z.string(),Xp),wu=z.strictObject({name:z.string().min(1),component:z.string().min(1),content:ec}),tc=z.record(z.string(),ec),Pu=z.strictObject({audiences:z.array(z.string()),content:tc}),nc=z.strictObject({default:tc.optional(),segmented:z.array(Pu).optional()}),Cu=z.strictObject({name:z.string(),content:nc,baseline:z.boolean().optional(),allocation:z.number().min(0)}),ku=z.strictObject({name:z.string(),draft:z.boolean().optional(),audiences:z.array(z.string()),slots:z.array(z.string()),experiment:z.strictObject({name:z.string(),goalId:z.string().optional(),crossDevice:z.boolean().optional(),traffic:z.number().min(0).max(1),variants:z.array(Cu)}).optional(),content:nc}),Au=z.record(z.string().min(1),z.string().min(1)),Gp=z.record(z.union([z.string().min(1).regex(/^\d+$/),z.number().nonnegative()]),z.string().min(1)),Bp=z.record(z.string().min(1),z.strictObject({id:z.string().min(1).optional(),version:z.string().min(1).optional()})),Eu=z.strictObject({resources:z.strictObject({audiences:z.record(z.string().min(1),au).optional(),components:z.record(z.string().min(1),fu).optional(),slots:z.record(z.string().min(1),wu).optional(),experiences:z.array(ku).optional()}),result:z.strictObject({audiences:Au.optional(),components:Bp.optional(),slots:Bp.optional(),experiences:Gp.optional(),experiments:Gp.optional()}).optional()}),ti=class extends I{constructor(){super(Eu);}};var Ou=z.union([z.string(),z.number(),z.boolean(),z.null()]),Ga=z.lazy(()=>z.union([Ou,z.array(Ga),z.record(Ga)])),Ru=z.strictObject({template:z.string().min(1),options:z.record(z.string().min(1),Ga).optional()}),ni=class extends I{constructor(){super(Ru);}};var ri=class{constructor({formatter:e}){this.formatter=e;}async execute(e,t){let{output:n}=t,r=n.notify("Formatting code");try{await this.formatter.format(e.files);}catch(i){throw h.fromCause(i)}finally{r.stop();}}};var Tu=z.strictObject({files:z.array(z.string().min(1)).min(1)}),ii=class extends I{constructor(){super(Tu);}};var Et=class{constructor(e){this.discriminator=e.discriminator,this.mapping=e.mapping;}async get(){let e=await this.discriminator(),t=this.mapping[e];if(t===void 0)throw new j(`No value found for discriminator "${String(e)}".`,{reason:"not_supported"});return t instanceof Function?t():t.get()}};var oi=class{constructor(e){this.runner=e;}execute(e,t){return e.condition?this.run(e.then,t):e.else!==void 0?this.run(e.else,t):Promise.resolve()}run(e,t){return this.runner.execute({actions:e},t)}};var Du=z.strictObject({condition:z.boolean(),then:z.instanceof(Promise),else:z.instanceof(Promise).optional()}),si=class extends I{constructor(){super(Du);}};var pi=class{execute(e,t){let n=t.output,r=e.semantics??"neutral";return e.title===void 0?n.log(e.message,r):n.announce({alignment:"left",semantics:r,title:e.title,message:e.message}),Promise.resolve()}};var Mu=z.strictObject({semantics:z.enum(["neutral","info","error","warning","success"]).optional(),title:z.string().optional(),message:z.string()}),li=class extends I{constructor(){super(Mu);}};var ui=class{execute(e){let{message:t,...n}=e;throw new h(t,{...n,reason:"precondition"})}};var Nu=z.strictObject({title:z.string().min(1).optional(),message:z.string().min(1),links:z.array(z.strictObject({label:z.string().min(1),url:z.string().url()})).optional(),suggestions:z.array(z.string().min(1)).optional(),details:z.array(z.string().min(1)).optional()}),mi=class extends I{constructor(){super(Nu);}};var di=class{constructor({url:e,provider:t}){this.url=e,this.provider=t;}get(){return this.provider.get(this.url)}};var Ot=class{constructor(e){this.data=e;}get(){return Promise.resolve(this.data)}};var gi=class{constructor({packageManager:e,parsers:t,factory:n}){this.packageManager=e,this.parsers=t,this.factory=n;}async get(){let e=await this.packageManager.getScripts();for(let[t,n]of Object.entries(e))for(let r of this.parsers){let i=r.parse(n);if(i!==null)return this.factory.create({...i,command:await this.packageManager.getScriptCommand(t)})}throw new j("No server found.")}};var fi=class{parse(e){if(!e.includes("next dev"))return null;let t=e.match(/(?:-p|--port)\s*(\d+)/),n=e.match(/(?:-H|--hostname)\s*(\S+)/),r=t!==null?Number.parseInt(t[1],10):null,i=n!==null?n[1]:"localhost";return {protocol:e.includes("-https")?"https":"http",host:i,...r!==null?{port:r}:{},defaultPort:3e3}}};var yi=class{parse(e){if(!e.includes("vite"))return null;let t=e.match(/--port\s*(\d+)/),n=e.match(/--host\s*(\S+)/),r=t!==null?Number.parseInt(t[1],10):null;return {protocol:"http",host:n!==null?n[1]:"localhost",...r!==null?{port:r}:{},defaultPort:5173}}};var hi=class{parse(e){if(!e.includes("parcel"))return null;let t=e.match(/(?:-p|--port)\s*(\d+)/),n=e.match(/--host\s*(\S+)/),r=t!==null?Number.parseInt(t[1],10):null,i=n!==null?n[1]:"localhost";return {protocol:e.includes("--https")?"https":"http",host:i,...r!==null?{port:r}:{},defaultPort:1234}}};var Si=class{parse(e){if(!e.includes("react-scripts start"))return null;let t=e.match(/PORT=(\d+)/),n=e.match(/HOST=(\S+)/),r=e.match(/HTTPS=(\S+)/),i=t!==null?Number.parseInt(t[1],10):null,o=n!==null?n[1]:"localhost";return {protocol:r!==null&&r[1]==="true"?"https":"http",host:o,...i!==null?{port:i}:{},defaultPort:5173}}};var bi=class{async execute(e,t){let{input:n}=t,r=n===void 0?this.getDefaultValue(e):await this.prompt(e,n);if(r===void 0)throw new h("Action requires user input.",{reason:"precondition",suggestions:["Retry in interactive mode"]});e.result!==void 0&&t.set(e.result,r);}getDefaultValue(e){switch(e.type){case "confirmation":return e.default;case "choice":return e.default;case "multi-choice":{let t=e.options.flatMap(n=>n.selected===true?[n.value]:[]);return t.length===0?void 0:t}case "text":return e.default;default:return}}prompt(e,t){switch(e.type){case "confirmation":return t.confirm(e);case "choice":return t.select(e);case "multi-choice":return t.selectMultiple(e);case "text":{let{required:n=false,...r}=e;return t.prompt({...r,validate:i=>n&&i===""?"This value is required.":true})}case "keypress":return t.wait(e)}}};var zu=z.strictObject({type:z.literal("confirmation"),message:z.string(),default:z.boolean().optional(),result:z.string()}),Za=z.string(),$u=z.preprocess(a=>typeof a=="string"?{value:a,label:a}:a,z.strictObject({value:Za,label:z.string().min(1).optional(),disabled:z.boolean().optional()})).transform(a=>({...a,label:a.label??a.value.toString()})),_u=z.strictObject({type:z.literal("choice"),message:z.string(),options:z.array($u),default:Za.optional(),result:z.string()}),Lu=z.preprocess(a=>typeof a=="string"?{value:a,label:a}:a,z.strictObject({value:Za,label:z.string().min(1).optional(),selected:z.boolean().optional(),disabled:z.boolean().optional()})).transform(a=>({...a,label:a.label??a.value.toString()})),Fu=z.strictObject({type:z.literal("multi-choice"),message:z.string(),min:z.number().optional(),max:z.number().optional(),options:z.array(Lu),result:z.string()}),ju=z.strictObject({type:z.literal("text"),message:z.string(),default:z.string().optional(),required:z.boolean().optional(),result:z.string()}),Uu=z.strictObject({type:z.literal("keypress"),message:z.string(),key:z.union([z.literal("enter"),z.literal("space"),z.string().length(1)]).optional(),result:z.string().optional()}),Vu=z.discriminatedUnion("type",[zu,_u,Fu,ju,Uu]),Ii=class extends I{constructor(){super(Vu);}};var vi=class{constructor({serverFactory:e,serverProvider:t,packageManager:n,serverMap:r}){this.factory=e,this.provider=t,this.packageManager=n,this.serverMap=r;}async execute(e,t){let{output:n}=t,r=n.notify("Checking server"),i;try{i=await this.startServer(r,e.server);}finally{r.stop();}e.result?.url!==void 0&&t.set(e.result.url,i.url.toString()),e.result?.id!==void 0&&t.set(e.result.id,i.id??null);}async startServer(e,t){let n=await this.getServer(t),r=await n.getStatus();if(r.running)return {url:r.url,owned:false};e.update("Starting server");let i=randomUUID();return this.serverMap.set(i,n),{id:i,url:await n.start({logger:new oe({status:"Starting server",notifier:e})}),owned:true}}async getServer(e){if(e===void 0){let i=await this.provider.get();if(i===null)throw new d("No server detected.");return i}let t=new URL(e.url),n=t.protocol==="https:",r=n?443:80;return this.factory.create({host:t.hostname,protocol:n?"https":"http",defaultPort:t.port===""?r:Number.parseInt(t.port,10),command:await this.packageManager.getScriptCommand(e.script,e.arguments)})}};var qu=z.strictObject({server:z.strictObject({script:z.string(),arguments:z.array(z.string()).optional(),url:z.string()}).optional(),result:z.strictObject({id:z.string().optional(),url:z.string().optional()}).optional()}),xi=class extends I{constructor(){super(qu);}};var wi=class{constructor(e){this.actions=e;}async execute(e,t){for(let n of Array.isArray(e.actions)?e.actions:[e.actions])try{await this.run(n,t);}catch(r){if(r instanceof se&&r.help.cause instanceof JsonParseError){let{location:i}=r.help.cause;throw h.fromCause(r,{tracing:[{name:n.name,source:{url:r.url,start:i.start,end:i.end}}]})}throw h.fromCause(r,{tracing:[{name:n.name,source:cn.get(n)??void 0}]})}}run({name:e,...t},n){let r=this.actions[e];if(r===void 0)throw new h(`Unsupported action \`${e}\`.`,{reason:"invalid_input"});return r.execute(t,n)}};var rc=z.object({name:z.string().min(1)}).passthrough(),Hu=z.strictObject({actions:z.union([rc,z.array(rc)])}),Pi=class extends I{constructor(){super(Hu);}};var Ci=class{async execute(e,t){let{output:n}=t;await n.open(e.url);}};var Gu=z.strictObject({url:z.string().url()}),ki=class extends I{constructor(){super(Gu);}};var Bu=z.union([z.string(),z.number(),z.boolean(),z.null()]),Ja=z.lazy(()=>z.union([Bu,z.array(Ja),z.record(Ja)])),Zu=z.strictObject({variables:z.record(z.string(),Ja)}),Ai=class extends I{constructor(){super(Zu);}};var Ei=class{execute(e,t){for(let[n,r]of Object.entries(e.variables))t.set(n,r);return Promise.resolve()}};var Ju=z.strictObject({id:z.string()}),Oi=class extends I{constructor(){super(Ju);}};var Rt=class a extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,a.prototype);}};var pe=class{constructor(){this.lines=[[]];this.cursor={row:0,column:0};this.snapshot=[[]];this.ansiSequence="";this.lines=[[]];}write(e){for(let t=0;t<e.length;t++){let n=e[t];if(n==="\x1B"){this.ansiSequence="\x1B";continue}if(this.ansiSequence.length>0){this.ansiSequence+=n,/[A-Za-z]/.test(n)&&(this.processAnsiSequence(this.ansiSequence),this.ansiSequence="");continue}if(n==="\r"){let r=this.lines[this.cursor.row];for(let i=this.cursor.column;i<r.length;i++)r[i]=" ";this.cursor.column=0;continue}if(n===`
1773
+ ${p}`,{reason:"invalid_input",url:e,violations:[{path:r,message:"Imported template creates a circular dependency."}]})}let{url:i,value:o}=await this.fileProvider.get(e),s;try{s=a.cleanJson(JsonParser$1.parse(o));}catch(p){throw new se("Failed to parse referenced JSON.",{reason:"invalid_input",cause:p,url:i,violations:[{path:r,message:d.formatMessage(p)}]})}this.loading.push(i.toString());try{return this.resolve(s,t,i,r)}finally{this.loading.pop();}}static createExpressionNode(e){return new JsonPrimitiveNode({value:e.expression,location:e.location,token:new JsonTokenNode({type:JsonTokenType.STRING,value:e.source,location:e.location})})}static cleanJson(e){if(e instanceof JsonPrimitiveNode)return e;if(e instanceof JsonArrayNode$1){for(let t of e.elements)this.cleanJson(t);return e}if(e instanceof JsonObjectNode$1)for(let t of e.properties){let n=t.key.toJSON();n==="$schema"?e.delete(n):this.cleanJson(t.value);}return e}};var Wa=Symbol("any-property"),Kp=Symbol("any-index"),un=Symbol("passthrough"),At=Symbol("resolve"),I=class a extends G{async validate(e){let t=this.findPassthroughPaths(this.schema),n;try{n=await this.resolveOptions(e,t);}catch(r){if(r instanceof se)return {valid:false,violations:r.violations};throw r}return super.validate(n).then(r=>(r.valid&&a.restoreSymbols(n,r.data),r))}async resolveOptions(e,t,n=[]){if(typeof e!="object"||e===null||a.isPassthroughPath(n,t))return e;if(e instanceof Promise)return this.resolveOptions(await e,t,n);if(Array.isArray(e)){let r=new Array(e.length),i=new Array(e.length);for(let[o,s]of e.entries()){let p=[...n,o];a.isPassthroughPath(p,t)?i[o]=s:r[o]=this.resolveOptions(await s,t,p);}for(let[o,s]of (await Promise.all(r)).entries())s!==void 0&&(i[o]=s);return i}return {...e,...Object.fromEntries(await Promise.all(Object.entries(e).map(async([r,i])=>{let o=[...n,r];return a.isPassthroughPath(o,t)?[r,i]:[r,await this.resolveOptions(await i,t,o)]})))}}static isPassthroughPath(e,t){for(let n of t)if(n.length===e.length+1)for(let[r,i]of n.entries()){let o=typeof e[r]=="number"?Kp:Wa;if(r<e.length?i!==e[r]&&i!==o:i!==At&&i!==un)break;if(r===n.length-1)return i===un}return false}findPassthroughPaths(e,t=[]){if(e instanceof ZodPromise)return [[...t,un]];if(e instanceof ZodOptional)return this.findPassthroughPaths(e.unwrap(),t);if(e instanceof ZodTuple)return [[...t,At],...e.items.flatMap((n,r)=>this.findPassthroughPaths(n,[...t,r]))];if(e instanceof ZodArray)return [[...t,At],...this.findPassthroughPaths(e.element,[...t,Kp])];if(e instanceof ZodRecord)return [[...t,At],...this.findPassthroughPaths(e.valueSchema,[...t,Wa])];if(e instanceof ZodObject){let n=[[...t,At],...Object.entries(e.shape).flatMap(([r,i])=>this.findPassthroughPaths(i,[...t,r]))];return e._def.unknownKeys==="passthrough"&&n.push([...t,Wa,un]),n}if(e instanceof ZodEffects){let n=e.innerType();return n instanceof ZodAny?[[...t,un]]:this.findPassthroughPaths(n,t)}return e instanceof ZodPipeline?this.findPassthroughPaths(e._def.out,t):e instanceof ZodUnion||e instanceof ZodDiscriminatedUnion?e.options.flatMap(n=>this.findPassthroughPaths(n,t)):[[...t,At]]}static restoreSymbols(e,t){if(Array.isArray(e)&&Array.isArray(t)){for(let[n,r]of e.entries())n<t.length&&a.restoreSymbols(r,t[n]);return}if(!(!qp(e)||!qp(t))){for(let n of Object.getOwnPropertySymbols(e))Object.assign(t,{[n]:e[n]});for(let[n,r]of Object.entries(e))n in t&&a.restoreSymbols(r,t[n]);}}};var Jl=z.strictObject({action:z.instanceof(Promise),else:z.instanceof(Promise).optional(),finally:z.instanceof(Promise).optional(),help:z.strictObject({message:z.string().min(1).optional(),links:z.array(z.strictObject({url:z.string().url(),label:z.string().min(1)})).optional(),suggestions:z.array(z.string().min(1)).optional()}).optional()}),Kr=class extends I{constructor(){super(Jl);}};var Ql=z.strictObject({name:z.string().min(1),version:z.string().min(1).optional(),optional:z.boolean().optional()}),Xl=z.strictObject({dependencies:z.array(Ql),help:z.strictObject({message:z.string().min(1).optional(),links:z.array(z.strictObject({url:z.string().url(),label:z.string().min(1)})).optional(),suggestions:z.array(z.string().min(1)).optional()}).optional(),result:z.record(z.string().min(1)).optional()}),Hr=class extends I{constructor(){super(Xl);}};var Yl=z.strictObject({source:z.string().min(1),filter:z.string().min(1).optional(),destination:z.string().min(1),mapping:z.record(z.string().min(1),z.string().min(1)).optional(),overwrite:z.boolean().optional(),result:z.strictObject({destination:z.string().min(1).optional()}).optional()}),Gr=class extends I{constructor(){super(Yl);}};var eu=z.strictObject({dependencies:z.array(z.string().min(1)).min(1),development:z.boolean().optional()}),Zr=class extends I{constructor(){super(eu);}};var tu=z.strictObject({pattern:z.string().min(1),caseSensitive:z.boolean().optional()}),Hp=z.union([tu,z.strictObject({type:z.enum(["and","or"]),matchers:z.array(z.lazy(()=>Hp)).min(1)})]),nu=z.strictObject({path:z.string().min(1),matcher:Hp.optional(),limit:z.number().int().positive().optional(),depth:z.number().int().nonnegative().optional(),result:z.string()}),Jr=class extends I{constructor(){super(nu);}};var ru=z.strictObject({files:z.array(z.strictObject({path:z.string(),replacements:z.array(z.strictObject({pattern:z.string().refine(a=>{try{return new RegExp(a),!0}catch{return {message:"Invalid regular expression pattern"}}}),caseSensitive:z.boolean().optional(),value:z.union([z.string(),z.number()])})).min(1)})).min(1)}),Qr=class extends I{constructor(){super(ru);}};var iu=z.strictObject({slots:z.array(z.string().min(1)).min(1),example:z.boolean().optional()}),Yr=class extends I{constructor(){super(iu);}};var ou=z.strictObject({components:z.array(z.string().min(1)).min(1)}),ei=class extends I{constructor(){super(ou);}};var au=z.strictObject({name:z.string().min(1),criteria:z.string().min(1)}),ct=z.strictObject({title:z.string().optional(),description:z.string().optional()}),su=ct.extend({type:z.literal("boolean"),label:z.strictObject({true:z.string(),false:z.string()}).optional(),default:z.boolean().optional()}),pu=z.strictObject({label:z.string().optional(),description:z.string().optional(),default:z.boolean().optional(),position:z.number().optional()}),cu=ct.extend({type:z.literal("text"),minimumLength:z.number().optional(),maximumLength:z.number().optional(),format:z.string().optional(),pattern:z.string().optional(),choices:z.record(pu).optional()}),lu=ct.extend({type:z.literal("number"),integer:z.boolean().optional(),minimum:z.number().optional(),maximum:z.number().optional()}),uu=z.lazy(()=>z.strictObject({type:z.lazy(()=>Qp),label:z.string().optional(),description:z.string().optional(),optional:z.boolean().optional(),private:z.boolean().optional(),position:z.number().optional()})),Ha=ct.extend({type:z.literal("structure"),attributes:z.record(z.string(),uu)}),mu=ct.extend({type:z.literal("list"),items:z.lazy(()=>Qp),itemLabel:z.string().optional(),minimumLength:z.number().optional(),maximumLength:z.number().optional()}),du=z.union([z.string(),z.number(),z.boolean(),z.null()]),Ka=z.lazy(()=>z.union([du,z.array(Ka),z.record(Ka)])),Zp=ct.extend({type:z.literal("reference"),id:z.string(),properties:z.record(z.string(),Ka).optional()}),Jp=ct.extend({type:z.literal("union"),types:z.record(z.string(),z.discriminatedUnion("type",[Ha,Zp]))}),Qp=z.discriminatedUnion("type",[su,cu,lu,Ha,mu,Jp,Zp]),gu=z.discriminatedUnion("type",[Ha,Jp]),fu=z.strictObject({name:z.string().min(1),description:z.string().min(1).optional(),schema:gu}),yu=z.union([z.strictObject({type:z.literal("static"),value:z.string()}),z.strictObject({type:z.literal("dynamic"),expression:z.string(),nullable:z.literal(false),default:z.string()}),z.strictObject({type:z.literal("dynamic"),expression:z.string(),nullable:z.literal(true),default:z.string().optional()})]),hu=z.union([z.strictObject({type:z.literal("static"),value:z.number()}),z.strictObject({type:z.literal("dynamic"),nullable:z.literal(false),default:z.number(),expression:z.string()}),z.strictObject({type:z.literal("dynamic"),nullable:z.literal(true),default:z.number().optional(),expression:z.string()})]),Su=z.union([z.strictObject({type:z.literal("static"),value:z.boolean()}),z.strictObject({type:z.literal("dynamic"),nullable:z.literal(false),default:z.boolean(),expression:z.string()}),z.strictObject({type:z.literal("dynamic"),nullable:z.literal(true),default:z.boolean().optional(),expression:z.string()})]),bu=z.strictObject({type:z.literal("text"),value:yu}),Iu=z.strictObject({type:z.literal("number"),value:hu}),vu=z.strictObject({type:z.literal("boolean"),value:Su}),Xp=z.strictObject({type:z.literal("structure"),name:z.string().optional(),attributes:z.record(z.string(),z.lazy(()=>Yp))}),xu=z.strictObject({type:z.literal("list"),items:z.array(z.lazy(()=>Yp))}),Yp=z.discriminatedUnion("type",[bu,Iu,vu,Xp,xu]),ec=z.record(z.string(),Xp),wu=z.strictObject({name:z.string().min(1),component:z.string().min(1),content:ec}),tc=z.record(z.string(),ec),Pu=z.strictObject({audiences:z.array(z.string()),content:tc}),nc=z.strictObject({default:tc.optional(),segmented:z.array(Pu).optional()}),Cu=z.strictObject({name:z.string(),content:nc,baseline:z.boolean().optional(),allocation:z.number().min(0)}),ku=z.strictObject({name:z.string(),draft:z.boolean().optional(),audiences:z.array(z.string()),slots:z.array(z.string()),experiment:z.strictObject({name:z.string(),goalId:z.string().optional(),crossDevice:z.boolean().optional(),traffic:z.number().min(0).max(1),variants:z.array(Cu)}).optional(),content:nc}),Au=z.record(z.string().min(1),z.string().min(1)),Gp=z.record(z.union([z.string().min(1).regex(/^\d+$/),z.number().nonnegative()]),z.string().min(1)),Bp=z.record(z.string().min(1),z.strictObject({id:z.string().min(1).optional(),version:z.string().min(1).optional()})),Eu=z.strictObject({resources:z.strictObject({audiences:z.record(z.string().min(1),au).optional(),components:z.record(z.string().min(1),fu).optional(),slots:z.record(z.string().min(1),wu).optional(),experiences:z.array(ku).optional()}),result:z.strictObject({audiences:Au.optional(),components:Bp.optional(),slots:Bp.optional(),experiences:Gp.optional(),experiments:Gp.optional()}).optional()}),ti=class extends I{constructor(){super(Eu);}};var Ou=z.union([z.string(),z.number(),z.boolean(),z.null()]),Ga=z.lazy(()=>z.union([Ou,z.array(Ga),z.record(Ga)])),Ru=z.strictObject({template:z.string().min(1),options:z.record(z.string().min(1),Ga).optional()}),ni=class extends I{constructor(){super(Ru);}};var ri=class{constructor({formatter:e}){this.formatter=e;}async execute(e,t){let{output:n}=t,r=n.notify("Formatting code");try{await this.formatter.format(e.files);}catch(i){throw h.fromCause(i)}finally{r.stop();}}};var Tu=z.strictObject({files:z.array(z.string().min(1)).min(1)}),ii=class extends I{constructor(){super(Tu);}};var Et=class{constructor(e){this.discriminator=e.discriminator,this.mapping=e.mapping;}async get(){let e=await this.discriminator(),t=this.mapping[e];if(t===void 0)throw new j(`No value found for discriminator "${String(e)}".`,{reason:"not_supported"});return t instanceof Function?t():t.get()}};var oi=class{constructor(e){this.runner=e;}execute(e,t){return e.condition?this.run(e.then,t):e.else!==void 0?this.run(e.else,t):Promise.resolve()}run(e,t){return this.runner.execute({actions:e},t)}};var Du=z.strictObject({condition:z.boolean(),then:z.instanceof(Promise),else:z.instanceof(Promise).optional()}),si=class extends I{constructor(){super(Du);}};var pi=class{execute(e,t){let n=t.output,r=e.semantics??"neutral";return e.title===void 0?n.log(e.message,r):n.announce({alignment:"left",semantics:r,title:e.title,message:e.message}),Promise.resolve()}};var Mu=z.strictObject({semantics:z.enum(["neutral","info","error","warning","success"]).optional(),title:z.string().optional(),message:z.string()}),li=class extends I{constructor(){super(Mu);}};var ui=class{execute(e){let{message:t,...n}=e;throw new h(t,{...n,reason:"precondition"})}};var Nu=z.strictObject({title:z.string().min(1).optional(),message:z.string().min(1),links:z.array(z.strictObject({label:z.string().min(1),url:z.string().url()})).optional(),suggestions:z.array(z.string().min(1)).optional(),details:z.array(z.string().min(1)).optional()}),mi=class extends I{constructor(){super(Nu);}};var di=class{constructor({url:e,provider:t}){this.url=e,this.provider=t;}get(){return this.provider.get(this.url)}};var Ot=class{constructor(e){this.data=e;}get(){return Promise.resolve(this.data)}};var gi=class{constructor({packageManager:e,parsers:t,factory:n}){this.packageManager=e,this.parsers=t,this.factory=n;}async get(){let e=await this.packageManager.getScripts();for(let[t,n]of Object.entries(e))for(let r of this.parsers){let i=r.parse(n);if(i!==null)return this.factory.create({...i,command:await this.packageManager.getScriptCommand(t)})}throw new j("No server found.")}};var fi=class{parse(e){if(!e.includes("next dev"))return null;let t=e.match(/(?:-p|--port)\s*(\d+)/),n=e.match(/(?:-H|--hostname)\s*(\S+)/),r=t!==null?Number.parseInt(t[1],10):null,i=n!==null?n[1]:"localhost";return {protocol:e.includes("-https")?"https":"http",host:i,...r!==null?{port:r}:{},defaultPort:3e3}}};var yi=class{parse(e){if(!e.includes("vite"))return null;let t=e.match(/--port\s*(\d+)/),n=e.match(/--host\s*(\S+)/),r=t!==null?Number.parseInt(t[1],10):null;return {protocol:"http",host:n!==null?n[1]:"localhost",...r!==null?{port:r}:{},defaultPort:5173}}};var hi=class{parse(e){if(!e.includes("parcel"))return null;let t=e.match(/(?:-p|--port)\s*(\d+)/),n=e.match(/--host\s*(\S+)/),r=t!==null?Number.parseInt(t[1],10):null,i=n!==null?n[1]:"localhost";return {protocol:e.includes("--https")?"https":"http",host:i,...r!==null?{port:r}:{},defaultPort:1234}}};var Si=class{parse(e){if(!e.includes("react-scripts start"))return null;let t=e.match(/PORT=(\d+)/),n=e.match(/HOST=(\S+)/),r=e.match(/HTTPS=(\S+)/),i=t!==null?Number.parseInt(t[1],10):null,o=n!==null?n[1]:"localhost";return {protocol:r!==null&&r[1]==="true"?"https":"http",host:o,...i!==null?{port:i}:{},defaultPort:5173}}};var bi=class{async execute(e,t){let{input:n}=t,r=n===void 0?this.getDefaultValue(e):await this.prompt(e,n);if(r===void 0)throw new h("Action requires user input.",{reason:"precondition",suggestions:["Retry in interactive mode"]});e.result!==void 0&&t.set(e.result,r);}getDefaultValue(e){switch(e.type){case "confirmation":return e.default;case "choice":return e.default;case "multi-choice":{let t=e.options.flatMap(n=>n.selected===true?[n.value]:[]);return t.length===0?void 0:t}case "text":return e.default;default:return}}prompt(e,t){switch(e.type){case "confirmation":return t.confirm(e);case "choice":return t.select(e);case "multi-choice":return t.selectMultiple(e);case "text":{let{required:n=false,...r}=e;return t.prompt({...r,validate:i=>n&&i===""?"This value is required.":true})}case "keypress":return t.wait(e)}}};var zu=z.strictObject({type:z.literal("confirmation"),message:z.string(),default:z.boolean().optional(),result:z.string()}),Za=z.string(),$u=z.preprocess(a=>typeof a=="string"?{value:a,label:a}:a,z.strictObject({value:Za,label:z.string().min(1).optional(),disabled:z.boolean().optional()})).transform(a=>({...a,label:a.label??a.value.toString()})),_u=z.strictObject({type:z.literal("choice"),message:z.string(),options:z.array($u),default:Za.optional(),result:z.string()}),Lu=z.preprocess(a=>typeof a=="string"?{value:a,label:a}:a,z.strictObject({value:Za,label:z.string().min(1).optional(),selected:z.boolean().optional(),disabled:z.boolean().optional()})).transform(a=>({...a,label:a.label??a.value.toString()})),Fu=z.strictObject({type:z.literal("multi-choice"),message:z.string(),min:z.number().optional(),max:z.number().optional(),options:z.array(Lu),result:z.string()}),ju=z.strictObject({type:z.literal("text"),message:z.string(),default:z.string().optional(),required:z.boolean().optional(),result:z.string()}),Uu=z.strictObject({type:z.literal("keypress"),message:z.string(),key:z.union([z.literal("enter"),z.literal("space"),z.string().length(1)]).optional(),result:z.string().optional()}),Vu=z.discriminatedUnion("type",[zu,_u,Fu,ju,Uu]),Ii=class extends I{constructor(){super(Vu);}};var vi=class{constructor({serverFactory:e,serverProvider:t,packageManager:n,serverMap:r}){this.factory=e,this.provider=t,this.packageManager=n,this.serverMap=r;}async execute(e,t){let{output:n}=t,r=n.notify("Checking server"),i;try{i=await this.startServer(r,e.server);}finally{r.stop();}e.result?.url!==void 0&&t.set(e.result.url,i.url.toString()),e.result?.id!==void 0&&t.set(e.result.id,i.id??null);}async startServer(e,t){let n=await this.getServer(t),r=await n.getStatus();if(r.running)return {url:r.url,owned:false};e.update("Starting server");let i=randomUUID();return this.serverMap.set(i,n),{id:i,url:await n.start({logger:new oe({status:"Starting server",notifier:e})}),owned:true}}async getServer(e){if(e===void 0){let i=await this.provider.get();if(i===null)throw new d("No server detected.");return i}let t=new URL(e.url),n=t.protocol==="https:",r=n?443:80;return this.factory.create({host:t.hostname,protocol:n?"https":"http",defaultPort:t.port===""?r:Number.parseInt(t.port,10),command:await this.packageManager.getScriptCommand(e.script,e.arguments)})}};var qu=z.strictObject({server:z.strictObject({script:z.string(),arguments:z.array(z.string()).optional(),url:z.string()}).optional(),result:z.strictObject({id:z.string().optional(),url:z.string().optional()}).optional()}),xi=class extends I{constructor(){super(qu);}};var wi=class{constructor(e){this.actions=e;}async execute(e,t){for(let n of Array.isArray(e.actions)?e.actions:[e.actions])try{await this.run(n,t);}catch(r){if(r instanceof se&&r.help.cause instanceof JsonParseError){let{location:i}=r.help.cause;throw h.fromCause(r,{tracing:[{name:n.name,source:{url:r.url,start:i.start,end:i.end}}]})}throw h.fromCause(r,{tracing:[{name:n.name,source:cn.get(n)??void 0}]})}}run({name:e,...t},n){let r=this.actions[e];if(r===void 0)throw new h(`Unsupported action \`${e}\`.`,{reason:"invalid_input"});return r.execute(t,n)}};var rc=z.object({name:z.string().min(1)}).passthrough(),Hu=z.strictObject({actions:z.union([rc,z.array(rc)])}),Pi=class extends I{constructor(){super(Hu);}};var Ci=class{async execute(e,t){let{output:n}=t;await n.open(e.url);}};var Gu=z.strictObject({url:z.string().url()}),ki=class extends I{constructor(){super(Gu);}};var Bu=z.union([z.string(),z.number(),z.boolean(),z.null()]),Ja=z.lazy(()=>z.union([Bu,z.array(Ja),z.record(Ja)])),Zu=z.strictObject({variables:z.record(z.string(),Ja)}),Ai=class extends I{constructor(){super(Zu);}};var Ei=class{execute(e,t){for(let[n,r]of Object.entries(e.variables))t.set(n,r);return Promise.resolve()}};var Ju=z.strictObject({id:z.string()}),Oi=class extends I{constructor(){super(Ju);}};var Rt=class a extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,a.prototype);}};var pe=class{constructor(){this.lines=[[]];this.cursor={row:0,column:0};this.snapshot=[[]];this.ansiSequence="";this.lines=[[]];}write(e){for(let t=0;t<e.length;t++){let n=e[t];if(n==="\x1B"){this.ansiSequence="\x1B";continue}if(this.ansiSequence.length>0){this.ansiSequence+=n,/[A-Za-z]/.test(n)&&(this.processAnsiSequence(this.ansiSequence),this.ansiSequence="");continue}if(n==="\r"){let r=this.lines[this.cursor.row];for(let i=this.cursor.column;i<r.length;i++)r[i]=" ";this.cursor.column=0;continue}if(n===`
1774
1774
  `){this.cursor.row++,this.cursor.column=0,this.resize(this.cursor.row);continue}for(this.resize(this.cursor.row);this.lines[this.cursor.row].length<this.cursor.column;)this.lines[this.cursor.row].push(" ");this.lines[this.cursor.row][this.cursor.column]=n,this.cursor.column++;}}processAnsiSequence(e){let t=e.match(/\x1b\[(\d*(?:;\d+)*)?([A-Za-z])/);if(t===null){this.lines[this.cursor.row].push(e);return}let[,n,r]=t,i=n?.split(";").map(o=>o===""?0:Number.parseInt(o,10))??[];switch(r){case "A":{let o=i[0]??1;this.cursor.row=Math.max(0,this.cursor.row-o);break}case "B":{let o=i[0]??1;this.cursor.row+=o,this.resize(this.cursor.row);break}case "C":{let o=i[0]??1;this.cursor.column+=o;break}case "D":{let o=i[0]??1;this.cursor.column=Math.max(0,this.cursor.column-o);break}case "E":{let o=i[0]??1;this.cursor.row+=o,this.resize(this.cursor.row),this.cursor.column=0;break}case "F":{let o=i[0]??1;this.cursor.row=Math.max(0,this.cursor.row-o),this.cursor.column=0;break}case "G":{let o=(i[0]??1)-1;this.cursor.column=Math.max(0,o);break}case "H":case "f":{let o=(i[0]??1)-1,s=(i[1]??1)-1;this.cursor.row=Math.max(0,o),this.resize(this.cursor.row),this.cursor.column=Math.max(0,s);break}case "K":{let o=i[0]??0,s=this.lines[this.cursor.row];switch(o){case 0:s.length=this.cursor.column;break;case 1:for(let p=0;p<=this.cursor.column;p++)s[p]=" ";break;case 2:for(let p=0;p<s.length;p++)s[p]=" ";break}break}case "J":{switch(i[0]??0){case 0:{this.lines[this.cursor.row].length=this.cursor.column,this.lines.length=this.cursor.row+1;break}case 1:{this.lines=this.lines.slice(this.cursor.row);for(let s=0;s<=this.cursor.column;s++)this.lines[0][s]=" ";break}case 2:{this.lines=[[]],this.cursor={row:0,column:0};break}}break}default:this.resize(this.cursor.row),this.lines[this.cursor.row].push(e);break}}resize(e){for(;this.lines.length<=e;)this.lines.push([]);}getSnapshot(){return this.lines.map(e=>e.join("")).join(`
1775
1775
  `)}saveSnapshot(){this.snapshot=this.lines.map(e=>[...e]);}getSnapshotDiff(){let e=[];for(let t=0;t<this.lines.length;t++){let n=this.lines[t];if(this.snapshot[t]===void 0){e.push(n.join(""));continue}for(let r=0;r<n.length;r++)if(n[r]!==this.snapshot[t][r]){e.push(n.join(""));break}}return e.join(`
1776
1776
  `)}static getRawString(e){return Mc(e)}};var Ri=class{constructor(e){this.configuration=e;}async getStatus(){let e=await this.findAddress();return e===null?{running:false}:{running:true,url:e}}async start({logger:e}={}){let{commandExecutor:t,command:n,workingDirectory:r,processObserver:i}=this.configuration;try{this.execution=await t.run(n,{workingDirectory:r.get()});}catch(g){throw new Rt("Failed to start server.",{cause:g})}let o=new AbortController,s=()=>(o.abort(),this.stop());if(this.execution.onExit(()=>{this.execution=void 0,i.off("exit",s);}),!this.execution.running)throw new Rt("Failed to start server.");i.on("exit",s);let{output:p}=this.execution,c=new pe,l=(async()=>{for await(let g of p){if(o.signal.aborted)return;c.write(g),e?.log({level:LogLevel.DEBUG,message:g});}})(),u=await this.waitStart(o);if(o.abort(),await l,u===null){e?.log({level:LogLevel.ERROR,message:"Unable to reach the server after it was started."});let g=pe.getRawString(c.getSnapshot()).trim();throw new Rt(`Server is unreachable${g===""?".":`:
@@ -1778,7 +1778,7 @@ ${p}`,{reason:"invalid_input",url:e,violations:[{path:r,message:"Imported templa
1778
1778
  ${g}`}`)}return u}async stop(){await this.execution?.kill("SIGINT"),this.execution=void 0;}async waitStart(e){let{startupCheckDelay:t,startupTimeout:n}=this.configuration,r=setTimeout(()=>e.abort(),n);r.unref(),e.signal.addEventListener("abort",()=>{clearTimeout(r);});let i=()=>new Promise(o=>{let s=()=>{o(),e.signal.removeEventListener("abort",s);};setTimeout(o,t),e.signal.addEventListener("abort",s);});do{let o=await this.findAddress(e);if(o!==null)return o;await i();}while(!e.signal.aborted);return null}async findAddress(e){let{lookupTimeout:t,lookupMaxPorts:n,server:{protocol:r,host:i,port:o,defaultPort:s}}=this.configuration,p=o??s,c=o??s+n-1,l=new AbortController;e!==void 0&&e.signal.addEventListener("abort",()=>l.abort()),setTimeout(()=>l.abort(),t).unref();let g=new URL(`${r}://${i}`);for(let y=p;y<=c;y++){try{return g.port=y.toString(),await fetch(g,{method:"HEAD",signal:l.signal}),g}catch{}if(l.signal.aborted)break}return null}};var Ti=class{constructor(e){this.configuration=e;}create(e){return Promise.resolve(new Ri({...this.configuration,command:e.command,server:{protocol:e.protocol,host:e.host,defaultPort:e.defaultPort,port:e.port}}))}};var Xu=z.strictObject({path:z.string()}),Di=class extends I{constructor(){super(Xu);}};var Mi=class{constructor({fileSystem:e,rootDirectory:t,currentDirectory:n}){this.fileSystem=e,this.rootDirectory=t,this.currentDirectory=n;}async execute(e){let t=this.fileSystem.normalizeSeparators(e.path),n=this.fileSystem.isAbsolutePath(t)?t:this.fileSystem.joinPaths(this.currentDirectory.get(),t);if(!await this.fileSystem.isDirectory(n))throw new h(`Target path \`${t}\` is not a directory.`,{reason:"invalid_input",details:[`Target path: ${t}`]});if(!this.fileSystem.isSubPath(this.rootDirectory,n))throw new h("Cannot change to a directory outside the current working directory.",{reason:"precondition",details:[`Working directory: ${this.rootDirectory}`,`Target directory: ${n}`]});return this.currentDirectory.setCurrentDirectory(n),Promise.resolve()}};var Ni=class a{static{this.INPUT_MAP={"[space]":" ","[enter]":`
1779
1779
  `,"[down]":"\x1B[A","[up]":"\x1B[B","[left]":"\x1B[C","[right]":"\x1B[D","[backspace]":"\b"};}constructor(e){this.configuration=e;}async execute(e,t){let{input:n,output:r}=t,{sourceChecker:i}=this.configuration;if(e.interactions===true&&e.output!==void 0)throw new h("Cannot capture output when interactions are enabled.",{reason:"not_supported",details:["Either use `interactions` or `output`, but not both."]});let o=await this.resolveCommand(e),s=a.formatCommand(o);if(e.script!==true&&!await i.test(t.baseUrl)){if(n===void 0)throw new h("Action requires explicit user confirmation.",{reason:"precondition",details:["Retry in interactive mode."]});if(r.warn(`This template will run the command \`${s}\``),!await n.confirm({message:"Continue?",default:true}))throw new h("Permission to run command denied.",{reason:"precondition"})}let p=r.notify(`Running \`${s}\``),c;try{c=await this.executeCommand(o,p,e.interactions??!1);}catch(l){throw h.fromCause(l)}finally{p?.stop();}e.output!==void 0&&t.set(e.output,c);}async resolveCommand(e){let t=await this.getPackageManager(e.runner);return e.script===true?t.getScriptCommand(e.command,e.arguments):t.getPackageCommand(e.command,e.arguments)}getPackageManager(e){return e===void 0?this.configuration.packageManager:this.configuration.packageManagerProvider.get(e)}async executeCommand(e,t,n){let{processObserver:r,workingDirectory:i,commandExecutor:o,commandTimeout:s}=this.configuration,p=await o.run(e,{workingDirectory:i.get(),timeout:s,inheritIo:n===true}),c=()=>{p.kill();};r.on("exit",c),p.onExit(()=>r.off("exit",c));let l=a.formatCommand(e);n===true&&t.stop(true);let u=new pe,g=new oe({status:`Running \`${l}\``,notifier:t});if(n!==true){let A=Array.isArray(n)?[...n]:[];A.length===0&&await p.endWriting();for await(let M of p.output){u.write(M),g.log({level:LogLevel.DEBUG,message:pe.getRawString(M)});let F=u.getSnapshotDiff();for(let[S,P]of A.entries())if(P.pattern===true?new RegExp(P.when).test(F):F.includes(P.when)){u.saveSnapshot(),P.always!==true&&A.splice(S,1);for(let ce of P.then??[])await p.write(a.INPUT_MAP[ce]??ce);P.final===true&&(await p.endWriting(),A.length=0);break}}}let y=-1;try{y=await p.wait();}catch(A){throw new h("Command execution failed.",{reason:"unexpected_result",cause:A})}let v=pe.getRawString(u.getSnapshot()).trim();if(y!==0)throw new h(`Command execution failed${v===""?".":`:
1780
1780
 
1781
- ${v}`}`,{reason:"unexpected_result"});return v}static formatCommand(e){return [e.name.split(/[\\/]/).pop(),...(e.arguments??[]).map(t=>!t.startsWith("-")&&t.includes(" ")?JSON.stringify(t):t)].join(" ")}};var em=z.array(z.object({when:z.string(),pattern:z.boolean().optional(),always:z.boolean().optional(),then:z.array(z.string()).min(1).optional(),final:z.boolean().optional()}).superRefine((a,e)=>{if(a.then===void 0&&a.final===void 0&&e.addIssue({code:z.ZodIssueCode.custom,message:"Either `then` or `final` must be defined"}),a.final===true&&a.always===true&&e.addIssue({code:z.ZodIssueCode.custom,path:["always"],message:"Final interactions must have `always` set to `false`"}),a.pattern===true)try{new RegExp(a.when);}catch{e.addIssue({code:z.ZodIssueCode.custom,path:["pattern"],message:"The `when` field must be a valid regular expression"});}})).min(1).optional().refine(a=>a===void 0||a.some(e=>e.final===true),{message:"At least one interaction must have `final` set to `true`"}),tm=z.strictObject({command:z.string(),script:z.boolean().optional(),arguments:z.array(z.string()).optional(),runner:z.string().optional(),interactions:z.union([z.boolean(),em]),output:z.string().optional()}),zi=class extends I{constructor(){super(tm);}};var de=class a extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,a.prototype);}};var Ze=class{constructor(e){this.manifestPath=new Map;this.projectDirectory=e.projectDirectory,this.fileSystem=e.fileSystem,this.agent=e.agent,this.packageValidator=e.packageValidator;}getName(){return this.agent.getName()}isInstalled(){return this.agent.isInstalled()}isProject(){return this.fileSystem.exists(this.getProjectManifestPath())}addDependencies(e,t){return this.agent.addDependencies(e,t)}installDependencies(e){return this.agent.installDependencies(e)}updatePackage(e,t){return this.agent.updatePackage(e,t)}getPackageCommand(e,t=[]){return this.agent.getPackageCommand(e,t)}getScriptCommand(e,t=[]){return this.agent.getScriptCommand(e,t)}getPackageUpdateCommand(e,t){return this.agent.getPackageUpdateCommand(e,t)}async hasDirectDependency(e,t){let n=await this.readManifest(this.getProjectManifestPath());return n?.dependencies?.[e]===void 0&&n?.devDependencies?.[e]===void 0?false:t===void 0?true:this.hasDependency(e,t)}async hasDependency(e,t){let n=await this.getDependency(e);return n===null?false:t===void 0||n.version===null?t===void 0:t===void 0||n.version!==null&&nm.satisfies(n.version,t)}async getDependency(e){let t=await this.findPackageManifestPath(e);if(t===null)return null;let n=await this.readManifest(t);return n===null?null:{name:n.name,version:n.version??null,directory:this.fileSystem.getDirectoryName(t),metadata:n}}async getScripts(){let e=await this.readManifest(this.getProjectManifestPath());return e===null?{}:e.scripts??{}}async addScript(e,t){let n=this.getProjectManifestPath();if(!await this.fileSystem.exists(n))throw new de("Package file not found in the project.",{reason:"precondition",details:[`File: ${n}`]});let r=await this.fileSystem.readTextFile(n),i=JsonParser.parse(r,JsonObjectNode);if(i.has("scripts")){let o=i.get("scripts",JsonObjectNode),s=t;if(o.has(e)){let c=o.get(e).toJSON();if(typeof c=="string"&&c.includes(t))return;s=`${c} && ${t}`;}o.set(e,s);}else i.set("scripts",{[e]:t});await this.fileSystem.writeTextFile(n,i.toString(),{overwrite:true});}async findPackageManifestPath(e,t){let n=t??this.projectDirectory.get(),r=this.fileSystem.joinPaths(n,"node_modules",e,"package.json"),i=this.manifestPath.get(r);if(i!==void 0)return i;let o=r;if(!await this.fileSystem.exists(r)){let s=this.fileSystem.getDirectoryName(n);o=s!==n?await this.findPackageManifestPath(e,s):null;}return this.manifestPath.set(r,o),o}getProjectManifestPath(){return this.fileSystem.joinPaths(this.projectDirectory.get(),"package.json")}async readManifest(e){if(!await this.fileSystem.exists(e))return null;let t;try{t=JSON.parse(await this.fileSystem.readTextFile(e));}catch{return null}let n=await this.packageValidator.validate(t);return n.valid?n.data:null}};var $e=class{constructor(e){this.projectDirectory=e.projectDirectory,this.commandRunner=e.commandExecutor,this.executableLocator=e.executableLocator;}isInstalled(){return this.installed===void 0&&(this.installed=this.getExecutable(this.getCommandName()).then(e=>e!==null)),this.installed}getName(){return Promise.resolve(this.getCommandName())}async addDependencies(e,t){return this.run(await this.createAddDependencyCommand(e,t?.dev??false),{logger:t?.logger})}async installDependencies(e){return this.run(await this.createInstallDependenciesCommand(),{logger:e?.logger})}async updatePackage(e,t){return this.run(await this.createPackageUpdateCommand(e,t?.global??false),{logger:t?.logger})}getPackageCommand(e,t){return this.createPackageCommand(e,t)}getPackageUpdateCommand(e,t={}){return this.createPackageUpdateCommand(e,t.global??false)}getScriptCommand(e,t){return this.createScriptCommand(e,t)}async run(e,{logger:t,...n}={}){if(!await this.isInstalled())throw new de(`Package manager \`${this.getCommandName()}\` is not installed.`);let r=await this.commandRunner.run(e,{...n,workingDirectory:this.projectDirectory.get()}),i=new pe;for await(let o of r.output)i.write(o),t?.log({level:LogLevel.DEBUG,message:pe.getRawString(o).trim(),details:{output:pe.getRawString(i.getSnapshot()).trim()}});if(await r.wait()!==0){let o=pe.getRawString(i.getSnapshot()).trim();throw t?.log({level:LogLevel.ERROR,message:`Failed to run \`${e.name}\` command.`,details:{command:e.name,arguments:e.arguments??[],output:o}}),new de(`Failed to run \`${e.name}\` command${o===""?".":`:
1781
+ ${v}`}`,{reason:"unexpected_result"});return v}static formatCommand(e){return [e.name.split(/[\\/]/).pop(),...(e.arguments??[]).map(t=>!t.startsWith("-")&&t.includes(" ")?JSON.stringify(t):t)].join(" ")}};var em=z.array(z.object({when:z.string(),pattern:z.boolean().optional(),always:z.boolean().optional(),then:z.array(z.string()).min(1).optional(),final:z.boolean().optional()}).superRefine((a,e)=>{if(a.then===void 0&&a.final===void 0&&e.addIssue({code:z.ZodIssueCode.custom,message:"Either `then` or `final` must be defined"}),a.final===true&&a.always===true&&e.addIssue({code:z.ZodIssueCode.custom,path:["always"],message:"Final interactions must have `always` set to `false`"}),a.pattern===true)try{new RegExp(a.when);}catch{e.addIssue({code:z.ZodIssueCode.custom,path:["pattern"],message:"The `when` field must be a valid regular expression"});}})).min(1).optional().refine(a=>a===void 0||a.some(e=>e.final===true),{message:"At least one interaction must have `final` set to `true`"}),tm=z.strictObject({command:z.string(),script:z.boolean().optional(),arguments:z.array(z.string()).optional(),runner:z.string().optional(),interactions:z.union([z.boolean(),em]),output:z.string().optional()}),zi=class extends I{constructor(){super(tm);}};var de=class a extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,a.prototype);}};var Ze=class{constructor(e){this.manifestPath=new Map;this.projectDirectory=e.projectDirectory,this.fileSystem=e.fileSystem,this.agent=e.agent,this.packageValidator=e.packageValidator;}getName(){return this.agent.getName()}isInstalled(){return this.agent.isInstalled()}isProject(){return this.fileSystem.exists(this.getProjectManifestPath())}addDependencies(e,t){return this.agent.addDependencies(e,t)}installDependencies(e){return this.agent.installDependencies(e)}updatePackage(e,t){return this.agent.updatePackage(e,t)}getPackageCommand(e,t=[]){return this.agent.getPackageCommand(e,t)}getScriptCommand(e,t=[]){return this.agent.getScriptCommand(e,t)}getPackageUpdateCommand(e,t){return this.agent.getPackageUpdateCommand(e,t)}async hasDirectDependency(e,t){let n=await this.readManifest(this.getProjectManifestPath());return n?.dependencies?.[e]===void 0&&n?.devDependencies?.[e]===void 0?false:t===void 0?true:this.hasDependency(e,t)}async hasDependency(e,t){let n=await this.getDependency(e);return n===null?false:t===void 0||n.version===null?t===void 0:t===void 0||n.version!==null&&nm.satisfies(n.version,t)}async getDependency(e){let t=await this.findPackageManifestPath(e);if(t===null)return null;let n=await this.readManifest(t);return n===null?null:{name:n.name,version:n.version??null,directory:this.fileSystem.getDirectoryName(t),metadata:n}}async getScripts(){let e=await this.readManifest(this.getProjectManifestPath());return e===null?{}:e.scripts??{}}async addScript(e,t){let n=this.getProjectManifestPath();if(!await this.fileSystem.exists(n))throw new de("Package file not found in the project.",{reason:"precondition",details:[`File: ${n}`]});let r=await this.fileSystem.readTextFile(n),i=JsonParser$1.parse(r,JsonObjectNode$1);if(i.has("scripts")){let o=i.get("scripts",JsonObjectNode$1),s=t;if(o.has(e)){let c=o.get(e).toJSON();if(typeof c=="string"&&c.includes(t))return;s=`${c} && ${t}`;}o.set(e,s);}else i.set("scripts",{[e]:t});await this.fileSystem.writeTextFile(n,i.toString(),{overwrite:true});}async findPackageManifestPath(e,t){let n=t??this.projectDirectory.get(),r=this.fileSystem.joinPaths(n,"node_modules",e,"package.json"),i=this.manifestPath.get(r);if(i!==void 0)return i;let o=r;if(!await this.fileSystem.exists(r)){let s=this.fileSystem.getDirectoryName(n);o=s!==n?await this.findPackageManifestPath(e,s):null;}return this.manifestPath.set(r,o),o}getProjectManifestPath(){return this.fileSystem.joinPaths(this.projectDirectory.get(),"package.json")}async readManifest(e){if(!await this.fileSystem.exists(e))return null;let t;try{t=JSON.parse(await this.fileSystem.readTextFile(e));}catch{return null}let n=await this.packageValidator.validate(t);return n.valid?n.data:null}};var $e=class{constructor(e){this.projectDirectory=e.projectDirectory,this.commandRunner=e.commandExecutor,this.executableLocator=e.executableLocator;}isInstalled(){return this.installed===void 0&&(this.installed=this.getExecutable(this.getCommandName()).then(e=>e!==null)),this.installed}getName(){return Promise.resolve(this.getCommandName())}async addDependencies(e,t){return this.run(await this.createAddDependencyCommand(e,t?.dev??false),{logger:t?.logger})}async installDependencies(e){return this.run(await this.createInstallDependenciesCommand(),{logger:e?.logger})}async updatePackage(e,t){return this.run(await this.createPackageUpdateCommand(e,t?.global??false),{logger:t?.logger})}getPackageCommand(e,t){return this.createPackageCommand(e,t)}getPackageUpdateCommand(e,t={}){return this.createPackageUpdateCommand(e,t.global??false)}getScriptCommand(e,t){return this.createScriptCommand(e,t)}async run(e,{logger:t,...n}={}){if(!await this.isInstalled())throw new de(`Package manager \`${this.getCommandName()}\` is not installed.`);let r=await this.commandRunner.run(e,{...n,workingDirectory:this.projectDirectory.get()}),i=new pe;for await(let o of r.output)i.write(o),t?.log({level:LogLevel.DEBUG,message:pe.getRawString(o).trim(),details:{output:pe.getRawString(i.getSnapshot()).trim()}});if(await r.wait()!==0){let o=pe.getRawString(i.getSnapshot()).trim();throw t?.log({level:LogLevel.ERROR,message:`Failed to run \`${e.name}\` command.`,details:{command:e.name,arguments:e.arguments??[],output:o}}),new de(`Failed to run \`${e.name}\` command${o===""?".":`:
1782
1782
 
1783
1783
  ${o}`}`)}}getExecutable(e){return this.executableLocator.locate(e)}};var $i=class extends $e{getCommandName(){return "npm"}createPackageCommand(e,t=[]){return Promise.resolve(this.getCommand("npx",["--yes",e,...t]))}createScriptCommand(e,t=[]){return Promise.resolve(this.getCommand(this.getCommandName(),["run",e,...t.length>0?["--",...t]:[]]))}createAddDependencyCommand(e,t){return Promise.resolve(this.getCommand(this.getCommandName(),["install",...t?["--save-dev"]:[],...e]))}createInstallDependenciesCommand(){return Promise.resolve(this.getCommand(this.getCommandName(),["install"]))}createPackageUpdateCommand(e,t=false){return Promise.resolve(this.getCommand(this.getCommandName(),["update",...t?["--global"]:[],e]))}getCommand(e,t=[]){return {name:e,arguments:t}}};var _i=class extends $e{getCommandName(){return "yarn"}createPackageCommand(e,t=[]){return Promise.resolve(this.getCommand("npx",["--yes",e,...t]))}createScriptCommand(e,t=[]){return Promise.resolve(this.getCommand(this.getCommandName(),["run",e,...t]))}createAddDependencyCommand(e,t){return Promise.resolve(this.getCommand(this.getCommandName(),["add",...t?["--dev"]:[],...e]))}createInstallDependenciesCommand(){return Promise.resolve(this.getCommand(this.getCommandName(),["install"]))}createPackageUpdateCommand(e,t=false){return Promise.resolve(this.getCommand(this.getCommandName(),t?["global","add",`${e}@latest`]:["upgrade",e]))}getCommand(e,t=[]){return {name:e,arguments:t}}};var Li=class extends $e{getCommandName(){return "bun"}createPackageCommand(e,t=[]){return Promise.resolve(this.getCommand(["x",e,...t]))}createScriptCommand(e,t=[]){return Promise.resolve(this.getCommand(["run",e,...t]))}createAddDependencyCommand(e,t){return Promise.resolve(this.getCommand(["install",...t?["--dev"]:[],...e]))}createInstallDependenciesCommand(){return Promise.resolve(this.getCommand(["install"]))}createPackageUpdateCommand(e,t=false){return Promise.resolve(this.getCommand(["update",...t?["--global"]:[],e]))}getCommand(e=[]){return {name:this.getCommandName(),arguments:e}}};var Fi=class extends $e{getCommandName(){return "pnpm"}createPackageCommand(e,t=[]){return Promise.resolve(this.getCommand(["dlx",e,...t]))}createScriptCommand(e,t=[]){return Promise.resolve(this.getCommand(["run",e,...t]))}createAddDependencyCommand(e,t){return Promise.resolve(this.getCommand(["install",...t?["--save-dev"]:[],...e]))}createInstallDependenciesCommand(){return Promise.resolve(this.getCommand(["install"]))}createPackageUpdateCommand(e,t=false){return Promise.resolve(this.getCommand(["update",...t?["--global"]:[],e]))}getCommand(e=[]){return {name:this.getCommandName(),arguments:e}}};var ji=class{constructor({projectDirectory:e,fileSystem:t,tsConfigLoader:n}){this.projectDirectory=e,this.fileSystem=t,this.tsConfigLoader=n;}async getImportPath(e,t){let n=this.projectDirectory.get(),r=this.fileSystem.isAbsolutePath(t)?t:this.fileSystem.joinPaths(n,t),i=this.fileSystem.isAbsolutePath(e)?e:this.fileSystem.joinPaths(n,e),o=await this.tsConfigLoader.load(n,{sourcePaths:[r]}),s=/\.m(?:js|ts)?$/.test(i)?i:i.replace(/\.(ts|js)x?$/,"");if(o!==null&&this.fileSystem.isSubPath(n,s)){let c=this.fileSystem.getRelativePath(n,s),l=0,u=null;for(let[g,y]of Object.entries(o.paths)){let v=this.fileSystem.normalizeSeparators(g.replace(/\*$/,""));for(let A of y){let M=A.replace(/\*$/,""),F=this.fileSystem.getRelativePath(n,this.fileSystem.joinPaths(o.baseUrl,M));if(c.startsWith(F)){let S=M.length;if(S>l){l=S;let P=c.slice(F.length).replace(/^[\\/]+/,"");u=v+P;}}}}if(u!==null)return Promise.resolve(u.replace(/\\+/g,"/"))}let p=this.fileSystem.getRelativePath(this.fileSystem.joinPaths(r,".."),s).replace(/\\/g,"/");return Promise.resolve(/^\.\.?\/ ?/.test(p)?p:`./${p}`)}};var im=z.object({extends:z.string().optional(),references:z.array(z.object({path:z.string()})).optional(),include:z.array(z.string()).optional(),compilerOptions:z.object({baseUrl:z.string().optional(),paths:z.record(z.array(z.string())).optional()}).optional()}),Ui=class extends G{constructor(){super(im);}};var dn=class{constructor(e){this.provider=e;}get manager(){return Promise.resolve(this.provider.get()).catch(e=>{throw e instanceof j?new de(e.message,e.help):e})}async getName(){return (await this.manager).getName()}async isInstalled(){return (await this.manager).isInstalled()}async isProject(){return (await this.manager).isProject()}async hasDependency(e,t){return (await this.manager).hasDependency(e,t)}async hasDirectDependency(e,t){return (await this.manager).hasDirectDependency(e,t)}async getDependency(e){return (await this.manager).getDependency(e)}async addDependencies(e,t){return (await this.manager).addDependencies(e,t)}async updatePackage(e,t){return (await this.manager).updatePackage(e,t)}async installDependencies(e){return (await this.manager).installDependencies(e)}async getScripts(){return (await this.manager).getScripts()}async addScript(e,t){return (await this.manager).addScript(e,t)}async getScriptCommand(e,t){return (await this.manager).getScriptCommand(e,t)}async getPackageCommand(e,t){return (await this.manager).getPackageCommand(e,t)}async getPackageUpdateCommand(e,t){return (await this.manager).getPackageUpdateCommand(e,t)}};var Vi=class{constructor(e){this.map=e;}supports(e){return this.map.has(e)}get(e){let t=this.map.get(e);if(t===void 0)throw new j(`No value found for key \`${e}\`.`,{reason:"not_found"});return Promise.resolve(t)}};var Wi=class{getName(){return Promise.resolve("noop")}isInstalled(){return Promise.resolve(false)}addDependencies(){return this.fail()}installDependencies(){return this.fail()}updatePackage(){return this.fail()}getPackageCommand(){return this.fail()}getScriptCommand(){return this.fail()}getPackageUpdateCommand(){return this.fail()}fail(){throw new de("The package manager is not installed")}};var Tt=class{constructor(e,t){this.provider=e,this.fallback=t;}async get(...e){let t=await this.provider.get(...e)??null;return t!==null?t:this.fallback.get(...e)}};var we=class{constructor(e){this.callback=e;}get(...e){return this.callback(...e)}};var lt=class{constructor(e){this.candidates=e.candidates;}async get(...e){for(let{condition:t,value:n}of this.candidates)try{if(await t.test(...e))return typeof n=="object"&&n!==null&&"get"in n?n.get(...e):n}catch{}return null}};var gn=class{constructor({fileSystem:e,files:t}){this.fileSystem=e,this.files=t;}async test(){return (await Promise.all(this.files.map(t=>this.fileSystem.exists(t)))).some(t=>t)}};var fn=class{constructor({packageManager:e,dependencies:t}){this.packageManager=e,this.dependencies=t;}async test(){return (await Promise.all(this.dependencies.map(t=>this.packageManager.hasDirectDependency(t)))).some(t=>t)}};var qi=class{constructor({packageManager:e}){this.packageManager=e;}test(){return this.packageManager.isProject()}};var Pe=class a extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,a.prototype);}};var Ki=class{constructor(){this.open=true;this.queue=[];}async*[Symbol.asyncIterator](){let e=await this.next();for(;e.done!==true;)yield e.value,e=await this.next();}next(){return this.queue.length>0?Promise.resolve({done:false,value:this.queue.shift()}):this.open?new Promise(e=>{this.resolve=()=>{this.resolve=void 0,this.queue.length===0?e({done:true,value:void 0}):e({done:false,value:this.queue.shift()});};}):Promise.resolve({done:true,value:void 0})}push(e){this.queue.push(e),this.resolve?.();}close(){this.open=false,this.resolve?.();}};var Hi=class a{constructor({currentDirectory:e,windows:t=false}){this.currentDirectory=e,this.isWindows=t;}run(e,t={}){let n=t.timeout!==void 0?AbortSignal.timeout(t.timeout):void 0,r=this.prepareCommand(e),i=spawn(r.name,r.arguments??[],{stdio:t.inheritIo===true?"inherit":"pipe",shell:r.shell,cwd:t?.workingDirectory??this.currentDirectory?.get(),signal:n}),o=new Ki,s=[],p=null;i.on("error",u=>{o.close(),p=n?.aborted===true?new Pe("Command timed out.",{reason:"precondition",cause:u}):new Pe(`Failed to run command: ${d.formatCause(u)}`,{cause:u});for(let g of s)g(p);});let c=u=>{o.push(u.toString());};i.stdout?.on("data",c),i.stderr?.on("data",c);let l=[];return i.on("exit",u=>{o.close();for(let g of l)g(u??1);}),Promise.resolve({output:o,get running(){return i.exitCode===null},onExit:u=>(l.push(u),()=>{let g=l.indexOf(u);g!==-1&&l.splice(g,1);}),write:u=>new Promise((g,y)=>{if(i.stdin===null){y(new Pe("Subprocess is not writable."));return}i.stdin.write(u,v=>{v===null?g():y(v);});}),endWriting:()=>new Promise(u=>{if(i.stdin===null||i.exitCode!==null){u();return}i.stdin.end(u);}),read:async()=>{let u="";for await(let g of o)u+=g;return u},wait:()=>new Promise((u,g)=>{if(p!==null){g(p);return}if(i.exitCode!==null){u(i.exitCode);return}s.push(g),i.on("exit",y=>{u(y??1);});}),kill:u=>new Promise((g,y)=>{if(i.exitCode!==null){g();return}i.stdout?.destroy(),i.stderr?.destroy(),i.stdin?.destroy(),i.kill(u)?g():y(new Pe("Failed to kill the subprocess."));})})}runSync(e,t={}){let n=t.timeout!==void 0?AbortSignal.timeout(t.timeout):void 0,r=this.prepareCommand(e),i=spawnSync(r.name,r.arguments,{stdio:[t.inheritIo===true?"inherit":"ignore","pipe","pipe"],cwd:t?.workingDirectory??this.currentDirectory?.get(),shell:r.shell,signal:n});if(i.error!==void 0){let{error:p}=i;throw n?.aborted===true?new Pe("Command timed out.",{reason:"precondition",cause:p}):new Pe(`Failed to run command: ${d.formatCause(p)}`,{cause:p})}let o=i.stdout.toString(),s=i.stderr.toString();return o!==""&&s!==""&&(o=`${o}
1784
1784
  ${s}`),{exitCode:i.status??1,output:o}}prepareCommand(e){return this.isWindowShell(e.name)?{name:a.escapeCommand(e.name),arguments:(e.arguments??[]).map(a.escapeArgument),shell:true}:{...e,shell:false}}isWindowShell(e){return this.isWindows&&(e.endsWith(".bat")||e.endsWith(".cmd"))}static escapeCommand(e){return `"${e}"`}static escapeArgument(e){return `"${e.replace("\\","\\\\").replace('"','\\"')}"`}};var Gi=class{constructor(e){this.provider=e;}async format(e){return (await this.formatter).format(e)}get formatter(){return Promise.resolve(this.provider.get()).catch(e=>{throw e instanceof j?new de(e.message,e.help):e})}};var Bi=class{constructor(e){this.provider=e;}get sdk(){return Promise.resolve(this.provider.get()).catch(e=>{throw e instanceof j?new X(e.message,e.help):e})}async setup(e){return (await this.sdk).setup(e)}async getPaths(e){return (await this.sdk).getPaths(e)}async update(e,t){return (await this.sdk).update(e,t)}async generateSlotExample(e,t){return (await this.sdk).generateSlotExample(e,t)}};var yn=class{constructor(e,t){this.valueProvider=e,this.keyProvider=t;}async get(...e){if(this.keyProvider!==void 0){let t=this.key;if(this.key=await this.keyProvider.get(...e),t===this.key&&this.value!==void 0)return this.value}else if(this.value!==void 0)return this.value;return this.value=Promise.resolve(this.valueProvider.get(...e)),this.value}};var Zi=class{constructor(e){this.predicate=e;}async test(...e){return !await this.predicate.test(...e)}};var Ji=class{constructor({fileSystem:e,workingDirectory:t}){this.cache=new Map;this.fileSystem=e,this.workingDirectory=t;}async test(e){return (await this.getPredicate()).test(e)}async getPredicate(){let e=this.workingDirectory.get(),t=this.fileSystem.joinPaths(e,".gitignore");if(this.cache.has(t))return this.cache.get(t);let n={test:()=>Promise.resolve(false)};if(await this.fileSystem.exists(t)){let r=sm();r.add(await this.fileSystem.readTextFile(t)),n={test:i=>{if(!this.fileSystem.isSubPath(e,i))return Promise.resolve(false);let o=this.fileSystem.getRelativePath(e,i);return o===""?Promise.resolve(false):Promise.resolve(r.ignores(o))}};}return this.cache.set(t,n),n}};var Qi=class{constructor(e){this.predicate=e;}get(...e){return this.predicate.test(...e)}};var hn=class{constructor(e){this.input=e;}confirm(e){return e.default!==void 0?Promise.resolve(e.default):this.input.confirm(e)}prompt(e){return e.default!==void 0?Promise.resolve(e.default):this.input.prompt(e)}select(e){return e.default!==void 0?Promise.resolve(e.default):this.input.select(e)}selectMultiple(e){let t=e.options.filter(n=>n.selected===true);return t.length>0&&(e.min===void 0||t.length>=e.min)?Promise.resolve(t.map(n=>n.value)):this.input.selectMultiple(e)}wait(e){return this.input.wait(e)}};var Sn=class{constructor(...e){this.predicates=e;}async test(...e){for(let t of this.predicates)if(await t.test(...e))return true;return false}};var Qa={};xc(Qa,{basename:()=>lm,dirname:()=>um,ext:()=>cm,uuid:()=>mm});var cm=a=>{if(typeof a!="string")throw new N(`The \`path\` argument of the \`ext\` function must be a string, but got ${d.describeType(a)}.`);return a.split(".").pop()??""},lm=(a,e=false)=>{if(typeof a!="string")throw new N(`The \`path\` argument of the \`basename\` function must be a string, but got ${d.describeType(a)}.`);if(typeof e!="boolean")throw new N(`The \`omitExtension\` argument of the \`basename\` function must be a boolean, but got ${d.describeType(e)}.`);let t=a.split(/[\\/]/).pop()??"";return e?t.replace(/\.[^/.]+$/,""):t},um=a=>{if(typeof a!="string")throw new N(`The \`path\` argument of the \`dirname\` function must be a string, but got ${d.describeType(a)}.`);return a.replace(/[\\/][^\\/]*$/,"")},mm=()=>randomUUID();var Xi=class{constructor(e){this.runner=e;}async execute(e,t){for(;await e.condition;)await this.run(e.actions,t);}run(e,t){return this.runner.execute({actions:e},t)}};var dm=z.strictObject({condition:z.instanceof(Promise),actions:z.instanceof(Promise)}),Yi=class extends I{constructor(){super(dm);}};var U=class a extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,a.prototype);}};var eo=class a{constructor({fileSystem:e,commandExecutor:t,appDirectory:n}){this.fileSystem=e,this.commandExecutor=t,this.appDirectory=n;}async isRegistered(e){return await this.findLauncher(e)!==null}async register(e){if(!await this.isRegistered(e.protocol))try{await this.install(e);}catch(t){throw new U("Failed to register protocol handler.",{cause:t})}}async unregister(e){let t=await this.findLauncher(e);if(t===null)return;let n=this.getLauncherAppPath(e);if(t!==n)throw new U(`Application registered for protocol \`${e}\` is externally managed.`,{reason:"precondition"});try{await this.fileSystem.delete(n,{recursive:!0}),await this.fileSystem.delete(this.getHandlerAppPath(e),{recursive:!0});}catch(r){throw new U("Failed to unregister protocol handler.",{cause:r})}}async install(e){let t=this.getLauncherAppPath(e.protocol),n=this.getHandlerAppPath(e.protocol),r=this.createLauncherApp(e,n),i=this.createHandlerApp(e),o=await this.fileSystem.createTemporaryDirectory("protocol"),s=this.fileSystem.joinPaths(o,"launcher.scpt"),p=this.fileSystem.joinPaths(o,"handler.scpt");await this.fileSystem.writeTextFile(s,r),await this.fileSystem.writeTextFile(p,i),await this.fileSystem.createDirectory(this.appDirectory,{recursive:true}),await this.execute({name:"osacompile",arguments:["-o",t,s]}),await this.execute({name:"osacompile",arguments:["-o",n,p]}),await this.execute({name:"plutil",arguments:["-insert","CFBundleURLTypes","-json",JSON.stringify([{CFBundleURLName:a.formatId(e.id),CFBundleURLSchemes:[e.protocol]}]),`${t}/Contents/Info.plist`]}),await this.execute({name:"open",arguments:["-g",t]});}async findLauncher(e){let n=(await this.execute({name:"osascript",arguments:["-e",Y`
@@ -1839,9 +1839,9 @@ ${t.join(`
1839
1839
  ${this.getPreferences(e.protocol).join(`
1840
1840
  `)}`;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(`
1841
1841
  `).filter(c=>!this.getPreferences(e).includes(c)).join(`
1842
- `);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$2(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 Uo=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 v=this.fileSystem.joinPaths("./",this.fileSystem.getRelativePath(this.fileSystem.getDirectoryName(u),y));for(let A of g.include){let M=new Minimatch(A,{partial:true,magicalBraces:true});if(!M.hasMagic()&&!A.includes(".")&&(M=new Minimatch(`${A.replace(/\/?$/,"")}/**/*`,{partial:true})),M.match(v))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(Fm(r))return t=true,n.stop()}}),t}function Fm(a){return isTypeScript(a)||jm(a)}function jm(a){return (isImportSpecifier(a)||isImportDeclaration(a))&&(a.importKind==="type"||a.importKind==="typeof")}var Wo=class{async apply(e){if(!gc(e))return {modified:false,result:e};let t=createConfigItem([Wm,{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],v=u.find((M,F)=>F>g&&!["CommentLine","CommentBlock"].includes(M.type));if(v===void 0)continue;v.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 Bo=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({}),Zo=class extends I{constructor(){super(Gm);}};var Jo=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 Qo=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 Bm=z.strictObject({path:z.string().min(1),destination:z.string().min(1),overwrite:z.boolean().optional()}),Yo=class extends I{constructor(){super(Bm);}};var Zm=z.strictObject({path:z.string().min(1),optional:z.boolean().optional(),result:z.string().min(1)}),ta=class extends I{constructor(){super(Zm);}};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 Jm=z.strictObject({path:z.string().min(1)}),ra=class extends I{constructor(){super(Jm);}};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 Qm=z.strictObject({path:z.string().min(1),content:z.string(),overwrite:z.boolean().optional()}),aa=class extends I{constructor(){super(Qm);}};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:
1842
+ `);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$2(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 Uo=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 v=this.fileSystem.joinPaths("./",this.fileSystem.getRelativePath(this.fileSystem.getDirectoryName(u),y));for(let A of g.include){let M=new Minimatch(A,{partial:true,magicalBraces:true});if(!M.hasMagic()&&!A.includes(".")&&(M=new Minimatch(`${A.replace(/\/?$/,"")}/**/*`,{partial:true})),M.match(v))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$1.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(Fm(r))return t=true,n.stop()}}),t}function Fm(a){return isTypeScript(a)||jm(a)}function jm(a){return (isImportSpecifier(a)||isImportDeclaration(a))&&(a.importKind==="type"||a.importKind==="typeof")}var Wo=class{async apply(e){if(!gc(e))return {modified:false,result:e};let t=createConfigItem([Wm,{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],v=u.find((M,F)=>F>g&&!["CommentLine","CommentBlock"].includes(M.type));if(v===void 0)continue;v.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 Bo=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({}),Zo=class extends I{constructor(){super(Gm);}};var Jo=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 Qo=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 Bm=z.strictObject({path:z.string().min(1),destination:z.string().min(1),overwrite:z.boolean().optional()}),Yo=class extends I{constructor(){super(Bm);}};var Zm=z.strictObject({path:z.string().min(1),optional:z.boolean().optional(),result:z.string().min(1)}),ta=class extends I{constructor(){super(Zm);}};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 Jm=z.strictObject({path:z.string().min(1)}),ra=class extends I{constructor(){super(Jm);}};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 Qm=z.strictObject({path:z.string().min(1),content:z.string(),overwrite:z.boolean().optional()}),aa=class extends I{constructor(){super(Qm);}};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:
1843
1843
  \`${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,Bt,Zt,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 Qi(new Sn(new Zi(new gn({fileSystem:this.getFileSystem(),files:[".git"]})))),api:{user:this.getUserApi(),organization:this.getOrganizationApi(),workspace:this.getWorkspaceApi()},form:{organization:new Fn({input:this.getFormInput(),output:this.getOutput(),userApi:this.getUserApi()}),workspace:new jn({input:this.getFormInput(),output:this.getOutput(),organizationApi:this.getOrganizationApi()}),application:new Un({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),slot:new Fe({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 Bt({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 Zt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),form:{slotForm:new Fe({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 Fe({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 Fe({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 Fe({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 Ft({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 Ft({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 Wo,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 Bo({packageManager:this.getPackageManager()}),validator:new Zo}),"add-dependency":new D({action:new Ir({packageManager:this.getPackageManager()}),validator:new Zr}),"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 Jr}),"move-path":new D({action:new Jo({fileSystem:e}),validator:new Yo}),"delete-path":new D({action:new pa({fileSystem:e}),validator:new ca}),"read-file":new D({action:new Qo({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 Qr}),"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 Fe({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 Ur({functions:Qa}),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:Z.transient(()=>({name:this.getPackageManager().getName()})),project:{features:Z.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load(),{features:r}=await this.getWorkspaceApi().getFeatures({organizationSlug:t,workspaceSlug:n})??{};return r??{}}),quotas:Z.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load(),{quotas:r}=await this.getWorkspaceApi().getFeatures({organizationSlug:t,workspaceSlug:n})??{};return r??{}}),organization:Z.transient(async()=>{let{organization:t}=await this.getConfigurationManager().load();return {slug:t,url:e(`organizations/${t}`)}}),workspace:Z.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load();return {slug:n,url:e(`organizations/${t}/workspaces/${n}`)}}),application:Z.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:Z.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:Z.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:Z.transient(async()=>{let t=this.getSdk(),n=await this.getConfigurationManager().load();return t.getPaths(n)}),platform:Z.transient(async()=>await this.getPlatformProvider().get()??"unknown"),server:Z.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 Wn({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 Bi(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 Zn({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 Jn({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 Ze({...r,agent:new $i(t)}),yarn:new Ze({...r,agent:new _i(t)}),bun:new Ze({...r,agent:new Li(t)}),pnpm:new Ze({...r,agent:new Fi(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 Uo({fileSystem:this.getFileSystem(),tsconfigValidator:new Ui}))}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 Ze({projectDirectory:this.workingDirectory,packageValidator:new en,fileSystem:this.getFileSystem(),agent:new Wi});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 _r,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 Ji({fileSystem:this.getFileSystem(),workingDirectory:this.workingDirectory});return async t=>!await e.test(t)})}getUserApi(e=false){return e?new Wt(this.getGraphqlClient(true)):this.share(this.getUserApi,()=>new Wt(this.getGraphqlClient()))}getOrganizationApi(){return this.share(this.getOrganizationApi,()=>new _n(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 _o(this.getGraphqlClient(),new InMemoryCache))}getGraphqlClient(e=false){return e?new Ut({endpoint:this.configuration.adminGraphqlEndpoint,tokenProvider:{getToken:()=>this.getAuthenticator().getToken()}}):this.share(this.getGraphqlClient,()=>{let t=this.getAuthenticator();return new Ut({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:Fo.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(`
1844
1844
  `);return new d(`${e.message}
1845
1845
 
1846
1846
  \u25B6\uFE0F **Trace**
1847
- ${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.10.0"};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 v={},A=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])=>[v[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}v[ce.attributeName()]=S,A.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();
1847
+ ${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.11.0"};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 v={},A=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])=>[v[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}v[ce.attributeName()]=S,A.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();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "croct",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "description": "A command-line interface (CLI) for managing projects using Croct.",
5
5
  "author": {
6
6
  "name": "Croct",
@@ -33,64 +33,64 @@
33
33
  "graphql-codegen": "graphql-codegen --config codegen.ts"
34
34
  },
35
35
  "dependencies": {
36
- "@babel/core": "^7.25.7",
37
- "@babel/generator": "^7.25.9",
38
- "@babel/parser": "^7.25.7",
36
+ "@babel/core": "^7.28.5",
37
+ "@babel/generator": "^7.28.5",
38
+ "@babel/parser": "^7.28.5",
39
39
  "@babel/plugin-syntax-decorators": "^7.27.1",
40
- "@babel/plugin-transform-typescript": "^7.27.1",
41
- "@babel/types": "^7.25.9",
42
- "@croct/cache": "^0.4.2",
43
- "@croct/content": "^1.0.0",
44
- "@croct/content-model": "^0.19.4",
40
+ "@babel/plugin-transform-typescript": "^7.28.5",
41
+ "@babel/types": "^7.28.5",
42
+ "@croct/cache": "^0.5.1",
43
+ "@croct/content": "^1.1.0",
44
+ "@croct/content-model": "^0.21.1",
45
45
  "@croct/json": "^2.1.0",
46
- "@croct/json5-parser": "^0.1.1",
46
+ "@croct/json5-parser": "^0.2.1",
47
47
  "@croct/logging": "^0.2.3",
48
48
  "@croct/md-lite": "^0.3.1",
49
- "@croct/sdk": "^0.18.0",
49
+ "@croct/sdk": "^0.18.2",
50
50
  "@jsep-plugin/object": "^1.2.2",
51
51
  "@jsep-plugin/regex": "^1.0.4",
52
52
  "@jsep-plugin/spread": "^1.0.3",
53
53
  "boxen": "^8.0.1",
54
- "chalk": "^5.3.0",
55
- "ci-info": "^4.1.0",
54
+ "chalk": "^5.6.2",
55
+ "ci-info": "^4.3.1",
56
56
  "cli-cursor": "^5.0.0",
57
57
  "clipboardy": "^4.0.0",
58
58
  "commander": "^12.1.0",
59
- "fast-equals": "^5.1.3",
60
- "ignore": "^7.0.3",
59
+ "fast-equals": "^5.3.2",
60
+ "ignore": "^7.0.5",
61
61
  "ini": "^5.0.0",
62
62
  "is-installed-globally": "^1.0.0",
63
63
  "is-plain-obj": "^4.1.0",
64
64
  "is-unicode-supported": "^2.1.0",
65
65
  "jsep": "^1.4.0",
66
- "minimatch": "^10.0.1",
66
+ "minimatch": "^10.0.3",
67
67
  "node-emoji": "^2.2.0",
68
- "open": "^10.1.0",
68
+ "open": "^10.2.0",
69
69
  "prompts": "^2.4.2",
70
70
  "recast": "^0.23.11",
71
- "semver": "^7.6.3",
71
+ "semver": "^7.7.3",
72
72
  "string-similarity-js": "^2.1.4",
73
- "strip-ansi": "^7.1.0",
73
+ "strip-ansi": "^7.1.2",
74
74
  "terminal-link": "^3.0.0",
75
75
  "xdg-app-paths": "^8.3.0",
76
- "zod": "^3.23.8",
76
+ "zod": "^3.25.76",
77
77
  "@croct/time": "^0.10.2",
78
78
  "@commander-js/extra-typings": "^12.1.0"
79
79
  },
80
80
  "devDependencies": {
81
81
  "@croct/eslint-plugin": "^0.7.1",
82
- "@graphql-codegen/cli": "^5.0.2",
83
- "@swc/jest": "^0.2.36",
82
+ "@graphql-codegen/cli": "^5.0.7",
83
+ "@swc/jest": "^0.2.39",
84
84
  "@types/ini": "^4.1.1",
85
- "@types/jest": "^29.0.0",
85
+ "@types/jest": "^29.5.14",
86
86
  "@types/prompts": "^2.4.9",
87
- "@types/tar-stream": "^3.1.3",
88
- "@typescript-eslint/parser": "^6.0.0",
87
+ "@types/tar-stream": "^3.1.4",
88
+ "@typescript-eslint/parser": "^6.21.0",
89
89
  "esbuild-plugin-file-path-extensions": "^2.1.4",
90
- "eslint": "^8.0.0",
90
+ "eslint": "^8.57.1",
91
91
  "jest": "^29.7.0",
92
- "tsup": "^8.1.0",
93
- "typescript": "^5.6.2"
92
+ "tsup": "^8.5.0",
93
+ "typescript": "^5.9.3"
94
94
  },
95
95
  "files": [
96
96
  "**/*.js",