croct 0.1.0-alpha2 → 0.1.0-alpha3

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 +142 -141
  2. package/package.json +5 -5
package/index.js CHANGED
@@ -1,24 +1,25 @@
1
1
  #!/usr/bin/env node
2
- 'use strict';var fs$1=require('fs'),apiKey=require('@croct/sdk/apiKey'),cache=require('@croct/cache'),tl=require('open'),os$1=require('os'),kd=require('xdg-app-paths'),Ad=require('ci-info'),logging=require('@croct/logging'),Dl=require('prompts'),stream=require('stream'),Ya=require('cli-cursor'),ct=require('chalk'),Vs=require('readline'),tty=require('tty'),Ml=require('is-unicode-supported'),rendering=require('@croct/md-lite/rendering'),$l=require('terminal-link'),parsing=require('@croct/md-lite/parsing'),nodeEmoji=require('node-emoji'),json5Parser=require('@croct/json5-parser'),g=require('@babel/types'),yt=require('@babel/traverse'),parser=require('@babel/parser'),crypto=require('crypto'),zr=require('recast'),babelTs=require('recast/parsers/babel-ts'),cu=require('string-similarity-js'),promises=require('fs/promises'),path=require('path'),minimatch=require('minimatch'),fastEquals=require('fast-equals'),Iu=require('tar-stream'),xu=require('gunzip-maybe'),zod=require('zod'),Ze=require('jsep'),Ru=require('@jsep-plugin/object'),Tu=require('@jsep-plugin/spread'),Dc=require('is-plain-obj'),Qm=require('strip-ansi'),Gc=require('semver'),nodePty=require('node-pty'),child_process=require('child_process'),id=require('ignore'),ud=require('clipboardy'),token=require('@croct/sdk/token'),Yc=require('boxen'),Ve=require('process'),async_hooks=require('async_hooks');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}function _interopNamespace(e){if(e&&e.__esModule)return e;var n=Object.create(null);if(e){Object.keys(e).forEach(function(k){if(k!=='default'){var d=Object.getOwnPropertyDescriptor(e,k);Object.defineProperty(n,k,d.get?d:{enumerable:true,get:function(){return e[k]}});}})}n.default=e;return Object.freeze(n)}var tl__default=/*#__PURE__*/_interopDefault(tl);var kd__default=/*#__PURE__*/_interopDefault(kd);var Ad__default=/*#__PURE__*/_interopDefault(Ad);var Dl__default=/*#__PURE__*/_interopDefault(Dl);var Ya__default=/*#__PURE__*/_interopDefault(Ya);var ct__default=/*#__PURE__*/_interopDefault(ct);var Vs__default=/*#__PURE__*/_interopDefault(Vs);var Ml__default=/*#__PURE__*/_interopDefault(Ml);var $l__default=/*#__PURE__*/_interopDefault($l);var g__namespace=/*#__PURE__*/_interopNamespace(g);var yt__default=/*#__PURE__*/_interopDefault(yt);var zr__namespace=/*#__PURE__*/_interopNamespace(zr);var cu__default=/*#__PURE__*/_interopDefault(cu);var Iu__default=/*#__PURE__*/_interopDefault(Iu);var xu__default=/*#__PURE__*/_interopDefault(xu);var Ze__default=/*#__PURE__*/_interopDefault(Ze);var Ru__default=/*#__PURE__*/_interopDefault(Ru);var Tu__default=/*#__PURE__*/_interopDefault(Tu);var Dc__default=/*#__PURE__*/_interopDefault(Dc);var Qm__default=/*#__PURE__*/_interopDefault(Qm);var Gc__default=/*#__PURE__*/_interopDefault(Gc);var id__default=/*#__PURE__*/_interopDefault(id);var ud__default=/*#__PURE__*/_interopDefault(ud);var Yc__default=/*#__PURE__*/_interopDefault(Yc);var Ve__default=/*#__PURE__*/_interopDefault(Ve);var ol=Object.create;var qa=Object.defineProperty;var al=Object.getOwnPropertyDescriptor;var sl=Object.getOwnPropertyNames;var pl=Object.getPrototypeOf,cl=Object.prototype.hasOwnProperty;var Rs=o=>{throw TypeError(o)};var ll=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var ve=(o,e)=>()=>(e||o((e={exports:{}}).exports,e),e.exports),ul=(o,e)=>{for(var t in e)qa(o,t,{get:e[t],enumerable:true});},ml=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of sl(e))!cl.call(o,r)&&r!==t&&qa(o,r,{get:()=>e[r],enumerable:!(n=al(e,r))||n.enumerable});return o};var vt=(o,e,t)=>(t=o!=null?ol(pl(o)):{},ml(e||!o||!o.__esModule?qa(t,"default",{value:o,enumerable:true}):t,o));var Ts=(o,e,t)=>e.has(o)||Rs("Cannot "+t);var en=(o,e,t)=>(Ts(o,e,"read from private field"),t?t.call(o):e.get(o)),Jn=(o,e,t)=>e.has(o)?Rs("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(o):e.set(o,t),Bn=(o,e,t,n)=>(Ts(o,e,"write to private field"),e.set(o,t),t);var Ds=ve((de,Os)=>{var Te=ll("commander");de=Os.exports={};de.program=new Te.Command;de.Argument=Te.Argument;de.Command=Te.Command;de.CommanderError=Te.CommanderError;de.Help=Te.Help;de.InvalidArgumentError=Te.InvalidArgumentError;de.InvalidOptionArgumentError=Te.InvalidArgumentError;de.Option=Te.Option;de.createCommand=o=>new Te.Command(o);de.createOption=(o,e)=>new Te.Option(o,e);de.createArgument=(o,e)=>new Te.Argument(o,e);});var Ha=ve(Yn=>{Object.defineProperty(Yn,"__esModule",{value:true});Yn.TimeZone=void 0;var tn=class o{constructor(e){this.id=e;}static getTimesZoneIds(){return o.SUPPORTED_TIMEZONE_IDS===void 0&&(o.SUPPORTED_TIMEZONE_IDS=new Set(["UTC","CET","CST6CDT","EET","EST","EST5EDT","Etc/GMT+1","Etc/GMT+10","Etc/GMT+11","Etc/GMT+12","Etc/GMT+2","Etc/GMT+3","Etc/GMT+4","Etc/GMT+5","Etc/GMT+6","Etc/GMT+7","Etc/GMT+8","Etc/GMT+9","Etc/GMT-1","Etc/GMT-10","Etc/GMT-11","Etc/GMT-12","Etc/GMT-13","Etc/GMT-14","Etc/GMT-2","Etc/GMT-3","Etc/GMT-4","Etc/GMT-5","Etc/GMT-6","Etc/GMT-7","Etc/GMT-8","Etc/GMT-9","HST","MET","MST","MST7MDT","PST8PDT","WET",...Intl.supportedValuesOf("timeZone")])),o.SUPPORTED_TIMEZONE_IDS}static of(e){if(!o.getTimesZoneIds().has(e))throw new Error(`The timezone ${e} is not supported.`);return new o(e)}getId(){return this.id}toString(){return this.id}equals(e){return this.id===e.id}toJSON(){return this.toString()}};Yn.TimeZone=tn;tn.UTC=new tn("UTC");});var Ga=ve(Xn=>{var Ka;Object.defineProperty(Xn,"__esModule",{value:true});Xn.SystemClock=void 0;var dl=rn(),gl=Ha(),nn=class{constructor(e){this.zone=e;}static of(e){return new this(e)}getZone(){return this.zone}getInstant(){return dl.Instant.ofEpochMilli(Date.now())}equals(e){return e===this||e instanceof Ka&&e.zone.equals(this.zone)}};Xn.SystemClock=nn;Ka=nn;nn.UTC=new Ka(gl.TimeZone.UTC);});var Za=ve(er=>{Object.defineProperty(er,"__esModule",{value:true});er.DefaultClockProvider=void 0;var fl=Ga(),zs;(function(o){let e=null;function t(){return e===null&&(e=fl.SystemClock.UTC),e}o.getClock=t;function n(r){e=r;}o.setClock=n;})(zs||(er.DefaultClockProvider=zs={}));});var on=ve(le=>{Object.defineProperty(le,"__esModule",{value:true});le.intDiv=le.multiplyExact=le.subtractExact=le.addExact=le.floorMod=le.floorDiv=void 0;function _s(o,e){let t=Math.trunc(o/e);return Math.sign(o)!==Math.sign(e)&&t*e!==o&&t--,t}le.floorDiv=_s;function yl(o,e){return o-_s(o,e)*e}le.floorMod=yl;function hl(o,e){let t=o+e;if(!Number.isSafeInteger(t))throw new Error("The result overflows the range of safe integers.");return t}le.addExact=hl;function Sl(o,e){let t=o-e;if(!Number.isSafeInteger(t))throw new Error("The result overflows the range of safe integers.");return t}le.subtractExact=Sl;function bl(o,e){let t=o*e;if(!Number.isSafeInteger(t))throw new Error("The result overflows the range of safe integers.");return t}le.multiplyExact=bl;function Il(o,e){let t=Math.trunc(o/e);if(!Number.isSafeInteger(t))throw new Error("The result overflows the range of safe integers.");return t}le.intDiv=Il;});var nr=ve(tr=>{Object.defineProperty(tr,"__esModule",{value:true});tr.LocalDate=void 0;var V=on(),ue=class o{constructor(e,t,n){this.year=e,this.month=t,this.day=n;}static of(e,t,n){if(!Number.isSafeInteger(e)||e<o.MIN_YEAR||e>o.MAX_YEAR)throw new Error(`Year must be a safe integer between ${o.MIN_YEAR} and ${o.MAX_YEAR}.`);if(!Number.isInteger(t)||t<1||t>12)throw new Error("Month must be an integer between 1 and 12.");let r=o.getMonthLength(t,o.isLeapYear(e));if(!Number.isInteger(n)||n<1||n>r)throw new Error(`Day must be an integer between 1 and ${r}.`);return new o(e,t,n)}static ofEpochDay(e){if(e<o.MIN_EPOCH_DAY||e>o.MAX_EPOCH_DAY)throw new Error(`The day ${e} is out of the range [${o.MIN_EPOCH_DAY} - ${o.MAX_EPOCH_DAY}].`);let t=(0, V.addExact)(e,719468),n=(0, V.floorDiv)(t,146097),r=(0, V.floorMod)(t,146097),i=(0, V.intDiv)(r,1460);i-=(0, V.intDiv)(r,36524),i+=(0, V.intDiv)(r,146096);let a=(0, V.intDiv)(r-i,365),s=a+n*400,p=365*a+(0, V.intDiv)(a,4)-(0, V.intDiv)(a,100),c=r-p,l=(0, V.intDiv)(c*5+2,153);s+=(0, V.intDiv)(l,10);let m=c-(0, V.intDiv)(l*306+5,10)+1;return l=(l+2)%12+1,o.of(s,l,m)}static fromNative(e){return o.of(e.getFullYear(),e.getMonth()+1,e.getDate())}static parse(e){let{groups:t}=e.match(o.PATTERN)??{};if(t===void 0)throw new Error(`Invalid ISO-8601 date string: ${e}`);let n=Number.parseInt(t.year,10),r=Number.parseInt(t.month,10),i=Number.parseInt(t.day,10);return o.of(n,r,i)}getYear(){return this.year}getMonth(){return this.month}getDay(){return this.day}equals(e){return this===e?true:this.year===e.year&&this.month===e.month&&this.day===e.day}plusYears(e){if(e===0)return this;let t=(0, V.addExact)(this.year,e);return o.resolvePreviousValid(t,this.month,this.day)}minusYears(e){return this.plusYears(-e)}plusMonths(e){if(e===0)return this;let t=this.year+(0, V.intDiv)(e,12),n=this.month+e%12,r=t+(0, V.floorDiv)(n-1,12),i=(0, V.floorMod)(n-1,12)+1;return o.resolvePreviousValid(r,i,this.day)}minusMonths(e){return this.plusMonths(-e)}plusWeeks(e){return e===0?this:this.plusDays((0, V.multiplyExact)(e,7))}minusWeeks(e){return this.plusWeeks(-e)}plusDays(e){if(e===0)return this;let t=this.day+e;if(t>0){if(t<=28)return o.of(this.year,this.month,t);if(t<=59){let n=o.getMonthLength(this.month,o.isLeapYear(this.year));return t<=n?o.of(this.year,this.month,t):this.month<12?o.of(this.year,this.month+1,t-n):o.of(this.year+1,1,t-n)}}return o.ofEpochDay((0, V.addExact)(this.toEpochDay(),e))}minusDays(e){return this.plusDays(-e)}isAfter(e){return this.compare(e)>0}isAfterOrEqual(e){return this.compare(e)>=0}isBefore(e){return this.compare(e)<0}isBeforeOrEqual(e){return this.compare(e)<=0}static isValid(e){try{o.parse(e);}catch{return false}return true}compare(e){return this.year!==e.year?this.year-e.year:this.month!==e.month?this.month-e.month:this.day-e.day}toEpochDay(){let{year:e}=this;this.month<=2&&e--;let t=(0, V.floorDiv)(e,400),n=(this.month+9)%12,r=(0, V.intDiv)(153*n+2,5)+this.day-1,i=e-t*400;return 365*i+(0, V.intDiv)(i,4)-(0, V.intDiv)(i,100)+r+t*146097-719468}toString(){let e=`${this.month}`.padStart(2,"0"),t=`${this.day}`.padStart(2,"0");return `${this.year}-${e}-${t}`}static resolvePreviousValid(e,t,n){let r=o.getMonthLength(t,o.isLeapYear(e));return o.of(e,t,Math.min(n,r))}static isLeapYear(e){return e%4===0&&(e%100!==0||e%400===0)}static getMonthLength(e,t){switch(e){case 2:return t?29:28;case 4:case 6:case 9:case 11:return 30;default:return 31}}toJSON(){return this.toString()}};tr.LocalDate=ue;ue.PATTERN=/^(?<year>[+-]?\d{4,19})-(?<month>\d{2})-(?<day>\d{2})$/;ue.MIN_EPOCH_DAY=-365961662;ue.MAX_EPOCH_DAY=364522971;ue.MIN_YEAR=-999999;ue.MAX_YEAR=999999;ue.MIN=new ue(ue.MIN_YEAR,1,1);ue.MAX=new ue(ue.MAX_YEAR,12,31);});var ir=ve(rr=>{Object.defineProperty(rr,"__esModule",{value:true});rr.LocalTime=void 0;var $e=on(),H=class o{constructor(e,t,n,r){this.hour=e,this.minute=t,this.second=n,this.nanos=r;}static of(e,t=0,n=0,r=0){if(!Number.isInteger(e)||e<0||e>23)throw new Error("Hour must be an integer between 0 and 23.");if(!Number.isInteger(t)||t<0||t>59)throw new Error("Minute must be an integer between 0 and 59.");if(!Number.isInteger(n)||n<0||n>59)throw new Error("Second must be an integer between 0 and 59.");if(!Number.isInteger(r)||r<0||r>999999999)throw new Error("Nanosecond of second must be an integer between 0 and 999999999.");return new o(e,t,n,r)}static ofSecondOfDay(e,t=0){if(e<0||e>o.SECONDS_PER_DAY-1)throw new Error(`The second value ${e} is out of the range [0 - ${o.SECONDS_PER_DAY-1}] of local time.`);if(t<0||t>o.NANOS_PER_SECOND-1)throw new Error(`The nanosecond value ${t} is out of the range [0 - ${o.NANOS_PER_SECOND-1}] of local time.`);let n=e,r=(0, $e.intDiv)(n,o.SECONDS_PER_HOUR);n-=r*o.SECONDS_PER_HOUR;let i=(0, $e.intDiv)(n,o.SECONDS_PER_MINUTE);return n-=i*o.SECONDS_PER_MINUTE,o.of(r,i,n,t)}static fromNative(e){return new o(e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()*o.NANOS_PER_MILLI)}static startOfDay(){return new o(0,0,0,0)}static endOfDay(){return new o(23,59,59,999999999)}static parse(e){let{groups:t}=e.match(o.PATTERN)??{};if(t===void 0)throw new Error(`Invalid ISO-8601 time string: ${e}`);let n=Number.parseInt(t.hour,10),r=Number.parseInt(t.minute,10),i=Number.parseInt(t.second??"0",10),a=Number.parseInt(t.fraction?.padEnd(9,"0")??"0",10);return o.of(n,r,i,a)}getHour(){return this.hour}getMinute(){return this.minute}getSecond(){return this.second}getNano(){return this.nanos}toMinuteOfDay(){return this.hour*o.MINUTES_PER_HOUR+this.minute}toSecondOfDay(){return this.toMinuteOfDay()*o.SECONDS_PER_MINUTE+this.second}toMilliOfDay(){return (0, $e.intDiv)(this.toNanoOfDay(),o.NANOS_PER_MILLI)}toMicroOfDay(){return (0, $e.intDiv)(this.toNanoOfDay(),o.NANOS_PER_MICRO)}toNanoOfDay(){return this.toSecondOfDay()*o.NANOS_PER_SECOND+this.nanos}plusHours(e){if(e===0)return this;let n=(e%o.HOURS_PER_DAY+this.hour+o.HOURS_PER_DAY)%o.HOURS_PER_DAY;return new o(n,this.minute,this.second,this.nanos)}minusHours(e){return this.plusHours(-e)}plusMinutes(e){if(e===0)return this;let t=e%o.MINUTES_PER_DAY,n=this.toMinuteOfDay(),r=(t+n+o.MINUTES_PER_DAY)%o.MINUTES_PER_DAY;if(n===r)return this;let i=(0, $e.intDiv)(r,o.MINUTES_PER_HOUR),a=r%o.MINUTES_PER_HOUR;return new o(i,a,this.second,this.nanos)}minusMinutes(e){return this.plusMinutes(-e)}plusSeconds(e){if(e===0)return this;let t=e%o.SECONDS_PER_DAY,n=this.toSecondOfDay(),r=(t+n+o.SECONDS_PER_DAY)%o.SECONDS_PER_DAY;if(n===r)return this;let i=(0, $e.intDiv)(r,o.SECONDS_PER_HOUR),a=(0, $e.intDiv)(r,o.SECONDS_PER_MINUTE)%o.MINUTES_PER_HOUR,s=r%o.SECONDS_PER_MINUTE;return o.of(i,a,s,this.nanos)}minusSeconds(e){return this.plusSeconds(-e)}plusMillis(e){return e===0?this:this.plusNanos(e%o.MILLIS_PER_DAY*o.NANOS_PER_MILLI)}minusMillis(e){return this.plusMillis(-e)}plusMicros(e){return e===0?this:this.plusNanos(e%o.MICROS_PER_DAY*o.NANOS_PER_MICRO)}minusMicros(e){return this.plusMicros(-e)}plusNanos(e){if(e===0)return this;let t=e%o.NANOS_PER_DAY,n=this.toNanoOfDay(),r=(t+n+o.NANOS_PER_DAY)%o.NANOS_PER_DAY;if(n===r)return this;let i=(0, $e.intDiv)(r,o.NANOS_PER_HOUR),a=(0, $e.intDiv)(r,o.NANOS_PER_MINUTE)%o.MINUTES_PER_HOUR,s=(0, $e.intDiv)(r,o.NANOS_PER_SECOND)%o.SECONDS_PER_MINUTE,p=r%o.NANOS_PER_SECOND;return o.of(i,a,s,p)}minusNanos(e){return this.plusNanos(-e)}equals(e){return this===e?true:this.hour===e.hour&&this.minute===e.minute&&this.second===e.second&&this.nanos===e.nanos}isAfter(e){return this.compare(e)>0}isAfterOrEqual(e){return this.compare(e)>=0}isBefore(e){return this.compare(e)<0}isBeforeOrEqual(e){return this.compare(e)<=0}static isValid(e){try{o.parse(e);}catch{return false}return true}compare(e){return this.hour!==e.hour?this.hour-e.hour:this.minute!==e.minute?this.minute-e.minute:this.second!==e.second?this.second-e.second:this.nanos-e.nanos}toString(){let e=`${this.hour}`.padStart(2,"0"),t=`${this.minute}`.padStart(2,"0"),n=`${e}:${t}`;if(this.second===0&&this.nanos===0)return n;let r=`${this.second}`.padStart(2,"0");if(n+=`:${r}`,this.nanos>0){let i=`${this.nanos}`.padStart(9,"0").replace(/0+$/,""),a=Math.floor((i.length+2)/3)*3;n+=`.${i.padEnd(a,"0")}`;}return n}toJSON(){return this.toString()}};rr.LocalTime=H;H.PATTERN=/^(?<hour>\d{2}):(?<minute>\d{2})(?::(?<second>\d{2})(?:.(?<fraction>\d{1,9}))?)?$/;H.HOURS_PER_DAY=24;H.MINUTES_PER_DAY=1440;H.MINUTES_PER_HOUR=60;H.SECONDS_PER_DAY=86400;H.SECONDS_PER_HOUR=3600;H.SECONDS_PER_MINUTE=60;H.MICROS_PER_DAY=864e8;H.MICROS_PER_SECOND=1e6;H.MILLIS_PER_DAY=864e5;H.MILLIS_PER_SECOND=1e3;H.NANOS_PER_DAY=864e11;H.NANOS_PER_HOUR=36e11;H.NANOS_PER_MINUTE=6e10;H.NANOS_PER_SECOND=1e9;H.NANOS_PER_MILLI=1e6;H.NANOS_PER_MICRO=1e3;});var Ja=ve(ar=>{Object.defineProperty(ar,"__esModule",{value:true});ar.LocalDateTime=void 0;var Ls=Za(),xl=rn(),or=nr(),k=ir(),K=on(),Qa=class o{constructor(e,t){this.date=e,this.time=t;}static nowIn(e,t=Ls.DefaultClockProvider.getClock()){return o.ofInstant(t.getInstant(),e)}static now(e=Ls.DefaultClockProvider.getClock()){return o.ofInstant(e.getInstant(),e.getZone())}static ofInstant(e,t){return o.fromZonedDate(e.toDate(),t)}static fromZonedDate(e,t){let i=e.toLocaleString("sv-SE",{timeZone:t.getId(),calendar:e.getUTCFullYear()<200?"gregory":"iso8601",hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3}).match(/(?<year>\d{1,4})-(?<month>\d{2})-(?<day>\d{2}) (?<hour>\d{2}):(?<minute>\d{2}):(?<second>\d{2}),(?<fraction>\d{3})/)?.groups;return o.of(or.LocalDate.of(Number.parseInt(i.year,10),Number.parseInt(i.month,10),Number.parseInt(i.day,10)),k.LocalTime.of(Number.parseInt(i.hour,10),Number.parseInt(i.minute,10),Number.parseInt(i.second,10),Number.parseInt(i.fraction.padEnd(9,"0"),10)))}static ofEpochSecond(e,t=0){if(!Number.isSafeInteger(e)||!Number.isSafeInteger(t))throw new Error("The timestamp must be a safe integer.");let n=(0, K.floorDiv)(e,k.LocalTime.SECONDS_PER_DAY),r=(0, K.floorMod)(e,k.LocalTime.SECONDS_PER_DAY),i=or.LocalDate.ofEpochDay(n),a=k.LocalTime.ofSecondOfDay(r,t);return o.of(i,a)}static fromNative(e){return o.of(or.LocalDate.fromNative(e),k.LocalTime.fromNative(e))}static of(e,t){return new o(e,t??k.LocalTime.startOfDay())}static parse(e){let t=e.split("T");if(t.length!==2)throw new Error(`Malformed local date-time "${e}".`);return o.of(or.LocalDate.parse(t[0]),k.LocalTime.parse(t[1]))}getLocalDate(){return this.date}getLocalTime(){return this.time}getDay(){return this.date.getDay()}getMonth(){return this.date.getMonth()}getYear(){return this.date.getYear()}getHour(){return this.time.getHour()}getMinute(){return this.time.getMinute()}getSecond(){return this.time.getSecond()}getNano(){return this.time.getNano()}plusYears(e){return o.of(this.date.plusYears(e),this.time)}minusYears(e){return this.plusYears(-e)}plusMonths(e){return o.of(this.date.plusMonths(e),this.time)}minusMonths(e){return this.plusMonths(-e)}plusWeeks(e){return o.of(this.date.plusWeeks(e),this.time)}minusWeeks(e){return this.plusWeeks(-e)}plusDays(e){return o.of(this.date.plusDays(e),this.time)}minusDays(e){return this.plusDays(-e)}plusHours(e){if(e===0)return this;let t=(0, K.intDiv)(e,k.LocalTime.HOURS_PER_DAY),n=e%k.LocalTime.HOURS_PER_DAY,r=n*k.LocalTime.NANOS_PER_HOUR+this.time.toNanoOfDay(),i=t+(0, K.floorDiv)(r,k.LocalTime.NANOS_PER_DAY);return o.of(this.date.plusDays(i),this.time.plusHours(n))}minusHours(e){return this.plusHours(-e)}plusMinutes(e){if(e===0)return this;let t=(0, K.intDiv)(e,k.LocalTime.MINUTES_PER_DAY),n=e%k.LocalTime.MINUTES_PER_DAY,r=n*k.LocalTime.NANOS_PER_MINUTE+this.time.toNanoOfDay(),i=t+(0, K.floorDiv)(r,k.LocalTime.NANOS_PER_DAY);return o.of(this.date.plusDays(i),this.time.plusMinutes(n))}minusMinutes(e){return this.plusMinutes(-e)}plusSeconds(e){if(e===0)return this;let t=(0, K.intDiv)(e,k.LocalTime.SECONDS_PER_DAY),n=e%k.LocalTime.SECONDS_PER_DAY,r=n*k.LocalTime.NANOS_PER_SECOND+this.time.toNanoOfDay(),i=t+(0, K.floorDiv)(r,k.LocalTime.NANOS_PER_DAY);return o.of(this.date.plusDays(i),this.time.plusSeconds(n))}minusSeconds(e){return this.plusSeconds(-e)}plusMillis(e){if(e===0)return this;let t=(0, K.intDiv)(e,k.LocalTime.MILLIS_PER_DAY),n=e%k.LocalTime.MILLIS_PER_DAY,r=n*k.LocalTime.NANOS_PER_MILLI+this.time.toNanoOfDay(),i=t+(0, K.floorDiv)(r,k.LocalTime.NANOS_PER_DAY);return o.of(this.date.plusDays(i),this.time.plusMillis(n))}minusMillis(e){return this.plusMillis(-e)}plusMicros(e){if(e===0)return this;let t=(0, K.intDiv)(e,k.LocalTime.MICROS_PER_DAY),n=e%k.LocalTime.MICROS_PER_DAY,r=n*k.LocalTime.NANOS_PER_MICRO+this.time.toNanoOfDay(),i=t+(0, K.floorDiv)(r,k.LocalTime.NANOS_PER_DAY);return o.of(this.date.plusDays(i),this.time.plusMicros(n))}minusMicros(e){return this.plusMicros(-e)}plusNanos(e){if(e===0)return this;let t=(0, K.intDiv)(e,k.LocalTime.NANOS_PER_DAY),n=e%k.LocalTime.NANOS_PER_DAY,r=n+this.time.toNanoOfDay(),i=t+(0, K.floorDiv)(r,k.LocalTime.NANOS_PER_DAY);return o.of(this.date.plusDays(i),this.time.plusNanos(n))}minusNanos(e){return this.plusNanos(-e)}equals(e){return this===e?true:this.date.equals(e.date)&&this.time.equals(e.time)}isAfter(e){return this.compare(e)>0}isAfterOrEqual(e){return this.compare(e)>=0}isBefore(e){return this.compare(e)<0}isBeforeOrEqual(e){return this.compare(e)<=0}static isValid(e){try{o.parse(e);}catch{return false}return true}compare(e){let t=this.date.compare(e.date);return t!==0?t:this.time.compare(e.time)}toInstant(e){let t=this.date.toEpochDay(),n=(0, K.multiplyExact)(t,k.LocalTime.SECONDS_PER_DAY),r=(0, K.subtractExact)((0, K.addExact)(n,this.time.toSecondOfDay()),14*k.LocalTime.SECONDS_PER_HOUR),i=(0, K.addExact)(r,26*k.LocalTime.SECONDS_PER_HOUR),a=o.of(this.date,k.LocalTime.of(this.time.getHour(),this.time.getMinute(),this.time.getSecond())),s=new Date(r*k.LocalTime.MILLIS_PER_SECOND),p=o.fromZonedDate(s,e),c=Math.min(o.getTimeZoneMultiple(s,e.getId()),o.getTimeZoneMultiple(new Date(i*k.LocalTime.MILLIS_PER_SECOND),e.getId()));for(;!p.equals(a)&&(s.setTime((0, K.addExact)(s.getTime(),c*k.LocalTime.MILLIS_PER_SECOND)),p=o.fromZonedDate(s,e),!p.isAfter(a)););let l=(0, K.intDiv)(s.getTime(),k.LocalTime.MILLIS_PER_SECOND),m=this.time.getNano();return xl.Instant.ofEpochSecond(l,m)}static getTimeZoneMultiple(e,t){let n=Math.abs(o.getTimeZoneOffset(e,t));return n%k.LocalTime.SECONDS_PER_HOUR===0?k.LocalTime.SECONDS_PER_HOUR:n%(k.LocalTime.SECONDS_PER_HOUR/2)===0?k.LocalTime.SECONDS_PER_HOUR/2:k.LocalTime.SECONDS_PER_HOUR/4}static getTimeZoneOffset(e,t){let r=new Intl.DateTimeFormat("sv-SE",{timeZone:t,calendar:"iso8601",timeZoneName:"short"}).format(e).match(/GMT([+-]\d+)(?::(\d+))?/),i=Number.parseInt(r?.[1]??"0",10),a=Number.parseInt(r?.[2]??"0",10);return i*k.LocalTime.SECONDS_PER_HOUR+a*k.LocalTime.SECONDS_PER_MINUTE}toString(){return `${this.date.toString()}T${this.time.toString()}`}toJSON(){return this.toString()}};ar.LocalDateTime=Qa;});var rn=ve(sr=>{Object.defineProperty(sr,"__esModule",{value:true});sr.Instant=void 0;var vl=Za(),wl=nr(),Cl=Ja(),F=ir(),z=on(),me=class o{constructor(e,t){this.nanos=0,this.seconds=e,this.nanos=t;}static now(e=vl.DefaultClockProvider.getClock()){return e.getInstant()}static fromDate(e){return o.ofEpochMilli(e.getTime())}static ofEpochMilli(e){if(!Number.isSafeInteger(e))throw new Error("The timestamp must be a safe integer.");let t=(0, z.floorDiv)(e,F.LocalTime.MILLIS_PER_SECOND),r=(0, z.floorMod)(e,F.LocalTime.MILLIS_PER_SECOND)*F.LocalTime.NANOS_PER_MILLI;return o.ofEpochSecond(t,r)}static ofEpochSecond(e,t=0){if(!Number.isSafeInteger(e)||!Number.isSafeInteger(t))throw new Error("The timestamp must be a safe integer.");if(e===0&&t===0)return o.EPOCH;if(e<o.MIN_SECOND||e>o.MAX_SECOND)throw new Error(`The value ${e} is out of the range [${o.MIN_SECOND} - ${o.MAX_SECOND}] of instant.`);let n=e,r=t;return t!==0&&(n=(0, z.addExact)(n,(0, z.floorDiv)(t,F.LocalTime.NANOS_PER_SECOND)),r=(0, z.floorMod)(t,F.LocalTime.NANOS_PER_SECOND)),new o(n,r)}static parse(e){let n=e.match(o.PATTERN)?.groups;if(n==null)throw new Error(`Unrecognized UTC ISO-8601 date-time string "${e}".`);let r=wl.LocalDate.of(Number.parseInt(n.year,10),Number.parseInt(n.month,10),Number.parseInt(n.day,10)).toEpochDay(),i=F.LocalTime.of(Number.parseInt(n.hour,10),Number.parseInt(n.minute??"0",10),Number.parseInt(n.second??"0",10),Number.parseInt(n.fraction?.padEnd(9,"0")??"0",10)).toNanoOfDay();return o.ofEpochSecond((0, z.multiplyExact)(r,F.LocalTime.SECONDS_PER_DAY),i)}static compareAscending(e,t){return e.compare(t)}static compareDescending(e,t){return t.compare(e)}getSeconds(){return this.seconds}getNano(){return this.nanos}toEpochMillis(){if(this.seconds<0&&this.nanos>0){let n=(0, z.multiplyExact)(this.seconds+1,F.LocalTime.MILLIS_PER_SECOND),r=(0, z.intDiv)(this.nanos,F.LocalTime.NANOS_PER_MILLI)-F.LocalTime.MILLIS_PER_SECOND;return (0, z.addExact)(n,r)}let e=(0, z.multiplyExact)(this.seconds,F.LocalTime.MILLIS_PER_SECOND),t=(0, z.intDiv)(this.nanos,F.LocalTime.NANOS_PER_MILLI);return (0, z.addExact)(e,t)}toDate(){return new Date(this.toEpochMillis())}toString(){let e=this.seconds%12622780800,t=Cl.LocalDateTime.ofEpochSecond(e,this.nanos),n=t.getYear()+(0, z.intDiv)(this.seconds,146097*86400)*400,r="";n<0?r="-":n>9999&&(r="+");let a=r+Math.abs(n).toString().padStart(4,"0")+t.toString().slice(4);return t.getSecond()===0&&t.getNano()===0&&(a+=":00"),a+="Z",a}toJSON(){return this.toString()}equals(e){return this.seconds===e.seconds&&this.nanos===e.nanos}plusDays(e){if(e===0)return this;let t=(0, z.multiplyExact)(e,F.LocalTime.SECONDS_PER_DAY);return this.plusSeconds(t)}minusDays(e){if(e===0)return this;let t=(0, z.multiplyExact)(e,F.LocalTime.SECONDS_PER_DAY);return this.minusSeconds(t)}plusHours(e){if(e===0)return this;let t=(0, z.multiplyExact)(e,F.LocalTime.SECONDS_PER_HOUR);return this.plusSeconds(t)}minusHours(e){if(e===0)return this;let t=(0, z.multiplyExact)(e,F.LocalTime.SECONDS_PER_HOUR);return this.minusSeconds(t)}plusMinutes(e){if(e===0)return this;let t=(0, z.multiplyExact)(e,F.LocalTime.SECONDS_PER_MINUTE);return this.plusSeconds(t)}minusMinutes(e){if(e===0)return this;let t=(0, z.multiplyExact)(e,F.LocalTime.SECONDS_PER_MINUTE);return this.minusSeconds(t)}plusSeconds(e){return e===0?this:o.ofEpochSecond((0, z.addExact)(this.seconds,e),this.nanos)}minusSeconds(e){return e===0?this:o.ofEpochSecond((0, z.subtractExact)(this.seconds,e),this.nanos)}plusMillis(e){if(e===0)return this;let t=(0, z.intDiv)(e,F.LocalTime.MILLIS_PER_SECOND),n=(0, z.addExact)(this.seconds,t),r=e%F.LocalTime.MILLIS_PER_SECOND,i=this.nanos+r*F.LocalTime.NANOS_PER_MILLI;return o.ofEpochSecond(n,i)}minusMillis(e){return this.plusMillis(-e)}plusMicros(e){if(e===0)return this;let t=(0, z.intDiv)(e,F.LocalTime.MICROS_PER_SECOND),n=(0, z.addExact)(this.seconds,t),r=e%F.LocalTime.MICROS_PER_SECOND,i=this.nanos+r*F.LocalTime.NANOS_PER_MICRO;return o.ofEpochSecond(n,i)}minusMicros(e){return this.plusMicros(-e)}plusNanos(e){if(e===0)return this;let t=(0, z.intDiv)(e,F.LocalTime.NANOS_PER_SECOND),n=(0, z.addExact)(this.seconds,t),r=e%F.LocalTime.NANOS_PER_SECOND,i=this.nanos+r;return o.ofEpochSecond(n,i)}minusNanos(e){return this.plusNanos(-e)}isAfter(e){return this.compare(e)>0}isAfterOrEqual(e){return this.compare(e)>=0}isBefore(e){return this.compare(e)<0}static isValid(e){try{o.parse(e);}catch{return false}return true}isBeforeOrEqual(e){return this.compare(e)<=0}compare(e){return this.seconds!==e.seconds?this.seconds-e.seconds:this.nanos-e.nanos}};sr.Instant=me;me.EPOCH=new me(0,0);me.MIN_SECOND=-31619087596800;me.MIN=new me(me.MIN_SECOND,0);me.MAX_SECOND=31494784780799;me.MAX=new me(me.MAX_SECOND,999999999);me.PATTERN=/^(?<year>[+-]?\d{4,19})-(?<month>\d{2})-(?<day>\d{2})T(?<hour>\d{2})(?::(?<minute>\d{2})(:(?<second>\d{2})(?:.(?<fraction>\d{1,9}))?)?)?Z$/;});var js=ve(pr=>{Object.defineProperty(pr,"__esModule",{value:true});pr.Weekday=void 0;var Fs;(function(o){o.SUNDAY="SUNDAY",o.MONDAY="MONDAY",o.TUESDAY="TUESDAY",o.WEDNESDAY="WEDNESDAY",o.THURSDAY="THURSDAY",o.FRIDAY="FRIDAY",o.SATURDAY="SATURDAY";})(Fs||(pr.Weekday=Fs={}));});var Ws=ve(cr=>{Object.defineProperty(cr,"__esModule",{value:true});cr.TimeInterval=void 0;var wt=rn(),Ba=class o{constructor(e,t){this.start=e,this.end=t;}static all(){return new o(wt.Instant.MIN,wt.Instant.MAX)}static between(e,t){if(t.isBefore(e))throw new Error("The end instant must be equal or after start instant.");return new o(e,t)}static parse(e){let t=e.split("/");if(t.length!==2||t[0]===""||t[1]==="")throw new Error(`Malformed time interval "${e}".`);return o.between(wt.Instant.parse(t[0]),wt.Instant.parse(t[1]))}static startingAt(e){return o.all().withStart(e)}static endingAt(e){return o.all().withEnd(e)}withStart(e){return o.between(e,this.end)}withEnd(e){return o.between(this.start,e)}getStart(){return this.start}getEnd(){return this.end}isEmpty(){return this.start.equals(this.end)}isUnboundedStart(){return this.start.equals(wt.Instant.MIN)}isUnboundedEnd(){return this.end.equals(wt.Instant.MAX)}encloses(e){return this.start.isBeforeOrEqual(e.start)&&this.end.isAfterOrEqual(e.end)}abuts(e){return this.start.equals(e.end)||this.end.equals(e.start)}isConnected(e){return this.equals(e)||this.start.isBeforeOrEqual(e.end)&&this.end.isAfterOrEqual(e.start)}overlaps(e){return this.equals(e)||this.start.isBefore(e.end)&&this.end.isAfter(e.start)}intersection(e){if(!this.isConnected(e))throw new Error("The intervals are not connected.");return this.start.isAfterOrEqual(e.start)&&this.end.isBefore(e.end)?this:e.start.isAfterOrEqual(this.start)&&e.end.isBeforeOrEqual(this.end)?e:o.between(this.start.isAfterOrEqual(e.start)?this.start:e.start,this.end.isBeforeOrEqual(e.end)?this.end:e.end)}union(e){if(!this.isConnected(e))throw new Error("The intervals are not connected.");return this.start.isAfterOrEqual(e.start)&&this.end.isBefore(e.end)?e:e.start.isAfterOrEqual(this.start)&&e.end.isBeforeOrEqual(this.end)?this:o.between(this.start.isAfterOrEqual(e.start)?e.start:this.start,this.end.isBeforeOrEqual(e.end)?e.end:this.end)}span(e){return o.between(this.start.isAfterOrEqual(e.start)?e.start:this.start,this.end.isBeforeOrEqual(e.end)?e.end:this.end)}isAfter(e){return this.start.isAfterOrEqual(e.end)&&!this.equals(e)}isBefore(e){return this.end.isBeforeOrEqual(e.start)&&!this.equals(e)}static isValid(e){try{o.parse(e);}catch{return false}return true}startsBefore(e){return this.start.isBefore(e)}startsAtOrBefore(e){return this.start.isBeforeOrEqual(e)}startsAfter(e){return this.start.isAfter(e)}startsAtOrAfter(e){return this.start.isAfterOrEqual(e)}endsBefore(e){return this.end.isBefore(e)}endsAtOrBefore(e){return this.end.isBeforeOrEqual(e)}endsAfter(e){return this.end.isAfter(e)}endsAtOrAfter(e){return this.end.isAfterOrEqual(e)}contains(e){return this.start.isBeforeOrEqual(e)&&this.end.isAfter(e)}equals(e){return e instanceof o&&this.start.equals(e.start)&&this.end.equals(e.end)}toString(){return `${this.start.toString()}/${this.end.toString()}`}toJSON(){return this.toString()}};cr.TimeInterval=Ba;});var an=ve(ee=>{Object.defineProperty(ee,"__esModule",{value:true});ee.TimeInterval=ee.TimeZone=ee.LocalDateTime=ee.LocalTime=ee.LocalDate=ee.Weekday=ee.Instant=void 0;var Pl=rn();Object.defineProperty(ee,"Instant",{enumerable:true,get:function(){return Pl.Instant}});var kl=js();Object.defineProperty(ee,"Weekday",{enumerable:true,get:function(){return kl.Weekday}});var Al=nr();Object.defineProperty(ee,"LocalDate",{enumerable:true,get:function(){return Al.LocalDate}});var El=ir();Object.defineProperty(ee,"LocalTime",{enumerable:true,get:function(){return El.LocalTime}});var Rl=Ja();Object.defineProperty(ee,"LocalDateTime",{enumerable:true,get:function(){return Rl.LocalDateTime}});var Tl=Ha();Object.defineProperty(ee,"TimeZone",{enumerable:true,get:function(){return Tl.TimeZone}});var Ol=Ws();Object.defineProperty(ee,"TimeInterval",{enumerable:true,get:function(){return Ol.TimeInterval}});});var Ms=vt(Ds(),1),{program:Nd,createCommand:$d,createArgument:zd,createOption:_d,CommanderError:Ld,InvalidArgumentError:Ue,InvalidOptionArgumentError:Fd,Command:Ns,Argument:$s,Option:se,Help:jd}=Ms.default;var xt=vt(an()),nl=vt(Ga());var lr=class{constructor(e){this.configuration=e;}prompt(e){return this.interact({type:e.type==="password"?"invisible":"text",message:e.message,initial:e.default,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=>({title:n.label,value:n.value,disabled:n.disabled})),initial:t===-1?void 0:t})}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=>({title:t.label,value:t.value,disabled:t.disabled,selected:t.selected}))})}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,a=false;return this.interact({type:"invisible",message:e.message,validate:s=>i===void 0||s===i?true:r,onState:function(p){if(!a){if(p.value===""){this.error&&e.key!==t.enter&&this.bell();return}i===void 0||p.value===i?(a=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={name:"value",...e,stdin:this.configuration.input,stdout:this.configuration.output,onState:function(s){e.onState?.apply(this,[s]),s.aborted&&(n.write("\x1B[?25h"),n.write(`
3
- `),r());}};try{return await Dl__default.default(i,t).then(a=>a.value)}finally{this.configuration.onInteractionEnd?.();}}};var pt=Ml__default.default(),sn={neutral:"cyan",info:"blue",error:"red",warning:"yellow",success:"green"},Ll={neutral:pt?"\u279C":">",info:pt?"\u2139":"i",error:pt?"\u2718":"\xD7",warning:pt?"\u26A0":"\u203C",success:pt?"\u2714":"\u221A"};function te(o,e={}){let t=e.basic===true?o:Fl(o);if(pt||(t=nodeEmoji.strip(t)),e.text!==void 0&&(t=ct__default.default[sn[e.text]](t)),e.icon!==void 0){let{semantic:n,symbol:r}=e.icon;t=r!==void 0?`${ct__default.default[sn[n]](r[pt?"unicode":"ascii"])} ${t}`:`${ct__default.default[sn[n]](Ll[n])} ${t}`;}return t}function Fl(o){return rendering.render(o,{fragment:e=>e.children.join(""),text:e=>e.content,bold:e=>ct__default.default.bold(e.children),italic:e=>ct__default.default.italic(e.children),strike:e=>ct__default.default.strikethrough(e.children),code:e=>ct__default.default.cyan(e.content),link:e=>$l__default.default(e.children,e.href,{fallback:(t,n)=>`${t} (${n})`}),image:e=>parsing.unescape(e.source),paragraph:e=>`${e.children.join("")}
2
+ import {createRequire}from'module';import {createReadStream,realpathSync}from'fs';import {ApiKey}from'@croct/sdk/apiKey';import {InMemoryCache,AutoSaveCache,AdaptedCache,NoopCache}from'@croct/cache';import Oc from'open';import {homedir}from'os';import nd from'xdg-app-paths';import rd from'ci-info';import {FilteredLogger,LogLevel}from'@croct/logging';import pl from'prompts';import {Readable,PassThrough}from'stream';import Ra from'cli-cursor';import nt from'chalk';import Ss from'node:readline';import {WriteStream}from'tty';import cl from'is-unicode-supported';import {render}from'@croct/md-lite/rendering.js';import ul 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 {JsonParser,JsonObjectNode,JsonArrayNode,JsonPrimitiveNode,JsonIdentifierNode,JsonTokenNode,JsonTokenType,isIdentifier}from'@croct/json5-parser';import*as g from'@babel/types';import {traverseFast}from'@babel/types';import {traverse}from'@babel/core';import {parse as parse$1}from'@babel/parser';import {createHash,randomUUID}from'crypto';import*as Sr from'recast';import {parse}from'recast/parsers/babel-ts.js';import Fl from'string-similarity-js';import {realpath,lstat,readdir,symlink,link,mkdir,writeFile,rm as rm$1,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 Ql from'tar-stream';import Bl from'gunzip-maybe';import {z,ZodPromise,ZodOptional,ZodTuple,ZodArray,ZodRecord,ZodObject,ZodEffects,ZodAny,ZodPipeline,ZodUnion,ZodDiscriminatedUnion}from'zod';import qe from'jsep';import ou from'@jsep-plugin/object';import au from'@jsep-plugin/spread';import pc from'is-plain-obj';import Cm from'strip-ansi';import wc from'semver';import {spawn}from'node-pty';import {spawn as spawn$1,spawnSync}from'child_process';import Nm from'ignore';import Wm from'clipboardy';import {Token}from'@croct/sdk/token';import Ec from'boxen';import Le from'node:process';import {AsyncLocalStorage}from'node:async_hooks';const require = createRequire(import.meta.url);
3
+ var $c=Object.create;var xa=Object.defineProperty;var zc=Object.getOwnPropertyDescriptor;var _c=Object.getOwnPropertyNames;var Lc=Object.getPrototypeOf,Fc=Object.prototype.hasOwnProperty;var jc=(o=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(o,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):o)(function(o){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+o+'" is not supported')});var be=(o,e)=>()=>(e||o((e={exports:{}}).exports,e),e.exports),Wc=(o,e)=>{for(var t in e)xa(o,t,{get:e[t],enumerable:true});},Vc=(o,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of _c(e))!Fc.call(o,r)&&r!==t&&xa(o,r,{get:()=>e[r],enumerable:!(n=zc(e,r))||n.enumerable});return o};var ft=(o,e,t)=>(t=o!=null?$c(Lc(o)):{},Vc(xa(t,"default",{value:o,enumerable:true}),o));var ps=be((ue,ss)=>{var ke=jc("commander");ue=ss.exports={};ue.program=new ke.Command;ue.Argument=ke.Argument;ue.Command=ke.Command;ue.CommanderError=ke.CommanderError;ue.Help=ke.Help;ue.InvalidArgumentError=ke.InvalidArgumentError;ue.InvalidOptionArgumentError=ke.InvalidArgumentError;ue.Option=ke.Option;ue.createCommand=o=>new ke.Command(o);ue.createOption=(o,e)=>new ke.Option(o,e);ue.createArgument=(o,e)=>new ke.Argument(o,e);});var va=be($n=>{Object.defineProperty($n,"__esModule",{value:true});$n.TimeZone=void 0;var qt=class o{constructor(e){this.id=e;}static getTimesZoneIds(){return o.SUPPORTED_TIMEZONE_IDS===void 0&&(o.SUPPORTED_TIMEZONE_IDS=new Set(["UTC","CET","CST6CDT","EET","EST","EST5EDT","Etc/GMT+1","Etc/GMT+10","Etc/GMT+11","Etc/GMT+12","Etc/GMT+2","Etc/GMT+3","Etc/GMT+4","Etc/GMT+5","Etc/GMT+6","Etc/GMT+7","Etc/GMT+8","Etc/GMT+9","Etc/GMT-1","Etc/GMT-10","Etc/GMT-11","Etc/GMT-12","Etc/GMT-13","Etc/GMT-14","Etc/GMT-2","Etc/GMT-3","Etc/GMT-4","Etc/GMT-5","Etc/GMT-6","Etc/GMT-7","Etc/GMT-8","Etc/GMT-9","HST","MET","MST","MST7MDT","PST8PDT","WET",...Intl.supportedValuesOf("timeZone")])),o.SUPPORTED_TIMEZONE_IDS}static of(e){if(!o.getTimesZoneIds().has(e))throw new Error(`The timezone ${e} is not supported.`);return new o(e)}getId(){return this.id}toString(){return this.id}equals(e){return this.id===e.id}toJSON(){return this.toString()}};$n.TimeZone=qt;qt.UTC=new qt("UTC");});var Pa=be(zn=>{var wa;Object.defineProperty(zn,"__esModule",{value:true});zn.SystemClock=void 0;var Uc=Gt(),qc=va(),Ht=class{constructor(e){this.zone=e;}static of(e){return new this(e)}getZone(){return this.zone}getInstant(){return Uc.Instant.ofEpochMilli(Date.now())}equals(e){return e===this||e instanceof wa&&e.zone.equals(this.zone)}};zn.SystemClock=Ht;wa=Ht;Ht.UTC=new wa(qc.TimeZone.UTC);});var Ca=be(_n=>{Object.defineProperty(_n,"__esModule",{value:true});_n.DefaultClockProvider=void 0;var Hc=Pa(),ms;(function(o){let e=null;function t(){return e===null&&(e=Hc.SystemClock.UTC),e}o.getClock=t;function n(r){e=r;}o.setClock=n;})(ms||(_n.DefaultClockProvider=ms={}));});var Kt=be(pe=>{Object.defineProperty(pe,"__esModule",{value:true});pe.intDiv=pe.multiplyExact=pe.subtractExact=pe.addExact=pe.floorMod=pe.floorDiv=void 0;function ds(o,e){let t=Math.trunc(o/e);return Math.sign(o)!==Math.sign(e)&&t*e!==o&&t--,t}pe.floorDiv=ds;function Gc(o,e){return o-ds(o,e)*e}pe.floorMod=Gc;function Kc(o,e){let t=o+e;if(!Number.isSafeInteger(t))throw new Error("The result overflows the range of safe integers.");return t}pe.addExact=Kc;function Zc(o,e){let t=o-e;if(!Number.isSafeInteger(t))throw new Error("The result overflows the range of safe integers.");return t}pe.subtractExact=Zc;function Jc(o,e){let t=o*e;if(!Number.isSafeInteger(t))throw new Error("The result overflows the range of safe integers.");return t}pe.multiplyExact=Jc;function Qc(o,e){let t=Math.trunc(o/e);if(!Number.isSafeInteger(t))throw new Error("The result overflows the range of safe integers.");return t}pe.intDiv=Qc;});var Fn=be(Ln=>{Object.defineProperty(Ln,"__esModule",{value:true});Ln.LocalDate=void 0;var V=Kt(),ce=class o{constructor(e,t,n){this.year=e,this.month=t,this.day=n;}static of(e,t,n){if(!Number.isSafeInteger(e)||e<o.MIN_YEAR||e>o.MAX_YEAR)throw new Error(`Year must be a safe integer between ${o.MIN_YEAR} and ${o.MAX_YEAR}.`);if(!Number.isInteger(t)||t<1||t>12)throw new Error("Month must be an integer between 1 and 12.");let r=o.getMonthLength(t,o.isLeapYear(e));if(!Number.isInteger(n)||n<1||n>r)throw new Error(`Day must be an integer between 1 and ${r}.`);return new o(e,t,n)}static ofEpochDay(e){if(e<o.MIN_EPOCH_DAY||e>o.MAX_EPOCH_DAY)throw new Error(`The day ${e} is out of the range [${o.MIN_EPOCH_DAY} - ${o.MAX_EPOCH_DAY}].`);let t=(0, V.addExact)(e,719468),n=(0, V.floorDiv)(t,146097),r=(0, V.floorMod)(t,146097),i=(0, V.intDiv)(r,1460);i-=(0, V.intDiv)(r,36524),i+=(0, V.intDiv)(r,146096);let a=(0, V.intDiv)(r-i,365),s=a+n*400,p=365*a+(0, V.intDiv)(a,4)-(0, V.intDiv)(a,100),c=r-p,l=(0, V.intDiv)(c*5+2,153);s+=(0, V.intDiv)(l,10);let m=c-(0, V.intDiv)(l*306+5,10)+1;return l=(l+2)%12+1,o.of(s,l,m)}static fromNative(e){return o.of(e.getFullYear(),e.getMonth()+1,e.getDate())}static parse(e){let{groups:t}=e.match(o.PATTERN)??{};if(t===void 0)throw new Error(`Invalid ISO-8601 date string: ${e}`);let n=Number.parseInt(t.year,10),r=Number.parseInt(t.month,10),i=Number.parseInt(t.day,10);return o.of(n,r,i)}getYear(){return this.year}getMonth(){return this.month}getDay(){return this.day}equals(e){return this===e?true:this.year===e.year&&this.month===e.month&&this.day===e.day}plusYears(e){if(e===0)return this;let t=(0, V.addExact)(this.year,e);return o.resolvePreviousValid(t,this.month,this.day)}minusYears(e){return this.plusYears(-e)}plusMonths(e){if(e===0)return this;let t=this.year+(0, V.intDiv)(e,12),n=this.month+e%12,r=t+(0, V.floorDiv)(n-1,12),i=(0, V.floorMod)(n-1,12)+1;return o.resolvePreviousValid(r,i,this.day)}minusMonths(e){return this.plusMonths(-e)}plusWeeks(e){return e===0?this:this.plusDays((0, V.multiplyExact)(e,7))}minusWeeks(e){return this.plusWeeks(-e)}plusDays(e){if(e===0)return this;let t=this.day+e;if(t>0){if(t<=28)return o.of(this.year,this.month,t);if(t<=59){let n=o.getMonthLength(this.month,o.isLeapYear(this.year));return t<=n?o.of(this.year,this.month,t):this.month<12?o.of(this.year,this.month+1,t-n):o.of(this.year+1,1,t-n)}}return o.ofEpochDay((0, V.addExact)(this.toEpochDay(),e))}minusDays(e){return this.plusDays(-e)}isAfter(e){return this.compare(e)>0}isAfterOrEqual(e){return this.compare(e)>=0}isBefore(e){return this.compare(e)<0}isBeforeOrEqual(e){return this.compare(e)<=0}static isValid(e){try{o.parse(e);}catch{return false}return true}compare(e){return this.year!==e.year?this.year-e.year:this.month!==e.month?this.month-e.month:this.day-e.day}toEpochDay(){let{year:e}=this;this.month<=2&&e--;let t=(0, V.floorDiv)(e,400),n=(this.month+9)%12,r=(0, V.intDiv)(153*n+2,5)+this.day-1,i=e-t*400;return 365*i+(0, V.intDiv)(i,4)-(0, V.intDiv)(i,100)+r+t*146097-719468}toString(){let e=`${this.month}`.padStart(2,"0"),t=`${this.day}`.padStart(2,"0");return `${this.year}-${e}-${t}`}static resolvePreviousValid(e,t,n){let r=o.getMonthLength(t,o.isLeapYear(e));return o.of(e,t,Math.min(n,r))}static isLeapYear(e){return e%4===0&&(e%100!==0||e%400===0)}static getMonthLength(e,t){switch(e){case 2:return t?29:28;case 4:case 6:case 9:case 11:return 30;default:return 31}}toJSON(){return this.toString()}};Ln.LocalDate=ce;ce.PATTERN=/^(?<year>[+-]?\d{4,19})-(?<month>\d{2})-(?<day>\d{2})$/;ce.MIN_EPOCH_DAY=-365961662;ce.MAX_EPOCH_DAY=364522971;ce.MIN_YEAR=-999999;ce.MAX_YEAR=999999;ce.MIN=new ce(ce.MIN_YEAR,1,1);ce.MAX=new ce(ce.MAX_YEAR,12,31);});var Wn=be(jn=>{Object.defineProperty(jn,"__esModule",{value:true});jn.LocalTime=void 0;var De=Kt(),H=class o{constructor(e,t,n,r){this.hour=e,this.minute=t,this.second=n,this.nanos=r;}static of(e,t=0,n=0,r=0){if(!Number.isInteger(e)||e<0||e>23)throw new Error("Hour must be an integer between 0 and 23.");if(!Number.isInteger(t)||t<0||t>59)throw new Error("Minute must be an integer between 0 and 59.");if(!Number.isInteger(n)||n<0||n>59)throw new Error("Second must be an integer between 0 and 59.");if(!Number.isInteger(r)||r<0||r>999999999)throw new Error("Nanosecond of second must be an integer between 0 and 999999999.");return new o(e,t,n,r)}static ofSecondOfDay(e,t=0){if(e<0||e>o.SECONDS_PER_DAY-1)throw new Error(`The second value ${e} is out of the range [0 - ${o.SECONDS_PER_DAY-1}] of local time.`);if(t<0||t>o.NANOS_PER_SECOND-1)throw new Error(`The nanosecond value ${t} is out of the range [0 - ${o.NANOS_PER_SECOND-1}] of local time.`);let n=e,r=(0, De.intDiv)(n,o.SECONDS_PER_HOUR);n-=r*o.SECONDS_PER_HOUR;let i=(0, De.intDiv)(n,o.SECONDS_PER_MINUTE);return n-=i*o.SECONDS_PER_MINUTE,o.of(r,i,n,t)}static fromNative(e){return new o(e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()*o.NANOS_PER_MILLI)}static startOfDay(){return new o(0,0,0,0)}static endOfDay(){return new o(23,59,59,999999999)}static parse(e){let{groups:t}=e.match(o.PATTERN)??{};if(t===void 0)throw new Error(`Invalid ISO-8601 time string: ${e}`);let n=Number.parseInt(t.hour,10),r=Number.parseInt(t.minute,10),i=Number.parseInt(t.second??"0",10),a=Number.parseInt(t.fraction?.padEnd(9,"0")??"0",10);return o.of(n,r,i,a)}getHour(){return this.hour}getMinute(){return this.minute}getSecond(){return this.second}getNano(){return this.nanos}toMinuteOfDay(){return this.hour*o.MINUTES_PER_HOUR+this.minute}toSecondOfDay(){return this.toMinuteOfDay()*o.SECONDS_PER_MINUTE+this.second}toMilliOfDay(){return (0, De.intDiv)(this.toNanoOfDay(),o.NANOS_PER_MILLI)}toMicroOfDay(){return (0, De.intDiv)(this.toNanoOfDay(),o.NANOS_PER_MICRO)}toNanoOfDay(){return this.toSecondOfDay()*o.NANOS_PER_SECOND+this.nanos}plusHours(e){if(e===0)return this;let n=(e%o.HOURS_PER_DAY+this.hour+o.HOURS_PER_DAY)%o.HOURS_PER_DAY;return new o(n,this.minute,this.second,this.nanos)}minusHours(e){return this.plusHours(-e)}plusMinutes(e){if(e===0)return this;let t=e%o.MINUTES_PER_DAY,n=this.toMinuteOfDay(),r=(t+n+o.MINUTES_PER_DAY)%o.MINUTES_PER_DAY;if(n===r)return this;let i=(0, De.intDiv)(r,o.MINUTES_PER_HOUR),a=r%o.MINUTES_PER_HOUR;return new o(i,a,this.second,this.nanos)}minusMinutes(e){return this.plusMinutes(-e)}plusSeconds(e){if(e===0)return this;let t=e%o.SECONDS_PER_DAY,n=this.toSecondOfDay(),r=(t+n+o.SECONDS_PER_DAY)%o.SECONDS_PER_DAY;if(n===r)return this;let i=(0, De.intDiv)(r,o.SECONDS_PER_HOUR),a=(0, De.intDiv)(r,o.SECONDS_PER_MINUTE)%o.MINUTES_PER_HOUR,s=r%o.SECONDS_PER_MINUTE;return o.of(i,a,s,this.nanos)}minusSeconds(e){return this.plusSeconds(-e)}plusMillis(e){return e===0?this:this.plusNanos(e%o.MILLIS_PER_DAY*o.NANOS_PER_MILLI)}minusMillis(e){return this.plusMillis(-e)}plusMicros(e){return e===0?this:this.plusNanos(e%o.MICROS_PER_DAY*o.NANOS_PER_MICRO)}minusMicros(e){return this.plusMicros(-e)}plusNanos(e){if(e===0)return this;let t=e%o.NANOS_PER_DAY,n=this.toNanoOfDay(),r=(t+n+o.NANOS_PER_DAY)%o.NANOS_PER_DAY;if(n===r)return this;let i=(0, De.intDiv)(r,o.NANOS_PER_HOUR),a=(0, De.intDiv)(r,o.NANOS_PER_MINUTE)%o.MINUTES_PER_HOUR,s=(0, De.intDiv)(r,o.NANOS_PER_SECOND)%o.SECONDS_PER_MINUTE,p=r%o.NANOS_PER_SECOND;return o.of(i,a,s,p)}minusNanos(e){return this.plusNanos(-e)}equals(e){return this===e?true:this.hour===e.hour&&this.minute===e.minute&&this.second===e.second&&this.nanos===e.nanos}isAfter(e){return this.compare(e)>0}isAfterOrEqual(e){return this.compare(e)>=0}isBefore(e){return this.compare(e)<0}isBeforeOrEqual(e){return this.compare(e)<=0}static isValid(e){try{o.parse(e);}catch{return false}return true}compare(e){return this.hour!==e.hour?this.hour-e.hour:this.minute!==e.minute?this.minute-e.minute:this.second!==e.second?this.second-e.second:this.nanos-e.nanos}toString(){let e=`${this.hour}`.padStart(2,"0"),t=`${this.minute}`.padStart(2,"0"),n=`${e}:${t}`;if(this.second===0&&this.nanos===0)return n;let r=`${this.second}`.padStart(2,"0");if(n+=`:${r}`,this.nanos>0){let i=`${this.nanos}`.padStart(9,"0").replace(/0+$/,""),a=Math.floor((i.length+2)/3)*3;n+=`.${i.padEnd(a,"0")}`;}return n}toJSON(){return this.toString()}};jn.LocalTime=H;H.PATTERN=/^(?<hour>\d{2}):(?<minute>\d{2})(?::(?<second>\d{2})(?:.(?<fraction>\d{1,9}))?)?$/;H.HOURS_PER_DAY=24;H.MINUTES_PER_DAY=1440;H.MINUTES_PER_HOUR=60;H.SECONDS_PER_DAY=86400;H.SECONDS_PER_HOUR=3600;H.SECONDS_PER_MINUTE=60;H.MICROS_PER_DAY=864e8;H.MICROS_PER_SECOND=1e6;H.MILLIS_PER_DAY=864e5;H.MILLIS_PER_SECOND=1e3;H.NANOS_PER_DAY=864e11;H.NANOS_PER_HOUR=36e11;H.NANOS_PER_MINUTE=6e10;H.NANOS_PER_SECOND=1e9;H.NANOS_PER_MILLI=1e6;H.NANOS_PER_MICRO=1e3;});var Aa=be(Un=>{Object.defineProperty(Un,"__esModule",{value:true});Un.LocalDateTime=void 0;var gs=Ca(),Bc=Gt(),Vn=Fn(),k=Wn(),G=Kt(),ka=class o{constructor(e,t){this.date=e,this.time=t;}static nowIn(e,t=gs.DefaultClockProvider.getClock()){return o.ofInstant(t.getInstant(),e)}static now(e=gs.DefaultClockProvider.getClock()){return o.ofInstant(e.getInstant(),e.getZone())}static ofInstant(e,t){return o.fromZonedDate(e.toDate(),t)}static fromZonedDate(e,t){let i=e.toLocaleString("sv-SE",{timeZone:t.getId(),calendar:e.getUTCFullYear()<200?"gregory":"iso8601",hourCycle:"h23",year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit",second:"2-digit",fractionalSecondDigits:3}).match(/(?<year>\d{1,4})-(?<month>\d{2})-(?<day>\d{2}) (?<hour>\d{2}):(?<minute>\d{2}):(?<second>\d{2}),(?<fraction>\d{3})/)?.groups;return o.of(Vn.LocalDate.of(Number.parseInt(i.year,10),Number.parseInt(i.month,10),Number.parseInt(i.day,10)),k.LocalTime.of(Number.parseInt(i.hour,10),Number.parseInt(i.minute,10),Number.parseInt(i.second,10),Number.parseInt(i.fraction.padEnd(9,"0"),10)))}static ofEpochSecond(e,t=0){if(!Number.isSafeInteger(e)||!Number.isSafeInteger(t))throw new Error("The timestamp must be a safe integer.");let n=(0, G.floorDiv)(e,k.LocalTime.SECONDS_PER_DAY),r=(0, G.floorMod)(e,k.LocalTime.SECONDS_PER_DAY),i=Vn.LocalDate.ofEpochDay(n),a=k.LocalTime.ofSecondOfDay(r,t);return o.of(i,a)}static fromNative(e){return o.of(Vn.LocalDate.fromNative(e),k.LocalTime.fromNative(e))}static of(e,t){return new o(e,t??k.LocalTime.startOfDay())}static parse(e){let t=e.split("T");if(t.length!==2)throw new Error(`Malformed local date-time "${e}".`);return o.of(Vn.LocalDate.parse(t[0]),k.LocalTime.parse(t[1]))}getLocalDate(){return this.date}getLocalTime(){return this.time}getDay(){return this.date.getDay()}getMonth(){return this.date.getMonth()}getYear(){return this.date.getYear()}getHour(){return this.time.getHour()}getMinute(){return this.time.getMinute()}getSecond(){return this.time.getSecond()}getNano(){return this.time.getNano()}plusYears(e){return o.of(this.date.plusYears(e),this.time)}minusYears(e){return this.plusYears(-e)}plusMonths(e){return o.of(this.date.plusMonths(e),this.time)}minusMonths(e){return this.plusMonths(-e)}plusWeeks(e){return o.of(this.date.plusWeeks(e),this.time)}minusWeeks(e){return this.plusWeeks(-e)}plusDays(e){return o.of(this.date.plusDays(e),this.time)}minusDays(e){return this.plusDays(-e)}plusHours(e){if(e===0)return this;let t=(0, G.intDiv)(e,k.LocalTime.HOURS_PER_DAY),n=e%k.LocalTime.HOURS_PER_DAY,r=n*k.LocalTime.NANOS_PER_HOUR+this.time.toNanoOfDay(),i=t+(0, G.floorDiv)(r,k.LocalTime.NANOS_PER_DAY);return o.of(this.date.plusDays(i),this.time.plusHours(n))}minusHours(e){return this.plusHours(-e)}plusMinutes(e){if(e===0)return this;let t=(0, G.intDiv)(e,k.LocalTime.MINUTES_PER_DAY),n=e%k.LocalTime.MINUTES_PER_DAY,r=n*k.LocalTime.NANOS_PER_MINUTE+this.time.toNanoOfDay(),i=t+(0, G.floorDiv)(r,k.LocalTime.NANOS_PER_DAY);return o.of(this.date.plusDays(i),this.time.plusMinutes(n))}minusMinutes(e){return this.plusMinutes(-e)}plusSeconds(e){if(e===0)return this;let t=(0, G.intDiv)(e,k.LocalTime.SECONDS_PER_DAY),n=e%k.LocalTime.SECONDS_PER_DAY,r=n*k.LocalTime.NANOS_PER_SECOND+this.time.toNanoOfDay(),i=t+(0, G.floorDiv)(r,k.LocalTime.NANOS_PER_DAY);return o.of(this.date.plusDays(i),this.time.plusSeconds(n))}minusSeconds(e){return this.plusSeconds(-e)}plusMillis(e){if(e===0)return this;let t=(0, G.intDiv)(e,k.LocalTime.MILLIS_PER_DAY),n=e%k.LocalTime.MILLIS_PER_DAY,r=n*k.LocalTime.NANOS_PER_MILLI+this.time.toNanoOfDay(),i=t+(0, G.floorDiv)(r,k.LocalTime.NANOS_PER_DAY);return o.of(this.date.plusDays(i),this.time.plusMillis(n))}minusMillis(e){return this.plusMillis(-e)}plusMicros(e){if(e===0)return this;let t=(0, G.intDiv)(e,k.LocalTime.MICROS_PER_DAY),n=e%k.LocalTime.MICROS_PER_DAY,r=n*k.LocalTime.NANOS_PER_MICRO+this.time.toNanoOfDay(),i=t+(0, G.floorDiv)(r,k.LocalTime.NANOS_PER_DAY);return o.of(this.date.plusDays(i),this.time.plusMicros(n))}minusMicros(e){return this.plusMicros(-e)}plusNanos(e){if(e===0)return this;let t=(0, G.intDiv)(e,k.LocalTime.NANOS_PER_DAY),n=e%k.LocalTime.NANOS_PER_DAY,r=n+this.time.toNanoOfDay(),i=t+(0, G.floorDiv)(r,k.LocalTime.NANOS_PER_DAY);return o.of(this.date.plusDays(i),this.time.plusNanos(n))}minusNanos(e){return this.plusNanos(-e)}equals(e){return this===e?true:this.date.equals(e.date)&&this.time.equals(e.time)}isAfter(e){return this.compare(e)>0}isAfterOrEqual(e){return this.compare(e)>=0}isBefore(e){return this.compare(e)<0}isBeforeOrEqual(e){return this.compare(e)<=0}static isValid(e){try{o.parse(e);}catch{return false}return true}compare(e){let t=this.date.compare(e.date);return t!==0?t:this.time.compare(e.time)}toInstant(e){let t=this.date.toEpochDay(),n=(0, G.multiplyExact)(t,k.LocalTime.SECONDS_PER_DAY),r=(0, G.subtractExact)((0, G.addExact)(n,this.time.toSecondOfDay()),14*k.LocalTime.SECONDS_PER_HOUR),i=(0, G.addExact)(r,26*k.LocalTime.SECONDS_PER_HOUR),a=o.of(this.date,k.LocalTime.of(this.time.getHour(),this.time.getMinute(),this.time.getSecond())),s=new Date(r*k.LocalTime.MILLIS_PER_SECOND),p=o.fromZonedDate(s,e),c=Math.min(o.getTimeZoneMultiple(s,e.getId()),o.getTimeZoneMultiple(new Date(i*k.LocalTime.MILLIS_PER_SECOND),e.getId()));for(;!p.equals(a)&&(s.setTime((0, G.addExact)(s.getTime(),c*k.LocalTime.MILLIS_PER_SECOND)),p=o.fromZonedDate(s,e),!p.isAfter(a)););let l=(0, G.intDiv)(s.getTime(),k.LocalTime.MILLIS_PER_SECOND),m=this.time.getNano();return Bc.Instant.ofEpochSecond(l,m)}static getTimeZoneMultiple(e,t){let n=Math.abs(o.getTimeZoneOffset(e,t));return n%k.LocalTime.SECONDS_PER_HOUR===0?k.LocalTime.SECONDS_PER_HOUR:n%(k.LocalTime.SECONDS_PER_HOUR/2)===0?k.LocalTime.SECONDS_PER_HOUR/2:k.LocalTime.SECONDS_PER_HOUR/4}static getTimeZoneOffset(e,t){let r=new Intl.DateTimeFormat("sv-SE",{timeZone:t,calendar:"iso8601",timeZoneName:"short"}).format(e).match(/GMT([+-]\d+)(?::(\d+))?/),i=Number.parseInt(r?.[1]??"0",10),a=Number.parseInt(r?.[2]??"0",10);return i*k.LocalTime.SECONDS_PER_HOUR+a*k.LocalTime.SECONDS_PER_MINUTE}toString(){return `${this.date.toString()}T${this.time.toString()}`}toJSON(){return this.toString()}};Un.LocalDateTime=ka;});var Gt=be(qn=>{Object.defineProperty(qn,"__esModule",{value:true});qn.Instant=void 0;var Yc=Ca(),Xc=Fn(),el=Aa(),F=Wn(),z=Kt(),le=class o{constructor(e,t){this.nanos=0,this.seconds=e,this.nanos=t;}static now(e=Yc.DefaultClockProvider.getClock()){return e.getInstant()}static fromDate(e){return o.ofEpochMilli(e.getTime())}static ofEpochMilli(e){if(!Number.isSafeInteger(e))throw new Error("The timestamp must be a safe integer.");let t=(0, z.floorDiv)(e,F.LocalTime.MILLIS_PER_SECOND),r=(0, z.floorMod)(e,F.LocalTime.MILLIS_PER_SECOND)*F.LocalTime.NANOS_PER_MILLI;return o.ofEpochSecond(t,r)}static ofEpochSecond(e,t=0){if(!Number.isSafeInteger(e)||!Number.isSafeInteger(t))throw new Error("The timestamp must be a safe integer.");if(e===0&&t===0)return o.EPOCH;if(e<o.MIN_SECOND||e>o.MAX_SECOND)throw new Error(`The value ${e} is out of the range [${o.MIN_SECOND} - ${o.MAX_SECOND}] of instant.`);let n=e,r=t;return t!==0&&(n=(0, z.addExact)(n,(0, z.floorDiv)(t,F.LocalTime.NANOS_PER_SECOND)),r=(0, z.floorMod)(t,F.LocalTime.NANOS_PER_SECOND)),new o(n,r)}static parse(e){let n=e.match(o.PATTERN)?.groups;if(n==null)throw new Error(`Unrecognized UTC ISO-8601 date-time string "${e}".`);let r=Xc.LocalDate.of(Number.parseInt(n.year,10),Number.parseInt(n.month,10),Number.parseInt(n.day,10)).toEpochDay(),i=F.LocalTime.of(Number.parseInt(n.hour,10),Number.parseInt(n.minute??"0",10),Number.parseInt(n.second??"0",10),Number.parseInt(n.fraction?.padEnd(9,"0")??"0",10)).toNanoOfDay();return o.ofEpochSecond((0, z.multiplyExact)(r,F.LocalTime.SECONDS_PER_DAY),i)}static compareAscending(e,t){return e.compare(t)}static compareDescending(e,t){return t.compare(e)}getSeconds(){return this.seconds}getNano(){return this.nanos}toEpochMillis(){if(this.seconds<0&&this.nanos>0){let n=(0, z.multiplyExact)(this.seconds+1,F.LocalTime.MILLIS_PER_SECOND),r=(0, z.intDiv)(this.nanos,F.LocalTime.NANOS_PER_MILLI)-F.LocalTime.MILLIS_PER_SECOND;return (0, z.addExact)(n,r)}let e=(0, z.multiplyExact)(this.seconds,F.LocalTime.MILLIS_PER_SECOND),t=(0, z.intDiv)(this.nanos,F.LocalTime.NANOS_PER_MILLI);return (0, z.addExact)(e,t)}toDate(){return new Date(this.toEpochMillis())}toString(){let e=this.seconds%12622780800,t=el.LocalDateTime.ofEpochSecond(e,this.nanos),n=t.getYear()+(0, z.intDiv)(this.seconds,146097*86400)*400,r="";n<0?r="-":n>9999&&(r="+");let a=r+Math.abs(n).toString().padStart(4,"0")+t.toString().slice(4);return t.getSecond()===0&&t.getNano()===0&&(a+=":00"),a+="Z",a}toJSON(){return this.toString()}equals(e){return this.seconds===e.seconds&&this.nanos===e.nanos}plusDays(e){if(e===0)return this;let t=(0, z.multiplyExact)(e,F.LocalTime.SECONDS_PER_DAY);return this.plusSeconds(t)}minusDays(e){if(e===0)return this;let t=(0, z.multiplyExact)(e,F.LocalTime.SECONDS_PER_DAY);return this.minusSeconds(t)}plusHours(e){if(e===0)return this;let t=(0, z.multiplyExact)(e,F.LocalTime.SECONDS_PER_HOUR);return this.plusSeconds(t)}minusHours(e){if(e===0)return this;let t=(0, z.multiplyExact)(e,F.LocalTime.SECONDS_PER_HOUR);return this.minusSeconds(t)}plusMinutes(e){if(e===0)return this;let t=(0, z.multiplyExact)(e,F.LocalTime.SECONDS_PER_MINUTE);return this.plusSeconds(t)}minusMinutes(e){if(e===0)return this;let t=(0, z.multiplyExact)(e,F.LocalTime.SECONDS_PER_MINUTE);return this.minusSeconds(t)}plusSeconds(e){return e===0?this:o.ofEpochSecond((0, z.addExact)(this.seconds,e),this.nanos)}minusSeconds(e){return e===0?this:o.ofEpochSecond((0, z.subtractExact)(this.seconds,e),this.nanos)}plusMillis(e){if(e===0)return this;let t=(0, z.intDiv)(e,F.LocalTime.MILLIS_PER_SECOND),n=(0, z.addExact)(this.seconds,t),r=e%F.LocalTime.MILLIS_PER_SECOND,i=this.nanos+r*F.LocalTime.NANOS_PER_MILLI;return o.ofEpochSecond(n,i)}minusMillis(e){return this.plusMillis(-e)}plusMicros(e){if(e===0)return this;let t=(0, z.intDiv)(e,F.LocalTime.MICROS_PER_SECOND),n=(0, z.addExact)(this.seconds,t),r=e%F.LocalTime.MICROS_PER_SECOND,i=this.nanos+r*F.LocalTime.NANOS_PER_MICRO;return o.ofEpochSecond(n,i)}minusMicros(e){return this.plusMicros(-e)}plusNanos(e){if(e===0)return this;let t=(0, z.intDiv)(e,F.LocalTime.NANOS_PER_SECOND),n=(0, z.addExact)(this.seconds,t),r=e%F.LocalTime.NANOS_PER_SECOND,i=this.nanos+r;return o.ofEpochSecond(n,i)}minusNanos(e){return this.plusNanos(-e)}isAfter(e){return this.compare(e)>0}isAfterOrEqual(e){return this.compare(e)>=0}isBefore(e){return this.compare(e)<0}static isValid(e){try{o.parse(e);}catch{return false}return true}isBeforeOrEqual(e){return this.compare(e)<=0}compare(e){return this.seconds!==e.seconds?this.seconds-e.seconds:this.nanos-e.nanos}};qn.Instant=le;le.EPOCH=new le(0,0);le.MIN_SECOND=-31619087596800;le.MIN=new le(le.MIN_SECOND,0);le.MAX_SECOND=31494784780799;le.MAX=new le(le.MAX_SECOND,999999999);le.PATTERN=/^(?<year>[+-]?\d{4,19})-(?<month>\d{2})-(?<day>\d{2})T(?<hour>\d{2})(?::(?<minute>\d{2})(:(?<second>\d{2})(?:.(?<fraction>\d{1,9}))?)?)?Z$/;});var ys=be(Hn=>{Object.defineProperty(Hn,"__esModule",{value:true});Hn.Weekday=void 0;var fs;(function(o){o.SUNDAY="SUNDAY",o.MONDAY="MONDAY",o.TUESDAY="TUESDAY",o.WEDNESDAY="WEDNESDAY",o.THURSDAY="THURSDAY",o.FRIDAY="FRIDAY",o.SATURDAY="SATURDAY";})(fs||(Hn.Weekday=fs={}));});var hs=be(Gn=>{Object.defineProperty(Gn,"__esModule",{value:true});Gn.TimeInterval=void 0;var yt=Gt(),Ea=class o{constructor(e,t){this.start=e,this.end=t;}static all(){return new o(yt.Instant.MIN,yt.Instant.MAX)}static between(e,t){if(t.isBefore(e))throw new Error("The end instant must be equal or after start instant.");return new o(e,t)}static parse(e){let t=e.split("/");if(t.length!==2||t[0]===""||t[1]==="")throw new Error(`Malformed time interval "${e}".`);return o.between(yt.Instant.parse(t[0]),yt.Instant.parse(t[1]))}static startingAt(e){return o.all().withStart(e)}static endingAt(e){return o.all().withEnd(e)}withStart(e){return o.between(e,this.end)}withEnd(e){return o.between(this.start,e)}getStart(){return this.start}getEnd(){return this.end}isEmpty(){return this.start.equals(this.end)}isUnboundedStart(){return this.start.equals(yt.Instant.MIN)}isUnboundedEnd(){return this.end.equals(yt.Instant.MAX)}encloses(e){return this.start.isBeforeOrEqual(e.start)&&this.end.isAfterOrEqual(e.end)}abuts(e){return this.start.equals(e.end)||this.end.equals(e.start)}isConnected(e){return this.equals(e)||this.start.isBeforeOrEqual(e.end)&&this.end.isAfterOrEqual(e.start)}overlaps(e){return this.equals(e)||this.start.isBefore(e.end)&&this.end.isAfter(e.start)}intersection(e){if(!this.isConnected(e))throw new Error("The intervals are not connected.");return this.start.isAfterOrEqual(e.start)&&this.end.isBefore(e.end)?this:e.start.isAfterOrEqual(this.start)&&e.end.isBeforeOrEqual(this.end)?e:o.between(this.start.isAfterOrEqual(e.start)?this.start:e.start,this.end.isBeforeOrEqual(e.end)?this.end:e.end)}union(e){if(!this.isConnected(e))throw new Error("The intervals are not connected.");return this.start.isAfterOrEqual(e.start)&&this.end.isBefore(e.end)?e:e.start.isAfterOrEqual(this.start)&&e.end.isBeforeOrEqual(this.end)?this:o.between(this.start.isAfterOrEqual(e.start)?e.start:this.start,this.end.isBeforeOrEqual(e.end)?e.end:this.end)}span(e){return o.between(this.start.isAfterOrEqual(e.start)?e.start:this.start,this.end.isBeforeOrEqual(e.end)?e.end:this.end)}isAfter(e){return this.start.isAfterOrEqual(e.end)&&!this.equals(e)}isBefore(e){return this.end.isBeforeOrEqual(e.start)&&!this.equals(e)}static isValid(e){try{o.parse(e);}catch{return false}return true}startsBefore(e){return this.start.isBefore(e)}startsAtOrBefore(e){return this.start.isBeforeOrEqual(e)}startsAfter(e){return this.start.isAfter(e)}startsAtOrAfter(e){return this.start.isAfterOrEqual(e)}endsBefore(e){return this.end.isBefore(e)}endsAtOrBefore(e){return this.end.isBeforeOrEqual(e)}endsAfter(e){return this.end.isAfter(e)}endsAtOrAfter(e){return this.end.isAfterOrEqual(e)}contains(e){return this.start.isBeforeOrEqual(e)&&this.end.isAfter(e)}equals(e){return e instanceof o&&this.start.equals(e.start)&&this.end.equals(e.end)}toString(){return `${this.start.toString()}/${this.end.toString()}`}toJSON(){return this.toString()}};Gn.TimeInterval=Ea;});var Zt=be(X=>{Object.defineProperty(X,"__esModule",{value:true});X.TimeInterval=X.TimeZone=X.LocalDateTime=X.LocalTime=X.LocalDate=X.Weekday=X.Instant=void 0;var tl=Gt();Object.defineProperty(X,"Instant",{enumerable:true,get:function(){return tl.Instant}});var nl=ys();Object.defineProperty(X,"Weekday",{enumerable:true,get:function(){return nl.Weekday}});var rl=Fn();Object.defineProperty(X,"LocalDate",{enumerable:true,get:function(){return rl.LocalDate}});var il=Wn();Object.defineProperty(X,"LocalTime",{enumerable:true,get:function(){return il.LocalTime}});var ol=Aa();Object.defineProperty(X,"LocalDateTime",{enumerable:true,get:function(){return ol.LocalDateTime}});var al=va();Object.defineProperty(X,"TimeZone",{enumerable:true,get:function(){return al.TimeZone}});var sl=hs();Object.defineProperty(X,"TimeInterval",{enumerable:true,get:function(){return sl.TimeInterval}});});var cs=ft(ps()),{program:ld,createCommand:ud,createArgument:md,createOption:dd,CommanderError:gd,InvalidArgumentError:Fe,InvalidOptionArgumentError:fd,Command:ls,Argument:us,Option:oe,Help:yd}=cs.default;var gt=ft(Zt()),Dc=ft(Pa());var Kn=class{constructor(e){this.configuration=e;}prompt(e){return this.interact({type:e.type==="password"?"invisible":"text",message:e.message,initial:e.default,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=>({title:n.label,value:n.value,disabled:n.disabled})),initial:t===-1?void 0:t})}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=>({title:t.label,value:t.value,disabled:t.disabled,selected:t.selected}))})}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,a=false;return this.interact({type:"invisible",message:e.message,validate:s=>i===void 0||s===i?true:r,onState:function(p){if(!a){if(p.value===""){this.error&&e.key!==t.enter&&this.bell();return}i===void 0||p.value===i?(a=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={name:"value",...e,stdin:this.configuration.input,stdout:this.configuration.output,onState:function(s){e.onState?.apply(this,[s]),s.aborted&&(n.write("\x1B[?25h"),n.write(`
4
+ `),r());}};try{return await pl(i,t).then(a=>a.value)}finally{this.configuration.onInteractionEnd?.();}}};var tt=cl(),Jt={neutral:"cyan",info:"blue",error:"red",warning:"yellow",success:"green"},gl={neutral:tt?"\u279C":">",info:tt?"\u2139":"i",error:tt?"\u2718":"\xD7",warning:tt?"\u26A0":"\u203C",success:tt?"\u2714":"\u221A"};function ee(o,e={}){let t=e.basic===true?o:fl(o);if(tt||(t=strip(t)),e.text!==void 0&&(t=nt[Jt[e.text]](t)),e.icon!==void 0){let{semantic:n,symbol:r}=e.icon;t=r!==void 0?`${nt[Jt[n]](r[tt?"unicode":"ascii"])} ${t}`:`${nt[Jt[n]](gl[n])} ${t}`;}return t}function fl(o){return render(o,{fragment:e=>e.children.join(""),text:e=>e.content,bold:e=>nt.bold(e.children),italic:e=>nt.italic(e.children),strike:e=>nt.strikethrough(e.children),code:e=>nt.cyan(e.content),link:e=>ul(e.children,e.href,{fallback:(t,n)=>`${t} (${n})`}),image:e=>unescape(e.source),paragraph:e=>`${e.children.join("")}
4
5
 
5
- `}).trim()}var Us=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"].map(o=>ct__default.default.cyan(o)),Xa=class o{constructor(e,t,n={}){this.tasks=[];this.interval=null;this.promise=null;this.active=false;this.frame=0;this.lineCount=0;this.output=t,this.options=n,this.tasks=e.map(r=>({title:r.title,subtitle:r.subtitle,status:"pending",task:r.task}));}suspend(){this.active&&(this.stopRendering(true),Ya__default.default.show());}stop(e){this.active&&(this.active=false,this.stopRendering(e!==void 0?!e:this.options.clear===true),Ya__default.default.show(),this.options.onStop?.(this));}start(){return this.promise!==null&&!this.active?this.promise:(this.promise===null&&(this.active=true,this.promise=this.execute()),this.active&&(Ya__default.default.hide(),this.resumeRendering()),this.promise)}async execute(){try{await(this.options.concurrent===!0?Promise.all(this.tasks.map(e=>this.startTask(e))):this.tasks.reduce((e,t)=>e.then(()=>this.startTask(t)),Promise.resolve())),this.options.manual!==!0&&this.stop();}catch(e){throw this.stop(),e}}startTask(e){return this.updateTask(e,{status:"loading"}),e.task({confirm:(t,n)=>this.updateTask(e,{status:"success",title:t,subtitle:n}),alert:(t,n)=>this.updateTask(e,{status:"error",title:t,subtitle:n}),warn:(t,n)=>this.updateTask(e,{status:"warning",title:t,subtitle:n}),update:(t,n)=>this.updateTask(e,{status:"loading",title:t,subtitle:n})})}setStatus(e,t){if(!this.active)throw new Error("Cannot update task status once the task is finished");this.updateTask(this.tasks[e],t);}updateTask(e,t){e.status=t.status,t.title!==void 0&&(e.title=t.title),e.subtitle=t.subtitle;}stopRendering(e){this.interval!==null&&(clearInterval(this.interval),this.interval=null,this.clear(),e||this.render());}resumeRendering(){this.render(),this.interval=setInterval(()=>{this.frame++,this.clear(),this.render();},80);}clear(){for(let e=0;e<this.lineCount;e++)Vs__default.default.moveCursor(this.output,0,-1),Vs__default.default.clearLine(this.output,0);this.lineCount=0;}render(){this.lineCount=0;let e=this.output instanceof tty.WriteStream?this.output.columns:0;for(let t of this.tasks){let n=this.formatTask(t),r=n.split(`
6
+ `}).trim()}var bs=["\u280B","\u2819","\u2839","\u2838","\u283C","\u2834","\u2826","\u2827","\u2807","\u280F"].map(o=>nt.cyan(o)),Ta=class o{constructor(e,t,n={}){this.tasks=[];this.interval=null;this.promise=null;this.active=false;this.frame=0;this.lineCount=0;this.output=t,this.options=n,this.tasks=e.map(r=>({title:r.title,subtitle:r.subtitle,status:"pending",task:r.task}));}suspend(){this.active&&(this.stopRendering(true),Ra.show());}stop(e){this.active&&(this.active=false,this.stopRendering(e!==void 0?!e:this.options.clear===true),Ra.show(),this.options.onStop?.(this));}start(){return this.promise!==null&&!this.active?this.promise:(this.promise===null&&(this.active=true,this.promise=this.execute()),this.active&&(Ra.hide(),this.resumeRendering()),this.promise)}async execute(){try{await(this.options.concurrent===!0?Promise.all(this.tasks.map(e=>this.startTask(e))):this.tasks.reduce((e,t)=>e.then(()=>this.startTask(t)),Promise.resolve())),this.options.manual!==!0&&this.stop();}catch(e){throw this.stop(),e}}startTask(e){return this.updateTask(e,{status:"loading"}),e.task({confirm:(t,n)=>this.updateTask(e,{status:"success",title:t,subtitle:n}),alert:(t,n)=>this.updateTask(e,{status:"error",title:t,subtitle:n}),warn:(t,n)=>this.updateTask(e,{status:"warning",title:t,subtitle:n}),update:(t,n)=>this.updateTask(e,{status:"loading",title:t,subtitle:n})})}setStatus(e,t){if(!this.active)throw new Error("Cannot update task status once the task is finished");this.updateTask(this.tasks[e],t);}updateTask(e,t){e.status=t.status,t.title!==void 0&&(e.title=t.title),e.subtitle=t.subtitle;}stopRendering(e){this.interval!==null&&(clearInterval(this.interval),this.interval=null,this.clear(),e||this.render());}resumeRendering(){this.render(),this.interval=setInterval(()=>{this.frame++,this.clear(),this.render();},80);}clear(){for(let e=0;e<this.lineCount;e++)Ss.moveCursor(this.output,0,-1),Ss.clearLine(this.output,0);this.lineCount=0;}render(){this.lineCount=0;let e=this.output instanceof WriteStream?this.output.columns:0;for(let t of this.tasks){let n=this.formatTask(t),r=n.split(`
6
7
  `).map(i=>e===0?1:Math.ceil([...i].length/e));this.lineCount+=r.reduce((i,a)=>i+a,0),this.output.write(`${n}
7
- `);}}formatTask(e){let t=o.getSemantic(e.status),n=e.status==="loading"?`${Us[this.frame%Us.length]} ${te(e.title)}`:te(e.title,{icon:{semantic:t,symbol:e.status==="pending"?{unicode:"\u25F7",ascii:"\u25A0"}:void 0}});return e.subtitle!==void 0&&(n+=`
8
- ${te(e.subtitle,{text:t,icon:{semantic:t,symbol:{unicode:"\u21B3",ascii:"\u203A"}}})}`),n}static getSemantic(e){return e==="loading"||e==="pending"?"neutral":e}},ur=class{constructor(e){this.watchers=[];this.output=e;}suspend(){for(let e of this.watchers)e.suspend();}stop(e){for(let t of this.watchers)t.stop(e);}resume(){this.watchers[this.watchers.length-1]?.start();}notify(e){let t=this.addWatcher({tasks:[{title:e,task:()=>Promise.resolve()}]},{manual:true});return t.start(),{stop:(n=false)=>{t.stop(n);},update:(n,r)=>{t.setStatus(0,{status:"loading",title:n,subtitle:r});},confirm:(n,r)=>{t.setStatus(0,{status:"success",title:n,subtitle:r}),t.stop(true);},alert:(n,r)=>{t.setStatus(0,{status:"error",title:n,subtitle:r}),t.stop(true);},warn:(n,r)=>{t.setStatus(0,{status:"warning",title:n,subtitle:r}),t.stop(true);}}}monitor(e){let t=this.addWatcher(e),n=t.start();return {wait:()=>n,stop:()=>t.stop()}}addWatcher(e,t={}){for(let r of this.watchers)r.suspend();let n=new Xa(e.tasks,this.output,{clear:e.clear,concurrent:e.concurrent,...t,onStop:r=>this.removeWatcher(r)});return this.watchers.push(n),n}removeWatcher(e){let t=this.watchers.indexOf(e),n=t===this.watchers.length-1;this.watchers.splice(t,1),n&&this.resume();}};var mr=class{constructor(e){this.notifiers=[];this.stopped=false;this.output=e;}suspend(){this.stop();}stop(){this.notifiers.forEach(e=>{e.stopped=true;});}resume(){this.notifiers.forEach(e=>{e.stopped=false;});}monitor(e){let t=e.tasks.map(r=>this.notify(r.title,e.clear)),n=e.concurrent===true?Promise.all(e.tasks.map((r,i)=>r.task(t[i]))):e.tasks.reduce((r,i,a)=>r.then(()=>i.task(t[a])),Promise.resolve());return {stop:()=>{t.forEach(r=>r.stop(false));},wait:()=>n.then(()=>{})}}notify(e,t=false){let n=(i,a,s,p=!t)=>{!this.stopped&&!r.stopped&&p&&this.log(i??r.lastStatus,a??r.latestDetails,s);let c=this.notifiers.indexOf(r);c!==-1&&this.notifiers.splice(c,1);},r={stopped:false,lastStatus:e,latestDetails:void 0,stop:(i=false)=>{n(r.lastStatus,r.latestDetails,"neutral",i);},update:(i,a)=>{r.lastStatus=i??r.lastStatus,r.latestDetails=a;},confirm:(i,a)=>{n(i,a,"success");},alert:(i,a)=>{n(i,a,"error");},warn:(i,a)=>{n(i,a,"warning");}};return this.notifiers.push(r),r}log(e,t,n){this.output.write(`${this.format(e,t,n)}
9
- `);}format(e,t,n="neutral"){let r=te(e,{icon:{semantic:n}});return t!==void 0&&(r+=`
10
- ${te(t,{text:n,icon:{semantic:n,symbol:{unicode:"\u21B3",ascii:"\u203A"}}})}`),r}};var pn=class{constructor(e){this.output=e.output,this.onExit=e.onExit,this.quiet=e.quiet??false,this.formatter=e.formatter,this.linkOpener=e.linkOpener,this.taskMonitor=(e.interactive??true)&&!this.quiet?new ur(this.output):new mr(this.quiet?new stream.PassThrough:this.output);}suspend(){this.taskMonitor.suspend();}resume(){this.taskMonitor.resume();}stop(){this.taskMonitor.stop(false);}async open(e){await this.linkOpener(e);}break(){this.write(`
8
+ `);}}formatTask(e){let t=o.getSemantic(e.status),n=e.status==="loading"?`${bs[this.frame%bs.length]} ${ee(e.title)}`:ee(e.title,{icon:{semantic:t,symbol:e.status==="pending"?{unicode:"\u25F7",ascii:"\u25A0"}:void 0}});return e.subtitle!==void 0&&(n+=`
9
+ ${ee(e.subtitle,{text:t,icon:{semantic:t,symbol:{unicode:"\u21B3",ascii:"\u203A"}}})}`),n}static getSemantic(e){return e==="loading"||e==="pending"?"neutral":e}},Zn=class{constructor(e){this.watchers=[];this.output=e;}suspend(){for(let e of this.watchers)e.suspend();}stop(e){for(let t of this.watchers)t.stop(e);}resume(){this.watchers[this.watchers.length-1]?.start();}notify(e){let t=this.addWatcher({tasks:[{title:e,task:()=>Promise.resolve()}]},{manual:true});return t.start(),{stop:(n=false)=>{t.stop(n);},update:(n,r)=>{t.setStatus(0,{status:"loading",title:n,subtitle:r});},confirm:(n,r)=>{t.setStatus(0,{status:"success",title:n,subtitle:r}),t.stop(true);},alert:(n,r)=>{t.setStatus(0,{status:"error",title:n,subtitle:r}),t.stop(true);},warn:(n,r)=>{t.setStatus(0,{status:"warning",title:n,subtitle:r}),t.stop(true);}}}monitor(e){let t=this.addWatcher(e),n=t.start();return {wait:()=>n,stop:()=>t.stop()}}addWatcher(e,t={}){for(let r of this.watchers)r.suspend();let n=new Ta(e.tasks,this.output,{clear:e.clear,concurrent:e.concurrent,...t,onStop:r=>this.removeWatcher(r)});return this.watchers.push(n),n}removeWatcher(e){let t=this.watchers.indexOf(e),n=t===this.watchers.length-1;this.watchers.splice(t,1),n&&this.resume();}};var Jn=class{constructor(e){this.notifiers=[];this.stopped=false;this.output=e;}suspend(){this.stop();}stop(){this.notifiers.forEach(e=>{e.stopped=true;});}resume(){this.notifiers.forEach(e=>{e.stopped=false;});}monitor(e){let t=e.tasks.map(r=>this.notify(r.title,e.clear)),n=e.concurrent===true?Promise.all(e.tasks.map((r,i)=>r.task(t[i]))):e.tasks.reduce((r,i,a)=>r.then(()=>i.task(t[a])),Promise.resolve());return {stop:()=>{t.forEach(r=>r.stop(false));},wait:()=>n.then(()=>{})}}notify(e,t=false){let n=(i,a,s,p=!t)=>{!this.stopped&&!r.stopped&&p&&this.log(i??r.lastStatus,a??r.latestDetails,s);let c=this.notifiers.indexOf(r);c!==-1&&this.notifiers.splice(c,1);},r={stopped:false,lastStatus:e,latestDetails:void 0,stop:(i=false)=>{n(r.lastStatus,r.latestDetails,"neutral",i);},update:(i,a)=>{r.lastStatus=i??r.lastStatus,r.latestDetails=a;},confirm:(i,a)=>{n(i,a,"success");},alert:(i,a)=>{n(i,a,"error");},warn:(i,a)=>{n(i,a,"warning");}};return this.notifiers.push(r),r}log(e,t,n){this.output.write(`${this.format(e,t,n)}
10
+ `);}format(e,t,n="neutral"){let r=ee(e,{icon:{semantic:n}});return t!==void 0&&(r+=`
11
+ ${ee(t,{text:n,icon:{semantic:n,symbol:{unicode:"\u21B3",ascii:"\u203A"}}})}`),r}};var Qt=class{constructor(e){this.output=e.output,this.onExit=e.onExit,this.quiet=e.quiet??false,this.formatter=e.formatter,this.linkOpener=e.linkOpener,this.taskMonitor=(e.interactive??true)&&!this.quiet?new Zn(this.output):new Jn(this.quiet?new PassThrough:this.output);}suspend(){this.taskMonitor.suspend();}resume(){this.taskMonitor.resume();}stop(){this.taskMonitor.stop(false);}async open(e){await this.linkOpener(e);}break(){this.write(`
11
12
  `);}announce(e){this.write(`${this.formatter.formatCallout(e)}
12
13
  `);}log(e,t){this.writeLog(e,t??"neutral");}confirm(e){this.writeLog(e,"success");}inform(e){this.writeLog(e,"info");}warn(e){this.writeLog(e,"warning");}alert(e){this.writeLog(e,"error");}debug(e){this.writeLog(e,"neutral");}notify(e){return this.taskMonitor.notify(e)}monitor(e){return typeof e=="function"?new Promise((t,n)=>{let r=this.taskMonitor.monitor(e(t,i=>{r.stop(),n(i);}));}):this.taskMonitor.monitor(e).wait()}report(e){this.stop(),this.write(`${this.formatter.formatError(e)}
13
- `,true);}exit(){return this.stop(),this.onExit()}writeLog(e,t){this.write(`${te(e,t==="neutral"?{}:{icon:{semantic:t}})}
14
- `);}write(e,t=false){(!this.quiet||t)&&(this.suspend(),this.output.write(e),this.resume());}};var d=class o extends Error{constructor(e,t={}){super(e),this.help=t,this.reason=t.reason??"other",Object.setPrototypeOf(this,o.prototype);}static formatMessage(e){let t=o.extractMessage(e).trim();return t.length===0?t:t.charAt(0).toUpperCase()+t.slice(1)+(/^[^\n.]+$/.test(t)?".":"")}static formatCause(e){let t=o.formatMessage(e);return t.length===0?t:t.charAt(0).toLowerCase()+t.slice(1)}static extractMessage(e){return e instanceof Error?e.message:typeof e=="string"&&e!==""?e:"unknown error"}static describeType(e){switch(true){case e===null:return "null";case typeof e=="object":return e.constructor.name!=="Object"?e.constructor.name:"object";default:return typeof e}}};var Y=class o extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var O=class o{constructor(e,t,n){this.min=t,this.max=n,this.versions=e??[];}static isValid(e){try{return o.parse(e),!0}catch{return false}}static between(e,t){if(e===t)return new o([e]);if(e>t)throw new Error(`Out of order range ${e}-${t}`);return new o(void 0,e,t)}static of(e){return new o([e])}static either(...e){if(e.length===0)throw new Error("No versions specified.");return new o([...new Set(e)].sort((t,n)=>t-n))}static parse(e){if(/^\d+$/.test(e))return new o([Number.parseInt(e,10)]);let{groups:t}=e.match(/^((?<range>(?<min>\d+)\s*-\s*(?<max>\d+))|(?<set>\d+(\s*,\s*\d+)+))$/)??{};if(t===void 0)throw new Error(`Invalid version pattern: ${e}`);return t.range!==void 0?o.between(Number.parseInt(t.min,10),Number.parseInt(t.max,10)):o.either(...t.set.split(",").map(n=>Number.parseInt(n,10)))}isRange(){return this.min!==void 0&&this.max!==void 0}isSet(){return this.versions.length>0}isExact(){return this.versions.length===1}getCardinality(){return this.min!==void 0&&this.max!==void 0?this.max-this.min+1:this.versions.length}getExactVersion(){if(!this.isExact())throw new Error("Not an exact version.");return this.versions[0]}getMinVersion(){return this.min??Math.min(...this.versions)}getMaxVersion(){return this.max??Math.max(...this.versions)}getVersions(){let{min:e,max:t}=this;if(e===void 0||t===void 0)return this.versions;let n=[];for(let r=e;r<=t;r++)n.push(r);return n}intersects(e){if(e.isRange())return e.intersects(this);if(this.isRange()){if(e.isRange())return this.getMinVersion()<=e.getMaxVersion()&&e.getMinVersion()<=this.getMaxVersion();if(e.isExact()){let a=e.getExactVersion();return this.getMinVersion()<=a&&a<=this.getMaxVersion()}let r=this.getMinVersion(),i=this.getMaxVersion();return e.getVersions().some(a=>r<=a&&a<=i)}let t=this.getVersions(),n=e.getVersions();return t.length===0||n.length===0?false:t.some(r=>n.includes(r))}contains(e){if(this.isExact()&&e.isExact())return this.getExactVersion()===e.getExactVersion();if(this.isRange()){if(e.isRange())return this.getMinVersion()<=e.getMinVersion()&&e.getMaxVersion()<=this.getMaxVersion();if(e.isExact()){let i=e.getExactVersion();return this.getMinVersion()<=i&&i<=this.getMaxVersion()}let n=this.getMinVersion(),r=this.getMaxVersion();return e.getVersions().every(i=>n<=i&&i<=r)}if(!e.isSet())return false;let t=this.getVersions();return e.getVersions().every(n=>t.includes(n))}without(e){if(!this.intersects(e))return this;if(e.contains(this))throw new Error("A version cannot be empty.");if(this.isRange()){if(e.isExact()){if(this.getMinVersion()===e.getExactVersion())return o.between(e.getExactVersion()+1,this.getMaxVersion());if(this.getMaxVersion()===e.getExactVersion())return o.between(this.getMinVersion(),e.getExactVersion()-1)}else if(e.isRange()){if(this.getMinVersion()===e.getMinVersion())return o.between(e.getMaxVersion()+1,this.getMaxVersion());if(this.getMaxVersion()===e.getMaxVersion())return o.between(this.getMinVersion(),e.getMinVersion()-1)}else if(e.isSet()&&e.getVersions().every((i,a)=>i===e.getMinVersion()+a)){if(this.getMinVersion()===e.getMinVersion())return o.between(e.getMaxVersion()+1,this.getMaxVersion());if(this.getMaxVersion()===e.getMaxVersion())return o.between(this.getMinVersion(),e.getMinVersion()-1)}}if(e.isRange()){let n=e.getMinVersion(),r=e.getMaxVersion();return o.either(...this.getVersions().filter(i=>i<n||i>r))}let t=e.getVersions();return o.either(...this.getVersions().filter(n=>!t.includes(n)))}with(e){if(this.contains(e))return this;if(e.isRange())return e.with(this);if(this.isRange()){if(e.isExact()){if(this.getMaxVersion()+1===e.getExactVersion())return o.between(this.getMinVersion(),e.getExactVersion());if(e.getExactVersion()+1===this.getMinVersion())return o.between(e.getExactVersion(),this.getMaxVersion())}else if(e.isRange()){if(this.getMaxVersion()+1===e.getMinVersion()||e.getMaxVersion()+1===this.getMinVersion())return o.between(Math.min(this.getMinVersion(),e.getMinVersion()),Math.max(this.getMaxVersion(),e.getMaxVersion()))}else if(e.isSet()&&this.contains(this))return this}return o.either(...this.getVersions(),...e.getVersions())}equals(e){if(e.min!==this.min||e.max!==this.max||e.versions.length!==this.versions.length)return false;for(let t=0;t<this.versions.length;t++)if(this.versions[t]!==e.versions[t])return false;return true}toString(){return this.isSet()?this.versions.join(", "):`${this.min} - ${this.max}`}toJSON(){return this.toString()}};function pe(o,...e){let t=[];for(let i=0;i<o.length;i++)t.push(o[i]),i<e.length&&t.push(e[i]);let n=t.join("").split(`
14
+ `,true);}exit(){return this.stop(),this.onExit()}writeLog(e,t){this.write(`${ee(e,t==="neutral"?{}:{icon:{semantic:t}})}
15
+ `);}write(e,t=false){(!this.quiet||t)&&(this.suspend(),this.output.write(e),this.resume());}};var d=class o extends Error{constructor(e,t={}){super(e),this.help=t,this.reason=t.reason??"other",Object.setPrototypeOf(this,o.prototype);}static formatMessage(e){let t=o.extractMessage(e).trim();return t.length===0?t:t.charAt(0).toUpperCase()+t.slice(1)+(/^[^\n.]+$/.test(t)?".":"")}static formatCause(e){let t=o.formatMessage(e);return t.length===0?t:t.charAt(0).toLowerCase()+t.slice(1)}static extractMessage(e){return e instanceof Error?e.message:typeof e=="string"&&e!==""?e:"unknown error"}static describeType(e){switch(true){case e===null:return "null";case typeof e=="object":return e.constructor.name!=="Object"?e.constructor.name:"object";default:return typeof e}}};var B=class o extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var O=class o{constructor(e,t,n){this.min=t,this.max=n,this.versions=e??[];}static isValid(e){try{return o.parse(e),!0}catch{return false}}static between(e,t){if(e===t)return new o([e]);if(e>t)throw new Error(`Out of order range ${e}-${t}`);return new o(void 0,e,t)}static of(e){return new o([e])}static either(...e){if(e.length===0)throw new Error("No versions specified.");return new o([...new Set(e)].sort((t,n)=>t-n))}static parse(e){if(/^\d+$/.test(e))return new o([Number.parseInt(e,10)]);let{groups:t}=e.match(/^((?<range>(?<min>\d+)\s*-\s*(?<max>\d+))|(?<set>\d+(\s*,\s*\d+)+))$/)??{};if(t===void 0)throw new Error(`Invalid version pattern: ${e}`);return t.range!==void 0?o.between(Number.parseInt(t.min,10),Number.parseInt(t.max,10)):o.either(...t.set.split(",").map(n=>Number.parseInt(n,10)))}isRange(){return this.min!==void 0&&this.max!==void 0}isSet(){return this.versions.length>0}isExact(){return this.versions.length===1}getCardinality(){return this.min!==void 0&&this.max!==void 0?this.max-this.min+1:this.versions.length}getExactVersion(){if(!this.isExact())throw new Error("Not an exact version.");return this.versions[0]}getMinVersion(){return this.min??Math.min(...this.versions)}getMaxVersion(){return this.max??Math.max(...this.versions)}getVersions(){let{min:e,max:t}=this;if(e===void 0||t===void 0)return this.versions;let n=[];for(let r=e;r<=t;r++)n.push(r);return n}intersects(e){if(e.isRange())return e.intersects(this);if(this.isRange()){if(e.isRange())return this.getMinVersion()<=e.getMaxVersion()&&e.getMinVersion()<=this.getMaxVersion();if(e.isExact()){let a=e.getExactVersion();return this.getMinVersion()<=a&&a<=this.getMaxVersion()}let r=this.getMinVersion(),i=this.getMaxVersion();return e.getVersions().some(a=>r<=a&&a<=i)}let t=this.getVersions(),n=e.getVersions();return t.length===0||n.length===0?false:t.some(r=>n.includes(r))}contains(e){if(this.isExact()&&e.isExact())return this.getExactVersion()===e.getExactVersion();if(this.isRange()){if(e.isRange())return this.getMinVersion()<=e.getMinVersion()&&e.getMaxVersion()<=this.getMaxVersion();if(e.isExact()){let i=e.getExactVersion();return this.getMinVersion()<=i&&i<=this.getMaxVersion()}let n=this.getMinVersion(),r=this.getMaxVersion();return e.getVersions().every(i=>n<=i&&i<=r)}if(!e.isSet())return false;let t=this.getVersions();return e.getVersions().every(n=>t.includes(n))}without(e){if(!this.intersects(e))return this;if(e.contains(this))throw new Error("A version cannot be empty.");if(this.isRange()){if(e.isExact()){if(this.getMinVersion()===e.getExactVersion())return o.between(e.getExactVersion()+1,this.getMaxVersion());if(this.getMaxVersion()===e.getExactVersion())return o.between(this.getMinVersion(),e.getExactVersion()-1)}else if(e.isRange()){if(this.getMinVersion()===e.getMinVersion())return o.between(e.getMaxVersion()+1,this.getMaxVersion());if(this.getMaxVersion()===e.getMaxVersion())return o.between(this.getMinVersion(),e.getMinVersion()-1)}else if(e.isSet()&&e.getVersions().every((i,a)=>i===e.getMinVersion()+a)){if(this.getMinVersion()===e.getMinVersion())return o.between(e.getMaxVersion()+1,this.getMaxVersion());if(this.getMaxVersion()===e.getMaxVersion())return o.between(this.getMinVersion(),e.getMinVersion()-1)}}if(e.isRange()){let n=e.getMinVersion(),r=e.getMaxVersion();return o.either(...this.getVersions().filter(i=>i<n||i>r))}let t=e.getVersions();return o.either(...this.getVersions().filter(n=>!t.includes(n)))}with(e){if(this.contains(e))return this;if(e.isRange())return e.with(this);if(this.isRange()){if(e.isExact()){if(this.getMaxVersion()+1===e.getExactVersion())return o.between(this.getMinVersion(),e.getExactVersion());if(e.getExactVersion()+1===this.getMinVersion())return o.between(e.getExactVersion(),this.getMaxVersion())}else if(e.isRange()){if(this.getMaxVersion()+1===e.getMinVersion()||e.getMaxVersion()+1===this.getMinVersion())return o.between(Math.min(this.getMinVersion(),e.getMinVersion()),Math.max(this.getMaxVersion(),e.getMaxVersion()))}else if(e.isSet()&&this.contains(this))return this}return o.either(...this.getVersions(),...e.getVersions())}equals(e){if(e.min!==this.min||e.max!==this.max||e.versions.length!==this.versions.length)return false;for(let t=0;t<this.versions.length;t++)if(this.versions[t]!==e.versions[t])return false;return true}toString(){return this.isSet()?this.versions.join(", "):`${this.min} - ${this.max}`}toJSON(){return this.toString()}};function ae(o,...e){let t=[];for(let i=0;i<o.length;i++)t.push(o[i]),i<e.length&&t.push(e[i]);let n=t.join("").split(`
15
16
  `);if(n.length<2)return t.join("");let r=n[1].search(/\S/);return n.map(i=>i.slice(r)).join(`
16
- `).trim()}function Ct(o){return o.normalize("NFD").replace(/(^[^a-z]+|[^a-z0-9_ -]+)/ig,"").split(/[^a-z0-9]+/i).map((e,t)=>t===0?e.toLowerCase():e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}var lt=class lt{constructor(e){this.projectDirectory=e.projectDirectory,this.packageManager=e.packageManager,this.workspaceApi=e.workspaceApi,this.formatter=e.formatter,this.fileSystem=e.fileSystem,this.importConfigLoader=e.tsConfigLoader;}async generateSlotExample(e,t){let n=this.projectDirectory.get(),r=[];for(let i of await this.generateSlotExampleFiles(e,t)){let a=this.fileSystem.joinPaths(n,this.fileSystem.getDirectoryName(i.path));await this.fileSystem.createDirectory(a,{recursive:true}).catch(()=>null);let s=this.fileSystem.joinPaths(n,i.path);await this.fileSystem.writeTextFile(s,i.code,{overwrite:true}),r.push(s);}await this.formatter.format(r);}async setup(e){let{input:t,output:n}=e,r=await this.getInstallationPlan(e),i={...r.configuration,paths:{content:".",components:await this.resolvePath(["components","Components","component","Component"],r.configuration.paths.components),examples:await this.resolvePath(["examples","Examples"],r.configuration.paths.examples)}},a={...e,configuration:{...e.configuration,...i,applications:e.configuration.applications}},s=[];if(s.push({title:"Install dependencies",task:async p=>{p.update("Installing dependencies");try{await this.packageManager.addDependencies(["croct"],!0),await this.packageManager.addDependencies([...r.dependencies]),p.confirm("Dependencies installed");}catch(c){p.alert("Failed to install dependencies",d.formatMessage(c));}}}),s.push(...r.tasks),Object.keys(i.slots).length>0&&s.push({title:"Download content",task:async p=>{p.update("Downloading content");try{await this.updateContent(a,{notifier:p,clean:!0});}catch(c){p.alert("Failed to download content",d.formatMessage(c));}}}),await this.isTypeScriptProject()&&s.push({title:"Generate types",task:async p=>{p.update("Generating types");try{await this.updateTypes(a,{notifier:p,clean:!0});}catch(c){p.alert("Failed to generate types",d.formatMessage(c));}try{await this.registerTypeFile(Object.values(a.configuration.paths),p);}catch(c){p.alert("Failed to register type file",d.formatMessage(c));}}}),s.push({title:"Register script",task:async p=>{p.update("Registering script");try{await this.packageManager.addScript("postinstall","croct install --no-interaction"),p.confirm("Script registered");}catch(c){p.alert("Failed to register script",d.formatMessage(c));}}}),s.length>0){if(t!==void 0){n.break(),n.inform("**Installation plan**");for(let{title:p}of s)n.log(` - ${p}`);if(n.break(),!await t.confirm({message:"Proceed?",default:true}))return n.exit()}await n.monitor({tasks:s});}return i}async resolvePath(e,t){if(t!=="")return t;let n=["src"],r=await this.locateFile(...n.flatMap(i=>e.map(a=>this.fileSystem.joinPaths(i,a))),...e,...n);return r===null?e[0]:n.includes(r)?this.fileSystem.joinPaths(r,e[0]):r}async update(e,t={}){await this.updateContent(e,t),await this.isTypeScriptProject()&&await this.updateTypes(e,t);}async updateContent(e,t={}){let{output:n,configuration:r}=e,i=t.notifier??n.notify("Updating content");if(Object.entries(r.slots).length===0){i.confirm("No slots to update");return}let s=await this.mountContentPackageFolder();if(s===null){i.alert(`The package ${lt.CONTENT_PACKAGE} is not installed`);return}let p=this.fileSystem.joinPaths(s.directory,"slot");for await(let M of this.fileSystem.list(p,0))M.type==="directory"&&await this.fileSystem.delete(this.fileSystem.joinPaths(p,M.name),{recursive:true});let c={},l={},m={};for(let[M,j]of Object.entries(await this.loadContent(e,t.clean))){let T=Math.max(...j.map(({version:q})=>q));for(let{version:q,content:xe}of j)for(let[ce,Es]of Object.entries(xe)){let Xt=`${M}@${q}`;c[ce]===void 0&&(c[ce]={});let Va=`${Ct(`${M}-${ce}`)}V${q}`,Ua=`./${ce}/${Xt}`;m[ce]===void 0&&(m[ce]={}),c[ce][Xt]=Ua,m[ce][Xt]=`${Va}`,l[Va]=Ua,q===T&&(c[ce][M]=Ua,m[ce][M]=`${Va}`);let il=this.fileSystem.joinPaths(p,ce);await this.fileSystem.isDirectory(il)||await this.fileSystem.createDirectory(this.fileSystem.joinPaths(p,ce),{recursive:true}),await this.fileSystem.writeTextFile(this.fileSystem.joinPaths(p,ce,`${Xt}.js`),`export default ${JSON.stringify(Es,null,2)};`,{overwrite:true}),await this.fileSystem.writeTextFile(this.fileSystem.joinPaths(p,ce,`${Xt}.cjs`),`module.exports = ${JSON.stringify(Es,null,2)};`,{overwrite:true});}}let f=Object.entries(l).map(([M,j])=>`import ${M} from '${j}.js';`).join(`
17
+ `).trim()}function ht(o){return o.normalize("NFD").replace(/(^[^a-z]+|[^a-z0-9_ -]+)/ig,"").split(/[^a-z0-9]+/i).map((e,t)=>t===0?e.toLowerCase():e.charAt(0).toUpperCase()+e.slice(1).toLowerCase()).join("")}var He=class o{static{this.CONTENT_PACKAGE="@croct/content";}constructor(e){this.projectDirectory=e.projectDirectory,this.packageManager=e.packageManager,this.workspaceApi=e.workspaceApi,this.formatter=e.formatter,this.fileSystem=e.fileSystem,this.importConfigLoader=e.tsConfigLoader;}async generateSlotExample(e,t){let n=this.projectDirectory.get(),r=[];for(let i of await this.generateSlotExampleFiles(e,t)){let a=this.fileSystem.joinPaths(n,this.fileSystem.getDirectoryName(i.path));await this.fileSystem.createDirectory(a,{recursive:true}).catch(()=>null);let s=this.fileSystem.joinPaths(n,i.path);await this.fileSystem.writeTextFile(s,i.code,{overwrite:true}),r.push(s);}await this.formatter.format(r);}async setup(e){let{input:t,output:n}=e,r=await this.getInstallationPlan(e),i={...r.configuration,paths:{content:".",components:await this.resolvePath(["components","Components","component","Component"],r.configuration.paths.components),examples:await this.resolvePath(["examples","Examples"],r.configuration.paths.examples)}},a={...e,configuration:{...e.configuration,...i,applications:e.configuration.applications}},s=[];if(s.push({title:"Install dependencies",task:async p=>{p.update("Installing dependencies");try{await this.packageManager.addDependencies(["croct"],!0),await this.packageManager.addDependencies([...r.dependencies]),p.confirm("Dependencies installed");}catch(c){p.alert("Failed to install dependencies",d.formatMessage(c));}}}),s.push(...r.tasks),Object.keys(i.slots).length>0&&s.push({title:"Download content",task:async p=>{p.update("Downloading content");try{await this.updateContent(a,{notifier:p,clean:!0});}catch(c){p.alert("Failed to download content",d.formatMessage(c));}}}),await this.isTypeScriptProject()&&s.push({title:"Generate types",task:async p=>{p.update("Generating types");try{await this.updateTypes(a,{notifier:p,clean:!0});}catch(c){p.alert("Failed to generate types",d.formatMessage(c));}try{await this.registerTypeFile(Object.values(a.configuration.paths),p);}catch(c){p.alert("Failed to register type file",d.formatMessage(c));}}}),s.push({title:"Register script",task:async p=>{p.update("Registering script");try{await this.packageManager.addScript("postinstall","croct install --no-interaction"),p.confirm("Script registered");}catch(c){p.alert("Failed to register script",d.formatMessage(c));}}}),s.length>0){if(t!==void 0){n.break(),n.inform("**Installation plan**");for(let{title:p}of s)n.log(` - ${p}`);if(n.break(),!await t.confirm({message:"Proceed?",default:true}))return n.exit()}await n.monitor({tasks:s});}return i}async resolvePath(e,t){if(t!=="")return t;let n=["src"],r=await this.locateFile(...n.flatMap(i=>e.map(a=>this.fileSystem.joinPaths(i,a))),...e,...n);return r===null?e[0]:n.includes(r)?this.fileSystem.joinPaths(r,e[0]):r}async update(e,t={}){await this.updateContent(e,t),await this.isTypeScriptProject()&&await this.updateTypes(e,t);}async updateContent(e,t={}){let{output:n,configuration:r}=e,i=t.notifier??n.notify("Updating content");if(Object.entries(r.slots).length===0){i.confirm("No slots to update");return}let s=await this.mountContentPackageFolder();if(s===null){i.alert(`The package ${o.CONTENT_PACKAGE} is not installed`);return}let p=this.fileSystem.joinPaths(s.directory,"slot");for await(let M of this.fileSystem.list(p,0))M.type==="directory"&&await this.fileSystem.delete(this.fileSystem.joinPaths(p,M.name),{recursive:true});let c={},l={},m={};for(let[M,j]of Object.entries(await this.loadContent(e,t.clean))){let T=Math.max(...j.map(({version:q})=>q));for(let{version:q,content:Se}of j)for(let[se,as]of Object.entries(Se)){let Ut=`${M}@${q}`;c[se]===void 0&&(c[se]={});let ba=`${ht(`${M}-${se}`)}V${q}`,Ia=`./${se}/${Ut}`;m[se]===void 0&&(m[se]={}),c[se][Ut]=Ia,m[se][Ut]=`${ba}`,l[ba]=Ia,q===T&&(c[se][M]=Ia,m[se][M]=`${ba}`);let Nc=this.fileSystem.joinPaths(p,se);await this.fileSystem.isDirectory(Nc)||await this.fileSystem.createDirectory(this.fileSystem.joinPaths(p,se),{recursive:true}),await this.fileSystem.writeTextFile(this.fileSystem.joinPaths(p,se,`${Ut}.js`),`export default ${JSON.stringify(as,null,2)};`,{overwrite:true}),await this.fileSystem.writeTextFile(this.fileSystem.joinPaths(p,se,`${Ut}.cjs`),`module.exports = ${JSON.stringify(as,null,2)};`,{overwrite:true});}}let f=Object.entries(l).map(([M,j])=>`import ${M} from '${j}.js';`).join(`
17
18
  `),b=`const contentMap = ${JSON.stringify(m,null,2).replace(/(?<=: )"(.*?)"/g,"$1")};
18
19
 
19
20
  `;await this.fileSystem.writeTextFile(this.fileSystem.joinPaths(p,"getSlotContent.js"),`${f}
20
21
 
21
- ${b}`+pe`
22
+ ${b}`+ae`
22
23
  const defaultLocale = ${JSON.stringify(r.defaultLocale)};
23
24
 
24
25
  export function getSlotContent(slotId, language = defaultLocale) {
@@ -35,7 +36,7 @@ ${b}`+pe`
35
36
  `,{overwrite:true});let A=Object.entries(l).map(([M,j])=>`const ${M} = require('${j}.cjs');`).join(`
36
37
  `);await this.fileSystem.writeTextFile(this.fileSystem.joinPaths(p,"getSlotContent.cjs"),`${A}
37
38
 
38
- ${b}`+pe`
39
+ ${b}`+ae`
39
40
  const defaultLocale = ${JSON.stringify(r.defaultLocale)};
40
41
 
41
42
  module.exports = {
@@ -53,7 +54,7 @@ ${b}`+pe`
53
54
  };
54
55
  `,{overwrite:true});let w=`const contentMap = ${JSON.stringify(c,null,2).replace(/"(\.\/.*?)"/g,'() => import("$1.js")')};
55
56
 
56
- `;await this.fileSystem.writeTextFile(this.fileSystem.joinPaths(p,"loadSlotContent.js"),w+pe`
57
+ `;await this.fileSystem.writeTextFile(this.fileSystem.joinPaths(p,"loadSlotContent.js"),w+ae`
57
58
  const defaultLocale = ${JSON.stringify(r.defaultLocale)};
58
59
 
59
60
  export function loadSlotContent(slotId, language = defaultLocale) {
@@ -69,7 +70,7 @@ ${b}`+pe`
69
70
  }
70
71
  `,{overwrite:true});let y=`const contentMap = ${JSON.stringify(c,null,2).replace(/"(\.\/.*?)"/g,'() => Promise.resolve(require("$1.cjs"))')};
71
72
 
72
- `;await this.fileSystem.writeTextFile(this.fileSystem.joinPaths(p,"loadSlotContent.cjs"),y+pe`
73
+ `;await this.fileSystem.writeTextFile(this.fileSystem.joinPaths(p,"loadSlotContent.cjs"),y+ae`
73
74
  const defaultLocale = ${JSON.stringify(r.defaultLocale)};
74
75
 
75
76
  module.exports = {
@@ -85,13 +86,13 @@ ${b}`+pe`
85
86
  return Promise.resolve(null);
86
87
  }
87
88
  };
88
- `,{overwrite:true}),i.confirm("Content updated");}async loadContent(e,t=false){let{configuration:n}=e;if(n.paths.content===void 0)return this.loadRemoteContent(e);let r=this.fileSystem.joinPaths(n.paths.content,"slots.json");if(!t&&await this.fileSystem.exists(r))return this.loadLocalContent(r);let i=await this.loadRemoteContent(e);return await this.saveContent(i,r),i}async saveContent(e,t){let n=this.fileSystem.getDirectoryName(t);await this.fileSystem.createDirectory(n,{recursive:true}),await this.fileSystem.writeTextFile(t,JSON.stringify(e,null,2),{overwrite:true});}async loadLocalContent(e){let t;try{t=await this.fileSystem.readTextFile(e);}catch{return {}}try{return JSON.parse(t)}catch(n){throw new Y("Failed to parse content file.",{reason:"invalid_input",cause:n,details:[`File: ${e}`]})}}async loadRemoteContent(e){let t=await this.resolveVersions(e.configuration),n=Object.entries(t.slots),r={};for(let[i,a]of n)r[i]=O.parse(a).getVersions();return Object.fromEntries(await Promise.all(n.map(async([i])=>[i,await Promise.all(r[i].map(a=>this.workspaceApi.getSlotStaticContent({organizationSlug:t.organization,workspaceSlug:t.workspace,slotSlug:i},a).then(s=>({version:a,content:Object.fromEntries(s.map(({locale:p,content:c})=>[p,c]))}))))])))}async updateTypes(e,t={}){let{output:n,configuration:r}=e,i=t.notifier??n.notify("Updating types"),a=await this.mountContentPackageFolder();if(a===null){i.alert(`The package ${lt.CONTENT_PACKAGE} is not installed`);return}let s=this.getTypeFile(a.directory);await this.fileSystem.createDirectory(this.fileSystem.getDirectoryName(s),{recursive:true}).catch(()=>{});let p="export {};";(Object.keys(r.slots).length>0||Object.keys(r.components).length>0)&&(p=`${await this.generateTypes(r,t.clean)}
89
- ${p}`),await this.fileSystem.writeTextFile(s,p,{overwrite:true}),i.confirm("Types updated");}async generateTypes(e,t=false){if(e.paths.content===void 0)return this.generateTypeRemotely(e);let n=this.fileSystem.joinPaths(e.paths.content,"slots.ts.dist");if(!t&&await this.fileSystem.exists(n))return this.fileSystem.readTextFile(n);let r=await this.generateTypeRemotely(e);return await this.fileSystem.writeTextFile(n,r,{overwrite:true}),r}async generateTypeRemotely(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(([a,s])=>({id:a,version:s})),slots:Object.entries(i).map(([a,s])=>({id:a,version:s}))})}async registerTypeFile(e,t){let[n,r]=await Promise.all([this.getTypeScriptConfigPath(e),this.mountContentPackageFolder()]);if(n===null)throw new Y("TypeScript configuration not found");let i=this.projectDirectory.get();if(!this.fileSystem.isSubPath(i,n)){let p=this.fileSystem.getRelativePath(i,n);throw new Y(`TypeScript configuration is outside the project directory: \`${p}\``)}if(r===null)throw new Y(`Package ${lt.CONTENT_PACKAGE} is not installed`);let a=this.fileSystem.getRelativePath(this.fileSystem.getDirectoryName(n),this.getTypeFile(r.directory)).replace(/\\/g,"/"),s=json5Parser.JsonParser.parse(await this.fileSystem.readTextFile(n),json5Parser.JsonObjectNode);if(s.has("files")){let p=s.get("files",json5Parser.JsonArrayNode);if(p.toJSON().includes(a))return t.confirm("Type file already registered");p.push(a);}else s.set("files",[a]);await this.fileSystem.writeTextFile(n,s.toString(),{overwrite:true}),t.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([this.workspaceApi.getSlots({organizationSlug:e.organization,workspaceSlug:e.workspace}),this.workspaceApi.getComponents({organizationSlug:e.organization,workspaceSlug:e.workspace})]);return {...e,components:Object.fromEntries(Object.entries(e.components).flatMap(([a,s])=>{let p=O.parse(s).getVersions().filter(c=>i.some(l=>l.slug===a&&c<=l.version.major));return p.length===0?[]:[[a,O.either(...p).toString()]]})),slots:Object.fromEntries(Object.entries(e.slots).flatMap(([a,s])=>{let p=O.parse(s).getVersions().filter(c=>r.some(l=>l.slug===a&&c<=l.version.major));return p.length===0?[]:[[a,O.either(...p).toString()]]}))}}async mountContentPackageFolder(){let e=await this.packageManager.getDependency(lt.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 Y("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,"types.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}};lt.CONTENT_PACKAGE="@croct/content";var Qe=lt;var ze=class o{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+=`
89
+ `,{overwrite:true}),i.confirm("Content updated");}async loadContent(e,t=false){let{configuration:n}=e;if(n.paths.content===void 0)return this.loadRemoteContent(e);let r=this.fileSystem.joinPaths(n.paths.content,"slots.json");if(!t&&await this.fileSystem.exists(r))return this.loadLocalContent(r);let i=await this.loadRemoteContent(e);return await this.saveContent(i,r),i}async saveContent(e,t){let n=this.fileSystem.getDirectoryName(t);await this.fileSystem.createDirectory(n,{recursive:true}),await this.fileSystem.writeTextFile(t,JSON.stringify(e,null,2),{overwrite:true});}async loadLocalContent(e){let t;try{t=await this.fileSystem.readTextFile(e);}catch{return {}}try{return JSON.parse(t)}catch(n){throw new B("Failed to parse content file.",{reason:"invalid_input",cause:n,details:[`File: ${e}`]})}}async loadRemoteContent(e){let t=await this.resolveVersions(e.configuration),n=Object.entries(t.slots),r={};for(let[i,a]of n)r[i]=O.parse(a).getVersions();return Object.fromEntries(await Promise.all(n.map(async([i])=>[i,await Promise.all(r[i].map(a=>this.workspaceApi.getSlotStaticContent({organizationSlug:t.organization,workspaceSlug:t.workspace,slotSlug:i},a).then(s=>({version:a,content:Object.fromEntries(s.map(({locale:p,content:c})=>[p,c]))}))))])))}async updateTypes(e,t={}){let{output:n,configuration:r}=e,i=t.notifier??n.notify("Updating types"),a=await this.mountContentPackageFolder();if(a===null){i.alert(`The package ${o.CONTENT_PACKAGE} is not installed`);return}let s=this.getTypeFile(a.directory);await this.fileSystem.createDirectory(this.fileSystem.getDirectoryName(s),{recursive:true}).catch(()=>{});let p="export {};";(Object.keys(r.slots).length>0||Object.keys(r.components).length>0)&&(p=`${await this.generateTypes(r,t.clean)}
90
+ ${p}`),await this.fileSystem.writeTextFile(s,p,{overwrite:true}),i.confirm("Types updated");}async generateTypes(e,t=false){if(e.paths.content===void 0)return this.generateTypeRemotely(e);let n=this.fileSystem.joinPaths(e.paths.content,"slots.ts.dist");if(!t&&await this.fileSystem.exists(n))return this.fileSystem.readTextFile(n);let r=await this.generateTypeRemotely(e);return await this.fileSystem.writeTextFile(n,r,{overwrite:true}),r}async generateTypeRemotely(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(([a,s])=>({id:a,version:s})),slots:Object.entries(i).map(([a,s])=>({id:a,version:s}))})}async registerTypeFile(e,t){let[n,r]=await Promise.all([this.getTypeScriptConfigPath(e),this.mountContentPackageFolder()]);if(n===null)throw new B("TypeScript configuration not found");let i=this.projectDirectory.get();if(!this.fileSystem.isSubPath(i,n)){let p=this.fileSystem.getRelativePath(i,n);throw new B(`TypeScript configuration is outside the project directory: \`${p}\``)}if(r===null)throw new B(`Package ${o.CONTENT_PACKAGE} is not installed`);let a=this.fileSystem.getRelativePath(this.fileSystem.getDirectoryName(n),this.getTypeFile(r.directory)).replace(/\\/g,"/"),s=JsonParser$1.parse(await this.fileSystem.readTextFile(n),JsonObjectNode$1);if(s.has("files")){let p=s.get("files",JsonArrayNode$1);if(p.toJSON().includes(a))return t.confirm("Type file already registered");p.push(a);}else s.set("files",[a]);await this.fileSystem.writeTextFile(n,s.toString(),{overwrite:true}),t.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([this.workspaceApi.getSlots({organizationSlug:e.organization,workspaceSlug:e.workspace}),this.workspaceApi.getComponents({organizationSlug:e.organization,workspaceSlug:e.workspace})]);return {...e,components:Object.fromEntries(Object.entries(e.components).flatMap(([a,s])=>{let p=O.parse(s).getVersions().filter(c=>i.some(l=>l.slug===a&&c<=l.version.major));return p.length===0?[]:[[a,O.either(...p).toString()]]})),slots:Object.fromEntries(Object.entries(e.slots).flatMap(([a,s])=>{let p=O.parse(s).getVersions().filter(c=>r.some(l=>l.slug===a&&c<=l.version.major));return p.length===0?[]:[[a,O.either(...p).toString()]]}))}}async mountContentPackageFolder(){let e=await this.packageManager.getDependency(o.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 B("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,"types.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 Me=class o{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+=`
90
91
  `.repeat(e),this}write(e,t=true){return this.code+=this.indentCode(`${e}`)+(t?`
91
- `:""),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+=o.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 a=0;a<e.length;a++)this.appendIndentation().appendValue(e[a],t),a<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 a=0;a<i.length;a++){let[s,p]=i[a];this.appendIndentation(),r||!json5Parser.isIdentifier(s)?this.appendValue(s,t):this.append(s),this.append(": ").appendValue(p,t),a<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,`
92
- ${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,a,s)=>t||s>0?(i??a).toUpperCase():(i??a).toLowerCase())}};function dr(o){let e=o.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 qs(o){return o.normalize("NFD").toLocaleLowerCase().replace(/(^[^a-z]+|[^a-z0-9_ &-]+)/ig,"").split(/[^a-z0-9]+/i).filter(e=>e!=="").join("-")}function Pt(o){return Object.entries(o).sort(([,e],[,t])=>{let n=e.position??Number.MAX_SAFE_INTEGER,r=t.position??Number.MAX_SAFE_INTEGER;return n-r})}var gr=class o{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>${o.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?Ct(t.itemLabel):"item";e.write("<ol>").indent().write(`\${${n}.map(${r} => \``).indent().write("<li>").indent();let i=o.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 Pt(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?o.escapeEntities(t.label).replace(/`/g,"\\`"):dr(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 ze(this.options.indentationSize)}};var fr=class o extends Qe{constructor({bundlers:e,...t}){super(t),this.bundlers=e;}async generateSlotExampleFiles(e,t){let{configuration:n}=t,[r,i,a]=await Promise.all([this.isTypeScriptProject(),this.detectBundler(),this.workspaceApi.getApplication({organizationSlug:n.organization,workspaceSlug:n.workspace,applicationSlug:n.applications.development})]);if(a===null)throw new Y(`Development application ${n.applications.development} not found.`,{reason:"not_found"});let s=this.fileSystem.joinPaths(t.configuration.paths.examples,e.slug),c=new gr({fileSystem:this.fileSystem,language:r?"typescript":"javascript",appId:a.publicId,fallbackContent:i===null?o.extractFallbackContent(e.content[t.configuration.defaultLocale],e.resolvedDefinition):void 0,containerId:"slot",slotPath:this.fileSystem.joinPaths(s,`slot.${r?"ts":"js"}`),pagePath:this.fileSystem.joinPaths(s,"index.html")}).generate({id:e.slug,version:e.version.major,definition:e.resolvedDefinition});return Promise.resolve(c.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=>o.extractFallbackContent(n,t.items));case "structure":{let n=t,r={};for(let[i,a]of Pt(n.attributes)){if(a.private===true)continue;let s=o.extractFallbackContent(e.attributes[i],n.attributes[i].type);(a.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 qe=class o{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=o.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=o.escapeRegex(e);if(n==="")return this.write(`${e}=${t}`);let i=n.replace(new RegExp(`${r}\\s*=\\s*((?!['"\`]).*$|\`(?:\\.|[^\`])*\`|'(?:\\.|[^'])*'|"(?:\\.|[^"])*")`,"m"),`${e}=${t}`);return i!==n?this.write(i):this.write(`${n}${n.endsWith(`
92
+ `:""),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+=o.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 a=0;a<e.length;a++)this.appendIndentation().appendValue(e[a],t),a<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 a=0;a<i.length;a++){let[s,p]=i[a];this.appendIndentation(),r||!isIdentifier(s)?this.appendValue(s,t):this.append(s),this.append(": ").appendValue(p,t),a<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,`
93
+ ${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,a,s)=>t||s>0?(i??a).toUpperCase():(i??a).toLowerCase())}};function Qn(o){let e=o.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(o){return o.normalize("NFD").toLocaleLowerCase().replace(/(^[^a-z]+|[^a-z0-9_ &-]+)/ig,"").split(/[^a-z0-9]+/i).filter(e=>e!=="").join("-")}function St(o){return Object.entries(o).sort(([,e],[,t])=>{let n=e.position??Number.MAX_SAFE_INTEGER,r=t.position??Number.MAX_SAFE_INTEGER;return n-r})}var Bn=class o{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>${o.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?ht(t.itemLabel):"item";e.write("<ol>").indent().write(`\${${n}.map(${r} => \``).indent().write("<li>").indent();let i=o.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 St(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?o.escapeEntities(t.label).replace(/`/g,"\\`"):Qn(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 Me(this.options.indentationSize)}};var Yn=class o extends He{constructor({bundlers:e,...t}){super(t),this.bundlers=e;}async generateSlotExampleFiles(e,t){let{configuration:n}=t,[r,i,a]=await Promise.all([this.isTypeScriptProject(),this.detectBundler(),this.workspaceApi.getApplication({organizationSlug:n.organization,workspaceSlug:n.workspace,applicationSlug:n.applications.development})]);if(a===null)throw new B(`Development application ${n.applications.development} not found.`,{reason:"not_found"});let s=this.fileSystem.joinPaths(t.configuration.paths.examples,e.slug),c=new Bn({fileSystem:this.fileSystem,language:r?"typescript":"javascript",appId:a.publicId,fallbackContent:i===null?o.extractFallbackContent(e.content[t.configuration.defaultLocale],e.resolvedDefinition):void 0,containerId:"slot",slotPath:this.fileSystem.joinPaths(s,`slot.${r?"ts":"js"}`),pagePath:this.fileSystem.joinPaths(s,"index.html")}).generate({id:e.slug,version:e.version.major,definition:e.resolvedDefinition});return Promise.resolve(c.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=>o.extractFallbackContent(n,t.items));case "structure":{let n=t,r={};for(let[i,a]of St(n.attributes)){if(a.private===true)continue;let s=o.extractFallbackContent(e.attributes[i],n.attributes[i].type);(a.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 je=class o{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=o.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=o.escapeRegex(e);if(n==="")return this.write(`${e}=${t}`);let i=n.replace(new RegExp(`${r}\\s*=\\s*((?!['"\`]).*$|\`(?:\\.|[^\`])*\`|'(?:\\.|[^'])*'|"(?:\\.|[^"])*")`,"m"),`${e}=${t}`);return i!==n?this.write(i):this.write(`${n}${n.endsWith(`
93
94
  `)?"":`
94
- `}${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 At=class o{constructor({fileSystem:e,...t}){this.options=t,this.fileSystem=e;}generate(e){let t=o.replaceVariables(this.options.slotFilePath,e.id),n=o.replaceVariables(this.options.slotComponentName,e.id);return {files:[this.generatePageFile(e,{name:n,path:t,importPath:o.replaceVariables(this.options.slotImportPath,e.id),definition:e}),this.generateSlotFile(e,t,n)]}}generatePageFile(e,t){let n=this.createWriter(),r=o.replaceVariables(this.options.pageFilePath,e.id),i=o.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?Ct(t.itemLabel):"item";e.write("<ol>").indent().write(`{${n}.map((${r}, index) => (`).indent().write("<li key={index}>").indent();let i=o.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 Pt(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,a]of Object.entries(t.types))e.write(`{${n}._type === '${i}' && (`).indent(),this.writeRenderingSnippet(e,a,n),e.outdent().write(")}");r&&e.outdent().write("</>");break}}}writeAttributeSnippet(e,t,n){let r=t.type,i=o.escapeEntities(t.label??dr(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 ze(this.options.indentationSize)}static replaceVariables(e,t){return e.replace(/%name%/g,o.formatName(t,true)).replace(/%slug%/g,qs(t))}static formatName(e,t=false){return ze.formatName(e,t)}static isInline(e){return ["number","text","boolean"].includes(e.type)}};var Et=class extends At{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 yr=class o extends Qe{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=this.fileSystem.joinPaths(t.configuration.paths.components,`%slug%${n?".tsx":".jsx"}`),i=this.fileSystem.joinPaths(t.configuration.paths.examples,`%slug%-example${n?".tsx":".jsx"}`);return new Et({fileSystem:this.fileSystem,language:await this.isTypeScriptProject()?"tsx":"jsx",contentVariable:"content",slotImportPath:await this.importResolver.getImportPath(r,this.fileSystem.getDirectoryName(i)),slotFilePath:r,slotComponentName:"%name%",pageFilePath:i,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 qe(this.fileSystem,this.fileSystem.joinPaths(n,".env.production")),developmentFile:new qe(this.fileSystem,this.fileSystem.joinPaths(n,".env.development"))}}}getInstallationTasks(e){let t=[],n=e.project.env,{configuration:r}=e,i=null,a=()=>(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 Y(`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 m=>{m.update("Setting up environment variables");try{let f=await a();await Promise.all([s.setVariable(l,f.development),f.production===void 0?Promise.resolve():p.setVariable(l,f.production)]),m.confirm("Environment variables updated");}catch(f){m.alert("Failed to update environment variables",d.formatMessage(f));}}});}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:o.getAppIdProperty(await a(),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 Je=class o extends d{constructor(e,t={}){super(e,t),Object.setPrototypeOf(this,o.prototype);}},hr=class o extends Je{constructor(e){super(e),Object.setPrototypeOf(this,o.prototype);}};function Be(o,e,t){try{return parser.parse(o,{...t,sourceType:"module",plugins:[...e,...t?.plugins??[]]})}catch{throw new hr("The source code contains syntax errors.")}}function Hs(o){let e={locales:Array()},t;try{t=Be(o,["jsx","typescript"]);}catch{return {i18n:e}}return yt__default.default(t,{ObjectProperty:n=>{if(es(n.node.key)!=="i18n")return n.skip();let r=n.node.value;if(!g__namespace.isObjectExpression(r))return n.stop();for(let i of r.properties)if(g__namespace.isObjectProperty(i)&&es(i.key)==="locales"){let a=i.value;if(g__namespace.isArrayExpression(a))for(let s of a.elements)s!==null&&g__namespace.isStringLiteral(s)&&e.locales.push(s.value);}else if(g__namespace.isObjectProperty(i)&&es(i.key)==="defaultLocale"){let a=i.value;a!==null&&g__namespace.isStringLiteral(a)&&(e.defaultLocale=a.value);}return n.stop()}}),{i18n:e}}function es(o){return g__namespace.isIdentifier(o)?o.name:g__namespace.isStringLiteral(o)?o.value:null}var Sr=class extends At{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=ze.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=ze.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 ne=class o extends d{constructor(e,t=[],n={}){super(e,{...n,details:n.details??t.map(r=>r.detail??r.title)}),Object.setPrototypeOf(this,o.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 fe=(t=>(t.DEVELOPMENT="DEVELOPMENT",t.PRODUCTION="PRODUCTION",t))(fe||{});(n=>{function o(r){switch(r){case "DEVELOPMENT":return "Development";case "PRODUCTION":return "Production"}}n.getLabel=o;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;})(fe||(fe={}));var we=(n=>(n.READ_RESOURCES="RESOURCE_READ_ACCESS",n.ISSUE_TOKEN="TOKEN_ISSUE",n.EXPORT_DATA="DATA_EXPORT",n))(we||{});(n=>{function o(r){switch(r){case "RESOURCE_READ_ACCESS":return "Read resources";case "TOKEN_ISSUE":return "Issue tokens";case "DATA_EXPORT":return "Export data"}}n.getLabel=o;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;})(we||(we={}));var br=class extends Qe{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()]),a=await this.isTypeScriptProject(),s=this.fileSystem.joinPaths(t.configuration.paths.components,`%slug%${a?".tsx":".jsx"}`),p=this.fileSystem.joinPaths(t.configuration.paths.examples,"%slug%"),c=await this.importResolver.getImportPath(s,p),l=r?"tsx":"jsx";return (i?new Et({fileSystem:this.fileSystem,language:l,contentVariable:"content",slotImportPath:c,slotFilePath:s,slotComponentName:"%name%",pageFilePath:this.fileSystem.joinPaths(p,`index${a?".tsx":".jsx"}`),pageComponentName:"Page"}):new Sr({fileSystem:this.fileSystem,router:n==="page"?"page":"app",language:l,slotImportPath:c,slotFilePath:s,slotComponentName:"%name%",pageFilePath:this.fileSystem.joinPaths(p,`${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 a=t.locales.filter(c=>r.locales.includes(c)||c===t.defaultLocale),s=a.length>0?a: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,a]=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.jsx"),this.fileSystem.joinPaths("app","layout.tsx")]:[this.fileSystem.joinPaths("pages","_app.jsx"),this.fileSystem.joinPaths("pages","_app.tsx")]).map(c=>this.fileSystem.joinPaths(r.sourceDirectory,c)))]),s=r.typescript?"ts":"js",p=this.projectDirectory.get();return {...r,fallbackMode:n,env:{localFile:new qe(this.fileSystem,this.fileSystem.joinPaths(p,".env.local")),developmentFile:new qe(this.fileSystem,this.fileSystem.joinPaths(p,".env.development")),productionFile:new qe(this.fileSystem,this.fileSystem.joinPaths(p,".env.production"))},middleware:{file:i??this.fileSystem.joinPaths(r.sourceDirectory,`middleware.${s}`)},provider:{file:a??(r.router==="app"?this.fileSystem.joinPaths("app",`layout.${s}x`):this.fileSystem.joinPaths("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;if(!await t.localFile.hasVariable("CROCT_API_KEY")){r.update("Loading information");let[i,a,s]=await Promise.all([this.userApi.getUser(),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(a===null)throw new Y(`Development application \`${n.applications.development}\` not found.`,{reason:"not_found"});r.update("Creating API key");let p;try{p=await this.applicationApi.createApiKey({organizationSlug:n.organization,workspaceSlug:n.workspace,applicationSlug:a.slug,name:`${i.username} CLI`,permissions:["TOKEN_ISSUE"]});}catch(c){throw c instanceof d?new Y(c instanceof ne&&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:a.publicId}),s===null?Promise.resolve():t.productionFile.setVariables({NEXT_PUBLIC_CROCT_APP_ID:s.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:""}}:Hs(t)}async isFallbackMode(){return !await this.packageManager.hasDirectDependency("next",">=13")}};var Ye=(n=>(n.NEXTJS="nextjs",n.REACT="react",n.JAVASCRIPT="javascript",n))(Ye||{});(e=>{function o(t){switch(t){case "nextjs":return "Next.js";case "react":return "React";case "javascript":return "JavaScript"}}e.getName=o;})(Ye||(Ye={}));var Ir=class{constructor(e){this.config=e;}async execute(e){let{configurationManager:t,platformProvider:n,sdkProvider:r,io:{output:i}}=this.config;if(e.override!==true&&await t.isInitialized())throw new d("Configuration file already exists, specify `override` to reconfigure.",{reason:"precondition"});let a=await n.get(),s=a!==null?`${Ye.getName(a)} project`:"project";i.break(),i.announce({semantics:"neutral",title:"\u{1F44B} Welcome to Croct",alignment:"center",message:`Let's configure your ${s} to get started!`}),i.break();let p=await this.getOrganization({new:e.new==="organization"},e.organization);if(p===null)throw new d(`Organization not found: ${e.organization}`,{reason:"invalid_input"});let c=await this.getWorkspace({organization:p,new:e.new==="workspace"},e.workspace),l={organization:p,workspace:c,platform:a??"javascript",new:e.new==="application"},m=await this.getApplication({...l,environment:"DEVELOPMENT"},e.devApplication),f={organization:p.slug,workspace:c.slug,applications:{development:m.slug},defaultLocale:c.defaultLocale,locales:c.locales,slots:{},components:{},paths:{components:"",examples:""}},b=c.website??p.website??void 0;if(b!==void 0&&new URL(b).hostname!=="localhost"){let w=await this.getApplication({...l,environment:"PRODUCTION"},e.prodApplication);f.applications.production=w.slug;}let A=await r.get();if(A===null){await t.update({...f,paths:{components:"components",examples:"examples"}}),i.warn("No suitable SDK found, skipping project configuration");return}await t.update(await this.configure(A,f));}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(a=>{if(a instanceof ne&&a.isAccessDenied())return null;throw a});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(a=>{if(a instanceof ne&&a.isAccessDenied())return null;throw a});if(i===null)throw new d(`No workspace found with slug "${t}".`,{reason:"invalid_input"});return i}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(a=>{if(a instanceof ne&&a.isAccessDenied())return null;throw a});if(i===null)throw new d(`No application found with slug "${t}".`,{reason:"invalid_input"});if(i.environment!==e.environment)throw new d(`No ${fe.getLabel(e.environment).toUpperCase()} application found with slug "${t}".`,{reason:"invalid_input"});return i}async getSlots(e,t){let{api:n,io:{output:r}}=this.config,i=r.notify("Loading slots"),a=await n.workspace.getSlots({organizationSlug:e,workspaceSlug:t});return i.stop(),Object.fromEntries(a.map(s=>[s.slug,`${s.version.major}`]))}async configure(e,t){let{skipConfirmation:n}=this.config;return e.setup({input:this.config.io.input===void 0||await n.get()?void 0:this.config.io.input,output:this.config.io.output,configuration:{...t,slots:await this.getSlots(t.organization,t.workspace)}})}};var xr=class{constructor(e){this.authenticator=e.authenticator;}async execute(e){await this.authenticator.logout(),await this.authenticator.login(e);}};var cn=class{constructor({output:e,authenticator:t}){this.authenticator=t,this.output=e;}async execute(){await this.authenticator.logout(),this.output.confirm("Logged out");}};var ut=class o extends d{constructor(e,t={}){super(e,{...t,reason:t.reason??"invalid_configuration"}),Object.setPrototypeOf(this,o.prototype);}};var wr=class wr{constructor({fileSystem:e,projectDirectory:t,validator:n}){this.fileSystem=e,this.projectDirectory=t,this.validator=n;}isInitialized(){return this.fileSystem.exists(this.getConfigurationFilePath())}async load(){let e=await this.loadConfigurationFile();if(e.configuration===null)throw new ut("Project configuration not found.",{reason:"not_found",suggestions:["Run `init` command to initialize the project"]});return e.configuration}async update(e){return this.updateConfigurationFile(await this.validateConfiguration(e))}async updateConfigurationFile(e){let t=await this.loadConfigurationFile(),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 json5Parser.JsonObjectNode.of({$schema:wr.CONFIGURATION_SCHEMA,...t});let n=json5Parser.JsonParser.parse(e.source,json5Parser.JsonObjectNode);return n.update({$schema:n.has("$schema")?n.get("$schema").toJSON():void 0,...t}).cast(json5Parser.JsonObjectNode)}async loadConfigurationFile(){let e={path:this.getConfigurationFilePath(),source:null,configuration:null},t;try{e.source=await this.fileSystem.readTextFile(e.path),t=json5Parser.JsonParser.parse(e.source).toJSON();}catch{return e}return t!==null&&(e.configuration=await this.validateConfiguration(t,e),e.configuration?.$schema!==void 0&&delete e.configuration?.$schema),e}getConfigurationFilePath(){return this.fileSystem.joinPaths(this.projectDirectory.get(),"croct.json")}async validateConfiguration(e,t){let n=await this.validator.validate(e);if(!n.valid){let r=n.violations[0];throw new ut(r.message,{details:[...t!==void 0?[`File: file://${t.path.replace(/\\/g,"/")}`]:[],`Violation path: ${r.path}`]})}return n.data}};wr.CONFIGURATION_SCHEMA="https://schema.croct.com/json/v1/project.json";var vr=wr;var ln=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,a=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 a.json().then(s=>{let{data:p,errors:c}=s;if(c!==void 0)throw new ne(c[0].message.replace(/"/g,"`"),c.map(({extensions:l})=>({...l,detail:l.detail?.replace(/"/g,"`")})));return {data:p,headers:a.headers}})}};function ns(o,e){return o.slice(0,o.indexOf("-",e-1)===e-1?e-1:e)}function*un({baseName:o,alwaysSuffixed:e=false}){let t=o.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 ns(n,30),n.length<29&&t.length>2&&(yield ns(t.join("-"),30)));;){let r=Math.floor(Math.random()*1e4).toString();yield `${ns(n,30-r.length-1)}-${r}`;}}function mt(o){let{baseName:e,query:t,client:n,alwaysSuffixed:r}=o;return Jl({baseName:e,alwaysSuffixed:r},async i=>{let a=[i.next().value,i.next().value,i.next().value],{data:{checkAvailability:s}}=await n.execute(t,{...o.variables??{},slugFirstOption:a[0],slugSecondOption:a[1],slugThirdOption:a[2]}),p=[s.slugFirstOption,s.slugSecondOption,s.slugThirdOption];return a.find((c,l)=>p[l])??null})}async function Jl(o,e){let t=un(o),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}},Gs=new E(`
95
+ `}${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 It=class o{constructor({fileSystem:e,...t}){this.options=t,this.fileSystem=e;}generate(e){let t=o.replaceVariables(this.options.slotFilePath,e.id),n=o.replaceVariables(this.options.slotComponentName,e.id);return {files:[this.generatePageFile(e,{name:n,path:t,importPath:o.replaceVariables(this.options.slotImportPath,e.id),definition:e}),this.generateSlotFile(e,t,n)]}}generatePageFile(e,t){let n=this.createWriter(),r=o.replaceVariables(this.options.pageFilePath,e.id),i=o.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?ht(t.itemLabel):"item";e.write("<ol>").indent().write(`{${n}.map((${r}, index) => (`).indent().write("<li key={index}>").indent();let i=o.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 St(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,a]of Object.entries(t.types))e.write(`{${n}._type === '${i}' && (`).indent(),this.writeRenderingSnippet(e,a,n),e.outdent().write(")}");r&&e.outdent().write("</>");break}}}writeAttributeSnippet(e,t,n){let r=t.type,i=o.escapeEntities(t.label??Qn(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 Me(this.options.indentationSize)}static replaceVariables(e,t){return e.replace(/%name%/g,o.formatName(t,true)).replace(/%slug%/g,Is(t))}static formatName(e,t=false){return Me.formatName(e,t)}static isInline(e){return ["number","text","boolean"].includes(e.type)}};var xt=class extends It{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 Xn=class o extends He{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=this.fileSystem.joinPaths(t.configuration.paths.components,`%slug%${n?".tsx":".jsx"}`),i=this.fileSystem.joinPaths(t.configuration.paths.examples,`%slug%-example${n?".tsx":".jsx"}`);return new xt({fileSystem:this.fileSystem,language:await this.isTypeScriptProject()?"tsx":"jsx",contentVariable:"content",slotImportPath:await this.importResolver.getImportPath(r,this.fileSystem.getDirectoryName(i)),slotFilePath:r,slotComponentName:"%name%",pageFilePath:i,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 je(this.fileSystem,this.fileSystem.joinPaths(n,".env.production")),developmentFile:new je(this.fileSystem,this.fileSystem.joinPaths(n,".env.development"))}}}getInstallationTasks(e){let t=[],n=e.project.env,{configuration:r}=e,i=null,a=()=>(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 B(`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 m=>{m.update("Setting up environment variables");try{let f=await a();await Promise.all([s.setVariable(l,f.development),f.production===void 0?Promise.resolve():p.setVariable(l,f.production)]),m.confirm("Environment variables updated");}catch(f){m.alert("Failed to update environment variables",d.formatMessage(f));}}});}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:o.getAppIdProperty(await a(),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 Ge=class o extends d{constructor(e,t={}){super(e,t),Object.setPrototypeOf(this,o.prototype);}},er=class o extends Ge{constructor(e){super(e),Object.setPrototypeOf(this,o.prototype);}};function Ke(o,e,t){try{return parse$1(o,{...t,sourceType:"module",plugins:[...e,...t?.plugins??[]]})}catch{throw new er("The source code contains syntax errors.")}}function xs(o){let e={locales:Array()},t;try{t=Ke(o,["jsx","typescript"]);}catch{return {i18n:e}}return traverse(t,{ObjectProperty:n=>{if(Oa(n.node.key)!=="i18n")return n.skip();let r=n.node.value;if(!g.isObjectExpression(r))return n.stop();for(let i of r.properties)if(g.isObjectProperty(i)&&Oa(i.key)==="locales"){let a=i.value;if(g.isArrayExpression(a))for(let s of a.elements)s!==null&&g.isStringLiteral(s)&&e.locales.push(s.value);}else if(g.isObjectProperty(i)&&Oa(i.key)==="defaultLocale"){let a=i.value;a!==null&&g.isStringLiteral(a)&&(e.defaultLocale=a.value);}return n.stop()}}),{i18n:e}}function Oa(o){return g.isIdentifier(o)?o.name:g.isStringLiteral(o)?o.value:null}var tr=class extends It{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=Me.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=Me.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 te=class o extends d{constructor(e,t=[],n={}){super(e,{...n,details:n.details??t.map(r=>r.detail??r.title)}),Object.setPrototypeOf(this,o.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 Ie=(t=>(t.DEVELOPMENT="DEVELOPMENT",t.PRODUCTION="PRODUCTION",t))(Ie||{});(n=>{function o(r){switch(r){case "DEVELOPMENT":return "Development";case "PRODUCTION":return "Production"}}n.getLabel=o;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;})(Ie||={});var Ae=(n=>(n.READ_RESOURCES="RESOURCE_READ_ACCESS",n.ISSUE_TOKEN="TOKEN_ISSUE",n.EXPORT_DATA="DATA_EXPORT",n))(Ae||{});(n=>{function o(r){switch(r){case "RESOURCE_READ_ACCESS":return "Read resources";case "TOKEN_ISSUE":return "Issue tokens";case "DATA_EXPORT":return "Export data"}}n.getLabel=o;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 nr=class extends He{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()]),a=await this.isTypeScriptProject(),s=this.fileSystem.joinPaths(t.configuration.paths.components,`%slug%${a?".tsx":".jsx"}`),p=this.fileSystem.joinPaths(t.configuration.paths.examples,"%slug%"),c=await this.importResolver.getImportPath(s,p),l=r?"tsx":"jsx";return (i?new xt({fileSystem:this.fileSystem,language:l,contentVariable:"content",slotImportPath:c,slotFilePath:s,slotComponentName:"%name%",pageFilePath:this.fileSystem.joinPaths(p,`index${a?".tsx":".jsx"}`),pageComponentName:"Page"}):new tr({fileSystem:this.fileSystem,router:n==="page"?"page":"app",language:l,slotImportPath:c,slotFilePath:s,slotComponentName:"%name%",pageFilePath:this.fileSystem.joinPaths(p,`${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 a=t.locales.filter(c=>r.locales.includes(c)||c===t.defaultLocale),s=a.length>0?a: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,a]=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.jsx"),this.fileSystem.joinPaths("app","layout.tsx")]:[this.fileSystem.joinPaths("pages","_app.jsx"),this.fileSystem.joinPaths("pages","_app.tsx")]).map(c=>this.fileSystem.joinPaths(r.sourceDirectory,c)))]),s=r.typescript?"ts":"js",p=this.projectDirectory.get();return {...r,fallbackMode:n,env:{localFile:new je(this.fileSystem,this.fileSystem.joinPaths(p,".env.local")),developmentFile:new je(this.fileSystem,this.fileSystem.joinPaths(p,".env.development")),productionFile:new je(this.fileSystem,this.fileSystem.joinPaths(p,".env.production"))},middleware:{file:i??this.fileSystem.joinPaths(r.sourceDirectory,`middleware.${s}`)},provider:{file:a??(r.router==="app"?this.fileSystem.joinPaths("app",`layout.${s}x`):this.fileSystem.joinPaths("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;if(!await t.localFile.hasVariable("CROCT_API_KEY")){r.update("Loading information");let[i,a,s]=await Promise.all([this.userApi.getUser(),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(a===null)throw new B(`Development application \`${n.applications.development}\` not found.`,{reason:"not_found"});r.update("Creating API key");let p;try{p=await this.applicationApi.createApiKey({organizationSlug:n.organization,workspaceSlug:n.workspace,applicationSlug:a.slug,name:`${i.username} CLI`,permissions:["TOKEN_ISSUE"]});}catch(c){throw c instanceof d?new B(c instanceof te&&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:a.publicId}),s===null?Promise.resolve():t.productionFile.setVariables({NEXT_PUBLIC_CROCT_APP_ID:s.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:""}}:xs(t)}async isFallbackMode(){return !await this.packageManager.hasDirectDependency("next",">=13")}};var rt=(n=>(n.NEXTJS="nextjs",n.REACT="react",n.JAVASCRIPT="javascript",n))(rt||{});(e=>{function o(t){switch(t){case "nextjs":return "Next.js";case "react":return "React";case "javascript":return "JavaScript"}}e.getName=o;})(rt||={});var rr=class{constructor(e){this.config=e;}async execute(e){let{configurationManager:t,platformProvider:n,sdkProvider:r,io:{output:i}}=this.config;if(e.override!==true&&await t.isInitialized())throw new d("Configuration file already exists, specify `override` to reconfigure.",{reason:"precondition"});let a=await n.get(),s=a!==null?`${rt.getName(a)} project`:"project";i.break(),i.announce({semantics:"neutral",title:"\u{1F44B} Welcome to Croct",alignment:"center",message:`Let's configure your ${s} to get started!`}),i.break();let p=await this.getOrganization({new:e.new==="organization"},e.organization);if(p===null)throw new d(`Organization not found: ${e.organization}`,{reason:"invalid_input"});let c=await this.getWorkspace({organization:p,new:e.new==="workspace"},e.workspace),l={organization:p,workspace:c,platform:a??"javascript",new:e.new==="application"},m=await this.getApplication({...l,environment:"DEVELOPMENT"},e.devApplication),f={organization:p.slug,workspace:c.slug,applications:{development:m.slug},defaultLocale:c.defaultLocale,locales:c.locales,slots:{},components:{},paths:{components:"",examples:""}},b=c.website??p.website??void 0;if(b!==void 0&&new URL(b).hostname!=="localhost"){let w=await this.getApplication({...l,environment:"PRODUCTION"},e.prodApplication);f.applications.production=w.slug;}let A=await r.get();if(A===null){await t.update({...f,paths:{components:"components",examples:"examples"}}),i.warn("No suitable SDK found, skipping project configuration");return}await t.update(await this.configure(A,f));}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(a=>{if(a instanceof te&&a.isAccessDenied())return null;throw a});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(a=>{if(a instanceof te&&a.isAccessDenied())return null;throw a});if(i===null)throw new d(`No workspace found with slug "${t}".`,{reason:"invalid_input"});return i}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(a=>{if(a instanceof te&&a.isAccessDenied())return null;throw a});if(i===null)throw new d(`No application found with slug "${t}".`,{reason:"invalid_input"});if(i.environment!==e.environment)throw new d(`No ${Ie.getLabel(e.environment).toUpperCase()} application found with slug "${t}".`,{reason:"invalid_input"});return i}async getSlots(e,t){let{api:n,io:{output:r}}=this.config,i=r.notify("Loading slots"),a=await n.workspace.getSlots({organizationSlug:e,workspaceSlug:t});return i.stop(),Object.fromEntries(a.map(s=>[s.slug,`${s.version.major}`]))}async configure(e,t){let{skipConfirmation:n}=this.config;return e.setup({input:this.config.io.input===void 0||await n.get()?void 0:this.config.io.input,output:this.config.io.output,configuration:{...t,slots:await this.getSlots(t.organization,t.workspace)}})}};var ir=class{constructor(e){this.authenticator=e.authenticator;}async execute(e){await this.authenticator.logout(),await this.authenticator.login(e);}};var Bt=class{constructor({output:e,authenticator:t}){this.authenticator=t,this.output=e;}async execute(){await this.authenticator.logout(),this.output.confirm("Logged out");}};var it=class o extends d{constructor(e,t={}){super(e,{...t,reason:t.reason??"invalid_configuration"}),Object.setPrototypeOf(this,o.prototype);}};var or=class o{static{this.CONFIGURATION_SCHEMA="https://schema.croct.com/json/v1/project.json";}constructor({fileSystem:e,projectDirectory:t,validator:n}){this.fileSystem=e,this.projectDirectory=t,this.validator=n;}isInitialized(){return this.fileSystem.exists(this.getConfigurationFilePath())}async load(){let e=await this.loadConfigurationFile();if(e.configuration===null)throw new it("Project configuration not found.",{reason:"not_found",suggestions:["Run `init` command to initialize the project"]});return e.configuration}async update(e){return this.updateConfigurationFile(await this.validateConfiguration(e))}async updateConfigurationFile(e){let t=await this.loadConfigurationFile(),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:o.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(){let e={path:this.getConfigurationFilePath(),source:null,configuration:null},t;try{e.source=await this.fileSystem.readTextFile(e.path),t=JsonParser.parse(e.source).toJSON();}catch{return e}return t!==null&&(e.configuration=await this.validateConfiguration(t,e),e.configuration?.$schema!==void 0&&delete e.configuration?.$schema),e}getConfigurationFilePath(){return this.fileSystem.joinPaths(this.projectDirectory.get(),"croct.json")}async validateConfiguration(e,t){let n=await this.validator.validate(e);if(!n.valid){let r=n.violations[0];throw new it(r.message,{details:[...t!==void 0?[`File: file://${t.path.replace(/\\/g,"/")}`]:[],`Violation path: ${r.path}`]})}return n.data}};var Yt=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,a=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 a.json().then(s=>{let{data:p,errors:c}=s;if(c!==void 0)throw new te(c[0].message.replace(/"/g,"`"),c.map(({extensions:l})=>({...l,detail:l.detail?.replace(/"/g,"`")})));return {data:p,headers:a.headers}})}};function Ma(o,e){return o.slice(0,o.indexOf("-",e-1)===e-1?e-1:e)}function*Xt({baseName:o,alwaysSuffixed:e=false}){let t=o.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 Ma(n,30),n.length<29&&t.length>2&&(yield Ma(t.join("-"),30)));;){let r=Math.floor(Math.random()*1e4).toString();yield `${Ma(n,30-r.length-1)}-${r}`;}}function ot(o){let{baseName:e,query:t,client:n,alwaysSuffixed:r}=o;return kl({baseName:e,alwaysSuffixed:r},async i=>{let a=[i.next().value,i.next().value,i.next().value],{data:{checkAvailability:s}}=await n.execute(t,{...o.variables??{},slugFirstOption:a[0],slugSecondOption:a[1],slugThirdOption:a[2]}),p=[s.slugFirstOption,s.slugSecondOption,s.slugThirdOption];return a.find((c,l)=>p[l])??null})}async function kl(o,e){let t=Xt(o),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}},ws=new E(`
95
96
  query ApplicationSlugAvailability($workspaceId: WorkspaceId!, $slugFirstOption: ReadableId!, $slugSecondOption: ReadableId!, $slugThirdOption: ReadableId!) {
96
97
  checkAvailability {
97
98
  slugFirstOption: applicationSlug(
@@ -108,7 +109,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
108
109
  )
109
110
  }
110
111
  }
111
- `),Zs=new E(`
112
+ `),Ps=new E(`
112
113
  query Applications($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {
113
114
  organization(slug: $organizationSlug) {
114
115
  workspace(slug: $workspaceSlug) {
@@ -133,7 +134,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
133
134
  }
134
135
  }
135
136
  }
136
- `),Qs=new E(`
137
+ `),Cs=new E(`
137
138
  query Application($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!, $applicationSlug: ReadableId!) {
138
139
  organization(slug: $organizationSlug) {
139
140
  workspace(slug: $workspaceSlug) {
@@ -154,7 +155,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
154
155
  }
155
156
  }
156
157
  }
157
- `),Js=new E(`
158
+ `),ks=new E(`
158
159
  mutation CreateApplication($workspaceId: WorkspaceId!, $payload: CreateWebApplicationPayload!) {
159
160
  createWebApplication(workspaceId: $workspaceId, payload: $payload) {
160
161
  id
@@ -171,7 +172,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
171
172
  }
172
173
  }
173
174
  }
174
- `),Bs=new E(`
175
+ `),As=new E(`
175
176
  mutation CreateApiKey($applicationId: ApplicationId!, $payload: CreateApiKeyPayload!) {
176
177
  createApiKey(applicationId: $applicationId, payload: $payload) {
177
178
  apiKey {
@@ -182,7 +183,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
182
183
  apiKeyValue
183
184
  }
184
185
  }
185
- `),Ys=new E(`
186
+ `),Es=new E(`
186
187
  query Audiences($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {
187
188
  organization(slug: $organizationSlug) {
188
189
  workspace(slug: $workspaceSlug) {
@@ -199,7 +200,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
199
200
  }
200
201
  }
201
202
  }
202
- `),Xs=new E(`
203
+ `),Rs=new E(`
203
204
  query Audience($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!, $audienceSlug: ReadableId!) {
204
205
  organization(slug: $organizationSlug) {
205
206
  workspace(slug: $workspaceSlug) {
@@ -212,43 +213,43 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
212
213
  }
213
214
  }
214
215
  }
215
- `),ep=new E(`
216
+ `),Ts=new E(`
216
217
  mutation SignIn($payload: SignInPayload!) {
217
218
  signIn(payload: $payload) {
218
219
  token
219
220
  }
220
221
  }
221
- `),tp=new E(`
222
+ `),Os=new E(`
222
223
  mutation SignUp($payload: SignUpPayload!) {
223
224
  signUp(payload: $payload) {
224
225
  userId
225
226
  }
226
227
  }
227
- `),np=new E(`
228
+ `),Ds=new E(`
228
229
  mutation IssueToken($payload: IssueTokenPayload!) {
229
230
  issueToken(payload: $payload)
230
231
  }
231
- `),rp=new E(`
232
+ `),Ms=new E(`
232
233
  mutation ResetPassword($payload: ResetPasswordPayload!) {
233
234
  resetPassword(payload: $payload) {
234
235
  token
235
236
  }
236
237
  }
237
- `),ip=new E(`
238
+ `),Ns=new E(`
238
239
  mutation RequestPasswordReset($email: String!, $sessionId: UserSessionId) {
239
240
  sendResetLink(email: $email, sessionId: $sessionId)
240
241
  }
241
- `),op=new E(`
242
+ `),$s=new E(`
242
243
  mutation RetryActivation($email: String!, $sessionId: UserSessionId!) {
243
244
  retry {
244
245
  accountActivation(sessionId: $sessionId, email: $email)
245
246
  }
246
247
  }
247
- `),ap=new E(`
248
+ `),zs=new E(`
248
249
  mutation CreateSession($redirectDestination: String) {
249
250
  createSession(redirectDestination: $redirectDestination)
250
251
  }
251
- `),sp=new E(`
252
+ `),_s=new E(`
252
253
  mutation CloseSession($sessionId: UserSessionId!) {
253
254
  closeSession(sessionId: $sessionId) {
254
255
  __typename
@@ -260,7 +261,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
260
261
  }
261
262
  }
262
263
  }
263
- `),pp=new E(`
264
+ `),Ls=new E(`
264
265
  query Components($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {
265
266
  organization(slug: $organizationSlug) {
266
267
  workspace(slug: $workspaceSlug) {
@@ -292,7 +293,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
292
293
  }
293
294
  }
294
295
  }
295
- `),cp=new E(`
296
+ `),Fs=new E(`
296
297
  query Component($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!, $componentSlug: ReadableId!, $majorVersion: Int) {
297
298
  organization(slug: $organizationSlug) {
298
299
  workspace(slug: $workspaceSlug) {
@@ -320,7 +321,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
320
321
  }
321
322
  }
322
323
  }
323
- `),lp=new E(`
324
+ `),js=new E(`
324
325
  query Experience($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!, $experienceId: ExperienceId!) {
325
326
  organization(slug: $organizationSlug) {
326
327
  workspace(slug: $workspaceSlug) {
@@ -474,7 +475,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
474
475
  }
475
476
  }
476
477
  }
477
- `),up=new E(`
478
+ `),Ws=new E(`
478
479
  query Experiences($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!, $status: [ExperienceStatus!]) {
479
480
  organization(slug: $organizationSlug) {
480
481
  workspace(slug: $workspaceSlug) {
@@ -530,7 +531,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
530
531
  }
531
532
  }
532
533
  }
533
- `),mp=new E(`
534
+ `),Vs=new E(`
534
535
  query ResourceIdQuery($organizationSlug: ReadableId!, $workspaceSlug: ReadableId, $applicationSlug: ReadableId) {
535
536
  organization(slug: $organizationSlug) {
536
537
  id
@@ -542,7 +543,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
542
543
  }
543
544
  }
544
545
  }
545
- `),dp=new E(`
546
+ `),Us=new E(`
546
547
  query Organization($slug: ReadableId!) {
547
548
  organization(slug: $slug) {
548
549
  id
@@ -554,7 +555,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
554
555
  email
555
556
  }
556
557
  }
557
- `),gp=new E(`
558
+ `),qs=new E(`
558
559
  query Organizations {
559
560
  organizations(first: 100) {
560
561
  edges {
@@ -570,7 +571,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
570
571
  }
571
572
  }
572
573
  }
573
- `),fp=new E(`
574
+ `),Hs=new E(`
574
575
  mutation SetupOrganization($payload: CreateConfiguredOrganizationPayload!) {
575
576
  createConfiguredOrganization(payload: $payload) {
576
577
  organization {
@@ -584,7 +585,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
584
585
  }
585
586
  }
586
587
  }
587
- `),yp=new E(`
588
+ `),Gs=new E(`
588
589
  query FindOrganizationSlug($slugFirstOption: ReadableId!, $slugSecondOption: ReadableId!, $slugThirdOption: ReadableId!) {
589
590
  checkAvailability {
590
591
  slugFirstOption: organizationSlug(slug: $slugFirstOption)
@@ -592,7 +593,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
592
593
  slugThirdOption: organizationSlug(slug: $slugThirdOption)
593
594
  }
594
595
  }
595
- `),hp=new E(`
596
+ `),Ks=new E(`
596
597
  query OrganizationMetadata($url: String!) {
597
598
  websiteMetadata(url: $url) {
598
599
  url
@@ -610,7 +611,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
610
611
  }
611
612
  }
612
613
  }
613
- `),Sp=new E(`
614
+ `),Zs=new E(`
614
615
  query Slots($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {
615
616
  organization(slug: $organizationSlug) {
616
617
  workspace(slug: $workspaceSlug) {
@@ -656,7 +657,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
656
657
  }
657
658
  }
658
659
  }
659
- `),bp=new E(`
660
+ `),Js=new E(`
660
661
  query Slot($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!, $slotSlug: ReadableId!, $majorVersion: Int) {
661
662
  organization(slug: $organizationSlug) {
662
663
  workspace(slug: $workspaceSlug) {
@@ -698,7 +699,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
698
699
  }
699
700
  }
700
701
  }
701
- `),Ip=new E(`
702
+ `),Qs=new E(`
702
703
  query SlotStaticContent($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!, $slotSlug: ReadableId!, $majorVersion: Int) {
703
704
  organization(slug: $organizationSlug) {
704
705
  workspace(slug: $workspaceSlug) {
@@ -711,11 +712,11 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
711
712
  }
712
713
  }
713
714
  }
714
- `),xp=new E(`
715
+ `),Bs=new E(`
715
716
  mutation GenerateTyping($workspaceId: WorkspaceId!, $payload: GenerateTypingPayload!) {
716
717
  generateTyping(workspaceId: $workspaceId, payload: $payload)
717
718
  }
718
- `),vp=new E(`
719
+ `),Ys=new E(`
719
720
  query User {
720
721
  userAccount {
721
722
  id
@@ -730,7 +731,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
730
731
  }
731
732
  }
732
733
  }
733
- `),wp=new E(`
734
+ `),Xs=new E(`
734
735
  query Username($slugFirstOption: ReadableId!, $slugSecondOption: ReadableId!, $slugThirdOption: ReadableId!) {
735
736
  checkAvailability {
736
737
  slugFirstOption: username(username: $slugFirstOption)
@@ -738,19 +739,19 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
738
739
  slugThirdOption: username(username: $slugThirdOption)
739
740
  }
740
741
  }
741
- `),Cp=new E(`
742
+ `),ep=new E(`
742
743
  query UserEmail($email: String!) {
743
744
  checkAvailability {
744
745
  email(email: $email)
745
746
  }
746
747
  }
747
- `),Pp=new E(`
748
+ `),tp=new E(`
748
749
  mutation AcceptInvitation($invitationId: InvitationId!) {
749
750
  acceptInvitation(invitationId: $invitationId) {
750
751
  id
751
752
  }
752
753
  }
753
- `),kp=new E(`
754
+ `),np=new E(`
754
755
  query Invitations {
755
756
  invitations(first: 100) {
756
757
  edges {
@@ -770,7 +771,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
770
771
  }
771
772
  }
772
773
  }
773
- `),Ap=new E(`
774
+ `),rp=new E(`
774
775
  query Workspace($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {
775
776
  organization(slug: $organizationSlug) {
776
777
  workspace(slug: $workspaceSlug) {
@@ -791,7 +792,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
791
792
  }
792
793
  }
793
794
  }
794
- `),Ep=new E(`
795
+ `),ip=new E(`
795
796
  query Workspaces($organizationSlug: ReadableId!) {
796
797
  organization(slug: $organizationSlug) {
797
798
  workspaces(first: 100) {
@@ -816,7 +817,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
816
817
  }
817
818
  }
818
819
  }
819
- `),Rp=new E(`
820
+ `),op=new E(`
820
821
  mutation CreateWorkspace($organizationId: OrganizationId!, $payload: CreateWorkspacePayload!) {
821
822
  createWorkspace(organizationId: $organizationId, payload: $payload) {
822
823
  id
@@ -835,7 +836,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
835
836
  }
836
837
  }
837
838
  }
838
- `),Tp=new E(`
839
+ `),ap=new E(`
839
840
  query FindWorkspaceSlug($organizationId: OrganizationId!, $slugFirstOption: ReadableId!, $slugSecondOption: ReadableId!, $slugThirdOption: ReadableId!) {
840
841
  checkAvailability {
841
842
  slugFirstOption: workspaceSlug(
@@ -852,7 +853,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
852
853
  )
853
854
  }
854
855
  }
855
- `),Op=new E(`
856
+ `),sp=new E(`
856
857
  query WorkspaceFeatures($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {
857
858
  organization(slug: $organizationSlug) {
858
859
  workspace(slug: $workspaceSlug) {
@@ -878,7 +879,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
878
879
  }
879
880
  }
880
881
  }
881
- `),Dp=new E(`
882
+ `),pp=new E(`
882
883
  mutation CreateResources($workspaceId: WorkspaceId!, $payload: CreateWorkspaceResourcePayload!) {
883
884
  createWorkspaceResources(workspaceId: $workspaceId, payload: $payload) {
884
885
  slots
@@ -890,7 +891,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
890
891
  }
891
892
  }
892
893
  }
893
- `);var Yl={"\n query ApplicationSlugAvailability(\n $workspaceId: WorkspaceId!\n $slugFirstOption: ReadableId!\n $slugSecondOption: ReadableId!\n $slugThirdOption: ReadableId!\n ) {\n checkAvailability {\n slugFirstOption: applicationSlug(workspaceId: $workspaceId, slug: $slugFirstOption)\n slugSecondOption: applicationSlug(workspaceId: $workspaceId, slug: $slugSecondOption)\n slugThirdOption: applicationSlug(workspaceId: $workspaceId, slug: $slugThirdOption)\n }\n }\n":Gs,"\n query Applications($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n applications(first: 100) {\n edges {\n node {\n id\n publicId\n name\n slug\n logo\n website\n environment\n platform\n applicationStatus\n settings {\n timeZone\n }\n }\n }\n }\n }\n }\n }\n":Zs,"\n query Application($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!, $applicationSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n application(slug: $applicationSlug) {\n id\n publicId\n name\n slug\n logo\n website\n environment\n platform\n applicationStatus\n settings {\n timeZone\n }\n }\n }\n }\n }\n":Qs,"\n mutation CreateApplication($workspaceId: WorkspaceId!, $payload: CreateWebApplicationPayload!) {\n createWebApplication(workspaceId: $workspaceId, payload: $payload) {\n id\n publicId\n name\n slug\n logo\n website\n environment\n platform\n applicationStatus\n settings {\n timeZone\n }\n }\n }\n":Js,"\n mutation CreateApiKey($applicationId: ApplicationId!, $payload: CreateApiKeyPayload!) {\n createApiKey(applicationId: $applicationId, payload: $payload) {\n apiKey {\n id\n name\n permissions\n }\n apiKeyValue\n }\n }\n":Bs,"\n query Audiences($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n audiences(first: 100) {\n edges {\n node {\n id\n customId\n name\n criteria\n }\n }\n }\n }\n }\n }\n":Ys,"\n query Audience(\n $organizationSlug: ReadableId!,\n $workspaceSlug: ReadableId!,\n $audienceSlug: ReadableId!\n ) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n audience(customId: $audienceSlug) {\n id\n customId\n name\n criteria\n }\n }\n }\n }\n":Xs,"\n mutation SignIn($payload: SignInPayload!) {\n signIn(payload: $payload) {\n token\n }\n }\n":ep,"\n mutation SignUp($payload: SignUpPayload!) {\n signUp(payload: $payload) {\n userId\n }\n }\n":tp,"\n mutation IssueToken($payload: IssueTokenPayload!) {\n issueToken(payload: $payload) \n }\n":np,"\n mutation ResetPassword($payload: ResetPasswordPayload!) {\n resetPassword(payload: $payload) {\n token\n }\n }\n":rp,"\n mutation RequestPasswordReset($email: String!, $sessionId: UserSessionId) {\n sendResetLink(email: $email, sessionId: $sessionId)\n }\n":ip,"\n mutation RetryActivation($email: String!, $sessionId: UserSessionId!) {\n retry {\n accountActivation(sessionId: $sessionId, email: $email)\n }\n }\n":op,"\n mutation CreateSession($redirectDestination: String) {\n createSession(redirectDestination: $redirectDestination)\n }\n":ap,"\n mutation CloseSession($sessionId: UserSessionId!) {\n closeSession(sessionId: $sessionId) {\n __typename\n ... on CloseSessionRecoveryGrantedResult {\n recoveryToken\n }\n ... on CloseSessionAccessGrantedResult {\n accessToken\n }\n }\n }\n":sp,"\n query Components($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n components(first: 100) {\n edges {\n node {\n id\n customId\n name\n description\n definition {\n definition,\n version {\n major\n minor\n }\n metadata {\n directReferences\n indirectReferences\n referenceMetadata {\n referenceName\n componentId\n }\n }\n }\n }\n }\n }\n }\n }\n }\n":pp,"\n query Component(\n $organizationSlug: ReadableId!,\n $workspaceSlug: ReadableId!,\n $componentSlug: ReadableId!,\n $majorVersion: Int\n ) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n component(customId: $componentSlug) {\n id\n customId\n name\n description\n definition(majorVersion: $majorVersion) {\n definition\n version {\n major\n minor\n }\n metadata {\n directReferences\n indirectReferences\n referenceMetadata {\n referenceName\n componentId\n }\n }\n }\n }\n }\n }\n }\n":cp,"\n query Experience(\n $organizationSlug: ReadableId!,\n $workspaceSlug: ReadableId!,\n $experienceId: ExperienceId!\n ) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n experience(id: $experienceId) {\n id,\n name,\n priority,\n status,\n hasExperiments,\n currentExperiment {\n id,\n name,\n crossDevice,\n goalId,\n traffic,\n status,\n variants {\n variantId\n name\n allocation\n baseline\n content {\n default {\n contents {\n slotId,\n content,\n locale,\n }\n },\n segmented {\n groupId,\n contents {\n slotId,\n content,\n locale,\n },\n audiences {\n audienceId\n }\n }\n }\n }\n }\n draft {\n priority,\n audiences {\n id,\n customId,\n },\n slots {\n slot {\n id,\n customId,\n }\n version {\n minor,\n major\n }\n },\n timeZone,\n content {\n default {\n contents {\n slotId,\n content,\n locale,\n }\n },\n segmented {\n groupId,\n contents {\n slotId,\n content,\n locale,\n },\n audiences {\n audienceId\n }\n }\n },\n experiment {\n name,\n crossDevice,\n goalId,\n traffic,\n variants {\n variantId\n name\n allocation\n baseline\n content {\n default {\n contents {\n slotId,\n content,\n locale,\n }\n },\n segmented {\n groupId,\n contents {\n slotId,\n content,\n locale,\n },\n audiences {\n audienceId\n }\n }\n }\n }\n }\n }\n settings {\n content {\n default {\n contents {\n slotId\n content,\n locale,\n }\n },\n segmented {\n groupId,\n contents {\n slotId,\n content,\n locale,\n },\n audiences {\n audienceId\n }\n }\n }\n audiences {\n id,\n customId,\n }\n slots {\n slot {\n id,\n customId,\n }\n version {\n minor,\n major\n }\n }\n }\n }\n }\n }\n }\n":lp,"\n query Experiences($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!, $status: [ExperienceStatus!]) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n experiences(first: 100, status: $status) {\n edges {\n node {\n id,\n name,\n priority,\n status,\n currentExperiment {\n name,\n },\n draft {\n priority,\n audiences {\n id,\n customId,\n },\n slots {\n slot {\n id,\n customId,\n }\n version {\n minor,\n major\n }\n },\n experiment {\n name,\n }\n }\n settings {\n audiences {\n id,\n customId\n }\n slots {\n slot {\n id,\n customId\n }\n version {\n minor,\n major\n }\n }\n }\n }\n }\n }\n }\n }\n }\n":up,"\n query ResourceIdQuery(\n $organizationSlug: ReadableId!,\n $workspaceSlug: ReadableId,\n $applicationSlug: ReadableId\n ) {\n organization(slug: $organizationSlug) {\n id\n workspace(slug: $workspaceSlug) {\n id\n application(slug: $applicationSlug) {\n id\n }\n }\n }\n }\n":mp,"\n query Organization($slug: ReadableId!) {\n organization(slug: $slug) {\n id\n name\n slug\n type\n website\n logo\n email\n }\n }\n":dp,"\n query Organizations {\n organizations(first: 100) {\n edges {\n node {\n id\n name\n slug\n type\n website\n logo\n email\n }\n }\n }\n }\n":gp,"\n mutation SetupOrganization($payload: CreateConfiguredOrganizationPayload!) {\n createConfiguredOrganization(payload: $payload) {\n organization {\n id\n name\n slug\n type\n website\n logo\n email\n }\n }\n }\n":fp,"\n query FindOrganizationSlug(\n $slugFirstOption: ReadableId!\n $slugSecondOption: ReadableId!\n $slugThirdOption: ReadableId!\n ) {\n checkAvailability {\n slugFirstOption: organizationSlug(slug: $slugFirstOption)\n slugSecondOption: organizationSlug(slug: $slugSecondOption)\n slugThirdOption: organizationSlug(slug: $slugThirdOption)\n }\n }\n":yp,"\n query OrganizationMetadata($url: String!) {\n websiteMetadata(url: $url){\n url\n siteName\n domain\n languages\n platform\n technologies {\n name\n }\n logo {\n data\n height\n width\n }\n }\n }\n":hp,"\n query Slots($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n slots(first: 100) {\n edges {\n node {\n id\n customId\n name\n content {\n component {\n customId\n definition {\n version {\n major\n minor\n }\n metadata {\n directReferences\n indirectReferences\n referenceMetadata {\n referenceName\n componentId\n }\n }\n }\n }\n version {\n major\n minor\n }\n componentDefinition {\n resolvedDefinition\n }\n default {\n content\n locale\n }\n }\n }\n }\n }\n }\n }\n }\n":Sp,"\n query Slot(\n $organizationSlug: ReadableId!,\n $workspaceSlug: ReadableId!,\n $slotSlug: ReadableId!,\n $majorVersion: Int\n ) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n slot(customId: $slotSlug) {\n id\n customId\n name\n content(majorVersion: $majorVersion) {\n component {\n customId\n definition {\n version {\n major\n minor\n }\n metadata {\n directReferences\n indirectReferences\n referenceMetadata {\n referenceName\n componentId\n }\n }\n }\n }\n version {\n major\n minor\n }\n componentDefinition {\n resolvedDefinition\n }\n default {\n content\n locale\n }\n }\n }\n }\n }\n }\n":bp,"\n query SlotStaticContent(\n $organizationSlug: ReadableId!,\n $workspaceSlug: ReadableId!,\n $slotSlug: ReadableId!\n $majorVersion: Int\n ) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n slot(customId: $slotSlug) {\n staticContent(majorVersion: $majorVersion) {\n locale\n content\n }\n }\n }\n }\n }\n":Ip,"\n mutation GenerateTyping($workspaceId: WorkspaceId!, $payload: GenerateTypingPayload!) {\n generateTyping(workspaceId: $workspaceId, payload: $payload)\n }\n":xp,"\n query User {\n userAccount {\n id\n user {\n username\n email\n profile {\n firstName\n lastName\n expertise\n }\n }\n }\n }\n":vp,"\n query Username(\n $slugFirstOption: ReadableId!\n $slugSecondOption: ReadableId!\n $slugThirdOption: ReadableId!\n ) {\n checkAvailability {\n slugFirstOption: username(username: $slugFirstOption)\n slugSecondOption: username(username: $slugSecondOption)\n slugThirdOption: username(username: $slugThirdOption)\n }\n }\n":wp,"\n query UserEmail($email: String!) {\n checkAvailability {\n email(email: $email)\n }\n }\n":Cp,"\n mutation AcceptInvitation($invitationId: InvitationId!) {\n acceptInvitation(invitationId: $invitationId) {\n id\n }\n }\n":Pp,"\n query Invitations {\n invitations(first: 100) {\n edges {\n node {\n id\n invitationTime\n organization {\n id\n name\n slug\n type\n website\n logo\n email\n }\n }\n }\n }\n }\n":kp,"\n query Workspace($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n id\n name\n slug\n logo\n website\n timeZone\n defaultLocale\n locales {\n edges {\n node {\n code\n }\n }\n }\n }\n }\n }\n":Ap,"\n query Workspaces($organizationSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspaces(first: 100) {\n edges {\n node {\n id\n name\n slug\n logo\n website\n timeZone\n defaultLocale\n locales {\n edges {\n node {\n code\n }\n }\n }\n }\n }\n }\n }\n }\n":Ep,"\n mutation CreateWorkspace($organizationId: OrganizationId!, $payload: CreateWorkspacePayload!) {\n createWorkspace(organizationId: $organizationId, payload: $payload) {\n id\n name\n slug\n logo\n website\n timeZone\n defaultLocale\n locales {\n edges {\n node {\n code\n }\n }\n }\n }\n }\n":Rp,"\n query FindWorkspaceSlug(\n $organizationId: OrganizationId!\n $slugFirstOption: ReadableId!\n $slugSecondOption: ReadableId!\n $slugThirdOption: ReadableId!\n ) {\n checkAvailability {\n slugFirstOption: workspaceSlug(organizationId: $organizationId, slug: $slugFirstOption)\n slugSecondOption: workspaceSlug(organizationId: $organizationId, slug: $slugSecondOption)\n slugThirdOption: workspaceSlug(organizationId: $organizationId, slug: $slugThirdOption)\n }\n }\n":Tp,"\n query WorkspaceFeatures($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n quotas {\n audience\n remainingAudiences\n component\n remainingComponents\n slot\n remainingSlots,\n experience\n remainingExperiences\n experiment\n remainingExperiments\n dynamicAttributesPerContent\n audiencesPerExperience\n }\n capabilities {\n features(requiredFeatures: [\n EXPERIMENT,\n CROSS_DEVICE_EXPERIMENT,\n API_DATA_EXPORT\n ])\n }\n } \n }\n }\n":Op,"\n mutation CreateResources($workspaceId: WorkspaceId!, $payload: CreateWorkspaceResourcePayload!) {\n createWorkspaceResources(workspaceId: $workspaceId, payload: $payload) {\n slots\n components\n audiences\n experiences {\n id,\n experimentId\n }\n }\n }\n":Dp};function x(o){return Yl[o]??{}}var Mp=x(`
894
+ `);var El={"\n query ApplicationSlugAvailability(\n $workspaceId: WorkspaceId!\n $slugFirstOption: ReadableId!\n $slugSecondOption: ReadableId!\n $slugThirdOption: ReadableId!\n ) {\n checkAvailability {\n slugFirstOption: applicationSlug(workspaceId: $workspaceId, slug: $slugFirstOption)\n slugSecondOption: applicationSlug(workspaceId: $workspaceId, slug: $slugSecondOption)\n slugThirdOption: applicationSlug(workspaceId: $workspaceId, slug: $slugThirdOption)\n }\n }\n":ws,"\n query Applications($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n applications(first: 100) {\n edges {\n node {\n id\n publicId\n name\n slug\n logo\n website\n environment\n platform\n applicationStatus\n settings {\n timeZone\n }\n }\n }\n }\n }\n }\n }\n":Ps,"\n query Application($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!, $applicationSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n application(slug: $applicationSlug) {\n id\n publicId\n name\n slug\n logo\n website\n environment\n platform\n applicationStatus\n settings {\n timeZone\n }\n }\n }\n }\n }\n":Cs,"\n mutation CreateApplication($workspaceId: WorkspaceId!, $payload: CreateWebApplicationPayload!) {\n createWebApplication(workspaceId: $workspaceId, payload: $payload) {\n id\n publicId\n name\n slug\n logo\n website\n environment\n platform\n applicationStatus\n settings {\n timeZone\n }\n }\n }\n":ks,"\n mutation CreateApiKey($applicationId: ApplicationId!, $payload: CreateApiKeyPayload!) {\n createApiKey(applicationId: $applicationId, payload: $payload) {\n apiKey {\n id\n name\n permissions\n }\n apiKeyValue\n }\n }\n":As,"\n query Audiences($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n audiences(first: 100) {\n edges {\n node {\n id\n customId\n name\n criteria\n }\n }\n }\n }\n }\n }\n":Es,"\n query Audience(\n $organizationSlug: ReadableId!,\n $workspaceSlug: ReadableId!,\n $audienceSlug: ReadableId!\n ) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n audience(customId: $audienceSlug) {\n id\n customId\n name\n criteria\n }\n }\n }\n }\n":Rs,"\n mutation SignIn($payload: SignInPayload!) {\n signIn(payload: $payload) {\n token\n }\n }\n":Ts,"\n mutation SignUp($payload: SignUpPayload!) {\n signUp(payload: $payload) {\n userId\n }\n }\n":Os,"\n mutation IssueToken($payload: IssueTokenPayload!) {\n issueToken(payload: $payload) \n }\n":Ds,"\n mutation ResetPassword($payload: ResetPasswordPayload!) {\n resetPassword(payload: $payload) {\n token\n }\n }\n":Ms,"\n mutation RequestPasswordReset($email: String!, $sessionId: UserSessionId) {\n sendResetLink(email: $email, sessionId: $sessionId)\n }\n":Ns,"\n mutation RetryActivation($email: String!, $sessionId: UserSessionId!) {\n retry {\n accountActivation(sessionId: $sessionId, email: $email)\n }\n }\n":$s,"\n mutation CreateSession($redirectDestination: String) {\n createSession(redirectDestination: $redirectDestination)\n }\n":zs,"\n mutation CloseSession($sessionId: UserSessionId!) {\n closeSession(sessionId: $sessionId) {\n __typename\n ... on CloseSessionRecoveryGrantedResult {\n recoveryToken\n }\n ... on CloseSessionAccessGrantedResult {\n accessToken\n }\n }\n }\n":_s,"\n query Components($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n components(first: 100) {\n edges {\n node {\n id\n customId\n name\n description\n definition {\n definition,\n version {\n major\n minor\n }\n metadata {\n directReferences\n indirectReferences\n referenceMetadata {\n referenceName\n componentId\n }\n }\n }\n }\n }\n }\n }\n }\n }\n":Ls,"\n query Component(\n $organizationSlug: ReadableId!,\n $workspaceSlug: ReadableId!,\n $componentSlug: ReadableId!,\n $majorVersion: Int\n ) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n component(customId: $componentSlug) {\n id\n customId\n name\n description\n definition(majorVersion: $majorVersion) {\n definition\n version {\n major\n minor\n }\n metadata {\n directReferences\n indirectReferences\n referenceMetadata {\n referenceName\n componentId\n }\n }\n }\n }\n }\n }\n }\n":Fs,"\n query Experience(\n $organizationSlug: ReadableId!,\n $workspaceSlug: ReadableId!,\n $experienceId: ExperienceId!\n ) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n experience(id: $experienceId) {\n id,\n name,\n priority,\n status,\n hasExperiments,\n currentExperiment {\n id,\n name,\n crossDevice,\n goalId,\n traffic,\n status,\n variants {\n variantId\n name\n allocation\n baseline\n content {\n default {\n contents {\n slotId,\n content,\n locale,\n }\n },\n segmented {\n groupId,\n contents {\n slotId,\n content,\n locale,\n },\n audiences {\n audienceId\n }\n }\n }\n }\n }\n draft {\n priority,\n audiences {\n id,\n customId,\n },\n slots {\n slot {\n id,\n customId,\n }\n version {\n minor,\n major\n }\n },\n timeZone,\n content {\n default {\n contents {\n slotId,\n content,\n locale,\n }\n },\n segmented {\n groupId,\n contents {\n slotId,\n content,\n locale,\n },\n audiences {\n audienceId\n }\n }\n },\n experiment {\n name,\n crossDevice,\n goalId,\n traffic,\n variants {\n variantId\n name\n allocation\n baseline\n content {\n default {\n contents {\n slotId,\n content,\n locale,\n }\n },\n segmented {\n groupId,\n contents {\n slotId,\n content,\n locale,\n },\n audiences {\n audienceId\n }\n }\n }\n }\n }\n }\n settings {\n content {\n default {\n contents {\n slotId\n content,\n locale,\n }\n },\n segmented {\n groupId,\n contents {\n slotId,\n content,\n locale,\n },\n audiences {\n audienceId\n }\n }\n }\n audiences {\n id,\n customId,\n }\n slots {\n slot {\n id,\n customId,\n }\n version {\n minor,\n major\n }\n }\n }\n }\n }\n }\n }\n":js,"\n query Experiences($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!, $status: [ExperienceStatus!]) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n experiences(first: 100, status: $status) {\n edges {\n node {\n id,\n name,\n priority,\n status,\n currentExperiment {\n name,\n },\n draft {\n priority,\n audiences {\n id,\n customId,\n },\n slots {\n slot {\n id,\n customId,\n }\n version {\n minor,\n major\n }\n },\n experiment {\n name,\n }\n }\n settings {\n audiences {\n id,\n customId\n }\n slots {\n slot {\n id,\n customId\n }\n version {\n minor,\n major\n }\n }\n }\n }\n }\n }\n }\n }\n }\n":Ws,"\n query ResourceIdQuery(\n $organizationSlug: ReadableId!,\n $workspaceSlug: ReadableId,\n $applicationSlug: ReadableId\n ) {\n organization(slug: $organizationSlug) {\n id\n workspace(slug: $workspaceSlug) {\n id\n application(slug: $applicationSlug) {\n id\n }\n }\n }\n }\n":Vs,"\n query Organization($slug: ReadableId!) {\n organization(slug: $slug) {\n id\n name\n slug\n type\n website\n logo\n email\n }\n }\n":Us,"\n query Organizations {\n organizations(first: 100) {\n edges {\n node {\n id\n name\n slug\n type\n website\n logo\n email\n }\n }\n }\n }\n":qs,"\n mutation SetupOrganization($payload: CreateConfiguredOrganizationPayload!) {\n createConfiguredOrganization(payload: $payload) {\n organization {\n id\n name\n slug\n type\n website\n logo\n email\n }\n }\n }\n":Hs,"\n query FindOrganizationSlug(\n $slugFirstOption: ReadableId!\n $slugSecondOption: ReadableId!\n $slugThirdOption: ReadableId!\n ) {\n checkAvailability {\n slugFirstOption: organizationSlug(slug: $slugFirstOption)\n slugSecondOption: organizationSlug(slug: $slugSecondOption)\n slugThirdOption: organizationSlug(slug: $slugThirdOption)\n }\n }\n":Gs,"\n query OrganizationMetadata($url: String!) {\n websiteMetadata(url: $url){\n url\n siteName\n domain\n languages\n platform\n technologies {\n name\n }\n logo {\n data\n height\n width\n }\n }\n }\n":Ks,"\n query Slots($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n slots(first: 100) {\n edges {\n node {\n id\n customId\n name\n content {\n component {\n customId\n definition {\n version {\n major\n minor\n }\n metadata {\n directReferences\n indirectReferences\n referenceMetadata {\n referenceName\n componentId\n }\n }\n }\n }\n version {\n major\n minor\n }\n componentDefinition {\n resolvedDefinition\n }\n default {\n content\n locale\n }\n }\n }\n }\n }\n }\n }\n }\n":Zs,"\n query Slot(\n $organizationSlug: ReadableId!,\n $workspaceSlug: ReadableId!,\n $slotSlug: ReadableId!,\n $majorVersion: Int\n ) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n slot(customId: $slotSlug) {\n id\n customId\n name\n content(majorVersion: $majorVersion) {\n component {\n customId\n definition {\n version {\n major\n minor\n }\n metadata {\n directReferences\n indirectReferences\n referenceMetadata {\n referenceName\n componentId\n }\n }\n }\n }\n version {\n major\n minor\n }\n componentDefinition {\n resolvedDefinition\n }\n default {\n content\n locale\n }\n }\n }\n }\n }\n }\n":Js,"\n query SlotStaticContent(\n $organizationSlug: ReadableId!,\n $workspaceSlug: ReadableId!,\n $slotSlug: ReadableId!\n $majorVersion: Int\n ) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n slot(customId: $slotSlug) {\n staticContent(majorVersion: $majorVersion) {\n locale\n content\n }\n }\n }\n }\n }\n":Qs,"\n mutation GenerateTyping($workspaceId: WorkspaceId!, $payload: GenerateTypingPayload!) {\n generateTyping(workspaceId: $workspaceId, payload: $payload)\n }\n":Bs,"\n query User {\n userAccount {\n id\n user {\n username\n email\n profile {\n firstName\n lastName\n expertise\n }\n }\n }\n }\n":Ys,"\n query Username(\n $slugFirstOption: ReadableId!\n $slugSecondOption: ReadableId!\n $slugThirdOption: ReadableId!\n ) {\n checkAvailability {\n slugFirstOption: username(username: $slugFirstOption)\n slugSecondOption: username(username: $slugSecondOption)\n slugThirdOption: username(username: $slugThirdOption)\n }\n }\n":Xs,"\n query UserEmail($email: String!) {\n checkAvailability {\n email(email: $email)\n }\n }\n":ep,"\n mutation AcceptInvitation($invitationId: InvitationId!) {\n acceptInvitation(invitationId: $invitationId) {\n id\n }\n }\n":tp,"\n query Invitations {\n invitations(first: 100) {\n edges {\n node {\n id\n invitationTime\n organization {\n id\n name\n slug\n type\n website\n logo\n email\n }\n }\n }\n }\n }\n":np,"\n query Workspace($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n id\n name\n slug\n logo\n website\n timeZone\n defaultLocale\n locales {\n edges {\n node {\n code\n }\n }\n }\n }\n }\n }\n":rp,"\n query Workspaces($organizationSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspaces(first: 100) {\n edges {\n node {\n id\n name\n slug\n logo\n website\n timeZone\n defaultLocale\n locales {\n edges {\n node {\n code\n }\n }\n }\n }\n }\n }\n }\n }\n":ip,"\n mutation CreateWorkspace($organizationId: OrganizationId!, $payload: CreateWorkspacePayload!) {\n createWorkspace(organizationId: $organizationId, payload: $payload) {\n id\n name\n slug\n logo\n website\n timeZone\n defaultLocale\n locales {\n edges {\n node {\n code\n }\n }\n }\n }\n }\n":op,"\n query FindWorkspaceSlug(\n $organizationId: OrganizationId!\n $slugFirstOption: ReadableId!\n $slugSecondOption: ReadableId!\n $slugThirdOption: ReadableId!\n ) {\n checkAvailability {\n slugFirstOption: workspaceSlug(organizationId: $organizationId, slug: $slugFirstOption)\n slugSecondOption: workspaceSlug(organizationId: $organizationId, slug: $slugSecondOption)\n slugThirdOption: workspaceSlug(organizationId: $organizationId, slug: $slugThirdOption)\n }\n }\n":ap,"\n query WorkspaceFeatures($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {\n organization(slug: $organizationSlug) {\n workspace(slug: $workspaceSlug) {\n quotas {\n audience\n remainingAudiences\n component\n remainingComponents\n slot\n remainingSlots,\n experience\n remainingExperiences\n experiment\n remainingExperiments\n dynamicAttributesPerContent\n audiencesPerExperience\n }\n capabilities {\n features(requiredFeatures: [\n EXPERIMENT,\n CROSS_DEVICE_EXPERIMENT,\n API_DATA_EXPORT\n ])\n }\n } \n }\n }\n":sp,"\n mutation CreateResources($workspaceId: WorkspaceId!, $payload: CreateWorkspaceResourcePayload!) {\n createWorkspaceResources(workspaceId: $workspaceId, payload: $payload) {\n slots\n components\n audiences\n experiences {\n id,\n experimentId\n }\n }\n }\n":pp};function x(o){return El[o]??{}}var cp=x(`
894
895
  query ResourceIdQuery(
895
896
  $organizationSlug: ReadableId!,
896
897
  $workspaceSlug: ReadableId,
@@ -906,7 +907,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
906
907
  }
907
908
  }
908
909
  }
909
- `),Np=x(`
910
+ `),lp=x(`
910
911
  query Organization($slug: ReadableId!) {
911
912
  organization(slug: $slug) {
912
913
  id
@@ -918,7 +919,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
918
919
  email
919
920
  }
920
921
  }
921
- `),$p=x(`
922
+ `),up=x(`
922
923
  query Organizations {
923
924
  organizations(first: 100) {
924
925
  edges {
@@ -934,7 +935,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
934
935
  }
935
936
  }
936
937
  }
937
- `),zp=x(`
938
+ `),mp=x(`
938
939
  mutation SetupOrganization($payload: CreateConfiguredOrganizationPayload!) {
939
940
  createConfiguredOrganization(payload: $payload) {
940
941
  organization {
@@ -948,7 +949,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
948
949
  }
949
950
  }
950
951
  }
951
- `),_p=x(`
952
+ `),dp=x(`
952
953
  query FindOrganizationSlug(
953
954
  $slugFirstOption: ReadableId!
954
955
  $slugSecondOption: ReadableId!
@@ -960,7 +961,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
960
961
  slugThirdOption: organizationSlug(slug: $slugThirdOption)
961
962
  }
962
963
  }
963
- `),Lp=x(`
964
+ `),gp=x(`
964
965
  query OrganizationMetadata($url: String!) {
965
966
  websiteMetadata(url: $url){
966
967
  url
@@ -978,7 +979,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
978
979
  }
979
980
  }
980
981
  }
981
- `);var Fp=x(`
982
+ `);var fp=x(`
982
983
  query User {
983
984
  userAccount {
984
985
  id
@@ -993,7 +994,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
993
994
  }
994
995
  }
995
996
  }
996
- `),jp=x(`
997
+ `),yp=x(`
997
998
  query Username(
998
999
  $slugFirstOption: ReadableId!
999
1000
  $slugSecondOption: ReadableId!
@@ -1005,19 +1006,19 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
1005
1006
  slugThirdOption: username(username: $slugThirdOption)
1006
1007
  }
1007
1008
  }
1008
- `),Wp=x(`
1009
+ `),hp=x(`
1009
1010
  query UserEmail($email: String!) {
1010
1011
  checkAvailability {
1011
1012
  email(email: $email)
1012
1013
  }
1013
1014
  }
1014
- `),Vp=x(`
1015
+ `),Sp=x(`
1015
1016
  mutation AcceptInvitation($invitationId: InvitationId!) {
1016
1017
  acceptInvitation(invitationId: $invitationId) {
1017
1018
  id
1018
1019
  }
1019
1020
  }
1020
- `),Up=x(`
1021
+ `),bp=x(`
1021
1022
  query Invitations {
1022
1023
  invitations(first: 100) {
1023
1024
  edges {
@@ -1037,43 +1038,43 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
1037
1038
  }
1038
1039
  }
1039
1040
  }
1040
- `);var qp=x(`
1041
+ `);var Ip=x(`
1041
1042
  mutation SignIn($payload: SignInPayload!) {
1042
1043
  signIn(payload: $payload) {
1043
1044
  token
1044
1045
  }
1045
1046
  }
1046
- `),Hp=x(`
1047
+ `),xp=x(`
1047
1048
  mutation SignUp($payload: SignUpPayload!) {
1048
1049
  signUp(payload: $payload) {
1049
1050
  userId
1050
1051
  }
1051
1052
  }
1052
- `),Kp=x(`
1053
+ `),vp=x(`
1053
1054
  mutation IssueToken($payload: IssueTokenPayload!) {
1054
1055
  issueToken(payload: $payload)
1055
1056
  }
1056
- `),Gp=x(`
1057
+ `),wp=x(`
1057
1058
  mutation ResetPassword($payload: ResetPasswordPayload!) {
1058
1059
  resetPassword(payload: $payload) {
1059
1060
  token
1060
1061
  }
1061
1062
  }
1062
- `),Zp=x(`
1063
+ `),Pp=x(`
1063
1064
  mutation RequestPasswordReset($email: String!, $sessionId: UserSessionId) {
1064
1065
  sendResetLink(email: $email, sessionId: $sessionId)
1065
1066
  }
1066
- `),Qp=x(`
1067
+ `),Cp=x(`
1067
1068
  mutation RetryActivation($email: String!, $sessionId: UserSessionId!) {
1068
1069
  retry {
1069
1070
  accountActivation(sessionId: $sessionId, email: $email)
1070
1071
  }
1071
1072
  }
1072
- `),Jp=x(`
1073
+ `),kp=x(`
1073
1074
  mutation CreateSession($redirectDestination: String) {
1074
1075
  createSession(redirectDestination: $redirectDestination)
1075
1076
  }
1076
- `),Bp=x(`
1077
+ `),Ap=x(`
1077
1078
  mutation CloseSession($sessionId: UserSessionId!) {
1078
1079
  closeSession(sessionId: $sessionId) {
1079
1080
  __typename
@@ -1085,7 +1086,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
1085
1086
  }
1086
1087
  }
1087
1088
  }
1088
- `);var mn=class o{constructor(e){this.client=e;}async getUser(){let{data:e}=await this.client.execute(Fp),{id:t,user:n}=e.userAccount,{profile:{lastName:r=null}}=n;return {id:t,username:n.profile.firstName,email:n.email,firstName:n.profile.firstName,expertise:n.profile.expertise,...r!==null?{lastName:r}:{}}}async isEmailRegistered(e){let{data:t}=await this.client.execute(Wp,{email:e});return !t.checkAvailability.email}async requestPasswordReset(e){await this.client.execute(Zp,{email:e.email,sessionId:e.sessionId});}async resetPassword(e){let{data:t}=await this.client.execute(Gp,{payload:{password:e.password,token:e.token}});return t.resetPassword.token}async retryActivation(e){await this.client.execute(Qp,{email:e.email,sessionId:e.sessionId});}async registerUser(e){await this.client.execute(Hp,{payload:{username:await this.generateUsername(`${e.firstName} ${e.lastName??""}`.trim()),email:e.email,password:e.password,firstName:e.firstName,lastName:e.lastName,expertise:e.expertise,sessionId:e.sessionId,bypassOnboarding:true}});}async createSession(e){let{data:t}=await this.client.execute(Jp,{redirectDestination:e?.destination});return t.createSession}async closeSession(e){let{data:t}=await this.client.execute(Bp,{sessionId:e});switch(t.closeSession.__typename){case "CloseSessionAccessGrantedResult":return {status:"access-granted",accessToken:t.closeSession.accessToken};case "CloseSessionRecoveryGrantedResult":return {status:"recovery-granted",recoveryToken:t.closeSession.recoveryToken};case "CloseSessionPendingResult":return {status:"pending"}}}async signIn(e){let{data:t}=await this.client.execute(qp,{payload:{email:e.email,password:e.password,duration:e.duration,remember:false}});return t.signIn.token}async issueToken(e){let{data:t}=await this.client.execute(Kp,{payload:{duration:e.duration}});return t.issueToken}async getOrganization(e){let{data:t}=await this.client.execute(Np,{slug:e}),n=t.organization??null;return n===null?null:o.normalizeOrganization(n)}async getOrganizations(){let{data:e}=await this.client.execute($p);return (e.organizations.edges??[]).flatMap(n=>{let r=n?.node??null;return r===null||r.slug==="demo"?[]:[o.normalizeOrganization(r)]})}async setupOrganization(e){let{data:t}=await this.client.execute(zp,{payload:await this.getOrganizationSetupPayload(e)}),{organization:n}=t.createConfiguredOrganization,{logo:r=null,website:i=null}=n;return {id:n.id,name:n.name,slug:n.slug,type:n.type,email:n.email,...r!==null?{logo:r}:{},...i!==null?{website:i}:{}}}async getOrganizationSetupPayload(e){let t=new URL(e.website),n=await this.getUser(),r=`${n.firstName} ${n.lastName??""}`.trim();if(t.hostname.toLowerCase()==="localhost")return {locale:e.locale,timeZone:e.timeZone,acceptedTerms:true,organization:{website:t.origin,email:n.email,name:"Personal organization",slug:await this.generateOrganizationSlug(r,true),type:"PERSONAL"},workspace:{name:"Personal workspace",slug:un({baseName:r,alwaysSuffixed:true}).next().value,website:t.origin},applications:[{environment:"DEVELOPMENT",name:"Website",slug:"website-dev",website:t.origin,platform:"JAVASCRIPT"}],audiences:[],components:[],experiences:[],slots:[],redirectUrl:e.redirectUrl};let i=await this.getOrganizationMetadata(t),a=`${t.protocol}//${i.domain}`,s=i.logo!==null&&i.logo!==void 0&&i.logo.width>=64&&i.logo.height>=64?i.logo.data:void 0;return {locale:i.languages[0]??e.locale,timeZone:e.timeZone,acceptedTerms:true,organization:{website:a,email:n.email,name:i.siteName,slug:await this.generateOrganizationSlug(i.siteName,false),type:"BUSINESS",logo:s},workspace:{name:i.siteName,slug:un({baseName:i.siteName,alwaysSuffixed:false}).next().value,logo:s,website:a},applications:[{environment:"PRODUCTION",name:"Website",slug:"website-prod",website:t.origin,platform:i.platform},{environment:"DEVELOPMENT",name:"Website",slug:"website-dev",website:t.origin,platform:i.platform}],audiences:[],components:[],experiences:[],slots:[],redirectUrl:e.redirectUrl}}async getInvitations(){let{data:e}=await this.client.execute(Up);return (e.invitations.edges??[]).flatMap(n=>{let r=n?.node??null;return r===null?[]:[{id:r.id,invitationTime:r.invitationTime,organization:o.normalizeOrganization(r.organization)}]})}async acceptInvitation(e){await this.client.execute(Vp,{invitationId:e});}static normalizeOrganization(e){let{logo:t=null,website:n=null}=e;return {id:e.id,name:e.name,slug:e.slug,type:e.type,email:e.email,...t!==null?{logo:t}:{},...n!==null?{website:n}:{}}}async getOrganizationMetadata(e){let{data:t}=await this.client.execute(Lp,{url:e.toString()});return t.websiteMetadata}generateOrganizationSlug(e,t=false){return mt({query:_p,baseName:e,client:this.client,alwaysSuffixed:t})}generateUsername(e){return mt({query:jp,baseName:e,client:this.client,alwaysSuffixed:false})}};var Yp=x(`
1089
+ `);var en=class o{constructor(e){this.client=e;}async getUser(){let{data:e}=await this.client.execute(fp),{id:t,user:n}=e.userAccount,{profile:{lastName:r=null}}=n;return {id:t,username:n.profile.firstName,email:n.email,firstName:n.profile.firstName,expertise:n.profile.expertise,...r!==null?{lastName:r}:{}}}async isEmailRegistered(e){let{data:t}=await this.client.execute(hp,{email:e});return !t.checkAvailability.email}async requestPasswordReset(e){await this.client.execute(Pp,{email:e.email,sessionId:e.sessionId});}async resetPassword(e){let{data:t}=await this.client.execute(wp,{payload:{password:e.password,token:e.token}});return t.resetPassword.token}async retryActivation(e){await this.client.execute(Cp,{email:e.email,sessionId:e.sessionId});}async registerUser(e){await this.client.execute(xp,{payload:{username:await this.generateUsername(`${e.firstName} ${e.lastName??""}`.trim()),email:e.email,password:e.password,firstName:e.firstName,lastName:e.lastName,expertise:e.expertise,sessionId:e.sessionId,bypassOnboarding:true}});}async createSession(e){let{data:t}=await this.client.execute(kp,{redirectDestination:e?.destination});return t.createSession}async closeSession(e){let{data:t}=await this.client.execute(Ap,{sessionId:e});switch(t.closeSession.__typename){case "CloseSessionAccessGrantedResult":return {status:"access-granted",accessToken:t.closeSession.accessToken};case "CloseSessionRecoveryGrantedResult":return {status:"recovery-granted",recoveryToken:t.closeSession.recoveryToken};case "CloseSessionPendingResult":return {status:"pending"}}}async signIn(e){let{data:t}=await this.client.execute(Ip,{payload:{email:e.email,password:e.password,duration:e.duration,remember:false}});return t.signIn.token}async issueToken(e){let{data:t}=await this.client.execute(vp,{payload:{duration:e.duration}});return t.issueToken}async getOrganization(e){let{data:t}=await this.client.execute(lp,{slug:e}),n=t.organization??null;return n===null?null:o.normalizeOrganization(n)}async getOrganizations(){let{data:e}=await this.client.execute(up);return (e.organizations.edges??[]).flatMap(n=>{let r=n?.node??null;return r===null||r.slug==="demo"?[]:[o.normalizeOrganization(r)]})}async setupOrganization(e){let{data:t}=await this.client.execute(mp,{payload:await this.getOrganizationSetupPayload(e)}),{organization:n}=t.createConfiguredOrganization,{logo:r=null,website:i=null}=n;return {id:n.id,name:n.name,slug:n.slug,type:n.type,email:n.email,...r!==null?{logo:r}:{},...i!==null?{website:i}:{}}}async getOrganizationSetupPayload(e){let t=new URL(e.website),n=await this.getUser(),r=`${n.firstName} ${n.lastName??""}`.trim();if(t.hostname.toLowerCase()==="localhost")return {locale:e.locale,timeZone:e.timeZone,acceptedTerms:true,organization:{website:t.origin,email:n.email,name:"Personal organization",slug:await this.generateOrganizationSlug(r,true),type:"PERSONAL"},workspace:{name:"Personal workspace",slug:Xt({baseName:r,alwaysSuffixed:true}).next().value,website:t.origin},applications:[{environment:"DEVELOPMENT",name:"Website",slug:"website-dev",website:t.origin,platform:"JAVASCRIPT"}],audiences:[],components:[],experiences:[],slots:[],redirectUrl:e.redirectUrl};let i=await this.getOrganizationMetadata(t),a=`${t.protocol}//${i.domain}`,s=i.logo!==null&&i.logo!==void 0&&i.logo.width>=64&&i.logo.height>=64?i.logo.data:void 0;return {locale:i.languages[0]??e.locale,timeZone:e.timeZone,acceptedTerms:true,organization:{website:a,email:n.email,name:i.siteName,slug:await this.generateOrganizationSlug(i.siteName,false),type:"BUSINESS",logo:s},workspace:{name:i.siteName,slug:Xt({baseName:i.siteName,alwaysSuffixed:false}).next().value,logo:s,website:a},applications:[{environment:"PRODUCTION",name:"Website",slug:"website-prod",website:t.origin,platform:i.platform},{environment:"DEVELOPMENT",name:"Website",slug:"website-dev",website:t.origin,platform:i.platform}],audiences:[],components:[],experiences:[],slots:[],redirectUrl:e.redirectUrl}}async getInvitations(){let{data:e}=await this.client.execute(bp);return (e.invitations.edges??[]).flatMap(n=>{let r=n?.node??null;return r===null?[]:[{id:r.id,invitationTime:r.invitationTime,organization:o.normalizeOrganization(r.organization)}]})}async acceptInvitation(e){await this.client.execute(Sp,{invitationId:e});}static normalizeOrganization(e){let{logo:t=null,website:n=null}=e;return {id:e.id,name:e.name,slug:e.slug,type:e.type,email:e.email,...t!==null?{logo:t}:{},...n!==null?{website:n}:{}}}async getOrganizationMetadata(e){let{data:t}=await this.client.execute(gp,{url:e.toString()});return t.websiteMetadata}generateOrganizationSlug(e,t=false){return ot({query:dp,baseName:e,client:this.client,alwaysSuffixed:t})}generateUsername(e){return ot({query:yp,baseName:e,client:this.client,alwaysSuffixed:false})}};var Ep=x(`
1089
1090
  query Workspace($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {
1090
1091
  organization(slug: $organizationSlug) {
1091
1092
  workspace(slug: $workspaceSlug) {
@@ -1106,7 +1107,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
1106
1107
  }
1107
1108
  }
1108
1109
  }
1109
- `),Xp=x(`
1110
+ `),Rp=x(`
1110
1111
  query Workspaces($organizationSlug: ReadableId!) {
1111
1112
  organization(slug: $organizationSlug) {
1112
1113
  workspaces(first: 100) {
@@ -1131,7 +1132,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
1131
1132
  }
1132
1133
  }
1133
1134
  }
1134
- `),ec=x(`
1135
+ `),Tp=x(`
1135
1136
  mutation CreateWorkspace($organizationId: OrganizationId!, $payload: CreateWorkspacePayload!) {
1136
1137
  createWorkspace(organizationId: $organizationId, payload: $payload) {
1137
1138
  id
@@ -1150,7 +1151,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
1150
1151
  }
1151
1152
  }
1152
1153
  }
1153
- `),tc=x(`
1154
+ `),Op=x(`
1154
1155
  query FindWorkspaceSlug(
1155
1156
  $organizationId: OrganizationId!
1156
1157
  $slugFirstOption: ReadableId!
@@ -1163,7 +1164,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
1163
1164
  slugThirdOption: workspaceSlug(organizationId: $organizationId, slug: $slugThirdOption)
1164
1165
  }
1165
1166
  }
1166
- `),nc=x(`
1167
+ `),Dp=x(`
1167
1168
  query WorkspaceFeatures($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {
1168
1169
  organization(slug: $organizationSlug) {
1169
1170
  workspace(slug: $workspaceSlug) {
@@ -1191,7 +1192,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
1191
1192
  }
1192
1193
  }
1193
1194
  }
1194
- `),rc=x(`
1195
+ `),Mp=x(`
1195
1196
  mutation CreateResources($workspaceId: WorkspaceId!, $payload: CreateWorkspaceResourcePayload!) {
1196
1197
  createWorkspaceResources(workspaceId: $workspaceId, payload: $payload) {
1197
1198
  slots
@@ -1203,7 +1204,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
1203
1204
  }
1204
1205
  }
1205
1206
  }
1206
- `);var Cr=class o{constructor(e,t){this.client=e,this.hierarchyResolver=t;}async getWorkspace(e){let{data:t}=await this.client.execute(Yp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug}),n=t.organization?.workspace??null;return n===null?null:o.normalizeWorkspace(n)}async getWorkspaces(e){let{data:t}=await this.client.execute(Xp,{organizationSlug:e.organizationSlug});return (t.organization?.workspaces.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[o.normalizeWorkspace(i)]})}static normalizeWorkspace(e){let{logo:t=null,website:n=null,locales:{edges:r=[]}}=e;return {id:e.id,name:e.name,slug:e.slug,timeZone:e.timeZone,defaultLocale:e.defaultLocale,locales:r?.flatMap(i=>{let a=i?.node?.code??null;return a===null?[]:[a]})??[],...t!==null?{logo:t}:{},...n!==null?{website:n}:{}}}async createWorkspace(e){let t=await this.hierarchyResolver.getHierarchy({organizationSlug:e.organizationSlug}),{data:n}=await this.client.execute(ec,{organizationId:t.organizationId,payload:{name:e.name,slug:await this.generateWorkspaceSlug(t.organizationId,e.name),timeZone:e.timeZone,defaultLocale:e.defaultLocale,website:e.website}}),r=n.createWorkspace,{logo:i=null,website:a=null,locales:{edges:s=[]}}=r;return {id:r.id,name:r.name,slug:r.slug,timeZone:r.timeZone,defaultLocale:r.defaultLocale,locales:s?.flatMap(p=>{let c=p?.node?.code??null;return c===null?[]:[c]})??[],...i!==null?{logo:i}:{},...a!==null?{website:a}:{}}}generateWorkspaceSlug(e,t){return mt({query:tc,baseName:t,client:this.client,variables:{organizationId:e}})}};var ic=x(`
1207
+ `);var ar=class o{constructor(e,t){this.client=e,this.hierarchyResolver=t;}async getWorkspace(e){let{data:t}=await this.client.execute(Ep,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug}),n=t.organization?.workspace??null;return n===null?null:o.normalizeWorkspace(n)}async getWorkspaces(e){let{data:t}=await this.client.execute(Rp,{organizationSlug:e.organizationSlug});return (t.organization?.workspaces.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[o.normalizeWorkspace(i)]})}static normalizeWorkspace(e){let{logo:t=null,website:n=null,locales:{edges:r=[]}}=e;return {id:e.id,name:e.name,slug:e.slug,timeZone:e.timeZone,defaultLocale:e.defaultLocale,locales:r?.flatMap(i=>{let a=i?.node?.code??null;return a===null?[]:[a]})??[],...t!==null?{logo:t}:{},...n!==null?{website:n}:{}}}async createWorkspace(e){let t=await this.hierarchyResolver.getHierarchy({organizationSlug:e.organizationSlug}),{data:n}=await this.client.execute(Tp,{organizationId:t.organizationId,payload:{name:e.name,slug:await this.generateWorkspaceSlug(t.organizationId,e.name),timeZone:e.timeZone,defaultLocale:e.defaultLocale,website:e.website}}),r=n.createWorkspace,{logo:i=null,website:a=null,locales:{edges:s=[]}}=r;return {id:r.id,name:r.name,slug:r.slug,timeZone:r.timeZone,defaultLocale:r.defaultLocale,locales:s?.flatMap(p=>{let c=p?.node?.code??null;return c===null?[]:[c]})??[],...i!==null?{logo:i}:{},...a!==null?{website:a}:{}}}generateWorkspaceSlug(e,t){return ot({query:Op,baseName:t,client:this.client,variables:{organizationId:e}})}};var Np=x(`
1207
1208
  query Audiences($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {
1208
1209
  organization(slug: $organizationSlug) {
1209
1210
  workspace(slug: $workspaceSlug) {
@@ -1220,7 +1221,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
1220
1221
  }
1221
1222
  }
1222
1223
  }
1223
- `),oc=x(`
1224
+ `),$p=x(`
1224
1225
  query Audience(
1225
1226
  $organizationSlug: ReadableId!,
1226
1227
  $workspaceSlug: ReadableId!,
@@ -1237,7 +1238,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
1237
1238
  }
1238
1239
  }
1239
1240
  }
1240
- `);var ac=x(`
1241
+ `);var zp=x(`
1241
1242
  query Slots($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {
1242
1243
  organization(slug: $organizationSlug) {
1243
1244
  workspace(slug: $workspaceSlug) {
@@ -1283,7 +1284,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
1283
1284
  }
1284
1285
  }
1285
1286
  }
1286
- `),sc=x(`
1287
+ `),_p=x(`
1287
1288
  query Slot(
1288
1289
  $organizationSlug: ReadableId!,
1289
1290
  $workspaceSlug: ReadableId!,
@@ -1330,7 +1331,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
1330
1331
  }
1331
1332
  }
1332
1333
  }
1333
- `),pc=x(`
1334
+ `),Lp=x(`
1334
1335
  query SlotStaticContent(
1335
1336
  $organizationSlug: ReadableId!,
1336
1337
  $workspaceSlug: ReadableId!,
@@ -1348,7 +1349,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
1348
1349
  }
1349
1350
  }
1350
1351
  }
1351
- `);var cc=x(`
1352
+ `);var Fp=x(`
1352
1353
  query ApplicationSlugAvailability(
1353
1354
  $workspaceId: WorkspaceId!
1354
1355
  $slugFirstOption: ReadableId!
@@ -1361,7 +1362,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
1361
1362
  slugThirdOption: applicationSlug(workspaceId: $workspaceId, slug: $slugThirdOption)
1362
1363
  }
1363
1364
  }
1364
- `),lc=x(`
1365
+ `),jp=x(`
1365
1366
  query Applications($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {
1366
1367
  organization(slug: $organizationSlug) {
1367
1368
  workspace(slug: $workspaceSlug) {
@@ -1386,7 +1387,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
1386
1387
  }
1387
1388
  }
1388
1389
  }
1389
- `),uc=x(`
1390
+ `),Wp=x(`
1390
1391
  query Application($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!, $applicationSlug: ReadableId!) {
1391
1392
  organization(slug: $organizationSlug) {
1392
1393
  workspace(slug: $workspaceSlug) {
@@ -1407,7 +1408,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
1407
1408
  }
1408
1409
  }
1409
1410
  }
1410
- `),mc=x(`
1411
+ `),Vp=x(`
1411
1412
  mutation CreateApplication($workspaceId: WorkspaceId!, $payload: CreateWebApplicationPayload!) {
1412
1413
  createWebApplication(workspaceId: $workspaceId, payload: $payload) {
1413
1414
  id
@@ -1424,7 +1425,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
1424
1425
  }
1425
1426
  }
1426
1427
  }
1427
- `),dc=x(`
1428
+ `),Up=x(`
1428
1429
  mutation CreateApiKey($applicationId: ApplicationId!, $payload: CreateApiKeyPayload!) {
1429
1430
  createApiKey(applicationId: $applicationId, payload: $payload) {
1430
1431
  apiKey {
@@ -1435,7 +1436,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
1435
1436
  apiKeyValue
1436
1437
  }
1437
1438
  }
1438
- `);var gc=x(`
1439
+ `);var qp=x(`
1439
1440
  query Components($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!) {
1440
1441
  organization(slug: $organizationSlug) {
1441
1442
  workspace(slug: $workspaceSlug) {
@@ -1467,7 +1468,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
1467
1468
  }
1468
1469
  }
1469
1470
  }
1470
- `),fc=x(`
1471
+ `),Hp=x(`
1471
1472
  query Component(
1472
1473
  $organizationSlug: ReadableId!,
1473
1474
  $workspaceSlug: ReadableId!,
@@ -1500,7 +1501,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
1500
1501
  }
1501
1502
  }
1502
1503
  }
1503
- `);var yc=x(`
1504
+ `);var Gp=x(`
1504
1505
  query Experience(
1505
1506
  $organizationSlug: ReadableId!,
1506
1507
  $workspaceSlug: ReadableId!,
@@ -1658,7 +1659,7 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
1658
1659
  }
1659
1660
  }
1660
1661
  }
1661
- `),hc=x(`
1662
+ `),Kp=x(`
1662
1663
  query Experiences($organizationSlug: ReadableId!, $workspaceSlug: ReadableId!, $status: [ExperienceStatus!]) {
1663
1664
  organization(slug: $organizationSlug) {
1664
1665
  workspace(slug: $workspaceSlug) {
@@ -1714,23 +1715,23 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
1714
1715
  }
1715
1716
  }
1716
1717
  }
1717
- `);var Sc=x(`
1718
+ `);var Zp=x(`
1718
1719
  mutation GenerateTyping($workspaceId: WorkspaceId!, $payload: GenerateTypingPayload!) {
1719
1720
  generateTyping(workspaceId: $workspaceId, payload: $payload)
1720
1721
  }
1721
- `);function Rt(o){return {model:o,api:Object.fromEntries(Object.entries(o).map(([e,t])=>[t,e]))}}var is=Rt({javascript:"JAVASCRIPT",react:"REACT",nextjs:"NEXT"}),os=Rt({DEVELOPMENT:"DEVELOPMENT",PRODUCTION:"PRODUCTION"}),bc=Rt({NEVER_RECEIVED_TRAFFIC:"NEVER_RECEIVED_TRAFFIC",NOT_RECEIVING_TRAFFIC:"NOT_RECEIVING_TRAFFIC",RECEIVING_TRAFFIC:"RECEIVING_TRAFFIC"}),tu=Rt({PLUG_JS:"PLUG_JS"}),as=Rt({DRAFT:"DRAFT",ACTIVE:"ACTIVE",SCHEDULED:"SCHEDULED",PAUSED:"PAUSED",ARCHIVED:"ARCHIVED"}),nu=Rt({DRAFT:"DRAFT",ACTIVE:"ACTIVE",SCHEDULED:"SCHEDULED",PAUSED:"PAUSED",FINISHED:"FINISHED",INDIRECTLY_PAUSED:"INDIRECTLY_PAUSED"}),Pr=class o{constructor(e,t){this.client=e,this.hierarchyResolver=t;}async getFeatures(e){let{data:t}=await this.client.execute(nc,{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(lc,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return (t.organization?.workspace?.applications.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[o.normalizeApplication(i)]})}async getApplication(e){let{data:t}=await this.client.execute(uc,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,applicationSlug:e.applicationSlug}),n=t.organization?.workspace?.application??null;return n===null?null:o.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:os.api[e.environment],platform:is.api[e.platform??"JAVASCRIPT"],publicId:e.publicId,trafficStatus:bc.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(mc,{workspaceId:t.workspaceId,payload:{name:e.name,website:e.website,environment:os.model[e.environment],platform:is.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:os.api[r.environment],platform:is.api[r.platform??"JAVASCRIPT"],publicId:r.publicId,trafficStatus:bc.api[r.applicationStatus],...i!==null?{logo:i}:{}}}async getAudiences(e){let{data:t}=await this.client.execute(ic,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return (t.organization?.workspace?.audiences.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[o.normalizeAudience(i)]})}async getAudience(e){let{data:t}=await this.client.execute(oc,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,audienceSlug:e.audienceSlug}),n=t.organization?.workspace?.audience??null;return n===null?null:o.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(gc,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return (t.organization?.workspace?.components.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[o.normalizeComponent(i)]})}async getComponent(e){let{data:t}=await this.client.execute(fc,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,componentSlug:e.componentSlug,majorVersion:e.majorVersion}),n=t.organization?.workspace?.component??null;return n===null?null:o.normalizeComponent(n)}static normalizeComponent(e){let{definition:t,metadata:{directReferences:n,indirectReferences:r,referenceMetadata:i}}=e.definition,a=e.description??null;return {id:e.id,name:e.name,slug:e.customId,...a!==null?{description:a}:{},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(ac,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return (t.organization?.workspace?.slots.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[o.normalizeSlot(i)]})}async getSlot(e){let{data:t}=await this.client.execute(sc,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,slotSlug:e.slotSlug,majorVersion:e.majorVersion}),n=t.organization?.workspace?.slot??null;return n===null?null:o.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(pc,{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(Sc,{workspaceId:t.workspaceId,payload:{target:tu.model[e.target],components:e.components,slots:e.slots}});return n.generateTyping}async getExperiences(e){let{data:t}=await this.client.execute(hc,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,status:e.status===void 0?void 0:(Array.isArray(e.status)?e.status:[e.status]).map(r=>as.model[r])});return (t.organization?.workspace?.experiences.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[o.normalizeExperience(i)]})}async getExperience(e){let{data:t}=await this.client.execute(yc,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,experienceId:e.experienceId}),n=t.organization?.workspace?.experience??null;return n===null?null:o.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:as.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:a=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:as.api[e.status],hasExperiments:e.hasExperiments,audiences:t.map(l=>l.customId),slots:Object.values(c),...r!==null?{experiment:{...i!==null?{name:i}:{},...a!==null?{goalId:a}:{},...s!==null?{crossDevice:s}:{},...p!==null?{traffic:p}:{},..."status"in r?{status:nu.api[r.status]}:{},variants:(r.variants??[]).map(l=>{let m=l.variantId,f=l.name??null,b=l.allocation??null;return {...m!==null?{id:m}:{},...f!==null?{name:f}:{},...b!==null?{allocation:b}:{},baseline:l.baseline===true,content:{default:o.normalizeLocalizedContent(l.content?.default.contents??[],c),segmented:(l.content?.segmented??[]).map(A=>({id:A.groupId,audiences:A.audiences.map(w=>w.audienceId),content:o.normalizeLocalizedContent(A.contents,c)}))}}})}}:{},content:{default:o.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:m})=>t.find(({id:f})=>f===m)?.customId??m),content:o.normalizeLocalizedContent(l.contents,c)}))}}}static normalizeLocalizedContent(e,t){let n={};for(let r of e){let{locale:i,slotId:a}=r,s=t[a];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,a])=>({customId:i,name:a.name,description:a.description,definition:a.definition})),slots:Object.entries(e.slots??{}).map(([i,a])=>({customId:i,name:a.name,component:a.component,defaultContent:Object.entries(a.content).map(([s,p])=>({locale:s,content:p}))})),audiences:Object.entries(e.audiences??{}).map(([i,a])=>({customId:i,name:a.name,criteria:a.criteria})),experiences:(e.experiences??[]).map(i=>{let a=i.experiment??null;return {name:i.name,audiences:i.audiences,slots:i.slots,experiment:a!==null?{name:a.name,goalId:a.goalId,traffic:a.traffic,crossDevice:a.crossDevice===true,variants:a.variants.map(s=>({id:crypto.randomUUID(),name:s.name??"",baseline:s.baseline===true,allocation:s.allocation??0,content:o.createContentVariantGroup(s.content)}))}:void 0,content:o.createContentVariantGroup(i.content),validate:true,publish:i.draft===false}})},{data:{createWorkspaceResources:r}}=await this.client.execute(rc,{workspaceId:t.workspaceId,payload:n});return {components:Object.fromEntries(n.components.map(({customId:i},a)=>[i,r.components[a]])),slots:Object.fromEntries(n.slots.map(({customId:i},a)=>[i,r.slots[a]])),audiences:Object.fromEntries(n.audiences.map(({customId:i},a)=>[i,r.audiences[a]])),experiences:r.experiences.map(i=>({experienceId:i.id,experimentId:i.experimentId??null}))}}static createContentVariantGroup(e){return {default:{id:crypto.randomUUID(),contents:o.createSlotContentMap(e.default)},segmented:e.segmented.map(t=>({id:crypto.randomUUID(),audiences:t.audiences,contents:o.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 mt({query:cc,baseName:`${t} ${n.slice(0,3).toLowerCase()}`,client:this.client,variables:{workspaceId:e}})}};var Xe;(t=>{function o(){return Intl.DateTimeFormat().resolvedOptions().locale.toLowerCase()}t.getLocale=o;function e(){return Intl.DateTimeFormat().resolvedOptions().timeZone}t.getTimeZone=e;})(Xe||(Xe={}));var Tt=class o{constructor(e){this.config=e;}static prompt(e){return new o(e).handle()}handle(){let{input:e,validate:t}=this.config;return e.prompt({message:this.config.label,default:this.config.default??"https://",validate:n=>URL.canParse(n)?t!==void 0?t(n):true:"Invalid URL"})}};var kr=class o{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=await t.getOrganizations(),m=o.getDefaultOrganization(l,e.default);if(m!==null)return c.confirm(`Organization: ${m.name}`),m;if(c.stop(),l.length>0)return r.select({message:"Select organization",options:l.map(f=>({value:f,label:f.name}))})}let i=Xe.getTimeZone(),a=Xe.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 Tt.prompt({input:r,label:"Organization website"}),p=this.notify("Setting up organization");try{let c=await t.setupOrganization({website:s,locale:a,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,a=setInterval(()=>{i>=n.length?clearInterval(a):r.update(n[i++]);},3e3);return {confirm:(s,p)=>{clearInterval(a),r.confirm(s,p);},stop:s=>{clearInterval(a),r.stop(s);}}}static getDefaultOrganization(e,t){return e.length===1?e[0]:t!==void 0?e.find(({slug:n})=>n===t)??null:null}};var _e=class o{constructor(e){this.config=e;}static prompt(e){return new o(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,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 Ar=class o{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 a=n.notify("Loading workspaces"),s=await t.getWorkspaces({organizationSlug:i.slug}),p=o.getDefaultWorkspace(s,e.default);if(p!==null)return a.confirm(`Workspace: ${p.name}`),p;if(a.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,a=t?await _e.prompt({input:r,label:"Workspace name",default:e.name}):e.name,s=Xe.getLocale(),p=Xe.getTimeZone(),c=i.notify("Creating workspace");try{let l=await n.createWorkspace({organizationSlug:e.slug,name:a,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 Er=class o{constructor(e){this.config=e;}async handle(e){let{workspaceApi:t,output:n,input:r}=this.config,{organization:i,workspace:a,environment:s}=e,p=n.notify("Loading applications"),c=await t.getApplications({workspaceSlug:a.slug,organizationSlug:i.slug}),l=c.filter(m=>m.environment===s&&(e.default??m.slug)===m.slug);if(p.stop(),l.length===0||e.new===true)return this.setupApplication(e,c);if(l.length===1){let m=l[0];return n.confirm(o.formatSelection(m)),m}return r.select({message:s==="DEVELOPMENT"?"Select development application":"Select production application",options:l.map(m=>({value:m,label:m.name}))})}async setupApplication(e,t){let{workspaceApi:n,output:r,input:i}=this.config,{organization:a,workspace:s,platform:p,environment:c}=e,l=e.new===true,m=l?await _e.prompt({input:i,label:"Application name",default:"Website",validator:w=>t.every(y=>y.name.toLowerCase()!==w.toLowerCase()||y.environment!==c)||"Name already in use"}):"Website",f=s.website??a.website??void 0,b=l||!o.isValidProductionUrl(f)?await Tt.prompt({input:i,label:"Application website",default:f,validate:o.isValidProductionUrl}):f,A=r.notify("Configuring application");try{let w=await n.createApplication({organizationSlug:a.slug,workspaceSlug:s.slug,name:m,website:b,environment:c,platform:p,timeZone:s.timeZone});return A.confirm(o.formatSelection(w)),w}finally{A.stop();}}static isValidProductionUrl(e){return e!==void 0&&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 Rr=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(dc,{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(we.fromValue),secret:n.createApiKey.apiKeyValue}}};var et=class o{constructor(e){this.config=e;}static prompt(e){return new o(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 Tr=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,a=e.username??await et.prompt({input:t,label:"Enter your email"}),s=n.notify("Finding account"),p=await r.isEmailRegistered(a);return s.stop(),p?(e.password===void 0&&n.inform("Account found, please sign in"),i.signIn.handle({email:a,password:e.password,retry:true})):(n.inform("New account, please sign up"),i.signUp.handle({email:a}))}logout(){return Promise.resolve()}};var tt=class o{constructor(e){this.config=e;}static prompt(e){return new o(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 Or=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:a}=this.config,s=e??await et.prompt({input:this.config.input,label:"Enter your email"}),p=t,c="retry-password";for(;c==="retry-password";){let l=p??await tt.prompt({input:r,label:"Password"});p=void 0;let m=i.notify("Checking credentials");try{let f=await a.signIn({email:s,password:l,duration:this.config.tokenDuration});return m.confirm("Logged in"),f}catch(f){if(f instanceof ne){if(f.isAccessDenied("UNVERIFIED_USER")){if(!n)throw new d("Email not verified.",{reason:"access_denied",cause:f,suggestions:["Access your email and click on the activation link"]});m.warn("Email not verified"),c=await r.confirm({message:"Resend activation link?",default:true})?"retry-activation":"cancel";continue}if(f.isAccessDenied("BAD_CREDENTIALS")){if(!n)throw new d("Username or password is incorrect.",{reason:"access_denied",cause:f,suggestions:["Check your credentials or reset your password"]});m.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 m.stop(),f}}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"),a=await n.createSession({destination:this.config.verificationLinkDestination.accountActivation});await n.retryActivation({email:e,sessionId:a}),i.confirm(`Link sent to \`${e}\``);let s=await this.getInboxLink(r,e),p=this.waitToken(a);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"),a=await n.createSession({destination:this.config.verificationLinkDestination.passwordReset});await n.requestPasswordReset({email:e,sessionId:a}),i.confirm(`Link sent to \`${e}\``);let s=await this.getInboxLink(r,e),p=this.waitToken(a);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 tt.prompt({input:e,label:"Enter your new password"}),i=await tt.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 Dr=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 a=await _e.prompt({input:t,minimumLength:2,maximumLength:30,label:"Name"}),[s,p]=a.replace(/\s+/g," ").trim().split(" "),c=e.email??await et.prompt({input:t,label:"Email"}),l=await tt.prompt({input:t,label:"Password",validator:y=>/[A-Z]/.test(y)?/[a-z]/.test(y)?/[^A-Za-z]/.test(y)?y.length<8?"Minimum of 8 characters":y.length>256?"Maximum of 256 characters":true:"Must contain a special character":"Must contain a lowercase letter":"Must contain an uppercase letter"}),m=i.createSession({destination:this.config.verificationLinkDestination}),f=n.notify("Creating account");await i.registerUser({sessionId:await m,email:c,password:l,firstName:s,lastName:p,expertise:e.expertise??"ENGINEERING"}),f.confirm(`Link to verify sent to \`${c}\``);let b=await this.config.emailLinkGenerator(c).then(async y=>y!==null&&await t.confirm({message:"Open your inbox?",default:true})?y.toString():null);f=n.notify("Waiting for account activation");let A=r.wait(await m);b!==null&&await n.open(b);let w=await A;return f.confirm("Account activated"),w}};var Mr=class{constructor(e){this.config=e;}async execute(e){let{output:t,pageForm:n,userApi:r}=this.config,i=await this.config.configurationManager.load(),a=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(a.startsWith("/")?a.slice(1):a,this.config.adminUrl);c.searchParams.set(this.config.adminTokenParameter,p),await t.open(c.toString());}};function ye(o,e){let t=[],n=null;if(yt__default.default(o,{ImportDeclaration:i=>{let{node:a}=i;if(a.source.value!==e.moduleName)return i.skip();t.push({declaration:a});let s=a.importKind??"value";for(let p of a.specifiers)if(!(!g__namespace.isImportSpecifier(p)||iu(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:a,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:a}=i;if(a.importKind==="type"&&e.type==="value"){a.importKind="value";for(let s of a.specifiers)g__namespace.isImportSpecifier(s)&&s!==i.specifier&&(s.importKind="type");if(i.localName===void 0){let s=g__namespace.importSpecifier(g__namespace.identifier(e.localName??e.importName),g__namespace.identifier(e.importName));s.importKind=e.type,a.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 a=i.importKind??"value";if(a==="value"||a===e.type){let s=g__namespace.importSpecifier(g__namespace.identifier(e.localName??e.importName),g__namespace.identifier(e.importName));return a!==e.type&&(s.importKind="type"),i.specifiers.push(s),{modified:true,localName:e.localName??e.importName}}}}let r=g__namespace.importDeclaration([g__namespace.importSpecifier(g__namespace.identifier(e.localName??e.importName),g__namespace.identifier(e.importName))],g__namespace.stringLiteral(e.moduleName));return e.type==="type"&&(r.importKind="type"),o.program.body.unshift(r),{modified:true,localName:e.localName??e.importName}}function iu(o){return g__namespace.isIdentifier(o)?o.name:o.value}function Dt(o,e){let t=typeof o=="string"?Be(o,["jsx","typescript"]):o,n=null;return yt__default.default(t,{ImportDeclaration:r=>{let{node:i}=r;if(!Nr(i.source.value,e.moduleName))return r.skip();for(let a of i.specifiers??[]){if(g__namespace.isImportDefaultSpecifier(a)){Nr("default",e.importName)&&(n=a.local.name);continue}if(g__namespace.isImportSpecifier(a)&&Nr(a.imported,e.importName))return n=a.local.name,r.skip()}return r.skip()}}),n}function Nr(o,e){return typeof o!="string"?Nr(g__namespace.isIdentifier(o)?o.name:o.value,e):typeof e=="string"?o===e:e.test(o)}function $r(o){let e=[];for(let[t,n]of Object.entries(o))e.push(g__namespace.jsxAttribute(g__namespace.jsxIdentifier(t),g__namespace.jsxExpressionContainer(dt(n))));return e}function dt(o){switch(o.type){case "reference":return o.path.length<2?g__namespace.identifier(o.path[0]):o.path.slice(2).reduce((e,t)=>g__namespace.memberExpression(e,g__namespace.identifier(t)),g__namespace.memberExpression(g__namespace.identifier(o.path[0]),g__namespace.identifier(o.path[1])));case "literal":return typeof o.value=="string"?g__namespace.stringLiteral(o.value):typeof o.value=="number"?g__namespace.numericLiteral(o.value):typeof o.value=="boolean"?g__namespace.booleanLiteral(o.value):g__namespace.nullLiteral();case "comparison":return g__namespace.binaryExpression(o.operator,dt(o.left),dt(o.right));case "ternary":return g__namespace.conditionalExpression(g__namespace.binaryExpression(o.condition.operator,dt(o.condition.left),dt(o.condition.right)),dt(o.consequent),dt(o.alternate))}}var gt=class o{constructor(e){this.configuration=e;}apply(e,t){let n=Dt(e,{importName:this.configuration.wrapper.component,moduleName:this.configuration.wrapper.module}),r=n??this.configuration.wrapper.component,i=[],a=1;if(yt__default.default(e,{ExportDefaultDeclaration:p=>(a=this.wrapDeclaration(p.node.declaration,r,e,t),p.stop()),ExportNamedDeclaration:p=>(i.push(p.node),p.skip())}),a===1&&this.configuration?.fallbackToNamedExports===true)for(let p of i){if(g__namespace.isFunctionDeclaration(p.declaration)&&(a=this.wrapBlockStatement(p.declaration.body,r,e,t),a===0))break;if(g__namespace.isVariableDeclaration(p.declaration)){let{declarations:c}=p.declaration;if(c.some(m=>g__namespace.isIdentifier(m.init)||g__namespace.isArrowFunctionExpression(m.init)||g__namespace.isFunctionExpression(m.init)?this.wrapDeclaration(m.init,r,e,t)===0:false)){a=0;break}}for(let c of p.specifiers??[])if(g__namespace.isExportSpecifier(c)){let l=this.findComponentDeclaration(e,c.local.name);if(l!==null&&g__namespace.isVariableDeclarator(l)&&g__namespace.isExpression(l.init)&&(a=this.wrapDeclaration(l.init,r,e,t),a===0))break}if(a===0)break}if(a===0&&n===null){let{body:p}=e.program;g__namespace.isImportDeclaration(p[0])||p.unshift(g__namespace.emptyStatement()),ye(e,{type:"value",moduleName:this.configuration.wrapper.module,importName:this.configuration.wrapper.component});}let s=this.configuration?.fallbackCodemod;return a===1&&s!==void 0?s.apply(e,t):Promise.resolve({modified:a===0,result:e})}wrapDeclaration(e,t,n,r){if(g__namespace.isArrowFunctionExpression(e)){if(g__namespace.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(g__namespace.isFunctionExpression(e)||g__namespace.isFunctionDeclaration(e))return this.wrapBlockStatement(e.body,t,n,r);if(g__namespace.isIdentifier(e)){let i=this.findComponentDeclaration(n,e.name);if(i!==null)if(g__namespace.isVariableDeclarator(i)){let a=i.init??null;if(a!==null)return this.wrapDeclaration(a,t,n,r)}else return this.wrapBlockStatement(i.body,t,n,r)}return 1}wrapBlockStatement(e,t,n,r){let i=o.findReturnStatement(e),a=i?.argument??null;if(i!==null&&a!==null){let s=this.insertWrapper(a,t,n,r);return s.result!==0?s.result:(i.argument=g__namespace.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:a,index:s}=i,p=[...a.children??[]],c=p.splice(s,1)[0];return i.parent.children=p.length===0?[g__namespace.jsxText(`
1722
- `),this.wrapElement(c,t,r),g__namespace.jsxText(`
1723
- `)]:[...p.slice(0,s),this.wrapElement(c,t,r),...p.slice(s)],{result:0,node:e}}return g__namespace.isJSXText(e)||g__namespace.isJSXExpressionContainer(e)||g__namespace.isJSXSpreadChild(e)||g__namespace.isJSXElement(e)||g__namespace.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),g__namespace.jsxElement(g__namespace.jsxOpeningElement(g__namespace.jsxIdentifier(t??this.configuration.wrapper.component),this.getProviderProps(n)),g__namespace.jsxClosingElement(g__namespace.jsxIdentifier(t??this.configuration.wrapper.component)),[g__namespace.jsxText(`
1724
- `),e,g__namespace.jsxText(`
1725
- `)])}getProviderProps(e){return $r({...this.configuration.wrapper.props,...e?.props})}containsElement(e,t){let n=false;return g.traverseFast(e,r=>{!n&&g__namespace.isJSXOpeningElement(r)&&g__namespace.isJSXIdentifier(r.name)&&r.name.name===t&&(n=true);}),n}findComponentDeclaration(e,t){let n=null;return yt__default.default(e,{VariableDeclaration:r=>{if(!g__namespace.isProgram(r.parent))return r.skip();for(let i of r.node.declarations)if(g__namespace.isVariableDeclarator(i)&&g__namespace.isIdentifier(i.id)&&i.id.name===t)return n=i,r.stop();return r.skip()},FunctionDeclaration:r=>{if(!g__namespace.isProgram(r.parent))return r.skip();let{id:i}=r.node;return g__namespace.isIdentifier(i)&&i.name===t?(n=r.node,r.stop()):r.skip()}}),n}findTargetChildren(e,t){let n=null,{configuration:r}=this;return r.targets?.variable===void 0&&r.targets?.component===void 0?null:(yt__default.default(e,{enter:function(a){let{node:s}=a;if(s===t)return a.traverse({JSXExpressionContainer:p=>{let{expression:c}=p.node;if(r.targets?.variable!==void 0&&g__namespace.isIdentifier(c)&&c.name===r.targets.variable){let l=p.parent;return n={parent:l,index:l.children.indexOf(p.node)},p.stop()}},JSXElement:p=>{let{openingElement:c}=p.node;if(r.targets?.component!==void 0&&g__namespace.isJSXOpeningElement(c)&&g__namespace.isJSXIdentifier(c.name)&&c.name.name===r.targets.component&&p.parent!==null){let l=p.parent;n={parent:l,index:l.children.indexOf(p.node)};}}}),a.stop()}}),n)}static findReturnStatement(e){let t=null;return g.traverseFast(e,n=>{t===null&&g__namespace.isReturnStatement(n)&&(t=n);}),t}};var He=class{constructor(e){this.codemod=e.codemod;}async apply(e,t){let n=zr__namespace.parse(e,{parser:{parse:babelTs.parse}}),r=await this.codemod.apply(n,t);return r.modified?{modified:true,result:zr__namespace.print(r.result,{reuseWhitespace:false}).code}:{modified:false,result:e}}};function cs(o,e){let t=typeof o=="string"?Be(o,["jsx","typescript"]):o,n=false;return yt__default.default(t,{ExportAllDeclaration:r=>{let{node:i}=r;return !g__namespace.isStringLiteral(i.source)||!ps(i.source,e.moduleName)||(n=true),r.skip()},ExportNamedDeclaration:r=>{let{node:i}=r;if(!g__namespace.isStringLiteral(i.source)||!ps(i.source,e.moduleName))return r.skip();if(e.importName===void 0)return n=true,r.skip();for(let a of i.specifiers)if(g__namespace.isExportSpecifier(a)&&ps(a.local,e.importName))return n=true,r.skip();return r.skip()}}),n}function ps(o,e){let t=g__namespace.isIdentifier(o)?o.name:o.value;return typeof e=="string"?t===e:e.test(t)}function _r(o,e){let t=[],n=false,r=false;if(yt__default.default(o,{ExportAllDeclaration:s=>{let{node:p}=s;if(p.source.value!==e.moduleName)return s.skip();let c=p.exportKind??"value";if(e.exportName===void 0&&e.importName===void 0){if(c==="value"||c==="type"&&e.type==="type")return n=true,s.stop();if(c==="type"&&e.type==="value")return p.exportKind="value",n=true,r=true,s.stop()}else if((e.exportName===void 0||e.exportName===e.importName)&&(c==="value"||c==="type"&&e.type==="type"))return n=true,s.stop();return s.skip()},ExportNamedDeclaration:s=>{let{node:p}=s,c=p.source??null;if(c===null||c.value!==e.moduleName)return s.skip();t.push({declaration:p});let l=p.exportKind??"value";for(let m of p.specifiers){if(g__namespace.isExportNamespaceSpecifier(m)&&e.importName===void 0&&m.exported.name===e.exportName)return n=true,e.type==="value"&&l==="type"&&(p.exportKind="value",r=true),s.stop();if(e.importName===void 0||!g__namespace.isExportSpecifier(m)||ls(m.local)!==e.importName||e.exportName!==void 0&&ls(m.exported)!==e.exportName)continue;let f=m.exportKind??"value";if(l===e.type||l==="value"&&(f==="value"||m.exportKind===e.type))return n=true,s.stop();t.unshift({declaration:p,specifier:m});}return s.skip()}}),n)return r;let{body:i}=o.program;if(e.importName===void 0){if(e.exportName===void 0)for(let p of t){let{declaration:c}=p,l=c.exportKind??"value",m=c.specifiers.filter(f=>!g__namespace.isExportSpecifier(f)||f.local.name!==ls(f.exported)||e.type==="type"&&l!=="type"&&f.exportKind!=="type");m.length===0?i.splice(i.indexOf(c),1):c.specifiers=m;}let s=e.exportName===void 0?g__namespace.exportAllDeclaration(g__namespace.stringLiteral(e.moduleName)):g__namespace.exportNamedDeclaration(null,[g__namespace.exportNamespaceSpecifier(g__namespace.identifier(e.exportName))],g__namespace.stringLiteral(e.moduleName));return e.type==="type"&&(s.exportKind="type"),i.push(s),true}for(let s of t){let{declaration:p}=s;if(p.exportKind==="type"&&e.type==="value"){p.exportKind="value";for(let c of p.specifiers)g__namespace.isExportSpecifier(c)&&c!==s.specifier&&(c.exportKind="type");return s.specifier===void 0&&p.specifiers.push(g__namespace.exportSpecifier(g__namespace.identifier(e.importName),g__namespace.identifier(e.exportName??e.importName))),true}}for(let{declaration:s}of t){let p=s.exportKind??"value";if(p==="value"||p===e.type){let c=g__namespace.exportSpecifier(g__namespace.identifier(e.importName),g__namespace.identifier(e.exportName??e.importName));return p!==e.type&&(c.exportKind="type"),s.specifiers.push(c),true}}let a=g__namespace.exportNamedDeclaration(null,[g__namespace.exportSpecifier(g__namespace.identifier(e.importName),g__namespace.identifier(e.exportName??e.importName))],g__namespace.stringLiteral(e.moduleName));return e.type==="type"&&(a.exportKind="type"),i.push(a),true}function ls(o){return g__namespace.isIdentifier(o)?o.name:o.value}var Lr=class o{constructor(e){this.configuration=e;}apply(e){let{body:t}=e.program,n=cs(e,{moduleName:this.configuration.import.module,importName:this.configuration.import.configName}),r=cs(e,{moduleName:this.configuration.import.module,importName:this.configuration.import.middlewareName}),i=n?null:o.findConfig(e);if(r){if(n||i!==null)return Promise.resolve({modified:false,result:e});let m=_r(e,{type:"value",moduleName:this.configuration.import.module,importName:this.configuration.import.configName});return Promise.resolve({modified:m,result:e})}let a=Dt(e,{moduleName:this.configuration.import.module,importName:this.configuration.import.middlewareFactoryName}),s=Dt(e,{moduleName:this.configuration.import.module,importName:this.configuration.import.middlewareName}),p=[];if(a!==null&&p.push(a),s!==null&&p.push(s),p.length>0&&o.isCalled(e,p))return Promise.resolve({modified:false,result:e});let c=i===null?null:Dt(e,{moduleName:this.configuration.import.module,importName:this.configuration.import.matcherName}),l=o.refactorMiddleware(e,a??this.configuration.import.middlewareFactoryName,i!==null&&i.matcher?i.name:void 0);if(l===null){if(i===null){let m=_r(e,{type:"value",moduleName:this.configuration.import.module,importName:this.configuration.import.middlewareName}),f=_r(e,{type:"value",moduleName:this.configuration.import.module,importName:this.configuration.import.configName});return Promise.resolve({modified:m||f,result:e})}l=g__namespace.exportDefaultDeclaration(g__namespace.callExpression(g__namespace.identifier(a??this.configuration.import.middlewareFactoryName),[g__namespace.objectExpression([g__namespace.objectProperty(g__namespace.identifier("matcher"),g__namespace.memberExpression(g__namespace.identifier(i.name),g__namespace.identifier(c??this.configuration.import.matcherName)))])])),t.push(l);}if(i!==null){this.configureMatcher(i.object,c??this.configuration.import.matcherLocalName);let m=t.indexOf(i.root),f=t.indexOf(l);if(m>f){t.splice(f,0,...t.splice(m,1));for(let b of o.findReferencesFrom(i.root,e.program)){let A=t.indexOf(b);A>f&&t.splice(f,0,...t.splice(A,1));}}}return a===null&&ye(e,{type:"value",moduleName:this.configuration.import.module,importName:this.configuration.import.middlewareFactoryName}),i?.matcher===true&&c===null&&ye(e,{type:"value",moduleName:this.configuration.import.module,importName:this.configuration.import.matcherName,localName:this.configuration.import.matcherLocalName}),Promise.resolve({modified:true,result:e})}configureMatcher(e,t){let n=false;for(let r of e.properties)if(g__namespace.isObjectProperty(r)&&g__namespace.isIdentifier(r.key)&&r.key.name==="matcher"){if(g__namespace.isStringLiteral(r.value)){r.value=g__namespace.arrayExpression([r.value,g__namespace.identifier(t)]),n=true;break}if(g__namespace.isArrayExpression(r.value)){let{elements:i}=r.value;i.some(a=>g__namespace.isIdentifier(a)&&a.name===t)||(i.push(g__namespace.identifier(t)),n=true);break}if(g__namespace.isIdentifier(r.value)){if(r.value.name===t)break;r.value=g__namespace.arrayExpression([g__namespace.spreadElement(g__namespace.conditionalExpression(g__namespace.callExpression(g__namespace.memberExpression(g__namespace.identifier("Array"),g__namespace.identifier("isArray")),[r.value]),r.value,g__namespace.arrayExpression([r.value]))),g__namespace.identifier(t)]),n=true;}}return n}static refactorMiddleware(e,t,n){let r=null;return yt__default.default(e,{ExportNamedDeclaration:i=>{let{node:a}=i,{declaration:s,specifiers:p=[]}=a;if(g__namespace.isFunctionDeclaration(s))return g__namespace.isFunctionDeclaration(a.declaration)&&g__namespace.isIdentifier(a.declaration.id)&&a.declaration.id.name==="middleware"?(i.replaceWith(g__namespace.exportNamedDeclaration(g__namespace.variableDeclaration("const",[g__namespace.variableDeclarator(g__namespace.identifier("middleware"),o.wrapMiddleware(g__namespace.isFunctionDeclaration(a.declaration)?o.createFunctionExpression(a.declaration):a.declaration,t,n))]),[])),r=o.getRootNode(i),i.stop()):i.skip();if(g__namespace.isVariableDeclaration(s)){for(let c of s.declarations)if(g__namespace.isVariableDeclarator(c)&&g__namespace.isIdentifier(c.id)&&c.id.name==="middleware"){let l=c.init??null;if(l!==null)return c.init=o.wrapMiddleware(l,t,n),r=o.getRootNode(i),i.stop()}}for(let c of p)if(g__namespace.isExportSpecifier(c)&&g__namespace.isIdentifier(c.exported)&&g__namespace.isIdentifier(c.local)&&["middleware","default"].includes(c.exported.name))return r=o.replaceMiddlewareDeclaration(e,c.local.name,t,n),i.stop();return i.skip()},ExportDefaultDeclaration:i=>{let{node:a}=i,{declaration:s}=a;return g__namespace.isArrowFunctionExpression(s)?(i.replaceWith(g__namespace.exportDefaultDeclaration(o.wrapMiddleware(s,t,n))),r=o.getRootNode(i),i.stop()):g__namespace.isFunctionDeclaration(s)?(i.replaceWith(g__namespace.exportDefaultDeclaration(o.wrapMiddleware(o.createFunctionExpression(s,true),t,n))),r=o.getRootNode(i),i.stop()):g__namespace.isIdentifier(s)?(r=o.replaceMiddlewareDeclaration(e,s.name,t,n),i.stop()):i.skip()}}),r}static replaceMiddlewareDeclaration(e,t,n,r){let i=null;return yt__default.default(e,{VariableDeclarator:a=>{let{node:s}=a;if(g__namespace.isIdentifier(s.id)&&s.id.name===t){let p=s.init??null;return p!==null&&(s.init=o.wrapMiddleware(p,n,r),i=o.getRootNode(a)),a.stop()}return a.skip()},FunctionDeclaration:a=>{let{node:s}=a;return g__namespace.isIdentifier(s.id)&&s.id.name===t?(a.replaceWith(o.wrapFunctionDeclaration(s,n,r,g__namespace.isIdentifier(s.id)?s.id.name:void 0)),i=o.getRootNode(a),a.stop()):a.skip()}}),i}static isCalled(e,t){let n=false;return yt__default.default(e,{CallExpression:r=>{let{node:i}=r;return g__namespace.isIdentifier(i.callee)&&t.includes(i.callee.name)?(n=true,r.stop()):r.skip()}}),n}static findConfig(e){let t=null;return yt__default.default(e,{ExportNamedDeclaration:n=>{let{declaration:r,specifiers:i=[]}=n.node;if(g__namespace.isVariableDeclaration(r)){for(let a of r.declarations)if(g__namespace.isVariableDeclarator(a)&&g__namespace.isIdentifier(a.id)&&a.id.name==="config"){let s=g__namespace.isIdentifier(a.init)?o.findVariableDeclarator(e,a.init.name):{name:"config",root:o.getRootNode(n),declaration:a};if(s===null||s.declaration.init===null)return n.stop();if(g__namespace.isObjectExpression(s.declaration.init))return t={name:s.name,root:s.root,object:s.declaration.init,matcher:o.hasMatcherProperty(s.declaration.init)},n.stop()}}for(let a of i)if(g__namespace.isExportSpecifier(a)&&g__namespace.isIdentifier(a.exported)&&g__namespace.isIdentifier(a.local)&&a.exported.name==="config"){let s=o.findVariableDeclarator(e,a.local.name);return s!==null&&g__namespace.isObjectExpression(s.declaration.init)&&(t={name:s.name,root:s.root,object:s.declaration.init,matcher:o.hasMatcherProperty(s.declaration.init)}),n.stop()}return n.skip()}}),t}static hasMatcherProperty(e){for(let t of e.properties)if(g__namespace.isObjectProperty(t)&&g__namespace.isIdentifier(t.key)&&t.key.name==="matcher")return true;return false}static findVariableDeclarator(e,t){let n=null;return yt__default.default(e,{VariableDeclarator:r=>{if(!g__namespace.isProgram(r.parentPath.parent))return r.skip();let{node:i}=r;return g__namespace.isVariableDeclarator(i)&&g__namespace.isIdentifier(i.id)&&i.id.name===t?(g__namespace.isIdentifier(i.init)?n=o.findVariableDeclarator(e,i.init.name):n={name:t,root:o.getRootNode(r),declaration:i},r.stop()):r.skip()}}),n}static wrapMiddleware(e,t,n){return g__namespace.callExpression(g__namespace.identifier(t),[n!==void 0?g__namespace.objectExpression([g__namespace.objectProperty(g__namespace.identifier("matcher"),g__namespace.memberExpression(g__namespace.identifier(n),g__namespace.identifier("matcher"))),g__namespace.objectProperty(g__namespace.identifier("next"),e)]):e])}static wrapFunctionDeclaration(e,t,n,r="middleware"){return g__namespace.variableDeclaration("const",[g__namespace.variableDeclarator(g__namespace.identifier(r),o.wrapMiddleware(o.createFunctionExpression(e),t,n))])}static findReferencesFrom(e,t){let n=new Set;yt__default.default(t,{enter:i=>{let{node:a}=i;if(a===e)return i.traverse({Identifier:function(p){let c=p.node;return o.isVariableReference(p.parent,c)&&n.add(c.name),p.skip()}}),i.stop()}});let r=[];return yt__default.default(t,{VariableDeclarator:i=>{if(!g__namespace.isProgram(i.parentPath.parent))return i.skip();let{node:a}=i;return g__namespace.isIdentifier(a.id)&&n.has(a.id.name)&&r.push(o.getRootNode(i)),i.skip()},FunctionDeclaration:i=>{if(!g__namespace.isProgram(i.parent))return;let{node:a}=i;return g__namespace.isIdentifier(a.id)&&n.has(a.id.name)&&r.push(o.getRootNode(i)),i.skip()},ClassDeclaration:i=>{if(!g__namespace.isProgram(i.parent))return;let{node:a}=i;return g__namespace.isIdentifier(a.id)&&n.has(a.id.name)&&r.push(o.getRootNode(i)),i.skip()}}),[...new Set(r.flatMap(i=>[i,...o.findReferencesFrom(i,t)]))]}static isVariableReference(e,t){return g__namespace.isVariableDeclarator(e)?e.init===t:g__namespace.isClassProperty(e)||g__namespace.isObjectProperty(e)||g__namespace.isProperty(e)?e.value===t:g__namespace.isMemberExpression(e)?e.object===t:g__namespace.isCallExpression(e)||g__namespace.isNewExpression(e)?e.callee===t:g__namespace.isExpression(e)}static createFunctionExpression(e,t=false){return g__namespace.functionExpression(t?e.id:null,e.params,e.body,e.generator,e.async)}static getRootNode(e){let t=e;for(;t.parentPath!==null&&!g__namespace.isProgram(t.parent);)t=t.parentPath;return t.node}};var Ke=class{constructor(e,t){this.codemod=t,this.formatter=e;}async apply(e,t){if(this.codemod===void 0)return await this.formatter.format([e]),{modified:true,result:e};let n=await this.codemod.apply(e,t);return n.modified&&await this.formatter.format([e]),n}};var Ge=class{constructor({fileSystem:e,codemod:t}){this.fileSystem=e,this.codemod=t;}async apply(e,t){let n="";if(await this.fileSystem.exists(e))try{n=await this.fileSystem.readTextFile(e);}catch(i){throw new Je("Failed to read file.",{cause:i,details:[`File: file://${e.replace(/\\/g,"/")}`]})}let r=await this.codemod.apply(n,t);if(r.modified)try{await this.fileSystem.writeTextFile(e,r.result,{overwrite:!0});}catch(i){throw new Je("Failed to write file",{cause:i,details:[`File: file://${e.replace(/\\/g,"/")}`]})}return {modified:r.modified,result:e}}};var Fr=class{constructor(e){this.configuration=e;}apply(e,t={}){let n=t.typescript??false,{body:r}=e.program,i=ye(e,{type:"value",moduleName:this.configuration.provider.module,importName:this.configuration.provider.component}),a=n?ye(e,{type:"type",moduleName:"react",importName:"PropsWithChildren"}):null,s=n?ye(e,{type:"type",moduleName:"react",importName:"ReactNode"}):null,p=g__namespace.objectPattern([g__namespace.objectProperty(g__namespace.identifier("children"),g__namespace.identifier("children"))]);a!==null&&(p.typeAnnotation=g__namespace.tsTypeAnnotation(g__namespace.tsTypeReference(g__namespace.identifier(a.localName))));let c=g__namespace.functionDeclaration(g__namespace.identifier("RootLayout"),[p],g__namespace.blockStatement([g__namespace.returnStatement(g__namespace.parenthesizedExpression(g__namespace.jsxElement(g__namespace.jsxOpeningElement(g__namespace.jsxIdentifier("html"),[g__namespace.jsxAttribute(g__namespace.jsxIdentifier("lang"),g__namespace.stringLiteral("en"))]),g__namespace.jsxClosingElement(g__namespace.jsxIdentifier("html")),[g__namespace.jsxText(`
1726
- `),g__namespace.jsxElement(g__namespace.jsxOpeningElement(g__namespace.jsxIdentifier("body"),[]),g__namespace.jsxClosingElement(g__namespace.jsxIdentifier("body")),[g__namespace.jsxText(`
1727
- `),g__namespace.jsxElement(g__namespace.jsxOpeningElement(g__namespace.jsxIdentifier(i.localName),[]),g__namespace.jsxClosingElement(g__namespace.jsxIdentifier(i.localName)),[g__namespace.jsxText(`
1728
- `),g__namespace.jsxExpressionContainer(g__namespace.identifier("children")),g__namespace.jsxText(`
1729
- `)]),g__namespace.jsxText(`
1730
- `)]),g__namespace.jsxText(`
1731
- `)])))]));return s!==null&&(c.returnType=g__namespace.tsTypeAnnotation(g__namespace.tsTypeReference(g__namespace.identifier(s.localName)))),r.push(g__namespace.exportDefaultDeclaration(c)),Promise.resolve({modified:true,result:e})}};var dn=class{constructor(e){this.configuration=e;}apply(e,t={}){let n=t.typescript??false,{body:r}=e.program,i=ye(e,{type:"value",moduleName:this.configuration.provider.module,importName:this.configuration.provider.component}),a=n?ye(e,{type:"type",moduleName:"next/app",importName:"AppProps"}):null,s=n?ye(e,{type:"type",moduleName:"react",importName:"ReactNode"}):null,p=g__namespace.objectPattern([g__namespace.objectProperty(g__namespace.identifier("Component"),g__namespace.identifier("Component")),g__namespace.objectProperty(g__namespace.identifier("pageProps"),g__namespace.identifier("pageProps"))]);a!==null&&(p.typeAnnotation=g__namespace.tsTypeAnnotation(g__namespace.tsTypeReference(g__namespace.identifier(a.localName))));let c=g__namespace.functionDeclaration(g__namespace.identifier("App"),[p],g__namespace.blockStatement([g__namespace.returnStatement(g__namespace.parenthesizedExpression(g__namespace.jsxElement(g__namespace.jsxOpeningElement(g__namespace.jsxIdentifier(i.localName),$r(this.configuration.provider.props??{})),g__namespace.jsxClosingElement(g__namespace.jsxIdentifier(i.localName)),[g__namespace.jsxText(`
1732
- `),g__namespace.jsxElement(g__namespace.jsxOpeningElement(g__namespace.jsxIdentifier("Component"),[g__namespace.jsxSpreadAttribute(g__namespace.identifier("pageProps"))]),g__namespace.jsxClosingElement(g__namespace.jsxIdentifier("Component")),[]),g__namespace.jsxText(`
1733
- `)])))]));return s!==null&&(c.returnType=g__namespace.tsTypeAnnotation(g__namespace.tsTypeReference(g__namespace.identifier(s.localName)))),r.push(g__namespace.exportDefaultDeclaration(c)),Promise.resolve({modified:true,result:e})}};var jr=class o extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var Wr=class o{constructor(e){this.configuration=e;}async format(e){let t=await this.getCommand(e);if(t!==null)try{await this.run(t);}catch{}}async run(e){let{commandExecutor:t,workingDirectory:n,timeout:r}=this.configuration;if(await t.run(e,{workingDirectory:n.get(),timeout:r}).wait()!==0)throw new jr("Failed to format code.")}async getCommand(e){let{tools:t,packageManager:n,fileSystem:r}=this.configuration;for(let i of t){if(!await n.hasDirectDependency(i.package))continue;let a=await n.getDependency(i.package);if(a===null)continue;let s=o.getBinPath(a,i.bin);if(s!==null)return {name:r.joinPaths(a.directory,r.normalizeSeparators(s)),arguments:i.args(e)}}return null}static getBinPath({metadata:e},t){return "bin"in e?typeof e.bin=="string"?e.bin:t!==void 0&&typeof e.bin=="object"&&e.bin!==null&&typeof e.bin[t]=="string"?e.bin[t]:null:null}};var Mt=class o{constructor(e){this.config=e;}async execute(e){let{sdk:t,configurationManager:n,io:r}=this.config,{output:i}=r,a=await n.load(),s=await this.getSlots(a,e);if(s.length===0){i.inform("No slots to add");return}let p={input:r.input,output:r.output,configuration:{...a,slots:{...a.slots,...Object.fromEntries(s.map(([c,l])=>[c.slug,l.toString()]))}}};if(await n.update(p.configuration),i.confirm("Configuration updated"),await t.update(p,{clean:true}),e.example===true){let c=i.notify("Generating example");try{await Promise.all(s.map(([l])=>t.generateSlotExample(l,p)));}catch(l){throw c.stop(),l}c.confirm("Example generated");}}async getSlots(e,t){let{slotForm:n,workspaceApi:r,io:{output:i}}=this.config,a=t.slots===void 0?void 0:o.getVersionMap(t.slots,e.slots),s=Object.keys(e.slots),p=await n.handle({organizationSlug:e.organization,workspaceSlug:e.workspace,preselected:a===void 0?void 0:Object.keys(a),selected:t.example===true?[]:s});if(s.length===p.length&&p.every(c=>s.includes(c.slug))&&i.inform("No new slots to add"),t.slots!==void 0&&t.slots.length>0&&p.length!==t.slots.length){let c=t.slots.filter(l=>!p.some(m=>m.slug===l));throw new d(`Non-existing slots: \`${c.join("`, `")}\``,{reason:"invalid_input",suggestions:["Run `slot add` without arguments to see available slots"]})}return Promise.all(p.map(async c=>{let l=a?.[c.slug];if(l===void 0||l.getMaxVersion()===c.version.major)return [c,l??O.of(c.version.major)];if(l.getMinVersion()>c.version.major)throw new d(`No matching version for slot \`${c.slug}\`.`,{reason:"invalid_input",details:[`Requested version: ${l.toString()}`,`Current version: ${c.version.major}`],suggestions:["Omit version specifier to use the latest version"]});return t.example!==true?[c,l]:[await r.getSlot({organizationSlug:e.organization,workspaceSlug:e.workspace,slotSlug:c.slug,majorVersion:Math.min(c.version.major,l.getMinVersion())})??c,l]}))}static getVersionMap(e,t){return Object.fromEntries(e.map(n=>{let[r,i]=n.split("@",2);if(i===void 0)return [r,void 0];if(!O.isValid(i))throw new d(`Invalid version specifier \`${i}\` for slot \`${r}\`.`,{reason:"invalid_input",suggestions:["Version must be exact (i.e. `1`), range (i.e. `1 - 2`), or set (i.e. `1 || 2`)."]});let a=O.parse(i);if(a.getCardinality()>5)throw new d(`The number of versions specified for slot \`${r}\` exceeds 5 major versions.`,{reason:"invalid_input",suggestions:["Narrow down the number of versions to 5 or less."]});if(t[r]!==void 0&&(a=O.parse(t[r]).with(a),a.getCardinality()>5))throw new d(`The cumulative number of versions for slot \`${r}\` cannot exceed 5 major versions.`,{reason:"invalid_input",suggestions:["Narrow down the number of versions to 5 or less."]});return [r,a]}))}};var nt=class{constructor(e){this.config=e;}async handle(e){let{output:t,input:n}=this.config,r=t.notify("Loading slots"),i=await this.getSlots(e,e.allowed);r.stop();let a=e.preselected??[];if(a.length>0)return i.filter(({slug:p})=>a.includes(p));let s=e.selected??[];return i.length===0||s.length>0&&i.every(({slug:p})=>s.includes(p))?i.filter(({slug:p})=>s.includes(p)):e.selectionConfirmation!==void 0&&!await n.confirm(e.selectionConfirmation)?i.filter(({slug:c})=>s.includes(c)):n.selectMultiple({message:"Select slots",options:i.map(p=>{let c=s.includes(p.slug);return {value:p,label:p.name,disabled:c,selected:c}})})}async getSlots(e,t){let{workspaceApi:n}=this.config,r=await n.getSlots({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return t===void 0?r:r.filter(({slug:i})=>t.includes(i))}};var Nt=class o{constructor(e){this.config=e;}async execute(e){let{sdk:t,configurationManager:n,io:r}=this.config,{output:i}=r,a=await n.load(),s=await this.getComponents(a,e);if(s.length===0){i.inform("No components to add");return}let p={input:r.input,output:r.output,configuration:{...a,components:{...a.components,...Object.fromEntries(s.map(([c,l])=>[c.slug,l.toString()]))}}};await n.update(p.configuration),i.confirm("Configuration updated"),await t.update(p,{clean:true});}async getComponents(e,t){let{componentForm:n,io:{output:r}}=this.config,i=t.components===void 0?void 0:o.getVersionMap(t.components,e.components),a=Object.keys(e.components),s=await n.handle({organizationSlug:e.organization,workspaceSlug:e.workspace,preselected:i===void 0?void 0:Object.keys(i),selected:a});if(a.length===s.length&&s.every(p=>a.includes(p.slug))&&r.inform("No new component to add"),t.components!==void 0&&t.components.length>0&&s.length!==t.components.length){let p=t.components.filter(c=>!s.some(l=>l.slug===c));throw new d(`Non-existing components: \`${p.join("`, `")}\``,{reason:"invalid_input",suggestions:["Run `component add` without arguments to see available components"]})}return s.map(p=>{let c=i?.[p.slug];if(c===void 0||c.getMaxVersion()===p.version.major)return [p,c??O.of(p.version.major)];if(c.getMinVersion()>p.version.major)throw new d(`No matching version for component \`${p.slug}\`.`,{reason:"invalid_input",details:[`Requested version: ${c.toString()}`,`Current version: ${p.version.major}`],suggestions:["Omit version specifier to use the latest version"]});return [p,c]})}static getVersionMap(e,t){return Object.fromEntries(e.map(n=>{let[r,i]=n.split("@",2);if(i===void 0)return [r,void 0];if(!O.isValid(i))throw new d(`Invalid version specifier \`${i}\` for component \`${r}\`.`,{reason:"invalid_input",suggestions:["Version must be exact (i.e. `1`), range (i.e. `1 - 2`), or set (i.e. `1 || 2`)."]});let a=O.parse(i);if(a.getCardinality()>5)throw new d(`The number of versions specified for component \`${r}\` exceeds 5 major versions.`,{reason:"invalid_input",suggestions:["Narrow down the number of versions to 5 or less."]});if(t[r]!==void 0&&(a=O.parse(t[r]).with(a),a.getCardinality()>5))throw new d(`The cumulative number of versions for component \`${r}\` cannot exceed 5 major versions.`,{reason:"invalid_input",suggestions:["Narrow down the number of versions to 5 or less."]});return [r,a]}))}};var rt=class{constructor(e){this.config=e;}async handle(e){let{workspaceApi:t}=this.config,{allowed:n}=e,r=await t.getComponents({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug}),i=await this.selectComponents(e,n===void 0?r:r.filter(({slug:a})=>n.includes(a)));if(e.includeDependencies!==true)return i;for(let a of i){let s=new Set([...a.metadata.directReferences,...a.metadata.indirectReferences]);for(let p of s)if(!i.some(({slug:c})=>c===p)){let c=r.find(({slug:l})=>l===p);c!==void 0&&i.push(c);}}return i}async selectComponents(e,t){let{output:n,input:r}=this.config;n.notify("Loading components").stop();let a=e.preselected??[];if(a.length>0)return t.filter(({slug:p})=>a.includes(p));let s=e.selected??[];return t.length===0||s.length>0&&t.every(({slug:p})=>s.includes(p))?t.filter(({slug:p})=>s.includes(p)):e.selectionConfirmation!==void 0&&!await r.confirm(e.selectionConfirmation)?t.filter(({slug:c})=>s.includes(c)):r.selectMultiple({message:"Select components",options:t.map(p=>{let c=s.includes(p.slug);return {value:p,label:p.name,disabled:c,selected:c}})})}};var gn=class o{constructor(e){this.config=e;}async execute(e){let{sdk:t,configurationManager:n,slotForm:r,io:i}=this.config,{output:a}=i,s=await n.load(),p=e.slots===void 0?void 0:o.getVersionMap(e.slots,s.slots),c=await r.handle({organizationSlug:s.organization,workspaceSlug:s.workspace,allowed:Object.keys(s.slots),preselected:p===void 0?void 0:Object.keys(p)});if(c.length===0)return a.inform("No slots to remove.");let l={input:i.input,output:i.output,configuration:{...s,slots:Object.fromEntries(Object.entries(s.slots).flatMap(([m,f])=>p?.[m]!==void 0?p[m]===null?[]:[[m,p[m].toString()]]:c.some(b=>b.slug===m)?[]:[[m,f.toString()]]))}};await n.update(l.configuration),a.confirm("Configuration updated"),await t.update(l,{clean:true});}static getVersionMap(e,t){return Object.fromEntries(e.map(n=>{let[r,i]=n.split("@",2);if(t[r]===void 0||i===void 0)return [r,null];let a=O.parse(t[r]);if(!O.isValid(i))return [r,a];let s=O.parse(i);return a.intersects(s)?s.contains(a)?[r,null]:[r,a.without(s)]:[r,a]}))}};var fn=class o{constructor(e){this.config=e;}async execute(e){let{sdk:t,configurationManager:n,componentForm:r,io:i}=this.config,{output:a}=i,s=await n.load(),p=e.components===void 0?void 0:o.getVersionMap(e.components,s.components),c=await r.handle({organizationSlug:s.organization,workspaceSlug:s.workspace,allowed:Object.keys(s.components),preselected:p===void 0?void 0:Object.keys(p)});if(c.length===0)return a.alert("No components to remove.");let l={input:i.input,output:i.output,configuration:{...s,components:Object.fromEntries(Object.entries(s.components).flatMap(([m,f])=>p?.[m]!==void 0?p[m]===null?[]:[[m,p[m].toString()]]:c.some(b=>b.slug===m)?[]:[[m,f.toString()]]))}};a.confirm("Configuration updated"),await n.update(l.configuration),await t.update(l,{clean:true});}static getVersionMap(e,t){return Object.fromEntries(e.map(n=>{let[r,i]=n.split("@",2);if(t[r]===void 0||i===void 0)return [r,null];let a=O.parse(t[r]);if(!O.isValid(i))return [r,a];let s=O.parse(i);return a.intersects(s)?s.contains(a)?[r,null]:[r,a.without(s)]:[r,a]}))}};var Vr=class{constructor({manager:e,initializer:t}){this.manager=e,this.initializer=t;}isInitialized(){return this.manager.isInitialized()}async load(){return await this.isInitialized()||await this.initializer.initialize(),this.manager.load()}update(e){return this.manager.update(e)}};var yn=class{constructor(e){this.configuration=e;}async execute(e){let{sdk:t,configurationManager:n,io:r}=this.configuration,i={input:r.input,output:r.output,configuration:await n.load()};await t.update(i,{clean:e.clean});}};var Le=class Le{constructor(e){this.config=e;}async handle(e){return Le.resolvePath(await this.getPage(e.page,e),e)}getPage(e,t){if(e!==void 0){let r=Le.findMatch(e,t);if(r!==null)return Promise.resolve(r)}let{input:n}=this.config;return n.select({message:"Where do you want to go?",options:Object.entries(Le.SITEMAP).map(([r,i])=>({value:i,label:r}))})}static findMatch(e,t){if(e.startsWith("/"))return e;let n=null,r=.5;for(let i of Object.keys(Le.getSitemap(t))){let a=cu__default.default(e,i);a>r&&(n=Le.SITEMAP[i],r=a);}return n}static getSitemap(e){return e.prodApplicationSlug!==void 0?Le.SITEMAP:Object.fromEntries(Object.entries(Le.SITEMAP).filter(([,t])=>!t.includes(":prod-application")))}static resolvePath(e,t){return e.replace(/:(organization|workspace|(dev|prod)-application)/g,(n,r)=>{switch(r){case "organization":return t.organizationSlug;case "workspace":return t.workspaceSlug;case "dev-application":return t.devApplicationSlug;case "prod-application":return t.prodApplicationSlug??""}})}};Le.SITEMAP={Home:"/","Personal settings":"/settings",Organization:"/organizations/:organization","Organization settings":"/organizations/:organization/settings","Organization members":"/organizations/:organization/members",Workspace:"/organizations/:organization/workspaces/:workspace","Workspace settings":"/organizations/:organization/workspaces/:workspace/settings","Workspace members":"/organizations/:organization/workspaces/:workspace/members","Dev application":"/organizations/:organization/workspaces/:workspace/applications/:dev-application/dashboard","Prod application":"/organizations/:organization/workspaces/:workspace/applications/:prod-application/dashboard","Dev application settings":"/organizations/:organization/workspaces/:workspace/applications/:dev-application/settings","Prod application settings":"/organizations/:organization/workspaces/:workspace/applications/:prod-application/settings",Slots:"/organizations/:organization/workspaces/:workspace/slots",Components:"/organizations/:organization/workspaces/:workspace/components",Experiences:"/organizations/:organization/workspaces/:workspace/experiences"};var Ur=Le;var qr=class{constructor({instruction:e,authenticator:t}){this.instruction=e,this.authenticator=t;}getToken(){return this.authenticator.getToken()}login(e){if(Object.keys(e).length===0){let{message:t,...n}=this.instruction;throw new d(t,n)}return this.authenticator.login(e)}logout(){return this.authenticator.logout()}};var Hr=class{constructor(e){this.instruction=e;}prompt(){return this.report()}select(){return this.report()}selectMultiple(){return this.report()}confirm(){return this.report()}wait(){return this.report()}report(){let{message:e,...t}=this.instruction;throw new d(e,t)}};var Kr=class{constructor(e){this.authenticators=e;}async getToken(){for(let e of Object.values(this.authenticators)){let t=await e.getToken();if(t!==null)return t}return null}login(e){let t={...e};return delete t.method,this.authenticators[e.method].login(t)}async logout(){await Promise.all(Object.values(this.authenticators).map(e=>e.logout()));}};var hn=class o{constructor(e){this.config=e;}async execute(e){let{sdk:t,configurationManager:n,io:r}=this.config,i=await n.load(),a=await this.selectSlots(i,e.slots),s=await this.selectComponents(i,e.components),p={input:r.input,output:r.output,configuration:{...i,slots:{...i.slots,...Object.fromEntries(a.map(c=>[c.slug,o.resolveVersion(c.version.major,i.slots[c.slug])]))},components:{...i.components,...Object.fromEntries(s.map(c=>[c.slug,o.resolveVersion(c.version.major,i.components[c.slug])]))}}};await n.update(p.configuration),await t.update(p,{clean:true});}async selectComponents(e,t){let{form:{componentForm:n}}=this.config,r=t===void 0?Object.keys(e.components):t,i=r.length===0?[]:await n.handle({organizationSlug:e.organization,workspaceSlug:e.workspace,preselected:r});if(r.length>0&&i.length!==r.length){let a=r.filter(s=>!i.some(p=>p.slug===s));throw new d(`Components not found: \`${a.join("`, `")}\`.`,{reason:"precondition",suggestions:["Run `remove component` to remove a component from your configuration."]})}return i}async selectSlots(e,t){let{form:{slotForm:n}}=this.config,r=t===void 0?Object.keys(e.slots):t,i=r.length===0?[]:await n.handle({organizationSlug:e.organization,workspaceSlug:e.workspace,preselected:r});if(r.length>0&&i.length!==r.length){let a=r.filter(s=>!i.some(p=>p.slug===s));throw new d(`Slots not found: \`${a.join("`, `")}\`.`,{reason:"precondition",suggestions:["Run `remove slot` to remove a slot from your configuration."]})}return i}static resolveVersion(e,t){let n=O.of(e);if(t===void 0)return n.toString();let r=O.parse(t);return r.isExact()?n.toString():r.isRange()?r.getMaxVersion()>=n.getMaxVersion()?t:O.between(r.getMinVersion(),n.getMaxVersion()).toString():O.either(...r.getVersions(),...n.getVersions()).toString()}};var Sn=class o extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var Ce=class Ce{constructor(e){this.config={...e,defaultEncoding:e.defaultEncoding??"utf8"};}getSeparator(){return path.sep}normalizeSeparators(e){return e.replace(/\//g,path.sep)}getBaseName(e){return path.basename(e)}getDirectoryName(e){return path.dirname(e)}getRealPath(e){return this.execute(()=>promises.realpath(this.resolvePath(e)))}getRelativePath(e,t){return path.relative(this.resolvePath(e),this.resolvePath(t))}isAbsolutePath(e){return path.isAbsolute(e)}isSubPath(e,t){let n=this.resolvePath(e),r=path.isAbsolute(t)?t:path.join(n,t),i=path.relative(n,r);return !i.startsWith("..")&&!path.isAbsolute(i)}isSymbolicLink(e){return this.execute(async()=>{try{return (await promises.lstat(this.resolvePath(e))).isSymbolicLink()}catch(t){if(Ce.isErrorCode(t,["ENOENT","ENOTDIR"]))return false;throw t}})}isDirectory(e){return this.execute(async()=>{try{return (await promises.lstat(this.resolvePath(e))).isDirectory()}catch(t){if(Ce.isErrorCode(t,["ENOENT","ENOTDIR"]))return false;throw t}})}isEmptyDirectory(e){return this.execute(async()=>(await promises.readdir(this.resolvePath(e))).length===0)}create(e){switch(e.type){case "file":return this.execute(()=>promises.writeFile(this.resolvePath(e.name),e.content));case "directory":return this.execute(()=>promises.mkdir(this.resolvePath(e.name)));case "link":return this.execute(()=>promises.link(e.target,this.resolvePath(e.name)));case "symlink":return this.execute(()=>promises.symlink(e.target,this.resolvePath(e.name)))}}list(e,t=Number.POSITIVE_INFINITY){let n=this.resolvePath(e);return this.listRelatively(n,n,t)}async*listRelatively(e,t,n){if(n<0)return;let r=await this.execute(()=>promises.lstat(e)).catch(()=>null);if(r===null)return;if(!r.isDirectory())return yield*this.createEntry(e,path.dirname(t),r,0);let i=await this.execute(()=>promises.readdir(e));for(let a of i){let s=path.join(e,a),p=await this.execute(()=>promises.lstat(s));yield*this.createEntry(s,t,p,n);}}async*createEntry(e,t,n,r){let i=path.relative(t,e);if(n.isFile()){let a=()=>this.execute(()=>fs$1.createReadStream(e));yield {type:"file",name:i,get content(){return a()}};}else n.isDirectory()?(yield {type:"directory",name:i},r>0&&(yield*this.listRelatively(e,t,r-1))):n.isSymbolicLink()?yield {type:"symlink",name:i,target:await this.execute(()=>promises.realpath(e))}:yield {type:"link",name:i,target:await this.execute(()=>promises.realpath(e))};}joinPaths(...e){return path.join(...e)}async exists(e){try{return await promises.lstat(this.resolvePath(e)),!0}catch(t){if(Ce.isErrorCode(t,["ENOENT","ENOTDIR"]))return false;throw t}}delete(e,t){return promises.rm(this.resolvePath(e),{recursive:t?.recursive??false,force:true})}readTextFile(e){return this.execute(()=>promises.readFile(this.resolvePath(e),this.config.defaultEncoding))}writeTextFile(e,t,n){return this.execute(()=>promises.writeFile(this.resolvePath(e),t,{flag:n?.overwrite===true?"w":"wx",encoding:this.config.defaultEncoding}))}async createDirectory(e,t){await this.execute(()=>promises.mkdir(this.resolvePath(e),{recursive:t?.recursive??false}));}createTemporaryDirectory(e){return this.execute(()=>promises.mkdtemp(this.joinPaths(os$1.tmpdir(),e)))}copy(e,t,n){return this.execute(()=>promises.cp(this.resolvePath(e),this.resolvePath(t),{recursive:true,force:n?.overwrite??false}))}resolvePath(e){return path.isAbsolute(e)?e:path.join(this.config.workingDirectory.get(),e)}execute(e){try{let t=e();return t instanceof Promise?t.catch(n=>Ce.reportError(n)):t}catch(t){Ce.reportError(t);}}static reportError(e){if(e instanceof Error){let t=Object.entries(Ce.ERRORS);for(let[n,r]of t)if(Ce.isErrorCode(e,[n]))throw new Sn(r,{reason:Ce.ERROR_REASONS[n]??"other",cause:e,details:[`Code: ${n}`]})}throw new Sn("An unexpected error occurred.",{cause:e})}static isErrorCode(e,t){return !(e instanceof Error)||!("code"in e)||typeof e.code!="string"?false:t.includes(e.code)}};Ce.ERRORS={ENOENT:"The file or directory does not exist.",EACCES:"Unable to access the file or directory.",EISDIR:"Expected a file, but the path is a directory.",ENOTDIR:"Expected a directory, but the path is a file.",EPERM:"Operation not permitted.",EEXIST:"The file or directory already exists.",ENOTEMPTY:"The directory is not empty."},Ce.ERROR_REASONS={ENOENT:"not_found",EACCES:"access_denied",EISDIR:"invalid_input",ENOTDIR:"invalid_input",EPERM:"access_denied",EEXIST:"invalid_input",ENOTEMPTY:"invalid_input"};var Qr=Ce;var Jr=class{constructor(e){this.configuration=e;}wait(e){let{listener:t}=this.configuration;return new Promise((n,r)=>{this.focus(()=>t.wait(e).then(n,r));})}focus(e){switch(this.configuration.platform){case "darwin":return this.darwinFocus(e);case "linux":return this.linuxFocus(e);case "win32":return this.win32Focus(e);default:return e()}}async darwinFocus(e){let t=this.runCommand({name:"osascript",arguments:["-e","bundle identifier of (info for (path to frontmost application))"]});await e(),t!==null&&this.runCommand({name:"open",arguments:["-b",t]});}async linuxFocus(e){let t=this.runCommand({name:"xdotool",arguments:["getactivewindow"]});await e(),t!==null&&this.runCommand({name:"xdotool",arguments:["windowactivate",t]});}async win32Focus(e){let t=pe`
1722
+ `);function vt(o){return {model:o,api:Object.fromEntries(Object.entries(o).map(([e,t])=>[t,e]))}}var $a=vt({javascript:"JAVASCRIPT",react:"REACT",nextjs:"NEXT"}),za=vt({DEVELOPMENT:"DEVELOPMENT",PRODUCTION:"PRODUCTION"}),Jp=vt({NEVER_RECEIVED_TRAFFIC:"NEVER_RECEIVED_TRAFFIC",NOT_RECEIVING_TRAFFIC:"NOT_RECEIVING_TRAFFIC",RECEIVING_TRAFFIC:"RECEIVING_TRAFFIC"}),Ol=vt({PLUG_JS:"PLUG_JS"}),_a=vt({DRAFT:"DRAFT",ACTIVE:"ACTIVE",SCHEDULED:"SCHEDULED",PAUSED:"PAUSED",ARCHIVED:"ARCHIVED"}),Dl=vt({DRAFT:"DRAFT",ACTIVE:"ACTIVE",SCHEDULED:"SCHEDULED",PAUSED:"PAUSED",FINISHED:"FINISHED",INDIRECTLY_PAUSED:"INDIRECTLY_PAUSED"}),sr=class o{constructor(e,t){this.client=e,this.hierarchyResolver=t;}async getFeatures(e){let{data:t}=await this.client.execute(Dp,{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(jp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return (t.organization?.workspace?.applications.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[o.normalizeApplication(i)]})}async getApplication(e){let{data:t}=await this.client.execute(Wp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,applicationSlug:e.applicationSlug}),n=t.organization?.workspace?.application??null;return n===null?null:o.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:za.api[e.environment],platform:$a.api[e.platform??"JAVASCRIPT"],publicId:e.publicId,trafficStatus:Jp.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(Vp,{workspaceId:t.workspaceId,payload:{name:e.name,website:e.website,environment:za.model[e.environment],platform:$a.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:za.api[r.environment],platform:$a.api[r.platform??"JAVASCRIPT"],publicId:r.publicId,trafficStatus:Jp.api[r.applicationStatus],...i!==null?{logo:i}:{}}}async getAudiences(e){let{data:t}=await this.client.execute(Np,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return (t.organization?.workspace?.audiences.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[o.normalizeAudience(i)]})}async getAudience(e){let{data:t}=await this.client.execute($p,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,audienceSlug:e.audienceSlug}),n=t.organization?.workspace?.audience??null;return n===null?null:o.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(qp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return (t.organization?.workspace?.components.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[o.normalizeComponent(i)]})}async getComponent(e){let{data:t}=await this.client.execute(Hp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,componentSlug:e.componentSlug,majorVersion:e.majorVersion}),n=t.organization?.workspace?.component??null;return n===null?null:o.normalizeComponent(n)}static normalizeComponent(e){let{definition:t,metadata:{directReferences:n,indirectReferences:r,referenceMetadata:i}}=e.definition,a=e.description??null;return {id:e.id,name:e.name,slug:e.customId,...a!==null?{description:a}:{},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(zp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return (t.organization?.workspace?.slots.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[o.normalizeSlot(i)]})}async getSlot(e){let{data:t}=await this.client.execute(_p,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,slotSlug:e.slotSlug,majorVersion:e.majorVersion}),n=t.organization?.workspace?.slot??null;return n===null?null:o.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(Lp,{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(Zp,{workspaceId:t.workspaceId,payload:{target:Ol.model[e.target],components:e.components,slots:e.slots}});return n.generateTyping}async getExperiences(e){let{data:t}=await this.client.execute(Kp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,status:e.status===void 0?void 0:(Array.isArray(e.status)?e.status:[e.status]).map(r=>_a.model[r])});return (t.organization?.workspace?.experiences.edges??[]).flatMap(r=>{let i=r?.node??null;return i===null?[]:[o.normalizeExperience(i)]})}async getExperience(e){let{data:t}=await this.client.execute(Gp,{organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,experienceId:e.experienceId}),n=t.organization?.workspace?.experience??null;return n===null?null:o.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:_a.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:a=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:_a.api[e.status],hasExperiments:e.hasExperiments,audiences:t.map(l=>l.customId),slots:Object.values(c),...r!==null?{experiment:{...i!==null?{name:i}:{},...a!==null?{goalId:a}:{},...s!==null?{crossDevice:s}:{},...p!==null?{traffic:p}:{},..."status"in r?{status:Dl.api[r.status]}:{},variants:(r.variants??[]).map(l=>{let m=l.variantId,f=l.name??null,b=l.allocation??null;return {...m!==null?{id:m}:{},...f!==null?{name:f}:{},...b!==null?{allocation:b}:{},baseline:l.baseline===true,content:{default:o.normalizeLocalizedContent(l.content?.default.contents??[],c),segmented:(l.content?.segmented??[]).map(A=>({id:A.groupId,audiences:A.audiences.map(w=>w.audienceId),content:o.normalizeLocalizedContent(A.contents,c)}))}}})}}:{},content:{default:o.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:m})=>t.find(({id:f})=>f===m)?.customId??m),content:o.normalizeLocalizedContent(l.contents,c)}))}}}static normalizeLocalizedContent(e,t){let n={};for(let r of e){let{locale:i,slotId:a}=r,s=t[a];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,a])=>({customId:i,name:a.name,description:a.description,definition:a.definition})),slots:Object.entries(e.slots??{}).map(([i,a])=>({customId:i,name:a.name,component:a.component,defaultContent:Object.entries(a.content).map(([s,p])=>({locale:s,content:p}))})),audiences:Object.entries(e.audiences??{}).map(([i,a])=>({customId:i,name:a.name,criteria:a.criteria})),experiences:(e.experiences??[]).map(i=>{let a=i.experiment??null;return {name:i.name,audiences:i.audiences,slots:i.slots,experiment:a!==null?{name:a.name,goalId:a.goalId,traffic:a.traffic,crossDevice:a.crossDevice===true,variants:a.variants.map(s=>({id:randomUUID(),name:s.name??"",baseline:s.baseline===true,allocation:s.allocation??0,content:o.createContentVariantGroup(s.content)}))}:void 0,content:o.createContentVariantGroup(i.content),validate:true,publish:i.draft===false}})},{data:{createWorkspaceResources:r}}=await this.client.execute(Mp,{workspaceId:t.workspaceId,payload:n});return {components:Object.fromEntries(n.components.map(({customId:i},a)=>[i,r.components[a]])),slots:Object.fromEntries(n.slots.map(({customId:i},a)=>[i,r.slots[a]])),audiences:Object.fromEntries(n.audiences.map(({customId:i},a)=>[i,r.audiences[a]])),experiences:r.experiences.map(i=>({experienceId:i.id,experimentId:i.experimentId??null}))}}static createContentVariantGroup(e){return {default:{id:randomUUID(),contents:o.createSlotContentMap(e.default)},segmented:e.segmented.map(t=>({id:randomUUID(),audiences:t.audiences,contents:o.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 ot({query:Fp,baseName:`${t} ${n.slice(0,3).toLowerCase()}`,client:this.client,variables:{workspaceId:e}})}};var at;(t=>{function o(){return Intl.DateTimeFormat().resolvedOptions().locale.toLowerCase()}t.getLocale=o;function e(){return Intl.DateTimeFormat().resolvedOptions().timeZone}t.getTimeZone=e;})(at||={});var wt=class o{constructor(e){this.config=e;}static prompt(e){return new o(e).handle()}handle(){let{input:e,validate:t}=this.config;return e.prompt({message:this.config.label,default:this.config.default??"https://",validate:n=>URL.canParse(n)?t!==void 0?t(n):true:"Invalid URL"})}};var pr=class o{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=await t.getOrganizations(),m=o.getDefaultOrganization(l,e.default);if(m!==null)return c.confirm(`Organization: ${m.name}`),m;if(c.stop(),l.length>0)return r.select({message:"Select organization",options:l.map(f=>({value:f,label:f.name}))})}let i=at.getTimeZone(),a=at.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 wt.prompt({input:r,label:"Organization website"}),p=this.notify("Setting up organization");try{let c=await t.setupOrganization({website:s,locale:a,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,a=setInterval(()=>{i>=n.length?clearInterval(a):r.update(n[i++]);},3e3);return {confirm:(s,p)=>{clearInterval(a),r.confirm(s,p);},stop:s=>{clearInterval(a),r.stop(s);}}}static getDefaultOrganization(e,t){return e.length===1?e[0]:t!==void 0?e.find(({slug:n})=>n===t)??null:null}};var Ne=class o{constructor(e){this.config=e;}static prompt(e){return new o(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,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 cr=class o{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 a=n.notify("Loading workspaces"),s=await t.getWorkspaces({organizationSlug:i.slug}),p=o.getDefaultWorkspace(s,e.default);if(p!==null)return a.confirm(`Workspace: ${p.name}`),p;if(a.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,a=t?await Ne.prompt({input:r,label:"Workspace name",default:e.name}):e.name,s=at.getLocale(),p=at.getTimeZone(),c=i.notify("Creating workspace");try{let l=await n.createWorkspace({organizationSlug:e.slug,name:a,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 lr=class o{constructor(e){this.config=e;}async handle(e){let{workspaceApi:t,output:n,input:r}=this.config,{organization:i,workspace:a,environment:s}=e,p=n.notify("Loading applications"),c=await t.getApplications({workspaceSlug:a.slug,organizationSlug:i.slug}),l=c.filter(m=>m.environment===s&&(e.default??m.slug)===m.slug);if(p.stop(),l.length===0||e.new===true)return this.setupApplication(e,c);if(l.length===1){let m=l[0];return n.confirm(o.formatSelection(m)),m}return r.select({message:s==="DEVELOPMENT"?"Select development application":"Select production application",options:l.map(m=>({value:m,label:m.name}))})}async setupApplication(e,t){let{workspaceApi:n,output:r,input:i}=this.config,{organization:a,workspace:s,platform:p,environment:c}=e,l=e.new===true,m=l?await Ne.prompt({input:i,label:"Application name",default:"Website",validator:w=>t.every(y=>y.name.toLowerCase()!==w.toLowerCase()||y.environment!==c)||"Name already in use"}):"Website",f=s.website??a.website??void 0,b=l||!o.isValidProductionUrl(f)?await wt.prompt({input:i,label:"Application website",default:f,validate:o.isValidProductionUrl}):f,A=r.notify("Configuring application");try{let w=await n.createApplication({organizationSlug:a.slug,workspaceSlug:s.slug,name:m,website:b,environment:c,platform:p,timeZone:s.timeZone});return A.confirm(o.formatSelection(w)),w}finally{A.stop();}}static isValidProductionUrl(e){return e!==void 0&&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 ur=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(Up,{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 Ze=class o{constructor(e){this.config=e;}static prompt(e){return new o(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 mr=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,a=e.username??await Ze.prompt({input:t,label:"Enter your email"}),s=n.notify("Finding account"),p=await r.isEmailRegistered(a);return s.stop(),p?(e.password===void 0&&n.inform("Account found, please sign in"),i.signIn.handle({email:a,password:e.password,retry:true})):(n.inform("New account, please sign up"),i.signUp.handle({email:a}))}logout(){return Promise.resolve()}};var Je=class o{constructor(e){this.config=e;}static prompt(e){return new o(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 dr=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:a}=this.config,s=e??await Ze.prompt({input:this.config.input,label:"Enter your email"}),p=t,c="retry-password";for(;c==="retry-password";){let l=p??await Je.prompt({input:r,label:"Password"});p=void 0;let m=i.notify("Checking credentials");try{let f=await a.signIn({email:s,password:l,duration:this.config.tokenDuration});return m.confirm("Logged in"),f}catch(f){if(f instanceof te){if(f.isAccessDenied("UNVERIFIED_USER")){if(!n)throw new d("Email not verified.",{reason:"access_denied",cause:f,suggestions:["Access your email and click on the activation link"]});m.warn("Email not verified"),c=await r.confirm({message:"Resend activation link?",default:true})?"retry-activation":"cancel";continue}if(f.isAccessDenied("BAD_CREDENTIALS")){if(!n)throw new d("Username or password is incorrect.",{reason:"access_denied",cause:f,suggestions:["Check your credentials or reset your password"]});m.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 m.stop(),f}}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"),a=await n.createSession({destination:this.config.verificationLinkDestination.accountActivation});await n.retryActivation({email:e,sessionId:a}),i.confirm(`Link sent to \`${e}\``);let s=await this.getInboxLink(r,e),p=this.waitToken(a);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"),a=await n.createSession({destination:this.config.verificationLinkDestination.passwordReset});await n.requestPasswordReset({email:e,sessionId:a}),i.confirm(`Link sent to \`${e}\``);let s=await this.getInboxLink(r,e),p=this.waitToken(a);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 Je.prompt({input:e,label:"Enter your new password"}),i=await Je.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 gr=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 a=await Ne.prompt({input:t,minimumLength:2,maximumLength:30,label:"Name"}),[s,p]=a.replace(/\s+/g," ").trim().split(" "),c=e.email??await Ze.prompt({input:t,label:"Email"}),l=await Je.prompt({input:t,label:"Password",validator:y=>/[A-Z]/.test(y)?/[a-z]/.test(y)?/[^A-Za-z]/.test(y)?y.length<8?"Minimum of 8 characters":y.length>256?"Maximum of 256 characters":true:"Must contain a special character":"Must contain a lowercase letter":"Must contain an uppercase letter"}),m=i.createSession({destination:this.config.verificationLinkDestination}),f=n.notify("Creating account");await i.registerUser({sessionId:await m,email:c,password:l,firstName:s,lastName:p,expertise:e.expertise??"ENGINEERING"}),f.confirm(`Link to verify sent to \`${c}\``);let b=await this.config.emailLinkGenerator(c).then(async y=>y!==null&&await t.confirm({message:"Open your inbox?",default:true})?y.toString():null);f=n.notify("Waiting for account activation");let A=r.wait(await m);b!==null&&await n.open(b);let w=await A;return f.confirm("Account activated"),w}};var fr=class{constructor(e){this.config=e;}async execute(e){let{output:t,pageForm:n,userApi:r}=this.config,i=await this.config.configurationManager.load(),a=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(a.startsWith("/")?a.slice(1):a,this.config.adminUrl);c.searchParams.set(this.config.adminTokenParameter,p),await t.open(c.toString());}};function de(o,e){let t=[],n=null;if(traverse(o,{ImportDeclaration:i=>{let{node:a}=i;if(a.source.value!==e.moduleName)return i.skip();t.push({declaration:a});let s=a.importKind??"value";for(let p of a.specifiers)if(!(!g.isImportSpecifier(p)||Nl(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:a,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:a}=i;if(a.importKind==="type"&&e.type==="value"){a.importKind="value";for(let s of a.specifiers)g.isImportSpecifier(s)&&s!==i.specifier&&(s.importKind="type");if(i.localName===void 0){let s=g.importSpecifier(g.identifier(e.localName??e.importName),g.identifier(e.importName));s.importKind=e.type,a.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 a=i.importKind??"value";if(a==="value"||a===e.type){let s=g.importSpecifier(g.identifier(e.localName??e.importName),g.identifier(e.importName));return a!==e.type&&(s.importKind="type"),i.specifiers.push(s),{modified:true,localName:e.localName??e.importName}}}}let r=g.importDeclaration([g.importSpecifier(g.identifier(e.localName??e.importName),g.identifier(e.importName))],g.stringLiteral(e.moduleName));return e.type==="type"&&(r.importKind="type"),o.program.body.unshift(r),{modified:true,localName:e.localName??e.importName}}function Nl(o){return g.isIdentifier(o)?o.name:o.value}function Ct(o,e){let t=typeof o=="string"?Ke(o,["jsx","typescript"]):o,n=null;return traverse(t,{ImportDeclaration:r=>{let{node:i}=r;if(!yr(i.source.value,e.moduleName))return r.skip();for(let a of i.specifiers??[]){if(g.isImportDefaultSpecifier(a)){yr("default",e.importName)&&(n=a.local.name);continue}if(g.isImportSpecifier(a)&&yr(a.imported,e.importName))return n=a.local.name,r.skip()}return r.skip()}}),n}function yr(o,e){return typeof o!="string"?yr(g.isIdentifier(o)?o.name:o.value,e):typeof e=="string"?o===e:e.test(o)}function hr(o){let e=[];for(let[t,n]of Object.entries(o))e.push(g.jsxAttribute(g.jsxIdentifier(t),g.jsxExpressionContainer(st(n))));return e}function st(o){switch(o.type){case "reference":return o.path.length<2?g.identifier(o.path[0]):o.path.slice(2).reduce((e,t)=>g.memberExpression(e,g.identifier(t)),g.memberExpression(g.identifier(o.path[0]),g.identifier(o.path[1])));case "literal":return typeof o.value=="string"?g.stringLiteral(o.value):typeof o.value=="number"?g.numericLiteral(o.value):typeof o.value=="boolean"?g.booleanLiteral(o.value):g.nullLiteral();case "comparison":return g.binaryExpression(o.operator,st(o.left),st(o.right));case "ternary":return g.conditionalExpression(g.binaryExpression(o.condition.operator,st(o.condition.left),st(o.condition.right)),st(o.consequent),st(o.alternate))}}var pt=class o{constructor(e){this.configuration=e;}apply(e,t){let n=Ct(e,{importName:this.configuration.wrapper.component,moduleName:this.configuration.wrapper.module}),r=n??this.configuration.wrapper.component,i=[],a=1;if(traverse(e,{ExportDefaultDeclaration:p=>(a=this.wrapDeclaration(p.node.declaration,r,e,t),p.stop()),ExportNamedDeclaration:p=>(i.push(p.node),p.skip())}),a===1&&this.configuration?.fallbackToNamedExports===true)for(let p of i){if(g.isFunctionDeclaration(p.declaration)&&(a=this.wrapBlockStatement(p.declaration.body,r,e,t),a===0))break;if(g.isVariableDeclaration(p.declaration)){let{declarations:c}=p.declaration;if(c.some(m=>g.isIdentifier(m.init)||g.isArrowFunctionExpression(m.init)||g.isFunctionExpression(m.init)?this.wrapDeclaration(m.init,r,e,t)===0:false)){a=0;break}}for(let c of p.specifiers??[])if(g.isExportSpecifier(c)){let l=this.findComponentDeclaration(e,c.local.name);if(l!==null&&g.isVariableDeclarator(l)&&g.isExpression(l.init)&&(a=this.wrapDeclaration(l.init,r,e,t),a===0))break}if(a===0)break}if(a===0&&n===null){let{body:p}=e.program;g.isImportDeclaration(p[0])||p.unshift(g.emptyStatement()),de(e,{type:"value",moduleName:this.configuration.wrapper.module,importName:this.configuration.wrapper.component});}let s=this.configuration?.fallbackCodemod;return a===1&&s!==void 0?s.apply(e,t):Promise.resolve({modified:a===0,result:e})}wrapDeclaration(e,t,n,r){if(g.isArrowFunctionExpression(e)){if(g.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(g.isFunctionExpression(e)||g.isFunctionDeclaration(e))return this.wrapBlockStatement(e.body,t,n,r);if(g.isIdentifier(e)){let i=this.findComponentDeclaration(n,e.name);if(i!==null)if(g.isVariableDeclarator(i)){let a=i.init??null;if(a!==null)return this.wrapDeclaration(a,t,n,r)}else return this.wrapBlockStatement(i.body,t,n,r)}return 1}wrapBlockStatement(e,t,n,r){let i=o.findReturnStatement(e),a=i?.argument??null;if(i!==null&&a!==null){let s=this.insertWrapper(a,t,n,r);return s.result!==0?s.result:(i.argument=g.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:a,index:s}=i,p=[...a.children??[]],c=p.splice(s,1)[0];return i.parent.children=p.length===0?[g.jsxText(`
1723
+ `),this.wrapElement(c,t,r),g.jsxText(`
1724
+ `)]:[...p.slice(0,s),this.wrapElement(c,t,r),...p.slice(s)],{result:0,node:e}}return g.isJSXText(e)||g.isJSXExpressionContainer(e)||g.isJSXSpreadChild(e)||g.isJSXElement(e)||g.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),g.jsxElement(g.jsxOpeningElement(g.jsxIdentifier(t??this.configuration.wrapper.component),this.getProviderProps(n)),g.jsxClosingElement(g.jsxIdentifier(t??this.configuration.wrapper.component)),[g.jsxText(`
1725
+ `),e,g.jsxText(`
1726
+ `)])}getProviderProps(e){return hr({...this.configuration.wrapper.props,...e?.props})}containsElement(e,t){let n=false;return traverseFast(e,r=>{!n&&g.isJSXOpeningElement(r)&&g.isJSXIdentifier(r.name)&&r.name.name===t&&(n=true);}),n}findComponentDeclaration(e,t){let n=null;return traverse(e,{VariableDeclaration:r=>{if(!g.isProgram(r.parent))return r.skip();for(let i of r.node.declarations)if(g.isVariableDeclarator(i)&&g.isIdentifier(i.id)&&i.id.name===t)return n=i,r.stop();return r.skip()},FunctionDeclaration:r=>{if(!g.isProgram(r.parent))return r.skip();let{id:i}=r.node;return g.isIdentifier(i)&&i.name===t?(n=r.node,r.stop()):r.skip()}}),n}findTargetChildren(e,t){let n=null,{configuration:r}=this;return r.targets?.variable===void 0&&r.targets?.component===void 0?null:(traverse(e,{enter:function(a){let{node:s}=a;if(s===t)return a.traverse({JSXExpressionContainer:p=>{let{expression:c}=p.node;if(r.targets?.variable!==void 0&&g.isIdentifier(c)&&c.name===r.targets.variable){let l=p.parent;return n={parent:l,index:l.children.indexOf(p.node)},p.stop()}},JSXElement:p=>{let{openingElement:c}=p.node;if(r.targets?.component!==void 0&&g.isJSXOpeningElement(c)&&g.isJSXIdentifier(c.name)&&c.name.name===r.targets.component&&p.parent!==null){let l=p.parent;n={parent:l,index:l.children.indexOf(p.node)};}}}),a.stop()}}),n)}static findReturnStatement(e){let t=null;return traverseFast(e,n=>{t===null&&g.isReturnStatement(n)&&(t=n);}),t}};var We=class{constructor(e){this.codemod=e.codemod;}async apply(e,t){let n=Sr.parse(e,{parser:{parse:parse}}),r=await this.codemod.apply(n,t);return r.modified?{modified:true,result:Sr.print(r.result,{reuseWhitespace:false}).code}:{modified:false,result:e}}};function ja(o,e){let t=typeof o=="string"?Ke(o,["jsx","typescript"]):o,n=false;return traverse(t,{ExportAllDeclaration:r=>{let{node:i}=r;return !g.isStringLiteral(i.source)||!Fa(i.source,e.moduleName)||(n=true),r.skip()},ExportNamedDeclaration:r=>{let{node:i}=r;if(!g.isStringLiteral(i.source)||!Fa(i.source,e.moduleName))return r.skip();if(e.importName===void 0)return n=true,r.skip();for(let a of i.specifiers)if(g.isExportSpecifier(a)&&Fa(a.local,e.importName))return n=true,r.skip();return r.skip()}}),n}function Fa(o,e){let t=g.isIdentifier(o)?o.name:o.value;return typeof e=="string"?t===e:e.test(t)}function br(o,e){let t=[],n=false,r=false;if(traverse(o,{ExportAllDeclaration:s=>{let{node:p}=s;if(p.source.value!==e.moduleName)return s.skip();let c=p.exportKind??"value";if(e.exportName===void 0&&e.importName===void 0){if(c==="value"||c==="type"&&e.type==="type")return n=true,s.stop();if(c==="type"&&e.type==="value")return p.exportKind="value",n=true,r=true,s.stop()}else if((e.exportName===void 0||e.exportName===e.importName)&&(c==="value"||c==="type"&&e.type==="type"))return n=true,s.stop();return s.skip()},ExportNamedDeclaration:s=>{let{node:p}=s,c=p.source??null;if(c===null||c.value!==e.moduleName)return s.skip();t.push({declaration:p});let l=p.exportKind??"value";for(let m of p.specifiers){if(g.isExportNamespaceSpecifier(m)&&e.importName===void 0&&m.exported.name===e.exportName)return n=true,e.type==="value"&&l==="type"&&(p.exportKind="value",r=true),s.stop();if(e.importName===void 0||!g.isExportSpecifier(m)||Wa(m.local)!==e.importName||e.exportName!==void 0&&Wa(m.exported)!==e.exportName)continue;let f=m.exportKind??"value";if(l===e.type||l==="value"&&(f==="value"||m.exportKind===e.type))return n=true,s.stop();t.unshift({declaration:p,specifier:m});}return s.skip()}}),n)return r;let{body:i}=o.program;if(e.importName===void 0){if(e.exportName===void 0)for(let p of t){let{declaration:c}=p,l=c.exportKind??"value",m=c.specifiers.filter(f=>!g.isExportSpecifier(f)||f.local.name!==Wa(f.exported)||e.type==="type"&&l!=="type"&&f.exportKind!=="type");m.length===0?i.splice(i.indexOf(c),1):c.specifiers=m;}let s=e.exportName===void 0?g.exportAllDeclaration(g.stringLiteral(e.moduleName)):g.exportNamedDeclaration(null,[g.exportNamespaceSpecifier(g.identifier(e.exportName))],g.stringLiteral(e.moduleName));return e.type==="type"&&(s.exportKind="type"),i.push(s),true}for(let s of t){let{declaration:p}=s;if(p.exportKind==="type"&&e.type==="value"){p.exportKind="value";for(let c of p.specifiers)g.isExportSpecifier(c)&&c!==s.specifier&&(c.exportKind="type");return s.specifier===void 0&&p.specifiers.push(g.exportSpecifier(g.identifier(e.importName),g.identifier(e.exportName??e.importName))),true}}for(let{declaration:s}of t){let p=s.exportKind??"value";if(p==="value"||p===e.type){let c=g.exportSpecifier(g.identifier(e.importName),g.identifier(e.exportName??e.importName));return p!==e.type&&(c.exportKind="type"),s.specifiers.push(c),true}}let a=g.exportNamedDeclaration(null,[g.exportSpecifier(g.identifier(e.importName),g.identifier(e.exportName??e.importName))],g.stringLiteral(e.moduleName));return e.type==="type"&&(a.exportKind="type"),i.push(a),true}function Wa(o){return g.isIdentifier(o)?o.name:o.value}var Ir=class o{constructor(e){this.configuration=e;}apply(e){let{body:t}=e.program,n=ja(e,{moduleName:this.configuration.import.module,importName:this.configuration.import.configName}),r=ja(e,{moduleName:this.configuration.import.module,importName:this.configuration.import.middlewareName}),i=n?null:o.findConfig(e);if(r){if(n||i!==null)return Promise.resolve({modified:false,result:e});let m=br(e,{type:"value",moduleName:this.configuration.import.module,importName:this.configuration.import.configName});return Promise.resolve({modified:m,result:e})}let a=Ct(e,{moduleName:this.configuration.import.module,importName:this.configuration.import.middlewareFactoryName}),s=Ct(e,{moduleName:this.configuration.import.module,importName:this.configuration.import.middlewareName}),p=[];if(a!==null&&p.push(a),s!==null&&p.push(s),p.length>0&&o.isCalled(e,p))return Promise.resolve({modified:false,result:e});let c=i===null?null:Ct(e,{moduleName:this.configuration.import.module,importName:this.configuration.import.matcherName}),l=o.refactorMiddleware(e,a??this.configuration.import.middlewareFactoryName,i!==null&&i.matcher?i.name:void 0);if(l===null){if(i===null){let m=br(e,{type:"value",moduleName:this.configuration.import.module,importName:this.configuration.import.middlewareName}),f=br(e,{type:"value",moduleName:this.configuration.import.module,importName:this.configuration.import.configName});return Promise.resolve({modified:m||f,result:e})}l=g.exportDefaultDeclaration(g.callExpression(g.identifier(a??this.configuration.import.middlewareFactoryName),[g.objectExpression([g.objectProperty(g.identifier("matcher"),g.memberExpression(g.identifier(i.name),g.identifier(c??this.configuration.import.matcherName)))])])),t.push(l);}if(i!==null){this.configureMatcher(i.object,c??this.configuration.import.matcherLocalName);let m=t.indexOf(i.root),f=t.indexOf(l);if(m>f){t.splice(f,0,...t.splice(m,1));for(let b of o.findReferencesFrom(i.root,e.program)){let A=t.indexOf(b);A>f&&t.splice(f,0,...t.splice(A,1));}}}return a===null&&de(e,{type:"value",moduleName:this.configuration.import.module,importName:this.configuration.import.middlewareFactoryName}),i?.matcher===true&&c===null&&de(e,{type:"value",moduleName:this.configuration.import.module,importName:this.configuration.import.matcherName,localName:this.configuration.import.matcherLocalName}),Promise.resolve({modified:true,result:e})}configureMatcher(e,t){let n=false;for(let r of e.properties)if(g.isObjectProperty(r)&&g.isIdentifier(r.key)&&r.key.name==="matcher"){if(g.isStringLiteral(r.value)){r.value=g.arrayExpression([r.value,g.identifier(t)]),n=true;break}if(g.isArrayExpression(r.value)){let{elements:i}=r.value;i.some(a=>g.isIdentifier(a)&&a.name===t)||(i.push(g.identifier(t)),n=true);break}if(g.isIdentifier(r.value)){if(r.value.name===t)break;r.value=g.arrayExpression([g.spreadElement(g.conditionalExpression(g.callExpression(g.memberExpression(g.identifier("Array"),g.identifier("isArray")),[r.value]),r.value,g.arrayExpression([r.value]))),g.identifier(t)]),n=true;}}return n}static refactorMiddleware(e,t,n){let r=null;return traverse(e,{ExportNamedDeclaration:i=>{let{node:a}=i,{declaration:s,specifiers:p=[]}=a;if(g.isFunctionDeclaration(s))return g.isFunctionDeclaration(a.declaration)&&g.isIdentifier(a.declaration.id)&&a.declaration.id.name==="middleware"?(i.replaceWith(g.exportNamedDeclaration(g.variableDeclaration("const",[g.variableDeclarator(g.identifier("middleware"),o.wrapMiddleware(g.isFunctionDeclaration(a.declaration)?o.createFunctionExpression(a.declaration):a.declaration,t,n))]),[])),r=o.getRootNode(i),i.stop()):i.skip();if(g.isVariableDeclaration(s)){for(let c of s.declarations)if(g.isVariableDeclarator(c)&&g.isIdentifier(c.id)&&c.id.name==="middleware"){let l=c.init??null;if(l!==null)return c.init=o.wrapMiddleware(l,t,n),r=o.getRootNode(i),i.stop()}}for(let c of p)if(g.isExportSpecifier(c)&&g.isIdentifier(c.exported)&&g.isIdentifier(c.local)&&["middleware","default"].includes(c.exported.name))return r=o.replaceMiddlewareDeclaration(e,c.local.name,t,n),i.stop();return i.skip()},ExportDefaultDeclaration:i=>{let{node:a}=i,{declaration:s}=a;return g.isArrowFunctionExpression(s)?(i.replaceWith(g.exportDefaultDeclaration(o.wrapMiddleware(s,t,n))),r=o.getRootNode(i),i.stop()):g.isFunctionDeclaration(s)?(i.replaceWith(g.exportDefaultDeclaration(o.wrapMiddleware(o.createFunctionExpression(s,true),t,n))),r=o.getRootNode(i),i.stop()):g.isIdentifier(s)?(r=o.replaceMiddlewareDeclaration(e,s.name,t,n),i.stop()):i.skip()}}),r}static replaceMiddlewareDeclaration(e,t,n,r){let i=null;return traverse(e,{VariableDeclarator:a=>{let{node:s}=a;if(g.isIdentifier(s.id)&&s.id.name===t){let p=s.init??null;return p!==null&&(s.init=o.wrapMiddleware(p,n,r),i=o.getRootNode(a)),a.stop()}return a.skip()},FunctionDeclaration:a=>{let{node:s}=a;return g.isIdentifier(s.id)&&s.id.name===t?(a.replaceWith(o.wrapFunctionDeclaration(s,n,r,g.isIdentifier(s.id)?s.id.name:void 0)),i=o.getRootNode(a),a.stop()):a.skip()}}),i}static isCalled(e,t){let n=false;return traverse(e,{CallExpression:r=>{let{node:i}=r;return g.isIdentifier(i.callee)&&t.includes(i.callee.name)?(n=true,r.stop()):r.skip()}}),n}static findConfig(e){let t=null;return traverse(e,{ExportNamedDeclaration:n=>{let{declaration:r,specifiers:i=[]}=n.node;if(g.isVariableDeclaration(r)){for(let a of r.declarations)if(g.isVariableDeclarator(a)&&g.isIdentifier(a.id)&&a.id.name==="config"){let s=g.isIdentifier(a.init)?o.findVariableDeclarator(e,a.init.name):{name:"config",root:o.getRootNode(n),declaration:a};if(s===null||s.declaration.init===null)return n.stop();if(g.isObjectExpression(s.declaration.init))return t={name:s.name,root:s.root,object:s.declaration.init,matcher:o.hasMatcherProperty(s.declaration.init)},n.stop()}}for(let a of i)if(g.isExportSpecifier(a)&&g.isIdentifier(a.exported)&&g.isIdentifier(a.local)&&a.exported.name==="config"){let s=o.findVariableDeclarator(e,a.local.name);return s!==null&&g.isObjectExpression(s.declaration.init)&&(t={name:s.name,root:s.root,object:s.declaration.init,matcher:o.hasMatcherProperty(s.declaration.init)}),n.stop()}return n.skip()}}),t}static hasMatcherProperty(e){for(let t of e.properties)if(g.isObjectProperty(t)&&g.isIdentifier(t.key)&&t.key.name==="matcher")return true;return false}static findVariableDeclarator(e,t){let n=null;return traverse(e,{VariableDeclarator:r=>{if(!g.isProgram(r.parentPath.parent))return r.skip();let{node:i}=r;return g.isVariableDeclarator(i)&&g.isIdentifier(i.id)&&i.id.name===t?(g.isIdentifier(i.init)?n=o.findVariableDeclarator(e,i.init.name):n={name:t,root:o.getRootNode(r),declaration:i},r.stop()):r.skip()}}),n}static wrapMiddleware(e,t,n){return g.callExpression(g.identifier(t),[n!==void 0?g.objectExpression([g.objectProperty(g.identifier("matcher"),g.memberExpression(g.identifier(n),g.identifier("matcher"))),g.objectProperty(g.identifier("next"),e)]):e])}static wrapFunctionDeclaration(e,t,n,r="middleware"){return g.variableDeclaration("const",[g.variableDeclarator(g.identifier(r),o.wrapMiddleware(o.createFunctionExpression(e),t,n))])}static findReferencesFrom(e,t){let n=new Set;traverse(t,{enter:i=>{let{node:a}=i;if(a===e)return i.traverse({Identifier:function(p){let c=p.node;return o.isVariableReference(p.parent,c)&&n.add(c.name),p.skip()}}),i.stop()}});let r=[];return traverse(t,{VariableDeclarator:i=>{if(!g.isProgram(i.parentPath.parent))return i.skip();let{node:a}=i;return g.isIdentifier(a.id)&&n.has(a.id.name)&&r.push(o.getRootNode(i)),i.skip()},FunctionDeclaration:i=>{if(!g.isProgram(i.parent))return;let{node:a}=i;return g.isIdentifier(a.id)&&n.has(a.id.name)&&r.push(o.getRootNode(i)),i.skip()},ClassDeclaration:i=>{if(!g.isProgram(i.parent))return;let{node:a}=i;return g.isIdentifier(a.id)&&n.has(a.id.name)&&r.push(o.getRootNode(i)),i.skip()}}),[...new Set(r.flatMap(i=>[i,...o.findReferencesFrom(i,t)]))]}static isVariableReference(e,t){return g.isVariableDeclarator(e)?e.init===t:g.isClassProperty(e)||g.isObjectProperty(e)||g.isProperty(e)?e.value===t:g.isMemberExpression(e)?e.object===t:g.isCallExpression(e)||g.isNewExpression(e)?e.callee===t:g.isExpression(e)}static createFunctionExpression(e,t=false){return g.functionExpression(t?e.id:null,e.params,e.body,e.generator,e.async)}static getRootNode(e){let t=e;for(;t.parentPath!==null&&!g.isProgram(t.parent);)t=t.parentPath;return t.node}};var Ve=class{constructor(e,t){this.codemod=t,this.formatter=e;}async apply(e,t){if(this.codemod===void 0)return await this.formatter.format([e]),{modified:true,result:e};let n=await this.codemod.apply(e,t);return n.modified&&await this.formatter.format([e]),n}};var Ue=class{constructor({fileSystem:e,codemod:t}){this.fileSystem=e,this.codemod=t;}async apply(e,t){let n="";if(await this.fileSystem.exists(e))try{n=await this.fileSystem.readTextFile(e);}catch(i){throw new Ge("Failed to read file.",{cause:i,details:[`File: file://${e.replace(/\\/g,"/")}`]})}let r=await this.codemod.apply(n,t);if(r.modified)try{await this.fileSystem.writeTextFile(e,r.result,{overwrite:!0});}catch(i){throw new Ge("Failed to write file",{cause:i,details:[`File: file://${e.replace(/\\/g,"/")}`]})}return {modified:r.modified,result:e}}};var xr=class{constructor(e){this.configuration=e;}apply(e,t={}){let n=t.typescript??false,{body:r}=e.program,i=de(e,{type:"value",moduleName:this.configuration.provider.module,importName:this.configuration.provider.component}),a=n?de(e,{type:"type",moduleName:"react",importName:"PropsWithChildren"}):null,s=n?de(e,{type:"type",moduleName:"react",importName:"ReactNode"}):null,p=g.objectPattern([g.objectProperty(g.identifier("children"),g.identifier("children"))]);a!==null&&(p.typeAnnotation=g.tsTypeAnnotation(g.tsTypeReference(g.identifier(a.localName))));let c=g.functionDeclaration(g.identifier("RootLayout"),[p],g.blockStatement([g.returnStatement(g.parenthesizedExpression(g.jsxElement(g.jsxOpeningElement(g.jsxIdentifier("html"),[g.jsxAttribute(g.jsxIdentifier("lang"),g.stringLiteral("en"))]),g.jsxClosingElement(g.jsxIdentifier("html")),[g.jsxText(`
1727
+ `),g.jsxElement(g.jsxOpeningElement(g.jsxIdentifier("body"),[]),g.jsxClosingElement(g.jsxIdentifier("body")),[g.jsxText(`
1728
+ `),g.jsxElement(g.jsxOpeningElement(g.jsxIdentifier(i.localName),[]),g.jsxClosingElement(g.jsxIdentifier(i.localName)),[g.jsxText(`
1729
+ `),g.jsxExpressionContainer(g.identifier("children")),g.jsxText(`
1730
+ `)]),g.jsxText(`
1731
+ `)]),g.jsxText(`
1732
+ `)])))]));return s!==null&&(c.returnType=g.tsTypeAnnotation(g.tsTypeReference(g.identifier(s.localName)))),r.push(g.exportDefaultDeclaration(c)),Promise.resolve({modified:true,result:e})}};var tn=class{constructor(e){this.configuration=e;}apply(e,t={}){let n=t.typescript??false,{body:r}=e.program,i=de(e,{type:"value",moduleName:this.configuration.provider.module,importName:this.configuration.provider.component}),a=n?de(e,{type:"type",moduleName:"next/app",importName:"AppProps"}):null,s=n?de(e,{type:"type",moduleName:"react",importName:"ReactNode"}):null,p=g.objectPattern([g.objectProperty(g.identifier("Component"),g.identifier("Component")),g.objectProperty(g.identifier("pageProps"),g.identifier("pageProps"))]);a!==null&&(p.typeAnnotation=g.tsTypeAnnotation(g.tsTypeReference(g.identifier(a.localName))));let c=g.functionDeclaration(g.identifier("App"),[p],g.blockStatement([g.returnStatement(g.parenthesizedExpression(g.jsxElement(g.jsxOpeningElement(g.jsxIdentifier(i.localName),hr(this.configuration.provider.props??{})),g.jsxClosingElement(g.jsxIdentifier(i.localName)),[g.jsxText(`
1733
+ `),g.jsxElement(g.jsxOpeningElement(g.jsxIdentifier("Component"),[g.jsxSpreadAttribute(g.identifier("pageProps"))]),g.jsxClosingElement(g.jsxIdentifier("Component")),[]),g.jsxText(`
1734
+ `)])))]));return s!==null&&(c.returnType=g.tsTypeAnnotation(g.tsTypeReference(g.identifier(s.localName)))),r.push(g.exportDefaultDeclaration(c)),Promise.resolve({modified:true,result:e})}};var vr=class o extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var wr=class o{constructor(e){this.configuration=e;}async format(e){let t=await this.getCommand(e);if(t!==null)try{await this.run(t);}catch{}}async run(e){let{commandExecutor:t,workingDirectory:n,timeout:r}=this.configuration;if(await t.run(e,{workingDirectory:n.get(),timeout:r}).wait()!==0)throw new vr("Failed to format code.")}async getCommand(e){let{tools:t,packageManager:n,fileSystem:r}=this.configuration;for(let i of t){if(!await n.hasDirectDependency(i.package))continue;let a=await n.getDependency(i.package);if(a===null)continue;let s=o.getBinPath(a,i.bin);if(s!==null)return {name:r.joinPaths(a.directory,r.normalizeSeparators(s)),arguments:i.args(e)}}return null}static getBinPath({metadata:e},t){return "bin"in e?typeof e.bin=="string"?e.bin:t!==void 0&&typeof e.bin=="object"&&e.bin!==null&&typeof e.bin[t]=="string"?e.bin[t]:null:null}};var kt=class o{constructor(e){this.config=e;}async execute(e){let{sdk:t,configurationManager:n,io:r}=this.config,{output:i}=r,a=await n.load(),s=await this.getSlots(a,e);if(s.length===0){i.inform("No slots to add");return}let p={input:r.input,output:r.output,configuration:{...a,slots:{...a.slots,...Object.fromEntries(s.map(([c,l])=>[c.slug,l.toString()]))}}};if(await n.update(p.configuration),i.confirm("Configuration updated"),await t.update(p,{clean:true}),e.example===true){let c=i.notify("Generating example");try{await Promise.all(s.map(([l])=>t.generateSlotExample(l,p)));}catch(l){throw c.stop(),l}c.confirm("Example generated");}}async getSlots(e,t){let{slotForm:n,workspaceApi:r,io:{output:i}}=this.config,a=t.slots===void 0?void 0:o.getVersionMap(t.slots,e.slots),s=Object.keys(e.slots),p=await n.handle({organizationSlug:e.organization,workspaceSlug:e.workspace,preselected:a===void 0?void 0:Object.keys(a),selected:t.example===true?[]:s});if(s.length===p.length&&p.every(c=>s.includes(c.slug))&&i.inform("No new slots to add"),t.slots!==void 0&&t.slots.length>0&&p.length!==t.slots.length){let c=t.slots.filter(l=>!p.some(m=>m.slug===l));throw new d(`Non-existing slots: \`${c.join("`, `")}\``,{reason:"invalid_input",suggestions:["Run `slot add` without arguments to see available slots"]})}return Promise.all(p.map(async c=>{let l=a?.[c.slug];if(l===void 0||l.getMaxVersion()===c.version.major)return [c,l??O.of(c.version.major)];if(l.getMinVersion()>c.version.major)throw new d(`No matching version for slot \`${c.slug}\`.`,{reason:"invalid_input",details:[`Requested version: ${l.toString()}`,`Current version: ${c.version.major}`],suggestions:["Omit version specifier to use the latest version"]});return t.example!==true?[c,l]:[await r.getSlot({organizationSlug:e.organization,workspaceSlug:e.workspace,slotSlug:c.slug,majorVersion:Math.min(c.version.major,l.getMinVersion())})??c,l]}))}static getVersionMap(e,t){return Object.fromEntries(e.map(n=>{let[r,i]=n.split("@",2);if(i===void 0)return [r,void 0];if(!O.isValid(i))throw new d(`Invalid version specifier \`${i}\` for slot \`${r}\`.`,{reason:"invalid_input",suggestions:["Version must be exact (i.e. `1`), range (i.e. `1 - 2`), or set (i.e. `1 || 2`)."]});let a=O.parse(i);if(a.getCardinality()>5)throw new d(`The number of versions specified for slot \`${r}\` exceeds 5 major versions.`,{reason:"invalid_input",suggestions:["Narrow down the number of versions to 5 or less."]});if(t[r]!==void 0&&(a=O.parse(t[r]).with(a),a.getCardinality()>5))throw new d(`The cumulative number of versions for slot \`${r}\` cannot exceed 5 major versions.`,{reason:"invalid_input",suggestions:["Narrow down the number of versions to 5 or less."]});return [r,a]}))}};var Qe=class{constructor(e){this.config=e;}async handle(e){let{output:t,input:n}=this.config,r=t.notify("Loading slots"),i=await this.getSlots(e,e.allowed);r.stop();let a=e.preselected??[];if(a.length>0)return i.filter(({slug:p})=>a.includes(p));let s=e.selected??[];return i.length===0||s.length>0&&i.every(({slug:p})=>s.includes(p))?i.filter(({slug:p})=>s.includes(p)):e.selectionConfirmation!==void 0&&!await n.confirm(e.selectionConfirmation)?i.filter(({slug:c})=>s.includes(c)):n.selectMultiple({message:"Select slots",options:i.map(p=>{let c=s.includes(p.slug);return {value:p,label:p.name,disabled:c,selected:c}})})}async getSlots(e,t){let{workspaceApi:n}=this.config,r=await n.getSlots({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return t===void 0?r:r.filter(({slug:i})=>t.includes(i))}};var At=class o{constructor(e){this.config=e;}async execute(e){let{sdk:t,configurationManager:n,io:r}=this.config,{output:i}=r,a=await n.load(),s=await this.getComponents(a,e);if(s.length===0){i.inform("No components to add");return}let p={input:r.input,output:r.output,configuration:{...a,components:{...a.components,...Object.fromEntries(s.map(([c,l])=>[c.slug,l.toString()]))}}};await n.update(p.configuration),i.confirm("Configuration updated"),await t.update(p,{clean:true});}async getComponents(e,t){let{componentForm:n,io:{output:r}}=this.config,i=t.components===void 0?void 0:o.getVersionMap(t.components,e.components),a=Object.keys(e.components),s=await n.handle({organizationSlug:e.organization,workspaceSlug:e.workspace,preselected:i===void 0?void 0:Object.keys(i),selected:a});if(a.length===s.length&&s.every(p=>a.includes(p.slug))&&r.inform("No new component to add"),t.components!==void 0&&t.components.length>0&&s.length!==t.components.length){let p=t.components.filter(c=>!s.some(l=>l.slug===c));throw new d(`Non-existing components: \`${p.join("`, `")}\``,{reason:"invalid_input",suggestions:["Run `component add` without arguments to see available components"]})}return s.map(p=>{let c=i?.[p.slug];if(c===void 0||c.getMaxVersion()===p.version.major)return [p,c??O.of(p.version.major)];if(c.getMinVersion()>p.version.major)throw new d(`No matching version for component \`${p.slug}\`.`,{reason:"invalid_input",details:[`Requested version: ${c.toString()}`,`Current version: ${p.version.major}`],suggestions:["Omit version specifier to use the latest version"]});return [p,c]})}static getVersionMap(e,t){return Object.fromEntries(e.map(n=>{let[r,i]=n.split("@",2);if(i===void 0)return [r,void 0];if(!O.isValid(i))throw new d(`Invalid version specifier \`${i}\` for component \`${r}\`.`,{reason:"invalid_input",suggestions:["Version must be exact (i.e. `1`), range (i.e. `1 - 2`), or set (i.e. `1 || 2`)."]});let a=O.parse(i);if(a.getCardinality()>5)throw new d(`The number of versions specified for component \`${r}\` exceeds 5 major versions.`,{reason:"invalid_input",suggestions:["Narrow down the number of versions to 5 or less."]});if(t[r]!==void 0&&(a=O.parse(t[r]).with(a),a.getCardinality()>5))throw new d(`The cumulative number of versions for component \`${r}\` cannot exceed 5 major versions.`,{reason:"invalid_input",suggestions:["Narrow down the number of versions to 5 or less."]});return [r,a]}))}};var Be=class{constructor(e){this.config=e;}async handle(e){let{workspaceApi:t}=this.config,{allowed:n}=e,r=await t.getComponents({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug}),i=await this.selectComponents(e,n===void 0?r:r.filter(({slug:a})=>n.includes(a)));if(e.includeDependencies!==true)return i;for(let a of i){let s=new Set([...a.metadata.directReferences,...a.metadata.indirectReferences]);for(let p of s)if(!i.some(({slug:c})=>c===p)){let c=r.find(({slug:l})=>l===p);c!==void 0&&i.push(c);}}return i}async selectComponents(e,t){let{output:n,input:r}=this.config;n.notify("Loading components").stop();let a=e.preselected??[];if(a.length>0)return t.filter(({slug:p})=>a.includes(p));let s=e.selected??[];return t.length===0||s.length>0&&t.every(({slug:p})=>s.includes(p))?t.filter(({slug:p})=>s.includes(p)):e.selectionConfirmation!==void 0&&!await r.confirm(e.selectionConfirmation)?t.filter(({slug:c})=>s.includes(c)):r.selectMultiple({message:"Select components",options:t.map(p=>{let c=s.includes(p.slug);return {value:p,label:p.name,disabled:c,selected:c}})})}};var nn=class o{constructor(e){this.config=e;}async execute(e){let{sdk:t,configurationManager:n,slotForm:r,io:i}=this.config,{output:a}=i,s=await n.load(),p=e.slots===void 0?void 0:o.getVersionMap(e.slots,s.slots),c=await r.handle({organizationSlug:s.organization,workspaceSlug:s.workspace,allowed:Object.keys(s.slots),preselected:p===void 0?void 0:Object.keys(p)});if(c.length===0)return a.inform("No slots to remove.");let l={input:i.input,output:i.output,configuration:{...s,slots:Object.fromEntries(Object.entries(s.slots).flatMap(([m,f])=>p?.[m]!==void 0?p[m]===null?[]:[[m,p[m].toString()]]:c.some(b=>b.slug===m)?[]:[[m,f.toString()]]))}};await n.update(l.configuration),a.confirm("Configuration updated"),await t.update(l,{clean:true});}static getVersionMap(e,t){return Object.fromEntries(e.map(n=>{let[r,i]=n.split("@",2);if(t[r]===void 0||i===void 0)return [r,null];let a=O.parse(t[r]);if(!O.isValid(i))return [r,a];let s=O.parse(i);return a.intersects(s)?s.contains(a)?[r,null]:[r,a.without(s)]:[r,a]}))}};var rn=class o{constructor(e){this.config=e;}async execute(e){let{sdk:t,configurationManager:n,componentForm:r,io:i}=this.config,{output:a}=i,s=await n.load(),p=e.components===void 0?void 0:o.getVersionMap(e.components,s.components),c=await r.handle({organizationSlug:s.organization,workspaceSlug:s.workspace,allowed:Object.keys(s.components),preselected:p===void 0?void 0:Object.keys(p)});if(c.length===0)return a.alert("No components to remove.");let l={input:i.input,output:i.output,configuration:{...s,components:Object.fromEntries(Object.entries(s.components).flatMap(([m,f])=>p?.[m]!==void 0?p[m]===null?[]:[[m,p[m].toString()]]:c.some(b=>b.slug===m)?[]:[[m,f.toString()]]))}};a.confirm("Configuration updated"),await n.update(l.configuration),await t.update(l,{clean:true});}static getVersionMap(e,t){return Object.fromEntries(e.map(n=>{let[r,i]=n.split("@",2);if(t[r]===void 0||i===void 0)return [r,null];let a=O.parse(t[r]);if(!O.isValid(i))return [r,a];let s=O.parse(i);return a.intersects(s)?s.contains(a)?[r,null]:[r,a.without(s)]:[r,a]}))}};var Pr=class{constructor({manager:e,initializer:t}){this.manager=e,this.initializer=t;}isInitialized(){return this.manager.isInitialized()}async load(){return await this.isInitialized()||await this.initializer.initialize(),this.manager.load()}update(e){return this.manager.update(e)}};var on=class{constructor(e){this.configuration=e;}async execute(e){let{sdk:t,configurationManager:n,io:r}=this.configuration,i={input:r.input,output:r.output,configuration:await n.load()};await t.update(i,{clean:e.clean});}};var Cr=class o{static{this.SITEMAP={Home:"/","Personal settings":"/settings",Organization:"/organizations/:organization","Organization settings":"/organizations/:organization/settings","Organization members":"/organizations/:organization/members",Workspace:"/organizations/:organization/workspaces/:workspace","Workspace settings":"/organizations/:organization/workspaces/:workspace/settings","Workspace members":"/organizations/:organization/workspaces/:workspace/members","Dev application":"/organizations/:organization/workspaces/:workspace/applications/:dev-application/dashboard","Prod application":"/organizations/:organization/workspaces/:workspace/applications/:prod-application/dashboard","Dev application settings":"/organizations/:organization/workspaces/:workspace/applications/:dev-application/settings","Prod application settings":"/organizations/:organization/workspaces/:workspace/applications/:prod-application/settings",Slots:"/organizations/:organization/workspaces/:workspace/slots",Components:"/organizations/:organization/workspaces/:workspace/components",Experiences:"/organizations/:organization/workspaces/:workspace/experiences"};}constructor(e){this.config=e;}async handle(e){return o.resolvePath(await this.getPage(e.page,e),e)}getPage(e,t){if(e!==void 0){let r=o.findMatch(e,t);if(r!==null)return Promise.resolve(r)}let{input:n}=this.config;return n.select({message:"Where do you want to go?",options:Object.entries(o.SITEMAP).map(([r,i])=>({value:i,label:r}))})}static findMatch(e,t){if(e.startsWith("/"))return e;let n=null,r=.5;for(let i of Object.keys(o.getSitemap(t))){let a=Fl(e,i);a>r&&(n=o.SITEMAP[i],r=a);}return n}static getSitemap(e){return e.prodApplicationSlug!==void 0?o.SITEMAP:Object.fromEntries(Object.entries(o.SITEMAP).filter(([,t])=>!t.includes(":prod-application")))}static resolvePath(e,t){return e.replace(/:(organization|workspace|(dev|prod)-application)/g,(n,r)=>{switch(r){case "organization":return t.organizationSlug;case "workspace":return t.workspaceSlug;case "dev-application":return t.devApplicationSlug;case "prod-application":return t.prodApplicationSlug??""}})}};var kr=class{constructor({instruction:e,authenticator:t}){this.instruction=e,this.authenticator=t;}getToken(){return this.authenticator.getToken()}login(e){if(Object.keys(e).length===0){let{message:t,...n}=this.instruction;throw new d(t,n)}return this.authenticator.login(e)}logout(){return this.authenticator.logout()}};var Ar=class{constructor(e){this.instruction=e;}prompt(){return this.report()}select(){return this.report()}selectMultiple(){return this.report()}confirm(){return this.report()}wait(){return this.report()}report(){let{message:e,...t}=this.instruction;throw new d(e,t)}};var Er=class{constructor(e){this.authenticators=e;}async getToken(){for(let e of Object.values(this.authenticators)){let t=await e.getToken();if(t!==null)return t}return null}login(e){let t={...e};return delete t.method,this.authenticators[e.method].login(t)}async logout(){await Promise.all(Object.values(this.authenticators).map(e=>e.logout()));}};var an=class o{constructor(e){this.config=e;}async execute(e){let{sdk:t,configurationManager:n,io:r}=this.config,i=await n.load(),a=await this.selectSlots(i,e.slots),s=await this.selectComponents(i,e.components),p={input:r.input,output:r.output,configuration:{...i,slots:{...i.slots,...Object.fromEntries(a.map(c=>[c.slug,o.resolveVersion(c.version.major,i.slots[c.slug])]))},components:{...i.components,...Object.fromEntries(s.map(c=>[c.slug,o.resolveVersion(c.version.major,i.components[c.slug])]))}}};await n.update(p.configuration),await t.update(p,{clean:true});}async selectComponents(e,t){let{form:{componentForm:n}}=this.config,r=t===void 0?Object.keys(e.components):t,i=r.length===0?[]:await n.handle({organizationSlug:e.organization,workspaceSlug:e.workspace,preselected:r});if(r.length>0&&i.length!==r.length){let a=r.filter(s=>!i.some(p=>p.slug===s));throw new d(`Components not found: \`${a.join("`, `")}\`.`,{reason:"precondition",suggestions:["Run `remove component` to remove a component from your configuration."]})}return i}async selectSlots(e,t){let{form:{slotForm:n}}=this.config,r=t===void 0?Object.keys(e.slots):t,i=r.length===0?[]:await n.handle({organizationSlug:e.organization,workspaceSlug:e.workspace,preselected:r});if(r.length>0&&i.length!==r.length){let a=r.filter(s=>!i.some(p=>p.slug===s));throw new d(`Slots not found: \`${a.join("`, `")}\`.`,{reason:"precondition",suggestions:["Run `remove slot` to remove a slot from your configuration."]})}return i}static resolveVersion(e,t){let n=O.of(e);if(t===void 0)return n.toString();let r=O.parse(t);return r.isExact()?n.toString():r.isRange()?r.getMaxVersion()>=n.getMaxVersion()?t:O.between(r.getMinVersion(),n.getMaxVersion()).toString():O.either(...r.getVersions(),...n.getVersions()).toString()}};var sn=class o extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var Or=class o{static{this.ERRORS={ENOENT:"The file or directory does not exist.",EACCES:"Unable to access the file or directory.",EISDIR:"Expected a file, but the path is a directory.",ENOTDIR:"Expected a directory, but the path is a file.",EPERM:"Operation not permitted.",EEXIST:"The file or directory already exists.",ENOTEMPTY:"The directory is not empty."};}static{this.ERROR_REASONS={ENOENT:"not_found",EACCES:"access_denied",EISDIR:"invalid_input",ENOTDIR:"invalid_input",EPERM:"access_denied",EEXIST:"invalid_input",ENOTEMPTY:"invalid_input"};}constructor(e){this.config={...e,defaultEncoding:e.defaultEncoding??"utf8"};}getSeparator(){return sep}normalizeSeparators(e){return e.replace(/\//g,sep)}getBaseName(e){return basename(e)}getDirectoryName(e){return dirname(e)}getRealPath(e){return this.execute(()=>realpath(this.resolvePath(e)))}getRelativePath(e,t){return relative(this.resolvePath(e),this.resolvePath(t))}isAbsolutePath(e){return isAbsolute(e)}isSubPath(e,t){let n=this.resolvePath(e),r=isAbsolute(t)?t:join(n,t),i=relative(n,r);return !i.startsWith("..")&&!isAbsolute(i)}isSymbolicLink(e){return this.execute(async()=>{try{return (await lstat(this.resolvePath(e))).isSymbolicLink()}catch(t){if(o.isErrorCode(t,["ENOENT","ENOTDIR"]))return false;throw t}})}isDirectory(e){return this.execute(async()=>{try{return (await lstat(this.resolvePath(e))).isDirectory()}catch(t){if(o.isErrorCode(t,["ENOENT","ENOTDIR"]))return false;throw t}})}isEmptyDirectory(e){return this.execute(async()=>(await readdir(this.resolvePath(e))).length===0)}create(e){switch(e.type){case "file":return this.execute(()=>writeFile(this.resolvePath(e.name),e.content));case "directory":return this.execute(()=>mkdir(this.resolvePath(e.name)));case "link":return this.execute(()=>link(e.target,this.resolvePath(e.name)));case "symlink":return this.execute(()=>symlink(e.target,this.resolvePath(e.name)))}}list(e,t=Number.POSITIVE_INFINITY){let n=this.resolvePath(e);return this.listRelatively(n,n,t)}async*listRelatively(e,t,n){if(n<0)return;let r=await this.execute(()=>lstat(e)).catch(()=>null);if(r===null)return;if(!r.isDirectory())return yield*this.createEntry(e,dirname(t),r,0);let i=await this.execute(()=>readdir(e));for(let a of i){let s=join(e,a),p=await this.execute(()=>lstat(s));yield*this.createEntry(s,t,p,n);}}async*createEntry(e,t,n,r){let i=relative(t,e);if(n.isFile()){let a=()=>this.execute(()=>createReadStream(e));yield {type:"file",name:i,get content(){return a()}};}else n.isDirectory()?(yield {type:"directory",name:i},r>0&&(yield*this.listRelatively(e,t,r-1))):n.isSymbolicLink()?yield {type:"symlink",name:i,target:await this.execute(()=>realpath(e))}:yield {type:"link",name:i,target:await this.execute(()=>realpath(e))};}joinPaths(...e){return join(...e)}async exists(e){try{return await lstat(this.resolvePath(e)),!0}catch(t){if(o.isErrorCode(t,["ENOENT","ENOTDIR"]))return false;throw t}}delete(e,t){return rm$1(this.resolvePath(e),{recursive:t?.recursive??false,force:true})}readTextFile(e){return this.execute(()=>readFile(this.resolvePath(e),this.config.defaultEncoding))}writeTextFile(e,t,n){return this.execute(()=>writeFile(this.resolvePath(e),t,{flag:n?.overwrite===true?"w":"wx",encoding:this.config.defaultEncoding}))}async createDirectory(e,t){await this.execute(()=>mkdir(this.resolvePath(e),{recursive:t?.recursive??false}));}createTemporaryDirectory(e){return this.execute(()=>mkdtemp(this.joinPaths(tmpdir(),e)))}copy(e,t,n){return this.execute(()=>cp$1(this.resolvePath(e),this.resolvePath(t),{recursive:true,force:n?.overwrite??false}))}resolvePath(e){return isAbsolute(e)?e:join(this.config.workingDirectory.get(),e)}execute(e){try{let t=e();return t instanceof Promise?t.catch(n=>o.reportError(n)):t}catch(t){o.reportError(t);}}static reportError(e){if(e instanceof Error){let t=Object.entries(o.ERRORS);for(let[n,r]of t)if(o.isErrorCode(e,[n]))throw new sn(r,{reason:o.ERROR_REASONS[n]??"other",cause:e,details:[`Code: ${n}`]})}throw new sn("An unexpected error occurred.",{cause:e})}static isErrorCode(e,t){return !(e instanceof Error)||!("code"in e)||typeof e.code!="string"?false:t.includes(e.code)}};var Dr=class{constructor(e){this.configuration=e;}wait(e){let{listener:t}=this.configuration;return new Promise((n,r)=>{this.focus(()=>t.wait(e).then(n,r));})}focus(e){switch(this.configuration.platform){case "darwin":return this.darwinFocus(e);case "linux":return this.linuxFocus(e);case "win32":return this.win32Focus(e);default:return e()}}async darwinFocus(e){let t=this.runCommand({name:"osascript",arguments:["-e","bundle identifier of (info for (path to frontmost application))"]});await e(),t!==null&&this.runCommand({name:"open",arguments:["-b",t]});}async linuxFocus(e){let t=this.runCommand({name:"xdotool",arguments:["getactivewindow"]});await e(),t!==null&&this.runCommand({name:"xdotool",arguments:["windowactivate",t]});}async win32Focus(e){let t=ae`
1734
1735
  Add-Type @"
1735
1736
  using System;
1736
1737
  using System.Runtime.InteropServices;
@@ -1743,35 +1744,35 @@ ${n}`)}toString(){return this.code}static formatName(e,t=true){let n=e.replace(/
1743
1744
  public static extern bool SetForegroundWindow(IntPtr hWnd);
1744
1745
  }
1745
1746
  "@
1746
- `,n=pe`
1747
+ `,n=ae`
1747
1748
  ${t}
1748
1749
  [Window]::GetForegroundWindow()
1749
- `,r=this.runCommand({name:"powershell",arguments:["-Command",`& {${n}}`]});if(await e(),r!==null){let i=pe`
1750
+ `,r=this.runCommand({name:"powershell",arguments:["-Command",`& {${n}}`]});if(await e(),r!==null){let i=ae`
1750
1751
  ${t}
1751
1752
  [Window]::SetForegroundWindow(${r})
1752
1753
  [Window]::ShowWindow(${r}, 9)
1753
- `;this.runCommand({name:"powershell",arguments:["-Command",`& {${i}}`]});}}runCommand(e){let{commandExecutor:t,timeout:n}=this.configuration;try{let r=t.runSync(e,{timeout:n});return r.exitCode!==0?null:r.output.trim()}catch{return null}}};var Br=class{constructor(e){this.detector=e.detector,this.templates=e.templates;}async generate(e){let t=await this.detector.detect(e.recipient);return t===null||this.templates[t]===void 0?null:this.templates[t].generate(e)}};var Yr=class{constructor(...e){this.detectors=e;}async detect(e){for(let t of this.detectors){let n=await t.detect(e);if(n!==null)return n}return null}};var ei=class ei{constructor(e=ei.DEFAULT_DOMAINS){this.domains=e;}detect(e){let t=e.toLowerCase().split("@")[1];for(let[n,r]of Object.entries(this.domains))if(r.some(a=>typeof a=="string"?a===t:a.test(t)))return Promise.resolve(n);return Promise.resolve(null)}};ei.DEFAULT_DOMAINS={google:["gmail.com","googlemail.com","google.com"],yahoo:[/yahoo\.com(?:\.\w+)?/,"yahoo.co.uk","yahoo.fr","yahoo.it","ymail.com","rocketmail.com"],microsoft:["outlook.com","live.com","hotmail.com","msn.com","passport.com","passport.net"],proton:["proton.me","protonmail.com"],icloud:["icloud.com"]};var Xr=ei;var ni=class ni{constructor(e=ni.DEFAULT_DOMAINS){this.domains=e;}async detect(e){let t=e.toLowerCase().split("@")[1],n=await this.lookup(t);for(let[r,i]of Object.entries(this.domains))for(let a of i)for(let s of n)if(s.endsWith(`.${a}.`))return r;return null}async lookup(e){let t=new URL("https://dns.google.com/resolve");t.searchParams.set("type","MX"),t.searchParams.set("name",e);let n;try{n=await fetch(t).then(r=>{if(!r.ok)throw new Error("Failed to lookup domain");return r.json()});}catch{return []}return n.Answer===void 0?[]:n.Answer.map(r=>r.data)}};ni.DEFAULT_DOMAINS={google:["google.com"],microsoft:["outlook.com"]};var ti=ni;var $t=vt(an()),ri=class o{generate(e){return new URL(`https://mail.google.com/mail${o.formatFilters(e)}`)}static formatFilters(e){let t=[`to:${e.recipient}`],n=`/u/${e.recipient}`;if(e.sender!==void 0&&t.push(`from:${e.sender}`),e.subject!==void 0&&t.push(`subject:${e.subject}`),e.timestamp!==void 0){let r=$t.TimeZone.of(Intl.DateTimeFormat().resolvedOptions().timeZone),i=$t.Instant.ofEpochSecond(e.timestamp),a=$t.LocalDateTime.ofInstant(i,r).getLocalDate();t.push(`after:${a}`);}return t.push("in:anywhere"),n+=`/#search/${t.map(r=>encodeURIComponent(r)).join("+")}`,n}};var ii=class{generate(e){return new URL("https://www.icloud.com/mail")}};var oi=class{generate(e){let t=new URL("https://outlook.live.com/mail");return e.recipient!==void 0&&t.searchParams.append("login_hint",e.recipient),t}};var ai=class o{generate(e){return new URL(`https://mail.proton.me/u/0/all-mail${o.formatFilters(e)}`)}static formatFilters(e){let t=new URLSearchParams;return t.set("to",e.recipient),e.sender!==void 0&&t.set("from",e.sender),e.timestamp!==void 0&&t.set("begin",e.timestamp.toFixed(0)),e.subject!==void 0&&t.set("keyword",e.subject),`#${t.toString()}`}};var si=class o{generate(e){return new URL(`https://mail.yahoo.com/d/search${o.formatFilters(e)}`)}static formatFilters(e){let t=[`to:${e.recipient}`];return e.sender!==void 0&&t.push(`from:${e.sender}`),e.subject!==void 0&&t.push(`subject:${e.subject}`),e.timestamp!==void 0&&t.push(`after:"${new Date(e.timestamp*1e3).toISOString().split("T")[0]}"`),t.length===0?"":`/keyword=${t.join(" ")}`}};var In=class{constructor(e){this.config=e;}async execute(e){let{fileSystem:t,io:n}=this.config,r=await this.createTemplate(e.empty??false),i=e.file??t.joinPaths(".","template.json5");try{let a=!1;await t.exists(i)&&(a=await n.input?.confirm({message:`Overwrite existing file at \`${i}\`?`,default:!1})??!1),await t.writeTextFile(i,JSON.stringify(r,null,2),{overwrite:a});}catch(a){throw new d("Failed to write template file",{reason:"other",cause:a})}n.output.confirm(`Template created at \`${i}\``);}async createTemplate(e){return {$schema:"https://schema.croct.com/json/v1/template.json",title:"My template",actions:e?[{name:"print",semantic:"info",title:"Empty template",message:"Edit this template to define your actions."}]:[{name:"create-resource",resources:await this.exportResources()}]}}async exportResources(){let{configurationManager:e,templateForm:t}=this.config,n=await e.load(),r=await t.handle({organizationSlug:n.organization,workspaceSlug:n.workspace}),i={audiences:Object.fromEntries(r.audiences.map(a=>[a.slug,{name:a.name,criteria:a.criteria}])),components:Object.fromEntries(r.components.map(a=>[a.slug,{name:a.name,description:a.description,definition:a.definition}])),slots:Object.fromEntries(r.slots.map(a=>[a.slug,{name:a.name,component:a.component?.slug??"",content:a.content}])),experiences:r.experiences.map(a=>{let{experiment:s}=a,p=s!==void 0?{name:s.name??"",goalId:s.goalId,crossDevice:s.crossDevice,traffic:s.traffic??1,variants:s.variants.map(c=>({name:c.name??"",content:c.content,baseline:c.baseline,allocation:c.allocation??1e3/s.variants.length}))}:void 0;return {name:a.name,draft:a.status==="DRAFT",audiences:a.audiences,slots:a.slots,content:a.content,...p!==void 0?{experiment:p}:{}}})};for(let[a,s]of Object.entries(i))typeof s=="object"&&s!==null&&(Array.isArray(s)&&s.length===0||Object.keys(s).length===0)&&delete i[a];return i}};var pi=class{constructor(e){this.config=e;}async handle(e){let{input:t,form:n}=this.config,r={components:[],slots:[],audiences:[],experiences:[]},i=new Set,a=new Set,s=await n.experience.handle({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,confirmation:"Do you want to include experiences?"});if(s.length>0){for(let c of s.flatMap(l=>l.audiences))i.add(c);for(let c of s.flatMap(l=>l.slots))a.add(c);r.experiences=s,s.some(c=>c.experiment!==void 0)&&(await t.confirm({message:"Include experiments?",default:false})||(r.experiences=r.experiences.map(c=>{let{experiment:l,...m}=c;return m})));}r.slots=await n.slot.handle({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,selected:[...a],selectionConfirmation:{message:a.size>0?"Do you want to include other slots?":"Do you want to include slots?",default:false}});let p=new Set(r.slots.map(c=>c.component?.slug??""));return r.components=await n.component.handle({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,includeDependencies:true,selected:[...p],selectionConfirmation:{message:p.size>0?"Do you want to include other components?":"Do you want to include components?",default:false}}),r.audiences=await n.audience.handle({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,selected:[...i],selectionConfirmation:{message:i.size>0?"Do you want to include other audiences?":"Do you want to include audiences?",default:false}}),r}};var ci=class{constructor(e){this.config=e;}async handle(e){let{output:t,input:n,workspaceApi:r}=this.config,i=t.notify("Loading experiences"),a=await r.getExperiences({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});i.stop();let{confirmation:s}=e;if(a.length===0||s!==void 0&&!await n.confirm({message:s}))return [];let p=await n.selectMultiple({message:"Select experiences",options:a.map(l=>({value:l,label:l.name}))});i=t.notify("Loading details");let c=await Promise.all(p.flatMap(async({id:l})=>{let m=await r.getExperience({experienceId:l,organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return m===null?[]:[m]}));return i.stop(),c.flat()}};var li=class{constructor(e){this.config=e;}async handle(e){let{output:t,input:n}=this.config,r=t.notify("Loading audiences"),i=await this.getAudiences(e,e.allowed);r.stop();let a=e.preselected??[];if(a.length>0)return i.filter(({slug:p})=>a.includes(p));let s=e.selected??[];return i.length===0||s.length>0&&i.every(({slug:p})=>s.includes(p))?i.filter(({slug:p})=>s.includes(p)):e.selectionConfirmation!==void 0&&!await n.confirm(e.selectionConfirmation)?i.filter(({slug:c})=>s.includes(c)):n.selectMultiple({message:"Select audiences",options:i.map(p=>{let c=s.includes(p.slug);return {value:p,label:p.name,disabled:c,selected:c}})})}async getAudiences(e,t){let{workspaceApi:n}=this.config,r=await n.getAudiences({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return t===void 0?r:r.filter(({slug:i})=>t.includes(i))}};var I=class o extends d{constructor(e,{tracing:t,...n}={}){super(e,n),this.tracing=t??[],Object.setPrototypeOf(this,o.prototype);}static fromCause(e,t={}){let{message:n,...r}=t;if(!(e instanceof Error))return new o(n??d.formatMessage(e),{...r,cause:e});let i=new o(n??e.message,{cause:e,...e instanceof d?e.help:{},...r,tracing:[...r.tracing??[],...e instanceof o?e.tracing:[]]});return i.stack=e.stack,i}};var zt=class{constructor(e){this.variables={};this.input=e.input,this.output=e.output,this.baseUrl=e.baseUrl;}getVariables(){return structuredClone(this.variables)}set(e,t){this.variables[e]=t;}};var ui=class{constructor(e){this.config=e;}async getOptions(e){let{templateProvider:t}=this.config;return (await t.get(await this.resolveUrl(e))).value.options??{}}async execute(e){let{action:t,io:n}=this.config,{template:r,options:i}=e,a=await this.resolveUrl(r);return t.execute({template:a.toString(),options:i},new zt({input:n.input,output:n.output,baseUrl:a}))}async resolveUrl(e){let{fileSystem:t}=this.config,n=e;if(URL.canParse(e)){let r=new URL(e);if(r.protocol!=="file:")return r;n=t.normalizeSeparators(r.pathname);}try{return new URL(`file://${await t.getRealPath(n)}`)}catch(r){throw new I(`Template file not found at \`${n}\`.`,{reason:"invalid_input",cause:r,suggestions:["Check the file path and try again."]})}}};function _t(o,e){if(URL.canParse(o))return new URL(o);let t=new URL(e.href.replace(/^(.*:)(?!\/)/,"$1/"));return new URL(o,t)}var mi=class{constructor(e){this.config=e;}async execute(e,t){let{fileSystem:n}=this.config,{input:r}=t,i=_t(e.source,t.baseUrl);if(i.protocol==="file:"&&t.baseUrl.protocol!=="file:")throw new I("File URL is not allowed from remote sources for security reasons.",{reason:"precondition",details:[`Source URL: ${i}`]});let a=n.normalizeSeparators(e.destination),{output:s}=t,p=s?.notify("Downloading sources");try{await this.download(i,a,e.filter!==void 0?new minimatch.Minimatch(e.filter):void 0,r);}finally{p?.stop();}e.result?.destination!==void 0&&t.set(e.result.destination,a);}async download(e,t,n,r){let{provider:i,fileSystem:a,codemod:s}=this.config,{value:p}=await i.get(e),c=[];for await(let l of p){let m=a.normalizeSeparators(l.name);if(!(a.isAbsolutePath(m)||!a.isSubPath(t,m))&&!(n!==void 0&&!n.match(m))){if(l.name=a.joinPaths(t,m),l.type==="link"||l.type==="symlink"){let f=a.normalizeSeparators(l.target);if(a.isAbsolutePath(f)||!a.isSubPath(t,f))continue;l.target=f;}c.push(l);}}if(c.length!==0){if(await a.exists(t)){if(c.length===1&&c[0].type==="file"){if(await a.exists(c[0].name)&&await r?.confirm({message:`File ${c[0].name} already exists. Do you want to overwrite it?`,default:false})!==true)throw new I("Destination file already exists.",{reason:"precondition",details:[`File: ${c[0].name}`],suggestions:["Delete the file"]})}else if(!await a.isDirectory(t)||!await a.isEmptyDirectory(t)){if(await r?.confirm({message:`Directory ${t} is not empty. Do you want to clear it?`,default:false})!==true)throw new I("Destination directory is not empty.",{reason:"precondition",details:[`Directory: ${t}`],suggestions:["Clear the directory"]});await a.delete(t,{recursive:true});}}await a.createDirectory(t,{recursive:true});for(let l of c)await a.create(l);for(let l of c)l.type==="file"&&await s.apply(await a.getRealPath(l.name));}}};var di=class{constructor({packageManager:e}){this.packageManager=e;}async execute(e,t){let{output:n}=t,r=n?.notify("Installing dependencies");try{await this.packageManager.addDependencies(e.dependencies,e.development===!0);}catch(i){throw I.fromCause(i)}finally{r?.stop();}}};var gi=class{constructor({projectDirectory:e,fileSystem:t,matcherProvider:n}){this.projectDirectory=e,this.fileSystem=t,this.matcherProvider=n;}async execute(e,t){let{output:n}=t,r=n?.notify("Locating files");try{await this.findMatches(e,t);}finally{r?.stop();}}async findMatches(e,t){let n=await this.findMatch(e.path,e);e.result!==void 0&&t.set(e.result,n);}async findMatch(e,t){let n=await this.matcherProvider.get(e),r=[];for await(let i of this.fileSystem.list(this.projectDirectory.get(),t.depth))if(await n.test(i.name)){if(t.matcher===void 0)r.push(i.name);else if(i.type==="file"){let a=await new Response(i.content).text();this.matches(a,t.matcher)&&r.push(i.name);}if(t.limit!==void 0&&r.length>=t.limit)break}return r}matches(e,t){if("pattern"in t)return new RegExp(t.pattern,t.caseSensitive===true?"i":void 0).test(e);switch(t.type){case "and":return t.matchers.every(n=>this.matches(e,n));case "or":return t.matchers.some(n=>this.matches(e,n))}}};var fi=class{constructor({fileSystem:e}){this.fileSystem=e;}async execute(e,t){let{output:n}=t,r=n.notify("Replacing file content");try{await this.replaceFiles(e);}finally{r.stop();}}async replaceFiles(e){for(let{path:t,replacements:n}of e.files)if(await this.fileSystem.exists(t))try{await this.fileSystem.writeTextFile(t,this.replaceContent(await this.fileSystem.readTextFile(t),n),{overwrite:!0});}catch(r){throw I.fromCause(r)}}replaceContent(e,t){let n=e;for(let{pattern:r,caseSensitive:i,value:a}of t){let s=i===true?"gi":"g";n=n.replaceAll(new RegExp(r,s),`${a}`);}return n}};var yi=class{constructor({installer:e}){this.installer=e;}async execute(e,t){let{output:n}=t,r=n?.notify("Installing slots");try{await this.installer(e.slots,e.example===!0);}catch(i){throw I.fromCause(i)}finally{r?.stop();}}};var hi=class{constructor({installer:e}){this.installer=e;}async execute(e,t){let{output:n}=t,r=n?.notify("Installing components");try{await this.installer(e.components);}catch(i){throw I.fromCause(i)}finally{r?.stop();}}};var Si=class{constructor(e){this.runner=e;}async execute(e,t){try{await this.run(e.action,t);}catch(n){if(e.else===void 0)throw e.help===void 0?n:I.fromCause(n,{...e.help,reason:"precondition"});await this.run(e.else,t);}finally{e.finally!==void 0&&await this.run(e.finally,t);}}run(e,t){return this.runner.execute({actions:e},t)}};var U=class o extends d{constructor(e,t={}){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var it=class{constructor(e){this.provider=e;}get action(){return Promise.resolve(this.provider.get()).catch(e=>{throw e instanceof U?new I(e.message,e.help):e})}async execute(e,t){return (await this.action).execute(e,t)}};var bi=class{constructor(e){this.manager=e;}isInitialized(){return this.manager.isInitialized()}load(){return this.configuration===void 0&&(this.configuration=this.manager.load()),this.configuration}update(e){return this.configuration=this.manager.update(e),this.configuration}};var Ii;(r=>{function o(i){let a=new Set(Object.values(i.slots??{}).map(m=>m.component)??[]),s=new Set(i.experiences?.flatMap(m=>m.slots)??[]),p=new Set(i.experiences?.flatMap(m=>m.audiences)??[]),c=(i.experiences??[]).map(m=>({name:m.name,maximumAudiencesPerExperience:m.audiences.length,crossDevice:m.experiment?.crossDevice===true,...e(m)})),l=new Set;for(let m of Object.values(i.slots??{}))for(let f of Object.keys(m.content))l.add(f);for(let m of c){for(let f of m.locales)l.add(f);for(let f of m.audiences)p.add(f);for(let f of m.slots)s.add(f);}return {components:a,slots:s,audiences:p,locales:l,experiences:c}}r.analyze=o;function e(i){let a=t(i.content);for(let s of i.experiment?.variants??[]){let p=t(s.content);p.audiences.forEach(c=>a.audiences.add(c)),p.slots.forEach(c=>a.slots.add(c));}return {...a}}function t(i){let a=new Set,s=new Set,p=0;for(let[m,f]of Object.entries(i.default)){a.add(m);for(let[b,A]of Object.entries(f))s.add(b),p=Math.max(p,n(A));}let c=new Set,l=0;for(let m of i.segmented){for(let f of m.audiences)c.add(f);l=Math.max(l,m.audiences.length);for(let[f,b]of Object.entries(m.content)){a.add(f);for(let[A,w]of Object.entries(b))s.add(A),p=Math.max(p,n(w));}}return {slots:a,audiences:c,locales:s,audiencesPerExperience:l,dynamicContentPerContent:p}}function n(i){switch(i.type){case "boolean":case "text":case "number":return i.value.type==="dynamic"?1:0;case "structure":return Object.values(i.attributes).map(n).reduce((a,s)=>a+s,0);case "list":return i.items.map(n).reduce((a,s)=>a+s,0)}}})(Ii||(Ii={}));var xi=class{constructor(e){this.refactoring=e;}refactor(e){return {components:Object.fromEntries(Object.entries(e.components??{}).map(([t,n])=>[this.refactoring.componentMapping[t]??t,n])),slots:Object.fromEntries(Object.entries(e.slots??{}).map(([t,n])=>[this.refactoring.slotMapping[t]??t,this.refactorSlotContent(n)])),audiences:Object.fromEntries(Object.entries(e.audiences??{}).map(([t,n])=>[this.refactoring.audienceMapping[t]??t,n])),experiences:e.experiences?.map(t=>this.refactorExperience(t))??[]}}refactorSlotContent(e){return {...e,component:this.refactoring.componentMapping[e.component]??e.component,content:this.refactorLocalizedContentMap(e.content)}}refactorExperience(e){return {...e,audiences:e.audiences.map(t=>this.refactoring.audienceMapping[t]??t),slots:e.slots.map(t=>this.refactoring.slotMapping[t]??t),experiment:e.experiment!==void 0?{...e.experiment,crossDevice:(e.experiment.crossDevice??false)&&this.refactoring.isCrossDeviceFeatureEnabled}:void 0,content:this.refactorPersonalizedContent(e.content,e.audiences.slice(0,this.refactoring.maximumAudiencePerExperience))}}refactorPersonalizedContent(e,t){return {default:this.refactorSlotContentMap(e.default),segmented:e.segmented.flatMap(n=>{let r=n.audiences.filter(i=>t.includes(i));return r.length===0?[]:{audiences:r,content:this.refactorSlotContentMap(n.content)}})}}refactorSlotContentMap(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[this.refactoring.slotMapping[t]??t,this.refactorLocalizedContentMap(n)]))}refactorLocalizedContentMap(e){return Object.fromEntries(Object.entries(e).flatMap(([t,n])=>{let r=this.refactoring.localeMapping[t];return r===null||r!==void 0&&e[r]!==void 0?[]:[[r??t,this.refactorContent(n,{dynamicAttributesPerContent:this.refactoring.dynamicAttributesPerContent})]]}))}refactorContent(e,t){switch(e.type){case "boolean":case "text":case "number":return e.value.type==="dynamic"&&t.dynamicAttributesPerContent>0&&t.dynamicAttributesPerContent--,e.value.type==="static"||t.dynamicAttributesPerContent>0?e:{...e,value:{type:"static",value:e.value.default}};case "structure":return {...e,attributes:Object.fromEntries(Object.entries(e.attributes).map(([n,r])=>[n,this.refactorContent(r,t)]))};case "list":return {...e,items:e.items.map(n=>this.refactorContent(n,t))}}}};var vi=class o{constructor(e){this.config=e;}async execute(e,t){let{output:n}=t,r=n?.notify("Analyzing resources"),i=Ii.analyze(e.resources);this.checkMissingResources({...i,locales:new Set},e.resources);let{configurationManager:a,api:{workspace:s}}=this.config,p=await a.load(),c=await this.getProjectInfo(p),l=await this.createPlan(e.resources,i,c);r?.update("Creating resources");let m=await s.createResources({organizationSlug:p.organization,workspaceSlug:p.workspace,...l.resources});if(r?.stop(),n!==void 0){let f=o.getWarnings(i,c.workspace);if(f.length>0)for(let b of f)n.warn(`${b}`);}e.result!==void 0&&o.setVariables(e.result,l,m,t);}async createPlan(e,t,n){let{mappingForm:r,matcher:i}=this.config,a=await i.match({resources:e,workspaceSlug:n.configuration.workspace,organizationSlug:n.configuration.organization}),s=Object.entries(a.audiences).filter(w=>!("id"in w[1])),p=Object.entries(a.components).filter(w=>!("id"in w[1])),c=Object.entries(a.slots).filter(w=>!("id"in w[1])),l=a.experiences.filter(w=>!("id"in w)),m=l.flatMap(w=>w.experiment===void 0?[]:[w.experiment]);await this.checkRequiredQuota(n,{components:p.length,slots:c.length,audiences:s.length,experiences:l.length,experiments:m.length});let f=await r.handle({organizationSlug:n.configuration.organization,workspaceSlug:n.configuration.workspace,resources:{audiences:s.map(([w])=>w),components:p.map(([w])=>w),slots:c.map(([w])=>w)}}),b={},{workspace:A}=n;for(let w of t.locales)A.locales.includes(w)||(b[w]=A.defaultLocale);return {matches:a,mapping:f,resources:new xi({componentMapping:f.components,audienceMapping:f.audiences,slotMapping:f.slots,dynamicAttributesPerContent:A.quotas.dynamicAttributesPerContent,maximumAudiencePerExperience:A.quotas.audiencesPerExperience,isCrossDeviceFeatureEnabled:A.features.crossDevice,localeMapping:b}).refactor({components:Object.fromEntries(p),slots:Object.fromEntries(c),audiences:Object.fromEntries(s),experiences:l})}}async getProjectInfo(e){let{api:t}=this.config,[n,r]=await Promise.all([t.organization.getWorkspace({organizationSlug:e.organization,workspaceSlug:e.workspace}),t.workspace.getFeatures({organizationSlug:e.organization,workspaceSlug:e.workspace})]);if(n==null||r==null)throw new d("Workspace not found",{title:"Invalid configuration",reason:"invalid_configuration",details:["The workspace defined in the configuration does not exist"],suggestions:["Check the configuration file"]});return {configuration:e,workspace:{...n,...r}}}async checkRequiredQuota(e,t){let{api:{user:n}}=this.config;for(let[r,i]of Object.entries(t)){let a=o.getRemainingQuota(e.workspace,r);if(a<i){let s=await n.getUser().catch(()=>({email:void 0})),p=new URL("https://croct.com/contact/support");throw p.searchParams.set("subject","limit-increase"),p.searchParams.set("organization",e.configuration.organization),p.searchParams.set("message",`I need more quota for ${r}`),s.email!==void 0&&p.searchParams.set("email",s.email),new d(`Not enough ${r} quota available in your workspace.`,{title:"Insufficient quota",reason:"precondition",links:[{label:"Request more quota",url:p.toString()}],details:[`Available: ${a}`,`Required: ${i}`],suggestions:[`Free up quota by removing unused ${r}`,"Request additional quota from support"]})}}}checkMissingResources(e,t){let n=this.findMissingResources(e,t);for(let[r,i]of Object.entries(n))if(i.size>0)throw new d(`Some ${r} referenced in the template are missing`,{title:"Invalid template",reason:"invalid_input",details:[`Missing ${r}: ${Array.from(i).join(", ")}`],suggestions:["Report this issue to the template author"]})}findMissingResources(e,t){let n=new Set(e.components),r=new Set(e.slots),i=new Set(e.audiences),a=new Set(e.locales);for(let s of Object.keys(t.components??{}))n.delete(s);for(let s of Object.keys(t.slots??{}))r.delete(s);for(let s of Object.keys(t.audiences??{}))i.delete(s);return {components:n,slots:r,audiences:i,locales:a}}static getRemainingQuota(e,t){let n=t.charAt(0).toUpperCase()+t.slice(1);return e.quotas[`remaining${n}`]}static getWarnings(e,t){let n=[];return Math.max(...e.experiences.map(s=>s.dynamicContentPerContent))>t.quotas.dynamicAttributesPerContent&&n.push("Some dynamic values have been removed from the content to fit the workspace quota"),Math.max(...e.experiences.map(s=>s.audiencesPerExperience))>t.quotas.audiencesPerExperience&&n.push("Some audiences have been removed from the experiences to fit the workspace quota"),Array.from(e.locales).filter(s=>!t.locales.includes(s)).length>0&&n.push("Content in unsupported locales have been mapped to default or removed"),!t.features.crossDevice&&e.experiences.some(s=>s.crossDevice)&&n.push("Cross-device experiments have been disabled "),n}static setVariables(e,t,n,r){if(e.audiences!==void 0)for(let[i]of Object.entries(t.matches.audiences??{}))e.audiences[i]!==void 0&&r.set(e.audiences[i],t.mapping.audiences[i]??i);if(e.components!==void 0)for(let[i]of Object.entries(t.matches.components??{})){let a=e.components[i];if(a!==void 0){let s=t.mapping.components[i]??i,p=t.matches.components[i]??{};a.id!==void 0&&r.set(a.id,s),a.version!==void 0&&r.set(a.version,"version"in p?p.version.major:1);}}if(e.slots!==void 0)for(let[i]of Object.entries(t.matches.slots??{})){let a=e.slots[i];if(a!==void 0){let s=t.mapping.slots[i]??i,p=t.matches.slots[i]??{};a.id!==void 0&&r.set(a.id,s),a.version!==void 0&&r.set(a.version,"version"in p?p.version.major:1);}}if(e.experiences!==void 0){let{experiences:i}=t.matches,a=0;for(let[s,p]of i.entries()){e.experiences[s]!==void 0&&r.set(e.experiences[s],"id"in p?p.id:n.experiences[a].experienceId);let c=p.experiment!==void 0&&"id"in p.experiment?p.experiment.id:n.experiences[a].experimentId;c!==void 0&&e.experiments?.[s]!==void 0&&r.set(e.experiments[s],c),"id"in p||a++;}}}};var Lt=class o{constructor(e){this.config=e;}static prompt(e){return new o(e).handle()}handle(){let{input:e,unavailableSlugs:t=[],default:n}=this.config;return e.prompt({message:this.config.label,default:n,validate:r=>/^[a-z]+(-?[a-z0-9]+)*$/i.test(r)?t.includes(r)?"The entered slug is already in use.":true:"The slug must start with a letter and contain only letters, numbers, and hyphens."})}};var wi=class{constructor(e){this.config=e;}async handle(e){let{input:t,workspaceApi:n}=this.config,{resources:r,...i}=e,a=r.slots??[],s=r.components??[],p=r.audiences??[],[c,l,m]=await Promise.all([a.length>0?n.getSlots(i):new Array,s.length>0?n.getComponents(i):new Array,p.length>0?n.getAudiences(i):new Array]),f=s.filter(j=>l.some(T=>T.slug===j)),b={};if(f.length>0){let j=l.map(T=>T.slug);for(let T of f){let q=await Lt.prompt({input:t,default:T,unavailableSlugs:j,label:`Component \`${T}\` already exists, enter a new component ID:`});j.push(q),b[T]=q;}}let A=a.filter(j=>c.some(T=>T.slug===j)),w={};if(A.length>0){let j=c.map(T=>T.slug);for(let T of A){let q=await Lt.prompt({input:t,default:T,unavailableSlugs:j,label:`Slot \`${T}\` already exists, enter a new slot ID:`});j.push(q),w[T]=q;}}let y=p.filter(j=>m.some(T=>T.slug===j)),M={};if(y.length>0){let j=m.map(T=>T.slug);for(let T of y){let q=await Lt.prompt({input:t,default:T,unavailableSlugs:j,label:`Audience \`${T}\` already exists, enter a new audience ID:`});j.push(q),M[T]=q;}}return {components:b,slots:w,audiences:M}}};var Ci=class o{constructor(e){this.config=e;}async match(e){let{resources:t,...n}=e,[r,i,a,s]=await Promise.all([this.mapComponents(t.components??{},n),this.mapSlots(t.slots??{},n),this.mapAudiences(t.audiences??{},n),this.mapExperiences(t.experiences??[],n)]);return {components:r,slots:i,audiences:a,experiences:s}}async mapAudiences(e,t){let{workspaceApi:n}=this.config,r=await Promise.all(Object.keys(e).map(async a=>[a,await n.getAudience({...t,audienceSlug:a})])),i={};for(let[a,s]of r)i[a]=s===null||!o.isSimilarAudience(e[a],s)?e[a]:s;return i}async mapComponents(e,t){let{workspaceApi:n}=this.config,r=await Promise.all(Object.keys(e).map(async a=>[a,await n.getComponent({...t,componentSlug:a})])),i={};for(let[a,s]of r)i[a]=s===null||!o.isSimilarComponent(e[a],s)?e[a]:s;return i}async mapSlots(e,t){let{workspaceApi:n}=this.config,r=await Promise.all(Object.keys(e).map(async a=>[a,await n.getSlot({...t,slotSlug:a})])),i={};for(let[a,s]of r)i[a]=s===null||!o.isSimilarSlot(e[a],s)?e[a]:s;return i}async mapExperiences(e,t){let{workspaceApi:n}=this.config,i=(await n.getExperiences({...t,status:["ACTIVE","PAUSED","DRAFT"]})).map(a=>{let s=null;function p(){return s===null&&(s=n.getExperience({...t,experienceId:a.id})),s}return {...a,details:{get content(){return p().then(c=>c?.content??null)},get experiment(){return p().then(c=>c?.experiment??null)}}}});return Promise.all(e.map(async a=>{for(let s of i)if(await this.matchesExperience(a,s)){let{details:p,...c}=s;return c}return a}))}async matchesExperience(e,t){if((e.draft===true?"DRAFT":"ACTIVE")!==t.status||!fastEquals.deepEqual(e.audiences,t.audiences)||!fastEquals.deepEqual(e.slots,t.slots)||e.experiment!==void 0&&t.experiment===void 0)return false;let[r,i=null]=await Promise.all([t.details.content,t.details.experiment]);return e.experiment!==void 0&&(i===null||e.experiment.goalId!==i.goalId||e.experiment.traffic!==i.traffic||e.experiment.crossDevice!==i.crossDevice||!o.isSimilarExperimentContent(e.experiment.variants,i.variants))?false:o.isSimilarPersonalizedContent(e.content,r??{default:{},segmented:[]})}static isSimilarAudience(e,t){return e.criteria===t.criteria}static isSimilarComponent(e,t){return fastEquals.deepEqual(e.definition,t.definition)}static isSimilarSlot(e,t){return e.component===t.component?.slug&&Object.values(e.content).some(n=>Object.values(t.content).some(r=>fastEquals.deepEqual(n,r)))}static isSimilarExperimentContent(e,t){return e.length!==t.length?false:e.some((n,r)=>fastEquals.deepEqual(n,t[r]))}static isSimilarPersonalizedContent(e,t){if(o.isSimilarSlotContent(e.default,t.default))return true;for(let n of e.segmented)for(let r of t.segmented)if(fastEquals.deepEqual(n.audiences,r.audiences)&&o.isSimilarSlotContent(n.content,r.content))return true;return false}static isSimilarSlotContent(e,t){for(let[n,r]of Object.entries(e)){let i=t[n];if(i!==void 0){for(let a of Object.values(r))if(Object.values(i).some(s=>fastEquals.deepEqual(a,s)))return true}}return false}};var W=class o extends U{constructor(e,{url:t,...n}){super(e,n),Object.setPrototypeOf(this,o.prototype),this.url=t;}},Fe=class o extends W{constructor(e,t){super(e,{...t,reason:t.reason??"not_found"}),Object.setPrototypeOf(this,o.prototype);}};var Pi=class o{async get(e){if(!["http:","https:"].includes(e.protocol))throw new W("Unsupported protocol.",{reason:"not_supported",url:e});let t=await fetch(e);if(t.status===404)throw new Fe("Resource not found.",{url:e});if(!o.isSuccessful(t))throw new W(t.statusText,{url:e});return {url:e,value:t}}static isSuccessful(e){return e.ok&&e.body!==null}};var ki=class{constructor({packageManager:e}){this.packageManager=e;}async execute(e,t){let{output:n}=t,r=n?.notify("Checking dependencies"),i;try{i=await Promise.all(e.dependencies.map(s=>this.checkRequirement(s)));}finally{r?.stop();}let a=[];if(e.result!==void 0)for(let s of i){if(e.result[s.dependency]!==void 0){t.set(e.result[s.dependency],s.issue===void 0);continue}s.issue!==void 0&&a.push(s);}if(a.length>0){let{message:s,...p}=e.help??{};throw new I(s??"Missing required dependencies.",{...p,details:a.map(({dependency:c,issue:l})=>`\`${c}\`: ${l}`)})}}async checkRequirement(e){let{name:t,version:n,optional:r=false}=e;if(r&&(n===void 0||!await this.packageManager.hasDirectDependency(t))||await this.packageManager.hasDirectDependency(t,n))return {dependency:t};let i=await this.packageManager.getDependency(t);return {dependency:t,issue:i===null?"not installed":`version \`${n}\` is required, found \`${i.version??"unknown"}\``}}};var Ft=class{constructor({dataProvider:e,registryProvider:t,baseUrl:n}){this.dataProvider=e,this.registryProvider=t,this.baseUrl=n;}async get(e){return this.dataProvider.get(await this.resolveUrl(e))}async resolveUrl(e){for(let{pattern:t,destination:n}of await this.loadMappings(e)){let r=e.href.match(typeof t=="string"?new RegExp(t):t);if(r!==null)return n instanceof URL?n:new URL(n.replace(/\$([0-9]+)/g,(i,a)=>r[Number.parseInt(a,10)]),this.baseUrl)}return e}async loadMappings(e){let t=await this.registryProvider.get(e);return Array.isArray(t)?t:t.value}};var xn=class xn{constructor(...e){this.providers=e;}async get(e){for(let t of this.providers)try{return await t.get(e)}catch(n){if(!xn.isExpectedError(n))throw n}throw new Fe("Resource not found.",{url:e})}static isExpectedError(e){return e instanceof W&&xn.EXPECTED_ERROR_REASONS.includes(e.reason)}};xn.EXPECTED_ERROR_REASONS=["not_supported","not_found"];var ot=xn;var Ai=class o{constructor(e){this.fileSystem=e;}supports(e){return Promise.resolve(o.supportsUrl(e))}get(e){if(!o.supportsUrl(e))throw new W(`Unsupported protocol "${e.protocol}".`,{reason:"not_supported",url:e});return Promise.resolve({url:e,value:this.fileSystem.list(this.fileSystem.normalizeSeparators(e.pathname))})}static supportsUrl(e){return e.protocol==="file:"}};var re=class re{constructor(e){this.provider=e;}async get(e){let t=this.parseUrl(e);if(t===null)throw new W("Unsupported GitHub URL.",{reason:"not_supported",url:e});let n=this.resolveFile(t),{value:r}=await this.provider.get(n.url);return {url:t.canonicalUrl,value:n.url.hostname===re.RAW_HOST?this.extractFile(r,n):this.extractTarball(r,n)}}async*extractTarball(e,t){let n=Iu__default.default.extract();stream.Readable.fromWeb(e.body).pipe(xu__default.default()).pipe(n);let r=re.removeTrailSlash(t.path??"");for await(let i of n){let{header:a}=i;i.resume();let s=re.removeTrailSlash(a.name.split("/").slice(1).join("/"));if(s===""||!s.startsWith(r)||i.header.type==="directory"&&s===r)continue;let p=s;switch(r.length>0&&s.length>r.length&&(p=s.slice(r.length+1)),a.type){case "file":yield {type:"file",name:p,content:i};break;case "directory":yield {type:"directory",name:p};break;case "link":yield {type:"link",name:p,target:a.linkname};break;case "symlink":yield {type:"symlink",name:p,target:a.linkname};break}if(p===r)break}}async*extractFile(e,t){yield {type:"file",name:t.url.pathname.split("/").pop(),content:stream.Readable.fromWeb(e.body)};}resolveFile(e){let{username:t,repository:n,path:r}=e,i=e.ref??"HEAD";return {...e,url:new URL(r!==null&&/\..+$/.test(r)?`https://${re.RAW_HOST}/${t}/${n}/${i}/${r}`:`https://${re.API_HOST}/repos/${t}/${n}/tarball/${i}`)}}parseUrl(e){if(!re.isUrlSupported(e))return null;let t,n,r=null,i,a=e.pathname.replace(/^\/+/,"").split("/"),s=null;return e.hostname===re.MAIN_HOST?(s=e,[t=null,n=null,,r=null,...i]=a):[t=null,n=null,...i]=a,t===null||n===null?null:(s===null&&(s=new URL(`https://${re.MAIN_HOST}`),s.pathname=`/${t}/${n}/blob/master/${i.join("/")}`),{canonicalUrl:s,username:t,repository:n,ref:r,path:i!==void 0&&i.length>0?i.join("/"):null})}static isUrlSupported(e){return e.protocol==="https:"?e.hostname===re.MAIN_HOST:e.protocol===re.PROTOCOL}static removeTrailSlash(e){return e.replace(/\/$/,"")}};re.PROTOCOL="github:",re.API_HOST="api.github.com",re.RAW_HOST="raw.github.com",re.MAIN_HOST="github.com";var vn=re;var wn=class o{constructor(e){this.provider=e;}async get(e){if(!o.supportsUrl(e))throw new W("Unsupported URL.",{reason:"not_supported",url:e});let{value:t,...n}=await this.provider.get(e);return {...n,value:this.yield(t,e)}}static supportsUrl(e){return e.pathname!=="/"}async*yield(e,t){yield {type:"file",name:t.pathname.split("/").pop(),content:stream.Readable.fromWeb(e.body)};}};var B=class{constructor(e){this.schema=e;}async validate(e){let t=await this.schema.safeParseAsync(e);if(t.success)return {valid:true,data:t.data};let{error:n}=t;return {valid:false,violations:n.issues.map(r=>({path:r.path.reduce((i,a)=>typeof a=="string"?i===""?a:`${i}.${a}`:`${i}[${a}]`,""),message:r.message}))}}};var wu=zod.z.object({name:zod.z.string(),version:zod.z.string().optional(),dependencies:zod.z.record(zod.z.string()).optional(),devDependencies:zod.z.record(zod.z.string()).optional(),bin:zod.z.record(zod.z.string()).optional(),scripts:zod.z.record(zod.z.string()).optional(),packageManager:zod.z.string().optional()}),Cn=class extends B{constructor(){super(wu);}};var Ei=zod.z.string().regex(/^[a-z]+(-?[a-z0-9]+)*$/i,"An identifier must start with a letter and contain only letters, numbers, and hyphens."),Ec=zod.z.string().regex(/^[a-z]{2,3}([-_][a-z]{2,3})?$/i,"Locale must be in the form of en, en_US, or en-US."),Rc=zod.z.string().refine(O.isValid,"Version must be exact (1), range (1 - 2), or set (1 || 2).").refine(o=>{try{return O.parse(o).getCardinality()<=5}catch{return false}},"Version range must not exceed 5 major versions."),Cu=zod.z.strictObject({$schema:zod.z.string().optional(),organization:Ei,workspace:Ei,applications:zod.z.strictObject({development:Ei,production:Ei.optional()}),locales:zod.z.array(Ec),defaultLocale:Ec,slots:zod.z.record(Rc),components:zod.z.record(Rc),paths:zod.z.strictObject({components:zod.z.string(),examples:zod.z.string(),content:zod.z.string().optional()})}).refine(o=>o.locales.includes(o.defaultLocale),{message:"The default locale is not included in the list of locales.",path:["defaultLocale"]}),Ri=class extends B{constructor(){super(Cu);}};var jt=class{constructor({provider:e,validator:t}){this.provider=e,this.validator=t;}async get(e){let{value:t,...n}=await this.provider.get(e),r=await this.validator.validate(t);if(!r.valid){let i=r.violations.map(a=>` \u2022 **${a.path}**: ${a.message}`).join(`
1754
+ `;this.runCommand({name:"powershell",arguments:["-Command",`& {${i}}`]});}}runCommand(e){let{commandExecutor:t,timeout:n}=this.configuration;try{let r=t.runSync(e,{timeout:n});return r.exitCode!==0?null:r.output.trim()}catch{return null}}};var Mr=class{constructor(e){this.detector=e.detector,this.templates=e.templates;}async generate(e){let t=await this.detector.detect(e.recipient);return t===null||this.templates[t]===void 0?null:this.templates[t].generate(e)}};var Nr=class{constructor(...e){this.detectors=e;}async detect(e){for(let t of this.detectors){let n=await t.detect(e);if(n!==null)return n}return null}};var $r=class o{static{this.DEFAULT_DOMAINS={google:["gmail.com","googlemail.com","google.com"],yahoo:[/yahoo\.com(?:\.\w+)?/,"yahoo.co.uk","yahoo.fr","yahoo.it","ymail.com","rocketmail.com"],microsoft:["outlook.com","live.com","hotmail.com","msn.com","passport.com","passport.net"],proton:["proton.me","protonmail.com"],icloud:["icloud.com"]};}constructor(e=o.DEFAULT_DOMAINS){this.domains=e;}detect(e){let t=e.toLowerCase().split("@")[1];for(let[n,r]of Object.entries(this.domains))if(r.some(a=>typeof a=="string"?a===t:a.test(t)))return Promise.resolve(n);return Promise.resolve(null)}};var zr=class o{static{this.DEFAULT_DOMAINS={google:["google.com"],microsoft:["outlook.com"]};}constructor(e=o.DEFAULT_DOMAINS){this.domains=e;}async detect(e){let t=e.toLowerCase().split("@")[1],n=await this.lookup(t);for(let[r,i]of Object.entries(this.domains))for(let a of i)for(let s of n)if(s.endsWith(`.${a}.`))return r;return null}async lookup(e){let t=new URL("https://dns.google.com/resolve");t.searchParams.set("type","MX"),t.searchParams.set("name",e);let n;try{n=await fetch(t).then(r=>{if(!r.ok)throw new Error("Failed to lookup domain");return r.json()});}catch{return []}return n.Answer===void 0?[]:n.Answer.map(r=>r.data)}};var Et=ft(Zt()),_r=class o{generate(e){return new URL(`https://mail.google.com/mail${o.formatFilters(e)}`)}static formatFilters(e){let t=[`to:${e.recipient}`],n=`/u/${e.recipient}`;if(e.sender!==void 0&&t.push(`from:${e.sender}`),e.subject!==void 0&&t.push(`subject:${e.subject}`),e.timestamp!==void 0){let r=Et.TimeZone.of(Intl.DateTimeFormat().resolvedOptions().timeZone),i=Et.Instant.ofEpochSecond(e.timestamp),a=Et.LocalDateTime.ofInstant(i,r).getLocalDate();t.push(`after:${a}`);}return t.push("in:anywhere"),n+=`/#search/${t.map(r=>encodeURIComponent(r)).join("+")}`,n}};var Lr=class{generate(e){return new URL("https://www.icloud.com/mail")}};var Fr=class{generate(e){let t=new URL("https://outlook.live.com/mail");return e.recipient!==void 0&&t.searchParams.append("login_hint",e.recipient),t}};var jr=class o{generate(e){return new URL(`https://mail.proton.me/u/0/all-mail${o.formatFilters(e)}`)}static formatFilters(e){let t=new URLSearchParams;return t.set("to",e.recipient),e.sender!==void 0&&t.set("from",e.sender),e.timestamp!==void 0&&t.set("begin",e.timestamp.toFixed(0)),e.subject!==void 0&&t.set("keyword",e.subject),`#${t.toString()}`}};var Wr=class o{generate(e){return new URL(`https://mail.yahoo.com/d/search${o.formatFilters(e)}`)}static formatFilters(e){let t=[`to:${e.recipient}`];return e.sender!==void 0&&t.push(`from:${e.sender}`),e.subject!==void 0&&t.push(`subject:${e.subject}`),e.timestamp!==void 0&&t.push(`after:"${new Date(e.timestamp*1e3).toISOString().split("T")[0]}"`),t.length===0?"":`/keyword=${t.join(" ")}`}};var cn=class{constructor(e){this.config=e;}async execute(e){let{fileSystem:t,io:n}=this.config,r=await this.createTemplate(e.empty??false),i=e.file??t.joinPaths(".","template.json5");try{let a=!1;await t.exists(i)&&(a=await n.input?.confirm({message:`Overwrite existing file at \`${i}\`?`,default:!1})??!1),await t.writeTextFile(i,JSON.stringify(r,null,2),{overwrite:a});}catch(a){throw new d("Failed to write template file",{reason:"other",cause:a})}n.output.confirm(`Template created at \`${i}\``);}async createTemplate(e){return {$schema:"https://schema.croct.com/json/v1/template.json",title:"My template",actions:e?[{name:"print",semantic:"info",title:"Empty template",message:"Edit this template to define your actions."}]:[{name:"create-resource",resources:await this.exportResources()}]}}async exportResources(){let{configurationManager:e,templateForm:t}=this.config,n=await e.load(),r=await t.handle({organizationSlug:n.organization,workspaceSlug:n.workspace}),i={audiences:Object.fromEntries(r.audiences.map(a=>[a.slug,{name:a.name,criteria:a.criteria}])),components:Object.fromEntries(r.components.map(a=>[a.slug,{name:a.name,description:a.description,definition:a.definition}])),slots:Object.fromEntries(r.slots.map(a=>[a.slug,{name:a.name,component:a.component?.slug??"",content:a.content}])),experiences:r.experiences.map(a=>{let{experiment:s}=a,p=s!==void 0?{name:s.name??"",goalId:s.goalId,crossDevice:s.crossDevice,traffic:s.traffic??1,variants:s.variants.map(c=>({name:c.name??"",content:c.content,baseline:c.baseline,allocation:c.allocation??1e3/s.variants.length}))}:void 0;return {name:a.name,draft:a.status==="DRAFT",audiences:a.audiences,slots:a.slots,content:a.content,...p!==void 0?{experiment:p}:{}}})};for(let[a,s]of Object.entries(i))typeof s=="object"&&s!==null&&(Array.isArray(s)&&s.length===0||Object.keys(s).length===0)&&delete i[a];return i}};var Vr=class{constructor(e){this.config=e;}async handle(e){let{input:t,form:n}=this.config,r={components:[],slots:[],audiences:[],experiences:[]},i=new Set,a=new Set,s=await n.experience.handle({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,confirmation:"Do you want to include experiences?"});if(s.length>0){for(let c of s.flatMap(l=>l.audiences))i.add(c);for(let c of s.flatMap(l=>l.slots))a.add(c);r.experiences=s,s.some(c=>c.experiment!==void 0)&&(await t.confirm({message:"Include experiments?",default:false})||(r.experiences=r.experiences.map(c=>{let{experiment:l,...m}=c;return m})));}r.slots=await n.slot.handle({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,selected:[...a],selectionConfirmation:{message:a.size>0?"Do you want to include other slots?":"Do you want to include slots?",default:false}});let p=new Set(r.slots.map(c=>c.component?.slug??""));return r.components=await n.component.handle({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,includeDependencies:true,selected:[...p],selectionConfirmation:{message:p.size>0?"Do you want to include other components?":"Do you want to include components?",default:false}}),r.audiences=await n.audience.handle({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,selected:[...i],selectionConfirmation:{message:i.size>0?"Do you want to include other audiences?":"Do you want to include audiences?",default:false}}),r}};var Ur=class{constructor(e){this.config=e;}async handle(e){let{output:t,input:n,workspaceApi:r}=this.config,i=t.notify("Loading experiences"),a=await r.getExperiences({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});i.stop();let{confirmation:s}=e;if(a.length===0||s!==void 0&&!await n.confirm({message:s}))return [];let p=await n.selectMultiple({message:"Select experiences",options:a.map(l=>({value:l,label:l.name}))});i=t.notify("Loading details");let c=await Promise.all(p.flatMap(async({id:l})=>{let m=await r.getExperience({experienceId:l,organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return m===null?[]:[m]}));return i.stop(),c.flat()}};var qr=class{constructor(e){this.config=e;}async handle(e){let{output:t,input:n}=this.config,r=t.notify("Loading audiences"),i=await this.getAudiences(e,e.allowed);r.stop();let a=e.preselected??[];if(a.length>0)return i.filter(({slug:p})=>a.includes(p));let s=e.selected??[];return i.length===0||s.length>0&&i.every(({slug:p})=>s.includes(p))?i.filter(({slug:p})=>s.includes(p)):e.selectionConfirmation!==void 0&&!await n.confirm(e.selectionConfirmation)?i.filter(({slug:c})=>s.includes(c)):n.selectMultiple({message:"Select audiences",options:i.map(p=>{let c=s.includes(p.slug);return {value:p,label:p.name,disabled:c,selected:c}})})}async getAudiences(e,t){let{workspaceApi:n}=this.config,r=await n.getAudiences({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug});return t===void 0?r:r.filter(({slug:i})=>t.includes(i))}};var I=class o extends d{constructor(e,{tracing:t,...n}={}){super(e,n),this.tracing=t??[],Object.setPrototypeOf(this,o.prototype);}static fromCause(e,t={}){let{message:n,...r}=t;if(!(e instanceof Error))return new o(n??d.formatMessage(e),{...r,cause:e});let i=new o(n??e.message,{cause:e,...e instanceof d?e.help:{},...r,tracing:[...r.tracing??[],...e instanceof o?e.tracing:[]]});return i.stack=e.stack,i}};var Rt=class{constructor(e){this.variables={};this.input=e.input,this.output=e.output,this.baseUrl=e.baseUrl;}getVariables(){return structuredClone(this.variables)}set(e,t){this.variables[e]=t;}};var Hr=class{constructor(e){this.config=e;}async getOptions(e){let{templateProvider:t}=this.config;return (await t.get(await this.resolveUrl(e))).value.options??{}}async execute(e){let{action:t,io:n}=this.config,{template:r,options:i}=e,a=await this.resolveUrl(r);return t.execute({template:a.toString(),options:i},new Rt({input:n.input,output:n.output,baseUrl:a}))}async resolveUrl(e){let{fileSystem:t}=this.config,n=e;if(URL.canParse(e)){let r=new URL(e);if(r.protocol!=="file:")return r;n=t.normalizeSeparators(r.pathname);}try{return new URL(`file://${await t.getRealPath(n)}`)}catch(r){throw new I(`Template file not found at \`${n}\`.`,{reason:"invalid_input",cause:r,suggestions:["Check the file path and try again."]})}}};function Tt(o,e){if(URL.canParse(o))return new URL(o);let t=new URL(e.href.replace(/^(.*:)(?!\/)/,"$1/"));return new URL(o,t)}var Gr=class{constructor(e){this.config=e;}async execute(e,t){let{fileSystem:n}=this.config,{input:r}=t,i=Tt(e.source,t.baseUrl);if(i.protocol==="file:"&&t.baseUrl.protocol!=="file:")throw new I("File URL is not allowed from remote sources for security reasons.",{reason:"precondition",details:[`Source URL: ${i}`]});let a=n.normalizeSeparators(e.destination),{output:s}=t,p=s?.notify("Downloading sources");try{await this.download(i,a,e.filter!==void 0?new Minimatch(e.filter):void 0,r);}finally{p?.stop();}e.result?.destination!==void 0&&t.set(e.result.destination,a);}async download(e,t,n,r){let{provider:i,fileSystem:a,codemod:s}=this.config,{value:p}=await i.get(e),c=[];for await(let l of p){let m=a.normalizeSeparators(l.name);if(!(a.isAbsolutePath(m)||!a.isSubPath(t,m))&&!(n!==void 0&&!n.match(m))){if(l.name=a.joinPaths(t,m),l.type==="link"||l.type==="symlink"){let f=a.normalizeSeparators(l.target);if(a.isAbsolutePath(f)||!a.isSubPath(t,f))continue;l.target=f;}c.push(l);}}if(c.length!==0){if(await a.exists(t)){if(c.length===1&&c[0].type==="file"){if(await a.exists(c[0].name)&&await r?.confirm({message:`File ${c[0].name} already exists. Do you want to overwrite it?`,default:false})!==true)throw new I("Destination file already exists.",{reason:"precondition",details:[`File: ${c[0].name}`],suggestions:["Delete the file"]})}else if(!await a.isDirectory(t)||!await a.isEmptyDirectory(t)){if(await r?.confirm({message:`Directory ${t} is not empty. Do you want to clear it?`,default:false})!==true)throw new I("Destination directory is not empty.",{reason:"precondition",details:[`Directory: ${t}`],suggestions:["Clear the directory"]});await a.delete(t,{recursive:true});}}await a.createDirectory(t,{recursive:true});for(let l of c)await a.create(l);for(let l of c)l.type==="file"&&await s.apply(await a.getRealPath(l.name));}}};var Kr=class{constructor({packageManager:e}){this.packageManager=e;}async execute(e,t){let{output:n}=t,r=n?.notify("Installing dependencies");try{await this.packageManager.addDependencies(e.dependencies,e.development===!0);}catch(i){throw I.fromCause(i)}finally{r?.stop();}}};var Zr=class{constructor({projectDirectory:e,fileSystem:t,matcherProvider:n}){this.projectDirectory=e,this.fileSystem=t,this.matcherProvider=n;}async execute(e,t){let{output:n}=t,r=n?.notify("Locating files");try{await this.findMatches(e,t);}finally{r?.stop();}}async findMatches(e,t){let n=await this.findMatch(e.path,e);e.result!==void 0&&t.set(e.result,n);}async findMatch(e,t){let n=await this.matcherProvider.get(e),r=[];for await(let i of this.fileSystem.list(this.projectDirectory.get(),t.depth))if(await n.test(i.name)){if(t.matcher===void 0)r.push(i.name);else if(i.type==="file"){let a=await new Response(i.content).text();this.matches(a,t.matcher)&&r.push(i.name);}if(t.limit!==void 0&&r.length>=t.limit)break}return r}matches(e,t){if("pattern"in t)return new RegExp(t.pattern,t.caseSensitive===true?"i":void 0).test(e);switch(t.type){case "and":return t.matchers.every(n=>this.matches(e,n));case "or":return t.matchers.some(n=>this.matches(e,n))}}};var Jr=class{constructor({fileSystem:e}){this.fileSystem=e;}async execute(e,t){let{output:n}=t,r=n.notify("Replacing file content");try{await this.replaceFiles(e);}finally{r.stop();}}async replaceFiles(e){for(let{path:t,replacements:n}of e.files)if(await this.fileSystem.exists(t))try{await this.fileSystem.writeTextFile(t,this.replaceContent(await this.fileSystem.readTextFile(t),n),{overwrite:!0});}catch(r){throw I.fromCause(r)}}replaceContent(e,t){let n=e;for(let{pattern:r,caseSensitive:i,value:a}of t){let s=i===true?"gi":"g";n=n.replaceAll(new RegExp(r,s),`${a}`);}return n}};var Qr=class{constructor({installer:e}){this.installer=e;}async execute(e,t){let{output:n}=t,r=n?.notify("Installing slots");try{await this.installer(e.slots,e.example===!0);}catch(i){throw I.fromCause(i)}finally{r?.stop();}}};var Br=class{constructor({installer:e}){this.installer=e;}async execute(e,t){let{output:n}=t,r=n?.notify("Installing components");try{await this.installer(e.components);}catch(i){throw I.fromCause(i)}finally{r?.stop();}}};var Yr=class{constructor(e){this.runner=e;}async execute(e,t){try{await this.run(e.action,t);}catch(n){if(e.else===void 0)throw e.help===void 0?n:I.fromCause(n,{...e.help,reason:"precondition"});await this.run(e.else,t);}finally{e.finally!==void 0&&await this.run(e.finally,t);}}run(e,t){return this.runner.execute({actions:e},t)}};var U=class o extends d{constructor(e,t={}){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var Ye=class{constructor(e){this.provider=e;}get action(){return Promise.resolve(this.provider.get()).catch(e=>{throw e instanceof U?new I(e.message,e.help):e})}async execute(e,t){return (await this.action).execute(e,t)}};var Xr=class{constructor(e){this.manager=e;}isInitialized(){return this.manager.isInitialized()}load(){return this.configuration===void 0&&(this.configuration=this.manager.load()),this.configuration}update(e){return this.configuration=this.manager.update(e),this.configuration}};var qa;(r=>{function o(i){let a=new Set(Object.values(i.slots??{}).map(m=>m.component)??[]),s=new Set(i.experiences?.flatMap(m=>m.slots)??[]),p=new Set(i.experiences?.flatMap(m=>m.audiences)??[]),c=(i.experiences??[]).map(m=>({name:m.name,maximumAudiencesPerExperience:m.audiences.length,crossDevice:m.experiment?.crossDevice===true,...e(m)})),l=new Set;for(let m of Object.values(i.slots??{}))for(let f of Object.keys(m.content))l.add(f);for(let m of c){for(let f of m.locales)l.add(f);for(let f of m.audiences)p.add(f);for(let f of m.slots)s.add(f);}return {components:a,slots:s,audiences:p,locales:l,experiences:c}}r.analyze=o;function e(i){let a=t(i.content);for(let s of i.experiment?.variants??[]){let p=t(s.content);p.audiences.forEach(c=>a.audiences.add(c)),p.slots.forEach(c=>a.slots.add(c));}return {...a}}function t(i){let a=new Set,s=new Set,p=0;for(let[m,f]of Object.entries(i.default)){a.add(m);for(let[b,A]of Object.entries(f))s.add(b),p=Math.max(p,n(A));}let c=new Set,l=0;for(let m of i.segmented){for(let f of m.audiences)c.add(f);l=Math.max(l,m.audiences.length);for(let[f,b]of Object.entries(m.content)){a.add(f);for(let[A,w]of Object.entries(b))s.add(A),p=Math.max(p,n(w));}}return {slots:a,audiences:c,locales:s,audiencesPerExperience:l,dynamicContentPerContent:p}}function n(i){switch(i.type){case "boolean":case "text":case "number":return i.value.type==="dynamic"?1:0;case "structure":return Object.values(i.attributes).map(n).reduce((a,s)=>a+s,0);case "list":return i.items.map(n).reduce((a,s)=>a+s,0)}}})(qa||={});var ei=class{constructor(e){this.refactoring=e;}refactor(e){return {components:Object.fromEntries(Object.entries(e.components??{}).map(([t,n])=>[this.refactoring.componentMapping[t]??t,n])),slots:Object.fromEntries(Object.entries(e.slots??{}).map(([t,n])=>[this.refactoring.slotMapping[t]??t,this.refactorSlotContent(n)])),audiences:Object.fromEntries(Object.entries(e.audiences??{}).map(([t,n])=>[this.refactoring.audienceMapping[t]??t,n])),experiences:e.experiences?.map(t=>this.refactorExperience(t))??[]}}refactorSlotContent(e){return {...e,component:this.refactoring.componentMapping[e.component]??e.component,content:this.refactorLocalizedContentMap(e.content)}}refactorExperience(e){return {...e,audiences:e.audiences.map(t=>this.refactoring.audienceMapping[t]??t),slots:e.slots.map(t=>this.refactoring.slotMapping[t]??t),experiment:e.experiment!==void 0?{...e.experiment,crossDevice:(e.experiment.crossDevice??false)&&this.refactoring.isCrossDeviceFeatureEnabled}:void 0,content:this.refactorPersonalizedContent(e.content,e.audiences.slice(0,this.refactoring.maximumAudiencePerExperience))}}refactorPersonalizedContent(e,t){return {default:this.refactorSlotContentMap(e.default),segmented:e.segmented.flatMap(n=>{let r=n.audiences.filter(i=>t.includes(i));return r.length===0?[]:{audiences:r,content:this.refactorSlotContentMap(n.content)}})}}refactorSlotContentMap(e){return Object.fromEntries(Object.entries(e).map(([t,n])=>[this.refactoring.slotMapping[t]??t,this.refactorLocalizedContentMap(n)]))}refactorLocalizedContentMap(e){return Object.fromEntries(Object.entries(e).flatMap(([t,n])=>{let r=this.refactoring.localeMapping[t];return r===null||r!==void 0&&e[r]!==void 0?[]:[[r??t,this.refactorContent(n,{dynamicAttributesPerContent:this.refactoring.dynamicAttributesPerContent})]]}))}refactorContent(e,t){switch(e.type){case "boolean":case "text":case "number":return e.value.type==="dynamic"&&t.dynamicAttributesPerContent>0&&t.dynamicAttributesPerContent--,e.value.type==="static"||t.dynamicAttributesPerContent>0?e:{...e,value:{type:"static",value:e.value.default}};case "structure":return {...e,attributes:Object.fromEntries(Object.entries(e.attributes).map(([n,r])=>[n,this.refactorContent(r,t)]))};case "list":return {...e,items:e.items.map(n=>this.refactorContent(n,t))}}}};var ti=class o{constructor(e){this.config=e;}async execute(e,t){let{output:n}=t,r=n?.notify("Analyzing resources"),i=qa.analyze(e.resources);this.checkMissingResources({...i,locales:new Set},e.resources);let{configurationManager:a,api:{workspace:s}}=this.config,p=await a.load(),c=await this.getProjectInfo(p),l=await this.createPlan(e.resources,i,c);r?.update("Creating resources");let m=await s.createResources({organizationSlug:p.organization,workspaceSlug:p.workspace,...l.resources});if(r?.stop(),n!==void 0){let f=o.getWarnings(i,c.workspace);if(f.length>0)for(let b of f)n.warn(`${b}`);}e.result!==void 0&&o.setVariables(e.result,l,m,t);}async createPlan(e,t,n){let{mappingForm:r,matcher:i}=this.config,a=await i.match({resources:e,workspaceSlug:n.configuration.workspace,organizationSlug:n.configuration.organization}),s=Object.entries(a.audiences).filter(w=>!("id"in w[1])),p=Object.entries(a.components).filter(w=>!("id"in w[1])),c=Object.entries(a.slots).filter(w=>!("id"in w[1])),l=a.experiences.filter(w=>!("id"in w)),m=l.flatMap(w=>w.experiment===void 0?[]:[w.experiment]);await this.checkRequiredQuota(n,{components:p.length,slots:c.length,audiences:s.length,experiences:l.length,experiments:m.length});let f=await r.handle({organizationSlug:n.configuration.organization,workspaceSlug:n.configuration.workspace,resources:{audiences:s.map(([w])=>w),components:p.map(([w])=>w),slots:c.map(([w])=>w)}}),b={},{workspace:A}=n;for(let w of t.locales)A.locales.includes(w)||(b[w]=A.defaultLocale);return {matches:a,mapping:f,resources:new ei({componentMapping:f.components,audienceMapping:f.audiences,slotMapping:f.slots,dynamicAttributesPerContent:A.quotas.dynamicAttributesPerContent,maximumAudiencePerExperience:A.quotas.audiencesPerExperience,isCrossDeviceFeatureEnabled:A.features.crossDevice,localeMapping:b}).refactor({components:Object.fromEntries(p),slots:Object.fromEntries(c),audiences:Object.fromEntries(s),experiences:l})}}async getProjectInfo(e){let{api:t}=this.config,[n,r]=await Promise.all([t.organization.getWorkspace({organizationSlug:e.organization,workspaceSlug:e.workspace}),t.workspace.getFeatures({organizationSlug:e.organization,workspaceSlug:e.workspace})]);if(n==null||r==null)throw new d("Workspace not found",{title:"Invalid configuration",reason:"invalid_configuration",details:["The workspace defined in the configuration does not exist"],suggestions:["Check the configuration file"]});return {configuration:e,workspace:{...n,...r}}}async checkRequiredQuota(e,t){let{api:{user:n}}=this.config;for(let[r,i]of Object.entries(t)){let a=o.getRemainingQuota(e.workspace,r);if(a<i){let s=await n.getUser().catch(()=>({email:void 0})),p=new URL("https://croct.com/contact/support");throw p.searchParams.set("subject","limit-increase"),p.searchParams.set("organization",e.configuration.organization),p.searchParams.set("message",`I need more quota for ${r}`),s.email!==void 0&&p.searchParams.set("email",s.email),new d(`Not enough ${r} quota available in your workspace.`,{title:"Insufficient quota",reason:"precondition",links:[{label:"Request more quota",url:p.toString()}],details:[`Available: ${a}`,`Required: ${i}`],suggestions:[`Free up quota by removing unused ${r}`,"Request additional quota from support"]})}}}checkMissingResources(e,t){let n=this.findMissingResources(e,t);for(let[r,i]of Object.entries(n))if(i.size>0)throw new d(`Some ${r} referenced in the template are missing`,{title:"Invalid template",reason:"invalid_input",details:[`Missing ${r}: ${Array.from(i).join(", ")}`],suggestions:["Report this issue to the template author"]})}findMissingResources(e,t){let n=new Set(e.components),r=new Set(e.slots),i=new Set(e.audiences),a=new Set(e.locales);for(let s of Object.keys(t.components??{}))n.delete(s);for(let s of Object.keys(t.slots??{}))r.delete(s);for(let s of Object.keys(t.audiences??{}))i.delete(s);return {components:n,slots:r,audiences:i,locales:a}}static getRemainingQuota(e,t){let n=t.charAt(0).toUpperCase()+t.slice(1);return e.quotas[`remaining${n}`]}static getWarnings(e,t){let n=[];return Math.max(...e.experiences.map(s=>s.dynamicContentPerContent))>t.quotas.dynamicAttributesPerContent&&n.push("Some dynamic values have been removed from the content to fit the workspace quota"),Math.max(...e.experiences.map(s=>s.audiencesPerExperience))>t.quotas.audiencesPerExperience&&n.push("Some audiences have been removed from the experiences to fit the workspace quota"),Array.from(e.locales).filter(s=>!t.locales.includes(s)).length>0&&n.push("Content in unsupported locales have been mapped to default or removed"),!t.features.crossDevice&&e.experiences.some(s=>s.crossDevice)&&n.push("Cross-device experiments have been disabled "),n}static setVariables(e,t,n,r){if(e.audiences!==void 0)for(let[i]of Object.entries(t.matches.audiences??{}))e.audiences[i]!==void 0&&r.set(e.audiences[i],t.mapping.audiences[i]??i);if(e.components!==void 0)for(let[i]of Object.entries(t.matches.components??{})){let a=e.components[i];if(a!==void 0){let s=t.mapping.components[i]??i,p=t.matches.components[i]??{};a.id!==void 0&&r.set(a.id,s),a.version!==void 0&&r.set(a.version,"version"in p?p.version.major:1);}}if(e.slots!==void 0)for(let[i]of Object.entries(t.matches.slots??{})){let a=e.slots[i];if(a!==void 0){let s=t.mapping.slots[i]??i,p=t.matches.slots[i]??{};a.id!==void 0&&r.set(a.id,s),a.version!==void 0&&r.set(a.version,"version"in p?p.version.major:1);}}if(e.experiences!==void 0){let{experiences:i}=t.matches,a=0;for(let[s,p]of i.entries()){e.experiences[s]!==void 0&&r.set(e.experiences[s],"id"in p?p.id:n.experiences[a].experienceId);let c=p.experiment!==void 0&&"id"in p.experiment?p.experiment.id:n.experiences[a].experimentId;c!==void 0&&e.experiments?.[s]!==void 0&&r.set(e.experiments[s],c),"id"in p||a++;}}}};var Ot=class o{constructor(e){this.config=e;}static prompt(e){return new o(e).handle()}handle(){let{input:e,unavailableSlugs:t=[],default:n}=this.config;return e.prompt({message:this.config.label,default:n,validate:r=>/^[a-z]+(-?[a-z0-9]+)*$/i.test(r)?t.includes(r)?"The entered slug is already in use.":true:"The slug must start with a letter and contain only letters, numbers, and hyphens."})}};var ni=class{constructor(e){this.config=e;}async handle(e){let{input:t,workspaceApi:n}=this.config,{resources:r,...i}=e,a=r.slots??[],s=r.components??[],p=r.audiences??[],[c,l,m]=await Promise.all([a.length>0?n.getSlots(i):new Array,s.length>0?n.getComponents(i):new Array,p.length>0?n.getAudiences(i):new Array]),f=s.filter(j=>l.some(T=>T.slug===j)),b={};if(f.length>0){let j=l.map(T=>T.slug);for(let T of f){let q=await Ot.prompt({input:t,default:T,unavailableSlugs:j,label:`Component \`${T}\` already exists, enter a new component ID:`});j.push(q),b[T]=q;}}let A=a.filter(j=>c.some(T=>T.slug===j)),w={};if(A.length>0){let j=c.map(T=>T.slug);for(let T of A){let q=await Ot.prompt({input:t,default:T,unavailableSlugs:j,label:`Slot \`${T}\` already exists, enter a new slot ID:`});j.push(q),w[T]=q;}}let y=p.filter(j=>m.some(T=>T.slug===j)),M={};if(y.length>0){let j=m.map(T=>T.slug);for(let T of y){let q=await Ot.prompt({input:t,default:T,unavailableSlugs:j,label:`Audience \`${T}\` already exists, enter a new audience ID:`});j.push(q),M[T]=q;}}return {components:b,slots:w,audiences:M}}};var ri=class o{constructor(e){this.config=e;}async match(e){let{resources:t,...n}=e,[r,i,a,s]=await Promise.all([this.mapComponents(t.components??{},n),this.mapSlots(t.slots??{},n),this.mapAudiences(t.audiences??{},n),this.mapExperiences(t.experiences??[],n)]);return {components:r,slots:i,audiences:a,experiences:s}}async mapAudiences(e,t){let{workspaceApi:n}=this.config,r=await Promise.all(Object.keys(e).map(async a=>[a,await n.getAudience({...t,audienceSlug:a})])),i={};for(let[a,s]of r)i[a]=s===null||!o.isSimilarAudience(e[a],s)?e[a]:s;return i}async mapComponents(e,t){let{workspaceApi:n}=this.config,r=await Promise.all(Object.keys(e).map(async a=>[a,await n.getComponent({...t,componentSlug:a})])),i={};for(let[a,s]of r)i[a]=s===null||!o.isSimilarComponent(e[a],s)?e[a]:s;return i}async mapSlots(e,t){let{workspaceApi:n}=this.config,r=await Promise.all(Object.keys(e).map(async a=>[a,await n.getSlot({...t,slotSlug:a})])),i={};for(let[a,s]of r)i[a]=s===null||!o.isSimilarSlot(e[a],s)?e[a]:s;return i}async mapExperiences(e,t){let{workspaceApi:n}=this.config,i=(await n.getExperiences({...t,status:["ACTIVE","PAUSED","DRAFT"]})).map(a=>{let s=null;function p(){return s===null&&(s=n.getExperience({...t,experienceId:a.id})),s}return {...a,details:{get content(){return p().then(c=>c?.content??null)},get experiment(){return p().then(c=>c?.experiment??null)}}}});return Promise.all(e.map(async a=>{for(let s of i)if(await this.matchesExperience(a,s)){let{details:p,...c}=s;return c}return a}))}async matchesExperience(e,t){if((e.draft===true?"DRAFT":"ACTIVE")!==t.status||!deepEqual(e.audiences,t.audiences)||!deepEqual(e.slots,t.slots)||e.experiment!==void 0&&t.experiment===void 0)return false;let[r,i=null]=await Promise.all([t.details.content,t.details.experiment]);return e.experiment!==void 0&&(i===null||e.experiment.goalId!==i.goalId||e.experiment.traffic!==i.traffic||e.experiment.crossDevice!==i.crossDevice||!o.isSimilarExperimentContent(e.experiment.variants,i.variants))?false:o.isSimilarPersonalizedContent(e.content,r??{default:{},segmented:[]})}static isSimilarAudience(e,t){return e.criteria===t.criteria}static isSimilarComponent(e,t){return deepEqual(e.definition,t.definition)}static isSimilarSlot(e,t){return e.component===t.component?.slug&&Object.values(e.content).some(n=>Object.values(t.content).some(r=>deepEqual(n,r)))}static isSimilarExperimentContent(e,t){return e.length!==t.length?false:e.some((n,r)=>deepEqual(n,t[r]))}static isSimilarPersonalizedContent(e,t){if(o.isSimilarSlotContent(e.default,t.default))return true;for(let n of e.segmented)for(let r of t.segmented)if(deepEqual(n.audiences,r.audiences)&&o.isSimilarSlotContent(n.content,r.content))return true;return false}static isSimilarSlotContent(e,t){for(let[n,r]of Object.entries(e)){let i=t[n];if(i!==void 0){for(let a of Object.values(r))if(Object.values(i).some(s=>deepEqual(a,s)))return true}}return false}};var W=class o extends U{constructor(e,{url:t,...n}){super(e,n),Object.setPrototypeOf(this,o.prototype),this.url=t;}},$e=class o extends W{constructor(e,t){super(e,{...t,reason:t.reason??"not_found"}),Object.setPrototypeOf(this,o.prototype);}};var ii=class o{async get(e){if(!["http:","https:"].includes(e.protocol))throw new W("Unsupported protocol.",{reason:"not_supported",url:e});let t=await fetch(e);if(t.status===404)throw new $e("Resource not found.",{url:e});if(!o.isSuccessful(t))throw new W(t.statusText,{url:e});return {url:e,value:t}}static isSuccessful(e){return e.ok&&e.body!==null}};var oi=class{constructor({packageManager:e}){this.packageManager=e;}async execute(e,t){let{output:n}=t,r=n?.notify("Checking dependencies"),i;try{i=await Promise.all(e.dependencies.map(s=>this.checkRequirement(s)));}finally{r?.stop();}let a=[];if(e.result!==void 0)for(let s of i){if(e.result[s.dependency]!==void 0){t.set(e.result[s.dependency],s.issue===void 0);continue}s.issue!==void 0&&a.push(s);}if(a.length>0){let{message:s,...p}=e.help??{};throw new I(s??"Missing required dependencies.",{...p,details:a.map(({dependency:c,issue:l})=>`\`${c}\`: ${l}`)})}}async checkRequirement(e){let{name:t,version:n,optional:r=false}=e;if(r&&(n===void 0||!await this.packageManager.hasDirectDependency(t))||await this.packageManager.hasDirectDependency(t,n))return {dependency:t};let i=await this.packageManager.getDependency(t);return {dependency:t,issue:i===null?"not installed":`version \`${n}\` is required, found \`${i.version??"unknown"}\``}}};var Dt=class{constructor({dataProvider:e,registryProvider:t,baseUrl:n}){this.dataProvider=e,this.registryProvider=t,this.baseUrl=n;}async get(e){return this.dataProvider.get(await this.resolveUrl(e))}async resolveUrl(e){for(let{pattern:t,destination:n}of await this.loadMappings(e)){let r=e.href.match(typeof t=="string"?new RegExp(t):t);if(r!==null)return n instanceof URL?n:new URL(n.replace(/\$([0-9]+)/g,(i,a)=>r[Number.parseInt(a,10)]),this.baseUrl)}return e}async loadMappings(e){let t=await this.registryProvider.get(e);return Array.isArray(t)?t:t.value}};var Xe=class o{static{this.EXPECTED_ERROR_REASONS=["not_supported","not_found"];}constructor(...e){this.providers=e;}async get(e){for(let t of this.providers)try{return await t.get(e)}catch(n){if(!o.isExpectedError(n))throw n}throw new $e("Resource not found.",{url:e})}static isExpectedError(e){return e instanceof W&&o.EXPECTED_ERROR_REASONS.includes(e.reason)}};var ai=class o{constructor(e){this.fileSystem=e;}supports(e){return Promise.resolve(o.supportsUrl(e))}get(e){if(!o.supportsUrl(e))throw new W(`Unsupported protocol "${e.protocol}".`,{reason:"not_supported",url:e});return Promise.resolve({url:e,value:this.fileSystem.list(this.fileSystem.normalizeSeparators(e.pathname))})}static supportsUrl(e){return e.protocol==="file:"}};var ln=class o{static{this.PROTOCOL="github:";}static{this.API_HOST="api.github.com";}static{this.RAW_HOST="raw.github.com";}static{this.MAIN_HOST="github.com";}constructor(e){this.provider=e;}async get(e){let t=this.parseUrl(e);if(t===null)throw new W("Unsupported GitHub URL.",{reason:"not_supported",url:e});let n=this.resolveFile(t),{value:r}=await this.provider.get(n.url);return {url:t.canonicalUrl,value:n.url.hostname===o.RAW_HOST?this.extractFile(r,n):this.extractTarball(r,n)}}async*extractTarball(e,t){let n=Ql.extract();Readable.fromWeb(e.body).pipe(Bl()).pipe(n);let r=o.removeTrailSlash(t.path??"");for await(let i of n){let{header:a}=i;i.resume();let s=o.removeTrailSlash(a.name.split("/").slice(1).join("/"));if(s===""||!s.startsWith(r)||i.header.type==="directory"&&s===r)continue;let p=s;switch(r.length>0&&s.length>r.length&&(p=s.slice(r.length+1)),a.type){case "file":yield {type:"file",name:p,content:i};break;case "directory":yield {type:"directory",name:p};break;case "link":yield {type:"link",name:p,target:a.linkname};break;case "symlink":yield {type:"symlink",name:p,target:a.linkname};break}if(p===r)break}}async*extractFile(e,t){yield {type:"file",name:t.url.pathname.split("/").pop(),content:Readable.fromWeb(e.body)};}resolveFile(e){let{username:t,repository:n,path:r}=e,i=e.ref??"HEAD";return {...e,url:new URL(r!==null&&/\..+$/.test(r)?`https://${o.RAW_HOST}/${t}/${n}/${i}/${r}`:`https://${o.API_HOST}/repos/${t}/${n}/tarball/${i}`)}}parseUrl(e){if(!o.isUrlSupported(e))return null;let t,n,r=null,i,a=e.pathname.replace(/^\/+/,"").split("/"),s=null;return e.hostname===o.MAIN_HOST?(s=e,[t=null,n=null,,r=null,...i]=a):[t=null,n=null,...i]=a,t===null||n===null?null:(s===null&&(s=new URL(`https://${o.MAIN_HOST}`),s.pathname=`/${t}/${n}/blob/master/${i.join("/")}`),{canonicalUrl:s,username:t,repository:n,ref:r,path:i!==void 0&&i.length>0?i.join("/"):null})}static isUrlSupported(e){return e.protocol==="https:"?e.hostname===o.MAIN_HOST:e.protocol===o.PROTOCOL}static removeTrailSlash(e){return e.replace(/\/$/,"")}};var un=class o{constructor(e){this.provider=e;}async get(e){if(!o.supportsUrl(e))throw new W("Unsupported URL.",{reason:"not_supported",url:e});let{value:t,...n}=await this.provider.get(e);return {...n,value:this.yield(t,e)}}static supportsUrl(e){return e.pathname!=="/"}async*yield(e,t){yield {type:"file",name:t.pathname.split("/").pop(),content:Readable.fromWeb(e.body)};}};var Q=class{constructor(e){this.schema=e;}async validate(e){let t=await this.schema.safeParseAsync(e);if(t.success)return {valid:true,data:t.data};let{error:n}=t;return {valid:false,violations:n.issues.map(r=>({path:r.path.reduce((i,a)=>typeof a=="string"?i===""?a:`${i}.${a}`:`${i}[${a}]`,""),message:r.message}))}}};var Xl=z.object({name:z.string(),version:z.string().optional(),dependencies:z.record(z.string()).optional(),devDependencies:z.record(z.string()).optional(),bin:z.record(z.string()).optional(),scripts:z.record(z.string()).optional(),packageManager:z.string().optional()}),mn=class extends Q{constructor(){super(Xl);}};var si=z.string().regex(/^[a-z]+(-?[a-z0-9]+)*$/i,"An identifier must start with a letter and contain only letters, numbers, and hyphens."),ic=z.string().regex(/^[a-z]{2,3}([-_][a-z]{2,3})?$/i,"Locale must be in the form of en, en_US, or en-US."),oc=z.string().refine(O.isValid,"Version must be exact (1), range (1 - 2), or set (1 || 2).").refine(o=>{try{return O.parse(o).getCardinality()<=5}catch{return false}},"Version range must not exceed 5 major versions."),eu=z.strictObject({$schema:z.string().optional(),organization:si,workspace:si,applications:z.strictObject({development:si,production:si.optional()}),locales:z.array(ic),defaultLocale:ic,slots:z.record(oc),components:z.record(oc),paths:z.strictObject({components:z.string(),examples:z.string(),content:z.string().optional()})}).refine(o=>o.locales.includes(o.defaultLocale),{message:"The default locale is not included in the list of locales.",path:["defaultLocale"]}),pi=class extends Q{constructor(){super(eu);}};var Mt=class{constructor({provider:e,validator:t}){this.provider=e,this.validator=t;}async get(e){let{value:t,...n}=await this.provider.get(e),r=await this.validator.validate(t);if(!r.valid){let i=r.violations.map(a=>` \u2022 **${a.path}**: ${a.message}`).join(`
1754
1755
 
1755
1756
  `);throw new W(`The response data is invalid:
1756
1757
 
1757
- ${i}`,{reason:"invalid_input",url:e})}return {...n,value:r.data}}};var St=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 Fe("File not found.",{url:e});return {...n,value:await new Response(r.value.content).text()}}};var Pn=class{constructor(e){this.provider=e;}async get(e){let{value:t,...n}=await this.provider.get(e);try{return {...n,value:json5Parser.JsonParser.parse(t).toJSON()}}catch(r){throw new W("Malformed JSON.",{reason:"precondition",url:e,cause:r})}}};var ku=zod.z.strictObject({pattern:zod.z.string().refine(o=>{try{return new RegExp(o),!0}catch{return {message:"Invalid regular expression."}}}),destination:zod.z.string()}),Au=zod.z.array(ku),Oi=class extends B{constructor(){super(Au);}};var kn=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:crypto.createHash("md5").update(e).digest("hex"))}};var An=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 bt;(e=>{function o(...t){return t.reduce((n,r)=>Object.defineProperties(n,Object.getOwnPropertyDescriptors(r)),{})}e.merge=o;})(bt||(bt={}));var $=class o extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var Q=class Q{constructor(e={}){this.cache=new Map;this.configuration=e;}evaluate(e,t){return this.evaluateExpression(this.parse(e),t)}parse(e){let t=this.cache.get(e);if(t!==void 0)return t;Ze__default.default.plugins.register(Ru__default.default),Ze__default.default.plugins.register(Tu__default.default),Ze__default.default.removeAllUnaryOps();for(let r of Object.keys(Q.UNARY_OPERATORS))Ze__default.default.addUnaryOp(r);Ze__default.default.removeAllBinaryOps();for(let[r,{precedence:i}]of Object.entries(Q.BINARY_OPERATORS))Ze__default.default.addBinaryOp(r,i);Ze__default.default.removeAllLiterals();for(let[r,i]of Object.entries(Q.LITERALS))Ze__default.default.addLiteral(r,i);let n;try{n=Ze__default.default(e);}catch(r){throw new $("Malformed expression.",{cause:r,details:[`Expression: ${e}`]})}return this.cache.set(e,n),n}async evaluateExpression(e,t){switch(true){case J(e,"Literal"):return e.value;case J(e,"ThisExpression"):case J(e,"Identifier"):{let n=e.type==="ThisExpression"?"this":e.name,r=t?.variables?.[n];if(r===void 0)throw new $(`Variable \`${n}\` is unknown.`);return r}case J(e,"ArrayExpression"):return (await Promise.all(e.elements.map(r=>{if(r===null)return [];if(J(r,"SpreadElement")){let i=this.evaluateExpression(r.argument,t);if(!(i instanceof Promise)&&!Array.isArray(i))throw new $(`Spread expression must evaluate to an array, got ${d.describeType(i)}.`);return i}return [this.evaluateExpression(r,t)]}))).flat();case J(e,"ObjectExpression"):return Object.fromEntries(await Promise.all(e.properties.flatMap(async n=>{if(J(n,"SpreadElement")){let i=await this.evaluateExpression(n.argument,t);if(typeof i!="object"||i===null)throw new $(`Spread expression must evaluate to an object, got ${d.describeType(i)}.`);return Object.entries(i)}return n.value===void 0&&J(n.key,"Identifier")?[n.key.name,await this.evaluateExpression(n.key,t)]:[[J(n.key,"Identifier")?n.key.name:this.evaluateExpression(n.key,t).then(i=>{if(typeof i!="string"&&typeof i!="number")throw new $(`Property name must be a string or a number, got ${d.describeType(i)}.`);return i}),await this.evaluateExpression(n.value,t)]]})));case J(e,"UnaryExpression"):return Q.UNARY_OPERATORS[e.operator].evaluate(()=>this.evaluateExpression(e.argument,t));case J(e,"BinaryExpression"):return Q.BINARY_OPERATORS[e.operator].evaluate(()=>this.evaluateExpression(e.left,t),()=>this.evaluateExpression(e.right,t));case J(e,"MemberExpression"):{let n=await this.evaluateExpression(e.object,t);if(typeof n!="object"||n===null)throw new $("Cannot access property of a non-object.");let r=J(e.property,"Identifier")?e.property.name:await this.evaluateExpression(e.property,t);if(typeof r=="number"){if(!Array.isArray(n))throw new $("Cannot access array index of a non-array.");if(r<0||r>=n.length)throw new $("Array index is out of bounds.");return n[r]}if(typeof r!="string")throw new $(`Property name must be a string, got ${d.describeType(r)}.`);if(!Q.isPropertyAllowed(n,r))throw new $(`Property \`${r}\` does not exist or is not accessible.`);return n[r]}case J(e,"CallExpression"):return (await this.getCallee(e.callee,t))(...await Promise.all(e.arguments.flatMap(r=>{let i=this.resolve(this.evaluateExpression(r,t));if(J(r,"SpreadElement")){if(!Array.isArray(i))throw new $(`Spread argument must evaluate to an array, got ${d.describeType(i)}.`);return i}return [i]})));case J(e,"ConditionalExpression"):return await this.evaluateExpression(e.test,t)?this.evaluateExpression(e.consequent,t):this.evaluateExpression(e.alternate,t);default:throw new $(`Unexpected expression type \`${e.type}\`.`)}}async getCallee(e,t){if(J(e,"Identifier")){let n=t?.functions?.[e.name]??this.configuration.functions?.[e.name];if(n===void 0)throw new $(`Function \`${e.name}\` does not exist.`);return n}if(J(e,"MemberExpression")){let n=await this.evaluateExpression(e.object,t),r=J(e.property,"Identifier")?e.property.name:await this.evaluateExpression(e.property,t);if(typeof r!="string")throw new $(`Method name must be a string, got ${d.describeType(r)}.`);if(!Q.isMethodAllowed(n,r))throw new $(`Method \`${r}\` does not exist or is not accessible.`);return n[r].bind(n)}throw new $("Callee is not callable.")}static isMethodAllowed(e,t){return typeof e=="string"?Q.ALLOWED_STRING_METHODS.includes(t):Array.isArray(e)?Q.ALLOWED_ARRAY_METHODS.includes(t):false}static isPropertyAllowed(e,t){return typeof e=="string"?Q.ALLOWED_STRING_PROPERTIES.includes(t):Array.isArray(e)?Q.ALLOWED_ARRAY_PROPERTIES.includes(t):typeof e=="object"&&e!==null&&Object.hasOwn(e,t)&&e[t]!==void 0}async resolve(e){if(!(e instanceof Promise)&&(typeof e!="object"||e===null))return e;let t=await e;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}};Q.ALLOWED_ARRAY_PROPERTIES=["length"],Q.ALLOWED_ARRAY_METHODS=["slice","join"],Q.ALLOWED_STRING_PROPERTIES=["length"],Q.ALLOWED_STRING_METHODS=["slice","includes","startsWith","endsWith","toLowerCase","toUpperCase"],Q.LITERALS={true:true,false:false,null:null},Q.UNARY_OPERATORS={"!":{evaluate:async e=>!await En(e)},"-":{evaluate:async e=>-await Z(e)},"+":{evaluate:async e=>+await Z(e)}},Q.BINARY_OPERATORS={"||":{precedence:1,evaluate:async(e,t)=>await En(e)||En(t)},"??":{precedence:1,evaluate:async(e,t)=>await e()??t()},"&&":{precedence:2,evaluate:async(e,t)=>await En(e)&&En(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 Z(e)<await Z(t)},">":{precedence:7,evaluate:async(e,t)=>await Z(e)>await Z(t)},"<=":{precedence:7,evaluate:async(e,t)=>await Z(e)<=await Z(t)},">=":{precedence:7,evaluate:async(e,t)=>await Z(e)>=await Z(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 $(`Operands must be numbers or strings, got ${d.describeType(n)} and ${d.describeType(r)}.`);return n+r}},"-":{precedence:9,evaluate:async(e,t)=>await Z(e)-await Z(t)},"*":{precedence:10,evaluate:async(e,t)=>await Z(e)*await Z(t)},"/":{precedence:10,evaluate:async(e,t)=>await Z(e)/await Z(t)},"%":{precedence:10,evaluate:async(e,t)=>await Z(e)%await Z(t)},"**":{precedence:11,evaluate:async(e,t)=>(await Z(e))**await Z(t)}};var Di=Q;function J(o,e){return o.type===e}async function Z(o){let e=await o();if(typeof e!="number")throw new $(`Number expected, got ${d.describeType(e)}.`);return e}async function En(o){let e=await o();if(typeof e!="boolean")throw new $(`Boolean expected, got ${d.describeType(e)}.`);return e}var Wt=zod.z.strictObject({description:zod.z.string(),required:zod.z.boolean().optional()}),Ou=zod.z.union([zod.z.string(),zod.z.number(),zod.z.boolean(),zod.z.null()]),Mi=zod.z.lazy(()=>zod.z.union([Ou,zod.z.array(Mi),zod.z.record(Mi)])),Du=zod.z.discriminatedUnion("type",[Wt.extend({type:zod.z.literal("reference"),default:zod.z.string().optional()}),Wt.extend({type:zod.z.literal("string"),options:zod.z.array(zod.z.string()).optional(),default:zod.z.string().optional()}),Wt.extend({type:zod.z.literal("number"),default:zod.z.number().optional()}),Wt.extend({type:zod.z.literal("boolean"),default:zod.z.boolean().optional()}),Wt.extend({type:zod.z.literal("array"),default:zod.z.array(Mi).optional()}),Wt.extend({type:zod.z.literal("object"),default:zod.z.record(zod.z.string(),Mi).optional()})]),Mu=zod.z.strictObject({$schema:zod.z.string().optional(),title:zod.z.string().min(1).optional(),description:zod.z.string().optional(),options:zod.z.record(zod.z.string().min(1),Du).optional(),actions:zod.z.array(zod.z.any())}),Rn=class extends B{constructor(){super(Mu);}};var Ni=class o{constructor(e){this.resolving=[];this.config=e;}async execute(e,t){let{output:n}=t,r=n.notify("Loading template");try{await this.importTemplate(e,t);}finally{r.stop();}}async importTemplate(e,t){let{value:n,url:r}=await this.loadTemplate(e.template,t.baseUrl),i=await this.getInputValues(n,e.options);if(this.resolving.includes(r.href)){let s=[...this.resolving,r.href].map((p,c)=>` ${c+1}. ${p}`).join(`
1758
+ ${i}`,{reason:"invalid_input",url:e})}return {...n,value:r.data}}};var mt=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 $e("File not found.",{url:e});return {...n,value:await new Response(r.value.content).text()}}};var dn=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 W("Malformed JSON.",{reason:"precondition",url:e,cause:r})}}};var nu=z.strictObject({pattern:z.string().refine(o=>{try{return new RegExp(o),!0}catch{return {message:"Invalid regular expression."}}}),destination:z.string()}),ru=z.array(nu),li=class extends Q{constructor(){super(ru);}};var gn=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 fn=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 Nt;(e=>{function o(...t){return t.reduce((n,r)=>Object.defineProperties(n,Object.getOwnPropertyDescriptors(r)),{})}e.merge=o;})(Nt||={});var $=class o extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var ui=class o{constructor(e={}){this.cache=new Map;this.configuration=e;}static{this.ALLOWED_ARRAY_PROPERTIES=["length"];}static{this.ALLOWED_ARRAY_METHODS=["slice","join"];}static{this.ALLOWED_STRING_PROPERTIES=["length"];}static{this.ALLOWED_STRING_METHODS=["slice","includes","startsWith","endsWith","toLowerCase","toUpperCase"];}static{this.LITERALS={true:true,false:false,null:null};}static{this.UNARY_OPERATORS={"!":{evaluate:async e=>!await yn(e)},"-":{evaluate:async e=>-await Z(e)},"+":{evaluate:async e=>+await Z(e)}};}static{this.BINARY_OPERATORS={"||":{precedence:1,evaluate:async(e,t)=>await yn(e)||yn(t)},"??":{precedence:1,evaluate:async(e,t)=>await e()??t()},"&&":{precedence:2,evaluate:async(e,t)=>await yn(e)&&yn(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 Z(e)<await Z(t)},">":{precedence:7,evaluate:async(e,t)=>await Z(e)>await Z(t)},"<=":{precedence:7,evaluate:async(e,t)=>await Z(e)<=await Z(t)},">=":{precedence:7,evaluate:async(e,t)=>await Z(e)>=await Z(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 $(`Operands must be numbers or strings, got ${d.describeType(n)} and ${d.describeType(r)}.`);return n+r}},"-":{precedence:9,evaluate:async(e,t)=>await Z(e)-await Z(t)},"*":{precedence:10,evaluate:async(e,t)=>await Z(e)*await Z(t)},"/":{precedence:10,evaluate:async(e,t)=>await Z(e)/await Z(t)},"%":{precedence:10,evaluate:async(e,t)=>await Z(e)%await Z(t)},"**":{precedence:11,evaluate:async(e,t)=>(await Z(e))**await Z(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;qe.plugins.register(ou),qe.plugins.register(au),qe.removeAllUnaryOps();for(let r of Object.keys(o.UNARY_OPERATORS))qe.addUnaryOp(r);qe.removeAllBinaryOps();for(let[r,{precedence:i}]of Object.entries(o.BINARY_OPERATORS))qe.addBinaryOp(r,i);qe.removeAllLiterals();for(let[r,i]of Object.entries(o.LITERALS))qe.addLiteral(r,i);let n;try{n=qe(e);}catch(r){throw new $("Malformed expression.",{cause:r,details:[`Expression: ${e}`]})}return this.cache.set(e,n),n}async evaluateExpression(e,t){switch(true){case J(e,"Literal"):return e.value;case J(e,"ThisExpression"):case J(e,"Identifier"):{let n=e.type==="ThisExpression"?"this":e.name,r=t?.variables?.[n];if(r===void 0)throw new $(`Variable \`${n}\` is unknown.`);return r}case J(e,"ArrayExpression"):return (await Promise.all(e.elements.map(r=>{if(r===null)return [];if(J(r,"SpreadElement")){let i=this.evaluateExpression(r.argument,t);if(!(i instanceof Promise)&&!Array.isArray(i))throw new $(`Spread expression must evaluate to an array, got ${d.describeType(i)}.`);return i}return [this.evaluateExpression(r,t)]}))).flat();case J(e,"ObjectExpression"):return Object.fromEntries(await Promise.all(e.properties.flatMap(async n=>{if(J(n,"SpreadElement")){let i=await this.evaluateExpression(n.argument,t);if(typeof i!="object"||i===null)throw new $(`Spread expression must evaluate to an object, got ${d.describeType(i)}.`);return Object.entries(i)}return n.value===void 0&&J(n.key,"Identifier")?[n.key.name,await this.evaluateExpression(n.key,t)]:[[J(n.key,"Identifier")?n.key.name:this.evaluateExpression(n.key,t).then(i=>{if(typeof i!="string"&&typeof i!="number")throw new $(`Property name must be a string or a number, got ${d.describeType(i)}.`);return i}),await this.evaluateExpression(n.value,t)]]})));case J(e,"UnaryExpression"):return o.UNARY_OPERATORS[e.operator].evaluate(()=>this.evaluateExpression(e.argument,t));case J(e,"BinaryExpression"):return o.BINARY_OPERATORS[e.operator].evaluate(()=>this.evaluateExpression(e.left,t),()=>this.evaluateExpression(e.right,t));case J(e,"MemberExpression"):{let n=await this.evaluateExpression(e.object,t);if(typeof n!="object"||n===null)throw new $("Cannot access property of a non-object.");let r=J(e.property,"Identifier")?e.property.name:await this.evaluateExpression(e.property,t);if(typeof r=="number"){if(!Array.isArray(n))throw new $("Cannot access array index of a non-array.");if(r<0||r>=n.length)throw new $("Array index is out of bounds.");return n[r]}if(typeof r!="string")throw new $(`Property name must be a string, got ${d.describeType(r)}.`);if(!o.isPropertyAllowed(n,r))throw new $(`Property \`${r}\` does not exist or is not accessible.`);return n[r]}case J(e,"CallExpression"):return (await this.getCallee(e.callee,t))(...await Promise.all(e.arguments.flatMap(r=>{let i=this.resolve(this.evaluateExpression(r,t));if(J(r,"SpreadElement")){if(!Array.isArray(i))throw new $(`Spread argument must evaluate to an array, got ${d.describeType(i)}.`);return i}return [i]})));case J(e,"ConditionalExpression"):return await this.evaluateExpression(e.test,t)?this.evaluateExpression(e.consequent,t):this.evaluateExpression(e.alternate,t);default:throw new $(`Unexpected expression type \`${e.type}\`.`)}}async getCallee(e,t){if(J(e,"Identifier")){let n=t?.functions?.[e.name]??this.configuration.functions?.[e.name];if(n===void 0)throw new $(`Function \`${e.name}\` does not exist.`);return n}if(J(e,"MemberExpression")){let n=await this.evaluateExpression(e.object,t),r=J(e.property,"Identifier")?e.property.name:await this.evaluateExpression(e.property,t);if(typeof r!="string")throw new $(`Method name must be a string, got ${d.describeType(r)}.`);if(!o.isMethodAllowed(n,r))throw new $(`Method \`${r}\` does not exist or is not accessible.`);return n[r].bind(n)}throw new $("Callee is not callable.")}static isMethodAllowed(e,t){return typeof e=="string"?o.ALLOWED_STRING_METHODS.includes(t):Array.isArray(e)?o.ALLOWED_ARRAY_METHODS.includes(t):false}static isPropertyAllowed(e,t){return typeof e=="string"?o.ALLOWED_STRING_PROPERTIES.includes(t):Array.isArray(e)?o.ALLOWED_ARRAY_PROPERTIES.includes(t):typeof e=="object"&&e!==null&&Object.hasOwn(e,t)&&e[t]!==void 0}async resolve(e){if(!(e instanceof Promise)&&(typeof e!="object"||e===null))return e;let t=await e;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}};function J(o,e){return o.type===e}async function Z(o){let e=await o();if(typeof e!="number")throw new $(`Number expected, got ${d.describeType(e)}.`);return e}async function yn(o){let e=await o();if(typeof e!="boolean")throw new $(`Boolean expected, got ${d.describeType(e)}.`);return e}var $t=z.strictObject({description:z.string(),required:z.boolean().optional()}),su=z.union([z.string(),z.number(),z.boolean(),z.null()]),mi=z.lazy(()=>z.union([su,z.array(mi),z.record(mi)])),pu=z.discriminatedUnion("type",[$t.extend({type:z.literal("reference"),default:z.string().optional()}),$t.extend({type:z.literal("string"),options:z.array(z.string()).optional(),default:z.string().optional()}),$t.extend({type:z.literal("number"),default:z.number().optional()}),$t.extend({type:z.literal("boolean"),default:z.boolean().optional()}),$t.extend({type:z.literal("array"),default:z.array(mi).optional()}),$t.extend({type:z.literal("object"),default:z.record(z.string(),mi).optional()})]),cu=z.strictObject({$schema:z.string().optional(),title:z.string().min(1).optional(),description:z.string().optional(),options:z.record(z.string().min(1),pu).optional(),actions:z.array(z.any())}),hn=class extends Q{constructor(){super(cu);}};var di=class o{constructor(e){this.resolving=[];this.config=e;}async execute(e,t){let{output:n}=t,r=n.notify("Loading template");try{await this.importTemplate(e,t);}finally{r.stop();}}async importTemplate(e,t){let{value:n,url:r}=await this.loadTemplate(e.template,t.baseUrl),i=await this.getInputValues(n,e.options);if(this.resolving.includes(r.href)){let s=[...this.resolving,r.href].map((p,c)=>` ${c+1}. ${p}`).join(`
1758
1759
  `);throw new I(`Circular dependency detected while loading templates:
1759
1760
 
1760
- ${s}`,{reason:"invalid_input"})}this.resolving.push(r.toString());let a=new zt({input:t.input,output:t.output,baseUrl:r});o.shareVariables(i.references,t,a);try{await this.run(n,i.values,a);}finally{this.resolving.pop();}o.shareVariables(i.references,a,t);}async getInputValues(e,t={}){let n={},r=[];for(let[i,a]of Object.entries(e.options??{})){let s=t[i];if(s===void 0&&a.required===true)throw new I(`Missing required option \`${i}\`.`,{reason:"invalid_input"});let p=await(s??a.resolveDefault?.(this.config.variables));p!==void 0&&(a.type==="reference"?(o.checkOptionValue(i,p,{...a,type:"string"}),r.push(p)):o.checkOptionValue(i,p,a),n[i]=p);}return {values:n,references:r}}async run(e,t,n){let{runner:r,variables:i}=this.config,{output:a}=n;for(let{resolve:s}of e.actions){let p=a.notify("Resolving options"),c;try{c=await s(bt.merge(i,{options:t,get this(){return n.getVariables()}}));}catch(l){throw I.fromCause(l,{message:"Unable to resolve action definition."})}finally{p.stop();}await r.execute({actions:[c]},n);}}async loadTemplate(e,t){let n=this.config.templateProvider,r=_t(e,t);try{return await n.get(r)}catch(i){throw i instanceof Fe?new d(`No template found at \`${r}\`.`,{cause:i,reason:"invalid_input",suggestions:["Check if the template path or URL is correct and try again."]}):i}}static checkOptionValue(e,t,n){switch(n.type){case "number":case "string":case "boolean":{if(typeof t!==n.type)throw new I(`Expected value of type ${n.type} for option \`${e}\`, but got ${d.describeType(t)}.`,{reason:"invalid_input"});if(n.type==="string"&&n.options!==void 0&&!n.options.includes(t))throw new I(`Invalid value for option \`${e}\`.`,{reason:"invalid_input",details:[`Allowed values: \`${n.options.join("`, `")}\`.`]});break}case "array":{if(!Array.isArray(t))throw new I(`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 I(`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 L=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 a=i.violations.map(s=>(s.path===""?s.message:`**${s.path}**: ${s.message}`).replace(/'/g,"`"));throw new I("Invalid action options.",{reason:"invalid_input",details:a})}await n.execute(i.data,t);}};var Vt;(n=>{let o=Symbol("source");function e(r){return r[o]??null}n.get=e;function t(r,i){r[o]=i;}n.set=t;})(Vt||(Vt={}));var $i=class o{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 [...o.from(e,t)]}static from(e,t){return new o(o.getExpression(e),t??(e instanceof json5Parser.JsonPrimitiveNode?e.location.start:{index:0,line:1,column:1}))}static getExpression(e){return typeof e=="string"?e:e instanceof json5Parser.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 a=this.chars[this.cursor],s=a==="$"&&this.chars[this.cursor+1]==="{";if(!(r+t+n>0)&&s&&i.length>0)return this.createLiteralFragment(i,e);if(this.cursor++,this.index++,a===`
1761
- `?(this.line++,this.column=1):this.column++,i+=a,t>0||n>0)a==="\\"?(i+=this.chars[this.cursor],this.cursor++,this.index++,this.column++):t>0&&a==="'"?t--:n>0&&a==='"'&&n--;else if(r>0){if(a==="'"?t++:a==='"'?n++:a==="{"?r++:a==="}"&&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 Tn,On,Ut,zi=class zi extends Promise{constructor(t,n=false){super(()=>{});Jn(this,Tn);Jn(this,On);Jn(this,Ut);Bn(this,Tn,t),Bn(this,On,n);}static from(t){return new zi(t)}static transient(t){return new zi(t,true)}get promise(){if(en(this,Ut)!==void 0)return en(this,Ut);let t=new Promise(n=>{n(en(this,Tn).call(this));});return en(this,On)||Bn(this,Ut,t),t}then(t,n){return this.promise.then(t,n)}catch(t){return this.promise.catch(t)}finally(t){return this.promise.finally(t)}};Tn=new WeakMap,On=new WeakMap,Ut=new WeakMap;var ie=zi;var ke=class o extends W{constructor(e,{violations:t,...n}){super(e,n),this.violations=t,Object.setPrototypeOf(this,o.prototype);}},_i=class o{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=o.cleanJson(json5Parser.JsonParser.parse(n,json5Parser.JsonObjectNode));}catch(f){throw new ke("Failed to parse the JSON template.",{reason:"invalid_input",url:t,cause:f,violations:[{path:"",message:d.formatMessage(f)}]})}let i=r.toJSON(),a=await this.validator.validate(i);if(!a.valid){let f=a.violations.map(b=>` \u2022 **${b.path}**: ${b.message}`).join(`
1761
+ ${s}`,{reason:"invalid_input"})}this.resolving.push(r.toString());let a=new Rt({input:t.input,output:t.output,baseUrl:r});o.shareVariables(i.references,t,a);try{await this.run(n,i.values,a);}finally{this.resolving.pop();}o.shareVariables(i.references,a,t);}async getInputValues(e,t={}){let n={},r=[];for(let[i,a]of Object.entries(e.options??{})){let s=t[i];if(s===void 0&&a.required===true)throw new I(`Missing required option \`${i}\`.`,{reason:"invalid_input"});let p=await(s??a.resolveDefault?.(this.config.variables));p!==void 0&&(a.type==="reference"?(o.checkOptionValue(i,p,{...a,type:"string"}),r.push(p)):o.checkOptionValue(i,p,a),n[i]=p);}return {values:n,references:r}}async run(e,t,n){let{runner:r,variables:i}=this.config,{output:a}=n;for(let{resolve:s}of e.actions){let p=a.notify("Resolving options"),c;try{c=await s(Nt.merge(i,{options:t,get this(){return n.getVariables()}}));}catch(l){throw I.fromCause(l,{message:"Unable to resolve action definition."})}finally{p.stop();}await r.execute({actions:[c]},n);}}async loadTemplate(e,t){let n=this.config.templateProvider,r=Tt(e,t);try{return await n.get(r)}catch(i){throw i instanceof $e?new d(`No template found at \`${r}\`.`,{cause:i,reason:"invalid_input",suggestions:["Check if the template path or URL is correct and try again."]}):i}}static checkOptionValue(e,t,n){switch(n.type){case "number":case "string":case "boolean":{if(typeof t!==n.type)throw new I(`Expected value of type ${n.type} for option \`${e}\`, but got ${d.describeType(t)}.`,{reason:"invalid_input"});if(n.type==="string"&&n.options!==void 0&&!n.options.includes(t))throw new I(`Invalid value for option \`${e}\`.`,{reason:"invalid_input",details:[`Allowed values: \`${n.options.join("`, `")}\`.`]});break}case "array":{if(!Array.isArray(t))throw new I(`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 I(`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 L=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 a=i.violations.map(s=>(s.path===""?s.message:`**${s.path}**: ${s.message}`).replace(/'/g,"`"));throw new I("Invalid action options.",{reason:"invalid_input",details:a})}await n.execute(i.data,t);}};var Sn;(n=>{let o=Symbol("source");function e(r){return r[o]??null}n.get=e;function t(r,i){r[o]=i;}n.set=t;})(Sn||={});var gi=class o{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 [...o.from(e,t)]}static from(e,t){return new o(o.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 a=this.chars[this.cursor],s=a==="$"&&this.chars[this.cursor+1]==="{";if(!(r+t+n>0)&&s&&i.length>0)return this.createLiteralFragment(i,e);if(this.cursor++,this.index++,a===`
1762
+ `?(this.line++,this.column=1):this.column++,i+=a,t>0||n>0)a==="\\"?(i+=this.chars[this.cursor],this.cursor++,this.index++,this.column++):t>0&&a==="'"?t--:n>0&&a==='"'&&n--;else if(r>0){if(a==="'"?t++:a==='"'?n++:a==="{"?r++:a==="}"&&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 ne=class o extends Promise{#t;#n;#e;constructor(e,t=false){super(()=>{}),this.#t=e,this.#n=t;}static from(e){return new o(e)}static transient(e){return new o(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 ve=class o extends W{constructor(e,{violations:t,...n}){super(e,n),this.violations=t,Object.setPrototypeOf(this,o.prototype);}},fi=class o{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=o.cleanJson(JsonParser.parse(n,JsonObjectNode));}catch(f){throw new ve("Failed to parse the JSON template.",{reason:"invalid_input",url:t,cause:f,violations:[{path:"",message:d.formatMessage(f)}]})}let i=r.toJSON(),a=await this.validator.validate(i);if(!a.valid){let f=a.violations.map(b=>` \u2022 **${b.path}**: ${b.message}`).join(`
1762
1763
 
1763
- `);throw new ke(`The template contains errors:
1764
+ `);throw new ve(`The template contains errors:
1764
1765
 
1765
- ${f}`,{reason:"invalid_input",url:t,violations:a.violations})}let{options:s,actions:p,...c}=a.data,l=r.get("actions",json5Parser.JsonArrayNode),m=this.parseOptions(r,s,t);return {url:t,value:{...c,...m!==void 0?{options:m}:{},actions:l.elements.map(f=>({resolve:b=>this.resolve(f,b,t)}))}}}parseOptions(e,t,n){if(t===void 0)return;let r=e.get("options",json5Parser.JsonObjectNode);return Object.fromEntries(Object.entries(t).map(([i,a])=>{if(a.default===void 0)return [i,a];let s=r.get(i,json5Parser.JsonObjectNode).get("default");return [i,{...a,resolveDefault:p=>this.resolve(s,p,n)}]}))}resolve(e,t,n,r=""){return e instanceof json5Parser.JsonArrayNode?e.elements.map((i,a)=>this.resolve(i,t,n,`${r}[${a}]`)):e instanceof json5Parser.JsonObjectNode?ie.transient(async()=>{let i=Object.fromEntries(await Promise.all(e.properties.map(async a=>{let s=await this.interpolate(a.key,t,n,r);if(typeof s!="string"&&typeof s!="number"){let c=a.key.location.start;throw new ke("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,ie.transient(()=>this.resolve(a.value,t,n,p))]})));return Vt.set(i,{url:n,start:e.location.start,end:e.location.end}),i}):e instanceof json5Parser.JsonPrimitiveNode&&typeof e.value=="string"?ie.transient(()=>this.interpolate(e,t,n,r)):e.toJSON()}interpolate(e,t,n,r){let i=$i.parse(e);if(i.length===1){let a=i[0];return a.type==="literal"?a.source:this.evaluate(o.createExpressionNode(a),t,n,r)}return Promise.all(i.map(async a=>{if(a.type==="literal")return a.source;let s=o.createExpressionNode(a),p=await this.evaluate(s,t,n,r);if(p!==null&&!["string","number","boolean"].includes(typeof p)){let c=e.location.start;throw new ke("Unexpected expression result.",{reason:"invalid_input",url:n,violations:[{path:r,message:`Expected expression \`${a.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(a=>a.join(""))}async evaluate(e,t,n,r){let i=(e instanceof json5Parser.JsonIdentifierNode?e.token.value:e.value).trim();try{return await this.evaluator.evaluate(i,{variables:t,functions:{import:(a,s)=>{if(typeof a!="string"){let p=e.location.start;throw new $("Invalid argument for function `import`.",{reason:"invalid_input",details:[`The \`url\` argument of the \`import\` function must be a string, but got ${d.describeType(a)} 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 $("Invalid argument for function `import`.",{reason:"invalid_input",details:[`The \`properties\` argument of the \`import\` function must be an object, but got ${d.describeType(a)} at line ${p.line}, column ${p.column}.`]})}return this.import(_t(a,n),s===void 0?t:bt.merge(t,{this:Promise.resolve(t.this).then(p=>typeof p=="object"&&p!==null&&!Array.isArray(p)?bt.merge(p,s):s)}),n,r)}}})}catch(a){let s=e.location.start;throw new ke("Failed to evaluate expression.",{reason:"invalid_input",url:n,cause:a,violations:[{path:r,message:`Evaluation of \`${i}\` at line ${s.line}, column ${s.column} failed because ${d.formatCause(a)}`}]})}}async import(e,t,n,r){if(e.protocol==="file:"&&n.protocol!=="file:")throw new ke("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(`
1766
- `);throw new ke(`Circular dependency detected while loading templates:
1766
+ ${f}`,{reason:"invalid_input",url:t,violations:a.violations})}let{options:s,actions:p,...c}=a.data,l=r.get("actions",JsonArrayNode),m=this.parseOptions(r,s,t);return {url:t,value:{...c,...m!==void 0?{options:m}:{},actions:l.elements.map(f=>({resolve:b=>this.resolve(f,b,t)}))}}}parseOptions(e,t,n){if(t===void 0)return;let r=e.get("options",JsonObjectNode);return Object.fromEntries(Object.entries(t).map(([i,a])=>{if(a.default===void 0)return [i,a];let s=r.get(i,JsonObjectNode).get("default");return [i,{...a,resolveDefault:p=>this.resolve(s,p,n)}]}))}resolve(e,t,n,r=""){return e instanceof JsonArrayNode?e.elements.map((i,a)=>this.resolve(i,t,n,`${r}[${a}]`)):e instanceof JsonObjectNode?ne.transient(async()=>{let i=Object.fromEntries(await Promise.all(e.properties.map(async a=>{let s=await this.interpolate(a.key,t,n,r);if(typeof s!="string"&&typeof s!="number"){let c=a.key.location.start;throw new ve("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,ne.transient(()=>this.resolve(a.value,t,n,p))]})));return Sn.set(i,{url:n,start:e.location.start,end:e.location.end}),i}):e instanceof JsonPrimitiveNode&&typeof e.value=="string"?ne.transient(()=>this.interpolate(e,t,n,r)):e.toJSON()}interpolate(e,t,n,r){let i=gi.parse(e);if(i.length===1){let a=i[0];return a.type==="literal"?a.source:this.evaluate(o.createExpressionNode(a),t,n,r)}return Promise.all(i.map(async a=>{if(a.type==="literal")return a.source;let s=o.createExpressionNode(a),p=await this.evaluate(s,t,n,r);if(p!==null&&!["string","number","boolean"].includes(typeof p)){let c=e.location.start;throw new ve("Unexpected expression result.",{reason:"invalid_input",url:n,violations:[{path:r,message:`Expected expression \`${a.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(a=>a.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:{import:(a,s)=>{if(typeof a!="string"){let p=e.location.start;throw new $("Invalid argument for function `import`.",{reason:"invalid_input",details:[`The \`url\` argument of the \`import\` function must be a string, but got ${d.describeType(a)} 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 $("Invalid argument for function `import`.",{reason:"invalid_input",details:[`The \`properties\` argument of the \`import\` function must be an object, but got ${d.describeType(a)} at line ${p.line}, column ${p.column}.`]})}return this.import(Tt(a,n),s===void 0?t:Nt.merge(t,{this:Promise.resolve(t.this).then(p=>typeof p=="object"&&p!==null&&!Array.isArray(p)?Nt.merge(p,s):s)}),n,r)}}})}catch(a){let s=e.location.start;throw new ve("Failed to evaluate expression.",{reason:"invalid_input",url:n,cause:a,violations:[{path:r,message:`Evaluation of \`${i}\` at line ${s.line}, column ${s.column} failed because ${d.formatCause(a)}`}]})}}async import(e,t,n,r){if(e.protocol==="file:"&&n.protocol!=="file:")throw new ve("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(`
1767
+ `);throw new ve(`Circular dependency detected while loading templates:
1767
1768
 
1768
- ${p}`,{reason:"invalid_input",url:e,violations:[{path:r,message:"Imported template creates a circular dependency."}]})}let{url:i,value:a}=await this.fileProvider.get(e),s;try{s=o.cleanJson(json5Parser.JsonParser.parse(a));}catch(p){throw new ke("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 json5Parser.JsonPrimitiveNode({value:e.expression,location:e.location,token:new json5Parser.JsonTokenNode({type:json5Parser.JsonTokenType.STRING,value:e.source,location:e.location})})}static cleanJson(e){if(e instanceof json5Parser.JsonPrimitiveNode)return e;if(e instanceof json5Parser.JsonArrayNode){for(let t of e.elements)this.cleanJson(t);return e}if(e instanceof json5Parser.JsonObjectNode)for(let t of e.properties){let n=t.key.toJSON();n==="$schema"?e.delete(n):this.cleanJson(t.value);}return e}};var fs=Symbol("any-property"),Mc=Symbol("any-index"),Mn=Symbol("passthrough"),qt=Symbol("resolve"),v=class o extends B{async validate(e){let t=this.findPassthroughPaths(this.schema),n;try{n=await this.resolveOptions(e,t);}catch(r){if(r instanceof ke)return {valid:false,violations:r.violations};throw r}return super.validate(n).then(r=>(r.valid&&o.restoreSymbols(n,r.data),r))}async resolveOptions(e,t,n=[]){if(typeof e!="object"||e===null||o.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[a,s]of e.entries()){let p=[...n,a];o.isPassthroughPath(p,t)?i[a]=s:r[a]=this.resolveOptions(await s,t,p);}for(let[a,s]of (await Promise.all(r)).entries())s!==void 0&&(i[a]=s);return i}return {...e,...Object.fromEntries(await Promise.all(Object.entries(e).map(async([r,i])=>{let a=[...n,r];return o.isPassthroughPath(a,t)?[r,i]:[r,await this.resolveOptions(await i,t,a)]})))}}static isPassthroughPath(e,t){for(let n of t)if(n.length===e.length+1)for(let[r,i]of n.entries()){let a=typeof e[r]=="number"?Mc:fs;if(r<e.length?i!==e[r]&&i!==a:i!==qt&&i!==Mn)break;if(r===n.length-1)return i===Mn}return false}findPassthroughPaths(e,t=[]){if(e instanceof zod.ZodPromise)return [[...t,Mn]];if(e instanceof zod.ZodOptional)return this.findPassthroughPaths(e.unwrap(),t);if(e instanceof zod.ZodTuple)return [[...t,qt],...e.items.flatMap((n,r)=>this.findPassthroughPaths(n,[...t,r]))];if(e instanceof zod.ZodArray)return [[...t,qt],...this.findPassthroughPaths(e.element,[...t,Mc])];if(e instanceof zod.ZodRecord)return [[...t,qt],...this.findPassthroughPaths(e.valueSchema,[...t,fs])];if(e instanceof zod.ZodObject){let n=[[...t,qt],...Object.entries(e.shape).flatMap(([r,i])=>this.findPassthroughPaths(i,[...t,r]))];return e._def.unknownKeys==="passthrough"&&n.push([...t,fs,Mn]),n}if(e instanceof zod.ZodEffects){let n=e.innerType();return n instanceof zod.ZodAny?[[...t,Mn]]:this.findPassthroughPaths(n,t)}return e instanceof zod.ZodPipeline?this.findPassthroughPaths(e._def.out,t):e instanceof zod.ZodUnion||e instanceof zod.ZodDiscriminatedUnion?e.options.flatMap(n=>this.findPassthroughPaths(n,t)):[[...t,qt]]}static restoreSymbols(e,t){if(Array.isArray(e)&&Array.isArray(t)){for(let[n,r]of e.entries())n<t.length&&o.restoreSymbols(r,t[n]);return}if(!(!Dc__default.default(e)||!Dc__default.default(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&&o.restoreSymbols(r,t[n]);}}};var Zu=zod.z.strictObject({action:zod.z.instanceof(Promise),else:zod.z.instanceof(Promise).optional(),finally:zod.z.instanceof(Promise).optional(),help:zod.z.strictObject({message:zod.z.string().min(1).optional(),links:zod.z.array(zod.z.strictObject({url:zod.z.string().url(),label:zod.z.string().min(1)})).optional(),suggestions:zod.z.array(zod.z.string().min(1)).optional()}).optional()}),Li=class extends v{constructor(){super(Zu);}};var Qu=zod.z.strictObject({name:zod.z.string().min(1),version:zod.z.string().min(1).optional(),optional:zod.z.boolean().optional()}),Ju=zod.z.strictObject({dependencies:zod.z.array(Qu),help:zod.z.strictObject({message:zod.z.string().min(1).optional(),links:zod.z.array(zod.z.strictObject({url:zod.z.string().url(),label:zod.z.string().min(1)})).optional(),suggestions:zod.z.array(zod.z.string().min(1)).optional()}).optional(),result:zod.z.record(zod.z.string().min(1)).optional()}),Fi=class extends v{constructor(){super(Ju);}};var Bu=zod.z.strictObject({source:zod.z.string().min(1),filter:zod.z.string().min(1).optional(),destination:zod.z.string().min(1),result:zod.z.strictObject({destination:zod.z.string().min(1).optional()}).optional()}),ji=class extends v{constructor(){super(Bu);}};var Yu=zod.z.strictObject({dependencies:zod.z.array(zod.z.string().min(1)).min(1),development:zod.z.boolean().optional()}),Vi=class extends v{constructor(){super(Yu);}};var Xu=zod.z.strictObject({pattern:zod.z.string().min(1),caseSensitive:zod.z.boolean().optional()}),Nc=zod.z.union([Xu,zod.z.strictObject({type:zod.z.enum(["and","or"]),matchers:zod.z.array(zod.z.lazy(()=>Nc)).min(1)})]),em=zod.z.strictObject({path:zod.z.string().min(1),matcher:Nc.optional(),limit:zod.z.number().int().positive().optional(),depth:zod.z.number().int().nonnegative().optional(),result:zod.z.string().optional()}),Ui=class extends v{constructor(){super(em);}};var tm=zod.z.strictObject({files:zod.z.array(zod.z.strictObject({path:zod.z.string(),replacements:zod.z.array(zod.z.strictObject({pattern:zod.z.string().refine(o=>{try{return new RegExp(o),!0}catch{return {message:"Invalid regular expression pattern"}}}),caseSensitive:zod.z.boolean().optional(),value:zod.z.union([zod.z.string(),zod.z.number()])})).min(1)})).min(1)}),qi=class extends v{constructor(){super(tm);}};var nm=zod.z.strictObject({slots:zod.z.array(zod.z.string().min(1)).min(1),example:zod.z.boolean().optional()}),Ki=class extends v{constructor(){super(nm);}};var rm=zod.z.strictObject({components:zod.z.array(zod.z.string().min(1)).min(1)}),Gi=class extends v{constructor(){super(rm);}};var im=zod.z.strictObject({name:zod.z.string().min(1),criteria:zod.z.string().min(1)}),It=zod.z.strictObject({title:zod.z.string().optional(),description:zod.z.string().optional()}),om=It.extend({type:zod.z.literal("boolean"),label:zod.z.strictObject({true:zod.z.string(),false:zod.z.string()}).optional(),default:zod.z.boolean().optional()}),am=zod.z.strictObject({label:zod.z.string().optional(),description:zod.z.string().optional(),default:zod.z.boolean().optional(),position:zod.z.number().optional()}),sm=It.extend({type:zod.z.literal("text"),minimumLength:zod.z.number().optional(),maximumLength:zod.z.number().optional(),format:zod.z.string().optional(),pattern:zod.z.string().optional(),choices:zod.z.record(am).optional()}),pm=It.extend({type:zod.z.literal("number"),integer:zod.z.boolean().optional(),minimum:zod.z.number().optional(),maximum:zod.z.number().optional()}),cm=zod.z.lazy(()=>zod.z.strictObject({type:zod.z.lazy(()=>Fc),label:zod.z.string().optional(),description:zod.z.string().optional(),optional:zod.z.boolean().optional(),private:zod.z.boolean().optional(),position:zod.z.number().optional()})),Ss=It.extend({type:zod.z.literal("structure"),attributes:zod.z.record(zod.z.string(),cm)}),lm=It.extend({type:zod.z.literal("list"),items:zod.z.lazy(()=>Fc),itemLabel:zod.z.string().optional(),minimumLength:zod.z.number().optional(),maximumLength:zod.z.number().optional()}),um=zod.z.union([zod.z.string(),zod.z.number(),zod.z.boolean(),zod.z.null()]),hs=zod.z.lazy(()=>zod.z.union([um,zod.z.array(hs),zod.z.record(hs)])),_c=It.extend({type:zod.z.literal("reference"),id:zod.z.string(),properties:zod.z.record(zod.z.string(),hs).optional()}),Lc=It.extend({type:zod.z.literal("union"),types:zod.z.record(zod.z.string(),zod.z.discriminatedUnion("type",[Ss,_c]))}),Fc=zod.z.discriminatedUnion("type",[om,sm,pm,Ss,lm,Lc,_c]),mm=zod.z.discriminatedUnion("type",[Ss,Lc]),dm=zod.z.strictObject({name:zod.z.string().min(1),description:zod.z.string().min(1).optional(),definition:mm}),gm=zod.z.union([zod.z.strictObject({type:zod.z.literal("static"),value:zod.z.string()}),zod.z.strictObject({type:zod.z.literal("dynamic"),expression:zod.z.string(),nullable:zod.z.literal(false),default:zod.z.string()}),zod.z.strictObject({type:zod.z.literal("dynamic"),expression:zod.z.string(),nullable:zod.z.literal(true),default:zod.z.string().optional()})]),fm=zod.z.union([zod.z.strictObject({type:zod.z.literal("static"),value:zod.z.number()}),zod.z.strictObject({type:zod.z.literal("dynamic"),nullable:zod.z.literal(false),default:zod.z.number(),expression:zod.z.string()}),zod.z.strictObject({type:zod.z.literal("dynamic"),nullable:zod.z.literal(true),default:zod.z.number().optional(),expression:zod.z.string()})]),ym=zod.z.union([zod.z.strictObject({type:zod.z.literal("static"),value:zod.z.boolean()}),zod.z.strictObject({type:zod.z.literal("dynamic"),nullable:zod.z.literal(false),default:zod.z.boolean(),expression:zod.z.string()}),zod.z.strictObject({type:zod.z.literal("dynamic"),nullable:zod.z.literal(true),default:zod.z.boolean().optional(),expression:zod.z.string()})]),hm=zod.z.strictObject({type:zod.z.literal("text"),value:gm}),Sm=zod.z.strictObject({type:zod.z.literal("number"),value:fm}),bm=zod.z.strictObject({type:zod.z.literal("boolean"),value:ym}),jc=zod.z.strictObject({type:zod.z.literal("structure"),name:zod.z.string().optional(),attributes:zod.z.record(zod.z.string(),zod.z.lazy(()=>Wc))}),Im=zod.z.strictObject({type:zod.z.literal("list"),items:zod.z.array(zod.z.lazy(()=>Wc))}),Wc=zod.z.discriminatedUnion("type",[hm,Sm,bm,jc,Im]),bs=zod.z.record(zod.z.string(),jc),xm=zod.z.strictObject({name:zod.z.string().min(1),component:zod.z.string().min(1),content:bs}),Vc=zod.z.record(zod.z.string(),bs),vm=zod.z.strictObject({audiences:zod.z.array(zod.z.string()),content:Vc}),Uc=zod.z.strictObject({default:Vc,segmented:zod.z.array(vm)}),wm=zod.z.strictObject({name:zod.z.string(),content:Uc,baseline:zod.z.boolean().optional(),allocation:zod.z.number().min(0).max(1)}),Cm=zod.z.strictObject({name:zod.z.string(),draft:zod.z.boolean().optional(),audiences:zod.z.array(zod.z.string()),slots:zod.z.array(zod.z.string()),experiment:zod.z.strictObject({name:zod.z.string(),goalId:zod.z.string().optional(),crossDevice:zod.z.boolean().optional(),traffic:zod.z.number().min(0).max(1),variants:zod.z.array(wm),content:bs}).optional(),content:Uc}),Pm=zod.z.record(zod.z.string().min(1),zod.z.string().min(1)),$c=zod.z.record(zod.z.number().nonnegative(),zod.z.string().min(1)),zc=zod.z.record(zod.z.string().min(1),zod.z.strictObject({id:zod.z.string().min(1).optional(),version:zod.z.string().min(1).optional()})),km=zod.z.strictObject({resources:zod.z.strictObject({audiences:zod.z.record(zod.z.string().min(1),im).optional(),components:zod.z.record(zod.z.string().min(1),dm).optional(),slots:zod.z.record(zod.z.string().min(1),xm).optional(),experiences:zod.z.array(Cm).optional()}),result:zod.z.strictObject({audiences:Pm.optional(),components:zc.optional(),slots:zc.optional(),experiences:$c.optional(),experiments:$c.optional()}).optional()}),Zi=class extends v{constructor(){super(km);}};var Am=zod.z.union([zod.z.string(),zod.z.number(),zod.z.boolean(),zod.z.null()]),Is=zod.z.lazy(()=>zod.z.union([Am,zod.z.array(Is),zod.z.record(Is)])),Em=zod.z.strictObject({template:zod.z.string().min(1),options:zod.z.record(zod.z.string().min(1),Is).optional()}),Qi=class extends v{constructor(){super(Em);}};var Ji=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 I.fromCause(i)}finally{r.stop();}}};var Rm=zod.z.strictObject({files:zod.z.array(zod.z.string().min(1)).min(1)}),Bi=class extends v{constructor(){super(Rm);}};var Kt=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 U(`No value found for discriminator "${String(e)}".`,{reason:"not_supported"});return t instanceof Function?t():t.get()}};var Yi=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 Tm=zod.z.strictObject({condition:zod.z.boolean(),then:zod.z.instanceof(Promise),else:zod.z.instanceof(Promise).optional()}),eo=class extends v{constructor(){super(Tm);}};var to=class{execute(e,t){let n=t.output,r=e.semantic??"neutral";return e.title===void 0?n.log(e.message,r):n.announce({semantics:r,title:e.title,message:e.message}),Promise.resolve()}};var Om=zod.z.strictObject({semantic:zod.z.enum(["neutral","info","error","warning","success"]).optional(),title:zod.z.string().optional(),message:zod.z.string()}),ro=class extends v{constructor(){super(Om);}};var io=class{execute(e){let{message:t,...n}=e;throw new I(t,{...n,reason:"precondition"})}};var Dm=zod.z.strictObject({title:zod.z.string().min(1).optional(),message:zod.z.string().min(1),links:zod.z.array(zod.z.strictObject({label:zod.z.string().min(1),url:zod.z.string().url()})).optional(),suggestions:zod.z.array(zod.z.string().min(1)).optional(),details:zod.z.array(zod.z.string().min(1)).optional()}),oo=class extends v{constructor(){super(Dm);}};var ao=class{constructor({url:e,provider:t}){this.url=e,this.provider=t;}get(){return this.provider.get(this.url)}};var Nn=class{constructor(e){this.data=e;}get(){return Promise.resolve(this.data)}};var so=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 U("No server found.")}};var po=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 co=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 lo=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 uo=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,a=n!==null?n[1]:"localhost";return {protocol:r!==null&&r[1]==="true"?"https":"http",host:a,...i!==null?{port:i}:{},defaultPort:5173}}};var mo=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 I("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 $n=zod.z.strictObject({result:zod.z.string().optional()}),Mm=$n.extend({type:zod.z.literal("confirmation"),message:zod.z.string(),default:zod.z.boolean().optional()}),vs=zod.z.string(),Nm=zod.z.preprocess(o=>typeof o=="string"?{value:o,label:o}:o,zod.z.strictObject({value:vs,label:zod.z.string().min(1).optional(),disabled:zod.z.boolean().optional()})).transform(o=>({...o,label:o.label??o.value.toString()})),$m=$n.extend({type:zod.z.literal("choice"),message:zod.z.string(),options:zod.z.array(Nm),default:vs.optional()}),zm=zod.z.preprocess(o=>typeof o=="string"?{value:o,label:o}:o,zod.z.strictObject({value:vs,label:zod.z.string().min(1).optional(),selected:zod.z.boolean().optional(),disabled:zod.z.boolean().optional()})).transform(o=>({...o,label:o.label??o.value.toString()})),_m=$n.extend({type:zod.z.literal("multi-choice"),message:zod.z.string(),min:zod.z.number().optional(),max:zod.z.number().optional(),options:zod.z.array(zm)}),Lm=$n.extend({type:zod.z.literal("text"),message:zod.z.string(),default:zod.z.string().optional(),required:zod.z.boolean().optional()}),Fm=$n.extend({type:zod.z.literal("keypress"),message:zod.z.string(),key:zod.z.union([zod.z.literal("enter"),zod.z.literal("space"),zod.z.string().length(1)]).optional()}),jm=zod.z.discriminatedUnion("type",[Mm,$m,_m,Lm,Fm]),go=class extends v{constructor(){super(jm);}};var fo=class{constructor({serverProvider:e}){this.provider=e;}async execute(e,t){let{output:n}=t,r=n.notify("Checking server"),i;try{i=await this.startServer(r);}finally{r.stop();}e.result?.url!==void 0&&t.set(e.result.url,i.url.toString()),e.result?.owned!==void 0&&t.set(e.result.owned,i.owned);}async startServer(e){let t=await this.provider.get();if(t===null)throw new d("No server detected.");let n=await t.getStatus();return n.running?{url:n.url,owned:false}:(e.update("Starting server"),{url:await t.start(),owned:true})}};var Wm=zod.z.strictObject({result:zod.z.strictObject({url:zod.z.string().optional(),owned:zod.z.string().optional()}).optional()}),ho=class extends v{constructor(){super(Wm);}};var So=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){throw I.fromCause(r,{tracing:[{name:n.name,source:Vt.get(n)??void 0}]})}}run({name:e,...t},n){let r=this.actions[e];if(r===void 0)throw new I(`Unsupported action \`${e}\`.`,{reason:"invalid_input"});return r.execute(t,n)}};var qc=zod.z.object({name:zod.z.string().min(1)}).passthrough(),Vm=zod.z.strictObject({actions:zod.z.union([qc,zod.z.array(qc)])}),bo=class extends v{constructor(){super(Vm);}};var Io=class{async execute(e,t){let{output:n}=t;await n.open(e.url);}};var Um=zod.z.strictObject({url:zod.z.string().url()}),xo=class extends v{constructor(){super(Um);}};var qm=zod.z.union([zod.z.string(),zod.z.number(),zod.z.boolean(),zod.z.null()]),ws=zod.z.lazy(()=>zod.z.union([qm,zod.z.array(ws),zod.z.record(ws)])),Hm=zod.z.strictObject({variables:zod.z.record(zod.z.string(),ws)}),vo=class extends v{constructor(){super(Hm);}};var wo=class{execute(e,t){for(let[n,r]of Object.entries(e.variables))t.set(n,r);return Promise.resolve()}};var Co=class{constructor({serverProvider:e}){this.provider=e;}async execute(e,t){let{output:n}=t,r=n.notify("Stopping server"),i=await this.provider.get();if(i===null)throw new d("No server detected.");try{await i.stop();}finally{r.stop();}}};var Gm=zod.z.strictObject({}),Po=class extends v{constructor(){super(Gm);}};var Gt=class o extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var ko=class{constructor(e){this.configuration=e;}async getStatus(){let e=await this.findAddress();return e===null?{running:false}:{running:true,url:e}}async start(){let{commandExecutor:e,command:t,workingDirectory:n,processObserver:r}=this.configuration;try{this.execution=e.run(t,{workingDirectory:n.get()});}catch(s){throw new Gt("Failed to start server.",{cause:s})}let i=()=>this.stop();if(this.execution.onExit(()=>{this.execution=void 0,r.off("exit",i);}),!this.execution.running)throw new Gt("Failed to start server.");r.on("exit",i);let a=await this.waitStart();if(a===null)throw new Gt("Server is unreachable.");return a}async stop(){await this?.execution?.kill("SIGINT"),this.execution=void 0;}async waitStart(){let{startupCheckDelay:e,startupTimeout:t}=this.configuration,n=new AbortController;setTimeout(()=>n.abort(),t).unref();let i=()=>new Promise(a=>{setTimeout(a,e);});do{let a=await this.findAddress(n);if(a!==null)return a;await i();}while(!n.signal.aborted);return null}async findAddress(e){let{lookupTimeout:t,lookupMaxPorts:n,server:{protocol:r,host:i,port:a,defaultPort:s}}=this.configuration,p=a??s,c=a??s+n-1,l=new AbortController;e!==void 0&&e.signal.addEventListener("abort",()=>l.abort()),setTimeout(()=>l.abort(),t).unref();let f=new URL(`${r}://${i}`);for(let b=p;b<=c;b++){try{return f.port=b.toString(),await fetch(f,{method:"HEAD",signal:l.signal}),f}catch{}if(l.signal.aborted)break}return null}};var Ao=class{constructor(e){this.configuration=e;}create(e){return new ko({...this.configuration,command:e.command,server:{protocol:e.protocol,host:e.host,defaultPort:e.defaultPort,port:e.port}})}};var Zm=zod.z.strictObject({path:zod.z.string()}),Eo=class extends v{constructor(){super(Zm);}};var Ro=class{constructor({fileSystem:e,rootDirectory:t,currentDirectory:n}){this.fileSystem=e,this.rootDirectory=t,this.currentDirectory=n;}execute(e){let t=this.fileSystem.isAbsolutePath(e.path)?e.path:this.fileSystem.joinPaths(this.currentDirectory.get(),e.path);if(!this.fileSystem.isSubPath(this.rootDirectory,t))throw new I("Cannot change to a directory outside the current working directory.",{reason:"precondition",details:[`Working directory: ${this.rootDirectory}`,`Target directory: ${t}`]});return this.currentDirectory.setCurrentDirectory(t),Promise.resolve()}};var To=class{constructor(){this.lines=[[]];this.cursor={row:0,column:0};this.ansiSequence="";this.lines=[[]];}buffer(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"){this.cursor.column=0;continue}if(n===`
1769
+ ${p}`,{reason:"invalid_input",url:e,violations:[{path:r,message:"Imported template creates a circular dependency."}]})}let{url:i,value:a}=await this.fileProvider.get(e),s;try{s=o.cleanJson(JsonParser.parse(a));}catch(p){throw new ve("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 Ka=Symbol("any-property"),cc=Symbol("any-index"),In=Symbol("passthrough"),zt=Symbol("resolve"),v=class o extends Q{async validate(e){let t=this.findPassthroughPaths(this.schema),n;try{n=await this.resolveOptions(e,t);}catch(r){if(r instanceof ve)return {valid:false,violations:r.violations};throw r}return super.validate(n).then(r=>(r.valid&&o.restoreSymbols(n,r.data),r))}async resolveOptions(e,t,n=[]){if(typeof e!="object"||e===null||o.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[a,s]of e.entries()){let p=[...n,a];o.isPassthroughPath(p,t)?i[a]=s:r[a]=this.resolveOptions(await s,t,p);}for(let[a,s]of (await Promise.all(r)).entries())s!==void 0&&(i[a]=s);return i}return {...e,...Object.fromEntries(await Promise.all(Object.entries(e).map(async([r,i])=>{let a=[...n,r];return o.isPassthroughPath(a,t)?[r,i]:[r,await this.resolveOptions(await i,t,a)]})))}}static isPassthroughPath(e,t){for(let n of t)if(n.length===e.length+1)for(let[r,i]of n.entries()){let a=typeof e[r]=="number"?cc:Ka;if(r<e.length?i!==e[r]&&i!==a:i!==zt&&i!==In)break;if(r===n.length-1)return i===In}return false}findPassthroughPaths(e,t=[]){if(e instanceof ZodPromise)return [[...t,In]];if(e instanceof ZodOptional)return this.findPassthroughPaths(e.unwrap(),t);if(e instanceof ZodTuple)return [[...t,zt],...e.items.flatMap((n,r)=>this.findPassthroughPaths(n,[...t,r]))];if(e instanceof ZodArray)return [[...t,zt],...this.findPassthroughPaths(e.element,[...t,cc])];if(e instanceof ZodRecord)return [[...t,zt],...this.findPassthroughPaths(e.valueSchema,[...t,Ka])];if(e instanceof ZodObject){let n=[[...t,zt],...Object.entries(e.shape).flatMap(([r,i])=>this.findPassthroughPaths(i,[...t,r]))];return e._def.unknownKeys==="passthrough"&&n.push([...t,Ka,In]),n}if(e instanceof ZodEffects){let n=e.innerType();return n instanceof ZodAny?[[...t,In]]: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,zt]]}static restoreSymbols(e,t){if(Array.isArray(e)&&Array.isArray(t)){for(let[n,r]of e.entries())n<t.length&&o.restoreSymbols(r,t[n]);return}if(!(!pc(e)||!pc(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&&o.restoreSymbols(r,t[n]);}}};var Pu=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()}),yi=class extends v{constructor(){super(Pu);}};var Cu=z.strictObject({name:z.string().min(1),version:z.string().min(1).optional(),optional:z.boolean().optional()}),ku=z.strictObject({dependencies:z.array(Cu),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()}),hi=class extends v{constructor(){super(ku);}};var Au=z.strictObject({source:z.string().min(1),filter:z.string().min(1).optional(),destination:z.string().min(1),result:z.strictObject({destination:z.string().min(1).optional()}).optional()}),Si=class extends v{constructor(){super(Au);}};var Eu=z.strictObject({dependencies:z.array(z.string().min(1)).min(1),development:z.boolean().optional()}),Ii=class extends v{constructor(){super(Eu);}};var Ru=z.strictObject({pattern:z.string().min(1),caseSensitive:z.boolean().optional()}),lc=z.union([Ru,z.strictObject({type:z.enum(["and","or"]),matchers:z.array(z.lazy(()=>lc)).min(1)})]),Tu=z.strictObject({path:z.string().min(1),matcher:lc.optional(),limit:z.number().int().positive().optional(),depth:z.number().int().nonnegative().optional(),result:z.string().optional()}),xi=class extends v{constructor(){super(Tu);}};var Ou=z.strictObject({files:z.array(z.strictObject({path:z.string(),replacements:z.array(z.strictObject({pattern:z.string().refine(o=>{try{return new RegExp(o),!0}catch{return {message:"Invalid regular expression pattern"}}}),caseSensitive:z.boolean().optional(),value:z.union([z.string(),z.number()])})).min(1)})).min(1)}),vi=class extends v{constructor(){super(Ou);}};var Du=z.strictObject({slots:z.array(z.string().min(1)).min(1),example:z.boolean().optional()}),Pi=class extends v{constructor(){super(Du);}};var Mu=z.strictObject({components:z.array(z.string().min(1)).min(1)}),Ci=class extends v{constructor(){super(Mu);}};var Nu=z.strictObject({name:z.string().min(1),criteria:z.string().min(1)}),dt=z.strictObject({title:z.string().optional(),description:z.string().optional()}),$u=dt.extend({type:z.literal("boolean"),label:z.strictObject({true:z.string(),false:z.string()}).optional(),default:z.boolean().optional()}),zu=z.strictObject({label:z.string().optional(),description:z.string().optional(),default:z.boolean().optional(),position:z.number().optional()}),_u=dt.extend({type:z.literal("text"),minimumLength:z.number().optional(),maximumLength:z.number().optional(),format:z.string().optional(),pattern:z.string().optional(),choices:z.record(zu).optional()}),Lu=dt.extend({type:z.literal("number"),integer:z.boolean().optional(),minimum:z.number().optional(),maximum:z.number().optional()}),Fu=z.lazy(()=>z.strictObject({type:z.lazy(()=>fc),label:z.string().optional(),description:z.string().optional(),optional:z.boolean().optional(),private:z.boolean().optional(),position:z.number().optional()})),Qa=dt.extend({type:z.literal("structure"),attributes:z.record(z.string(),Fu)}),ju=dt.extend({type:z.literal("list"),items:z.lazy(()=>fc),itemLabel:z.string().optional(),minimumLength:z.number().optional(),maximumLength:z.number().optional()}),Wu=z.union([z.string(),z.number(),z.boolean(),z.null()]),Ja=z.lazy(()=>z.union([Wu,z.array(Ja),z.record(Ja)])),dc=dt.extend({type:z.literal("reference"),id:z.string(),properties:z.record(z.string(),Ja).optional()}),gc=dt.extend({type:z.literal("union"),types:z.record(z.string(),z.discriminatedUnion("type",[Qa,dc]))}),fc=z.discriminatedUnion("type",[$u,_u,Lu,Qa,ju,gc,dc]),Vu=z.discriminatedUnion("type",[Qa,gc]),Uu=z.strictObject({name:z.string().min(1),description:z.string().min(1).optional(),definition:Vu}),qu=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()})]),Gu=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()})]),Ku=z.strictObject({type:z.literal("text"),value:qu}),Zu=z.strictObject({type:z.literal("number"),value:Hu}),Ju=z.strictObject({type:z.literal("boolean"),value:Gu}),yc=z.strictObject({type:z.literal("structure"),name:z.string().optional(),attributes:z.record(z.string(),z.lazy(()=>hc))}),Qu=z.strictObject({type:z.literal("list"),items:z.array(z.lazy(()=>hc))}),hc=z.discriminatedUnion("type",[Ku,Zu,Ju,yc,Qu]),Ba=z.record(z.string(),yc),Bu=z.strictObject({name:z.string().min(1),component:z.string().min(1),content:Ba}),Sc=z.record(z.string(),Ba),Yu=z.strictObject({audiences:z.array(z.string()),content:Sc}),bc=z.strictObject({default:Sc,segmented:z.array(Yu)}),Xu=z.strictObject({name:z.string(),content:bc,baseline:z.boolean().optional(),allocation:z.number().min(0).max(1)}),em=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(Xu),content:Ba}).optional(),content:bc}),tm=z.record(z.string().min(1),z.string().min(1)),uc=z.record(z.number().nonnegative(),z.string().min(1)),mc=z.record(z.string().min(1),z.strictObject({id:z.string().min(1).optional(),version:z.string().min(1).optional()})),nm=z.strictObject({resources:z.strictObject({audiences:z.record(z.string().min(1),Nu).optional(),components:z.record(z.string().min(1),Uu).optional(),slots:z.record(z.string().min(1),Bu).optional(),experiences:z.array(em).optional()}),result:z.strictObject({audiences:tm.optional(),components:mc.optional(),slots:mc.optional(),experiences:uc.optional(),experiments:uc.optional()}).optional()}),ki=class extends v{constructor(){super(nm);}};var rm=z.union([z.string(),z.number(),z.boolean(),z.null()]),Ya=z.lazy(()=>z.union([rm,z.array(Ya),z.record(Ya)])),im=z.strictObject({template:z.string().min(1),options:z.record(z.string().min(1),Ya).optional()}),Ai=class extends v{constructor(){super(im);}};var Ei=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 I.fromCause(i)}finally{r.stop();}}};var om=z.strictObject({files:z.array(z.string().min(1)).min(1)}),Ri=class extends v{constructor(){super(om);}};var Lt=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 U(`No value found for discriminator "${String(e)}".`,{reason:"not_supported"});return t instanceof Function?t():t.get()}};var Ti=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 am=z.strictObject({condition:z.boolean(),then:z.instanceof(Promise),else:z.instanceof(Promise).optional()}),Di=class extends v{constructor(){super(am);}};var Mi=class{execute(e,t){let n=t.output,r=e.semantic??"neutral";return e.title===void 0?n.log(e.message,r):n.announce({semantics:r,title:e.title,message:e.message}),Promise.resolve()}};var sm=z.strictObject({semantic:z.enum(["neutral","info","error","warning","success"]).optional(),title:z.string().optional(),message:z.string()}),$i=class extends v{constructor(){super(sm);}};var zi=class{execute(e){let{message:t,...n}=e;throw new I(t,{...n,reason:"precondition"})}};var pm=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()}),_i=class extends v{constructor(){super(pm);}};var Li=class{constructor({url:e,provider:t}){this.url=e,this.provider=t;}get(){return this.provider.get(this.url)}};var xn=class{constructor(e){this.data=e;}get(){return Promise.resolve(this.data)}};var Fi=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 U("No server found.")}};var ji=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 Wi=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 Vi=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 Ui=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,a=n!==null?n[1]:"localhost";return {protocol:r!==null&&r[1]==="true"?"https":"http",host:a,...i!==null?{port:i}:{},defaultPort:5173}}};var qi=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 I("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 vn=z.strictObject({result:z.string().optional()}),cm=vn.extend({type:z.literal("confirmation"),message:z.string(),default:z.boolean().optional()}),es=z.string(),lm=z.preprocess(o=>typeof o=="string"?{value:o,label:o}:o,z.strictObject({value:es,label:z.string().min(1).optional(),disabled:z.boolean().optional()})).transform(o=>({...o,label:o.label??o.value.toString()})),um=vn.extend({type:z.literal("choice"),message:z.string(),options:z.array(lm),default:es.optional()}),mm=z.preprocess(o=>typeof o=="string"?{value:o,label:o}:o,z.strictObject({value:es,label:z.string().min(1).optional(),selected:z.boolean().optional(),disabled:z.boolean().optional()})).transform(o=>({...o,label:o.label??o.value.toString()})),dm=vn.extend({type:z.literal("multi-choice"),message:z.string(),min:z.number().optional(),max:z.number().optional(),options:z.array(mm)}),gm=vn.extend({type:z.literal("text"),message:z.string(),default:z.string().optional(),required:z.boolean().optional()}),fm=vn.extend({type:z.literal("keypress"),message:z.string(),key:z.union([z.literal("enter"),z.literal("space"),z.string().length(1)]).optional()}),ym=z.discriminatedUnion("type",[cm,um,dm,gm,fm]),Hi=class extends v{constructor(){super(ym);}};var Gi=class{constructor({serverProvider:e}){this.provider=e;}async execute(e,t){let{output:n}=t,r=n.notify("Checking server"),i;try{i=await this.startServer(r);}finally{r.stop();}e.result?.url!==void 0&&t.set(e.result.url,i.url.toString()),e.result?.owned!==void 0&&t.set(e.result.owned,i.owned);}async startServer(e){let t=await this.provider.get();if(t===null)throw new d("No server detected.");let n=await t.getStatus();return n.running?{url:n.url,owned:false}:(e.update("Starting server"),{url:await t.start(),owned:true})}};var hm=z.strictObject({result:z.strictObject({url:z.string().optional(),owned:z.string().optional()}).optional()}),Zi=class extends v{constructor(){super(hm);}};var Ji=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){throw I.fromCause(r,{tracing:[{name:n.name,source:Sn.get(n)??void 0}]})}}run({name:e,...t},n){let r=this.actions[e];if(r===void 0)throw new I(`Unsupported action \`${e}\`.`,{reason:"invalid_input"});return r.execute(t,n)}};var Ic=z.object({name:z.string().min(1)}).passthrough(),Sm=z.strictObject({actions:z.union([Ic,z.array(Ic)])}),Qi=class extends v{constructor(){super(Sm);}};var Bi=class{async execute(e,t){let{output:n}=t;await n.open(e.url);}};var bm=z.strictObject({url:z.string().url()}),Yi=class extends v{constructor(){super(bm);}};var Im=z.union([z.string(),z.number(),z.boolean(),z.null()]),ts=z.lazy(()=>z.union([Im,z.array(ts),z.record(ts)])),xm=z.strictObject({variables:z.record(z.string(),ts)}),Xi=class extends v{constructor(){super(xm);}};var eo=class{execute(e,t){for(let[n,r]of Object.entries(e.variables))t.set(n,r);return Promise.resolve()}};var to=class{constructor({serverProvider:e}){this.provider=e;}async execute(e,t){let{output:n}=t,r=n.notify("Stopping server"),i=await this.provider.get();if(i===null)throw new d("No server detected.");try{await i.stop();}finally{r.stop();}}};var wm=z.strictObject({}),no=class extends v{constructor(){super(wm);}};var Ft=class o extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var ro=class{constructor(e){this.configuration=e;}async getStatus(){let e=await this.findAddress();return e===null?{running:false}:{running:true,url:e}}async start(){let{commandExecutor:e,command:t,workingDirectory:n,processObserver:r}=this.configuration;try{this.execution=e.run(t,{workingDirectory:n.get()});}catch(s){throw new Ft("Failed to start server.",{cause:s})}let i=()=>this.stop();if(this.execution.onExit(()=>{this.execution=void 0,r.off("exit",i);}),!this.execution.running)throw new Ft("Failed to start server.");r.on("exit",i);let a=await this.waitStart();if(a===null)throw new Ft("Server is unreachable.");return a}async stop(){await this?.execution?.kill("SIGINT"),this.execution=void 0;}async waitStart(){let{startupCheckDelay:e,startupTimeout:t}=this.configuration,n=new AbortController;setTimeout(()=>n.abort(),t).unref();let i=()=>new Promise(a=>{setTimeout(a,e);});do{let a=await this.findAddress(n);if(a!==null)return a;await i();}while(!n.signal.aborted);return null}async findAddress(e){let{lookupTimeout:t,lookupMaxPorts:n,server:{protocol:r,host:i,port:a,defaultPort:s}}=this.configuration,p=a??s,c=a??s+n-1,l=new AbortController;e!==void 0&&e.signal.addEventListener("abort",()=>l.abort()),setTimeout(()=>l.abort(),t).unref();let f=new URL(`${r}://${i}`);for(let b=p;b<=c;b++){try{return f.port=b.toString(),await fetch(f,{method:"HEAD",signal:l.signal}),f}catch{}if(l.signal.aborted)break}return null}};var io=class{constructor(e){this.configuration=e;}create(e){return new ro({...this.configuration,command:e.command,server:{protocol:e.protocol,host:e.host,defaultPort:e.defaultPort,port:e.port}})}};var Pm=z.strictObject({path:z.string()}),oo=class extends v{constructor(){super(Pm);}};var ao=class{constructor({fileSystem:e,rootDirectory:t,currentDirectory:n}){this.fileSystem=e,this.rootDirectory=t,this.currentDirectory=n;}execute(e){let t=this.fileSystem.isAbsolutePath(e.path)?e.path:this.fileSystem.joinPaths(this.currentDirectory.get(),e.path);if(!this.fileSystem.isSubPath(this.rootDirectory,t))throw new I("Cannot change to a directory outside the current working directory.",{reason:"precondition",details:[`Working directory: ${this.rootDirectory}`,`Target directory: ${t}`]});return this.currentDirectory.setCurrentDirectory(t),Promise.resolve()}};var so=class{constructor(){this.lines=[[]];this.cursor={row:0,column:0};this.ansiSequence="";this.lines=[[]];}buffer(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"){this.cursor.column=0;continue}if(n===`
1769
1770
  `){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)return;let[,n,r]=t,i=n?.split(";").map(a=>a===""?0:Number.parseInt(a,10))??[];switch(r){case "A":this.cursor.row=Math.max(0,this.cursor.row-(i[0]??1));break;case "B":this.cursor.row+=i[0]??1,this.resize(this.cursor.row);break;case "C":this.cursor.column+=i[0]??1;break;case "D":this.cursor.column=Math.max(0,this.cursor.column-(i[0]??1));break;case "K":i[0]===2?this.lines[this.cursor.row]=[]:i[0]===0&&(this.lines[this.cursor.row]=this.lines[this.cursor.row].slice(0,this.cursor.column));break;case "J":i[0]===2?(this.lines=[[]],this.cursor={row:0,column:0}):i[0]===0&&(this.lines=this.lines.slice(0,this.cursor.row+1),this.lines[this.cursor.row]=this.lines[this.cursor.row].slice(0,this.cursor.column));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([]);}toString(){return this.lines.map(e=>e.join("")).join(`
1770
- `).trim()}toRawString(){return Qm__default.default(this.toString())}};var Do=class Do{constructor(e){this.configuration=e;}async execute(e,t){let{input:n,output:r}=t,{sourceChecker:i}=this.configuration,s=await(await this.getPackageManager(e.runner)).getPackageCommand(e.package,e.arguments),p=[s.name.split(/[\\/]/).pop(),...s.arguments??[]].join(" ");if(!await i.test(t.baseUrl)){if(n===void 0)throw new I("Action requires explicit user confirmation.",{reason:"precondition",details:["Retry in interactive mode."]});if(r.warn(`This template will run the command \`${p}\``),!await n.confirm({message:"Continue?",default:true}))throw new I("Permission to run command denied.",{reason:"precondition",details:[`Command: ${p}`]})}let c=r.notify(`Running \`${p}\``);try{await this.executeCommand(s,e.interactions);}catch(l){throw I.fromCause(l)}finally{c.stop();}}getPackageManager(e){return e===void 0?this.configuration.packageManager:this.configuration.packageManagerProvider.get(e)}async executeCommand(e,t=[]){let{workingDirectory:n,commandExecutor:r,commandTimeout:i}=this.configuration,a=r.run(e,{workingDirectory:n.get(),timeout:i}),s=[...t],p=new To;for await(let m of a.output){p.buffer(m);for(let[f,b]of s.entries())if(p.toRawString().includes(b.when)){b.once===true&&s.splice(f,1);for(let A of b.then)await a.write(Do.INPUT_MAP[A]??A);break}}let c=-1,l;try{c=await a.wait();}catch(m){l=m;}if(c!==0)throw new I(`Command failed with output:
1771
+ `).trim()}toRawString(){return Cm(this.toString())}};var po=class o{static{this.INPUT_MAP={"[space]":" ","[enter]":`
1772
+ `,"[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,s=await(await this.getPackageManager(e.runner)).getPackageCommand(e.package,e.arguments),p=[s.name.split(/[\\/]/).pop(),...s.arguments??[]].join(" ");if(!await i.test(t.baseUrl)){if(n===void 0)throw new I("Action requires explicit user confirmation.",{reason:"precondition",details:["Retry in interactive mode."]});if(r.warn(`This template will run the command \`${p}\``),!await n.confirm({message:"Continue?",default:true}))throw new I("Permission to run command denied.",{reason:"precondition",details:[`Command: ${p}`]})}let c=r.notify(`Running \`${p}\``);try{await this.executeCommand(s,e.interactions);}catch(l){throw I.fromCause(l)}finally{c.stop();}}getPackageManager(e){return e===void 0?this.configuration.packageManager:this.configuration.packageManagerProvider.get(e)}async executeCommand(e,t=[]){let{workingDirectory:n,commandExecutor:r,commandTimeout:i}=this.configuration,a=r.run(e,{workingDirectory:n.get(),timeout:i}),s=[...t],p=new so;for await(let m of a.output){p.buffer(m);for(let[f,b]of s.entries())if(p.toRawString().includes(b.when)){b.once===true&&s.splice(f,1);for(let A of b.then)await a.write(o.INPUT_MAP[A]??A);break}}let c=-1,l;try{c=await a.wait();}catch(m){l=m;}if(c!==0)throw new I(`Command failed with output:
1771
1773
 
1772
- ${p.toString()}`,{reason:"unexpected_result",cause:l})}};Do.INPUT_MAP={"[space]":" ","[enter]":`
1773
- `,"[down]":"\x1B[A","[up]":"\x1B[B","[left]":"\x1B[C","[right]":"\x1B[D","[backspace]":"\b"};var Oo=Do;var Jm=zod.z.strictObject({package:zod.z.string(),arguments:zod.z.array(zod.z.string()).optional(),runner:zod.z.string().optional(),interactions:zod.z.array(zod.z.object({when:zod.z.string(),once:zod.z.boolean().optional(),then:zod.z.array(zod.z.string())})).optional()}),Mo=class extends v{constructor(){super(Jm);}};var Ie=class o extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var at=class{constructor(e){this.projectDirectory=e.projectDirectory,this.fileSystem=e.fileSystem,this.agent=e.agent,this.packageValidator=e.packageValidator;}isInstalled(){return this.agent.isInstalled()}isProject(){return this.fileSystem.exists(this.getProjectManifestPath())}addDependencies(e,t){return this.agent.addDependencies(e,t)}installDependencies(){return this.agent.installDependencies()}getPackageCommand(e,t=[]){return this.agent.getPackageCommand(e,t)}getScriptCommand(e,t=[]){return this.agent.getScriptCommand(e,t)}async hasDirectDependency(e,t){let n=await this.readManifest(this.getProjectManifestPath());if(n===null)return false;let r=n.dependencies?.[e]??n.devDependencies?.[e];return r===void 0?false:t===void 0||Gc__default.default.satisfies(r,t)}async hasDependency(e,t){let n=await this.getDependency(e);return n===null?false:t===void 0||n.version!==null&&Gc__default.default.satisfies(n.version,t)}async getDependency(e){let t=this.getPackageManifestPath(e),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 Ie("Package file not found in the project.",{reason:"precondition",details:[`File: ${n}`]});let r=await this.fileSystem.readTextFile(n),i=json5Parser.JsonParser.parse(r,json5Parser.JsonObjectNode);if(i.has("scripts")){let a=i.get("scripts",json5Parser.JsonObjectNode),s=t;if(a.has(e)){let c=a.get(e).toJSON();if(typeof c=="string"&&c.includes(t))return;s=`${c} && ${t}`;}a.set(e,s);}else i.set("scripts",{[e]:t});await this.fileSystem.writeTextFile(n,i.toString(),{overwrite:true});}getPackageManifestPath(e){return this.fileSystem.joinPaths(this.projectDirectory.get(),"node_modules",e,"package.json")}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 je=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}addDependencies(e,t=false){return this.run(this.createAddDependencyCommand(e,t))}installDependencies(){return this.run(this.createInstallDependenciesCommand())}getPackageCommand(e,t){return this.createPackageCommand(e,t)}getScriptCommand(e,t){return this.createScriptCommand(e,t)}async run(e,t={}){if(!await this.isInstalled())throw new Ie(`Package manager \`${this.getCommandName()}\` is not installed.`);if(await this.commandRunner.run(e,{...t,workingDirectory:this.projectDirectory.get()}).wait()!==0)throw new Ie(`Failed to run \`${e.name}\` command.`)}getExecutable(e){return this.executableLocator.locate(e)}};var No=class extends je{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 this.getCommand(this.getCommandName(),["install",...t?["--save-dev"]:[],...e])}createInstallDependenciesCommand(){return this.getCommand(this.getCommandName(),["install"])}getCommand(e,t=[]){return {name:e,arguments:t}}};var $o=class extends je{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 this.getCommand(this.getCommandName(),["add",...t?["--dev"]:[],...e])}createInstallDependenciesCommand(){return this.getCommand(this.getCommandName(),["install"])}getCommand(e,t=[]){return {name:e,arguments:t}}};var zo=class extends je{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 this.getCommand(["install",...t?["--dev"]:[],...e])}createInstallDependenciesCommand(){return this.getCommand(["install"])}getCommand(e=[]){return {name:this.getCommandName(),arguments:e}}};var _o=class extends je{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 this.getCommand(["install",...t?["--save-dev"]:[],...e])}createInstallDependenciesCommand(){return this.getCommand(["install"])}getCommand(e=[]){return {name:this.getCommandName(),arguments:e}}};var Zt=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 We=class o extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var Lo=class{constructor(e={}){this.configuration=e;}run(e,t={}){let n=nodePty.spawn(e.name,e.arguments??[],{...this.configuration,cwd:t.workingDirectory??this.configuration.cwd}),r=new Zt;n.onData(c=>r.push(c));let i,a=null,s=false;t.timeout!==void 0&&(i=setTimeout(()=>{a===null&&(n.kill("SIGINT"),s=true);},t.timeout),i.unref());let p=[];return n.onExit(c=>{r.close(),a=c.exitCode;for(let l of p)l(c.exitCode);}),{output:r,get running(){return a===null},read:async()=>{let c="";for await(let l of r)c+=l;return c},onExit:c=>(p.push(c),()=>{let l=p.indexOf(c);l!==-1&&p.splice(l,1);}),write:c=>(n.write(c),Promise.resolve()),wait:()=>s?Promise.reject(new We("Command timed out.",{reason:"precondition"})):a!==null?Promise.resolve(a):new Promise(c=>{n.onExit(l=>{c(l.exitCode);});}),kill:c=>{if(i!==void 0&&clearTimeout(i),a!==null)return Promise.resolve();let l=new Promise(m=>{n.onExit(()=>{m();});});return n.kill(c),l}}}};var Fo=class o{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 a=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 a===null?null:{rootConfigPath:a.rootConfigPath,matchedConfigPath:a.matchedConfigPath,baseUrl:this.fileSystem.joinPaths(this.fileSystem.getDirectoryName(a.matchedConfigPath),a.compilerOptions?.baseUrl??"."),paths:a.compilerOptions?.paths??{}}}async locateConfig(e,t,n=false){for(let i of t){let a=this.fileSystem.joinPaths(e,i);if(await this.fileSystem.exists(a))return a}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,a=await this.parseConfig(t);if(a?.extends!==void 0){let s=await this.locateParentConfig(r,this.fileSystem.getDirectoryName(t),a.extends);if(s!==null){let p=await this.resolveConfig({...e,configPath:s});p!==null&&(a=o.mergeConfig(a,p));}}if(a?.references!==void 0&&i.length>0){let{references:s,...p}=a;for(let c of a.references){let l=this.fileSystem.joinPaths(this.fileSystem.getDirectoryName(t),c.path),m=l.endsWith(".json")?l:await this.locateConfig(l,n);if(m===null)continue;let f=await this.resolveConfig({...e,configPath:m});if(f?.include!==void 0)for(let b of i){let A=this.fileSystem.joinPaths("./",this.fileSystem.getRelativePath(this.fileSystem.getDirectoryName(m),b));for(let w of f.include){let y=new minimatch.Minimatch(w,{partial:true,magicalBraces:true});if(!y.hasMagic()&&!w.includes(".")&&(y=new minimatch.Minimatch(`${w.replace(/\/?$/,"")}/**/*`,{partial:true})),y.match(A))return o.mergeConfig({...f,rootConfigPath:a.rootConfigPath},p)}}}}return a}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 a=this.fileSystem.joinPaths(e,"node_modules",r);return await this.fileSystem.exists(a)?a:null}async parseConfig(e){let t;try{t=json5Parser.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 jo=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=await this.tsConfigLoader.load(n,{sourcePaths:[this.fileSystem.joinPaths(n,t)]}),i=/\.m(?:js|ts)?$/.test(e)?e:e.replace(/\.(ts|js)x?$/,""),a=this.fileSystem.joinPaths(n,i);if(r!==null){let p=0,c=null;for(let[l,m]of Object.entries(r.paths)){let f=this.fileSystem.normalizeSeparators(l.replace(/\*$/,""));for(let b of m){let A=b.replace(/\*$/,""),w=this.fileSystem.joinPaths(r.baseUrl,A);if(a.startsWith(w)){let y=A.length;if(y>p){p=y;let M=a.slice(w.length).replace(/^[\\/]+/,"");c=f+M;}}}}if(c!==null)return Promise.resolve(c.replace(/\\+/g,"/"))}let s=this.fileSystem.getRelativePath(this.fileSystem.joinPaths(n,t),this.fileSystem.joinPaths(n,i));return Promise.resolve(s.replace(/\\/g,"/"))}};var ed=zod.z.object({extends:zod.z.string().optional(),references:zod.z.array(zod.z.object({path:zod.z.string()})).optional(),include:zod.z.array(zod.z.string()).optional(),compilerOptions:zod.z.object({baseUrl:zod.z.string().optional(),paths:zod.z.record(zod.z.array(zod.z.string())).optional()}).optional()}),Wo=class extends B{constructor(){super(ed);}};var _n=class{constructor(e){this.provider=e;}get manager(){return Promise.resolve(this.provider.get()).catch(e=>{throw e instanceof U?new Ie(e.message,e.help):e})}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 installDependencies(){return (await this.manager).installDependencies()}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)}};var Vo=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 U(`No value found for key \`${e}\`.`,{reason:"not_found"});return Promise.resolve(t)}};var Uo=class{isInstalled(){return Promise.resolve(false)}addDependencies(){return this.fail()}installDependencies(){return this.fail()}getPackageCommand(){return this.fail()}getScriptCommand(){return this.fail()}fail(){throw new Ie("The package manager is not installed")}};var Qt=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 Ne=class{constructor(e){this.callback=e;}get(...e){return this.callback(...e)}};var Jt=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 Ln=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 qo=class{constructor({packageManager:e}){this.packageManager=e;}test(){return this.packageManager.isProject()}};var Ho=class{constructor({currentDirectory:e}={}){this.currentDirectory=e;}run(e,t={}){let n=t.timeout!==void 0?AbortSignal.timeout(t.timeout):void 0,r=child_process.spawn(e.name,e.arguments,{stdio:["pipe","pipe","pipe"],cwd:t?.workingDirectory??this.currentDirectory?.get(),signal:n}),i=[];r.on("error",c=>{for(let l of i)l(n?.aborted===true?new We("Command timed out.",{reason:"precondition",cause:c}):new We("Failed to run command.",{cause:c}));});let a=new Zt;r.stdout.on("data",c=>{a.push(c.toString());}),r.stderr.on("data",c=>{a.push(c.toString());});let s=null,p=[];return r.on("exit",c=>{a.close(),s=c??1;for(let l of p)l(s);}),{output:a,get running(){return s===null},onExit:c=>(p.push(c),()=>{let l=p.indexOf(c);l!==-1&&p.splice(l,1);}),write:c=>new Promise((l,m)=>{r.stdin.write(c,f=>{f===null?l():m(f);});}),read:async()=>{let c="";for await(let l of a)c+=l;return c},wait:()=>new Promise((c,l)=>{i.push(l),r.on("exit",m=>{c(m??1);});}),kill:c=>new Promise((l,m)=>{if(s!==null){l();return}r.stdout.destroy(),r.stderr.destroy(),r.stdin.destroy(),r.kill(c)?(l(),s=1):m(new We("Failed to kill the subprocess."));})}}runSync(e,t={}){let n=t.timeout!==void 0?AbortSignal.timeout(t.timeout):void 0,r=child_process.spawnSync(e.name,e.arguments,{stdio:["ignore","pipe","pipe"],cwd:t?.workingDirectory??this.currentDirectory?.get(),signal:n});if(r.error!==void 0){let{error:s}=r;throw n?.aborted===true?new We("Command timed out.",{reason:"precondition",cause:s}):new We("Failed to run command.",{cause:s})}let i=r.stdout.toString(),a=r.stderr.toString();return i!==""&&a!==""&&(i=`${i}
1774
- ${a}`),{exitCode:r.status??1,output:i}}};var Ko=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 U?new Ie(e.message,e.help):e})}};var Go=class{constructor(e){this.provider=e;}get sdk(){return Promise.resolve(this.provider.get()).catch(e=>{throw e instanceof U?new Y(e.message,e.help):e})}async setup(e){return (await this.sdk).setup(e)}async update(e,t){return (await this.sdk).update(e,t)}async generateSlotExample(e,t){return (await this.sdk).generateSlotExample(e,t)}};var jn=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 Zo=class o{constructor(e){this.instances=new Map;this.factory=e;}create(e){let t=o.getServerId(e),n=this.instances.get(t);if(n!==void 0)return n;let r=this.factory.create(e);return this.instances.set(t,r),r}static getServerId({command:e,...t}){let n=new URL(`${t.protocol}://${t.host}`);return n.port=`${t.port??t.defaultPort}`,n.searchParams.set("command",e.name),e.arguments!==void 0&&e.arguments.length>0&&n.searchParams.set("args",e.arguments.join(",")),n.toString()}};var Qo=class o{constructor(e){this.matcher=e;}static fromPattern(e){return new o(new minimatch.Minimatch(e))}test(e){return Promise.resolve(this.matcher.match(e))}};var Jo=class{constructor(...e){this.predicates=e;}async test(...e){for(let t of this.predicates)if(!await t.test(...e))return false;return true}};var Wn=class{constructor(e){this.predicate=e;}async test(...e){return !await this.predicate.test(...e)}};var Bo=class o{constructor(e){this.filter=e;}static fromPatterns(...e){return new o(id__default.default().add(e))}test(e){return Promise.resolve(this.filter.ignores(e))}};var Yo=class{constructor(e){this.predicate=e;}get(...e){return this.predicate.test(...e)}};var Vn=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 Un=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 Cs={};ul(Cs,{basename:()=>ad,dirname:()=>sd,ext:()=>od});var od=o=>{if(typeof o!="string")throw new $(`The \`path\` argument of the \`ext\` function must be a string, but got ${d.describeType(o)}.`);return o.split(".").pop()??""},ad=o=>{if(typeof o!="string")throw new $(`The \`path\` argument of the \`basename\` function must be a string, but got ${d.describeType(o)}.`);return o.split(/[\\/]/).pop()??""},sd=o=>{if(typeof o!="string")throw new $(`The \`path\` argument of the \`dirname\` function must be a string, but got ${d.describeType(o)}.`);return o.replace(/[\\/][^\\/]*$/,"")};var Xo=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 pd=zod.z.strictObject({condition:zod.z.instanceof(Promise),actions:zod.z.instanceof(Promise)}),ea=class extends v{constructor(){super(pd);}};var X=class o extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var ta=class o{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))throw new X(`Protocol \`${e.protocol}\` is already registered.`,{reason:"precondition"});try{await this.install(e);}catch(t){throw new X("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 X(`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 X("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),a=await this.fileSystem.createTemporaryDirectory("protocol"),s=this.fileSystem.joinPaths(a,"launcher.scpt"),p=this.fileSystem.joinPaths(a,"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:o.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",pe`
1774
+ ${p.toString()}`,{reason:"unexpected_result",cause:l})}};var km=z.strictObject({package:z.string(),arguments:z.array(z.string()).optional(),runner:z.string().optional(),interactions:z.array(z.object({when:z.string(),once:z.boolean().optional(),then:z.array(z.string())})).optional()}),co=class extends v{constructor(){super(km);}};var he=class o extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var et=class{constructor(e){this.projectDirectory=e.projectDirectory,this.fileSystem=e.fileSystem,this.agent=e.agent,this.packageValidator=e.packageValidator;}isInstalled(){return this.agent.isInstalled()}isProject(){return this.fileSystem.exists(this.getProjectManifestPath())}addDependencies(e,t){return this.agent.addDependencies(e,t)}installDependencies(){return this.agent.installDependencies()}getPackageCommand(e,t=[]){return this.agent.getPackageCommand(e,t)}getScriptCommand(e,t=[]){return this.agent.getScriptCommand(e,t)}async hasDirectDependency(e,t){let n=await this.readManifest(this.getProjectManifestPath());if(n===null)return false;let r=n.dependencies?.[e]??n.devDependencies?.[e];return r===void 0?false:t===void 0||wc.satisfies(r,t)}async hasDependency(e,t){let n=await this.getDependency(e);return n===null?false:t===void 0||n.version!==null&&wc.satisfies(n.version,t)}async getDependency(e){let t=this.getPackageManifestPath(e),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 he("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 a=i.get("scripts",JsonObjectNode),s=t;if(a.has(e)){let c=a.get(e).toJSON();if(typeof c=="string"&&c.includes(t))return;s=`${c} && ${t}`;}a.set(e,s);}else i.set("scripts",{[e]:t});await this.fileSystem.writeTextFile(n,i.toString(),{overwrite:true});}getPackageManifestPath(e){return this.fileSystem.joinPaths(this.projectDirectory.get(),"node_modules",e,"package.json")}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 ze=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}addDependencies(e,t=false){return this.run(this.createAddDependencyCommand(e,t))}installDependencies(){return this.run(this.createInstallDependenciesCommand())}getPackageCommand(e,t){return this.createPackageCommand(e,t)}getScriptCommand(e,t){return this.createScriptCommand(e,t)}async run(e,t={}){if(!await this.isInstalled())throw new he(`Package manager \`${this.getCommandName()}\` is not installed.`);if(await this.commandRunner.run(e,{...t,workingDirectory:this.projectDirectory.get()}).wait()!==0)throw new he(`Failed to run \`${e.name}\` command.`)}getExecutable(e){return this.executableLocator.locate(e)}};var lo=class extends ze{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 this.getCommand(this.getCommandName(),["install",...t?["--save-dev"]:[],...e])}createInstallDependenciesCommand(){return this.getCommand(this.getCommandName(),["install"])}getCommand(e,t=[]){return {name:e,arguments:t}}};var uo=class extends ze{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 this.getCommand(this.getCommandName(),["add",...t?["--dev"]:[],...e])}createInstallDependenciesCommand(){return this.getCommand(this.getCommandName(),["install"])}getCommand(e,t=[]){return {name:e,arguments:t}}};var mo=class extends ze{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 this.getCommand(["install",...t?["--dev"]:[],...e])}createInstallDependenciesCommand(){return this.getCommand(["install"])}getCommand(e=[]){return {name:this.getCommandName(),arguments:e}}};var go=class extends ze{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 this.getCommand(["install",...t?["--save-dev"]:[],...e])}createInstallDependenciesCommand(){return this.getCommand(["install"])}getCommand(e=[]){return {name:this.getCommandName(),arguments:e}}};var jt=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 _e=class o extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var fo=class{constructor(e={}){this.configuration=e;}run(e,t={}){let n=spawn(e.name,e.arguments??[],{...this.configuration,cwd:t.workingDirectory??this.configuration.cwd}),r=new jt;n.onData(c=>r.push(c));let i,a=null,s=false;t.timeout!==void 0&&(i=setTimeout(()=>{a===null&&(n.kill("SIGINT"),s=true);},t.timeout),i.unref());let p=[];return n.onExit(c=>{r.close(),a=c.exitCode;for(let l of p)l(c.exitCode);}),{output:r,get running(){return a===null},read:async()=>{let c="";for await(let l of r)c+=l;return c},onExit:c=>(p.push(c),()=>{let l=p.indexOf(c);l!==-1&&p.splice(l,1);}),write:c=>(n.write(c),Promise.resolve()),wait:()=>s?Promise.reject(new _e("Command timed out.",{reason:"precondition"})):a!==null?Promise.resolve(a):new Promise(c=>{n.onExit(l=>{c(l.exitCode);});}),kill:c=>{if(i!==void 0&&clearTimeout(i),a!==null)return Promise.resolve();let l=new Promise(m=>{n.onExit(()=>{m();});});return n.kill(c),l}}}};var yo=class o{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 a=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 a===null?null:{rootConfigPath:a.rootConfigPath,matchedConfigPath:a.matchedConfigPath,baseUrl:this.fileSystem.joinPaths(this.fileSystem.getDirectoryName(a.matchedConfigPath),a.compilerOptions?.baseUrl??"."),paths:a.compilerOptions?.paths??{}}}async locateConfig(e,t,n=false){for(let i of t){let a=this.fileSystem.joinPaths(e,i);if(await this.fileSystem.exists(a))return a}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,a=await this.parseConfig(t);if(a?.extends!==void 0){let s=await this.locateParentConfig(r,this.fileSystem.getDirectoryName(t),a.extends);if(s!==null){let p=await this.resolveConfig({...e,configPath:s});p!==null&&(a=o.mergeConfig(a,p));}}if(a?.references!==void 0&&i.length>0){let{references:s,...p}=a;for(let c of a.references){let l=this.fileSystem.joinPaths(this.fileSystem.getDirectoryName(t),c.path),m=l.endsWith(".json")?l:await this.locateConfig(l,n);if(m===null)continue;let f=await this.resolveConfig({...e,configPath:m});if(f?.include!==void 0)for(let b of i){let A=this.fileSystem.joinPaths("./",this.fileSystem.getRelativePath(this.fileSystem.getDirectoryName(m),b));for(let w of f.include){let y=new Minimatch(w,{partial:true,magicalBraces:true});if(!y.hasMagic()&&!w.includes(".")&&(y=new Minimatch(`${w.replace(/\/?$/,"")}/**/*`,{partial:true})),y.match(A))return o.mergeConfig({...f,rootConfigPath:a.rootConfigPath},p)}}}}return a}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 a=this.fileSystem.joinPaths(e,"node_modules",r);return await this.fileSystem.exists(a)?a: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 ho=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=await this.tsConfigLoader.load(n,{sourcePaths:[this.fileSystem.joinPaths(n,t)]}),i=/\.m(?:js|ts)?$/.test(e)?e:e.replace(/\.(ts|js)x?$/,""),a=this.fileSystem.joinPaths(n,i);if(r!==null){let p=0,c=null;for(let[l,m]of Object.entries(r.paths)){let f=this.fileSystem.normalizeSeparators(l.replace(/\*$/,""));for(let b of m){let A=b.replace(/\*$/,""),w=this.fileSystem.joinPaths(r.baseUrl,A);if(a.startsWith(w)){let y=A.length;if(y>p){p=y;let M=a.slice(w.length).replace(/^[\\/]+/,"");c=f+M;}}}}if(c!==null)return Promise.resolve(c.replace(/\\+/g,"/"))}let s=this.fileSystem.getRelativePath(this.fileSystem.joinPaths(n,t),this.fileSystem.joinPaths(n,i));return Promise.resolve(s.replace(/\\/g,"/"))}};var Tm=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()}),So=class extends Q{constructor(){super(Tm);}};var Pn=class{constructor(e){this.provider=e;}get manager(){return Promise.resolve(this.provider.get()).catch(e=>{throw e instanceof U?new he(e.message,e.help):e})}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 installDependencies(){return (await this.manager).installDependencies()}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)}};var bo=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 U(`No value found for key \`${e}\`.`,{reason:"not_found"});return Promise.resolve(t)}};var Io=class{isInstalled(){return Promise.resolve(false)}addDependencies(){return this.fail()}installDependencies(){return this.fail()}getPackageCommand(){return this.fail()}getScriptCommand(){return this.fail()}fail(){throw new he("The package manager is not installed")}};var Wt=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 Oe=class{constructor(e){this.callback=e;}get(...e){return this.callback(...e)}};var Vt=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 Cn=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 kn=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 xo=class{constructor({packageManager:e}){this.packageManager=e;}test(){return this.packageManager.isProject()}};var vo=class{constructor({currentDirectory:e}={}){this.currentDirectory=e;}run(e,t={}){let n=t.timeout!==void 0?AbortSignal.timeout(t.timeout):void 0,r=spawn$1(e.name,e.arguments,{stdio:["pipe","pipe","pipe"],cwd:t?.workingDirectory??this.currentDirectory?.get(),signal:n}),i=[];r.on("error",c=>{for(let l of i)l(n?.aborted===true?new _e("Command timed out.",{reason:"precondition",cause:c}):new _e("Failed to run command.",{cause:c}));});let a=new jt;r.stdout.on("data",c=>{a.push(c.toString());}),r.stderr.on("data",c=>{a.push(c.toString());});let s=null,p=[];return r.on("exit",c=>{a.close(),s=c??1;for(let l of p)l(s);}),{output:a,get running(){return s===null},onExit:c=>(p.push(c),()=>{let l=p.indexOf(c);l!==-1&&p.splice(l,1);}),write:c=>new Promise((l,m)=>{r.stdin.write(c,f=>{f===null?l():m(f);});}),read:async()=>{let c="";for await(let l of a)c+=l;return c},wait:()=>new Promise((c,l)=>{i.push(l),r.on("exit",m=>{c(m??1);});}),kill:c=>new Promise((l,m)=>{if(s!==null){l();return}r.stdout.destroy(),r.stderr.destroy(),r.stdin.destroy(),r.kill(c)?(l(),s=1):m(new _e("Failed to kill the subprocess."));})}}runSync(e,t={}){let n=t.timeout!==void 0?AbortSignal.timeout(t.timeout):void 0,r=spawnSync(e.name,e.arguments,{stdio:["ignore","pipe","pipe"],cwd:t?.workingDirectory??this.currentDirectory?.get(),signal:n});if(r.error!==void 0){let{error:s}=r;throw n?.aborted===true?new _e("Command timed out.",{reason:"precondition",cause:s}):new _e("Failed to run command.",{cause:s})}let i=r.stdout.toString(),a=r.stderr.toString();return i!==""&&a!==""&&(i=`${i}
1775
+ ${a}`),{exitCode:r.status??1,output:i}}};var wo=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 U?new he(e.message,e.help):e})}};var Po=class{constructor(e){this.provider=e;}get sdk(){return Promise.resolve(this.provider.get()).catch(e=>{throw e instanceof U?new B(e.message,e.help):e})}async setup(e){return (await this.sdk).setup(e)}async update(e,t){return (await this.sdk).update(e,t)}async generateSlotExample(e,t){return (await this.sdk).generateSlotExample(e,t)}};var An=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 Co=class o{constructor(e){this.instances=new Map;this.factory=e;}create(e){let t=o.getServerId(e),n=this.instances.get(t);if(n!==void 0)return n;let r=this.factory.create(e);return this.instances.set(t,r),r}static getServerId({command:e,...t}){let n=new URL(`${t.protocol}://${t.host}`);return n.port=`${t.port??t.defaultPort}`,n.searchParams.set("command",e.name),e.arguments!==void 0&&e.arguments.length>0&&n.searchParams.set("args",e.arguments.join(",")),n.toString()}};var ko=class o{constructor(e){this.matcher=e;}static fromPattern(e){return new o(new Minimatch(e))}test(e){return Promise.resolve(this.matcher.match(e))}};var Ao=class{constructor(...e){this.predicates=e;}async test(...e){for(let t of this.predicates)if(!await t.test(...e))return false;return true}};var En=class{constructor(e){this.predicate=e;}async test(...e){return !await this.predicate.test(...e)}};var Eo=class o{constructor(e){this.filter=e;}static fromPatterns(...e){return new o(Nm().add(e))}test(e){return Promise.resolve(this.filter.ignores(e))}};var Ro=class{constructor(e){this.predicate=e;}get(...e){return this.predicate.test(...e)}};var Rn=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 Tn=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 ns={};Wc(ns,{basename:()=>zm,dirname:()=>_m,ext:()=>$m});var $m=o=>{if(typeof o!="string")throw new $(`The \`path\` argument of the \`ext\` function must be a string, but got ${d.describeType(o)}.`);return o.split(".").pop()??""},zm=o=>{if(typeof o!="string")throw new $(`The \`path\` argument of the \`basename\` function must be a string, but got ${d.describeType(o)}.`);return o.split(/[\\/]/).pop()??""},_m=o=>{if(typeof o!="string")throw new $(`The \`path\` argument of the \`dirname\` function must be a string, but got ${d.describeType(o)}.`);return o.replace(/[\\/][^\\/]*$/,"")};var To=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 Lm=z.strictObject({condition:z.instanceof(Promise),actions:z.instanceof(Promise)}),Oo=class extends v{constructor(){super(Lm);}};var Y=class o extends d{constructor(e,t){super(e,t),Object.setPrototypeOf(this,o.prototype);}};var Do=class o{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))throw new Y(`Protocol \`${e.protocol}\` is already registered.`,{reason:"precondition"});try{await this.install(e);}catch(t){throw new Y("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 Y(`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 Y("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),a=await this.fileSystem.createTemporaryDirectory("protocol"),s=this.fileSystem.joinPaths(a,"launcher.scpt"),p=this.fileSystem.joinPaths(a,"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:o.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",ae`
1775
1776
  use AppleScript version "2.4"
1776
1777
  use framework "Foundation"
1777
1778
  use framework "AppKit"
@@ -1786,47 +1787,47 @@ ${a}`),{exitCode:r.status??1,output:i}}};var Ko=class{constructor(e){this.provid
1786
1787
  end if
1787
1788
 
1788
1789
  return appUrl's path as text
1789
- `]})).trim();return n===""?null:n}async execute(e){let t=this.commandExecutor.run(e);if(await t.wait()!==0)throw new d(`Failed to execute command \`${e.name}\`.`);return t.read()}createLauncherApp(e,t){let n=o.formatId(e.id);return pe`
1790
+ `]})).trim();return n===""?null:n}async execute(e){let t=this.commandExecutor.run(e);if(await t.wait()!==0)throw new d(`Failed to execute command \`${e.name}\`.`);return t.read()}createLauncherApp(e,t){let n=o.formatId(e.id);return ae`
1790
1791
  on open location this_URL
1791
1792
  do shell script "defaults write ${n} current_url " & quoted form of this_URL
1792
1793
  tell application "${t}" to activate
1793
1794
  end open location
1794
- `}createHandlerApp(e){let t=o.formatId(e.id),n=e.command.replace(/\$url/,'" & quoted form of this_URL & "');return pe`
1795
+ `}createHandlerApp(e){let t=o.formatId(e.id),n=e.command.replace(/\$url/,'" & quoted form of this_URL & "');return ae`
1795
1796
  set this_URL to do shell script "defaults read ${t} current_url"
1796
1797
  tell application "Terminal"
1797
1798
  do script "${n}"
1798
1799
  activate
1799
1800
  end tell
1800
- `}getLauncherAppPath(e){return this.getAppPath(`${e}`)}getHandlerAppPath(e){return this.getAppPath(`${e}-handler`)}getAppPath(e){return this.fileSystem.joinPaths(this.appDirectory,`${e}.app`)}static formatId(e){return e.split(/[^a-zA-Z0-9]+/g).join(".")}};var na=class o{constructor({commandExecutor:e}){this.commandExecutor=e;}async isRegistered(e){return await this.findCommand(e)!==null}async register(e){if(await this.isRegistered(e.protocol))throw new X(`Protocol \`${e.protocol}\` is already registered.`,{reason:"precondition"});try{await this.install(e);}catch(t){throw new X("Failed to register protocol handler",{cause:t})}}async install(e){let t=o.getRegistryPath(e.protocol),n=o.getCommandRegistryPath(e.protocol),r=o.getCommand(e.command);await this.execute({name:"REG",arguments:["add",t,"/f"]}),await this.execute({name:"REG",arguments:["add",t,"/v","URL Protocol","/t","REG_SZ","/d","","/f"]}),await this.execute({name:"REG",arguments:["add",t,"/ve","/t","REG_SZ","/d",`URL:${e.protocol}`,"/f"]}),await this.execute({name:"REG",arguments:["add",n,"/ve","/t","REG_SZ","/d",r,"/f"]});}async unregister(e){let t=await this.findCommand(e);if(t!==null){if(!t.startsWith(o.getCommand("")))throw new X(`Application registered for protocol \`${e}\` is externally managed.`,{reason:"precondition"});try{await this.execute({name:"REG",arguments:["DELETE",`${o.getRegistryPath(e)}`,"/f"]});}catch(n){throw new X("Failed to unregister protocol handler",{cause:n})}}}async execute(e){let t=this.commandExecutor.run(e);if(await t.wait()!==0)throw new d(`Failed to execute command \`${e.name}\`.`);return t.read()}async findCommand(e){let t=await this.execute({name:"REG",arguments:["query",`${o.getCommandRegistryPath(e)}`,"/ve"]}).catch(()=>null);if(t===null)return null;let n=/REG_SZ\s+(.*)/g.exec(t);return n===null?null:n[1].trim()}static getCommand(e){return `PowerShell -NoExit -Command ${e.replace(/\$url/,'"%1"')}`}static getCommandRegistryPath(e){return o.getRegistryPath(e,"shell\\open\\command")}static getRegistryPath(e,t){return `HKCU\\Software\\Classes\\${e}${t!==void 0?`\\${t}`:""}`}};var Bt=class Bt{constructor({fileSystem:e,commandExecutor:t,homeDirectory:n}){this.fileSystem=e,this.commandExecutor=t,this.homeDirectory=n;}async isRegistered(e){return await this.findDesktopEntry(e)!==null}async register(e){if(await this.isRegistered(e.protocol))throw new X(`Protocol \`${e.protocol}\` is already registered.`,{reason:"precondition"});try{await this.fileSystem.writeTextFile(this.getDesktopEntryPath(e.protocol),Bt.createDesktopEntry(e)),await this.updateDesktopDatabase();}catch(t){throw new X("Failed to register protocol handler.",{cause:t})}}async unregister(e){let t=await this.findDesktopEntry(e);if(t===null)return;let n=await this.getCommand(t),r=this.getDesktopEntryPath(e);if(t!==r||n?.startsWith(Bt.COMMAND)!==true)throw new X(`Application registered for protocol \`${e}\` is externally managed.`,{reason:"precondition"});try{await this.fileSystem.delete(t),await this.updateDesktopDatabase();}catch(i){throw new X("Failed to unregister protocol handler.",{cause:i})}}async updateDesktopDatabase(){await this.execute({name:"update-desktop-database",arguments:[this.getApplicationPath()]});}async getCommand(e){if(!await this.fileSystem.exists(e))return null;let t=await this.fileSystem.readTextFile(e);if(!/^MimeType=x-scheme-handler\//im.test(t))return null;let n=t.match(/^Exec=(.*)$/im);return n===null?null:n[1].trim()}async findDesktopEntry(e){let t=null;try{t=await this.execute({name:"xdg-mime",arguments:["query","default",`x-scheme-handler/${e}`]});}catch{return null}let n=t.trim();return n===""?null:this.fileSystem.joinPaths(this.getApplicationPath(),n)}async execute(e){let t=this.commandExecutor.run(e);if(await t.wait()!==0)throw new d(`Failed to execute command \`${e.name}\`.`);return t.read()}static createDesktopEntry(e){let t=e.command.replace(/\$url/,"'%u'");return pe`
1801
+ `}getLauncherAppPath(e){return this.getAppPath(`${e}`)}getHandlerAppPath(e){return this.getAppPath(`${e}-handler`)}getAppPath(e){return this.fileSystem.joinPaths(this.appDirectory,`${e}.app`)}static formatId(e){return e.split(/[^a-zA-Z0-9]+/g).join(".")}};var Mo=class o{constructor({commandExecutor:e}){this.commandExecutor=e;}async isRegistered(e){return await this.findCommand(e)!==null}async register(e){if(await this.isRegistered(e.protocol))throw new Y(`Protocol \`${e.protocol}\` is already registered.`,{reason:"precondition"});try{await this.install(e);}catch(t){throw new Y("Failed to register protocol handler",{cause:t})}}async install(e){let t=o.getRegistryPath(e.protocol),n=o.getCommandRegistryPath(e.protocol),r=o.getCommand(e.command);await this.execute({name:"REG",arguments:["add",t,"/f"]}),await this.execute({name:"REG",arguments:["add",t,"/v","URL Protocol","/t","REG_SZ","/d","","/f"]}),await this.execute({name:"REG",arguments:["add",t,"/ve","/t","REG_SZ","/d",`URL:${e.protocol}`,"/f"]}),await this.execute({name:"REG",arguments:["add",n,"/ve","/t","REG_SZ","/d",r,"/f"]});}async unregister(e){let t=await this.findCommand(e);if(t!==null){if(!t.startsWith(o.getCommand("")))throw new Y(`Application registered for protocol \`${e}\` is externally managed.`,{reason:"precondition"});try{await this.execute({name:"REG",arguments:["DELETE",`${o.getRegistryPath(e)}`,"/f"]});}catch(n){throw new Y("Failed to unregister protocol handler",{cause:n})}}}async execute(e){let t=this.commandExecutor.run(e);if(await t.wait()!==0)throw new d(`Failed to execute command \`${e.name}\`.`);return t.read()}async findCommand(e){let t=await this.execute({name:"REG",arguments:["query",`${o.getCommandRegistryPath(e)}`,"/ve"]}).catch(()=>null);if(t===null)return null;let n=/REG_SZ\s+(.*)/g.exec(t);return n===null?null:n[1].trim()}static getCommand(e){return `PowerShell -NoExit -Command ${e.replace(/\$url/,'"%1"')}`}static getCommandRegistryPath(e){return o.getRegistryPath(e,"shell\\open\\command")}static getRegistryPath(e,t){return `HKCU\\Software\\Classes\\${e}${t!==void 0?`\\${t}`:""}`}};var No=class o{static{this.COMMAND="gnome-terminal -- bash --login -ic ";}constructor({fileSystem:e,commandExecutor:t,homeDirectory:n}){this.fileSystem=e,this.commandExecutor=t,this.homeDirectory=n;}async isRegistered(e){return await this.findDesktopEntry(e)!==null}async register(e){if(await this.isRegistered(e.protocol))throw new Y(`Protocol \`${e.protocol}\` is already registered.`,{reason:"precondition"});try{await this.fileSystem.writeTextFile(this.getDesktopEntryPath(e.protocol),o.createDesktopEntry(e)),await this.updateDesktopDatabase();}catch(t){throw new Y("Failed to register protocol handler.",{cause:t})}}async unregister(e){let t=await this.findDesktopEntry(e);if(t===null)return;let n=await this.getCommand(t),r=this.getDesktopEntryPath(e);if(t!==r||n?.startsWith(o.COMMAND)!==true)throw new Y(`Application registered for protocol \`${e}\` is externally managed.`,{reason:"precondition"});try{await this.fileSystem.delete(t),await this.updateDesktopDatabase();}catch(i){throw new Y("Failed to unregister protocol handler.",{cause:i})}}async updateDesktopDatabase(){await this.execute({name:"update-desktop-database",arguments:[this.getApplicationPath()]});}async getCommand(e){if(!await this.fileSystem.exists(e))return null;let t=await this.fileSystem.readTextFile(e);if(!/^MimeType=x-scheme-handler\//im.test(t))return null;let n=t.match(/^Exec=(.*)$/im);return n===null?null:n[1].trim()}async findDesktopEntry(e){let t=null;try{t=await this.execute({name:"xdg-mime",arguments:["query","default",`x-scheme-handler/${e}`]});}catch{return null}let n=t.trim();return n===""?null:this.fileSystem.joinPaths(this.getApplicationPath(),n)}async execute(e){let t=this.commandExecutor.run(e);if(await t.wait()!==0)throw new d(`Failed to execute command \`${e.name}\`.`);return t.read()}static createDesktopEntry(e){let t=e.command.replace(/\$url/,"'%u'");return ae`
1801
1802
  [Desktop Entry]
1802
1803
  Type=Application
1803
1804
  Name=${e.name}
1804
- Exec=${Bt.COMMAND} "${t}; exec bash"
1805
+ Exec=${o.COMMAND} "${t}; exec bash"
1805
1806
  StartupNotify=false
1806
1807
  Terminal=true
1807
1808
  MimeType=x-scheme-handler/${e.protocol}
1808
- `}getDesktopEntryPath(e){return this.fileSystem.joinPaths(this.getApplicationPath(),`${e}.desktop`)}getApplicationPath(){return this.fileSystem.joinPaths(this.homeDirectory,".local","share","applications")}};Bt.COMMAND="gnome-terminal -- bash --login -ic ";var ra=Bt;var ia=class{constructor(e){this.config=e;}async execute({url:e}){if(!URL.canParse(e))throw new d("The URL is not valid.",{reason:"invalid_input"});let t=new URL(e);if(!this.isValidUrl(t))throw new d("The URL is not supported.",{reason:"invalid_input"});let{input:n,output:r}=this.config.io;if(n===void 0)throw new d("Deep links requires explicit user interaction.",{reason:"precondition",details:["Retry in interactive mode."]});let i=this.parseArguments(t);r.announce({semantics:"neutral",title:"\u{1F517} Croct link",message:"You just opened a link to a `Croct CLI` command.",alignment:"center"});let a=i.join(" ");r.inform(`The command is \`${a}\``),await n.confirm({message:"Continue?",default:true})&&(await this.selectDirectory(n),await this.config.program(i));}async selectDirectory(e){let{workingDirectory:t,configurationProvider:n,fileSystem:r,io:{output:i}}=this.config,a=t.get(),{projectPaths:s}=await n.get(),p="";if(s.length>0){let c=r.getDirectoryName(s[0]);p=await e.select({message:"Where should this command run?",options:[{label:`${a} (current)`,value:""},{label:c,value:c},...s.map(l=>({value:l,label:l}))]});}else i.inform(`You are currently in \`${a}\``),await e.confirm({message:"Run the command from the current directory?",default:true})||await e.prompt({message:"Where do you want to run the command from?",default:a,validate:async c=>await r.isDirectory(c)?true:"Enter a valid directory path."});p!==""&&t.setCurrentDirectory(p);}parseArguments(e){let t=[];for(let r of e.pathname.split("/"))r!==""&&t.push(r);let n=[];for(let[r,i]of e.searchParams){if(r==="arg"){n.push(i);continue}if(i===""){t.push(`-${r.length===1?"":"-"}${r}`);continue}t.push(`--${r}`),t.push(i);}return t.push(...n),t}isValidUrl(e){return e.protocol===`${this.config.protocol}:`&&e.hostname===""&&e.username===""&&e.password===""&&e.port===""&&e.hash===""}};var cd=zod.z.strictObject({projectPaths:zod.z.array(zod.z.string().min(1)),isDeepLinkingEnabled:zod.z.boolean().optional()}),aa=class extends B{constructor(){super(cd);}};var sa=class{constructor({manager:e,workingDirectory:t,store:n}){this.manager=e,this.workingDirectory=t,this.store=n;}isInitialized(){return this.manager.isInitialized()}async load(){let e=await this.manager.load();return await this.updateIndex(),e}update(e){return Promise.all([this.manager.update(e),this.updateIndex()]).then(([t])=>t)}async updateIndex(){let e=await this.store.get();await this.store.save({...e,projectPaths:[this.workingDirectory.get(),...e.projectPaths]});}};var pa=class{constructor(e){this.fileSystem=e.fileSystem,this.executablePaths=e.executablePaths,this.executableExtensions=e.executableExtensions??[],this.executableCache=e.cache??new cache.NoopCache;}locate(e){return this.executableCache.get(e,t=>this.findPath(t))}async findPath(e){for(let t of this.executablePaths)for(let n of ["",...this.executableExtensions]){let r=this.fileSystem.joinPaths(t,e+n.toLowerCase());if(r!==null&&await this.fileSystem.exists(r))return r}return null}};var ca=class{constructor(e){this.projectDirectory=e.projectDirectory,this.fileSystem=e.fileSystem,this.packageManager=e.packageManager;}async test(){return (await this.getPreferredPackageManager())?.includes(this.packageManager)===true}async getPreferredPackageManager(){let e=this.fileSystem.joinPaths(this.projectDirectory.get(),"package.json");if(!await this.fileSystem.exists(e))return null;let t;try{t=JSON.parse(await this.fileSystem.readTextFile(e));}catch{return null}return typeof t=="object"&&t!==null&&"packageManager"in t&&typeof t.packageManager=="string"?t.packageManager:null}};var qn=class{constructor(e){this.config=e;}async execute(){try{await this.enableDeepLinks();}catch{}}async enableDeepLinks(){let{cliPackage:e,packageManager:t,protocolRegistryProvider:n,protocolHandler:r,io:{output:i,input:a}}=this.config,s=await n.get();if(s===null||a===void 0)return;let[p,c]=await Promise.all([s.isRegistered(r.protocol),t.isInstalled()]);if(p||!c||!await a.confirm({message:"Turn on deep links to streamline your experience?",default:true}))return;let l=i.notify("Enabling deep links...");try{let m=await t.getPackageCommand(e,["open","$url"]);await s.register({...r,command:`${m.name} ${(m.arguments??[]).join(" ")}`}),i.confirm("Deep links enabled");}finally{l.stop();}}};var la=class{constructor(e){this.process=e.process,this.variable=e.variable,this.value=e.value;}test(){let e=this.process.getEnvValue(this.variable);return e===null?false:this.value?.test(e)===true}};var ua=class{constructor(...e){this.providers=e;}async get(...e){for(let t of this.providers){let n=await t.get(...e)??null;if(n!==null)return n}return null}};var ma=class{constructor(e){this.config=e;}async handle(){let{input:e,output:t,userApi:n}=this.config,r=await n.getInvitations();if(r.length!==0){if(r.length===1){let{id:i,organization:a}=r[0];await e.confirm({message:`${a.name} has invited you to join. Accept?`,default:true})&&await n.acceptInvitation(i);return}r.length>1&&t.inform(`You have ${r.length} pending invitations:`);for(let{id:i,organization:a}of r)await e.confirm({message:`Accept invitation to join ${a.name}?`,default:true})&&await n.acceptInvitation(i);}}};var da=class{constructor(e){this.authenticator=e.authenticator,this.invitationForm=e.invitationForm;}getToken(){return this.authenticator.getToken()}async login(e){let t=await this.authenticator.login(e);return await this.invitationForm.handle({}),t}logout(){return this.authenticator.logout()}};var Yt=class Yt{constructor({fileSystem:e,validator:t,filePath:n}){this.fileSystem=e,this.validator=t,this.filePath=n;}async get(){if(!await this.fileSystem.exists(this.filePath))return Yt.EMPTY_SETTINGS;let e;try{e=await this.fileSystem.readTextFile(this.filePath);}catch{return Yt.EMPTY_SETTINGS}let t=await this.validator.validate(JSON.parse(e));return t.valid?t.data:Yt.EMPTY_SETTINGS}save(e){return this.fileSystem.writeTextFile(this.filePath,JSON.stringify(e),{overwrite:true})}};Yt.EMPTY_SETTINGS={projectPaths:[]};var ga=Yt;var fa=class{constructor({fileSystem:e,store:t}){this.fileSystem=e,this.store=t;}async get(){return this.normalizeSettings(await this.store.get())}async save(e){return this.store.save(await this.normalizeSettings(e))}async normalizeSettings(e){return {...e,projectPaths:(await Promise.all([...new Set(e.projectPaths)].map(async t=>await this.fileSystem.exists(t)?[t]:[]))).flat()}}};var ya=class{constructor(e){this.config=e;}async execute(e){let{configurationManager:t,api:n,fileSystem:r,io:i}=this.config,a=await t.load(),s=e.environment??await i.input.select({message:"Which environment?",options:fe.all().map(y=>({label:fe.getLabel(y),value:y}))}),p=s==="PRODUCTION"?a.applications.production:a.applications.development;if(p===void 0)throw new d(`No ${fe.getLabel(s).toLowerCase()} application found in the project configuration.`,{reason:"invalid_input"});let c=i.output.notify("Loading information"),l=e.name??`${(await n.user.getUser()).username} (CLI)`,m=await n.workspace.getFeatures({organizationSlug:a.organization,workspaceSlug:a.workspace});if(c.stop(),e.permissions?.includes("DATA_EXPORT")===true&&m?.features.dataExport!==true)throw new d("The workspace does not have the data export feature enabled.",{reason:"invalid_input"});let f=e.name??await _e.prompt({input:i.input,label:"API key name",default:l}),b=e.permissions??await i.input.selectMultiple({message:"Select permissions",min:1,options:we.all().map(y=>({label:we.getLabel(y),value:y,disabled:y==="DATA_EXPORT"&&m?.features.dataExport!==true}))}),A=await n.application.createApiKey({organizationSlug:a.organization,workspaceSlug:a.workspace,applicationSlug:p,name:f,permissions:b});if(e.copy===true||await i.input.confirm({message:"Copy to clipboard?",default:false})){await ud__default.default.write(A.secret),i.output.confirm("API key copied to clipboard");return}let w=`api-key-${A.id}.txt`;await r.writeTextFile(w,A.secret),i.output.confirm(`API key saved to \`${w}\``);}};var Jc=vt(an());var ha=class{constructor({apiKey:e,clock:t,tokenDuration:n}){this.apiKey=e,this.clock=t,this.tokenDuration=n;}getToken(){return Promise.resolve(this.token?.toString()??null)}async login(){return this.token=await this.issueToken(),this.token.toString()}logout(){return this.token=void 0,Promise.resolve()}async issueToken(){let e=Jc.Instant.now(this.clock).getSeconds();return token.Token.of({kid:await this.apiKey.getIdentifierHash(),alg:"ES256",typ:"JWT"},{iat:e,nbf:e,exp:e+this.tokenDuration,iss:"cli.croct.com",aud:"app.croct.com",scope:["ADMIN"]}).signedWith(this.apiKey)}};var Sa=class{constructor(e){this.currentDirectory=e;}get(){return this.currentDirectory}setCurrentDirectory(e){this.currentDirectory=e;}toString(){return this.get()}};var ba=class{constructor(e){this.process=e;}get(){return this.process.getCurrentDirectory()}setCurrentDirectory(e){this.process.changeDirectory(e);}toString(){return this.get()}};var Ia=class{constructor({authenticator:e,cacheKey:t,cacheProvider:n}){this.authenticator=e,this.cacheKey=t,this.cacheProvider=n;}getToken(){return this.cacheProvider.get(this.cacheKey,()=>this.authenticator.getToken())}async login(e){let t=await this.authenticator.login(e);return await this.cacheProvider.set(this.cacheKey,t),t}async logout(){await this.authenticator.logout(),await this.cacheProvider.delete(this.cacheKey);}};var Bc=vt(an());var xa=class{constructor(e){this.revalidating=new Map;this.cacheProvider=e.cacheProvider,this.clock=e.clock,this.tokenFreshPeriod=e.tokenFreshPeriod,this.tokenIssuer=e.tokenIssuer;}async get(e,t){let n=await this.cacheProvider.get(e,async()=>await t(e)??"");if(n==="")return null;let r=this.clock.getInstant(),i=this.parseToken(n);if(i!==null){if(!i.isValidNow(r.getSeconds()))return null;this.revalidateToken(e,i).catch(()=>{});}return n}set(e,t){return this.cacheProvider.set(e,t)}delete(e){return this.cacheProvider.delete(e)}async revalidateToken(e,t){let n=this.clock.getInstant();if(this.revalidating.has(e))return;let r=t.getIssueTime(),i=Bc.Instant.ofEpochSecond(r+this.tokenFreshPeriod);n.isAfter(i)&&await this.renewToken(e,t);}async renewToken(e,t){let n=this.tokenIssuer(t);this.revalidating.set(e,true);try{await this.cacheProvider.set(e,await n);}finally{this.revalidating.delete(e);}}parseToken(e){let t;try{t=token.Token.parse(e);}catch{return null}return t}};var va=class{constructor(e){this.api=e.api,this.pollingInterval=e.pollingInterval;}async wait(e){let t=await this.api.closeSession(e);for(;t.status==="pending";)await this.delay(),t=await this.api.closeSession(e);switch(t.status){case "access-granted":return t.accessToken;case "recovery-granted":return t.recoveryToken}}delay(){return new Promise(e=>{setTimeout(e,this.pollingInterval);})}};var wa=class o{constructor(e){this.boxenStyle=e??{titleAlignment:"center",borderStyle:"round",padding:{top:1,bottom:1,right:2,left:2}};}formatCallout(e){return Yc__default.default(te(e.message),{...this.boxenStyle,title:te(e.title,{basic:true}),textAlignment:e.alignment,borderColor:sn[e.semantics]})}formatError(e){return Yc__default.default(o.formatErrorBody(e),{...this.boxenStyle,title:o.formatErrorTitle(e),borderColor:"red"})}static formatErrorTitle(e){return e instanceof d?{access_denied:"Access denied",invalid_configuration:"Invalid configuration",invalid_input:"Invalid input",not_found:"Not found",not_supported:"Not supported",precondition:"Precondition failed",unexpected_result:"Unexpected result",other:"Error"}[e.reason]:"Unexpected error"}static formatErrorBody(e){let t=te(d.formatMessage(e));if(e instanceof d){t+=o.formatErrorDetails(e);let{cause:n}=e.help;n!==void 0&&!o.isCauseReported(e.message,n)&&(t+=`
1809
+ `}getDesktopEntryPath(e){return this.fileSystem.joinPaths(this.getApplicationPath(),`${e}.desktop`)}getApplicationPath(){return this.fileSystem.joinPaths(this.homeDirectory,".local","share","applications")}};var $o=class{constructor(e){this.config=e;}async execute({url:e}){if(!URL.canParse(e))throw new d("The URL is not valid.",{reason:"invalid_input"});let t=new URL(e);if(!this.isValidUrl(t))throw new d("The URL is not supported.",{reason:"invalid_input"});let{input:n,output:r}=this.config.io;if(n===void 0)throw new d("Deep links requires explicit user interaction.",{reason:"precondition",details:["Retry in interactive mode."]});let i=this.parseArguments(t);r.announce({semantics:"neutral",title:"\u{1F517} Croct link",message:"You just opened a link to a `Croct CLI` command.",alignment:"center"});let a=i.join(" ");r.inform(`The command is \`${a}\``),await n.confirm({message:"Continue?",default:true})&&(await this.selectDirectory(n),await this.config.program(i));}async selectDirectory(e){let{workingDirectory:t,configurationProvider:n,fileSystem:r,io:{output:i}}=this.config,a=t.get(),{projectPaths:s}=await n.get(),p="";if(s.length>0){let c=r.getDirectoryName(s[0]);p=await e.select({message:"Where should this command run?",options:[{label:`${a} (current)`,value:""},{label:c,value:c},...s.map(l=>({value:l,label:l}))]});}else i.inform(`You are currently in \`${a}\``),await e.confirm({message:"Run the command from the current directory?",default:true})||await e.prompt({message:"Where do you want to run the command from?",default:a,validate:async c=>await r.isDirectory(c)?true:"Enter a valid directory path."});p!==""&&t.setCurrentDirectory(p);}parseArguments(e){let t=[];for(let r of e.pathname.split("/"))r!==""&&t.push(r);let n=[];for(let[r,i]of e.searchParams){if(r==="arg"){n.push(i);continue}if(i===""){t.push(`-${r.length===1?"":"-"}${r}`);continue}t.push(`--${r}`),t.push(i);}return t.push(...n),t}isValidUrl(e){return e.protocol===`${this.config.protocol}:`&&e.hostname===""&&e.username===""&&e.password===""&&e.port===""&&e.hash===""}};var Fm=z.strictObject({projectPaths:z.array(z.string().min(1)),isDeepLinkingEnabled:z.boolean().optional()}),_o=class extends Q{constructor(){super(Fm);}};var Lo=class{constructor({manager:e,workingDirectory:t,store:n}){this.manager=e,this.workingDirectory=t,this.store=n;}isInitialized(){return this.manager.isInitialized()}async load(){let e=await this.manager.load();return await this.updateIndex(),e}update(e){return Promise.all([this.manager.update(e),this.updateIndex()]).then(([t])=>t)}async updateIndex(){let e=await this.store.get();await this.store.save({...e,projectPaths:[this.workingDirectory.get(),...e.projectPaths]});}};var Fo=class{constructor(e){this.fileSystem=e.fileSystem,this.executablePaths=e.executablePaths,this.executableExtensions=e.executableExtensions??[],this.executableCache=e.cache??new NoopCache;}locate(e){return this.executableCache.get(e,t=>this.findPath(t))}async findPath(e){for(let t of this.executablePaths)for(let n of ["",...this.executableExtensions]){let r=this.fileSystem.joinPaths(t,e+n.toLowerCase());if(r!==null&&await this.fileSystem.exists(r))return r}return null}};var jo=class{constructor(e){this.projectDirectory=e.projectDirectory,this.fileSystem=e.fileSystem,this.packageManager=e.packageManager;}async test(){return (await this.getPreferredPackageManager())?.includes(this.packageManager)===true}async getPreferredPackageManager(){let e=this.fileSystem.joinPaths(this.projectDirectory.get(),"package.json");if(!await this.fileSystem.exists(e))return null;let t;try{t=JSON.parse(await this.fileSystem.readTextFile(e));}catch{return null}return typeof t=="object"&&t!==null&&"packageManager"in t&&typeof t.packageManager=="string"?t.packageManager:null}};var On=class{constructor(e){this.config=e;}async execute(){try{await this.enableDeepLinks();}catch{}}async enableDeepLinks(){let{cliPackage:e,packageManager:t,protocolRegistryProvider:n,protocolHandler:r,io:{output:i,input:a}}=this.config,s=await n.get();if(s===null||a===void 0)return;let[p,c]=await Promise.all([s.isRegistered(r.protocol),t.isInstalled()]);if(p||!c||!await a.confirm({message:"Turn on deep links to streamline your experience?",default:true}))return;let l=i.notify("Enabling deep links...");try{let m=await t.getPackageCommand(e,["open","$url"]);await s.register({...r,command:`${m.name} ${(m.arguments??[]).join(" ")}`}),i.confirm("Deep links enabled");}finally{l.stop();}}};var Wo=class{constructor(e){this.process=e.process,this.variable=e.variable,this.value=e.value;}test(){let e=this.process.getEnvValue(this.variable);return e===null?false:this.value?.test(e)===true}};var Vo=class{constructor(...e){this.providers=e;}async get(...e){for(let t of this.providers){let n=await t.get(...e)??null;if(n!==null)return n}return null}};var Uo=class{constructor(e){this.config=e;}async handle(){let{input:e,output:t,userApi:n}=this.config,r=await n.getInvitations();if(r.length!==0){if(r.length===1){let{id:i,organization:a}=r[0];await e.confirm({message:`${a.name} has invited you to join. Accept?`,default:true})&&await n.acceptInvitation(i);return}r.length>1&&t.inform(`You have ${r.length} pending invitations:`);for(let{id:i,organization:a}of r)await e.confirm({message:`Accept invitation to join ${a.name}?`,default:true})&&await n.acceptInvitation(i);}}};var qo=class{constructor(e){this.authenticator=e.authenticator,this.invitationForm=e.invitationForm;}getToken(){return this.authenticator.getToken()}async login(e){let t=await this.authenticator.login(e);return await this.invitationForm.handle({}),t}logout(){return this.authenticator.logout()}};var Ho=class o{static{this.EMPTY_SETTINGS={projectPaths:[]};}constructor({fileSystem:e,validator:t,filePath:n}){this.fileSystem=e,this.validator=t,this.filePath=n;}async get(){if(!await this.fileSystem.exists(this.filePath))return o.EMPTY_SETTINGS;let e;try{e=await this.fileSystem.readTextFile(this.filePath);}catch{return o.EMPTY_SETTINGS}let t=await this.validator.validate(JSON.parse(e));return t.valid?t.data:o.EMPTY_SETTINGS}save(e){return this.fileSystem.writeTextFile(this.filePath,JSON.stringify(e),{overwrite:true})}};var Go=class{constructor({fileSystem:e,store:t}){this.fileSystem=e,this.store=t;}async get(){return this.normalizeSettings(await this.store.get())}async save(e){return this.store.save(await this.normalizeSettings(e))}async normalizeSettings(e){return {...e,projectPaths:(await Promise.all([...new Set(e.projectPaths)].map(async t=>await this.fileSystem.exists(t)?[t]:[]))).flat()}}};var Ko=class{constructor(e){this.config=e;}async execute(e){let{configurationManager:t,api:n,fileSystem:r,io:i}=this.config,a=await t.load(),s=e.environment??await i.input.select({message:"Which environment?",options:Ie.all().map(y=>({label:Ie.getLabel(y),value:y}))}),p=s==="PRODUCTION"?a.applications.production:a.applications.development;if(p===void 0)throw new d(`No ${Ie.getLabel(s).toLowerCase()} application found in the project configuration.`,{reason:"invalid_input"});let c=i.output.notify("Loading information"),l=e.name??`${(await n.user.getUser()).username} (CLI)`,m=await n.workspace.getFeatures({organizationSlug:a.organization,workspaceSlug:a.workspace});if(c.stop(),e.permissions?.includes("DATA_EXPORT")===true&&m?.features.dataExport!==true)throw new d("The workspace does not have the data export feature enabled.",{reason:"invalid_input"});let f=e.name??await Ne.prompt({input:i.input,label:"API key name",default:l}),b=e.permissions??await i.input.selectMultiple({message:"Select permissions",min:1,options:Ae.all().map(y=>({label:Ae.getLabel(y),value:y,disabled:y==="DATA_EXPORT"&&m?.features.dataExport!==true}))}),A=await n.application.createApiKey({organizationSlug:a.organization,workspaceSlug:a.workspace,applicationSlug:p,name:f,permissions:b});if(e.copy===true||await i.input.confirm({message:"Copy to clipboard?",default:false})){await Wm.write(A.secret),i.output.confirm("API key copied to clipboard");return}let w=`api-key-${A.id}.txt`;await r.writeTextFile(w,A.secret),i.output.confirm(`API key saved to \`${w}\``);}};var kc=ft(Zt());var Zo=class{constructor({apiKey:e,clock:t,tokenDuration:n}){this.apiKey=e,this.clock=t,this.tokenDuration=n;}getToken(){return Promise.resolve(this.token?.toString()??null)}async login(){return this.token=await this.issueToken(),this.token.toString()}logout(){return this.token=void 0,Promise.resolve()}async issueToken(){let e=kc.Instant.now(this.clock).getSeconds();return Token.of({kid:await this.apiKey.getIdentifierHash(),alg:"ES256",typ:"JWT"},{iat:e,nbf:e,exp:e+this.tokenDuration,iss:"cli.croct.com",aud:"app.croct.com",scope:["ADMIN"]}).signedWith(this.apiKey)}};var Jo=class{constructor(e){this.currentDirectory=e;}get(){return this.currentDirectory}setCurrentDirectory(e){this.currentDirectory=e;}toString(){return this.get()}};var Qo=class{constructor(e){this.process=e;}get(){return this.process.getCurrentDirectory()}setCurrentDirectory(e){this.process.changeDirectory(e);}toString(){return this.get()}};var Bo=class{constructor({authenticator:e,cacheKey:t,cacheProvider:n}){this.authenticator=e,this.cacheKey=t,this.cacheProvider=n;}getToken(){return this.cacheProvider.get(this.cacheKey,()=>this.authenticator.getToken())}async login(e){let t=await this.authenticator.login(e);return await this.cacheProvider.set(this.cacheKey,t),t}async logout(){await this.authenticator.logout(),await this.cacheProvider.delete(this.cacheKey);}};var Ac=ft(Zt());var Yo=class{constructor(e){this.revalidating=new Map;this.cacheProvider=e.cacheProvider,this.clock=e.clock,this.tokenFreshPeriod=e.tokenFreshPeriod,this.tokenIssuer=e.tokenIssuer;}async get(e,t){let n=await this.cacheProvider.get(e,async()=>await t(e)??"");if(n==="")return null;let r=this.clock.getInstant(),i=this.parseToken(n);if(i!==null){if(!i.isValidNow(r.getSeconds()))return null;this.revalidateToken(e,i).catch(()=>{});}return n}set(e,t){return this.cacheProvider.set(e,t)}delete(e){return this.cacheProvider.delete(e)}async revalidateToken(e,t){let n=this.clock.getInstant();if(this.revalidating.has(e))return;let r=t.getIssueTime(),i=Ac.Instant.ofEpochSecond(r+this.tokenFreshPeriod);n.isAfter(i)&&await this.renewToken(e,t);}async renewToken(e,t){let n=this.tokenIssuer(t);this.revalidating.set(e,true);try{await this.cacheProvider.set(e,await n);}finally{this.revalidating.delete(e);}}parseToken(e){let t;try{t=Token.parse(e);}catch{return null}return t}};var Xo=class{constructor(e){this.api=e.api,this.pollingInterval=e.pollingInterval;}async wait(e){let t=await this.api.closeSession(e);for(;t.status==="pending";)await this.delay(),t=await this.api.closeSession(e);switch(t.status){case "access-granted":return t.accessToken;case "recovery-granted":return t.recoveryToken}}delay(){return new Promise(e=>{setTimeout(e,this.pollingInterval);})}};var ea=class o{constructor(e){this.boxenStyle=e??{titleAlignment:"center",borderStyle:"round",padding:{top:1,bottom:1,right:2,left:2}};}formatCallout(e){return Ec(ee(e.message),{...this.boxenStyle,title:ee(e.title,{basic:true}),textAlignment:e.alignment,borderColor:Jt[e.semantics]})}formatError(e){return Ec(o.formatErrorBody(e),{...this.boxenStyle,title:o.formatErrorTitle(e),borderColor:"red"})}static formatErrorTitle(e){return e instanceof d?{access_denied:"Access denied",invalid_configuration:"Invalid configuration",invalid_input:"Invalid input",not_found:"Not found",not_supported:"Not supported",precondition:"Precondition failed",unexpected_result:"Unexpected result",other:"Error"}[e.reason]:"Unexpected error"}static formatErrorBody(e){let t=ee(d.formatMessage(e));if(e instanceof d){t+=o.formatErrorDetails(e);let{cause:n}=e.help;n!==void 0&&!o.isCauseReported(e.message,n)&&(t+=`
1809
1810
 
1810
- \u{1F6A8} ${ct__default.default.bold("Cause")}
1811
- `,t+=`${te(d.formatMessage(e.help.cause))}`),t+=o.formatErrorSuggestions(e),t+=o.formatErrorUsefulLinks(e);}return (!(e instanceof d)||e.reason==="other"&&e.help.cause instanceof Error)&&(t+=o.formatStackTrace(e)),t}static isCauseReported(e,t){return e.toLowerCase().includes(d.formatMessage(t).toLowerCase())}static formatErrorDetails(e){let t="",{details:n}=e.help;return n!==void 0&&(t+=`
1811
+ \u{1F6A8} ${nt.bold("Cause")}
1812
+ `,t+=`${ee(d.formatMessage(e.help.cause))}`),t+=o.formatErrorSuggestions(e),t+=o.formatErrorUsefulLinks(e);}return (!(e instanceof d)||e.reason==="other"&&e.help.cause instanceof Error)&&(t+=o.formatStackTrace(e)),t}static isCauseReported(e,t){return e.toLowerCase().includes(d.formatMessage(t).toLowerCase())}static formatErrorDetails(e){let t="",{details:n}=e.help;return n!==void 0&&(t+=`
1812
1813
 
1813
- \u{1F50D} ${ct__default.default.bold("Details")}
1814
- `,t+=n.map(r=>` \u2022 ${te(r)}`).join(`
1814
+ \u{1F50D} ${nt.bold("Details")}
1815
+ `,t+=n.map(r=>` \u2022 ${ee(r)}`).join(`
1815
1816
  `)),t}static formatStackTrace(e){if(!(e instanceof Error)||e.stack===void 0)return "";let t=e.stack.split(`
1816
1817
  `).map(n=>` \u203A ${n.trim().replace(/^at /,"")}`).slice(1);return `
1817
1818
 
1818
- \u{1F4C4} ${ct__default.default.bold("Stack trace")}
1819
+ \u{1F4C4} ${nt.bold("Stack trace")}
1819
1820
  ${t.join(`
1820
1821
  `)}`}static formatErrorSuggestions(e){let{suggestions:t}=e.help,n="";return t!==void 0&&t.length>0&&(n+=`
1821
1822
 
1822
- \u{1F4A1} ${ct__default.default.bold("Suggestions")}
1823
- `,n+=t.map(r=>` \u2022 ${te(r)}`).join(`
1823
+ \u{1F4A1} ${nt.bold("Suggestions")}
1824
+ `,n+=t.map(r=>` \u2022 ${ee(r)}`).join(`
1824
1825
  `)),n}static formatErrorUsefulLinks(e){let t=[],n="";switch(e.reason){case "invalid_input":case "precondition":t.push({label:"Documentation",url:"https://docs.croct.io/sdk/cli"});break;case "invalid_configuration":break;default:t.push({label:"Open an issue",url:"https://github.com/croct-tech/croct-cli/issues/new"});break}return e.help.links!==void 0&&t.push(...e.help.links),t.length>0&&(n+=`
1825
1826
 
1826
- \u{1F517} ${ct__default.default.bold("Useful links")}
1827
- `,n+=t.map(({label:r,url:i})=>` \u2022 ${$l__default.default(r,i,{fallback:()=>`${r}: ${i}`})}`).join(`
1828
- `)),n}};var Ca=class{constructor(){this.listeners={};}on(e,t){this.listeners[e]===void 0&&(this.listeners[e]=new Set),this.listeners[e].add(t);}off(e,t){this.listeners[e]!==void 0&&this.listeners[e].delete(t);}async emit(e,...t){this.listeners[e]!==void 0&&await Promise.all(Array.from(this.listeners[e]).map(n=>n(...t)));}};var Pa=class{constructor(){this.eventDispatcher=new Ca;Ve__default.default.on("SIGTERM",()=>this.exit()),Ve__default.default.on("SIGINT",()=>this.exit());}getCurrentDirectory(){return Ve__default.default.cwd()}getEnvValue(e){return Ve__default.default.env[e]??null}getEnvList(e){return this.getEnvValue(e)?.split(path.delimiter)??null}getPlatform(){return Ve__default.default.platform}getStandardError(){return Ve__default.default.stderr}getStandardInput(){return Ve__default.default.stdin}getStandardOutput(){return Ve__default.default.stdout}on(e,t){this.eventDispatcher.on(e,t);}off(e,t){this.eventDispatcher.off(e,t);}async exit(e){return await this.eventDispatcher.emit("exit").catch(()=>{}),Ve__default.default.exit(e)}changeDirectory(e){Ve__default.default.chdir(e);}};var ka=class{constructor({callback:e}){this.callback=e;}async execute(e,t){try{return await this.callback(e,t)}catch(n){if(!(n instanceof I))throw I.fromCause(n)}}};var hd=zod.z.strictObject({}),Aa=class extends v{constructor(){super(hd);}};var Kn=class Kn{constructor(e){this.metadataProvider=e;}async get(e){let t=this.getMetadataUrl(e);if(t===null)throw new W("Unsupported NPM URL.",{reason:"not_supported",url:e});let{value:n}=await this.metadataProvider.get(t),r=Kn.getRepositoryUrl(n.repository);return r===null?{url:e,value:[]}:{url:r,value:[{pattern:".*",destination:r}]}}static getRepositoryUrl(e){for(let t of Kn.REPOSITORY_PATTERNS){let n=t.exec(e.url);if(n!==null)return new URL(`${n[1]}/`)}return null}getMetadataUrl(e){if(e.protocol!=="npm:")return null;let t=e.pathname.slice(1);return new URL(`https://registry.npmjs.org/${t}/latest`)}};Kn.REPOSITORY_PATTERNS=[/git\+(https:\/\/.+)\.git$/];var Ea=Kn;var Ra=class o{constructor({provider:e,reader:t}){this.provider=e,this.reader=t;}static text(e){return new o({provider:e,reader:t=>t.text()})}static json(e){return new o({provider:e,reader:t=>t.json()})}static blob(e){return new o({provider:e,reader:t=>t.blob()})}async get(e){let t=await this.provider.get(e),n;try{n=await this.reader(new Response(t.value.body));}catch(r){throw new W("Failed to read response body.",{reason:"unexpected_result",url:e,cause:r})}return {url:t.url,value:n}}};var Sd=zod.z.object({name:zod.z.string(),repository:zod.z.object({type:zod.z.string(),url:zod.z.string()})}),Ta=class extends B{constructor(){super(Sd);}};var Da=class{constructor({provider:e,logger:t,label:n}){this.provider=e,this.logger=t,this.label=n;}get(e){return this.logger.nest({message:`\`${this.label??this.provider.constructor.name}\``,level:logging.LogLevel.DEBUG},()=>this.trace(e))}async trace(e){this.logger.log({message:`URL: ${e}`,level:logging.LogLevel.DEBUG});try{let t=await this.provider.get(e);return this.logger.log({message:"No errors",level:logging.LogLevel.DEBUG}),t}catch(t){throw this.logger.log({message:`Error: ${d.formatMessage(t)}`,level:logging.LogLevel.DEBUG}),t}}};var Ma=class{constructor(e){this.storage=new async_hooks.AsyncLocalStorage;this.logger=e;}nest(e,t){let n=this.storage.getStore();if(n!==void 0)return this.logNested(n,e,t);let r={level:0,logs:[]};return this.storage.run(r,()=>this.logNested(r,e,t))}async logNested(e,t,n){this.buffer(e,{...t,message:`\u250C\u2500 ${t.message}`}),e.level++;try{return await n()}finally{e.level--,this.buffer(e,{...t,message:"\u2514\u2500"}),e.level===0&&(e.logs.forEach(r=>this.logger.log(r)),e.logs=[]);}}log(e){let t=this.storage.getStore();if(t!==void 0){this.buffer(t,e);return}this.logger.log(e);}buffer(e,t){e.logs.push({...t,message:`${e.level>0?`${"\u2502 ".repeat(e.level-1)}\u2502 `:""}${t.message}`});}};var Na=class{constructor(e){this.output=e;}log(e){switch(e.level){case "debug":this.output.debug(e.message);break;case "info":this.output.inform(e.message);break;case "warning":this.output.warn(e.message);break;case "error":this.output.alert(e.message);}}};var Zn=class Zn{constructor(e){this.rootPath=e.rootPath,this.importResolver=e.importResolver,this.exportMatcher=e.exportMatcher,this.importCodemod=e.importCodemod,this.fileSystem=e.fileSystem,this.maxSearchDepth=e.maxSearchDepth;}apply(e){return this.importCodemod.apply(e,{transformer:t=>{if(!t.source.startsWith(Zn.PREFIX))return;let n=t.source.slice(Zn.PREFIX.length);return this.resolvePath(t,n,e)}})}async resolvePath(e,t,n){let r=new minimatch.Minimatch(t);for await(let i of this.fileSystem.list(this.rootPath.get(),this.maxSearchDepth))if(i.type==="file"&&r.match(i.name)&&await this.exportMatcher.test(await new Response(i.content).text(),e))return this.importResolver.getImportPath(i.name,n);throw new Je(`Unable to resolve import \`${t}\` from \`${n}\`.`,{reason:"not_found"})}};Zn.PREFIX="?/";var $a=Zn;var za=class{constructor({codemods:e}){this.codemods=e;}apply(e,t){let[,n]=Object.entries(this.codemods).find(([r])=>minimatch.minimatch(e,r))??[];return n===void 0?Promise.resolve({modified:false,result:e}):n.apply(e,t)}};function Xc(o){let e=typeof o=="string"?Be(o,["jsx","typescript"]):o,t=[];return yt__default.default(e,{ExportDeclaration:n=>{let{node:r}=n;if(g__namespace.isExportNamedDeclaration(r))if(r.specifiers.length>0)for(let i of r.specifiers)g__namespace.isExportSpecifier(i)?(!g__namespace.isIdentifier(i.exported)||i.exported.name!=="default")&&t.push(g__namespace.isIdentifier(i.exported)?i.exported.name:i.exported.value):g__namespace.isExportNamespaceSpecifier(i)&&g__namespace.isIdentifier(i.exported)&&t.push(i.exported.name);else if(g__namespace.isVariableDeclaration(r.declaration))for(let i of r.declaration.declarations)g__namespace.isVariableDeclarator(i)&&g__namespace.isIdentifier(i.id)&&t.push(i.id.name);else typeof r.declaration=="object"&&r.declaration!==null&&"id"in r.declaration&&g__namespace.isIdentifier(r.declaration.id)&&t.push(r.declaration.id.name);return n.skip()}}),t}async function el(o,e){let t=[];return yt__default.default(o,{ImportDeclaration:n=>{let{node:r}=n,i=Promise.resolve(e(Cd(r)));return i!==void 0&&t.push(i.then(a=>typeof a=="string"&&r.source.value!==a?(r.source.value=a,true):false)),n.skip()}}),(await Promise.all(t)).some(n=>n)}function Cd(o){let e={names:[],source:o.source.value};for(let t of o.specifiers)g__namespace.isImportSpecifier(t)&&e.names.push(g__namespace.isIdentifier(t.imported)?t.imported.name:t.imported.value);return e}var La=class{async apply(e,t){let n=await el(e,t.transformer);return {result:e,modified:n}}};var Fa=class{constructor(...e){this.codemods=e;}async apply(e,t){let n=e,r=false;for(let i of this.codemods){let a=await i.apply(n,t);n=a.result,r=r||a.modified;}return {modified:r,result:n}}};var ja=class o{constructor(e,t){this.client=e,this.cache=t;}getHierarchy(e){return this.cache.get(o.getHierarchyKey(e),async()=>{let t=await this.resolveHierarchy(e);return await this.saveCache(e,t),t})}async resolveHierarchy(e){let{data:{organization:t}}=await this.client.execute(Mp,e),n=t?.id,r=t?.workspace?.id,i=t?.workspace?.application?.id;return o.checkMissing("organization",e.organizationSlug,n),"workspaceSlug"in e?(o.checkMissing("workspace",e.workspaceSlug,r),"applicationSlug"in e?(o.checkMissing("application",e.applicationSlug,i),{organizationId:n,workspaceId:r,applicationId:i}):{organizationId:n,workspaceId:r}):{organizationId:n}}async saveCache(e,t){let n=[this.setCache({organizationSlug:e.organizationSlug},{organizationId:t.organizationId})];"workspaceId"in t&&"workspaceSlug"in e&&n.push(this.setCache({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug},{organizationId:t.organizationId,workspaceId:t.workspaceId})),"applicationId"in t&&"applicationSlug"in e&&n.push(this.setCache({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,applicationSlug:e.applicationSlug},{organizationId:t.organizationId,workspaceId:t.workspaceId,applicationId:t.applicationId})),await Promise.all(n);}setCache(e,t){return this.cache.set(o.getHierarchyKey(e),t)}static getHierarchyKey(e){let t=[`organization:${e.organizationSlug}`];return "workspaceSlug"in e&&t.push(`workspace:${e.workspaceSlug}`),"applicationSlug"in e&&t.push(`application${e.applicationSlug}`),t.join("/")}static checkMissing(e,t,n){if(n===void 0)throw new ne(`No ${e} found with slug "${t}".`,[],{reason:"not_found"})}};var st=class st{constructor(e){this.instances=new Map;this.configuration=e,this.skipPrompts=e.skipPrompts,this.initialDirectory=e.directories.current??e.process.getCurrentDirectory(),this.workingDirectory=new Sa(this.initialDirectory);}static fromDefaults(e){let t=kd__default.default("com.croct.cli"),n=new Pa;return new st({program:e.program??(()=>{throw new d("CLI is running in standalone mode.")}),process:e.process??n,quiet:e.quiet??false,debug:e.debug??false,interactive:e.interactive??!Ad__default.default.isCI,apiKey:e.apiKey,skipPrompts:e.skipPrompts??false,adminTokenDuration:e.adminTokenDuration??7*xt.LocalTime.SECONDS_PER_DAY,apiKeyTokenDuration:e.apiKeyTokenDuration??30*xt.LocalTime.SECONDS_PER_MINUTE,cliTokenDuration:e.cliTokenDuration??90*xt.LocalTime.SECONDS_PER_DAY,cliTokenFreshPeriod:e.cliTokenFreshPeriod??15*xt.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??os$1.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){return this.execute(new qn({packageManager:this.getNodePackageManager(),protocolRegistryProvider:this.getProtocolRegistryProvider(),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 ia({program:this.configuration.program,protocol:this.configuration.deepLinkProtocol,configurationProvider:this.getCliConfigurationStore(),workingDirectory:new ba(this.configuration.process),fileSystem:this.getFileSystem(),io:{input:this.getInput(),output:this.getOutput()}}),e)}init(e){return this.execute(new Ir({sdkProvider:this.getSdkProvider(),platformProvider:this.getPlatformProvider(),configurationManager:this.getConfigurationManager(),skipConfirmation:new Yo(new Un(new Wn(new Ln({fileSystem:this.getFileSystem(),files:[".git"]})))),api:{user:this.getUserApi(),organization:this.getOrganizationApi(),workspace:this.getWorkspaceApi()},form:{organization:new kr({input:this.getFormInput(),output:this.getOutput(),userApi:this.getUserApi()}),workspace:new Ar({input:this.getFormInput(),output:this.getOutput(),organizationApi:this.getOrganizationApi()}),application:new Er({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()})},io:{input:this.getInput(),output:this.getOutput()}}),e)}install(e){return this.execute(new yn({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),io:{input:this.getInput(),output:this.getOutput()}}),e)}upgrade(e){return this.execute(new hn({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),form:{slotForm:new nt({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),componentForm:new rt({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()})},io:{input:this.getInput(),output:this.getOutput()}}),e)}addSlot(e){return this.execute(new Mt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),workspaceApi:this.getWorkspaceApi(),slotForm:new nt({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}removeSlot(e){return this.execute(new gn({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),slotForm:new nt({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}addComponent(e){return this.execute(new Nt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new rt({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}removeComponent(e){return this.execute(new fn({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new rt({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}login(e){return this.execute(new xr({authenticator:this.getAuthenticator()}),e)}logout(){return this.execute(new cn({authenticator:this.getAuthenticator(),output:this.getOutput()}),{})}admin(e){return this.execute(new Mr({output:this.getOutput(),pageForm:new Ur({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 In({configurationManager:this.getConfigurationManager(),fileSystem:this.getFileSystem(),templateForm:new pi({input:this.getFormInput(),form:{component:new rt({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),slot:new nt({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),experience:new ci({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),audience:new li({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");try{return await t.getOptions(e)}finally{r.stop();}}getUseTemplateCommand(){return new ui({templateProvider:new jt({provider:new Pn(this.getTemplateProvider()),validator:new Rn}),fileSystem:this.getFileSystem(),action:this.getImportAction(),io:{input:this.getInput(),output:this.getOutput()}})}createApiKey(e){return this.execute(new ya({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 Vn(new Hr(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 lr({input:this.configuration.process.getStandardInput(),output:this.configuration.process.getStandardOutput(),onAbort:()=>e.exit(),onInteractionStart:()=>e.suspend(),onInteractionEnd:()=>e.resume()});return this.skipPrompts?new Vn(t):t})}getNonInteractiveOutput(e=false){let{configuration:t}=this;return new pn({output:t.process.getStandardOutput(),formatter:this.getLogFormatter(),interactive:false,quiet:e,onExit:()=>t.process.exit(),linkOpener:async n=>{await tl__default.default(n,{wait:true});}})}getHierarchicalLogger(){return this.share(this.getHierarchicalLogger,()=>new Ma(this.getLogger()))}getLogger(){return this.share(this.getLogger,()=>{let e=new Na(this.getOutput());return this.configuration.debug?e:new logging.FilteredLogger(e,logging.LogLevel.WARNING)})}getOutput(){return this.share(this.getOutput,()=>{let{configuration:e}=this;return new pn({output:e.process.getStandardOutput(),formatter:this.getLogFormatter(),interactive:this.configuration.interactive,quiet:this.configuration.quiet,onExit:()=>e.process.exit(),linkOpener:async t=>{await tl__default.default(t);}})})}getLogFormatter(){return this.share(this.getLogFormatter,()=>new wa)}getTemplateProvider(){return this.share(this.getTemplateProvider,()=>{let e=n=>new ot(...["template.json5","template.json"].map(r=>new Ft({dataProvider:n,registryProvider:new Nn([{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 An({resourceCache:new cache.AutoSaveCache(new cache.InMemoryCache),errorCache:new cache.InMemoryCache,provider:new ot(new Ft({dataProvider:this.traceProvider({label:"ResourceProvider",provider:e(new St(new ot(this.traceProvider({provider:new vn(t)}),this.traceProvider({provider:new wn(t)}))))}),registryProvider:this.traceProvider({label:"NpmRegistryProvider",provider:new Ea(new jt({provider:Ra.json(this.traceProvider({provider:this.getHttpProvider()})),validator:new Ta}))})}),e(new St(this.getFileProvider())))})})})}getFileProvider(){return this.share(this.getFileProvider,()=>{let e=this.traceProvider({provider:this.getHttpProvider()}),t=this.traceProvider({provider:new Ai(this.getFileSystem())}),n=new ot(t,this.traceProvider({provider:new vn(e)}),this.traceProvider({provider:new wn(e)}));return this.traceProvider({label:"FileProvider",provider:new ot(t,this.traceProvider({provider:new Ft({baseUrl:new URL("./",this.configuration.templateRegistryUrl),dataProvider:this.traceProvider({label:"ResourceProvider",provider:n}),registryProvider:new ao({url:this.configuration.templateRegistryUrl,provider:this.traceProvider({label:"GlobalRegistryProvider",provider:new An({errorCache:new cache.InMemoryCache,resourceCache:new cache.AutoSaveCache(new cache.InMemoryCache),provider:new jt({provider:new Pn(new St(n)),validator:new Oi})})})})})}))})})}traceProvider({provider:e,label:t}){return new Da({label:t,provider:e,logger:this.getHierarchicalLogger()})}getImportAction(){return this.share(this.getImportAction,()=>{let e=this.getFileSystem(),t={run:new L({action:new it(new Ne(()=>new So(t))),validator:new bo}),try:new L({action:new it(new Ne(()=>new Si(t.run))),validator:new Li}),test:new L({action:new it(new Ne(()=>new Yi(t.run))),validator:new eo}),repeat:new L({action:new it(new Ne(()=>new Xo(t.run))),validator:new ea}),print:new L({action:new to,validator:new ro}),fail:new L({action:new io,validator:new oo}),define:new L({action:new wo,validator:new vo}),prompt:new L({action:new mo,validator:new go}),"change-directory":new L({action:new Ro({fileSystem:e,rootDirectory:this.initialDirectory,currentDirectory:this.workingDirectory}),validator:new Eo}),"open-link":new L({action:new Io,validator:new xo}),"start-server":new L({action:new fo({serverProvider:this.getServerProvider()}),validator:new ho}),"stop-server":new L({action:new Co({serverProvider:this.getServerProvider()}),validator:new Po}),"execute-package":new L({action:new Oo({packageManager:this.getPackageManager(),packageManagerProvider:this.getPackageManagerRegistry(),workingDirectory:this.workingDirectory,commandExecutor:new Lo({cols:80,rows:24}),commandTimeout:2*60*1e3,sourceChecker:{test:()=>true}}),validator:new Mo}),"check-dependencies":new L({action:new ki({packageManager:this.getPackageManager()}),validator:new Fi}),download:new L({action:new mi({fileSystem:e,provider:this.getFileProvider(),codemod:new za({codemods:{"**/*.{js,jsx,ts,tsx}":new Fa(new $a({fileSystem:e,rootPath:this.workingDirectory,maxSearchDepth:10,importResolver:this.getNodeImportResolver(),importCodemod:new Ge({fileSystem:e,codemod:new He({languages:["typescript","jsx"],codemod:new La})}),exportMatcher:{test:(n,{names:r})=>r.length===0?true:Xc(n).some(i=>r.includes(i))}}),new Ke(this.getJavaScriptFormatter()))}})}),validator:new ji}),"add-dependency":new L({action:new di({packageManager:this.getPackageManager()}),validator:new Vi}),"locate-file":new L({action:new gi({projectDirectory:this.workingDirectory,fileSystem:e,matcherProvider:{get:async n=>{let r=e.joinPaths(this.workingDirectory.get(),".gitignore"),i=Qo.fromPattern(n);if(await e.exists(r)){let a=await e.readTextFile(r);return new Jo(new Wn(Bo.fromPatterns(a)),i)}return i}}}),validator:new Ui}),"replace-file-content":new L({action:new fi({fileSystem:e}),validator:new qi}),initialize:new L({action:new ka({callback:()=>this.init({})}),validator:new Aa}),"add-slot":new L({action:new yi({installer:(n,r)=>{let i=this.getNonInteractiveOutput(true);return this.execute(new Mt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),workspaceApi:this.getWorkspaceApi(),slotForm:new nt({input:this.getNonInteractiveInput(),output:i,workspaceApi:this.getWorkspaceApi()}),io:{output:i}}),{slots:n,example:r})}}),validator:new Ki}),"add-component":new L({action:new hi({installer:n=>{let r=this.getNonInteractiveOutput(true);return this.execute(new Nt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new rt({input:this.getNonInteractiveInput(),output:r,workspaceApi:this.getWorkspaceApi()}),io:{output:r}}),{components:n})}}),validator:new Gi}),"create-resource":new L({action:new vi({configurationManager:this.getConfigurationManager(),matcher:new Ci({workspaceApi:this.getWorkspaceApi()}),api:{user:this.getUserApi(),workspace:this.getWorkspaceApi(),organization:this.getOrganizationApi()},mappingForm:new wi({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 Zi}),"format-code":new L({action:new Ji({formatter:this.getCodeFormatter()}),validator:new Bi}),import:new L({action:new it(new Ne(()=>new Ni({runner:t.run,templateProvider:new _i({evaluator:new Di({functions:Cs}),validator:new Rn,templateProvider:this.getTemplateProvider(),fileProvider:new St(this.getFileProvider())}),variables:this.getActionVariables()}))),validator:new Qi})};return t.import})}getActionVariables(){let e=t=>new URL(t,this.configuration.adminUrl).toString();return {project:{features:ie.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load(),{features:r}=await this.getWorkspaceApi().getFeatures({organizationSlug:t,workspaceSlug:n})??{};return r??{}}),quotas:ie.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load(),{quotas:r}=await this.getWorkspaceApi().getFeatures({organizationSlug:t,workspaceSlug:n})??{};return r??{}}),organization:ie.transient(async()=>{let{organization:t}=await this.getConfigurationManager().load();return {slug:t,url:e(`organizations/${t}`)}}),workspace:ie.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load();return {slug:n,url:e(`organizations/${t}/workspaces/${n}`)}}),application:ie.transient(async()=>{let{organization:t,workspace:n,applications:r}=await this.getConfigurationManager().load(),i=`organizations/${t}/workspaces/${n}/applications/`;return {development:{slug:r.development,url:e(i+r.development)},production:{slug:r.production,url:e(i+r.production)}}}),path:{example:ie.transient(async()=>(await this.getConfigurationManager().load()).paths.examples),component:ie.transient(async()=>(await this.getConfigurationManager().load()).paths.components)},platform:ie.transient(async()=>await this.getPlatformProvider().get()??"unknown"),server:ie.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 Pi)}getAuthenticator(){return this.share(this.getAuthenticator,()=>{if(this.configuration.apiKey!==void 0)return new ha({apiKey:this.configuration.apiKey,clock:this.getClock(),tokenDuration:this.configuration.apiKeyTokenDuration});let e=this.getFormInput(),t=this.getFileSystem(),n=new Tr({input:e,output:this.getOutput(),userApi:this.getUserApi(true),form:{signIn:new Or({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 Dr({input:e,output:this.getOutput(),userApi:this.getUserApi(true),listener:this.getTokenListener(),emailLinkGenerator:this.createEmailLinkGenerator(this.configuration.emailSubject.accountActivation),verificationLinkDestination:this.configuration.verificationLinkDestination.accountActivation})}}),r=this.getUserApi(true),i=new Ia({cacheKey:"token",cacheProvider:new xa({clock:this.getClock(),tokenFreshPeriod:this.configuration.cliTokenFreshPeriod,tokenIssuer:()=>r.issueToken({duration:this.configuration.cliTokenDuration}),cacheProvider:new kn({fileSystem:t,directory:this.configuration.directories.config,useKeyAsFileName:true})}),authenticator:new Kr({default:this.configuration.interactive?n:new qr({authenticator:n,instruction:{message:"Authentication required.",suggestions:["Run `login` to authenticate"],reason:"precondition"}}),credentials:n})});return this.configuration.interactive?new da({authenticator:i,invitationForm:new ma({output:this.getOutput(),input:e,userApi:this.getUserApi(true)})}):i})}getSdk(){return this.share(this.getSdk,()=>{let e=new Qt(this.getSdkProvider(),new Ne(()=>{throw new U("No suitable SDK detected.",{reason:"not_supported",suggestions:["Make sure you are running the command in the project root directory."]})}));return new Go(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 Kt({discriminator:async()=>await this.getPlatformProvider().get()??i,mapping:{javascript:()=>new fr({...r,bundlers:["vite","parcel","tsup","rollup"]}),react:()=>new yr({...r,importResolver:n,codemod:{provider:new Ke(e,new Ge({fileSystem:this.getFileSystem(),codemod:new He({languages:["typescript","jsx"],codemod:new gt({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 a={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 br({...r,userApi:this.getUserApi(),applicationApi:this.getApplicationApi(),importResolver:n,codemod:{middleware:new Ke(e,new Ge({fileSystem:this.getFileSystem(),codemod:new He({languages:["typescript","jsx"],codemod:new Lr({import:{module:"@croct/plug-next/middleware",middlewareName:"middleware",middlewareFactoryName:"withCroct",configName:"config",matcherName:"matcher",matcherLocalName:"croctMatcher"}})})})),appRouterProvider:new Ke(e,new Ge({fileSystem:this.getFileSystem(),codemod:new He({languages:["typescript","jsx"],codemod:new gt({fallbackToNamedExports:false,fallbackCodemod:new Fr({provider:{component:"CroctProvider",module:"@croct/plug-next/CroctProvider"}}),wrapper:{module:"@croct/plug-next/CroctProvider",component:"CroctProvider"},targets:{variable:"children"}})})})),pageRouterProvider:new Ke(e,new Ge({fileSystem:this.getFileSystem(),codemod:new He({languages:["typescript","jsx"],codemod:new gt({fallbackToNamedExports:false,fallbackCodemod:new dn({provider:{component:"CroctProvider",module:"@croct/plug-next/CroctProvider"}}),wrapper:{module:"@croct/plug-next/CroctProvider",component:"CroctProvider"},targets:{component:"Component"}})})})),fallbackProvider:new Ke(e,new Ge({fileSystem:this.getFileSystem(),codemod:new He({languages:["typescript","jsx"],codemod:new gt({fallbackToNamedExports:false,fallbackCodemod:new dn({provider:{component:"CroctProvider",module:"@croct/plug-react",props:a}}),wrapper:{module:"@croct/plug-react",component:"CroctProvider",props:a},targets:{component:"Component"}})})}))}})},[i]:()=>null}})})}getCodeFormatter(){return this.share(this.getCodeFormatter,()=>{let e=Symbol("unknown");return new Ko(new Kt({discriminator:async()=>await this.getPlatformProvider().get()??e,mapping:{javascript:()=>this.getJavaScriptFormatter(),react:()=>this.getJavaScriptFormatter(),nextjs:()=>this.getJavaScriptFormatter(),[e]:()=>{throw new U("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 Vo(new Map(Object.entries(this.getPackageManagers()))))}getPackageManagers(){return this.getNodePackageManagers()}getPackageManager(){return this.share(this.getPackageManager,()=>new _n(new Qt(this.getNodePackageManagerProvider(),new Ne(()=>{throw new U("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 _n(new Qt(this.getNodePackageManagerProvider(),new Nn(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 jn(new ua(new Jt({candidates:Object.entries(e).map(([r,i])=>({value:i,condition:new la({process:this.configuration.process,variable:"npm_config_user_agent",value:new RegExp(`^${r}`)})}))}),new Jt({candidates:Object.entries(e).map(([r,i])=>({value:i,condition:new Un(new ca({packageManager:r,fileSystem:t,projectDirectory:this.workingDirectory}),new Ln({fileSystem:t,files:n[r]}))}))})),this.workingDirectory)})}getNodePackageManagers(){return this.share(this.getNodePackageManagers,()=>{let e=this.getFileSystem(),t={projectDirectory:this.workingDirectory,fileSystem:e,commandExecutor:this.getCommandExecutor(),executableLocator:this.getExecutableLocator()},n=new Cn,r={fileSystem:e,projectDirectory:this.workingDirectory,packageValidator:n};return {npm:new at({...r,agent:new No(t)}),yarn:new at({...r,agent:new $o(t)}),bun:new at({...r,agent:new zo(t)}),pnpm:new at({...r,agent:new _o(t)})}})}getNodeServerProvider(){return this.share(this.getNodeServerProvider,()=>new so({packageManager:this.getNodePackageManager(),factory:this.getServerFactory(),parsers:[new po,new co,new lo,new uo]}))}getServerProvider(){return this.share(this.getServerProvider,()=>{let e=Symbol("unknown");return new Kt({discriminator:async()=>await this.getPlatformProvider().get()??e,mapping:{javascript:()=>this.getNodeServerProvider().get(),react:()=>this.getNodeServerProvider().get(),nextjs:()=>this.getNodeServerProvider().get(),[e]:()=>null}})})}getServerFactory(){return this.share(this.getServerFactory,()=>new Zo(new Ao({commandExecutor:this.getCommandExecutor(),workingDirectory:this.workingDirectory,startupTimeout:2e4,startupCheckDelay:1500,lookupMaxPorts:30,lookupTimeout:2e3,processObserver:this.configuration.process})))}getJavaScriptFormatter(){return this.share(this.getJavaScriptFormatter,()=>new Wr({commandExecutor:this.getCommandExecutor(),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 jo({fileSystem:this.getFileSystem(),tsConfigLoader:this.getTsConfigLoader(),projectDirectory:this.workingDirectory}))}getTsConfigLoader(){return this.share(this.getTsConfigLoader,()=>new Fo({fileSystem:this.getFileSystem(),tsconfigValidator:new Wo}))}getCommandExecutor(){return this.share(this.getCommandExecutor,()=>new Ho)}getExecutableLocator(){return this.share(this.getExecutableLocator,()=>{let{process:e}=this.configuration;return new pa({fileSystem:this.getFileSystem(),cache:new cache.AutoSaveCache(new cache.InMemoryCache),executablePaths:e.getEnvList("PATH")??[],executableExtensions:e.getEnvList("PATHEXT")??[]})})}getPlatformProvider(){return this.share(this.getPlatformProvider,()=>{let e=new at({projectDirectory:this.workingDirectory,packageValidator:new Cn,fileSystem:this.getFileSystem(),agent:new Uo});return new jn(new Jt({candidates:[{value:"nextjs",condition:new Fn({packageManager:e,dependencies:["next"]})},{value:"react",condition:new Fn({packageManager:e,dependencies:["react"]})},{value:"javascript",condition:new qo({packageManager:e})}]}),this.workingDirectory)})}getConfigurationManager(){return this.share(this.getConfigurationManager,()=>{let e=this.getOutput(),t=new vr({fileSystem:this.getFileSystem(),validator:new Ri,projectDirectory:this.workingDirectory});return new sa({workingDirectory:this.workingDirectory,store:this.getCliConfigurationStore(),manager:new bi(this.configuration.interactive&&!this.isReadOnlyMode()?new Vr({manager:t,initializer:{initialize:async()=>{await this.init({}),e.break();}}}):t)})})}getUserApi(e=false){return e?new mn(this.getGraphqlClient(true)):this.share(this.getUserApi,()=>new mn(this.getGraphqlClient()))}getOrganizationApi(){return this.share(this.getOrganizationApi,()=>new Cr(this.getGraphqlClient(),this.getHierarchyResolver()))}getWorkspaceApi(){return this.share(this.getWorkspaceApi,()=>new Pr(this.getGraphqlClient(),this.getHierarchyResolver()))}getApplicationApi(){return this.share(this.getApplicationApi,()=>new Rr(this.getGraphqlClient(),this.getHierarchyResolver()))}getHierarchyResolver(){return this.share(this.getHierarchyResolver,()=>{let e=this.getFileSystem();return new ja(this.getGraphqlClient(),cache.AdaptedCache.transformValues(new kn({fileSystem:e,directory:e.joinPaths(this.configuration.directories.cache,"hierarchy")}),cache.AdaptedCache.jsonSerializer(),cache.AdaptedCache.jsonDeserializer()))})}getGraphqlClient(e=false){return e?new ln({endpoint:this.configuration.adminGraphqlEndpoint,tokenProvider:{getToken:()=>this.getAuthenticator().getToken()}}):this.share(this.getGraphqlClient,()=>{let t=this.getAuthenticator();return new ln({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 Jr({platform:e.process.getPlatform(),commandExecutor:this.getCommandExecutor(),timeout:2e3,listener:new va({api:this.getUserApi(true),pollingInterval:1e3})})})}getFileSystem(){return this.share(this.getFileSystem,()=>new Qr({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:xt.Instant.now(n).getSeconds()})}getEmailLinkGenerator(){return this.share(this.getEmailLinkGenerator,()=>new Br({detector:new Yr(new Xr,new ti),templates:{google:new ri,icloud:new ii,microsoft:new oi,proton:new ai,yahoo:new si}}))}getClock(){return nl.SystemClock.UTC}getProtocolRegistryProvider(){return this.share(this.getProtocolRegistryProvider,()=>new Ne(()=>{let e=this.getFileSystem(),{process:t}=this.configuration;switch(t.getPlatform()){case "darwin":return new ta({fileSystem:e,appDirectory:e.joinPaths(this.configuration.directories.data,"apps"),commandExecutor:this.getCommandExecutor()});case "win32":return new na({commandExecutor:this.getCommandExecutor()});case "linux":return new ra({fileSystem:e,homeDirectory:this.configuration.directories.home,commandExecutor:this.getCommandExecutor()});default:return null}}))}getCliConfigurationStore(){return this.share(this.getCliConfigurationStore,()=>{let e=this.getFileSystem();return new fa({fileSystem:e,store:new ga({fileSystem:e,validator:new aa,filePath:e.joinPaths(this.configuration.directories.config,"config.json")})})})}async execute(e,t){if(this.isReadOnlyMode()&&!st.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=st.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(st.handleError(e)),t.exit()}static handleError(e){switch(true){case e instanceof ne: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 I:if(e.tracing.length>0){let t=e.tracing.map(({name:n,source:r},i)=>{let a=r!==void 0?` at ${st.getSourceLocation(r)}`:"";return `${" ".repeat(i+1)}\u21B3 \`${n}\`${a}`}).join(`
1827
+ \u{1F517} ${nt.bold("Useful links")}
1828
+ `,n+=t.map(({label:r,url:i})=>` \u2022 ${ul(r,i,{fallback:()=>`${r}: ${i}`})}`).join(`
1829
+ `)),n}};var ta=class{constructor(){this.listeners={};}on(e,t){this.listeners[e]===void 0&&(this.listeners[e]=new Set),this.listeners[e].add(t);}off(e,t){this.listeners[e]!==void 0&&this.listeners[e].delete(t);}async emit(e,...t){this.listeners[e]!==void 0&&await Promise.all(Array.from(this.listeners[e]).map(n=>n(...t)));}};var na=class{constructor(){this.eventDispatcher=new ta;Le.on("SIGTERM",()=>this.exit()),Le.on("SIGINT",()=>this.exit());}getCurrentDirectory(){return Le.cwd()}getEnvValue(e){return Le.env[e]??null}getEnvList(e){return this.getEnvValue(e)?.split(delimiter)??null}getPlatform(){return Le.platform}getStandardError(){return Le.stderr}getStandardInput(){return Le.stdin}getStandardOutput(){return Le.stdout}on(e,t){this.eventDispatcher.on(e,t);}off(e,t){this.eventDispatcher.off(e,t);}async exit(e){return await this.eventDispatcher.emit("exit").catch(()=>{}),Le.exit(e)}changeDirectory(e){Le.chdir(e);}};var ra=class{constructor({callback:e}){this.callback=e;}async execute(e,t){try{return await this.callback(e,t)}catch(n){if(!(n instanceof I))throw I.fromCause(n)}}};var Km=z.strictObject({}),ia=class extends v{constructor(){super(Km);}};var oa=class o{static{this.REPOSITORY_PATTERNS=[/git\+(https:\/\/.+)\.git$/];}constructor(e){this.metadataProvider=e;}async get(e){let t=this.getMetadataUrl(e);if(t===null)throw new W("Unsupported NPM URL.",{reason:"not_supported",url:e});let{value:n}=await this.metadataProvider.get(t),r=o.getRepositoryUrl(n.repository);return r===null?{url:e,value:[]}:{url:r,value:[{pattern:".*",destination:r}]}}static getRepositoryUrl(e){for(let t of o.REPOSITORY_PATTERNS){let n=t.exec(e.url);if(n!==null)return new URL(`${n[1]}/`)}return null}getMetadataUrl(e){if(e.protocol!=="npm:")return null;let t=e.pathname.slice(1);return new URL(`https://registry.npmjs.org/${t}/latest`)}};var aa=class o{constructor({provider:e,reader:t}){this.provider=e,this.reader=t;}static text(e){return new o({provider:e,reader:t=>t.text()})}static json(e){return new o({provider:e,reader:t=>t.json()})}static blob(e){return new o({provider:e,reader:t=>t.blob()})}async get(e){let t=await this.provider.get(e),n;try{n=await this.reader(new Response(t.value.body));}catch(r){throw new W("Failed to read response body.",{reason:"unexpected_result",url:e,cause:r})}return {url:t.url,value:n}}};var Zm=z.object({name:z.string(),repository:z.object({type:z.string(),url:z.string()})}),sa=class extends Q{constructor(){super(Zm);}};var ca=class{constructor({provider:e,logger:t,label:n}){this.provider=e,this.logger=t,this.label=n;}get(e){return this.logger.nest({message:`\`${this.label??this.provider.constructor.name}\``,level:LogLevel.DEBUG},()=>this.trace(e))}async trace(e){this.logger.log({message:`URL: ${e}`,level:LogLevel.DEBUG});try{let t=await this.provider.get(e);return this.logger.log({message:"No errors",level:LogLevel.DEBUG}),t}catch(t){throw this.logger.log({message:`Error: ${d.formatMessage(t)}`,level:LogLevel.DEBUG}),t}}};var la=class{constructor(e){this.storage=new AsyncLocalStorage;this.logger=e;}nest(e,t){let n=this.storage.getStore();if(n!==void 0)return this.logNested(n,e,t);let r={level:0,logs:[]};return this.storage.run(r,()=>this.logNested(r,e,t))}async logNested(e,t,n){this.buffer(e,{...t,message:`\u250C\u2500 ${t.message}`}),e.level++;try{return await n()}finally{e.level--,this.buffer(e,{...t,message:"\u2514\u2500"}),e.level===0&&(e.logs.forEach(r=>this.logger.log(r)),e.logs=[]);}}log(e){let t=this.storage.getStore();if(t!==void 0){this.buffer(t,e);return}this.logger.log(e);}buffer(e,t){e.logs.push({...t,message:`${e.level>0?`${"\u2502 ".repeat(e.level-1)}\u2502 `:""}${t.message}`});}};var ua=class{constructor(e){this.output=e;}log(e){switch(e.level){case "debug":this.output.debug(e.message);break;case "info":this.output.inform(e.message);break;case "warning":this.output.warn(e.message);break;case "error":this.output.alert(e.message);}}};var ma=class o{static{this.PREFIX="?/";}constructor(e){this.rootPath=e.rootPath,this.importResolver=e.importResolver,this.exportMatcher=e.exportMatcher,this.importCodemod=e.importCodemod,this.fileSystem=e.fileSystem,this.maxSearchDepth=e.maxSearchDepth;}apply(e){return this.importCodemod.apply(e,{transformer:t=>{if(!t.source.startsWith(o.PREFIX))return;let n=t.source.slice(o.PREFIX.length);return this.resolvePath(t,n,e)}})}async resolvePath(e,t,n){let r=new Minimatch(t);for await(let i of this.fileSystem.list(this.rootPath.get(),this.maxSearchDepth))if(i.type==="file"&&r.match(i.name)&&await this.exportMatcher.test(await new Response(i.content).text(),e))return this.importResolver.getImportPath(i.name,n);throw new Ge(`Unable to resolve import \`${t}\` from \`${n}\`.`,{reason:"not_found"})}};var da=class{constructor({codemods:e}){this.codemods=e;}apply(e,t){let[,n]=Object.entries(this.codemods).find(([r])=>minimatch(e,r))??[];return n===void 0?Promise.resolve({modified:false,result:e}):n.apply(e,t)}};function Rc(o){let e=typeof o=="string"?Ke(o,["jsx","typescript"]):o,t=[];return traverse(e,{ExportDeclaration:n=>{let{node:r}=n;if(g.isExportNamedDeclaration(r))if(r.specifiers.length>0)for(let i of r.specifiers)g.isExportSpecifier(i)?(!g.isIdentifier(i.exported)||i.exported.name!=="default")&&t.push(g.isIdentifier(i.exported)?i.exported.name:i.exported.value):g.isExportNamespaceSpecifier(i)&&g.isIdentifier(i.exported)&&t.push(i.exported.name);else if(g.isVariableDeclaration(r.declaration))for(let i of r.declaration.declarations)g.isVariableDeclarator(i)&&g.isIdentifier(i.id)&&t.push(i.id.name);else typeof r.declaration=="object"&&r.declaration!==null&&"id"in r.declaration&&g.isIdentifier(r.declaration.id)&&t.push(r.declaration.id.name);return n.skip()}}),t}async function Tc(o,e){let t=[];return traverse(o,{ImportDeclaration:n=>{let{node:r}=n,i=Promise.resolve(e(ed(r)));return i!==void 0&&t.push(i.then(a=>typeof a=="string"&&r.source.value!==a?(r.source.value=a,true):false)),n.skip()}}),(await Promise.all(t)).some(n=>n)}function ed(o){let e={names:[],source:o.source.value};for(let t of o.specifiers)g.isImportSpecifier(t)&&e.names.push(g.isIdentifier(t.imported)?t.imported.name:t.imported.value);return e}var fa=class{async apply(e,t){let n=await Tc(e,t.transformer);return {result:e,modified:n}}};var ya=class{constructor(...e){this.codemods=e;}async apply(e,t){let n=e,r=false;for(let i of this.codemods){let a=await i.apply(n,t);n=a.result,r=r||a.modified;}return {modified:r,result:n}}};var ha=class o{constructor(e,t){this.client=e,this.cache=t;}getHierarchy(e){return this.cache.get(o.getHierarchyKey(e),async()=>{let t=await this.resolveHierarchy(e);return await this.saveCache(e,t),t})}async resolveHierarchy(e){let{data:{organization:t}}=await this.client.execute(cp,e),n=t?.id,r=t?.workspace?.id,i=t?.workspace?.application?.id;return o.checkMissing("organization",e.organizationSlug,n),"workspaceSlug"in e?(o.checkMissing("workspace",e.workspaceSlug,r),"applicationSlug"in e?(o.checkMissing("application",e.applicationSlug,i),{organizationId:n,workspaceId:r,applicationId:i}):{organizationId:n,workspaceId:r}):{organizationId:n}}async saveCache(e,t){let n=[this.setCache({organizationSlug:e.organizationSlug},{organizationId:t.organizationId})];"workspaceId"in t&&"workspaceSlug"in e&&n.push(this.setCache({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug},{organizationId:t.organizationId,workspaceId:t.workspaceId})),"applicationId"in t&&"applicationSlug"in e&&n.push(this.setCache({organizationSlug:e.organizationSlug,workspaceSlug:e.workspaceSlug,applicationSlug:e.applicationSlug},{organizationId:t.organizationId,workspaceId:t.workspaceId,applicationId:t.applicationId})),await Promise.all(n);}setCache(e,t){return this.cache.set(o.getHierarchyKey(e),t)}static getHierarchyKey(e){let t=[`organization:${e.organizationSlug}`];return "workspaceSlug"in e&&t.push(`workspace:${e.workspaceSlug}`),"applicationSlug"in e&&t.push(`application${e.applicationSlug}`),t.join("/")}static checkMissing(e,t,n){if(n===void 0)throw new te(`No ${e} found with slug "${t}".`,[],{reason:"not_found"})}};var Sa=class o{constructor(e){this.instances=new Map;this.configuration=e,this.skipPrompts=e.skipPrompts,this.initialDirectory=e.directories.current??e.process.getCurrentDirectory(),this.workingDirectory=new Jo(this.initialDirectory);}static{this.READ_ONLY_COMMANDS=new Set([On,on,an,kt,At,nn,rn,cn,Bt]);}static fromDefaults(e){let t=nd("com.croct.cli"),n=new na;return new o({program:e.program??(()=>{throw new d("CLI is running in standalone mode.")}),process:e.process??n,quiet:e.quiet??false,debug:e.debug??false,interactive:e.interactive??!rd.isCI,apiKey:e.apiKey,skipPrompts:e.skipPrompts??false,adminTokenDuration:e.adminTokenDuration??7*gt.LocalTime.SECONDS_PER_DAY,apiKeyTokenDuration:e.apiKeyTokenDuration??30*gt.LocalTime.SECONDS_PER_MINUTE,cliTokenDuration:e.cliTokenDuration??90*gt.LocalTime.SECONDS_PER_DAY,cliTokenFreshPeriod:e.cliTokenFreshPeriod??15*gt.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){return this.execute(new On({packageManager:this.getNodePackageManager(),protocolRegistryProvider:this.getProtocolRegistryProvider(),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 $o({program:this.configuration.program,protocol:this.configuration.deepLinkProtocol,configurationProvider:this.getCliConfigurationStore(),workingDirectory:new Qo(this.configuration.process),fileSystem:this.getFileSystem(),io:{input:this.getInput(),output:this.getOutput()}}),e)}init(e){return this.execute(new rr({sdkProvider:this.getSdkProvider(),platformProvider:this.getPlatformProvider(),configurationManager:this.getConfigurationManager(),skipConfirmation:new Ro(new Tn(new En(new Cn({fileSystem:this.getFileSystem(),files:[".git"]})))),api:{user:this.getUserApi(),organization:this.getOrganizationApi(),workspace:this.getWorkspaceApi()},form:{organization:new pr({input:this.getFormInput(),output:this.getOutput(),userApi:this.getUserApi()}),workspace:new cr({input:this.getFormInput(),output:this.getOutput(),organizationApi:this.getOrganizationApi()}),application:new lr({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()})},io:{input:this.getInput(),output:this.getOutput()}}),e)}install(e){return this.execute(new on({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),io:{input:this.getInput(),output:this.getOutput()}}),e)}upgrade(e){return this.execute(new an({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),form:{slotForm:new Qe({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),componentForm:new Be({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()})},io:{input:this.getInput(),output:this.getOutput()}}),e)}addSlot(e){return this.execute(new kt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),workspaceApi:this.getWorkspaceApi(),slotForm:new Qe({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}removeSlot(e){return this.execute(new nn({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),slotForm:new Qe({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}addComponent(e){return this.execute(new At({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new Be({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}removeComponent(e){return this.execute(new rn({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new Be({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),io:{input:this.getInput(),output:this.getOutput()}}),e)}login(e){return this.execute(new ir({authenticator:this.getAuthenticator()}),e)}logout(){return this.execute(new Bt({authenticator:this.getAuthenticator(),output:this.getOutput()}),{})}admin(e){return this.execute(new fr({output:this.getOutput(),pageForm:new Cr({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 cn({configurationManager:this.getConfigurationManager(),fileSystem:this.getFileSystem(),templateForm:new Vr({input:this.getFormInput(),form:{component:new Be({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),slot:new Qe({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),experience:new Ur({input:this.getFormInput(),output:this.getOutput(),workspaceApi:this.getWorkspaceApi()}),audience:new qr({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");try{return await t.getOptions(e)}finally{r.stop();}}getUseTemplateCommand(){return new Hr({templateProvider:new Mt({provider:new dn(this.getTemplateProvider()),validator:new hn}),fileSystem:this.getFileSystem(),action:this.getImportAction(),io:{input:this.getInput(),output:this.getOutput()}})}createApiKey(e){return this.execute(new Ko({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 Rn(new Ar(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 Kn({input:this.configuration.process.getStandardInput(),output:this.configuration.process.getStandardOutput(),onAbort:()=>e.exit(),onInteractionStart:()=>e.suspend(),onInteractionEnd:()=>e.resume()});return this.skipPrompts?new Rn(t):t})}getNonInteractiveOutput(e=false){let{configuration:t}=this;return new Qt({output:t.process.getStandardOutput(),formatter:this.getLogFormatter(),interactive:false,quiet:e,onExit:()=>t.process.exit(),linkOpener:async n=>{await Oc(n,{wait:true});}})}getHierarchicalLogger(){return this.share(this.getHierarchicalLogger,()=>new la(this.getLogger()))}getLogger(){return this.share(this.getLogger,()=>{let e=new ua(this.getOutput());return this.configuration.debug?e:new FilteredLogger(e,LogLevel.WARNING)})}getOutput(){return this.share(this.getOutput,()=>{let{configuration:e}=this;return new Qt({output:e.process.getStandardOutput(),formatter:this.getLogFormatter(),interactive:this.configuration.interactive,quiet:this.configuration.quiet,onExit:()=>e.process.exit(),linkOpener:async t=>{await Oc(t);}})})}getLogFormatter(){return this.share(this.getLogFormatter,()=>new ea)}getTemplateProvider(){return this.share(this.getTemplateProvider,()=>{let e=n=>new Xe(...["template.json5","template.json"].map(r=>new Dt({dataProvider:n,registryProvider:new xn([{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 fn({resourceCache:new AutoSaveCache(new InMemoryCache),errorCache:new InMemoryCache,provider:new Xe(new Dt({dataProvider:this.traceProvider({label:"ResourceProvider",provider:e(new mt(new Xe(this.traceProvider({provider:new ln(t)}),this.traceProvider({provider:new un(t)}))))}),registryProvider:this.traceProvider({label:"NpmRegistryProvider",provider:new oa(new Mt({provider:aa.json(this.traceProvider({provider:this.getHttpProvider()})),validator:new sa}))})}),e(new mt(this.getFileProvider())))})})})}getFileProvider(){return this.share(this.getFileProvider,()=>{let e=this.traceProvider({provider:this.getHttpProvider()}),t=this.traceProvider({provider:new ai(this.getFileSystem())}),n=new Xe(t,this.traceProvider({provider:new ln(e)}),this.traceProvider({provider:new un(e)}));return this.traceProvider({label:"FileProvider",provider:new Xe(t,this.traceProvider({provider:new Dt({baseUrl:new URL("./",this.configuration.templateRegistryUrl),dataProvider:this.traceProvider({label:"ResourceProvider",provider:n}),registryProvider:new Li({url:this.configuration.templateRegistryUrl,provider:this.traceProvider({label:"GlobalRegistryProvider",provider:new fn({errorCache:new InMemoryCache,resourceCache:new AutoSaveCache(new InMemoryCache),provider:new Mt({provider:new dn(new mt(n)),validator:new li})})})})})}))})})}traceProvider({provider:e,label:t}){return new ca({label:t,provider:e,logger:this.getHierarchicalLogger()})}getImportAction(){return this.share(this.getImportAction,()=>{let e=this.getFileSystem(),t={run:new L({action:new Ye(new Oe(()=>new Ji(t))),validator:new Qi}),try:new L({action:new Ye(new Oe(()=>new Yr(t.run))),validator:new yi}),test:new L({action:new Ye(new Oe(()=>new Ti(t.run))),validator:new Di}),repeat:new L({action:new Ye(new Oe(()=>new To(t.run))),validator:new Oo}),print:new L({action:new Mi,validator:new $i}),fail:new L({action:new zi,validator:new _i}),define:new L({action:new eo,validator:new Xi}),prompt:new L({action:new qi,validator:new Hi}),"change-directory":new L({action:new ao({fileSystem:e,rootDirectory:this.initialDirectory,currentDirectory:this.workingDirectory}),validator:new oo}),"open-link":new L({action:new Bi,validator:new Yi}),"start-server":new L({action:new Gi({serverProvider:this.getServerProvider()}),validator:new Zi}),"stop-server":new L({action:new to({serverProvider:this.getServerProvider()}),validator:new no}),"execute-package":new L({action:new po({packageManager:this.getPackageManager(),packageManagerProvider:this.getPackageManagerRegistry(),workingDirectory:this.workingDirectory,commandExecutor:new fo({cols:80,rows:24}),commandTimeout:2*60*1e3,sourceChecker:{test:()=>true}}),validator:new co}),"check-dependencies":new L({action:new oi({packageManager:this.getPackageManager()}),validator:new hi}),download:new L({action:new Gr({fileSystem:e,provider:this.getFileProvider(),codemod:new da({codemods:{"**/*.{js,jsx,ts,tsx}":new ya(new ma({fileSystem:e,rootPath:this.workingDirectory,maxSearchDepth:10,importResolver:this.getNodeImportResolver(),importCodemod:new Ue({fileSystem:e,codemod:new We({languages:["typescript","jsx"],codemod:new fa})}),exportMatcher:{test:(n,{names:r})=>r.length===0?true:Rc(n).some(i=>r.includes(i))}}),new Ve(this.getJavaScriptFormatter()))}})}),validator:new Si}),"add-dependency":new L({action:new Kr({packageManager:this.getPackageManager()}),validator:new Ii}),"locate-file":new L({action:new Zr({projectDirectory:this.workingDirectory,fileSystem:e,matcherProvider:{get:async n=>{let r=e.joinPaths(this.workingDirectory.get(),".gitignore"),i=ko.fromPattern(n);if(await e.exists(r)){let a=await e.readTextFile(r);return new Ao(new En(Eo.fromPatterns(a)),i)}return i}}}),validator:new xi}),"replace-file-content":new L({action:new Jr({fileSystem:e}),validator:new vi}),initialize:new L({action:new ra({callback:()=>this.init({})}),validator:new ia}),"add-slot":new L({action:new Qr({installer:(n,r)=>{let i=this.getNonInteractiveOutput(true);return this.execute(new kt({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),workspaceApi:this.getWorkspaceApi(),slotForm:new Qe({input:this.getNonInteractiveInput(),output:i,workspaceApi:this.getWorkspaceApi()}),io:{output:i}}),{slots:n,example:r})}}),validator:new Pi}),"add-component":new L({action:new Br({installer:n=>{let r=this.getNonInteractiveOutput(true);return this.execute(new At({sdk:this.getSdk(),configurationManager:this.getConfigurationManager(),componentForm:new Be({input:this.getNonInteractiveInput(),output:r,workspaceApi:this.getWorkspaceApi()}),io:{output:r}}),{components:n})}}),validator:new Ci}),"create-resource":new L({action:new ti({configurationManager:this.getConfigurationManager(),matcher:new ri({workspaceApi:this.getWorkspaceApi()}),api:{user:this.getUserApi(),workspace:this.getWorkspaceApi(),organization:this.getOrganizationApi()},mappingForm:new ni({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 ki}),"format-code":new L({action:new Ei({formatter:this.getCodeFormatter()}),validator:new Ri}),import:new L({action:new Ye(new Oe(()=>new di({runner:t.run,templateProvider:new fi({evaluator:new ui({functions:ns}),validator:new hn,templateProvider:this.getTemplateProvider(),fileProvider:new mt(this.getFileProvider())}),variables:this.getActionVariables()}))),validator:new Ai})};return t.import})}getActionVariables(){let e=t=>new URL(t,this.configuration.adminUrl).toString();return {project:{features:ne.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load(),{features:r}=await this.getWorkspaceApi().getFeatures({organizationSlug:t,workspaceSlug:n})??{};return r??{}}),quotas:ne.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load(),{quotas:r}=await this.getWorkspaceApi().getFeatures({organizationSlug:t,workspaceSlug:n})??{};return r??{}}),organization:ne.transient(async()=>{let{organization:t}=await this.getConfigurationManager().load();return {slug:t,url:e(`organizations/${t}`)}}),workspace:ne.transient(async()=>{let{organization:t,workspace:n}=await this.getConfigurationManager().load();return {slug:n,url:e(`organizations/${t}/workspaces/${n}`)}}),application:ne.transient(async()=>{let{organization:t,workspace:n,applications:r}=await this.getConfigurationManager().load(),i=`organizations/${t}/workspaces/${n}/applications/`;return {development:{slug:r.development,url:e(i+r.development)},production:{slug:r.production,url:e(i+r.production)}}}),path:{example:ne.transient(async()=>(await this.getConfigurationManager().load()).paths.examples),component:ne.transient(async()=>(await this.getConfigurationManager().load()).paths.components)},platform:ne.transient(async()=>await this.getPlatformProvider().get()??"unknown"),server:ne.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 ii)}getAuthenticator(){return this.share(this.getAuthenticator,()=>{if(this.configuration.apiKey!==void 0)return new Zo({apiKey:this.configuration.apiKey,clock:this.getClock(),tokenDuration:this.configuration.apiKeyTokenDuration});let e=this.getFormInput(),t=this.getFileSystem(),n=new mr({input:e,output:this.getOutput(),userApi:this.getUserApi(true),form:{signIn:new dr({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 gr({input:e,output:this.getOutput(),userApi:this.getUserApi(true),listener:this.getTokenListener(),emailLinkGenerator:this.createEmailLinkGenerator(this.configuration.emailSubject.accountActivation),verificationLinkDestination:this.configuration.verificationLinkDestination.accountActivation})}}),r=this.getUserApi(true),i=new Bo({cacheKey:"token",cacheProvider:new Yo({clock:this.getClock(),tokenFreshPeriod:this.configuration.cliTokenFreshPeriod,tokenIssuer:()=>r.issueToken({duration:this.configuration.cliTokenDuration}),cacheProvider:new gn({fileSystem:t,directory:this.configuration.directories.config,useKeyAsFileName:true})}),authenticator:new Er({default:this.configuration.interactive?n:new kr({authenticator:n,instruction:{message:"Authentication required.",suggestions:["Run `login` to authenticate"],reason:"precondition"}}),credentials:n})});return this.configuration.interactive?new qo({authenticator:i,invitationForm:new Uo({output:this.getOutput(),input:e,userApi:this.getUserApi(true)})}):i})}getSdk(){return this.share(this.getSdk,()=>{let e=new Wt(this.getSdkProvider(),new Oe(()=>{throw new U("No suitable SDK detected.",{reason:"not_supported",suggestions:["Make sure you are running the command in the project root directory."]})}));return new Po(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 Lt({discriminator:async()=>await this.getPlatformProvider().get()??i,mapping:{javascript:()=>new Yn({...r,bundlers:["vite","parcel","tsup","rollup"]}),react:()=>new Xn({...r,importResolver:n,codemod:{provider:new Ve(e,new Ue({fileSystem:this.getFileSystem(),codemod:new We({languages:["typescript","jsx"],codemod:new pt({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 a={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 nr({...r,userApi:this.getUserApi(),applicationApi:this.getApplicationApi(),importResolver:n,codemod:{middleware:new Ve(e,new Ue({fileSystem:this.getFileSystem(),codemod:new We({languages:["typescript","jsx"],codemod:new Ir({import:{module:"@croct/plug-next/middleware",middlewareName:"middleware",middlewareFactoryName:"withCroct",configName:"config",matcherName:"matcher",matcherLocalName:"croctMatcher"}})})})),appRouterProvider:new Ve(e,new Ue({fileSystem:this.getFileSystem(),codemod:new We({languages:["typescript","jsx"],codemod:new pt({fallbackToNamedExports:false,fallbackCodemod:new xr({provider:{component:"CroctProvider",module:"@croct/plug-next/CroctProvider"}}),wrapper:{module:"@croct/plug-next/CroctProvider",component:"CroctProvider"},targets:{variable:"children"}})})})),pageRouterProvider:new Ve(e,new Ue({fileSystem:this.getFileSystem(),codemod:new We({languages:["typescript","jsx"],codemod:new pt({fallbackToNamedExports:false,fallbackCodemod:new tn({provider:{component:"CroctProvider",module:"@croct/plug-next/CroctProvider"}}),wrapper:{module:"@croct/plug-next/CroctProvider",component:"CroctProvider"},targets:{component:"Component"}})})})),fallbackProvider:new Ve(e,new Ue({fileSystem:this.getFileSystem(),codemod:new We({languages:["typescript","jsx"],codemod:new pt({fallbackToNamedExports:false,fallbackCodemod:new tn({provider:{component:"CroctProvider",module:"@croct/plug-react",props:a}}),wrapper:{module:"@croct/plug-react",component:"CroctProvider",props:a},targets:{component:"Component"}})})}))}})},[i]:()=>null}})})}getCodeFormatter(){return this.share(this.getCodeFormatter,()=>{let e=Symbol("unknown");return new wo(new Lt({discriminator:async()=>await this.getPlatformProvider().get()??e,mapping:{javascript:()=>this.getJavaScriptFormatter(),react:()=>this.getJavaScriptFormatter(),nextjs:()=>this.getJavaScriptFormatter(),[e]:()=>{throw new U("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 bo(new Map(Object.entries(this.getPackageManagers()))))}getPackageManagers(){return this.getNodePackageManagers()}getPackageManager(){return this.share(this.getPackageManager,()=>new Pn(new Wt(this.getNodePackageManagerProvider(),new Oe(()=>{throw new U("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 Pn(new Wt(this.getNodePackageManagerProvider(),new xn(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 An(new Vo(new Vt({candidates:Object.entries(e).map(([r,i])=>({value:i,condition:new Wo({process:this.configuration.process,variable:"npm_config_user_agent",value:new RegExp(`^${r}`)})}))}),new Vt({candidates:Object.entries(e).map(([r,i])=>({value:i,condition:new Tn(new jo({packageManager:r,fileSystem:t,projectDirectory:this.workingDirectory}),new Cn({fileSystem:t,files:n[r]}))}))})),this.workingDirectory)})}getNodePackageManagers(){return this.share(this.getNodePackageManagers,()=>{let e=this.getFileSystem(),t={projectDirectory:this.workingDirectory,fileSystem:e,commandExecutor:this.getCommandExecutor(),executableLocator:this.getExecutableLocator()},n=new mn,r={fileSystem:e,projectDirectory:this.workingDirectory,packageValidator:n};return {npm:new et({...r,agent:new lo(t)}),yarn:new et({...r,agent:new uo(t)}),bun:new et({...r,agent:new mo(t)}),pnpm:new et({...r,agent:new go(t)})}})}getNodeServerProvider(){return this.share(this.getNodeServerProvider,()=>new Fi({packageManager:this.getNodePackageManager(),factory:this.getServerFactory(),parsers:[new ji,new Wi,new Vi,new Ui]}))}getServerProvider(){return this.share(this.getServerProvider,()=>{let e=Symbol("unknown");return new Lt({discriminator:async()=>await this.getPlatformProvider().get()??e,mapping:{javascript:()=>this.getNodeServerProvider().get(),react:()=>this.getNodeServerProvider().get(),nextjs:()=>this.getNodeServerProvider().get(),[e]:()=>null}})})}getServerFactory(){return this.share(this.getServerFactory,()=>new Co(new io({commandExecutor:this.getCommandExecutor(),workingDirectory:this.workingDirectory,startupTimeout:2e4,startupCheckDelay:1500,lookupMaxPorts:30,lookupTimeout:2e3,processObserver:this.configuration.process})))}getJavaScriptFormatter(){return this.share(this.getJavaScriptFormatter,()=>new wr({commandExecutor:this.getCommandExecutor(),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 ho({fileSystem:this.getFileSystem(),tsConfigLoader:this.getTsConfigLoader(),projectDirectory:this.workingDirectory}))}getTsConfigLoader(){return this.share(this.getTsConfigLoader,()=>new yo({fileSystem:this.getFileSystem(),tsconfigValidator:new So}))}getCommandExecutor(){return this.share(this.getCommandExecutor,()=>new vo)}getExecutableLocator(){return this.share(this.getExecutableLocator,()=>{let{process:e}=this.configuration;return new Fo({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 et({projectDirectory:this.workingDirectory,packageValidator:new mn,fileSystem:this.getFileSystem(),agent:new Io});return new An(new Vt({candidates:[{value:"nextjs",condition:new kn({packageManager:e,dependencies:["next"]})},{value:"react",condition:new kn({packageManager:e,dependencies:["react"]})},{value:"javascript",condition:new xo({packageManager:e})}]}),this.workingDirectory)})}getConfigurationManager(){return this.share(this.getConfigurationManager,()=>{let e=this.getOutput(),t=new or({fileSystem:this.getFileSystem(),validator:new pi,projectDirectory:this.workingDirectory});return new Lo({workingDirectory:this.workingDirectory,store:this.getCliConfigurationStore(),manager:new Xr(this.configuration.interactive&&!this.isReadOnlyMode()?new Pr({manager:t,initializer:{initialize:async()=>{await this.init({}),e.break();}}}):t)})})}getUserApi(e=false){return e?new en(this.getGraphqlClient(true)):this.share(this.getUserApi,()=>new en(this.getGraphqlClient()))}getOrganizationApi(){return this.share(this.getOrganizationApi,()=>new ar(this.getGraphqlClient(),this.getHierarchyResolver()))}getWorkspaceApi(){return this.share(this.getWorkspaceApi,()=>new sr(this.getGraphqlClient(),this.getHierarchyResolver()))}getApplicationApi(){return this.share(this.getApplicationApi,()=>new ur(this.getGraphqlClient(),this.getHierarchyResolver()))}getHierarchyResolver(){return this.share(this.getHierarchyResolver,()=>{let e=this.getFileSystem();return new ha(this.getGraphqlClient(),AdaptedCache.transformValues(new gn({fileSystem:e,directory:e.joinPaths(this.configuration.directories.cache,"hierarchy")}),AdaptedCache.jsonSerializer(),AdaptedCache.jsonDeserializer()))})}getGraphqlClient(e=false){return e?new Yt({endpoint:this.configuration.adminGraphqlEndpoint,tokenProvider:{getToken:()=>this.getAuthenticator().getToken()}}):this.share(this.getGraphqlClient,()=>{let t=this.getAuthenticator();return new Yt({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 Dr({platform:e.process.getPlatform(),commandExecutor:this.getCommandExecutor(),timeout:2e3,listener:new Xo({api:this.getUserApi(true),pollingInterval:1e3})})})}getFileSystem(){return this.share(this.getFileSystem,()=>new Or({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:gt.Instant.now(n).getSeconds()})}getEmailLinkGenerator(){return this.share(this.getEmailLinkGenerator,()=>new Mr({detector:new Nr(new $r,new zr),templates:{google:new _r,icloud:new Lr,microsoft:new Fr,proton:new jr,yahoo:new Wr}}))}getClock(){return Dc.SystemClock.UTC}getProtocolRegistryProvider(){return this.share(this.getProtocolRegistryProvider,()=>new Oe(()=>{let e=this.getFileSystem(),{process:t}=this.configuration;switch(t.getPlatform()){case "darwin":return new Do({fileSystem:e,appDirectory:e.joinPaths(this.configuration.directories.data,"apps"),commandExecutor:this.getCommandExecutor()});case "win32":return new Mo({commandExecutor:this.getCommandExecutor()});case "linux":return new No({fileSystem:e,homeDirectory:this.configuration.directories.home,commandExecutor:this.getCommandExecutor()});default:return null}}))}getCliConfigurationStore(){return this.share(this.getCliConfigurationStore,()=>{let e=this.getFileSystem();return new Go({fileSystem:e,store:new Ho({fileSystem:e,validator:new _o,filePath:e.joinPaths(this.configuration.directories.config,"config.json")})})})}async execute(e,t){if(this.isReadOnlyMode()&&!o.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=o.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(o.handleError(e)),t.exit()}static handleError(e){switch(true){case e instanceof te: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 I:if(e.tracing.length>0){let t=e.tracing.map(({name:n,source:r},i)=>{let a=r!==void 0?` at ${o.getSourceLocation(r)}`:"";return `${" ".repeat(i+1)}\u21B3 \`${n}\`${a}`}).join(`
1829
1830
  `);return new d(`${e.message}
1830
1831
 
1831
1832
  \u25B6\uFE0F **Trace**
1832
- ${t}`,e.help)}break;case e instanceof ut: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}`}};st.READ_ONLY_COMMANDS=new Set([qn,yn,hn,Mt,Nt,gn,fn,In,cn]);var Wa=st;function rl(o){let e=new Ns().name("croct").description("Manage your Croct projects").enablePositionalOptions().option("--cwd <path>","The working directory.",y=>{try{return fs$1.realpathSync(y)}catch{throw new Ue("The path does not exist.")}}).addOption(new se("--api-key <key>","The API key to use for authentication.").env("CROCT_API_KEY").argParser(y=>{try{return apiKey.ApiKey.parse(y)}catch{throw new Ue("The API key is malformed.")}})).option("--registry <url>","The template registry.",y=>{if(!URL.canParse(y))throw new Ue("Malformed URL.");return y}).option("--no-interaction","Disable interaction mode.").addOption(new se("-s, --skip-prompts","Skip prompts with default options.").default(false)).addOption(new se("-q, --quiet","Disable output messages.").default(false).implies({interaction:false})).option("--debug","Enable debug mode.").version("0.0.1","-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 y=>{await o.cli?.open({url:y});});let t=e.command("login").description("Authenticate your user."),n=new se("-u, --username <username>","The email."),r=new se("-p, --password <password>","The password.");t.command("credentials",{isDefault:true}).description("Authenticate using credentials.").addOption(o.interactive?n:n.makeOptionMandatory()).addOption(o.interactive?r:r.makeOptionMandatory()).action(async y=>{await o.cli?.login({method:"credentials",username:y.username,password:y.password});}),e.command("logout").description("Logout the current user.").action(async()=>{await o.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 y=>{await o.cli?.admin({page:y!==void 0?y.join(" "):o.interactive?void 0:"/"});});let i=new se("--wor <workspace-slug>","The workspace slug."),a=new se("--org <organization-slug>","The organization slug."),s=new se("--dev-app <application-slug>","The development application slug."),p=new se("--prod-app <application-slug>","The production application slug.");e.command("init").description("Configure the project.").option("-o, --override","Override any existing configuration.").addOption(new se("-n, --new <resource>","The resources to create.").choices(["organization","org","workspace","wor","application","app"])).addOption(new se("-s, --sdk <platform>","The SDK to use.").choices(["javascript","react","next"])).addOption(o.interactive?a:a.makeOptionMandatory()).addOption(o.interactive?i:i.makeOptionMandatory()).addOption(o.interactive?s:s.makeOptionMandatory()).addOption(p).action(async y=>{await o.cli?.init({override:y.override,new:(()=>{switch(y.new){case "organization":case "org":return "organization";case "workspace":case "wor":return "workspace";case "application":case "app":return "application";default:return}})(),sdk:y.sdk,organization:y.org,workspace:y.wor,devApplication:y.devApp,prodApplication:y.prodApp});}),e.command("install").description("Install content and types.").action(async()=>{await o.cli?.install({});}),e.command("update").description("Update content and types.").action(async()=>{await o.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 y=>{await o.cli?.upgrade({slots:y.slots??(y.components!==void 0?[]:void 0),components:y.components??(y.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(o.interactive?"[slots...]":"<slots...>").option("-e, --example","Generate an implementation example.").action(async(y,M)=>{await o.cli?.addSlot({slots:y,example:M.example});}),c.command("component").description("Add a component to your project.").argument(o.interactive?"[components...]":"<components...>").action(async y=>{await o.cli?.addComponent({components:y});});let l=e.command("remove").description("Remove a resource from your project.");l.command("slot").description("Remove a slot from your project.").argument(o.interactive?"[slots...]":"<slots...>").action(async y=>{await o.cli?.removeSlot({slots:y});}),l.command("component").description("Remove a component from your project.").argument(o.interactive?"[components...]":"<components...>").action(async y=>{await o.cli?.removeComponent({components:y});});let m=e.command("create").description("Create a resource in your project.");m.command("template").description("Create a template from your project.").addArgument(new $s("<path>","The path to the file.").argOptional()).option("-e, --empty","Create an empty template.").action(async(y,M)=>{await o.cli?.createTemplate({file:y,empty:M.empty});});let f=new se("--permissions <permissions...>","The permissions of the API key.").argParser(y=>y.split(",").map(M=>{try{return we.fromValue(M)}catch{throw new Ue(`Unknown permission "${M}".`)}})),b=new se("--env <environment>","The environment of the API key.").choices(["prod","dev"]).argParser(y=>y==="prod"?"PRODUCTION":"DEVELOPMENT");m.command("api-key").description("Create an API key.").option("--name <name>","The name of the API key.").addOption(o.interactive?f:f.makeOptionMandatory()).addOption(o.interactive?b:b.makeOptionMandatory()).option("-c, --copy","Copy the API key to the clipboard.").action(async y=>{await o.cli?.createApiKey({name:y.name,permissions:y.permissions,environment:y.env,copy:y.copy});});let A={},w=e.command("use").description("Use a template.").argument("template","The path to the template.").passThroughOptions(o.cli===void 0).allowUnknownOption(o.cli===void 0||o.template===null).action(async(y,M)=>{await o.cli?.useTemplate({template:y,options:Object.fromEntries(Object.entries(M).map(([j,T])=>[A[j],T]))});});for(let[y,M]of Object.entries(o.template??{})){let j=`--${y}${M.type!=="boolean"?" <value>":""}`,T=new se(j,M.description).makeOptionMandatory(M.required===true);switch(M.type){case "string":M.options!==void 0&&M.options.length>0&&T.choices(M.options);break;case "number":T.argParser(q=>{let xe=Number.parseFloat(q);if(Number.isNaN(xe))throw new Ue("The value must be a number.");return xe});break;case "array":T.argParser(q=>{let xe;try{xe=JSON.parse(q);}catch{}if(xe===void 0||!Array.isArray(xe))throw new Ue("The value must be a JSON array.");return q.split(",")});break;case "object":T.argParser(q=>{let xe;try{xe=JSON.parse(q);}catch{throw new Ue("The JSON is malformed.")}if(typeof xe!="object"||xe===null)throw new Ue("The value must be a JSON object.")});break}A[T.attributeName()]=y,w.addOption(T);}return e}function Dd(o){let e=["use","help use"];for(let t of e){let n=t.split(" ").length;if(o.length>n&&o.slice(0,n).join(" ")===t&&(o[n]??"")!=="")return o[n]}return null}(async function o(e=process.argv,t=true){let n=rl({interactive:true}).parse(e),r=n.opts(),i=Wa.fromDefaults({program:c=>o(n.args.slice(0,2).concat(c)),quiet:r.quiet,debug:r.debug,interactive:r.interaction?void 0:false,apiKey:r.apiKey,skipPrompts:r.skipPrompts===true,templateRegistryUrl:r.registry===void 0?void 0:new URL(r.registry)}),a=Dd(n.args),s=a!==null?await i.getTemplateOptions(a).catch(()=>null):void 0,p=rl({cli:i,interactive:r.interaction,template:s});t&&await i.welcome({}),await p.parseAsync(e);})();
1833
+ ${t}`,e.help)}break;case e instanceof it: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}`}};function Mc(o){let e=new ls().name("croct").description("Manage your Croct projects").enablePositionalOptions().option("--cwd <path>","The working directory.",y=>{try{return realpathSync(y)}catch{throw new Fe("The path does not exist.")}}).addOption(new oe("--api-key <key>","The API key to use for authentication.").env("CROCT_API_KEY").argParser(y=>{try{return ApiKey.parse(y)}catch{throw new Fe("The API key is malformed.")}})).option("--registry <url>","The template registry.",y=>{if(!URL.canParse(y))throw new Fe("Malformed URL.");return y}).option("--no-interaction","Disable interaction mode.").addOption(new oe("-s, --skip-prompts","Skip prompts with default options.").default(false)).addOption(new oe("-q, --quiet","Disable output messages.").default(false).implies({interaction:false})).option("--debug","Enable debug mode.").version("0.0.1","-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 y=>{await o.cli?.open({url:y});});let t=e.command("login").description("Authenticate your user."),n=new oe("-u, --username <username>","The email."),r=new oe("-p, --password <password>","The password.");t.command("credentials",{isDefault:true}).description("Authenticate using credentials.").addOption(o.interactive?n:n.makeOptionMandatory()).addOption(o.interactive?r:r.makeOptionMandatory()).action(async y=>{await o.cli?.login({method:"credentials",username:y.username,password:y.password});}),e.command("logout").description("Logout the current user.").action(async()=>{await o.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 y=>{await o.cli?.admin({page:y!==void 0?y.join(" "):o.interactive?void 0:"/"});});let i=new oe("--wor <workspace-slug>","The workspace slug."),a=new oe("--org <organization-slug>","The organization slug."),s=new oe("--dev-app <application-slug>","The development application slug."),p=new oe("--prod-app <application-slug>","The production application slug.");e.command("init").description("Configure the project.").option("-o, --override","Override any existing configuration.").addOption(new oe("-n, --new <resource>","The resources to create.").choices(["organization","org","workspace","wor","application","app"])).addOption(new oe("-s, --sdk <platform>","The SDK to use.").choices(["javascript","react","next"])).addOption(o.interactive?a:a.makeOptionMandatory()).addOption(o.interactive?i:i.makeOptionMandatory()).addOption(o.interactive?s:s.makeOptionMandatory()).addOption(p).action(async y=>{await o.cli?.init({override:y.override,new:(()=>{switch(y.new){case "organization":case "org":return "organization";case "workspace":case "wor":return "workspace";case "application":case "app":return "application";default:return}})(),sdk:y.sdk,organization:y.org,workspace:y.wor,devApplication:y.devApp,prodApplication:y.prodApp});}),e.command("install").description("Install content and types.").action(async()=>{await o.cli?.install({});}),e.command("update").description("Update content and types.").action(async()=>{await o.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 y=>{await o.cli?.upgrade({slots:y.slots??(y.components!==void 0?[]:void 0),components:y.components??(y.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(o.interactive?"[slots...]":"<slots...>").option("-e, --example","Generate an implementation example.").action(async(y,M)=>{await o.cli?.addSlot({slots:y,example:M.example});}),c.command("component").description("Add a component to your project.").argument(o.interactive?"[components...]":"<components...>").action(async y=>{await o.cli?.addComponent({components:y});});let l=e.command("remove").description("Remove a resource from your project.");l.command("slot").description("Remove a slot from your project.").argument(o.interactive?"[slots...]":"<slots...>").action(async y=>{await o.cli?.removeSlot({slots:y});}),l.command("component").description("Remove a component from your project.").argument(o.interactive?"[components...]":"<components...>").action(async y=>{await o.cli?.removeComponent({components:y});});let m=e.command("create").description("Create a resource in your project.");m.command("template").description("Create a template from your project.").addArgument(new us("<path>","The path to the file.").argOptional()).option("-e, --empty","Create an empty template.").action(async(y,M)=>{await o.cli?.createTemplate({file:y,empty:M.empty});});let f=new oe("--permissions <permissions...>","The permissions of the API key.").argParser(y=>y.split(",").map(M=>{try{return Ae.fromValue(M)}catch{throw new Fe(`Unknown permission "${M}".`)}})),b=new oe("--env <environment>","The environment of the API key.").choices(["prod","dev"]).argParser(y=>y==="prod"?"PRODUCTION":"DEVELOPMENT");m.command("api-key").description("Create an API key.").option("--name <name>","The name of the API key.").addOption(o.interactive?f:f.makeOptionMandatory()).addOption(o.interactive?b:b.makeOptionMandatory()).option("-c, --copy","Copy the API key to the clipboard.").action(async y=>{await o.cli?.createApiKey({name:y.name,permissions:y.permissions,environment:y.env,copy:y.copy});});let A={},w=e.command("use").description("Use a template.").argument("template","The path to the template.").passThroughOptions(o.cli===void 0).allowUnknownOption(o.cli===void 0||o.template===null).action(async(y,M)=>{await o.cli?.useTemplate({template:y,options:Object.fromEntries(Object.entries(M).map(([j,T])=>[A[j],T]))});});for(let[y,M]of Object.entries(o.template??{})){let j=`--${y}${M.type!=="boolean"?" <value>":""}`,T=new oe(j,M.description).makeOptionMandatory(M.required===true);switch(M.type){case "string":M.options!==void 0&&M.options.length>0&&T.choices(M.options);break;case "number":T.argParser(q=>{let Se=Number.parseFloat(q);if(Number.isNaN(Se))throw new Fe("The value must be a number.");return Se});break;case "array":T.argParser(q=>{let Se;try{Se=JSON.parse(q);}catch{}if(Se===void 0||!Array.isArray(Se))throw new Fe("The value must be a JSON array.");return q.split(",")});break;case "object":T.argParser(q=>{let Se;try{Se=JSON.parse(q);}catch{throw new Fe("The JSON is malformed.")}if(typeof Se!="object"||Se===null)throw new Fe("The value must be a JSON object.")});break}A[T.attributeName()]=y,w.addOption(T);}return e}function pd(o){let e=["use","help use"];for(let t of e){let n=t.split(" ").length;if(o.length>n&&o.slice(0,n).join(" ")===t&&(o[n]??"")!=="")return o[n]}return null}(async function o(e=process.argv,t=true){let n=Mc({interactive:true}).parse(e),r=n.opts(),i=Sa.fromDefaults({program:c=>o(n.args.slice(0,2).concat(c)),quiet:r.quiet,debug:r.debug,interactive:r.interaction?void 0:false,apiKey:r.apiKey,skipPrompts:r.skipPrompts===true,templateRegistryUrl:r.registry===void 0?void 0:new URL(r.registry)}),a=pd(n.args),s=a!==null?await i.getTemplateOptions(a).catch(()=>null):void 0,p=Mc({cli:i,interactive:r.interaction,template:s});t&&await i.welcome({}),await p.parseAsync(e);})();