croct 0.8.6 → 0.8.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/index.js +2 -2
- package/package.json +1 -1
package/index.js
CHANGED
|
@@ -1730,7 +1730,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
|
|
|
1730
1730
|
mutation GenerateTyping($workspaceId: WorkspaceId!, $payload: GenerateTypingPayload!) {
|
|
1731
1731
|
generateTyping(workspaceId: $workspaceId, payload: $payload)
|
|
1732
1732
|
}
|
|
1733
|
-
`);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"}),Dp=yt({NEVER_RECEIVED_TRAFFIC:"NEVER_RECEIVED_TRAFFIC",NOT_RECEIVING_TRAFFIC:"NOT_RECEIVING_TRAFFIC",RECEIVING_TRAFFIC:"RECEIVING_TRAFFIC"}),Hc=yt({PLUG_JS:"PLUG_JS"}),Ea=yt({DRAFT:"DRAFT",ACTIVE:"ACTIVE",SCHEDULED:"SCHEDULED",PAUSED:"PAUSED",ARCHIVED:"ARCHIVED"}),Gc=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(fp,{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,experiments:r.experiment,remainingExperiments:r.remainingExperiments,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(wp,{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(Pp,{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:Dp.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(Cp,{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:Dp.api[r.applicationStatus],...i!==null?{logo:i}:{}}}async getAudiences(e){let{data:t}=await this.client.execute(hp,{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(Sp,{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(Ap,{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(Ep,{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(bp,{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(Ip,{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(vp,{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(Tp,{workspaceId:t.workspaceId,payload:{target:Hc.model[e.target],components:e.components,slots:e.slots}});return n.generateTyping}async getExperiences(e){let{data:t}=await this.client.execute(Op,{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:Gc.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(C=>({id:C.groupId,audiences:C.audiences.map(v=>v.audienceId),content:a.normalizeLocalizedContent(C.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===false}})},{data:{createWorkspaceResources:r}}=await this.client.execute(yp,{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:xp,baseName:`${t} ${n.slice(0,3).toLowerCase()}`,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 _n=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}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}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 Wn=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:"Application name",default:"Website",validator:v=>t.every(O=>O.name.toLowerCase()!==v.toLowerCase()||O.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:"Application website",default:g,validate:v=>URL.canParse(v)?a.isValidUrl(v,c)?true:"Production URL must not be localhost":"Invalid URL"}):g,C=r.notify("Configuring application");try{let v=await n.createApplication({organizationSlug:o.slug,workspaceSlug:s.slug,name:u,website:y,environment:c,platform:p,timeZone:s.timeZone});return C.confirm(a.formatSelection(v)),v}finally{C.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(kp,{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 Un=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:O=>/[A-Z]/.test(O)?/[a-z]/.test(O)?/[^A-Za-z]/.test(O)?O.length<8?"Minimum of 8 characters":O.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 O=>O!==null&&await t.confirm({message:"Open your inbox?",default:true})?O.toString():null);g=n.notify("Waiting for account activation");let C=r.wait(await u);y!==null&&await n.open(y);let v=await C;return g.confirm("Account activated"),v}};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 Zn(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(`
|
|
1733
|
+
`);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"}),Dp=yt({NEVER_RECEIVED_TRAFFIC:"NEVER_RECEIVED_TRAFFIC",NOT_RECEIVING_TRAFFIC:"NOT_RECEIVING_TRAFFIC",RECEIVING_TRAFFIC:"RECEIVING_TRAFFIC"}),Hc=yt({PLUG_JS:"PLUG_JS"}),Ea=yt({DRAFT:"DRAFT",ACTIVE:"ACTIVE",SCHEDULED:"SCHEDULED",PAUSED:"PAUSED",ARCHIVED:"ARCHIVED"}),Gc=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(fp,{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,experiments:r.experiment,remainingExperiments:r.remainingExperiments,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(wp,{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(Pp,{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:Dp.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(Cp,{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:Dp.api[r.applicationStatus],...i!==null?{logo:i}:{}}}async getAudiences(e){let{data:t}=await this.client.execute(hp,{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(Sp,{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(Ap,{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(Ep,{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(bp,{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(Ip,{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(vp,{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(Tp,{workspaceId:t.workspaceId,payload:{target:Hc.model[e.target],components:e.components,slots:e.slots}});return n.generateTyping}async getExperiences(e){let{data:t}=await this.client.execute(Op,{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:Gc.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(C=>({id:C.groupId,audiences:C.audiences.map(v=>v.audienceId),content:a.normalizeLocalizedContent(C.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(yp,{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:xp,baseName:`${t} ${n.slice(0,3).toLowerCase()}`,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 _n=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}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}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 Wn=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:"Application name",default:"Website",validator:v=>t.every(O=>O.name.toLowerCase()!==v.toLowerCase()||O.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:"Application website",default:g,validate:v=>URL.canParse(v)?a.isValidUrl(v,c)?true:"Production URL must not be localhost":"Invalid URL"}):g,C=r.notify("Configuring application");try{let v=await n.createApplication({organizationSlug:o.slug,workspaceSlug:s.slug,name:u,website:y,environment:c,platform:p,timeZone:s.timeZone});return C.confirm(a.formatSelection(v)),v}finally{C.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(kp,{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 Un=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:O=>/[A-Z]/.test(O)?/[a-z]/.test(O)?/[^A-Za-z]/.test(O)?O.length<8?"Minimum of 8 characters":O.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 O=>O!==null&&await t.confirm({message:"Open your inbox?",default:true})?O.toString():null);g=n.notify("Waiting for account activation");let C=r.wait(await u);y!==null&&await n.open(y);let v=await C;return g.confirm("Account activated"),v}};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 Zn(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(`
|
|
1734
1734
|
`),this.wrapElement(c,t,r),f.jsxText(`
|
|
1735
1735
|
`)]:[...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(`
|
|
1736
1736
|
`),e,f.jsxText(`
|
|
@@ -1851,4 +1851,4 @@ ${this.getPreferences(e.protocol).join(`
|
|
|
1851
1851
|
`);return new d(`${e.message}
|
|
1852
1852
|
|
|
1853
1853
|
\u25B6\uFE0F **Trace**
|
|
1854
|
-
${t}`,e.help)}break;case e instanceof Ie:return new d(e.message,{...e.help,suggestions:["Run `init` to create a new configuration."]})}return e}static getSourceLocation(e){return e.url.protocol==="file:"?`${e.url}:${e.start.line}:${e.start.column}`:e.url.hostname==="github.com"?`${e.url}#L${e.start.line}-L${e.end.line}`:`${e.url}#${e.start.line}:${e.start.column}-${e.end.line}:${e.end.column}`}};var es={version:"0.8.
|
|
1854
|
+
${t}`,e.help)}break;case e instanceof Ie:return new d(e.message,{...e.help,suggestions:["Run `init` to create a new configuration."]})}return e}static getSourceLocation(e){return e.url.protocol==="file:"?`${e.url}:${e.start.line}:${e.start.column}`:e.url.hostname==="github.com"?`${e.url}#L${e.start.line}-L${e.end.line}`:`${e.url}#${e.start.line}:${e.start.column}-${e.end.line}:${e.end.column}`}};var es={version:"0.8.7"};function Sc(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(es.version,"-v, --version","Display the version number.").helpOption("-h, --help","Display help for a command.").helpCommand("help [command]","Display help for a command.");e.command("open <url>").description("Open a deep link.").action(async S=>{await a.cli?.open({url:S});});let t=e.command("login").description("Authenticate your user."),n=new Option("-u, --username <username>","The email."),r=new Option("-p, --password <password>","The password.");t.command("credentials",{isDefault:true}).description("Authenticate using credentials.").addOption(a.interactive?n:n.makeOptionMandatory()).addOption(a.interactive?r:r.makeOptionMandatory()).action(async S=>{await a.cli?.login({method:"credentials",username:S.username,password:S.password});}),e.command("logout").description("Logout the current user.").action(async()=>{await a.cli?.logout();}),e.command("admin").argument("[page...]","The name of the page or path to open.").description("Log in and open the admin panel.").action(async S=>{await a.cli?.admin({page:S!==void 0?S.join(" "):a.interactive?void 0:"/"});});let i=new Option("--wor <workspace-slug>","The workspace slug."),o=new Option("--org <organization-slug>","The organization slug."),s=new Option("--dev-app <application-slug>","The development application slug."),p=new Option("--prod-app <application-slug>","The production application slug.");e.command("init").description("Configure the project.").option("-o, --override","Override any existing configuration.").addOption(new Option("-n, --new <resource>","The resources to create.").choices(["organization","org","workspace","wor","application","app"])).addOption(new Option("-s, --sdk <platform>","The SDK to use.").choices(["javascript","react","next"])).addOption(new Option("--skip-api-key-setup","Opt-out of API key setup.").default(false).env("CROCT_SKIP_API_KEY_SETUP")).addOption(a.interactive?o:o.makeOptionMandatory()).addOption(a.interactive?i:i.makeOptionMandatory()).addOption(a.interactive?s:s.makeOptionMandatory()).addOption(p).action(async S=>{await a.cli?.init({override:S.override,new:(()=>{switch(S.new){case "organization":case "org":return "organization";case "workspace":case "wor":return "workspace";case "application":case "app":return "application";default:return}})(),sdk:S.sdk,organization:S.org,workspace:S.wor,devApplication:S.devApp,prodApplication:S.prodApp,skipApiKeySetup:S.skipApiKeySetup});}),e.command("install").description("Install content and types.").action(async()=>{await a.cli?.install({});}),e.command("update").description("Update content and types.").action(async()=>{await a.cli?.install({clean:true});}),e.command("upgrade").description("Upgrade components and slots to the latest version.").option("-s, --slots <slots...>","The slots to upgrade.").option("-c, --components <components...>","The components to upgrade.").action(async S=>{await a.cli?.upgrade({slots:S.slots??(S.components!==void 0?[]:void 0),components:S.components??(S.slots!==void 0?[]:void 0)});});let c=e.command("add").description("Add a resource to your project.");c.command("slot").description("Add a slot to your project.").argument(a.interactive?"[slots...]":"<slots...>").option("-e, --example","Generate an implementation example.").action(async(S,P)=>{await a.cli?.addSlot({slots:S,example:P.example});}),c.command("component").description("Add a component to your project.").argument(a.interactive?"[components...]":"<components...>").action(async S=>{await a.cli?.addComponent({components:S});});let l=e.command("remove").description("Remove a resource from your project.");l.command("slot").description("Remove a slot from your project.").argument(a.interactive?"[slots...]":"<slots...>").action(async S=>{await a.cli?.removeSlot({slots:S});}),l.command("component").description("Remove a component from your project.").argument(a.interactive?"[components...]":"<components...>").action(async S=>{await a.cli?.removeComponent({components:S});});let u=e.command("create").description("Create a resource in your project.");u.command("template").description("Create a template from your project.").addArgument(new Argument("<path>","The path to the file.").argOptional()).option("-e, --empty","Create an empty template.").action(async(S,P)=>{await a.cli?.createTemplate({file:S,empty:P.empty});});let g=new Option("--permissions <permissions...>","The permissions of the API key.").argParser(S=>S.split(",").map(P=>{try{return ae.fromValue(P)}catch{throw new InvalidOptionArgumentError(`Unknown permission "${P}".`)}})),y=new Option("--env <environment>","The environment of the API key.").choices(["prod","dev"]).argParser(S=>S==="prod"?"PRODUCTION":"DEVELOPMENT");u.command("api-key").description("Create an API key.").option("--name <name>","The name of the API key.").addOption(a.interactive?g:g.makeOptionMandatory()).addOption(a.interactive?y:y.makeOptionMandatory()).option("-c, --copy","Copy the API key to the clipboard.").action(async S=>{await a.cli?.createApiKey({name:S.name,permissions:S.permissions,environment:S.env,copy:S.copy});});let C={},v=e.command("use").description("Use a template.").argument("template","The path to the template.").passThroughOptions(a.cli===void 0).allowUnknownOption(a.cli===void 0||a.template===null).action(async(S,P)=>{await a.cli?.useTemplate({template:S,options:Object.fromEntries(Object.entries(P).map(([H,ce])=>[C[H],ce]))});});for(let[S,P]of Object.entries(a.template??{})){let H=`--${S}${P.type!=="boolean"?" <value>":""}`,ce=new Option(H,P.description).makeOptionMandatory(P.required===true);switch(P.type){case "string":P.choices!==void 0&&P.choices.length>0&&ce.choices(P.choices);break;case "number":ce.argParser(V=>{let ie=Number.parseFloat(V);if(Number.isNaN(ie))throw new InvalidOptionArgumentError("The value must be a number.");return ie});break;case "array":ce.argParser(V=>{let ie;try{ie=JSON.parse(V);}catch{}if(ie===void 0||!Array.isArray(ie))throw new InvalidOptionArgumentError("The value must be a JSON array.");return ie});break;case "object":ce.argParser(V=>{let ie;try{ie=JSON.parse(V);}catch{throw new InvalidOptionArgumentError("The JSON is malformed.")}if(typeof ie!="object"||ie===null)throw new InvalidOptionArgumentError("The value must be a JSON object.")});break}C[ce.attributeName()]=S,v.addOption(ce);}return e.command("enable").description("Enable a feature.").command("deep-link").description("Enable deep link support.").action(async()=>{await a.cli?.deepLink({operation:"enable"});}),e.command("disable").description("Disable a feature.").command("deep-link").description("Disable deep link support.").action(async()=>{await a.cli?.deepLink({operation:"disable"});}),e}function gd(a){let e=["use","help use"];for(let t of e){let n=t.split(" ").length;if(a.length>n&&a.slice(0,n).join(" ")===t&&(a[n]??"")!=="")return a[n]}return null}function fd(a){return a.length>=2&&["enable","disable"].includes(a[0])&&a[1]==="deep-link"}async function ts(a=process.argv,e=true){let t=Sc({interactive:true}).parse(a),n=t.opts(),r=fa.fromDefaults({program:p=>ts(t.args.slice(0,2).concat(p)),version:es.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=Sc({cli:r,interactive:n.interaction,template:o});e&&await r.welcome({skipDeepLinkCheck:fd(t.args)}),await s.parseAsync(a);}ts();
|