@tailorkit/cli 0.1.0-beta.11 → 0.1.0-beta.12

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/dist/index.js +1 -1
  2. package/package.json +4 -4
package/dist/index.js CHANGED
@@ -248,4 +248,4 @@ export interface CardProps {
248
248
  export const Card = createRemoteComponent<CardProps, true>("Card", {
249
249
  children: true,
250
250
  });
251
- `,ma=new fe({strictVariables:!0}),ha=(e,t)=>ma.parseAndRender(e,t),ga=e=>h(e,{recursive:!0}).then(()=>{}),_a=async(e,t,n)=>{if(!n&&ce(e))throw Error(`${e} already exists. Use --force to overwrite it.`);await re(e,t,`utf-8`)},va=async e=>{let{targetDirectory:t,force:n,formatting:r,hostUrl:i,linting:a,packageName:o,packageVersions:s,useWorkspaceDependencies:c}=e,l=c?`workspace:*`:s.tailorkit,u=[],d=[];a&&(u.push(`pnpm run lint`),d.push(`pnpm run lint:fix`)),r&&(u.push(`pnpm run format`),d.push(`pnpm run format:fix`));let f={checkScript:u.join(` && `),fixScript:d.join(` && `),formatting:r,hostUrl:i,linting:a,oxfmtVersion:s.oxfmt,oxlintVersion:s.oxlint,packageName:o,preactVersion:s.preact,tailorkitVersion:l,typescriptVersion:s.typescript};await ga(_.join(t,`src`,`views`));let p=[{template:aa,dest:`package.json`},{template:oa,dest:`tsconfig.json`},{template:sa,dest:`tailorkit.config.ts`},{template:ca,dest:`.gitignore`},{template:la,dest:`oxlint.config.ts`,condition:a},{template:ua,dest:`oxfmt.config.ts`,condition:r},{template:da,dest:_.join(`src`,`client.ts`)},{template:fa,dest:_.join(`src`,`views`,`default.tsx`)},{template:pa,dest:_.join(`src`,`tailorkit.gen.ts`)}];await Promise.all(p.filter(e=>e.condition!==!1).map(async({template:e,dest:r})=>{let i=await ha(e,f);await _a(_.join(t,r),i,n)}))},ya=`https://registry.npmjs.org`,ba=5e3,xa={oxfmt:{fallback:`^0.46.0`,matcher:`^0`,packageName:`oxfmt`},oxlint:{fallback:`^1.61.0`,matcher:`^1`,packageName:`oxlint`},preact:{fallback:`^10.29.1`,matcher:`^10`,packageName:`preact`},tailorkit:{fallback:`latest`,matcher:`^0`,packageName:`tailorkit`},typescript:{fallback:`^6.0.3`,matcher:`^6`,packageName:`typescript`}},Sa=e=>{let t=/^(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)$/u.exec(e);if(!t?.groups)return;let{major:n,minor:r,patch:i}=t.groups;if(n&&r&&i)return{major:Number.parseInt(n,10),minor:Number.parseInt(r,10),patch:Number.parseInt(i,10),raw:e}},Ca=(e,t)=>e.major===t.major?e.minor===t.minor?e.patch-t.patch:e.minor-t.minor:e.major-t.major,wa=(e,t)=>{let n=/^\^(?<major>\d+)(?:\.(?<minor>\d+))?/u.exec(t);if(!n?.groups?.major)return!1;let r=Number.parseInt(n.groups.major,10),i=Number.parseInt(n.groups.minor??`0`,10);return e.major===r&&e.minor>=i},Ta=async({fallback:e,matcher:t,packageName:n})=>{try{let r=await fetch(`${ya}/${encodeURIComponent(n)}`,{signal:AbortSignal.timeout(ba)});if(!r.ok)return e;let i=await r.json(),a=Object.keys(i.versions??{}).map(Sa).filter(e=>e!==void 0).filter(e=>wa(e,t)).toSorted(Ca).at(-1);return a?`^${a.raw}`:e}catch{return e}},Ea=async()=>{let[e,t,n,r,i]=await Promise.all([Ta(xa.oxfmt),Ta(xa.oxlint),Ta(xa.preact),Ta(xa.tailorkit),Ta(xa.typescript)]);return{oxfmt:e,oxlint:t,preact:n,tailorkit:r,typescript:i}},Da=[`pnpm`,`yarn`,`npm`,`bun`],Oa=e=>Da.includes(e),ka=e=>e.trim().toLowerCase().replaceAll(/[^a-z0-9._/-]+/gu,`-`).replaceAll(/^-+|-+$/gu,``),Aa=e=>(s(e)&&(i(`Init cancelled.`),process.exit(0)),e),ja=(e,t)=>_.resolve(t,e??`.`),Ma=async(e,t)=>{let n=ka(_.basename(t))||`tailorkit-app`;return ka(e===void 0?Aa(await f({defaultValue:n,message:`Package name`,placeholder:n,validate:e=>ka(e??``).length===0?`Enter a package name.`:void 0})):e)},Na=async e=>{if(e!==void 0){if(Oa(e))return e;throw Error(`--package-manager must be one of: ${Da.join(`, `)}.`)}return Aa(await u({initialValue:`pnpm`,message:`Package manager`,options:Da.map(e=>({label:e,value:e}))}))},Pa=async e=>e===void 0?Aa(await a({initialValue:!0,message:`Add linting with oxlint?`})):e,Fa=async e=>e===void 0?Aa(await a({initialValue:!0,message:`Add formatting with oxfmt?`})):e,Ia=e=>{try{Hr(e??``);return}catch{return`Enter a valid host URL.`}},La=async e=>{if(e!==void 0){let t=Ia(e);if(t!==void 0)throw Error(t);return Hr(e)}let t=`https://example.com/api/tailorkit`;return Hr(Aa(await f({defaultValue:t,message:`Host URL`,placeholder:t,validate:Ia})))},Ra=async e=>e===void 0?Aa(await a({initialValue:!0,message:`Install dependencies?`})):e,za=async(e,t)=>t||!ce(e)?t:Aa(await a({initialValue:!1,message:`${m.cyan(e)} already exists. Overwrite matching files?`})),Ba=(e,t,n)=>new Promise((r,i)=>{let a=de(e,t,{cwd:n,stdio:`inherit`});a.on(`close`,r),a.on(`error`,i)}),Va=async(e,t)=>{let n=d();n.start(`Installing dependencies with ${t}`);let r=await Ba(t,[`install`],e);if(r!==0)throw n.stop(`Install failed.`),Error(`${t} install exited with code ${r}.`);n.stop(`Installed dependencies.`)},Ha=async(e,t)=>{let n=d();n.start(`Formatting project`);let r=await Ba(t,[`run`,`format:fix`],e);if(r!==0)throw n.stop(`Formatting failed.`),Error(`${t} run format:fix exited with code ${r}.`);n.stop(`Formatted project.`)},Ua=async e=>{let t=ja(e.directory,e.cwd),n=await Ma(e.name,t),r=_.join(t,n),i=await za(r,e.force??!1),a=await Na(e.packageManager),o=await La(e.host),s=await Pa(e.linting),c=await Fa(e.formatting),l=await Ra(e.install),u=d();u.start(`Resolving package versions`);let f=await Ea();return u.stop(`Resolved package versions.`),await h(r,{recursive:!0}),await va({force:i,formatting:c,hostUrl:o,linting:s,packageName:n,packageVersions:f,targetDirectory:r}),l&&(await Va(r,a),c&&await Ha(r,a)),r},Wa=/^http:\/\/orpc\//,Ga=(e=>(e[e.REQUEST=1]=`REQUEST`,e[e.RESPONSE=2]=`RESPONSE`,e[e.EVENT_ITERATOR=3]=`EVENT_ITERATOR`,e[e.ABORT_SIGNAL=4]=`ABORT_SIGNAL`,e))(Ga||{});function Ka(e,t,n){if(t===3){let r=n;return{i:e,t,p:{e:r.event,d:r.data,m:r.meta}}}if(t===4)return{i:e,t,p:n};let r=n;return{i:e,p:{u:r.url.toString().replace(Wa,`/`),b:r.body,h:Object.keys(r.headers).length>0?r.headers:void 0,m:r.method===`POST`?void 0:r.method}}}function qa(e){let t=e.i,n=e.t;if(n===3){let r=e.p;return[t,n,{event:r.e,data:r.d,meta:r.m}]}if(n===4)return[t,n,e.p];let r=e.p;return[t,2,{status:r.s??200,headers:r.h??{},body:r.b}]}async function Ja(e,t,n){if(t===3||t===4)return $a(Ka(e,t,n));let r=n,{body:i,headers:a}=await Xa(r.body,r.headers),o=Ka(e,1,{...r,body:i instanceof Blob?void 0:i,headers:a});return i instanceof Blob?$a(o,i):$a(o)}async function Ya(e){let{json:t,buffer:n}=await eo(e),[r,i,a]=qa(t);if(i===3||i===4)return[r,i,a];let o=a,s=await Za(o.headers,o.body,n);return[r,i,{...o,body:s}]}async function Xa(e,t){let n={...t},r=n[`content-disposition`];if(delete n[`content-type`],delete n[`content-disposition`],e instanceof Blob)return n[`content-type`]=e.type,n[`content-disposition`]=r??Nt(e instanceof File?e.name:`blob`),{body:e,headers:n};if(e instanceof FormData){let t=new Response(e);return n[`content-type`]=t.headers.get(`content-type`),{body:await t.blob(),headers:n}}return e instanceof URLSearchParams?(n[`content-type`]=`application/x-www-form-urlencoded`,{body:e.toString(),headers:n}):w(e)?(n[`content-type`]=`text/event-stream`,{body:void 0,headers:n}):{body:e,headers:n}}async function Za(e,t,n){let r=It(e[`content-type`]),i=It(e[`content-disposition`]);if(typeof i==`string`){let e=Pt(i)??`blob`;return new File(n===void 0?[]:[n],e,{type:r})}return r?.startsWith(`multipart/form-data`)?new Response(n,{headers:{"content-type":r}}).formData():r?.startsWith(`application/x-www-form-urlencoded`)&&typeof t==`string`?new URLSearchParams(t):t}var Qa=255;async function $a(e,t){let n=D(e);return t===void 0||t.size===0?n:je(new Blob([new TextEncoder().encode(n),new Uint8Array([Qa]),t]))}async function eo(e){if(typeof e==`string`)return{json:JSON.parse(e)};let t=e instanceof Uint8Array?e:new Uint8Array(e),n=t.indexOf(Qa);if(n===-1){let e=new TextDecoder().decode(t);return{json:JSON.parse(e)}}let r=new TextDecoder().decode(t.subarray(0,n)),i=t.subarray(n+1);return{json:JSON.parse(r),buffer:i}}function to(e,t,n,r={}){let i;return new We(async()=>{i??=Ve(`consume_event_iterator_stream`);try{let n=await C(i,()=>e.pull(t));switch(n.event){case`message`:{let e=n.data;return n.meta&&O(e)&&(e=I(e,n.meta)),i?.addEvent(`message`),{value:e,done:!1}}case`error`:{let e=new P({data:n.data});throw n.meta&&(e=I(e,n.meta)),i?.addEvent(`error`),e}case`done`:{let e=n.data;return n.meta&&O(e)&&(e=I(e,n.meta)),i?.addEvent(`done`),{value:e,done:!0}}}}catch(e){throw e instanceof P||x(i,e,r),e}},async e=>{try{e!==`next`&&i?.addEvent(`cancelled`),await C(i,()=>n(e))}catch(e){throw x(i,e,r),e}finally{i?.end()}})}function no(e,t){return S({name:`stream_event_iterator`},async n=>{for(;;){let r=await(async()=>{try{let{value:t,done:r}=await e.next();return r?(n?.addEvent(`done`),{event:`done`,data:t,meta:jt(t)}):(n?.addEvent(`message`),{event:`message`,data:t,meta:jt(t)})}catch(e){if(e instanceof P)return n?.addEvent(`error`),{event:`error`,data:e.data,meta:jt(e)};try{await t({event:`error`,data:void 0})}catch(t){throw x(n,e),t}throw e}})(),i=!1;try{let n=await t(r);if(r.event===`done`||r.event===`error`)return;if(n===`abort`){i=!0,await e.return?.();return}}catch(t){if(!i)try{await e.return?.()}catch(e){throw x(n,t),e}throw t}}})}var ro=class{peer;constructor(e){this.peer=new io(async([t,n,r])=>{await e(await Ja(t,n,r))})}get length(){return this.peer.length}open(e){return this.peer.open(e)}async request(e){return this.peer.request(e)}async message(e){return this.peer.message(await Ya(e))}close(e={}){return this.peer.close(e)}},io=class{idGenerator=new Ge;responseQueue=new Ue;serverEventIteratorQueue=new Ue;serverControllers=new Map;cleanupFns=new Map;send;constructor(e){this.send=async t=>{let n=t[0];this.serverControllers.has(n)&&await e(t)}}get length(){return(+this.responseQueue.length+this.serverEventIteratorQueue.length+this.serverControllers.size+this.cleanupFns.size)/4}open(e){this.serverEventIteratorQueue.open(e),this.responseQueue.open(e);let t=new AbortController;return this.serverControllers.set(e,t),this.cleanupFns.set(e,[]),t}async request(e){let t=e.signal;return S({name:`send_peer_request`,signal:t},async()=>{if(t?.aborted)throw t.reason;let n=this.idGenerator.generate(),r=this.open(n);try{let i=Be();if(i){let t=Xe(e.headers);i.propagation.inject(i.context.active(),t),e={...e,headers:t}}if(await this.send([n,Ga.REQUEST,e]),t?.aborted)throw await this.send([n,Ga.ABORT_SIGNAL,void 0]),t.reason;let a;if(t?.addEventListener(`abort`,a=async()=>{await this.send([n,Ga.ABORT_SIGNAL,void 0]),this.close({id:n,reason:t.reason})},{once:!0}),this.cleanupFns.get(n)?.push(()=>{t?.removeEventListener(`abort`,a)}),w(e.body)){let t=e.body;no(t,async e=>r.signal.aborted?`abort`:(await this.send([n,Ga.EVENT_ITERATOR,e]),`next`))}let o=await this.responseQueue.pull(n);if(L(o.headers)){let e=to(this.serverEventIteratorQueue,n,async e=>{try{e!==`next`&&await this.send([n,Ga.ABORT_SIGNAL,void 0])}finally{this.close({id:n})}},{signal:t});return{...o,body:e}}return this.close({id:n}),o}catch(e){throw this.close({id:n,reason:e}),e}})}async message([e,t,n]){if(t===Ga.ABORT_SIGNAL){this.serverControllers.get(e)?.abort();return}if(t===Ga.EVENT_ITERATOR){this.serverEventIteratorQueue.isOpen(e)&&this.serverEventIteratorQueue.push(e,n);return}this.responseQueue.isOpen(e)&&this.responseQueue.push(e,n)}close(e={}){e.id===void 0?(this.serverControllers.forEach(t=>t.abort(e.reason)),this.serverControllers.clear(),this.cleanupFns.forEach(e=>e.forEach(e=>e())),this.cleanupFns.clear()):(this.serverControllers.get(e.id)?.abort(e.reason),this.serverControllers.delete(e.id),this.cleanupFns.get(e.id)?.forEach(e=>e()),this.cleanupFns.delete(e.id)),this.responseQueue.close(e),this.serverEventIteratorQueue.close(e)}},ao=0,oo=1,so=class{peer;constructor(e){this.peer=new ro(async t=>{if(e.websocket.readyState===ao&&await new Promise(t=>{let n=()=>{e.websocket.removeEventListener(`open`,n),e.websocket.removeEventListener(`close`,n),t()};e.websocket.addEventListener(`open`,n,{once:!0}),e.websocket.addEventListener(`close`,n,{once:!0})}),e.websocket.readyState!==oo)throw Error(`Cannot send message, WebSocket is not open.`);return e.websocket.send(t)}),e.websocket.addEventListener(`message`,async e=>{let t=e.data instanceof Blob?await je(e.data):e.data;this.peer.message(t)}),e.websocket.addEventListener(`close`,()=>{this.peer.close()})}async call(e,t,n,r){let i=await this.peer.request(e);return{...i,body:()=>Promise.resolve(i.body)}}},co=class extends nn{constructor(e){let t=new so(e);super(t,{...e,url:`http://orpc`})}};function lo(e){return zt(new co({websocket:e}))}var uo=1048576;async function fo(e,t,n){try{let r=await fetch(new URL(t.path,n),{method:t.method}),i=Number(r.headers.get(`content-length`));if(Number.isFinite(i)&&i>uo)throw Error(`Preview asset exceeds the maximum supported size.`);let a=Buffer.from(await r.arrayBuffer());if(a.byteLength>uo)throw Error(`Preview asset exceeds the maximum supported size.`);await e.respond({type:`response`,id:t.id,status:r.status,body:a.toString(`base64`),contentType:r.headers.get(`content-type`)??`application/octet-stream`})}catch{await e.respond({type:`response`,id:t.id,status:502,contentType:`text/plain`,body:``})}}function po(e,t,n){let r=1e3,i=()=>{let a=new WebSocket(e,t),o=lo(a);a.addEventListener(`open`,()=>{r=1e3,(async()=>{try{let e=await o.connect();for await(let t of e)fo(o,t,n)}catch{a.close()}})()}),a.addEventListener(`close`,()=>{setTimeout(i,r),r=Math.min(r*2,3e4)})};i()}async function mo(e){let t=await Oe(e.configPath,e.cwd);if(!t.config.appId)throw Error(`Missing appId. Deploy once before starting a remote preview.`);let n=await ai(e),r=await ri(n.hostUrl);if(!r?.deployToken)throw Error(`Not logged in. Run tailorkit login first.`);let i=await Er({headers:{authorization:`Bearer ${r.deployToken}`},url:n.hostUrl}).preview.start({appId:t.config.appId});if(!(`data`in i)||!i.data)throw Error(`Unable to start preview session.`);let a=i.data;po(a.tunnelUrl,a.tunnelToken,`http://${e.host??`127.0.0.1`}:${e.port??4175}`),await xo(e),c.info(m.green(`Host preview session: ${a.sessionId}`))}var ho={".css":`text/css; charset=utf-8`,".html":`text/html; charset=utf-8`,".js":`text/javascript; charset=utf-8`,".json":`application/json; charset=utf-8`,".map":`application/json; charset=utf-8`},go=e=>ho[_.extname(e)]??`application/octet-stream`,_o=e=>{if(e===void 0)return;let t=Number.parseInt(String(e),10);if(!Number.isInteger(t)||t<=0)throw Error(`--port must be a positive integer.`);return t},vo=e=>({configPath:e.config,cwd:String(e.cwd??`.`),entry:e.entry,host:e.host,mode:e.mode,outDir:e.outDir,port:_o(e.port)}),yo=(e,t)=>pe(async(n,r)=>{try{let i=new URL(n.url??`/`,`http://localhost`);if(i.pathname===`/apps`){r.writeHead(200,{"access-control-allow-origin":`*`,"content-type":`application/json; charset=utf-8`}),r.end(JSON.stringify(t));return}let a=decodeURIComponent(i.pathname),o=a===`/`?`client.js`:a.slice(1),s=_.resolve(e,o),c=_.relative(e,s);if(c.startsWith(`..`)||_.isAbsolute(c)){r.writeHead(403),r.end(`Forbidden`);return}if(!(await ne(s).catch(()=>null))?.isFile()){r.writeHead(404),r.end(`Not found`);return}r.writeHead(200,{"access-control-allow-origin":`*`,"content-type":go(s)}),r.end(await g(s))}catch(e){r.writeHead(500),r.end(e instanceof Error?e.message:String(e))}}),bo=async e=>{let t=_.join(e,`package.json`),n=JSON.parse(await g(t,`utf-8`)),r=typeof n.name==`string`?n.name:_.basename(e);return[{clientPath:`/client.js`,description:typeof n.description==`string`?n.description:void 0,id:r,name:typeof n.name==`string`?n.name:void 0}]},xo=async e=>{let t=await Oe(e.configPath,e.cwd),n=_.resolve(t.root,e.outDir??t.config.build?.outDir??`.tailorkit`),r=e.host??`127.0.0.1`,i=e.port??4175,{buildApp:a}=await import(`./assets/builder-D5o0m6gu.js`),o=await a({configPath:e.configPath,cwd:e.cwd,entry:e.entry,mode:e.mode,outDir:e.outDir,watch:!0}),s=()=>{o&&typeof o==`object`&&`close`in o&&o.close()},l=yo(n,await bo(t.root));await new Promise((e,t)=>{l.once(`error`,t),l.listen(i,r,e)}),l.removeAllListeners(`error`),process.once(`SIGINT`,()=>{s(),l.close(),process.exit(0)}),process.once(`SIGTERM`,()=>{s(),l.close(),process.exit(0)}),c.info(m.green(`Experimental preview running at http://${r}:${i}`)),c.info(m.dim(`Serving built app client from ${n}`))},So=e=>{let t=ae();return t===`darwin`?{args:[e],command:`open`}:t===`win32`?{args:[`/c`,`start`,``,e],command:`cmd`}:{args:[e],command:`xdg-open`}},Co=e=>new Promise(t=>{let{args:n,command:r}=So(e),i=de(r,n,{detached:!0,stdio:`ignore`,windowsHide:!0});i.once(`error`,()=>{t(!1)}),i.once(`spawn`,()=>{i.unref(),t(!0)})}),$=p(`tailorkit`),wo=e=>{if(e<1024)return`${e} B`;let t=[`KB`,`MB`,`GB`],n=e/1024,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;return`${n.toFixed(n>=10?1:2)} ${t[r]}`};$.option(`--cwd <path>`,`Working directory`,{default:`.`}),$.command(`preview`,`Preview the app inside a host app`).option(`--config <path>`,`Path to tailorkit config`).option(`--host <host>`,`Local preview host`).option(`--port <port>`,`Local preview port`).action(async e=>{o(m.bold(`TailorKit`));try{await mo(vo(e))}catch(e){c.error(e instanceof Error?e.message:String(e)),process.exit(1)}}),$.command(`login`,`Authenticate the TailorKit CLI with a host app`).option(`--config <path>`,`Path to tailorkit config`).option(`--open`,`Open the approval URL in the default browser`,{default:!0}).option(`--timeout <seconds>`,`Seconds to wait for approval`,{default:1800}).action(async e=>{o(m.bold(`TailorKit`));let t=d(),n=!1;try{let r=Number.parseInt(String(e.timeout??`1800`),10);if(!Number.isInteger(r)||r<=0)throw Error(`--timeout must be a positive integer.`);await ii({configPath:e.config,cwd:String(e.cwd??`.`),timeout:r*1e3},({expiresAt:r,hostUrl:i,userCode:a})=>{let o=$r(i,a);e.open!==!1&&Co(o),c.info(`Enter this code in the host app: ${m.bold(a)}`),c.info(`Approval URL: ${m.cyan(o)}`),c.info(`Code expires at ${r.toLocaleString()}.`),c.info(`Waiting for approval...`),t.start(`Checking approval status`),n=!0}),n&&t.stop(`Approved.`),l(`Authenticated successfully.`)}catch(e){n&&t.stop(`Approval failed.`),c.error(e instanceof Error?e.message:String(e)),process.exit(1)}}),$.command(`logout`,`Remove stored TailorKit CLI credentials for a host app`).option(`--config <path>`,`Path to tailorkit config`).action(async e=>{o(m.bold(`TailorKit`));try{let t=await oi({configPath:e.config,cwd:String(e.cwd??`.`)});l(t.removed?`Logged out of ${m.cyan(t.hostUrl)}.`:`No stored credentials found for ${m.cyan(t.hostUrl)}.`)}catch(e){c.error(e instanceof Error?e.message:String(e)),process.exit(1)}}),$.command(`whoami`,`Show the current TailorKit CLI authentication scope`).option(`--config <path>`,`Path to tailorkit config`).action(async e=>{o(m.bold(`TailorKit`));try{let t=await ai({configPath:e.config,cwd:String(e.cwd??`.`)});c.info(`Host: ${m.cyan(t.hostUrl)}`),c.info(`Scope: ${m.cyan(t.scopeId)}`),l(`Authenticated.`)}catch(e){c.error(e instanceof Error?e.message:String(e)),process.exit(1)}}),$.command(`deploy`,`Build and deploy the TailorKit app`).option(`--config <path>`,`Path to tailorkit config`).option(`--entry <path>`,`Client entry file`).option(`--out-dir <path>`,`Build output directory`).option(`--mode <mode>`,`Vite mode`).action(async e=>{o(m.bold(`TailorKit`));let t=d();try{t.start(`Building and deploying app`);let n=await Si({configPath:e.config,cwd:String(e.cwd??`.`),entry:e.entry,mode:e.mode,onMissingAppId:async({appName:e,configPath:n,hostUrl:r,reason:i})=>{t.stop(`App not linked.`),c.info(i===`missing`?`No appId found in ${m.cyan(n)}.`:`The appId in ${m.cyan(n)} does not exist.`),c.info(`Host: ${m.cyan(r)}`);let o=await a({initialValue:!0,message:i===`missing`?`Create a TailorKit app named ${e}?`:`Create a new TailorKit app named ${e} and update the config?`});return!s(o)&&(o&&t.start(`Creating app and deploying`),o===!0)},onTypecheckFailed:async({command:e,output:n})=>{t.stop(`Type check failed.`),c.error(`Type check failed while running ${m.cyan(e)}.`),n&&c.error(n);let r=await a({initialValue:!1,message:`Type check failed, but the app built successfully. Upload anyway?`});return!s(r)&&(r&&t.start(`Uploading app`),r===!0)},outDir:e.outDir});t.stop(`Deployed app.`),n.createdApp&&c.info(`Created app and updated tailorkit.config.ts with ${m.cyan(n.appId)}.`),c.info(`Host: ${m.cyan(n.hostUrl)}`),c.info(`App: ${m.cyan(n.appId)}`),c.info(`Deployment: ${m.cyan(n.deploymentId)}`),c.info(`Uploaded files:`);for(let e of n.uploadedFiles)c.info(` ${m.cyan(e.path)} ${m.dim(`${wo(e.size)} raw, ${wo(e.gzipSize)} gzip`)}`);n.status&&c.info(`Status: ${m.cyan(n.status)}`),l(`Deployment published.`)}catch(e){t.stop(`Deployment failed.`),c.error(e instanceof Error?e.message:String(e)),process.exit(1)}}),$.command(`build`,`Build the TailorKit app`).option(`--config <path>`,`Path to tailorkit config`).option(`--entry <path>`,`Client entry file`).option(`--out-dir <path>`,`Build output directory`).option(`--mode <mode>`,`Vite mode`).action(async e=>{o(m.bold(`TailorKit`));try{let{buildApp:t}=await import(`./assets/builder-D5o0m6gu.js`);await t({configPath:e.config,cwd:String(e.cwd??`.`),entry:e.entry,mode:e.mode,outDir:e.outDir}),l(`Built app.`)}catch(e){c.error(e instanceof Error?e.message:String(e)),process.exit(1)}}),$.command(`experimental-preview`,`Build and preview the TailorKit app`).option(`--config <path>`,`Path to tailorkit config`).option(`--entry <path>`,`Client entry file`).option(`--out-dir <path>`,`Build output directory`).option(`--host <host>`,`Preview host`).option(`--port <port>`,`Preview port`).option(`--mode <mode>`,`Vite mode`).action(async e=>{o(m.bold(`TailorKit`));try{await xo(vo(e))}catch(e){c.error(e instanceof Error?e.message:String(e)),process.exit(1)}}),$.command(`generate`,`Generate TailorKit app bindings`).option(`--config <path>`,`Path to tailorkit config`).option(`--out <path>`,`Generated TypeScript output file`).action(async e=>{o(m.bold(`TailorKit`));try{let t=await ia({configPath:e.config,cwd:String(e.cwd??`.`),outFile:e.out});l(`Generated ${m.cyan(t)}.`)}catch(e){c.error(e instanceof Error?e.message:String(e)),process.exit(1)}}),$.command(`init [directory]`,`Create a new TailorKit app`).option(`--name <name>`,`Package name`).option(`--host <url>`,`TailorKit host URL`).option(`--package-manager <pm>`,`Package manager: bun, yarn, pnpm, or npm`).option(`--lint`,`Add oxlint (use --no-lint to skip)`).option(`--format`,`Add oxfmt (use --no-format to skip)`).option(`--install`,`Install dependencies after scaffolding (use --no-install to skip)`).option(`--force`,`Overwrite existing files`).action(async(e,t)=>{o(m.bold(`TailorKit`));try{let n=await Ua({cwd:String(t.cwd??`.`),directory:e,force:t.force,formatting:t.format,host:t.host,install:t.install,linting:t.lint,name:t.name,packageManager:t.packageManager});l(`Created app at ${m.cyan(n)}.`)}catch(e){c.error(e instanceof Error?e.message:String(e)),process.exit(1)}}),$.help(),$.version(`0.1.0-beta.11`),$.parse();export{Oe as t};
251
+ `,ma=new fe({strictVariables:!0}),ha=(e,t)=>ma.parseAndRender(e,t),ga=e=>h(e,{recursive:!0}).then(()=>{}),_a=async(e,t,n)=>{if(!n&&ce(e))throw Error(`${e} already exists. Use --force to overwrite it.`);await re(e,t,`utf-8`)},va=async e=>{let{targetDirectory:t,force:n,formatting:r,hostUrl:i,linting:a,packageName:o,packageVersions:s,useWorkspaceDependencies:c}=e,l=c?`workspace:*`:s.tailorkit,u=[],d=[];a&&(u.push(`pnpm run lint`),d.push(`pnpm run lint:fix`)),r&&(u.push(`pnpm run format`),d.push(`pnpm run format:fix`));let f={checkScript:u.join(` && `),fixScript:d.join(` && `),formatting:r,hostUrl:i,linting:a,oxfmtVersion:s.oxfmt,oxlintVersion:s.oxlint,packageName:o,preactVersion:s.preact,tailorkitVersion:l,typescriptVersion:s.typescript};await ga(_.join(t,`src`,`views`));let p=[{template:aa,dest:`package.json`},{template:oa,dest:`tsconfig.json`},{template:sa,dest:`tailorkit.config.ts`},{template:ca,dest:`.gitignore`},{template:la,dest:`oxlint.config.ts`,condition:a},{template:ua,dest:`oxfmt.config.ts`,condition:r},{template:da,dest:_.join(`src`,`client.ts`)},{template:fa,dest:_.join(`src`,`views`,`default.tsx`)},{template:pa,dest:_.join(`src`,`tailorkit.gen.ts`)}];await Promise.all(p.filter(e=>e.condition!==!1).map(async({template:e,dest:r})=>{let i=await ha(e,f);await _a(_.join(t,r),i,n)}))},ya=`https://registry.npmjs.org`,ba=5e3,xa={oxfmt:{fallback:`^0.46.0`,matcher:`^0`,packageName:`oxfmt`},oxlint:{fallback:`^1.61.0`,matcher:`^1`,packageName:`oxlint`},preact:{fallback:`^10.29.1`,matcher:`^10`,packageName:`preact`},tailorkit:{fallback:`latest`,matcher:`^0`,packageName:`tailorkit`},typescript:{fallback:`^6.0.3`,matcher:`^6`,packageName:`typescript`}},Sa=e=>{let t=/^(?<major>\d+)\.(?<minor>\d+)\.(?<patch>\d+)$/u.exec(e);if(!t?.groups)return;let{major:n,minor:r,patch:i}=t.groups;if(n&&r&&i)return{major:Number.parseInt(n,10),minor:Number.parseInt(r,10),patch:Number.parseInt(i,10),raw:e}},Ca=(e,t)=>e.major===t.major?e.minor===t.minor?e.patch-t.patch:e.minor-t.minor:e.major-t.major,wa=(e,t)=>{let n=/^\^(?<major>\d+)(?:\.(?<minor>\d+))?/u.exec(t);if(!n?.groups?.major)return!1;let r=Number.parseInt(n.groups.major,10),i=Number.parseInt(n.groups.minor??`0`,10);return e.major===r&&e.minor>=i},Ta=async({fallback:e,matcher:t,packageName:n})=>{try{let r=await fetch(`${ya}/${encodeURIComponent(n)}`,{signal:AbortSignal.timeout(ba)});if(!r.ok)return e;let i=await r.json(),a=Object.keys(i.versions??{}).map(Sa).filter(e=>e!==void 0).filter(e=>wa(e,t)).toSorted(Ca).at(-1);return a?`^${a.raw}`:e}catch{return e}},Ea=async()=>{let[e,t,n,r,i]=await Promise.all([Ta(xa.oxfmt),Ta(xa.oxlint),Ta(xa.preact),Ta(xa.tailorkit),Ta(xa.typescript)]);return{oxfmt:e,oxlint:t,preact:n,tailorkit:r,typescript:i}},Da=[`pnpm`,`yarn`,`npm`,`bun`],Oa=e=>Da.includes(e),ka=e=>e.trim().toLowerCase().replaceAll(/[^a-z0-9._/-]+/gu,`-`).replaceAll(/^-+|-+$/gu,``),Aa=e=>(s(e)&&(i(`Init cancelled.`),process.exit(0)),e),ja=(e,t)=>_.resolve(t,e??`.`),Ma=async(e,t)=>{let n=ka(_.basename(t))||`tailorkit-app`;return ka(e===void 0?Aa(await f({defaultValue:n,message:`Package name`,placeholder:n,validate:e=>ka(e??``).length===0?`Enter a package name.`:void 0})):e)},Na=async e=>{if(e!==void 0){if(Oa(e))return e;throw Error(`--package-manager must be one of: ${Da.join(`, `)}.`)}return Aa(await u({initialValue:`pnpm`,message:`Package manager`,options:Da.map(e=>({label:e,value:e}))}))},Pa=async e=>e===void 0?Aa(await a({initialValue:!0,message:`Add linting with oxlint?`})):e,Fa=async e=>e===void 0?Aa(await a({initialValue:!0,message:`Add formatting with oxfmt?`})):e,Ia=e=>{try{Hr(e??``);return}catch{return`Enter a valid host URL.`}},La=async e=>{if(e!==void 0){let t=Ia(e);if(t!==void 0)throw Error(t);return Hr(e)}let t=`https://example.com/api/tailorkit`;return Hr(Aa(await f({defaultValue:t,message:`Host URL`,placeholder:t,validate:Ia})))},Ra=async e=>e===void 0?Aa(await a({initialValue:!0,message:`Install dependencies?`})):e,za=async(e,t)=>t||!ce(e)?t:Aa(await a({initialValue:!1,message:`${m.cyan(e)} already exists. Overwrite matching files?`})),Ba=(e,t,n)=>new Promise((r,i)=>{let a=de(e,t,{cwd:n,stdio:`inherit`});a.on(`close`,r),a.on(`error`,i)}),Va=async(e,t)=>{let n=d();n.start(`Installing dependencies with ${t}`);let r=await Ba(t,[`install`],e);if(r!==0)throw n.stop(`Install failed.`),Error(`${t} install exited with code ${r}.`);n.stop(`Installed dependencies.`)},Ha=async(e,t)=>{let n=d();n.start(`Formatting project`);let r=await Ba(t,[`run`,`format:fix`],e);if(r!==0)throw n.stop(`Formatting failed.`),Error(`${t} run format:fix exited with code ${r}.`);n.stop(`Formatted project.`)},Ua=async e=>{let t=ja(e.directory,e.cwd),n=await Ma(e.name,t),r=_.join(t,n),i=await za(r,e.force??!1),a=await Na(e.packageManager),o=await La(e.host),s=await Pa(e.linting),c=await Fa(e.formatting),l=await Ra(e.install),u=d();u.start(`Resolving package versions`);let f=await Ea();return u.stop(`Resolved package versions.`),await h(r,{recursive:!0}),await va({force:i,formatting:c,hostUrl:o,linting:s,packageName:n,packageVersions:f,targetDirectory:r}),l&&(await Va(r,a),c&&await Ha(r,a)),r},Wa=/^http:\/\/orpc\//,Ga=(e=>(e[e.REQUEST=1]=`REQUEST`,e[e.RESPONSE=2]=`RESPONSE`,e[e.EVENT_ITERATOR=3]=`EVENT_ITERATOR`,e[e.ABORT_SIGNAL=4]=`ABORT_SIGNAL`,e))(Ga||{});function Ka(e,t,n){if(t===3){let r=n;return{i:e,t,p:{e:r.event,d:r.data,m:r.meta}}}if(t===4)return{i:e,t,p:n};let r=n;return{i:e,p:{u:r.url.toString().replace(Wa,`/`),b:r.body,h:Object.keys(r.headers).length>0?r.headers:void 0,m:r.method===`POST`?void 0:r.method}}}function qa(e){let t=e.i,n=e.t;if(n===3){let r=e.p;return[t,n,{event:r.e,data:r.d,meta:r.m}]}if(n===4)return[t,n,e.p];let r=e.p;return[t,2,{status:r.s??200,headers:r.h??{},body:r.b}]}async function Ja(e,t,n){if(t===3||t===4)return $a(Ka(e,t,n));let r=n,{body:i,headers:a}=await Xa(r.body,r.headers),o=Ka(e,1,{...r,body:i instanceof Blob?void 0:i,headers:a});return i instanceof Blob?$a(o,i):$a(o)}async function Ya(e){let{json:t,buffer:n}=await eo(e),[r,i,a]=qa(t);if(i===3||i===4)return[r,i,a];let o=a,s=await Za(o.headers,o.body,n);return[r,i,{...o,body:s}]}async function Xa(e,t){let n={...t},r=n[`content-disposition`];if(delete n[`content-type`],delete n[`content-disposition`],e instanceof Blob)return n[`content-type`]=e.type,n[`content-disposition`]=r??Nt(e instanceof File?e.name:`blob`),{body:e,headers:n};if(e instanceof FormData){let t=new Response(e);return n[`content-type`]=t.headers.get(`content-type`),{body:await t.blob(),headers:n}}return e instanceof URLSearchParams?(n[`content-type`]=`application/x-www-form-urlencoded`,{body:e.toString(),headers:n}):w(e)?(n[`content-type`]=`text/event-stream`,{body:void 0,headers:n}):{body:e,headers:n}}async function Za(e,t,n){let r=It(e[`content-type`]),i=It(e[`content-disposition`]);if(typeof i==`string`){let e=Pt(i)??`blob`;return new File(n===void 0?[]:[n],e,{type:r})}return r?.startsWith(`multipart/form-data`)?new Response(n,{headers:{"content-type":r}}).formData():r?.startsWith(`application/x-www-form-urlencoded`)&&typeof t==`string`?new URLSearchParams(t):t}var Qa=255;async function $a(e,t){let n=D(e);return t===void 0||t.size===0?n:je(new Blob([new TextEncoder().encode(n),new Uint8Array([Qa]),t]))}async function eo(e){if(typeof e==`string`)return{json:JSON.parse(e)};let t=e instanceof Uint8Array?e:new Uint8Array(e),n=t.indexOf(Qa);if(n===-1){let e=new TextDecoder().decode(t);return{json:JSON.parse(e)}}let r=new TextDecoder().decode(t.subarray(0,n)),i=t.subarray(n+1);return{json:JSON.parse(r),buffer:i}}function to(e,t,n,r={}){let i;return new We(async()=>{i??=Ve(`consume_event_iterator_stream`);try{let n=await C(i,()=>e.pull(t));switch(n.event){case`message`:{let e=n.data;return n.meta&&O(e)&&(e=I(e,n.meta)),i?.addEvent(`message`),{value:e,done:!1}}case`error`:{let e=new P({data:n.data});throw n.meta&&(e=I(e,n.meta)),i?.addEvent(`error`),e}case`done`:{let e=n.data;return n.meta&&O(e)&&(e=I(e,n.meta)),i?.addEvent(`done`),{value:e,done:!0}}}}catch(e){throw e instanceof P||x(i,e,r),e}},async e=>{try{e!==`next`&&i?.addEvent(`cancelled`),await C(i,()=>n(e))}catch(e){throw x(i,e,r),e}finally{i?.end()}})}function no(e,t){return S({name:`stream_event_iterator`},async n=>{for(;;){let r=await(async()=>{try{let{value:t,done:r}=await e.next();return r?(n?.addEvent(`done`),{event:`done`,data:t,meta:jt(t)}):(n?.addEvent(`message`),{event:`message`,data:t,meta:jt(t)})}catch(e){if(e instanceof P)return n?.addEvent(`error`),{event:`error`,data:e.data,meta:jt(e)};try{await t({event:`error`,data:void 0})}catch(t){throw x(n,e),t}throw e}})(),i=!1;try{let n=await t(r);if(r.event===`done`||r.event===`error`)return;if(n===`abort`){i=!0,await e.return?.();return}}catch(t){if(!i)try{await e.return?.()}catch(e){throw x(n,t),e}throw t}}})}var ro=class{peer;constructor(e){this.peer=new io(async([t,n,r])=>{await e(await Ja(t,n,r))})}get length(){return this.peer.length}open(e){return this.peer.open(e)}async request(e){return this.peer.request(e)}async message(e){return this.peer.message(await Ya(e))}close(e={}){return this.peer.close(e)}},io=class{idGenerator=new Ge;responseQueue=new Ue;serverEventIteratorQueue=new Ue;serverControllers=new Map;cleanupFns=new Map;send;constructor(e){this.send=async t=>{let n=t[0];this.serverControllers.has(n)&&await e(t)}}get length(){return(+this.responseQueue.length+this.serverEventIteratorQueue.length+this.serverControllers.size+this.cleanupFns.size)/4}open(e){this.serverEventIteratorQueue.open(e),this.responseQueue.open(e);let t=new AbortController;return this.serverControllers.set(e,t),this.cleanupFns.set(e,[]),t}async request(e){let t=e.signal;return S({name:`send_peer_request`,signal:t},async()=>{if(t?.aborted)throw t.reason;let n=this.idGenerator.generate(),r=this.open(n);try{let i=Be();if(i){let t=Xe(e.headers);i.propagation.inject(i.context.active(),t),e={...e,headers:t}}if(await this.send([n,Ga.REQUEST,e]),t?.aborted)throw await this.send([n,Ga.ABORT_SIGNAL,void 0]),t.reason;let a;if(t?.addEventListener(`abort`,a=async()=>{await this.send([n,Ga.ABORT_SIGNAL,void 0]),this.close({id:n,reason:t.reason})},{once:!0}),this.cleanupFns.get(n)?.push(()=>{t?.removeEventListener(`abort`,a)}),w(e.body)){let t=e.body;no(t,async e=>r.signal.aborted?`abort`:(await this.send([n,Ga.EVENT_ITERATOR,e]),`next`))}let o=await this.responseQueue.pull(n);if(L(o.headers)){let e=to(this.serverEventIteratorQueue,n,async e=>{try{e!==`next`&&await this.send([n,Ga.ABORT_SIGNAL,void 0])}finally{this.close({id:n})}},{signal:t});return{...o,body:e}}return this.close({id:n}),o}catch(e){throw this.close({id:n,reason:e}),e}})}async message([e,t,n]){if(t===Ga.ABORT_SIGNAL){this.serverControllers.get(e)?.abort();return}if(t===Ga.EVENT_ITERATOR){this.serverEventIteratorQueue.isOpen(e)&&this.serverEventIteratorQueue.push(e,n);return}this.responseQueue.isOpen(e)&&this.responseQueue.push(e,n)}close(e={}){e.id===void 0?(this.serverControllers.forEach(t=>t.abort(e.reason)),this.serverControllers.clear(),this.cleanupFns.forEach(e=>e.forEach(e=>e())),this.cleanupFns.clear()):(this.serverControllers.get(e.id)?.abort(e.reason),this.serverControllers.delete(e.id),this.cleanupFns.get(e.id)?.forEach(e=>e()),this.cleanupFns.delete(e.id)),this.responseQueue.close(e),this.serverEventIteratorQueue.close(e)}},ao=0,oo=1,so=class{peer;constructor(e){this.peer=new ro(async t=>{if(e.websocket.readyState===ao&&await new Promise(t=>{let n=()=>{e.websocket.removeEventListener(`open`,n),e.websocket.removeEventListener(`close`,n),t()};e.websocket.addEventListener(`open`,n,{once:!0}),e.websocket.addEventListener(`close`,n,{once:!0})}),e.websocket.readyState!==oo)throw Error(`Cannot send message, WebSocket is not open.`);return e.websocket.send(t)}),e.websocket.addEventListener(`message`,async e=>{let t=e.data instanceof Blob?await je(e.data):e.data;this.peer.message(t)}),e.websocket.addEventListener(`close`,()=>{this.peer.close()})}async call(e,t,n,r){let i=await this.peer.request(e);return{...i,body:()=>Promise.resolve(i.body)}}},co=class extends nn{constructor(e){let t=new so(e);super(t,{...e,url:`http://orpc`})}};function lo(e){return zt(new co({websocket:e}))}var uo=1048576;async function fo(e,t,n){try{let r=await fetch(new URL(t.path,n),{method:t.method}),i=Number(r.headers.get(`content-length`));if(Number.isFinite(i)&&i>uo)throw Error(`Preview asset exceeds the maximum supported size.`);let a=Buffer.from(await r.arrayBuffer());if(a.byteLength>uo)throw Error(`Preview asset exceeds the maximum supported size.`);await e.respond({type:`response`,id:t.id,status:r.status,body:a.toString(`base64`),contentType:r.headers.get(`content-type`)??`application/octet-stream`})}catch{await e.respond({type:`response`,id:t.id,status:502,contentType:`text/plain`,body:``})}}function po(e,t,n){let r=1e3,i=()=>{let a=new WebSocket(e,t),o=lo(a);a.addEventListener(`open`,()=>{r=1e3,(async()=>{try{let e=await o.connect();for await(let t of e)fo(o,t,n)}catch{a.close()}})()}),a.addEventListener(`close`,()=>{setTimeout(i,r),r=Math.min(r*2,3e4)})};i()}async function mo(e){let t=await Oe(e.configPath,e.cwd);if(!t.config.appId)throw Error(`Missing appId. Deploy once before starting a remote preview.`);let n=await ai(e),r=await ri(n.hostUrl);if(!r?.deployToken)throw Error(`Not logged in. Run tailorkit login first.`);let i=await Er({headers:{authorization:`Bearer ${r.deployToken}`},url:n.hostUrl}).preview.start({appId:t.config.appId}),a=`data`in i?i.data:i;if(!a)throw Error(`Unable to start preview session.`);po(a.tunnelUrl,a.tunnelToken,`http://${e.host??`127.0.0.1`}:${e.port??4175}`),await xo(e),c.info(m.green(`Host preview session: ${a.sessionId}`))}var ho={".css":`text/css; charset=utf-8`,".html":`text/html; charset=utf-8`,".js":`text/javascript; charset=utf-8`,".json":`application/json; charset=utf-8`,".map":`application/json; charset=utf-8`},go=e=>ho[_.extname(e)]??`application/octet-stream`,_o=e=>{if(e===void 0)return;let t=Number.parseInt(String(e),10);if(!Number.isInteger(t)||t<=0)throw Error(`--port must be a positive integer.`);return t},vo=e=>({configPath:e.config,cwd:String(e.cwd??`.`),entry:e.entry,host:e.host,mode:e.mode,outDir:e.outDir,port:_o(e.port)}),yo=(e,t)=>pe(async(n,r)=>{try{let i=new URL(n.url??`/`,`http://localhost`);if(i.pathname===`/apps`){r.writeHead(200,{"access-control-allow-origin":`*`,"content-type":`application/json; charset=utf-8`}),r.end(JSON.stringify(t));return}let a=decodeURIComponent(i.pathname),o=a===`/`?`client.js`:a.slice(1),s=_.resolve(e,o),c=_.relative(e,s);if(c.startsWith(`..`)||_.isAbsolute(c)){r.writeHead(403),r.end(`Forbidden`);return}if(!(await ne(s).catch(()=>null))?.isFile()){r.writeHead(404),r.end(`Not found`);return}r.writeHead(200,{"access-control-allow-origin":`*`,"content-type":go(s)}),r.end(await g(s))}catch(e){r.writeHead(500),r.end(e instanceof Error?e.message:String(e))}}),bo=async e=>{let t=_.join(e,`package.json`),n=JSON.parse(await g(t,`utf-8`)),r=typeof n.name==`string`?n.name:_.basename(e);return[{clientPath:`/client.js`,description:typeof n.description==`string`?n.description:void 0,id:r,name:typeof n.name==`string`?n.name:void 0}]},xo=async e=>{let t=await Oe(e.configPath,e.cwd),n=_.resolve(t.root,e.outDir??t.config.build?.outDir??`.tailorkit`),r=e.host??`127.0.0.1`,i=e.port??4175,{buildApp:a}=await import(`./assets/builder-D5o0m6gu.js`),o=await a({configPath:e.configPath,cwd:e.cwd,entry:e.entry,mode:e.mode,outDir:e.outDir,watch:!0}),s=()=>{o&&typeof o==`object`&&`close`in o&&o.close()},l=yo(n,await bo(t.root));await new Promise((e,t)=>{l.once(`error`,t),l.listen(i,r,e)}),l.removeAllListeners(`error`),process.once(`SIGINT`,()=>{s(),l.close(),process.exit(0)}),process.once(`SIGTERM`,()=>{s(),l.close(),process.exit(0)}),c.info(m.green(`Experimental preview running at http://${r}:${i}`)),c.info(m.dim(`Serving built app client from ${n}`))},So=e=>{let t=ae();return t===`darwin`?{args:[e],command:`open`}:t===`win32`?{args:[`/c`,`start`,``,e],command:`cmd`}:{args:[e],command:`xdg-open`}},Co=e=>new Promise(t=>{let{args:n,command:r}=So(e),i=de(r,n,{detached:!0,stdio:`ignore`,windowsHide:!0});i.once(`error`,()=>{t(!1)}),i.once(`spawn`,()=>{i.unref(),t(!0)})}),$=p(`tailorkit`),wo=e=>{if(e<1024)return`${e} B`;let t=[`KB`,`MB`,`GB`],n=e/1024,r=0;for(;n>=1024&&r<t.length-1;)n/=1024,r+=1;return`${n.toFixed(n>=10?1:2)} ${t[r]}`};$.option(`--cwd <path>`,`Working directory`,{default:`.`}),$.command(`preview`,`Preview the app inside a host app`).option(`--config <path>`,`Path to tailorkit config`).option(`--host <host>`,`Local preview host`).option(`--port <port>`,`Local preview port`).action(async e=>{o(m.bold(`TailorKit`));try{await mo(vo(e))}catch(e){c.error(e instanceof Error?e.message:String(e)),process.exit(1)}}),$.command(`login`,`Authenticate the TailorKit CLI with a host app`).option(`--config <path>`,`Path to tailorkit config`).option(`--open`,`Open the approval URL in the default browser`,{default:!0}).option(`--timeout <seconds>`,`Seconds to wait for approval`,{default:1800}).action(async e=>{o(m.bold(`TailorKit`));let t=d(),n=!1;try{let r=Number.parseInt(String(e.timeout??`1800`),10);if(!Number.isInteger(r)||r<=0)throw Error(`--timeout must be a positive integer.`);await ii({configPath:e.config,cwd:String(e.cwd??`.`),timeout:r*1e3},({expiresAt:r,hostUrl:i,userCode:a})=>{let o=$r(i,a);e.open!==!1&&Co(o),c.info(`Enter this code in the host app: ${m.bold(a)}`),c.info(`Approval URL: ${m.cyan(o)}`),c.info(`Code expires at ${r.toLocaleString()}.`),c.info(`Waiting for approval...`),t.start(`Checking approval status`),n=!0}),n&&t.stop(`Approved.`),l(`Authenticated successfully.`)}catch(e){n&&t.stop(`Approval failed.`),c.error(e instanceof Error?e.message:String(e)),process.exit(1)}}),$.command(`logout`,`Remove stored TailorKit CLI credentials for a host app`).option(`--config <path>`,`Path to tailorkit config`).action(async e=>{o(m.bold(`TailorKit`));try{let t=await oi({configPath:e.config,cwd:String(e.cwd??`.`)});l(t.removed?`Logged out of ${m.cyan(t.hostUrl)}.`:`No stored credentials found for ${m.cyan(t.hostUrl)}.`)}catch(e){c.error(e instanceof Error?e.message:String(e)),process.exit(1)}}),$.command(`whoami`,`Show the current TailorKit CLI authentication scope`).option(`--config <path>`,`Path to tailorkit config`).action(async e=>{o(m.bold(`TailorKit`));try{let t=await ai({configPath:e.config,cwd:String(e.cwd??`.`)});c.info(`Host: ${m.cyan(t.hostUrl)}`),c.info(`Scope: ${m.cyan(t.scopeId)}`),l(`Authenticated.`)}catch(e){c.error(e instanceof Error?e.message:String(e)),process.exit(1)}}),$.command(`deploy`,`Build and deploy the TailorKit app`).option(`--config <path>`,`Path to tailorkit config`).option(`--entry <path>`,`Client entry file`).option(`--out-dir <path>`,`Build output directory`).option(`--mode <mode>`,`Vite mode`).action(async e=>{o(m.bold(`TailorKit`));let t=d();try{t.start(`Building and deploying app`);let n=await Si({configPath:e.config,cwd:String(e.cwd??`.`),entry:e.entry,mode:e.mode,onMissingAppId:async({appName:e,configPath:n,hostUrl:r,reason:i})=>{t.stop(`App not linked.`),c.info(i===`missing`?`No appId found in ${m.cyan(n)}.`:`The appId in ${m.cyan(n)} does not exist.`),c.info(`Host: ${m.cyan(r)}`);let o=await a({initialValue:!0,message:i===`missing`?`Create a TailorKit app named ${e}?`:`Create a new TailorKit app named ${e} and update the config?`});return!s(o)&&(o&&t.start(`Creating app and deploying`),o===!0)},onTypecheckFailed:async({command:e,output:n})=>{t.stop(`Type check failed.`),c.error(`Type check failed while running ${m.cyan(e)}.`),n&&c.error(n);let r=await a({initialValue:!1,message:`Type check failed, but the app built successfully. Upload anyway?`});return!s(r)&&(r&&t.start(`Uploading app`),r===!0)},outDir:e.outDir});t.stop(`Deployed app.`),n.createdApp&&c.info(`Created app and updated tailorkit.config.ts with ${m.cyan(n.appId)}.`),c.info(`Host: ${m.cyan(n.hostUrl)}`),c.info(`App: ${m.cyan(n.appId)}`),c.info(`Deployment: ${m.cyan(n.deploymentId)}`),c.info(`Uploaded files:`);for(let e of n.uploadedFiles)c.info(` ${m.cyan(e.path)} ${m.dim(`${wo(e.size)} raw, ${wo(e.gzipSize)} gzip`)}`);n.status&&c.info(`Status: ${m.cyan(n.status)}`),l(`Deployment published.`)}catch(e){t.stop(`Deployment failed.`),c.error(e instanceof Error?e.message:String(e)),process.exit(1)}}),$.command(`build`,`Build the TailorKit app`).option(`--config <path>`,`Path to tailorkit config`).option(`--entry <path>`,`Client entry file`).option(`--out-dir <path>`,`Build output directory`).option(`--mode <mode>`,`Vite mode`).action(async e=>{o(m.bold(`TailorKit`));try{let{buildApp:t}=await import(`./assets/builder-D5o0m6gu.js`);await t({configPath:e.config,cwd:String(e.cwd??`.`),entry:e.entry,mode:e.mode,outDir:e.outDir}),l(`Built app.`)}catch(e){c.error(e instanceof Error?e.message:String(e)),process.exit(1)}}),$.command(`experimental-preview`,`Build and preview the TailorKit app`).option(`--config <path>`,`Path to tailorkit config`).option(`--entry <path>`,`Client entry file`).option(`--out-dir <path>`,`Build output directory`).option(`--host <host>`,`Preview host`).option(`--port <port>`,`Preview port`).option(`--mode <mode>`,`Vite mode`).action(async e=>{o(m.bold(`TailorKit`));try{await xo(vo(e))}catch(e){c.error(e instanceof Error?e.message:String(e)),process.exit(1)}}),$.command(`generate`,`Generate TailorKit app bindings`).option(`--config <path>`,`Path to tailorkit config`).option(`--out <path>`,`Generated TypeScript output file`).action(async e=>{o(m.bold(`TailorKit`));try{let t=await ia({configPath:e.config,cwd:String(e.cwd??`.`),outFile:e.out});l(`Generated ${m.cyan(t)}.`)}catch(e){c.error(e instanceof Error?e.message:String(e)),process.exit(1)}}),$.command(`init [directory]`,`Create a new TailorKit app`).option(`--name <name>`,`Package name`).option(`--host <url>`,`TailorKit host URL`).option(`--package-manager <pm>`,`Package manager: bun, yarn, pnpm, or npm`).option(`--lint`,`Add oxlint (use --no-lint to skip)`).option(`--format`,`Add oxfmt (use --no-format to skip)`).option(`--install`,`Install dependencies after scaffolding (use --no-install to skip)`).option(`--force`,`Overwrite existing files`).action(async(e,t)=>{o(m.bold(`TailorKit`));try{let n=await Ua({cwd:String(t.cwd??`.`),directory:e,force:t.force,formatting:t.format,host:t.host,install:t.install,linting:t.lint,name:t.name,packageManager:t.packageManager});l(`Created app at ${m.cyan(n)}.`)}catch(e){c.error(e instanceof Error?e.message:String(e)),process.exit(1)}}),$.help(),$.version(`0.1.0-beta.12`),$.parse();export{Oe as t};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tailorkit/cli",
3
- "version": "0.1.0-beta.11",
3
+ "version": "0.1.0-beta.12",
4
4
  "license": "Apache-2.0",
5
5
  "repository": {
6
6
  "type": "git",
@@ -23,9 +23,9 @@
23
23
  },
24
24
  "dependencies": {
25
25
  "@clack/prompts": "^1.8.0",
26
- "@tailorkit/app": "0.1.0-beta.11",
27
- "@tailorkit/client-platform": "0.1.0-beta.11",
28
- "@tailorkit/core": "0.1.0-beta.11",
26
+ "@tailorkit/app": "0.1.0-beta.12",
27
+ "@tailorkit/client-platform": "0.1.0-beta.12",
28
+ "@tailorkit/core": "0.1.0-beta.12",
29
29
  "cac": "^7.0.0",
30
30
  "liquidjs": "^10.29.0",
31
31
  "picocolors": "^1.1.1",