@format.dev/studio 0.4.1 → 0.4.2

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.
@@ -262,4 +262,4 @@ footer { padding: 12px 20px; border-top: 1px solid var(--island-border); backgro
262
262
  export const components = {
263
263
  ${Ho(e)}
264
264
  }
265
- `;return await Jt.format(t,Ro)}const Ko={react:Uo,vue:Wo,html:Go};async function qo(e,t){return await Ko[t.framework](e)}const Jo=`virtual:generate-modules`;function Yo(){return{name:`user-virtual-module`,apply:`serve`,resolveId(e){if(e===Jo)return e},async load(e){if(e===Jo){let e=S.getConfig();return await qo(await pt(e),e)}}}}const Xo=/\.(css|scss|sass|less)(\?inline)?$/i;function Zo(){return{name:`auto-inline-css`,enforce:`pre`,resolveId(e,t,n){return n?.ssr||!Xo.test(e)||!t||/\?inline($|&)/.test(e)?null:this.resolve(e+`?inline`,t)}}}function Qo(t,n){let r=e.relative(e.resolve(n),e.resolve(t));return r===``||!r.startsWith(`..`)&&!e.isAbsolute(r)}function $o(e,t){for(let n of t)if(Qo(e,n))return!0;return!1}async function es(e){try{let t=await y(e);return C(`sha256`).update(t).digest(`hex`).slice(0,8)}catch{return null}}function ts(t={}){let n=(t.watchDirs??[]).map(t=>e.resolve(t)),r=t.documentsDir?e.resolve(t.documentsDir):null,i=t.onFileChanged??(()=>{});return{name:`hot-update-notifier`,apply:`serve`,configureServer(t){if(n.length===0&&!r)return;let a=null,o=null,s=async()=>{if(!o)return;let{event:e,file:n}=o;o=null,g.debug(`HMR asset event detected (${e})`,n),t.ws.send({type:`custom`,event:`hmr`,data:{file:n,ts:Date.now(),hash:e===`unlink`||e===`unlinkDir`?null:await es(n),event:e}})},c=(t,r)=>{let i=e.resolve(r);$o(i,n)&&(o={event:t,file:i},a&&clearTimeout(a),a=setTimeout(()=>void s(),75))},l=null,u=()=>{g.debug(`documents change settled, client refreshing documents`),t.ws.send({type:`custom`,event:`documents-changed`,data:{ts:Date.now()}})},d=(t,n)=>{!r||!Qo(e.resolve(n),r)||(g.debug(`documents ${t}: ${n}`),l&&clearTimeout(l),l=setTimeout(u,100))},f=[...n,...r?[r]:[]];for(let e of f)t.watcher.add(e);r&&g.debug(`Watching for document changes in: ${r}`);let p=e=>{i(e),c(`add`,e),d(`add`,e)},m=e=>{i(e),c(`change`,e)},ee=e=>{i(e),c(`unlink`,e),d(`unlink`,e)},h=e=>{i(e),c(`addDir`,e),d(`addDir`,e)},te=e=>{i(e),c(`unlinkDir`,e),d(`unlinkDir`,e)};t.watcher.on(`add`,p),t.watcher.on(`change`,m),t.watcher.on(`unlink`,ee),t.watcher.on(`addDir`,h),t.watcher.on(`unlinkDir`,te),t.httpServer?.once(`close`,()=>{for(let e of f)t.watcher.unwatch(e);a&&clearTimeout(a),l&&clearTimeout(l),t.watcher.off(`add`,p),t.watcher.off(`change`,m),t.watcher.off(`unlink`,ee),t.watcher.off(`addDir`,h),t.watcher.off(`unlinkDir`,te)})},async handleHotUpdate(e){if(i(e.file),n.length>0&&$o(e.file,n))return[];g.debug(`HMR file update detected`,e.file);let t=await es(e.file);return e.server.ws.send({type:`custom`,event:`hmr`,data:{file:e.file,ts:Date.now(),hash:t,modules:e.modules.map(e=>e.url)}}),[]}}}const ns={appDir:a(I,`app`),engineDir:B};function rs(e,t=ns){return[re(e),t.appDir,t.engineDir]}function is(){let e=new Set,t=new Map;return function(n={}){let r=[er()],i={};for(let e of r){if(!l.existsSync(e))continue;let t=Se(l.readFileSync(e,`utf8`));Object.assign(i,t)}let a=n.keyFilter??(()=>!0),o=new Set(Object.keys(i).filter(a));for(let n of e)if(!o.has(n))if(t.has(n)){let e=t.get(n);e===void 0?delete process.env[n]:process.env[n]=e,t.delete(n)}else delete process.env[n];for(let e of o)t.has(e)||t.set(e,process.env[e]),process.env[e]=i[e];e=o}}const as=is();function os(e={}){return as(e)}function ss(e){return t=>{let n=s(er()),r=null,i=t=>{s(t)===n&&(r&&clearTimeout(r),r=setTimeout(()=>{e()},75))};t.watcher.add(n),t.watcher.on(`add`,i),t.watcher.on(`change`,i),t.watcher.on(`unlink`,i),t.httpServer?.once(`close`,()=>{r&&clearTimeout(r),t.watcher.unwatch(n),t.watcher.off(`add`,i),t.watcher.off(`change`,i),t.watcher.off(`unlink`,i)})}}function cs(e,t){let n=!1,r=null,i=i=>{r&&clearTimeout(r),r=setTimeout(async()=>{if(!n){n=!0;try{g.info(`Config file changed — restarting Format Studio server...`);let{config:n}=await he(e);S.setConfig(n),await t?.(),await i.restart()}catch(e){g.error(`Restart failed.`,e);let t={message:`Failed to restart Format Studio server after config file change.`};e instanceof Error&&e.message&&(t.details=[{message:e.message}]),A(i,t)}finally{n=!1}}},120)};return t=>{let n=n=>{n===e&&(H.consumeConfigRestartSkip()||i(t))};t.watcher.add(e),t.watcher.on(`change`,n),t.watcher.on(`add`,n),t.watcher.on(`unlink`,n),t.httpServer?.once(`close`,()=>{t.watcher.unwatch(e),t.watcher.off(`change`,n),t.watcher.off(`add`,n),t.watcher.off(`unlink`,n)})}}function ls(e,t,n=`pre`){return{name:e,enforce:n,async configResolved(e){for(let n of t.configResolved??[])await n(e)},async configureServer(e){for(let n of t.configureServer??[])await n(e)},async handleHotUpdate(e){for(let n of t.handleHotUpdate??[])await n(e)},async buildStart(){for(let e of t.buildStart??[])await e()},async closeBundle(){for(let e of t.closeBundle??[])await e()}}}function us(e,t={}){let{onRestart:n}=t,r=()=>{os(),ve(ge())};return ls(`format:hooks`,{configResolved:[r],configureServer:[r,ss(r),cs(e,n)]})}async function ds(){let e=await he();return S.setConfig(e.config),os(),e}function fs(e=process.env.FMT_ENGINE_VERSION,t=P()){return e?.trim()||(t.stampEngineVersion??`0.4.1`)}const ps={FMT_ENV:`the FMT_ENV variable`,settings:`saved settings`,default:`the default`},ms=e=>ps[e],hs=e=>e.port?Number(e.port):process.env.PORT?Number(process.env.PORT):1234;async function gs(e){let{config:t,filepath:n}=await ds(),r=er();u(r)||g.debug(`No .env file found at startup: ${r}`),ve(ge()),Sn({settings:await M()});let i=wn();Cn(i)&&g.info(`Environment: ${i.environment.name} (from ${ms(i.source)})`);let a=hs(e),o=x();g.info(`Loading Format Studio...`),g.debug(`Format dev options`,e),g.debug(`CWD: ${o}`),g.debug(`User config: ${JSON.stringify(t)}`),g.debug(`Log level: ${me()}`),g.debug(`Checking dependency versions`);try{$t(o)}catch(e){g.error(e.message),process.exit(1)}let c=await Qt(o);if(c.pinnedVersion||(g.error(`No "version" field found in your Format config. Run \`${Y(`update latest`)}\` to pin a release.`),process.exit()),c.mismatches.length>0){g.error(`Some installed Format packages do not match the pinned version (${c.pinnedVersion}):`);for(let e of c.mismatches)g.error(` ${e.name} ${e.actual} (expected ${e.expected})`);g.error(`Run \`${Y(`update`)}\` to bring everything in line.`),process.exit()}let l=fs();g.debug(`Engine requested: ${l}`),wa(e.authMode);let d=Da();try{g.debug(`Authenticating`);let t=await Ga(l,e,d);if(!t)throw new T(`Failed to authenticate`);let{accessToken:n,engineUrl:r,engineDigest:i,engine:a}=t;if(!n)throw new T(`Access token missing from credentials`);if(!r)throw new T(`Engine URL missing from access token`);H.setToken(n),H.setEngineVersions({requested:l,resolved:a}),await bo(r,a,i)}catch(e){e instanceof sa&&(console.error(e.message),process.exit(3)),g.error(`Failed to start Format Studio`),e instanceof E&&(g.error(pn),process.exit()),g.error(`Error: ${e.message}`),process.exit()}let f=(0,F.getSharedAssetsDir)(t),{isDirectory:p}=await fe(f),m=p;!p&&t.sharedAssetsDir&&g.error(`Shared assets directory (sharedAssetsDir) not found or is not a directory: ${t.sharedAssetsDir} (${f})`);let{baseViteConfig:ee,frameworkPlugins:re,stylePlugins:ae}=Xt(),oe=new en({log:e=>g.debug(e),warn:e=>g.warn(e),allowedReadPaths:[o],sandbox:`standard`}),se=[()=>void oe.dispose(),Hr];process.once(`exit`,()=>{for(let e of se)e()});let ce=()=>process.exit();process.once(`SIGINT`,ce),process.once(`SIGTERM`,ce);let le=await te(ne(ee,{clearScreen:!1,configFile:!1,server:{port:a,strictPort:!0,fs:{allow:rs(o)},watch:{ignored:Re,awaitWriteFinish:{stabilityThreshold:200,pollInterval:50}}},plugins:[ts({watchDirs:[r,...m?[f]:[]],documentsDir:(0,F.getDocumentsDir)(t),onFileChanged:e=>Rr(e,t)}),us(n),Yt(!1),Zo(),Yo(),Lo(a,oe),...re,...ae],optimizeDeps:{entries:!1,exclude:[`dist/app`]},define:{DEFAULT_VARIANT:JSON.stringify(Ue),VARIANT_PARAM:JSON.stringify(Ye)},build:{rollupOptions:{input:{}}},cacheDir:s(Mn(),`vite-cache`),resolve:{dedupe:[`react`,`react-dom`],alias:{[Dn]:ao(I,`app`,`index.js`)},mainFields:[]}}));Dr(e=>{le.ws.send({type:`custom`,event:`pdf-build-status`,data:e})}),await oe.initDev({root:o,framework:t.framework,configJson:JSON.stringify(t),decodeStyleEntities:Zt({framework:t.framework})});try{await le.listen()}catch(e){if(!/already in use/i.test(e.message))throw e;g.error(mn(a)),process.exit(1)}se.push(za({server:le}));let ue=`${fn}:${a}`;d.studioListening(ue),e.open&&!await d.browserSent&&await ie(ue);let de=[`FORMAT STUDIO`,`————————————————————————`,ue,`————————————————————————`,`Build something amazing.`],pe=Math.max(...de.map(e=>e.length))+8,he=`═`.repeat(pe+2);console.log(h(`╔${he}╗`)),de.forEach(e=>{let t=e.padStart((pe+e.length)/2).padEnd(pe);console.log(h(`║ ${t} ║`))}),console.log(h(`╚${he}╝`))}export{M as C,Sn as S,T,ii as _,Ma as a,R as b,Pi as c,Di as d,Ti as f,q as g,bi as h,Z as i,Y as l,J as m,fs as n,Mi as o,Ei as p,ds as r,Ni as s,gs as t,xi as u,ai as v,E as w,P as x,Mn as y};
265
+ `;return await Jt.format(t,Ro)}const Ko={react:Uo,vue:Wo,html:Go};async function qo(e,t){return await Ko[t.framework](e)}const Jo=`virtual:generate-modules`;function Yo(){return{name:`user-virtual-module`,apply:`serve`,resolveId(e){if(e===Jo)return e},async load(e){if(e===Jo){let e=S.getConfig();return await qo(await pt(e),e)}}}}const Xo=/\.(css|scss|sass|less)(\?inline)?$/i;function Zo(){return{name:`auto-inline-css`,enforce:`pre`,resolveId(e,t,n){return n?.ssr||!Xo.test(e)||!t||/\?inline($|&)/.test(e)?null:this.resolve(e+`?inline`,t)}}}function Qo(t,n){let r=e.relative(e.resolve(n),e.resolve(t));return r===``||!r.startsWith(`..`)&&!e.isAbsolute(r)}function $o(e,t){for(let n of t)if(Qo(e,n))return!0;return!1}async function es(e){try{let t=await y(e);return C(`sha256`).update(t).digest(`hex`).slice(0,8)}catch{return null}}function ts(t={}){let n=(t.watchDirs??[]).map(t=>e.resolve(t)),r=t.documentsDir?e.resolve(t.documentsDir):null,i=t.onFileChanged??(()=>{});return{name:`hot-update-notifier`,apply:`serve`,configureServer(t){if(n.length===0&&!r)return;let a=null,o=null,s=async()=>{if(!o)return;let{event:e,file:n}=o;o=null,g.debug(`HMR asset event detected (${e})`,n),t.ws.send({type:`custom`,event:`hmr`,data:{file:n,ts:Date.now(),hash:e===`unlink`||e===`unlinkDir`?null:await es(n),event:e}})},c=(t,r)=>{let i=e.resolve(r);$o(i,n)&&(o={event:t,file:i},a&&clearTimeout(a),a=setTimeout(()=>void s(),75))},l=null,u=()=>{g.debug(`documents change settled, client refreshing documents`),t.ws.send({type:`custom`,event:`documents-changed`,data:{ts:Date.now()}})},d=(t,n)=>{!r||!Qo(e.resolve(n),r)||(g.debug(`documents ${t}: ${n}`),l&&clearTimeout(l),l=setTimeout(u,100))},f=[...n,...r?[r]:[]];for(let e of f)t.watcher.add(e);r&&g.debug(`Watching for document changes in: ${r}`);let p=e=>{i(e),c(`add`,e),d(`add`,e)},m=e=>{i(e),c(`change`,e)},ee=e=>{i(e),c(`unlink`,e),d(`unlink`,e)},h=e=>{i(e),c(`addDir`,e),d(`addDir`,e)},te=e=>{i(e),c(`unlinkDir`,e),d(`unlinkDir`,e)};t.watcher.on(`add`,p),t.watcher.on(`change`,m),t.watcher.on(`unlink`,ee),t.watcher.on(`addDir`,h),t.watcher.on(`unlinkDir`,te),t.httpServer?.once(`close`,()=>{for(let e of f)t.watcher.unwatch(e);a&&clearTimeout(a),l&&clearTimeout(l),t.watcher.off(`add`,p),t.watcher.off(`change`,m),t.watcher.off(`unlink`,ee),t.watcher.off(`addDir`,h),t.watcher.off(`unlinkDir`,te)})},async handleHotUpdate(e){if(i(e.file),n.length>0&&$o(e.file,n))return[];g.debug(`HMR file update detected`,e.file);let t=await es(e.file);return e.server.ws.send({type:`custom`,event:`hmr`,data:{file:e.file,ts:Date.now(),hash:t,modules:e.modules.map(e=>e.url)}}),[]}}}const ns={appDir:a(I,`app`),engineDir:B};function rs(e,t=ns){return[re(e),t.appDir,t.engineDir]}function is(){let e=new Set,t=new Map;return function(n={}){let r=[er()],i={};for(let e of r){if(!l.existsSync(e))continue;let t=Se(l.readFileSync(e,`utf8`));Object.assign(i,t)}let a=n.keyFilter??(()=>!0),o=new Set(Object.keys(i).filter(a));for(let n of e)if(!o.has(n))if(t.has(n)){let e=t.get(n);e===void 0?delete process.env[n]:process.env[n]=e,t.delete(n)}else delete process.env[n];for(let e of o)t.has(e)||t.set(e,process.env[e]),process.env[e]=i[e];e=o}}const as=is();function os(e={}){return as(e)}function ss(e){return t=>{let n=s(er()),r=null,i=t=>{s(t)===n&&(r&&clearTimeout(r),r=setTimeout(()=>{e()},75))};t.watcher.add(n),t.watcher.on(`add`,i),t.watcher.on(`change`,i),t.watcher.on(`unlink`,i),t.httpServer?.once(`close`,()=>{r&&clearTimeout(r),t.watcher.unwatch(n),t.watcher.off(`add`,i),t.watcher.off(`change`,i),t.watcher.off(`unlink`,i)})}}function cs(e,t){let n=!1,r=null,i=i=>{r&&clearTimeout(r),r=setTimeout(async()=>{if(!n){n=!0;try{g.info(`Config file changed — restarting Format Studio server...`);let{config:n}=await he(e);S.setConfig(n),await t?.(),await i.restart()}catch(e){g.error(`Restart failed.`,e);let t={message:`Failed to restart Format Studio server after config file change.`};e instanceof Error&&e.message&&(t.details=[{message:e.message}]),A(i,t)}finally{n=!1}}},120)};return t=>{let n=n=>{n===e&&(H.consumeConfigRestartSkip()||i(t))};t.watcher.add(e),t.watcher.on(`change`,n),t.watcher.on(`add`,n),t.watcher.on(`unlink`,n),t.httpServer?.once(`close`,()=>{t.watcher.unwatch(e),t.watcher.off(`change`,n),t.watcher.off(`add`,n),t.watcher.off(`unlink`,n)})}}function ls(e,t,n=`pre`){return{name:e,enforce:n,async configResolved(e){for(let n of t.configResolved??[])await n(e)},async configureServer(e){for(let n of t.configureServer??[])await n(e)},async handleHotUpdate(e){for(let n of t.handleHotUpdate??[])await n(e)},async buildStart(){for(let e of t.buildStart??[])await e()},async closeBundle(){for(let e of t.closeBundle??[])await e()}}}function us(e,t={}){let{onRestart:n}=t,r=()=>{os(),ve(ge())};return ls(`format:hooks`,{configResolved:[r],configureServer:[r,ss(r),cs(e,n)]})}async function ds(){let e=await he();return S.setConfig(e.config),os(),e}function fs(e=process.env.FMT_ENGINE_VERSION,t=P()){return e?.trim()||(t.stampEngineVersion??`0.4.2`)}const ps={FMT_ENV:`the FMT_ENV variable`,settings:`saved settings`,default:`the default`},ms=e=>ps[e],hs=e=>e.port?Number(e.port):process.env.PORT?Number(process.env.PORT):1234;async function gs(e){let{config:t,filepath:n}=await ds(),r=er();u(r)||g.debug(`No .env file found at startup: ${r}`),ve(ge()),Sn({settings:await M()});let i=wn();Cn(i)&&g.info(`Environment: ${i.environment.name} (from ${ms(i.source)})`);let a=hs(e),o=x();g.info(`Loading Format Studio...`),g.debug(`Format dev options`,e),g.debug(`CWD: ${o}`),g.debug(`User config: ${JSON.stringify(t)}`),g.debug(`Log level: ${me()}`),g.debug(`Checking dependency versions`);try{$t(o)}catch(e){g.error(e.message),process.exit(1)}let c=await Qt(o);if(c.pinnedVersion||(g.error(`No "version" field found in your Format config. Run \`${Y(`update latest`)}\` to pin a release.`),process.exit()),c.mismatches.length>0){g.error(`Some installed Format packages do not match the pinned version (${c.pinnedVersion}):`);for(let e of c.mismatches)g.error(` ${e.name} ${e.actual} (expected ${e.expected})`);g.error(`Run \`${Y(`update`)}\` to bring everything in line.`),process.exit()}let l=fs();g.debug(`Engine requested: ${l}`),wa(e.authMode);let d=Da();try{g.debug(`Authenticating`);let t=await Ga(l,e,d);if(!t)throw new T(`Failed to authenticate`);let{accessToken:n,engineUrl:r,engineDigest:i,engine:a}=t;if(!n)throw new T(`Access token missing from credentials`);if(!r)throw new T(`Engine URL missing from access token`);H.setToken(n),H.setEngineVersions({requested:l,resolved:a}),await bo(r,a,i)}catch(e){e instanceof sa&&(console.error(e.message),process.exit(3)),g.error(`Failed to start Format Studio`),e instanceof E&&(g.error(pn),process.exit()),g.error(`Error: ${e.message}`),process.exit()}let f=(0,F.getSharedAssetsDir)(t),{isDirectory:p}=await fe(f),m=p;!p&&t.sharedAssetsDir&&g.error(`Shared assets directory (sharedAssetsDir) not found or is not a directory: ${t.sharedAssetsDir} (${f})`);let{baseViteConfig:ee,frameworkPlugins:re,stylePlugins:ae}=Xt(),oe=new en({log:e=>g.debug(e),warn:e=>g.warn(e),allowedReadPaths:[o],sandbox:`standard`}),se=[()=>void oe.dispose(),Hr];process.once(`exit`,()=>{for(let e of se)e()});let ce=()=>process.exit();process.once(`SIGINT`,ce),process.once(`SIGTERM`,ce);let le=await te(ne(ee,{clearScreen:!1,configFile:!1,server:{port:a,strictPort:!0,fs:{allow:rs(o)},watch:{ignored:Re,awaitWriteFinish:{stabilityThreshold:200,pollInterval:50}}},plugins:[ts({watchDirs:[r,...m?[f]:[]],documentsDir:(0,F.getDocumentsDir)(t),onFileChanged:e=>Rr(e,t)}),us(n),Yt(!1),Zo(),Yo(),Lo(a,oe),...re,...ae],optimizeDeps:{entries:!1,exclude:[`dist/app`]},define:{DEFAULT_VARIANT:JSON.stringify(Ue),VARIANT_PARAM:JSON.stringify(Ye)},build:{rollupOptions:{input:{}}},cacheDir:s(Mn(),`vite-cache`),resolve:{dedupe:[`react`,`react-dom`],alias:{[Dn]:ao(I,`app`,`index.js`)},mainFields:[]}}));Dr(e=>{le.ws.send({type:`custom`,event:`pdf-build-status`,data:e})}),await oe.initDev({root:o,framework:t.framework,configJson:JSON.stringify(t),decodeStyleEntities:Zt({framework:t.framework})});try{await le.listen()}catch(e){if(!/already in use/i.test(e.message))throw e;g.error(mn(a)),process.exit(1)}se.push(za({server:le}));let ue=`${fn}:${a}`;d.studioListening(ue),e.open&&!await d.browserSent&&await ie(ue);let de=[`FORMAT STUDIO`,`————————————————————————`,ue,`————————————————————————`,`Build something amazing.`],pe=Math.max(...de.map(e=>e.length))+8,he=`═`.repeat(pe+2);console.log(h(`╔${he}╗`)),de.forEach(e=>{let t=e.padStart((pe+e.length)/2).padEnd(pe);console.log(h(`║ ${t} ║`))}),console.log(h(`╚${he}╝`))}export{M as C,Sn as S,T,ii as _,Ma as a,R as b,Pi as c,Di as d,Ti as f,q as g,bi as h,Z as i,Y as l,J as m,fs as n,Mi as o,Ei as p,ds as r,Ni as s,gs as t,xi as u,ai as v,E as w,P as x,Mn as y};
package/dist/node/bin.js CHANGED
@@ -1,4 +1,4 @@
1
- import{C as e,S as t,T as n,_ as r,a as i,b as a,c as o,d as s,f as c,g as l,h as u,i as d,l as f,m as p,n as m,o as h,p as g,r as _,s as v,t as y,u as b,v as x,w as S,x as C,y as w}from"./C1fjQUpt.js";import{join as T}from"node:path";import{readFile as E,readdir as D,rm as O}from"node:fs/promises";import{createSpecProgram as ee}from"@format.dev/compile/server/cli/index";import{rimraf as te}from"rimraf";var ne=class extends n{constructor(){super(`No code was entered. Nothing was sent.`),this.name=`CodeEntryCancelledError`}};async function re(e){let t=[];for await(let n of e)t.push(Buffer.isBuffer(n)?n:Buffer.from(String(n)));return Buffer.concat(t).toString(`utf8`).split(/\r?\n/).map(e=>e.trim()).find(Boolean)??``}function k(e,t){return new Promise((n,r)=>{let i=``,a=n=>{e.off(`data`,o),e.setRawMode(!1),e.pause(),t.write(`
1
+ import{C as e,S as t,T as n,_ as r,a as i,b as a,c as o,d as s,f as c,g as l,h as u,i as d,l as f,m as p,n as m,o as h,p as g,r as _,s as v,t as y,u as b,v as x,w as S,x as C,y as w}from"./DJhtSY7k.js";import{join as T}from"node:path";import{readFile as E,readdir as D,rm as O}from"node:fs/promises";import{createSpecProgram as ee}from"@format.dev/compile/server/cli/index";import{rimraf as te}from"rimraf";var ne=class extends n{constructor(){super(`No code was entered. Nothing was sent.`),this.name=`CodeEntryCancelledError`}};async function re(e){let t=[];for await(let n of e)t.push(Buffer.isBuffer(n)?n:Buffer.from(String(n)));return Buffer.concat(t).toString(`utf8`).split(/\r?\n/).map(e=>e.trim()).find(Boolean)??``}function k(e,t){return new Promise((n,r)=>{let i=``,a=n=>{e.off(`data`,o),e.setRawMode(!1),e.pause(),t.write(`
2
2
  `),n()},o=e=>{for(let t of String(e)){if(t===``||t===``){a(()=>r(new ne));return}if(t===`\r`||t===`
3
3
  `){a(()=>n(i.trim()));return}if(t===``||t===`\b`){i=i.slice(0,-1);continue}i+=t}};t.write(`Paste the code from the browser and press Enter: `),e.setRawMode(!0),e.resume(),e.on(`data`,o)})}async function A(e={}){let{input:t=process.stdin,prompt:r=process.stderr}=e,i=t.isTTY?await k(t,r):await re(t);if(!i)throw new n(`No code was given. Paste the one-time code Dash shows.`);return i}const j=/^[A-Za-z0-9_-]{22}$/,M=()=>T(a(),`sign-in-attempts`);function N(e){if(!j.test(e))throw Error(`Not a connection request id: ${e}`);return T(M(),`${e}.json`)}async function P(e){try{return JSON.parse(await E(N(e),`utf8`))}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function F(e){let t=e.status===`completed`||e.status===`interrupted`?{...e,codeVerifier:``}:e;await x(N(e.attemptId),JSON.stringify(t,null,2))}async function I(e){await O(N(e),{force:!0})}async function L(){let e=(await D(M()).catch(()=>[])).filter(e=>e.endsWith(`.json`)).map(e=>e.slice(0,-5));return(await Promise.all(e.filter(e=>j.test(e)).map(P))).filter(e=>e!==null)}function R(e,t=Date.now()){return e.expiresAt<=t}async function z(e=Date.now()){let t=await L();await Promise.all(t.filter(t=>R(t,e)).map(e=>I(e.attemptId)))}var B=class extends n{constructor(e,t){super(t),this.code=e,this.name=`AuthCommandError`}};const V={InvalidSignInCodeError:`INVALID_CODE`,SignInRefusedError:`ACCESS_DENIED`,UnsupportedSignInProtocolError:`UNSUPPORTED_PROTOCOL`,ServerUnreachableError:`UNREACHABLE`,CodeEntryCancelledError:`CANCELLED`};function H(e){return e instanceof B?e.code:V[e?.name]??`FAILED`}function U(e){let{json:t,data:n,lines:r}=e;if(t){process.stdout.write(`${JSON.stringify(n)}\n`);return}console.log(r.join(`
4
4
  `))}function ie(e,t){let n=t instanceof Error?t.message:String(t),r=H(t);if(process.exitCode=1,e){process.stdout.write(`${JSON.stringify({status:`error`,error:{code:r,message:n}})}\n`);return}console.error(n)}async function W(e,t){try{await t()}catch(t){ie(e,t)}}async function G(){return await _(),t({settings:await e()})}function K(e){if(!e.request)throw new B(`MISSING_REQUEST`,`Name the request with --request <id>, as \`${f(`auth start`)}\` printed it.`);return e.request}function q(e){return f(`auth complete --request ${e}`)}function J(e){return`${q(e)} --code-stdin`}async function Y(e){if(e.code!==void 0)return e.code.trim();let t=process.stdin.isTTY===!0;if(e.codeStdin||t)return A();throw new B(`MISSING_CODE`,`Give the code with --code <code>, or pipe it in with --code-stdin.`)}function ae(e,t){if(!(e.environment===t.name&&e.dashboardApiUrl===t.dashboardApiUrl))throw new B(`WRONG_ENVIRONMENT`,`This request was started for the ${e.environment} environment. Complete it with the same FMT_ENV.`)}async function oe(e){let t=await P(e);if(!t)throw new B(`NOT_FOUND`,`No connection request ${e} on this machine. Check the id for a typo, or run \`${f(`auth start`)}\` to begin a new one.`);return t}async function se(e){throw await I(e),new B(`EXPIRED`,`This request has expired. Run \`${f(`auth start`)}\` to begin again.`)}async function ce(e){await W(e.json,async()=>{let t=await G(),n=c({mode:`remote`}),i=g(),a=Date.now();await z(a);let o={attemptId:n.attemptId,mode:`remote`,codeVerifier:n.codeVerifier,codeChallenge:n.codeChallenge,protocol:b,environment:t.name,dashboardApiUrl:t.dashboardApiUrl,requestedEngine:m(),deviceName:i,createdAt:a,expiresAt:a+18e5,status:`pending`};await r(N(o.attemptId),()=>F(o));let l=s({dashboardUrl:t.dashboardUrl,attempt:n,deviceName:i}),u=q(o.attemptId);U({json:e.json,data:{status:`pending`,attemptId:o.attemptId,url:l,expiresAt:new Date(o.expiresAt).toISOString(),next:J(o.attemptId)},lines:[``,` Connect Studio on this machine`,``,` 1. Open the link in your browser:`,``,` ${l}`,``,` 2. Choose an organization and select Approve connection.`,` 3. Copy the code, then run the command below and paste it when asked:`,``,` ${u}`,``]})})}function X(e){let t=d(e);if(!t)throw new n(`Format answered with an access token Studio cannot read.`);return{organization:{id:t.org.id,name:t.org.name,isPersonal:t.org.isPersonal},account:{name:t.name,email:t.email}}}function Z(e,t){let n=t.account.email??t.account.name,r=t.organization.isPersonal?`your personal organization`:t.organization.name;U({json:e,data:{status:`signed-in`,...t},lines:[`Studio is connected to ${r} as ${n}. Run \`${f(`dev`)}\` to start.`]})}async function Q(e){let t=await oe(e);if(ae(t,C()),t.status===`completed`&&t.result)return{attempt:t,result:t.result};let n=(await l()).find(t=>t.signInAttemptId===e);if(n){let e=X(n.accessToken);return await u(n.org.id),await F({...t,status:`completed`,result:e}),{attempt:t,result:e}}if(t.status!==`pending`)throw new B(`INTERRUPTED`,`This request did not finish and cannot be used again. Run \`${f(`auth start`)}\`.`);return R(t)&&await se(e),{attempt:t,result:null}}async function le(e,t){let{attempt:n,result:r}=await Q(e);if(r)return r;let a=await v({apiUrl:n.dashboardApiUrl,attempt:n,code:t,requestedEngine:n.requestedEngine,signal:AbortSignal.timeout(6e4)}).catch(async e=>{throw e instanceof h&&await F({...n,status:`interrupted`}),e instanceof S?new B(`UNREACHABLE`,`${e.message} Run this command again with the same code. If the code is refused, run \`${f(`auth start`)}\`.`):e}),s=await i({authResult:a,requestedEngine:n.requestedEngine,signInAttemptId:e}).catch(async e=>{throw await o({apiUrl:n.dashboardApiUrl,refreshToken:a.refreshToken}),await F({...n,status:`interrupted`}),e});await u(s.org.id);let c=X(s.accessToken);return await F({...n,status:`completed`,result:c}),c}async function ue(e){await W(e.json,async()=>{let t=K(e);await G();let n=N(t),i=await r(n,()=>Q(t));if(i.result){Z(e.json,i.result);return}let a=await Y(e),o=await r(n,()=>le(t,a));Z(e.json,o)})}function $(e){let t=e.status===`pending`&&R(e)?`expired`:e.status;return{attemptId:e.attemptId,status:t,createdAt:new Date(e.createdAt).toISOString(),expiresAt:new Date(e.expiresAt).toISOString(),...e.result&&{result:e.result}}}async function de(e){await W(e.json,async()=>{await G();let t=e.request?[await P(e.request)].filter(e=>e!==null):await L(),{currentOrgId:n}=await p(),r=(await l()).map(e=>({organization:{id:e.org.id,name:e.org.name},current:e.org.id===n})),i=t.map(e=>` ${e.attemptId} ${$(e).status}`),a=r.map(({organization:e,current:t})=>` ${e.name}${t?` (current)`:``}`);U({json:e.json,data:{attempts:t.map($),connections:r,source:`local`},lines:[`Connection requests on this machine:`,...i.length?i:[` none`],``,`Saved connections:`,...a.length?a:[` none`],``,`This reads local files only. It cannot tell whether a browser approved, or whether Format still accepts these.`]})})}async function fe(e){await W(e.json,async()=>{let t=K(e);await G();let n=await r(N(t),async()=>{let e=await P(t);return await I(t),e!==null});U({json:e.json,data:{cancelled:n,attemptId:t},lines:[n?`Connection request cancelled.`:`No connection request ${t} on this machine.`]})})}var pe={commands:[{name:`dev`,description:`Run the Format Studio server.`,options:[{field:`open`,flags:`--no-open`,description:`Do not automatically open Studio in the browser after authentication.`,type:`boolean`,defaultValue:!0},{field:`port`,flags:`--port <port>`,description:`Port to run the server on. Defaults to 1234.`,type:`number`},{field:`authMode`,flags:`--auth-mode <mode>`,description:`Sign in through a listener on this machine even where Studio detects SSH or a container. Use this when your browser can reach this machine's loopback address.`,type:`string`,choices:[`local`]}]},{name:`auth`,description:`Sign in to Format from a machine your browser cannot reach, such as over SSH, in a container, or in a cloud agent's sandbox.`,options:[],commands:[{name:`start`,description:`Start a sign-in. Prints a link to open in any browser, and the command to run with the code it gives you.`,options:[{field:`json`,flags:`--json`,description:`Prints the result as a JSON object to stdout. Useful for scripts and agents.`,type:`boolean`}]},{name:`complete`,description:`Finish a sign-in with the code from the browser. A terminal asks for it; a script passes --code or pipes it in with --code-stdin.`,options:[{field:`request`,flags:`--request <id>`,description:"The sign-in request to complete against. You obtain this from running `format auth start`.",type:`string`},{field:`code`,flags:`--code <code>`,description:`Pass your sign-in code with the command as text. Be aware that it lands in your shell history.`,type:`string`},{field:`codeStdin`,flags:`--code-stdin`,description:`Reads your sign-in code from stdin. Useful for scripts and agents that pipe it in. Standard terminals default to this behaviour but this flag forces it regardless of the terminal.`,type:`boolean`},{field:`json`,flags:`--json`,description:`Prints the result as a JSON object to stdout. Useful for scripts and agents.`,type:`boolean`}]},{name:`status`,description:`Show the sign-ins started on this machine and the saved connections. Reads local files only.`,options:[{field:`request`,flags:`--request <id>`,description:`Limit the status to a specific sign-in request ID.`,type:`string`},{field:`json`,flags:`--json`,description:`Prints the result as a JSON object to stdout. Useful for scripts and agents.`,type:`boolean`}]},{name:`cancel`,description:`Cancels a sign-in, so the code issued for it can no longer be used.`,options:[{field:`request`,flags:`--request <id>`,description:`The sign-in request ID to cancel.`,type:`string`},{field:`json`,flags:`--json`,description:`Prints the result as a JSON object to stdout. Useful for scripts and agents.`,type:`boolean`}]}]}]};function me(){return ee({name:`format-studio`,description:`Format Studio`,spec:pe,handlers:{dev:y,"auth start":ce,"auth complete":ue,"auth status":de,"auth cancel":fe,"clear-cache":async()=>{await te(w())}}})}me().parse();export{};
@@ -1 +1 @@
1
- import{t as e}from"./C1fjQUpt.js";export{e as serve};
1
+ import{t as e}from"./DJhtSY7k.js";export{e as serve};
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@format.dev/studio",
3
3
  "module": "./dist/node/index.js",
4
4
  "type": "module",
5
- "version": "0.4.1",
5
+ "version": "0.4.2",
6
6
  "license": "Elastic-2.0",
7
7
  "repository": {
8
8
  "type": "git",
@@ -36,12 +36,12 @@
36
36
  "access": "public"
37
37
  },
38
38
  "dependencies": {
39
- "@format.dev/cli": "0.4.1",
40
- "@format.dev/client": "0.4.1",
41
- "@format.dev/compile": "0.4.1",
42
- "@format.dev/fonts": "0.4.1",
43
- "@format.dev/utils": "0.4.1",
44
- "@format.dev/zip": "0.4.1",
39
+ "@format.dev/cli": "0.4.2",
40
+ "@format.dev/client": "0.4.2",
41
+ "@format.dev/compile": "0.4.2",
42
+ "@format.dev/fonts": "0.4.2",
43
+ "@format.dev/utils": "0.4.2",
44
+ "@format.dev/zip": "0.4.2",
45
45
  "@inquirer/prompts": "^7.10.1",
46
46
  "@radix-ui/react-focus-scope": "^1.1.7",
47
47
  "@radix-ui/react-slider": "^1.4.0",
@@ -64,8 +64,8 @@
64
64
  "vite": "8.3.2"
65
65
  },
66
66
  "devDependencies": {
67
- "@format.dev/react": "0.4.1",
68
- "@format.dev/vue": "0.4.1",
67
+ "@format.dev/react": "0.4.2",
68
+ "@format.dev/vue": "0.4.2",
69
69
  "@storybook/addon-a11y": "10.6.1",
70
70
  "@storybook/react-vite": "10.6.1",
71
71
  "@testing-library/react": "^16.3.0",