@format.dev/studio 0.4.0 → 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.
@@ -0,0 +1,265 @@
1
+ import*as e from"node:path";import t,{basename as n,dirname as r,isAbsolute as i,join as a,relative as o,resolve as s,sep as c}from"node:path";import l,{existsSync as u,readFileSync as d,readdirSync as f,renameSync as p,rmSync as m,writeFileSync as ee}from"node:fs";import{atlas as h}from"gradient-string";import{createServer as te,mergeConfig as ne,searchForWorkspaceRoot as re}from"vite";import ie from"open";import{RemoteAssetFetchError as ae,fetchRemote as oe,fetchRemoteIfChanged as se,readRemoteAssets as ce,scanAssetRefs as le,scanRemoteRefs as ue}from"@format.dev/zip";import{SUPPORTED_FRAMEWORKS as de}from"@format.dev/compile/shared/types/public/index";import{checkDir as fe,formatForLog as pe,getLogLevel as me,loadConfig as he,logger as g,parseLogLevelFromEnv as ge,readFile as _e,setLogLevel as ve}from"@format.dev/compile/server/utils/index";import{getSchemaPath as ye,validate as be}from"@format.dev/compile/server/utils/schema";import xe,{parseEnv as Se,stripVTControlCharacters as Ce}from"node:util";import _,{chmod as we,mkdir as v,open as Te,readFile as y,readdir as Ee,rename as De,rm as Oe,stat as ke,writeFile as b}from"node:fs/promises";import{CliError as Ae,buildDocumentPlan as je,maybeInstallDependencies as Me,maybeSetupProject as Ne,readProjectDependencies as Pe,resolveStyling as Fe,writeDocument as Ie}from"@format.dev/cli/scaffold";import{PROJECT_EXTENSIONS_ALL as Le,SERVER_WATCH_IGNORE as Re}from"@format.dev/compile/server/constants";import ze from"node:os";import{fileURLToPath as Be}from"node:url";import{DOT_FORMAT_DIR_NAME as Ve,DOT_TMP_DIR_NAME as He}from"@format.dev/compile/server/project/paths";import{DEFAULT_VARIANT as Ue,DEV_API_PORT as We,DEV_DASHBOARD_API_PORT as Ge,DEV_DASHBOARD_PORT as Ke,DEV_WEB_PORT as qe,NO_DOCUMENTS_MESSAGE as Je,VARIANT_PARAM as Ye}from"@format.dev/compile/shared/constants";import{readFile as Xe}from"@format.dev/compile/server/utils/read-file";import{CompileError as Ze}from"@format.dev/compile/server/errors";import{DEFAULT_STYLING as Qe,PAGE_LENGTH_HINT as $e,SCHEMA_DEPENDENCIES as et,STYLING_DEPENDENCIES as tt,isSchemaKind as nt,parsePageLength as rt}from"@format.dev/cli/scaffold/shared";import{findFormatConfigPath as it,loadConfig as at}from"@format.dev/compile/server/utils/load-config";import{getUserProjectDir as x}from"@format.dev/compile/server/project/user-project-dir";import{SHARED_ASSETS_OUT_DIR_NAME as ot}from"@format.dev/compile/server/compile/constants";import{compileState as S}from"@format.dev/compile/server/runtime-state";import{getDataVariants as st,getDocumentDataDir as ct,getDocumentDataFile as lt,getDocumentDataVariantPath as ut,getDocumentDataVariantPath as dt,getDocuments as ft,getDocuments as pt,getUserDocumentIndex as mt}from"@format.dev/compile/server/project/documents";import{SANDBOX_ERROR_CODE as ht}from"@format.dev/compile/server/render-worker/sandbox";import{LogLevel as gt}from"@format.dev/compile/shared/types/index";import{STUDIO_FORBID_TAGS as _t,UNSUPPORTED_TAGS as vt,getPermittedContentType as yt}from"@format.dev/utils";import{unified as bt}from"unified";import xt,{defaultSchema as St}from"rehype-sanitize";import{buildObservedSchema as Ct,parseHtmlFragment as wt,removeTags as Tt,stringifyHtmlFragment as Et,stripDangerousUrls as Dt}from"@format.dev/compile/server/compile/sanitize/shared";import{compileForStudio as Ot,getBundleOutDir as kt,getDocumentAssetsPath as At,getDocumentEntryPath as jt,renderCompiledDocument as Mt}from"@format.dev/compile/server/compile/compile";import{DOCUMENT_ASSETS_DIR_NAME as Nt,resolveDocumentAssetSources as Pt}from"@format.dev/compile/server/compile/document-assets";import*as Ft from"@format.dev/compile/server/compile/producer-release";import{createHash as C,randomBytes as It,randomUUID as Lt}from"node:crypto";import{documentFontCss as Rt,fontsDir as zt}from"@format.dev/fonts";import{isDev as Bt}from"@format.dev/compile/shared/env";import{restampDocumentEngine as Vt}from"@format.dev/compile/server/compile/finalize-document-html";import{http as Ht}from"@format.dev/compile/shared/http";import{setTimeout as Ut}from"node:timers/promises";import{createServer as Wt}from"node:http";import{FormatClient as Gt}from"@format.dev/client";import{logger as Kt}from"@format.dev/compile/server/utils/log";import w from"os";import qt from"adm-zip";import Jt from"prettier";import{stylesPreProcessor as Yt}from"@format.dev/compile/server/vite/plugins/styles-pre-processor";import{createConfig as Xt}from"@format.dev/compile/server/vite/create-config";import{shouldDecodeStyleEntities as Zt}from"@format.dev/compile/server/utils/dependencies";import{getLockstepStatus as Qt}from"@format.dev/cli/lockstep";import{assertProducersAgree as $t}from"@format.dev/compile/server/compile/producer-agreement";import{RenderWorker as en}from"@format.dev/compile/server/render-worker/index";var tn=Object.defineProperty,nn=Object.getOwnPropertyDescriptor,rn=Object.getOwnPropertyNames,an=Object.prototype.hasOwnProperty,on=(e,t)=>{let n={};for(var r in e)tn(n,r,{get:e[r],enumerable:!0});return t&&tn(n,Symbol.toStringTag,{value:`Module`}),n},sn=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=rn(t),a=0,o=i.length,s;a<o;a++)s=i[a],!an.call(e,s)&&s!==n&&tn(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=nn(t,s))||r.enumerable});return e},cn=(e,t,n)=>(sn(e,t,`default`),n&&sn(n,t,`default`)),T=class e extends Error{constructor(t){super(t),this.name=`StudioError`,Error.captureStackTrace?.(this,e)}},E=class extends T{constructor(e){super(e),this.name=`ServerUnreachableError`}},ln=class extends T{constructor(e){super(e),this.name=`SessionExpiredError`}};function D({res:e,status:t,data:n}){let r=JSON.stringify(n);e.statusCode=t,e.setHeader(`Content-Type`,`application/json; charset=utf-8`),e.setHeader(`Content-Length`,Buffer.byteLength(r)),e.end(r)}async function un(e){let t=``;for await(let n of e)t+=n.toString();if(!t)throw Error(`Request body is empty`);try{return JSON.parse(t)}catch{throw Error(`Invalid JSON body`)}}var O=class extends Error{constructor(e,t){super(t),this.status=e,this.name=`HttpError`}};function k(e,t){return t instanceof O?D({res:e,status:t.status,data:{error:t.message}}):D({res:e,status:500,data:{error:t instanceof Error?t.message:`Internal server error`}})}function dn(e){return typeof e==`string`?Ce(e):Array.isArray(e)?e.map(dn):typeof e==`object`&&e&&Object.getPrototypeOf(e)===Object.prototype?Object.fromEntries(Object.entries(e).map(([e,t])=>[e,dn(t)])):e}function A(e,t){e?.ws.send({type:`custom`,event:`studio-server-error`,data:dn(t)})}const j=`Your Studio session has expired. Reconnect to continue.`,fn=`http://localhost`,pn=`Can't connect to Format servers. Check your connection and try again.`,mn=e=>`Port ${e} is already in use. Another Studio may still be running. Stop it, or pass --port <number>.`;function hn(e){return e.backgroundPdfBuild??!0}function gn(){try{return JSON.parse(d(L,`utf-8`))}catch{return{}}}async function _n(){await Xe(L)||(await v(On,{recursive:!0}),await b(L,JSON.stringify({},null,2)))}async function M(){return await _n(),await Xe(L)}async function vn(e){await _n(),await b(L,JSON.stringify(e,null,2))}const yn={production:{name:`production`,dashboardUrl:`https://dash.format.dev`,dashboardApiUrl:`https://backend.dash.format.dev`,apiUrl:`https://api.format.dev`,webUrl:`https://format.dev`},local:{name:`local`,dashboardUrl:`http://localhost:${Ke}`,dashboardApiUrl:`http://localhost:${Ge}`,apiUrl:`http://localhost:${We}`,webUrl:`http://localhost:${qe}`,stampEngineVersion:`999.0.0`}};let N=null;function bn(e){let t=process.env.FMT_ENV?.trim();if(t)return{name:t,source:`FMT_ENV`};let n=typeof e.env==`string`?e.env:void 0;return n?{name:n,source:`settings`}:{name:`production`,source:`default`}}function xn(e){let{name:t,source:n}=bn(e),r=process.env.FMT_DASHBOARD_URL?.trim(),i=process.env.FMT_DASHBOARD_API_URL?.trim(),a=process.env.FMT_API_URL?.trim(),o=process.env.FMT_WEB_URL?.trim(),s=yn[t];if(s)return{environment:{...s,dashboardUrl:r||s.dashboardUrl,dashboardApiUrl:i||s.dashboardApiUrl,apiUrl:a||s.apiUrl,webUrl:o||s.webUrl},source:n};if(r&&i&&a&&o)return{environment:{name:t,dashboardUrl:r,dashboardApiUrl:i,apiUrl:a,webUrl:o},source:n};throw new T(`Unknown environment "${t}". Known environments are production and local; define another by setting FMT_DASHBOARD_URL, FMT_DASHBOARD_API_URL, FMT_API_URL and FMT_WEB_URL.`)}function Sn(e){return N=xn(e.settings),N.environment}function Cn(e){return e.environment.name!==`production`||e.source===`FMT_ENV`}function wn(){return N||(N=xn(gn())),N}function P(){return wn().environment}var F=on({DOT_FORMAT_DIR:()=>On,ENGINE_DIR:()=>B,ENVS_DIR:()=>kn,FORMAT_ENGINE_PATH:()=>Nn,PUBLIC_DIR:()=>En,SETTINGS_FILE:()=>L,STUDIO_APP_ALIAS:()=>Dn,_dirname:()=>I,getCredentialsFile:()=>An,getDotTempDir:()=>Mn,getEnvDir:()=>R,getPdfBuildDir:()=>z,getStateFile:()=>jn});import*as Tn from"@format.dev/compile/server/project/paths";cn(F,Tn);const I=a(r(Be(import.meta.url)),`..`),En=a(I,`public`),Dn=`/@format/studio`,On=a(ze.homedir(),Ve),L=a(On,`settings.json`),kn=a(On,`envs`),R=()=>a(kn,P().name),An=()=>a(R(),`credentials.json`),jn=()=>a(R(),`state.json`),Mn=()=>process.env.FMT_DOT_TMP_DIR?.trim()||s(I,`..`,He),z=e=>a(e,`node_modules`,`.cache`,`format-studio`,`pdf-build`),B=a(I,`engine`),Nn=e=>a(B,e,`format_engine.js`),V={diagnostics:{sanitization:null,remoteAssets:null,imageFormats:null,unsupportedElements:null},auth:{token:null,failed:!1},engine:{requested:null,resolved:null},activeDocumentAssetSources:null,skipNextConfigRestart:!1},H={armConfigRestartSkip(){V.skipNextConfigRestart=!0},consumeConfigRestartSkip(){return V.skipNextConfigRestart?(V.skipNextConfigRestart=!1,!0):!1},getToken(){if(!V.auth.token)throw new T(`Auth token not initialized`);return V.auth.token},setToken(e){V.auth.token=e},clearToken(){V.auth.token=null},isAuthFailed(){return V.auth.failed},setAuthFailed(){V.auth.failed=!0},clearAuthFailed(){V.auth.failed=!1},setEngineVersions(e){V.engine.requested=e.requested,V.engine.resolved=e.resolved},getEngineRequested(){if(!V.engine.requested)throw new T(`Requested engine not set`);return V.engine.requested},getEngineResolved(){if(!V.engine.resolved)throw new T(`Resolved engine not set`);return V.engine.resolved},setSanitizationDiagnostics(e){V.diagnostics.sanitization=e},setRemoteAssetDiagnostics(e){V.diagnostics.remoteAssets=e},setImageFormatDiagnostics(e){V.diagnostics.imageFormats=e},setUnsupportedElementDiagnostics(e){V.diagnostics.unsupportedElements=e},getDiagnostics(){return V.diagnostics},setActiveDocumentAssetSources(e){V.activeDocumentAssetSources=e},getActiveDocumentAssetSources(){return V.activeDocumentAssetSources}};function Pn(e){return async(t,n,r)=>{let i=t.url?.match(/^\/api\/documents\/([^\/]+)\/data\/([^\/]+)$/);if(!i)return r();if(H.isAuthFailed())return k(n,new O(401,j));let[,a,o]=i,s=await lt(a,o,S.getConfig());if(!s){let n=o===Ue?`Please create a default.json file in the ${a}/data directory. Refer to our documentation for more information.`:`Failed to load ${a} with variant ${o}. Please check the URL or create a ${o}.json file in the ${a}/data directory. Refer to our documentation for more information.`;return A(e,{scope:`document`,path:t.url,message:n,dismissible:!1}),r()}D({res:n,status:200,data:s})}}function Fn(){return async(e,t)=>{try{if(H.isAuthFailed())throw new O(401,j);D({res:t,status:200,data:await ft(S.getConfig())})}catch(e){k(t,e)}}}const In={react:`.tsx`,vue:`.vue`,html:`.ts`};async function Ln(e){let{wanted:t,styling:n,config:r}=e;if(!t||n===void 0||!Fe({framework:r.framework,method:n}).setupProject)return null;let i=x(),a=it(i);if(!a)return g.warn(`Skipping project setup: no Format config file found to amend.`),null;let s=o(i,(0,F.getDocumentsDir)(r));H.armConfigRestartSkip();let c=await Ne({wanted:t,styling:n,config:r,projectRoot:i,formatConfigPath:a,documentsGlobBase:s});try{let e=await at(a);S.setConfig(e.config)}catch(e){g.warn(`Failed to reload the Format config after project setup.`,e)}return c}function Rn(e){if(e==null)return;if(typeof e!=`string`)return e;let t=e.trim();if(t!==``)try{return JSON.parse(t)}catch{throw new O(400,`The data you provided isn't valid JSON.`)}}function zn(e){let t=e=>e!=null;if(!t(e.width)&&!t(e.height))return;if(!t(e.width)||!t(e.height))throw new O(400,`A page size needs both a width and a height.`);let n=t=>{let n=e[t],r=typeof n==`number`||typeof n==`string`,i=r?rt(String(n)):void 0;if(i===void 0)throw new O(400,`Invalid ${t}${r?`: "${n}"`:``}. ${$e}`);return i};return{width:n(`width`),height:n(`height`)}}function Bn(e){return async(t,n,r)=>{if(t.method!==`POST`)return r();try{if(H.isAuthFailed())throw new O(401,j);let r=await un(t);if(typeof r.name!=`string`)throw new O(400,`A document name is required.`);let i=r.styling===void 0?void 0:String(r.styling),a=S.getConfig(),o=r.schema===!0,s=typeof r.schemaKind==`string`&&nt(r.schemaKind)?r.schemaKind:void 0,c=zn(r),l=Rn(r.data),u=await je({config:a,projectRoot:x(),name:r.name,styling:i,emitSchema:o,schemaKind:s,width:c?.width,height:c?.height,data:l}),d=await Me({wanted:r.installDependencies===!0,projectRoot:x(),emitSchema:o,schemaKind:s,missingStylingDependencies:u.prerequisites.missingDependencies.map(e=>e.name)}),f=await Ln({wanted:r.installDependencies===!0,styling:i,config:a});await Ie(u);let p={name:u.documentName,variants:[Ue],extension:In[a.framework],lastModified:Date.now()},m=await Fe({framework:a.framework,method:i??Qe}).checkPrerequisites({config:S.getConfig(),projectRoot:x()});if(d.attempted&&d.ok||f!==null)try{f!==null&&e.updateInitConfig(JSON.stringify(S.getConfig())),await e.restart()}catch(e){g.warn(`Failed to restart the render worker after project setup.`,e)}D({res:n,status:201,data:{document:p,prerequisites:m,install:d,projectSetup:f}})}catch(e){if(e instanceof Ze||e instanceof Ae)return k(n,new O(400,e.message));k(n,e)}}}async function Vn(e){try{return await y(e,`utf-8`)}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function Hn(e){let{dataFilePath:t,documentName:i,variant:a,hasDataFiles:o}=e,s=`${n(r(t))}/${n(t)}`,c=await Vn(t);if(c===null)return a===Ue&&!o?{ok:!0,data:{}}:{ok:!1,title:`Missing data file`,message:`The \`${a}\` variant of \`${i}\` has no data file. Add \`${s}\`, or pick another variant.`};try{return{ok:!0,data:JSON.parse(c)}}catch(e){return{ok:!1,title:`Invalid data file`,message:`\`${s}\` in \`${i}\` isn't valid JSON.\n\n\`\`\`\n${e.message}\n\`\`\``}}}const Un=async(e,t)=>{try{return await e.ssrLoadModule(t)}catch(e){return g.error(`Failed to load module at path: ${t}`,e),null}};async function Wn(e){let t=performance.now(),n={},{dataFilePath:r,variant:i,config:a,documentName:o,server:s,renderWorker:c}=e;g.debug(`Render input args`,JSON.stringify({dataFilePath:r,config:a}));try{if(!a.framework)throw new T(`Framework not provided or invalid: ${a.framework}. Must be one of: ${de.join(`, `)}`);if(r){let e=await Hn({dataFilePath:r,documentName:o,variant:i,hasDataFiles:(await st(o,a)).length>0});if(!e.ok)return A(s,{scope:`document`,dismissible:!1,title:e.title,message:e.message}),g.error(e.message),null;n=e.data}let l=await ye(ct(o,a));if(l){let{default:e}=await Un(s,l);if(e||g.warn(`Schema File found, but no valid schema found at ${l}. Ensure your schema library follows the Standard Schema V1 spec and you are using a default export. Read more in our docs.`),e){let t=await be(e,n);if(!t.ok){let{errors:e}=t;return A(s,{scope:`document`,dismissible:!1,message:`Data validation failed for ${o}. Check your schema and data.`,details:e}),g.error(`Data validation failed for ${o}. Check your schema and data.`,e),null}n=t.data}}let{framework:u}=a,d=H.getEngineResolved();g.debug(`Delegating render to worker (framework=${u}, engine=${d})`);let f=await c.devRender({entryFilePath:e.entryFilePath,data:n,framework:u,engineVersion:d});return g.info(`Loaded "${o}" document in: ${(performance.now()-t).toFixed(2)}ms`),f.html}catch(e){let t=e?.code===ht;throw A(s,{scope:`document`,dismissible:!1,title:t?`Document restriction`:`Document rendering error`,message:t?e.message:void 0,...!t&&{stack:e.stack}}),e}}const Gn=new Set(_t.map(e=>e.toLowerCase()));function Kn(e){return Ct(St,e,!0)}function qn(e){let t={},n=wt(e);Tt(n,Gn,e=>{t[e]=(t[e]??0)+1}),Dt(n);let r=Kn(n),i=bt().use(xt,r).runSync(n),a=Et(i),o=Object.values(t).reduce((e,t)=>e+t,0),s=o===0?null:{removedElements:o,removedTags:t};return{html:String(a),diagnostics:s,tree:i}}const Jn=[`.webp`,`.avif`];function Yn(e){let t=e.toLowerCase();return Jn.some(e=>t.endsWith(e))}function Xn(e){return e.filter(Yn).sort()}const Zn=new Set(vt.map(e=>e.toLowerCase()));function Qn(e,t){if(e.type===`element`&&e.tagName){let n=e.tagName.toLowerCase();Zn.has(n)&&t.add(n)}for(let n of e.children||[])Qn(n,t);for(let n of e.content?.children||[])Qn(n,t)}function $n(e){let t=new Set;return Qn(e,t),[...t].sort()}function er(){let e=S.getConfig(),t=x(),n=e.dotEnvPath??`.env`;return i(n)?n:a(t,n)}async function tr(e,t){return or(await Promise.all([...e].sort().map(async e=>(await t(e)).map(e=>`${e.path}:${e.mtimeMs}:${e.size}`).sort().join(`
2
+ `))))}async function nr(e){let{inputs:t,directories:n,key:r,stat:i,listDir:a}=e;return{files:(await Promise.all(t.map(async e=>({path:e,stats:await i(e)})))).filter(e=>e.stats!==null).map(({path:e,stats:t})=>({path:e,mtimeMs:t.mtimeMs,size:t.size})).sort((e,t)=>e.path.localeCompare(t.path)),directories:[...n].sort(),directoriesHash:await tr(n,a),key:r}}async function rr(e){let{manifest:t,key:n,stat:r,listDir:i}=e;return t.key!==n||t.files.length===0||await tr(t.directories,i)!==t.directoriesHash?!1:(await Promise.all(t.files.map(async e=>{let t=await r(e.path);return t!==null&&t.mtimeMs===e.mtimeMs&&t.size===e.size}))).every(Boolean)}function ir(e,t){let n=o(s(t),s(e));return n===``||!n.startsWith(`..${c}`)&&n!==`..`&&!n.startsWith(`/`)}function ar(e,t){let n=s(t);return e.files.some(e=>e.path===n)||e.directories.some(e=>ir(n,e))?!0:e.files.some(e=>r(e.path)===n)}function or(e){return C(`sha256`).update(JSON.stringify(e)).digest(`hex`)}function sr(e){let t=C(`sha256`);for(let n of e)t.update(typeof n==`string`?n:Buffer.from(n)),t.update(`\0`);return t.digest(`hex`)}function cr(){let e=new Map,t=Promise.resolve(),n=e=>{let n=t.then(e,e);return t=n.catch(()=>{}),n},r=(t,r)=>{let i={running:Promise.resolve(),dirty:!1},a=(async()=>{let e=await n(r);return i.dirty?(i.dirty=!1,n(r)):e})().finally(()=>{e.get(t)===i&&e.delete(t)});return i.running=a,e.set(t,i),a};return{run(t,n){let i=e.get(t);return i?(i.dirty=!0,i.running):r(t,n)},isRunning(t){return e.has(t)},isBusy(){return e.size>0}}}function lr(e={fetchRemote:oe,fetchRemoteIfChanged:se}){let t=new Map,n=new Map;async function r(n){let r=t.get(n.url);if(!r){let r=await e.fetchRemote(n);return t.set(n.url,r),r}try{let i=await e.fetchRemoteIfChanged({...n,validators:r.validators});return i?(t.set(n.url,i),i):r}catch(e){if(!(e instanceof ae))throw e;return g.debug(`Could not reach ${n.url} to check for changes, using the copy from earlier`),r}}function i(e){let t=n.get(e.url);if(t)return t;let i=r(e).finally(()=>n.delete(e.url));return n.set(e.url,i),i}return{beginCheck(){let e=new Set;return async n=>{let r=t.get(n.url);if(r&&e.has(n.url))return r;let a=await i(n);return e.add(n.url),a}},clear(){t.clear(),n.clear()}}}const ur=(e,t)=>a(e,t,`build`),dr=(e,t)=>a(e,t,`inputs.json`),fr=(e,t)=>a(e,t,`pdfs`);async function pr(e,t){try{let n=await y(dr(e,t),`utf-8`),r=JSON.parse(n);return!Array.isArray(r.files)||!Array.isArray(r.directories)||typeof r.key!=`string`?null:r}catch{return null}}async function mr(e,t,n){let r=dr(e,t);await v(s(r,`..`),{recursive:!0}),await b(r,JSON.stringify(n),`utf-8`)}async function hr(e,t){await Oe(dr(e,t),{force:!0}).catch(()=>{})}async function gr(e,t,n){try{return await y(a(fr(e,t),`${n}.pdf`))}catch{return null}}async function _r(e,t,n,r){let i=fr(e,t);try{await v(i,{recursive:!0}),await b(a(i,`${n}.pdf`),r),await yr(i)}catch(e){g.debug(`Could not cache the generated PDF`,e)}}async function vr(e){let{pdfBuildDir:t,documentName:n,key:r,cache:i,generate:a}=e;if(i){let e=await gr(t,n,r);if(e)return{bytes:e,cached:!0}}let o=await a();return i&&await _r(t,n,r,o),{bytes:o,cached:!1}}async function yr(e){let t=(await Ee(e).catch(()=>[])).filter(e=>e.endsWith(`.pdf`));if(t.length<=5)return;let n=(await Promise.all(t.map(async t=>({name:t,mtimeMs:(await ke(a(e,t)).catch(()=>null))?.mtimeMs??0})))).sort((e,t)=>t.mtimeMs-e.mtimeMs).slice(5);await Promise.all(n.map(t=>Oe(a(e,t.name),{force:!0}).catch(()=>{})))}const U=async e=>{let t=await ke(e).catch(()=>null);return!t||!t.isFile()?null:{mtimeMs:t.mtimeMs,size:t.size}},br=async e=>{let t=await Ee(e,{recursive:!0,withFileTypes:!0}).catch(()=>[]);return(await Promise.all(t.filter(e=>e.isFile()).map(async e=>{let t=a(e.parentPath,e.name),n=await U(t);return n?{path:t,mtimeMs:n.mtimeMs,size:n.size}:null}))).filter(e=>e!==null)},W=new Map,xr=new Map,Sr=cr();let Cr=1,wr=null;const Tr=lr(),Er=new Set;function Dr(e){wr=e}function G(e,t){wr?.({documentName:e,state:t})}const Or=(e,t)=>`${e}/${t}`;function kr(e,t){return{documents:[e],remoteAssets:!0,inlineRemoteCss:!0,validateSchema:!1,clean:!1,outDir:t}}function Ar(e){return or({options:e.options,config:e.config,sdkVersion:Ft.sdkVersion,engineTarget:Ft.engineTarget})}function jr(e,t){return[(0,F.getSharedAssetsDir)(t),a((0,F.getDocumentsDir)(t),e,Nt)]}async function Mr(e){let{documentName:t,outDir:n,key:r}=e,i=await pr(z(x()),t);return!i||await U(jt(n,t))===null||!await rr({manifest:i,key:r,stat:U,listDir:br})?null:(g.debug(`Reusing the PDF bundle on disk for "${t}"`),{buildId:Cr++,outDir:n,manifest:i})}async function Nr(e){let{documentName:t,config:n,outDir:r,key:i,background:a,remoteFetch:o}=e,s=z(x()),c=kr(t,r);G(t,`building`);let l=performance.now(),{inputs:u}=await Ot(c,{useDiskCache:!1,remoteFetch:o,quiet:a}),d=er(),f=await nr({inputs:await U(d)===null?u:[...u,d],directories:jr(t,n),key:i,stat:U,listDir:br});return await mr(s,t,f),g.debug(`Built the PDF bundle for "${t}" in ${(performance.now()-l).toFixed(0)}ms`),{buildId:Cr++,outDir:r,manifest:f}}async function Pr(e){let{documentName:t,config:n,background:r=!1,remoteFetch:i=Tr.beginCheck()}=e,a=z(x()),o=ur(a,t),s=Ar({documentName:t,config:n,options:kr(t,o)}),c=W.get(t);return!Er.has(t)&&c&&c.manifest.key===s&&await rr({manifest:c.manifest,key:s,stat:U,listDir:br})?c:Sr.run(t,async()=>{let e=Er.has(t),c=W.get(t);if(!e&&c&&c.manifest.key===s&&await rr({manifest:c.manifest,key:s,stat:U,listDir:br}))return c;try{let a=(e?null:await Mr({documentName:t,config:n,outDir:o,key:s}))??await Nr({documentName:t,config:n,outDir:o,key:s,background:r,remoteFetch:i});return Er.delete(t),W.set(t,a),G(t,`ready`),a}catch(e){throw W.delete(t),await hr(a,t),G(t,`error`),e}})}async function Fr(e){let{documentName:t,variant:n,config:r,remoteFetch:i}=e,a=await Pr({documentName:t,config:r,remoteFetch:i}),o=(await U(ut(t,n,r)))?.mtimeMs??null,s=Or(t,n),c=xr.get(s);if(c&&c.buildId===a.buildId&&c.dataMtimeMs===o)return{html:c.html,outDir:a.outDir};let l=await Mt({outDir:a.outDir,documentName:t,variant:n,config:r,remoteAssets:!0,remoteFetch:i});return xr.set(s,{buildId:a.buildId,dataMtimeMs:o,html:l}),{html:l,outDir:a.outDir}}async function Ir(e){let{documentName:t,variant:n,config:r,stampHtml:i,cachePdf:a,generatePdf:o}=e,s=Tr.beginCheck();await Lr({documentName:t,config:r,remoteFetch:s});let{html:c,outDir:l}=await Fr({documentName:t,variant:n,config:r,remoteFetch:s}),u=i(c),d=await y(At(l,t)).catch(()=>void 0),f=await vr({pdfBuildDir:z(x()),documentName:t,key:sr([u,d??new Uint8Array]),cache:a,generate:()=>o({html:u,assets:d})});return f.cached&&g.debug(`Serving "${t}" (${n}) from the PDF cache`),f}async function Lr(e){let{documentName:t,config:n,remoteFetch:r}=e,i=await y(At((await Pr({documentName:t,config:n,remoteFetch:r})).outDir,t)).catch(()=>void 0);i&&(await Promise.all(ce(i).map(async e=>{let t=await r({url:e.url});return Buffer.compare(t.bytes,e.bytes)!==0}))).some(Boolean)&&(g.debug(`A remote asset used by "${t}" changed, rebuilding its PDF bundle`),Er.add(t),W.delete(t),zr(t),G(t,`stale`))}function Rr(e,t){for(let[t,n]of W)ar(n.manifest,e)&&(W.delete(t),zr(t),G(t,`stale`))}function zr(e){for(let t of xr.keys())t.startsWith(`${e}/`)&&xr.delete(t)}let K=null;function Br(e){let{documentName:t,config:n}=e;K&&clearTimeout(K),K=setTimeout(()=>{K=null,Vr({documentName:t,config:n})},1e3),K.unref?.()}async function Vr(e){let{documentName:t,config:n}=e;if(hn(await M().catch(()=>({}))))try{await Pr({documentName:t,config:n,background:!0})}catch(e){g.debug(`Background PDF build for "${t}" failed`,e)}}function Hr(){K&&(clearTimeout(K),K=null)}async function Ur(e){let{entryFilePath:t,config:n}=e;try{let e=await Pt({entryFilePath:t,config:n,outDir:kt(n),sharedAssetsOutDirName:ot});H.setActiveDocumentAssetSources(e)}catch(e){g.debug(`Asset source resolution skipped`,e)}}function Wr(){H.setSanitizationDiagnostics(null),H.setRemoteAssetDiagnostics(null),H.setImageFormatDiagnostics(null),H.setUnsupportedElementDiagnostics(null)}function Gr(e,t){return async(n,r,i)=>{let a=n.url?.match(/^\/api\/render\/([^\/]+)\/([^\/]+)$/);if(!a)return i();let[,o,s]=a;try{if(H.isAuthFailed())throw new O(401,j);let n=S.getConfig(),i=await mt({documentName:o,config:n}),a=await Wn({entryFilePath:i,dataFilePath:dt(o,s,n),variant:s,config:n,server:e,documentName:o,renderWorker:t});if(typeof a!=`string`)throw new O(500,`Render output must be HTML.`);let c=qn(a);me()>=gt.DEBUG&&g.debug(`Final HTML (post-sanitize)
3
+ `,await pe(c.html,`html`)),H.setSanitizationDiagnostics(c?.diagnostics?{documentName:o,variant:s,...c.diagnostics,timestamp:Date.now()}:null),await Ur({entryFilePath:i,config:n});let l=ue(c.html);H.setRemoteAssetDiagnostics(l.length>0?{documentName:o,variant:s,urls:l,timestamp:Date.now()}:null);let u=Xn(le(c.html));H.setImageFormatDiagnostics(u.length>0?{documentName:o,variant:s,assets:u,timestamp:Date.now()}:null);let d=$n(c.tree);H.setUnsupportedElementDiagnostics(d.length>0?{documentName:o,variant:s,tags:d,timestamp:Date.now()}:null),Br({documentName:o,config:n}),r.setHeader(`Content-Type`,`text/html`),r.setHeader(`Cache-Control`,`no-store, no-cache, must-revalidate, max-age=0`),r.setHeader(`Pragma`,`no-cache`),r.setHeader(`Expires`,`0`),r.end(c.html);return}catch(e){Wr(),e?.code===ht?g.error(e.message):g.error(`Render error`,e),k(r,e);return}}}function Kr(){return async(e,n,r)=>{let i=e.url?.replace(`/@studio`,``);if(!i){r();return}let a=t.join(En,i);try{await _.access(a);let e=await _.readFile(a),r=yt(t.extname(i).toLowerCase());if(r){n.setHeader(`Content-Type`,r),Bt()&&n.setHeader(`Cache-Control`,`no-store`),n.end(e);return}}catch{}r()}}function qr(){return(e,t)=>{let n=Rt(new URL(e.url??``,fn).searchParams.get(`mode`),{delivery:`url`,baseUrl:`/@studio/fonts`});t.setHeader(`Content-Type`,`text/css`),t.setHeader(`Cache-Control`,`no-store`),t.end(n)}}function Jr(){return async(e,n,r)=>{let i=e.url?.split(`?`)[0];if(!i){r();return}let a;try{a=decodeURIComponent(i.replace(/^\/+/,``))}catch{r();return}let o=t.resolve(zt,t.normalize(a)),s=t.resolve(zt);if(!o.startsWith(s+t.sep)){n.statusCode=403,n.end(`Forbidden`);return}let c=yt(t.extname(a).toLowerCase());if(!c){r();return}try{let e=await _.readFile(o);n.setHeader(`Content-Type`,c),n.end(e);return}catch{r()}}}async function Yr(e,n){for(let r of e){let e=t.resolve(r,n),i=t.resolve(r);if(e.startsWith(i+t.sep))try{if((await _.stat(e)).isFile())return e}catch{}}return null}const Xr=new Set([`.svg`,`.png`,`.jpg`,`.jpeg`,`.gif`,`.webp`,`.avif`,`.ico`]),Zr=new Set([`.woff`,`.woff2`,`.ttf`,`.otf`,`.eot`]);function Qr(e){return Xr.has(e)?`image`:Zr.has(e)?`font`:`other`}async function $r(e,n){let r=[],i=async(e,a)=>{let o;try{o=await _.readdir(e,{withFileTypes:!0})}catch{return}for(let s of o){let o=a?`${a}/${s.name}`:s.name;if(s.isDirectory()){await i(t.join(e,s.name),o);continue}if(!(!s.isFile()||s.name.startsWith(`.`)))try{let i=await _.stat(t.join(e,s.name));r.push({path:o,size:i.size,type:Qr(t.extname(s.name).toLowerCase()),source:n})}catch{}}};return await i(e,``),r}function ei(){return async(e,n,r)=>{if(e.method!==`GET`)return r();let i=e.url?.match(/^\/api\/documents\/([^/]+)\/assets$/);if(!i)return r();try{if(H.isAuthFailed())throw new O(401,j);let e=decodeURIComponent(i[1]),r=S.getConfig(),a=t.resolve((0,F.getDocumentsDir)(r),e,`assets`),[o,s]=await Promise.all([$r(a,`document`),$r((0,F.getSharedAssetsDir)(r),`shared`)]),c=new Set(o.map(e=>e.path));D({res:n,status:200,data:{assets:[...o,...s.filter(e=>!c.has(e.path))]}})}catch(e){k(n,e)}}}function ti(e){return async(e,n,r)=>{if(e.method!==`GET`&&e.method!==`HEAD`)return r();if(H.isAuthFailed()){n.statusCode=401,n.end(j);return}let i=new URL(e.url??``,fn).pathname;if(i.startsWith(`/.well-known/`)||i.startsWith(`/@fs/`)||i.startsWith(`/@id/`)||i.startsWith(`/@vite/`))return r();let a=yt(t.extname(i).toLowerCase());if(!a)return r();let o=(0,F.getSharedAssetsDir)(S.getConfig()),s=[H.getActiveDocumentAssetSources()?.documentAssetsDir,o].filter(e=>!!e),c;try{c=decodeURIComponent(i.slice(1))}catch{return r()}let l=await Yr(s,t.normalize(c));if(!l)return r();try{let e=await _.readFile(l);n.setHeader(`Content-Type`,a),n.setHeader(`Cache-Control`,`no-store`),n.setHeader(`Pragma`,`no-cache`),n.setHeader(`Expires`,`0`),n.end(e);return}catch{return r()}}}function ni(e){return e?.code===`EEXIST`}async function ri(e){try{let{mtimeMs:t}=await ke(e);return Date.now()-t>12e4}catch{return!0}}async function ii(e,t){let n=`${e}.lock`,i=Date.now()+1e4;for(await v(r(n),{recursive:!0,mode:448});;)try{await(await Te(n,`wx`,384)).close();break}catch(e){if(!ni(e))throw e;if(await ri(n)){await Oe(n,{force:!0});continue}if(Date.now()>i)throw new T(`Another Studio process is holding ${n}. Try again in a moment.`);await Ut(50)}try{return await t()}finally{await Oe(n,{force:!0})}}async function ai(e,t){let n=`${e}.${It(6).toString(`hex`)}.tmp`;await v(r(e),{recursive:!0,mode:448}),await b(n,t,{mode:384}),await we(n,384),await De(n,e)}async function oi(e){let t=An();await ii(t,async()=>{let n=await q(),r=t=>t.org.id===e.org.id,i=n.some(r)?n.map(t=>r(t)?e:t):[...n,e];await ai(t,JSON.stringify(i,null,2))})}async function q(){return await _e(An())||(g.debug(`Credentials file not found or empty`),[])}async function si(e){return e&&(await q()).find(t=>t.org.id===e)||null}const ci=[`format_engine.js`,`format_engine_bg.wasm`],li=`.engine-digest`,ui=/^[0-9a-f]{64}$/;function di(e){return ci.every(t=>u(a(B,e,t)))}function fi(e){let t=a(B,e,li);if(!u(t))return null;try{let e=d(t,`utf8`).trim();return ui.test(e)?e:null}catch{return null}}function pi(e,t){ee(a(e,li),`${t}\n`)}function mi(e,t){return di(e)?fi(e)===t:!1}const hi=/^[0-9a-f]{64}$/;function gi(e){let t;try{t=new URL(e).hostname}catch{return!1}return t===`localhost`||t===`::1`||t===`[::1]`||/^127(?:\.\d{1,3}){3}$/.test(t)}function _i(e,t){return e?t==null?gi(e)?{ok:!0,digest:null}:{ok:!1,reason:`no expected SHA-256 was supplied for a remote engine`}:hi.test(t)?{ok:!0,digest:t}:{ok:!1,reason:`'${t}' is not a SHA-256`}:{ok:!1,reason:`the credentials name no engine URL`}}function vi(e,t){let n=_i(e,t);if(!n.ok)throw new T(`Engine download refused: ${n.reason}. Reconnect Studio to obtain a usable one.`);return n.digest}async function J(){let e=await _e(jn());return g.debug(`State loaded`,{hasState:!!e,currentOrgId:e?.currentOrgId}),e||{}}async function yi(e){await v(R(),{recursive:!0}),await b(jn(),JSON.stringify(e,null,2))}async function bi(e){let t=await J();t.currentOrgId=e,await yi(t)}const xi=2,Si=e=>It(e).toString(`base64url`);function Ci(e){return C(`sha256`).update(e).digest(`base64url`)}function wi(){return Si(16)}function Ti(e){let{mode:t,port:n,state:r}=e,i=Si(32),a=t===`local`;return{attemptId:Si(16),mode:t,codeVerifier:i,codeChallenge:Ci(i),port:a?n:void 0,state:a?r:void 0}}function Ei(){return ze.platform()===`darwin`?ze.hostname().replace(/\.local$/,``):ze.hostname()}function Di(e){let{dashboardUrl:t,attempt:n,deviceName:r,linkedOrganizationIds:i=[]}=e,a=new URL(`/studio/link`,t);return a.searchParams.set(`v`,`2`),a.searchParams.set(`mode`,n.mode),a.searchParams.set(`attempt`,n.attemptId),a.searchParams.set(`challenge`,n.codeChallenge),a.searchParams.set(`device`,r),n.port!==void 0&&n.state&&(a.searchParams.set(`port`,String(n.port)),a.searchParams.set(`state`,n.state)),i.length>0&&a.searchParams.set(`linked`,i.join(`,`)),a.href}function Y(e){return`${Oi(process.env.npm_config_user_agent)}format ${e}`}function Oi(e=``){return e.startsWith(`pnpm/`)?`pnpm exec `:e.startsWith(`yarn/`)?`yarn `:e.startsWith(`bun/`)?`bunx `:e.startsWith(`npm/`)?`npx `:``}const ki=/^[A-Za-z0-9_-]{22}$/;var Ai=class extends T{constructor(){super(`That code is not valid. Check you copied all of it, or start again.`),this.name=`InvalidSignInCodeError`}},ji=class extends T{constructor(){super(`Format no longer accepts connections from this version of Studio. Run \`${Y(`update latest`)}\`, then connect again.`),this.name=`UnsupportedSignInProtocolError`}},Mi=class extends T{constructor(){super(`That account can no longer connect Studio to the organization it chose.`),this.name=`SignInRefusedError`}};async function Ni(e){let{apiUrl:t,attempt:n,requestedEngine:r,signal:i}=e,a=e.code.trim();if(!ki.test(a))throw new Ai;let{data:o,error:s,status:c}=await Ht(`${t}/studio/link/exchange`,{method:`POST`,body:{protocol:2,code:a,codeVerifier:n.codeVerifier,attemptId:n.attemptId,mode:n.mode,port:n.port,requestedEngine:r},signal:i});if(c===200&&o)return o;throw s===`invalid_grant`?new Ai:s===`unsupported_protocol`?new ji:c===403?new Mi:c===null||c>=500||s===`server_error`?new E(`Format did not confirm the connection, so the code may or may not have been used.`):new T(`Connection failed: ${s}`)}async function Pi(e){let{apiUrl:t,refreshToken:n}=e;await Ht(`${t}/studio/session/revoke`,{method:`POST`,body:{refreshToken:n},signal:AbortSignal.timeout(1e4)})}function Fi(e){let t=new URL(e);return t.searchParams.set(`connected`,`1`),t.toString()}const Ii=`window.close()`,Li=`'sha256-${C(`sha256`).update(Ii).digest(`base64`)}'`,Ri=`/fonts/mona-sans.woff2`,zi=a(En,`fonts/mona-sans/mona-sans.woff2`),Bi={success:`#2f9e5e`,error:`#d0472b`,warning:`#e8833f`,progress:`#0e85ff`};function Vi(){try{return d(a(En,`format-logo.svg`),`utf8`)}catch{return`<strong>Format</strong>`}}function Hi(e){return e.replace(/[&<>"']/g,e=>`&#${e.charCodeAt(0)};`)}const Ui=`
4
+ @font-face { font-family: 'Format Studio UI'; font-weight: 100 900; font-display: swap; src: url('${Ri}') format('woff2') }
5
+ :root { color-scheme: light dark; --gray-100: #f8f8f8; --gray-200: #f2f2f2; --gray-800: #434343; --gray-900: #222222; --island: #ffffff; --island-border: #e7e7e7; --muted: #757575; --fs-color-logo: #1e1e1e }
6
+ @media (prefers-color-scheme: dark) { :root { --gray-100: #181818; --gray-200: #303030; --gray-800: #d4d4d4; --gray-900: #f2f2f2; --island: #0d0d0d; --island-border: #424242; --muted: #a3a3a3; --fs-color-logo: #f2f2f2 } }
7
+ * { box-sizing: border-box }
8
+ body { margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 24px; background: var(--gray-100); color: var(--gray-900); font: 500 15px/1.5 'Format Studio UI', system-ui, sans-serif; letter-spacing: -0.1px; -webkit-font-smoothing: antialiased }
9
+ .dialog { width: min(100%, 420px); background: var(--island); border: 1px solid var(--island-border); border-radius: 16px; box-shadow: 0 24px 80px rgb(0 0 0 / 12%); overflow: hidden }
10
+ header { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 20px 20px 0 }
11
+ header svg { display: block; height: 15px; width: auto }
12
+ .content { display: flex; flex-direction: column; gap: 15px; padding: 20px }
13
+ h1 { margin: 0; font-size: 20px; font-weight: 650; letter-spacing: -0.4px; line-height: 1.2 }
14
+ p { margin: 0; color: var(--gray-800); overflow-wrap: anywhere }
15
+ .status { display: inline-flex; align-items: center; gap: 8px; padding: 2px 10px 2px 8px; border-radius: 9999px; background: var(--gray-200); font-size: 13px }
16
+ .status::before { content: ''; width: 8px; height: 8px; border-radius: 50%; background: var(--tone) }
17
+ footer { padding: 12px 20px; border-top: 1px solid var(--island-border); background: color-mix(in srgb, var(--gray-900) 3%, transparent); font-size: 13px; color: var(--muted) }
18
+ `;let Wi=null;function Gi(e){let{title:t,body:n,tone:r,status:i,closeTab:a=!1}=e,o=a?`<script>${Ii}<\/script>`:``;return Wi??(Wi=Vi()),`<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${Hi(t)}</title><style>${Ui}</style></head><body><main class="dialog" style="--tone: ${Bi[r]}"><header aria-label="Format Studio">${Wi}<span class="status">${Hi(i)}</span></header><div class="content"><h1>${Hi(t)}</h1><p>${Hi(n)}</p></div><footer>You can close this tab.</footer></main>${o}</body></html>`}var X=class extends T{constructor(e=`The request was closed without connecting an organization.`){super(e),this.name=`LinkCancelledError`}},Ki=class extends X{constructor(){super(`You've already connected all your organizations.`),this.name=`NothingToLinkError`}};const qi=`/done`,Ji={"content-type":`text/html; charset=utf-8`,"cache-control":`no-store`,"referrer-policy":`no-referrer`,"x-content-type-options":`nosniff`,"content-security-policy":`default-src 'none'; style-src 'unsafe-inline'; font-src 'self'`};async function Yi(e){if(!e)return null;let t,n=new Promise(e=>{t=setTimeout(()=>e(null),12e4).unref()});try{return await Promise.race([e.catch(()=>null),n])}finally{clearTimeout(t)}}function Xi(e,t,n){let r=n.closeTab?{...Ji,"content-security-policy":`${Ji[`content-security-policy`]}; script-src ${Li}`}:Ji;e.writeHead(t,r),e.end(Gi(n))}function Zi(e){return e.kind===`signed-in`?{title:`Studio connected`,body:`Go back to your terminal or Studio to carry on.`,tone:`success`,status:`Connected`}:{title:`Connection did not finish`,body:e.message,tone:`error`,status:`Not connected`}}async function Qi(e){let t=await y(zi).catch(()=>null);if(!t){e.writeHead(404).end();return}e.writeHead(200,{"content-type":`font/woff2`,"cache-control":`no-store`,"x-content-type-options":`nosniff`}),e.end(t)}async function $i(e){let{state:t,signal:n}=e,r=null,i=!1,a=()=>{},o=()=>{},s=()=>{},c=new Promise(e=>{s=e}),l=new Promise((e,t)=>{a=e,o=t});l.catch(()=>{});let u=Wt((e,n)=>{let l=new URL(e.url??`/`,`http://127.0.0.1`);if(e.method!==`GET`){n.writeHead(405).end();return}if(l.pathname===Ri){Qi(n);return}if(l.pathname===qi&&r){Xi(n,200,Zi(r)),s(),setTimeout(d,1e3).unref();return}if(l.pathname!==`/callback`){n.writeHead(404).end();return}let u=l.searchParams.get(`code`),f=l.searchParams.get(`state`)===t;if(f&&!u&&l.searchParams.get(`outcome`)===`all-linked`&&!i){Xi(n,200,{title:`Nothing to connect`,body:`You've already connected all your organizations.`,tone:`progress`,status:`Already connected`,closeTab:!0}),o(new Ki),setTimeout(d,1e3).unref();return}if(!(f&&u)){Xi(n,400,{title:`This request does not match`,body:`This page came from a different request. Go back to your terminal and use the link it printed.`,tone:`warning`,status:`Wrong request`});return}if(i){Xi(n,409,{title:`Already connecting`,body:`Go back to your terminal to see how it went.`,tone:`progress`,status:`In progress`});return}i=!0,a({code:u,finish:async e=>{let t=e.kind===`signed-in`?await Yi(e.returnTo):null;if(t)return n.writeHead(303,{...Ji,location:Fi(t)}),n.end(),setTimeout(d,1e3).unref(),!0;r=e,n.writeHead(303,{...Ji,location:qi}),n.end(),setTimeout(d,1e4).unref();let i=new Promise(e=>setTimeout(e,5e3).unref());return await Promise.race([c,i]),!1}})});function d(){s(),n.removeEventListener(`abort`,f),u.close(),u.closeAllConnections()}function f(){o(n.reason),d()}await new Promise((e,t)=>{u.once(`error`,t),u.listen(0,`127.0.0.1`,()=>e())});let{port:p}=u.address();return n.addEventListener(`abort`,f,{once:!0}),n.aborted&&f(),{port:p,received:l,close:d}}function ea(e){"@babel/helpers - typeof";return ea=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},ea(e)}function ta(e,t){if(ea(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(ea(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function na(e){var t=ta(e,`string`);return ea(t)==`symbol`?t:t+``}function ra(e,t,n){return(t=na(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}const ia=()=>Y(`auth start`),aa=()=>`If your browser can't reach Studio, cancel this request and run \`${ia()}\` to connect with a code.`,oa={ci:`This job needs Studio credentials.`,ssh:`Studio is running over SSH.`,container:`Studio is running in a container.`};var sa=class extends T{constructor(e,t){let n=e===`ci`?`Connect Studio outside CI, then provide the saved credentials to this job.`:`Run \`${ia()}\` to connect with a one-time code. If your browser can reach this machine, run \`${Y(`dev --auth-mode local`)}\` instead.`;super(`Studio isn't connected (AUTH_REQUIRED). ${oa[e]} ${n} Read more: ${t}/docs/studio/authentication#on-a-remote-machine`),ra(this,`code`,`AUTH_REQUIRED`),this.name=`AuthRequiredError`}};function ca(e){console.log([``,` ${xe.styleText(`bold`,`Connect Studio`)}`,``,` Open the link to choose an organization and approve the connection.`,``,` ${xe.styleText(`cyan`,e)}`,``,` ${aa()}`,``].join(`
19
+ `))}const la=[`/.dockerenv`,`/run/.containerenv`],ua=[`KUBERNETES_SERVICE_HOST`,`CODESPACES`,`REMOTE_CONTAINERS`,`GITPOD_WORKSPACE_ID`],da=[`SSH_CONNECTION`,`SSH_CLIENT`,`SSH_TTY`];function fa(e){return e!==void 0&&e!==``&&e!==`0`&&e.toLowerCase()!==`false`}function pa(e){let{env:t,authMode:n,fileExists:r=u}=e;return n===`local`?{kind:`local`}:fa(t.CI)?{kind:`auth-required`,reason:`ci`}:da.some(e=>fa(t[e]))?{kind:`auth-required`,reason:`ssh`}:fa(t.container)||ua.some(e=>fa(t[e]))||la.some(e=>r(e))?{kind:`auth-required`,reason:`container`}:{kind:`local`}}function ma(){let{dashboardUrl:e,dashboardApiUrl:t}=P();return{dashboardUrl:e,refreshUrl:`${t}/studio/refresh`}}let ha=null,ga=!1;function _a(){ha=null,ga=!1}function va(){return ga}function ya(e){return xe.inspect(e,{depth:null,colors:!0})}function ba(e){if(!e||typeof e!=`object`)return!1;let t=e;return!(typeof t.id!=`string`||typeof t.name!=`string`||`logo`in t&&t.logo!==void 0&&typeof t.logo!=`string`||typeof t.isPersonal!=`boolean`)}function xa(e){if(!e||typeof e!=`object`)return!1;let t=e;return!(typeof t.sub!=`string`||typeof t.name!=`string`||typeof t.sid!=`string`||typeof t.engine!=`string`||typeof t.plan!=`string`||typeof t.pageLimit!=`number`||`email`in t&&typeof t.email!=`string`||!ba(t.org))}function Z(e){try{let t=e.split(`.`);if(t.length!==3)throw new T(`Invalid JWT format`);let n=t[1].replace(/-/g,`+`).replace(/_/g,`/`),r=Buffer.from(n,`base64`).toString(`utf-8`),i=JSON.parse(r);if(!xa(i))throw new T(`Invalid JWT payload`);return i}catch(e){return g.warn(`Failed to decode JWT payload:`,ya(e)),null}}const Sa=`The link expired. Start again to get a new link.`;let Ca;function wa(e){Ca=e}function Ta(){let e=pa({env:process.env,authMode:Ca});if(e.kind===`auth-required`)throw new sa(e.reason,P().webUrl)}function Ea(e,t){t.open&&ie(e)}function Da(){let e=()=>{},t=()=>{},n=!1;return{studioUrl:new Promise(t=>{e=t}),browserSent:new Promise(e=>{t=e}),expectBrowser:e=>{n=!0,e.then(t,()=>t(!1))},studioListening:r=>{e(r),n||t(!1)}}}async function Oa(e){let{attempt:t,code:n,requestedEngine:r,signal:i}=e,{dashboardApiUrl:a}=P(),o=await Ni({apiUrl:a,attempt:t,code:n,requestedEngine:r,signal:i}).catch(e=>{throw i.aborted?new X:e});if(i.aborted)throw await Pi({apiUrl:a,refreshToken:o.refreshToken}),new X;try{return await Ma({authResult:o,requestedEngine:r})}catch(e){throw await Pi({apiUrl:a,refreshToken:o.refreshToken}),e}}function ka(e){return e instanceof Error?e.message:`Connection failed.`}async function Aa(e,t){Ta();let n=AbortSignal.timeout(9e5),r=t?.signal?AbortSignal.any([t.signal,n]):n,i=wi(),a=await $i({state:i,signal:r}),o=Ti({mode:`local`,port:a.port,state:i}),s=Di({dashboardUrl:P().dashboardUrl,attempt:o,deviceName:Ei(),linkedOrganizationIds:t?.linkedOrganizationIds});r.aborted||ca(s);let c=()=>{},l=new Promise(e=>{c=e});return{loginUrl:s,waitForLogin:(async()=>{let i=await a.received.catch(e=>{throw a.close(),c(!1),e instanceof Ki?e:n.aborted?new T(`${Sa} ${aa()}`):new X});try{let n=await Oa({attempt:o,code:i.code,requestedEngine:e,signal:r}),a=i.finish({kind:`signed-in`,returnTo:t?.returnTo});return a.then(c,()=>c(!1)),t?.returnTo||await a,Bt()&&g.debug(`Login success`,{org:n.org.id,engine:n.engine}),n}catch(e){throw c(!1),await i.finish({kind:`failed`,message:ka(e)}),e}})(),browserSentOn:l}}function ja(e){let{accessToken:t,requestedEngine:n,expectedOrgId:r}=e,i=Z(t);if(!i)throw new T(`Failed to decode access token`);let{engine:a,org:o}=i,s=i.exp;if(typeof s==`number`){let e=Math.floor(Date.now()/1e3);if(s<e)throw new T(`Access token is already expired (expired ${e-s}s ago, exp=${s}, now=${e})`)}if(a!==n&&!a.startsWith(`${n}-edge.`))throw new T(`Engine version mismatch (requested: ${n}, resolved: ${a})`);if(r&&o.id!==r)throw new T(`Organization ID mismatch`);return{engine:a,org:o}}async function Ma(e){let{authResult:t,requestedEngine:n,expectedOrgId:r,signInAttemptId:i}=e,{accessToken:a,engineUrl:o,engineDigest:s}=t,{engine:c,org:l}=ja({accessToken:a,requestedEngine:n,expectedOrgId:r});return await oi({org:l,...t,...i&&{signInAttemptId:i}}),{org:l,accessToken:a,engineUrl:o,engineDigest:s,engine:c}}const Na=new Map;function Pa(e,t){let n=Na.get(e);if(n)return n;let r=Fa(e,t).catch(e=>{throw e instanceof E&&(ga=!0),e}).finally(()=>Na.delete(e));return Na.set(e,r),r}async function Fa(e,t){let n=await si(e);if(!n||!n.refreshToken)throw Error(`No refresh token found for org`);let r=await Va({refreshToken:n.refreshToken,requestedEngine:t,orgId:e});return H.setToken(r.accessToken),{accessToken:r.accessToken,engineUrl:r.engineUrl,engineDigest:r.engineDigest}}async function Ia(){let e=Z(H.getToken());if(!e)throw new T(`Failed to decode current token`);let{accessToken:t}=await Pa(e.org.id,H.getEngineRequested());return t}function La(e){let t=Z(e),n=t&&t.exp;return typeof n==`number`?n:null}function Ra(e){let{accessToken:t,now:n}=e,r=La(t);return r===null||r*1e3-6e5<=n}function za({server:e}){let t=!1,n=!1,r=async()=>{try{Bt()&&g.debug(`Refreshing engine licence`);let t=Z(H.getToken());if(!t)throw Error(`Failed to decode current token`);let r=t.org.id,{accessToken:i}=await Pa(r,H.getEngineRequested()),a=H.isAuthFailed()||va();H.clearAuthFailed(),Bt()&&g.debug(`Engine licence refreshed`),e.ws.send({type:`custom`,event:`token-refreshed`,data:i}),a&&e.ws.send({type:`custom`,event:`auth-restored`}),n&&g.info(`Reconnected to Format servers.`),n=!1,_a()}catch(t){if(g.debug(`Failed to refresh licence:`,ya(t)),t instanceof E){n||g.warn(`Can't reach Format servers. Studio keeps trying.`),n=!0;return}g.warn(j),ha=H.getToken(),H.setAuthFailed(),e.ws.send({type:`custom`,event:`token-refresh-failed`,data:{message:j,details:[{message:`Token refresh failed`,error:ya(t)}]}})}},i=async()=>{let e=H.getToken(),n=e===ha,i=va()||Ra({accessToken:e,now:Date.now()});t||n||!i||(t=!0,await r().finally(()=>{t=!1}))},a=setInterval(()=>{i().catch(e=>g.debug(`Failed to check the licence:`,ya(e)))},6e4);return a.unref(),()=>clearInterval(a)}function Ba(e){let{status:t,message:n}=e;return t===null||t>=500?new E(n??`Format servers are unreachable`):new ln(n??`Refresh token rejected`)}async function Va(e){let{refreshToken:t,requestedEngine:n,orgId:r}=e;g.debug(`Refreshing credentials from stored refresh token`);let{data:i,error:a,status:o}=await Ht(ma().refreshUrl,{method:`POST`,body:{refreshToken:t,requestedEngine:n},signal:AbortSignal.timeout(6e4)});if(a||!i)throw g.debug(`Token refresh failed`),Ba({status:o,message:a});g.debug(`Refresh result: success`);let s=await si(r);return s&&await oi({...s,...i}),await Ma({authResult:i,requestedEngine:n,expectedOrgId:r})}async function Ha(e,t,n){let{loginUrl:r,waitForLogin:i,browserSentOn:a}=await Aa(e,{returnTo:n?.studioUrl});n?.expectBrowser(a),Ea(r,t);let o=await i;return await bi(o.org.id),o}function Ua(e){let t=Z(e);if(!t)return!1;let n=t.exp;return typeof n==`number`?n>Math.floor(Date.now()/1e3)+60:!1}function Wa(e,t){if(!Ua(e.accessToken))return null;let n=Z(e.accessToken);if(!n||!(n.engine===t||n.engine.startsWith(`${t}-edge.`)))return null;let r=_i(e.engineUrl,e.engineDigest);return!r.ok||!mi(n.engine,r.digest)?null:{org:e.org,accessToken:e.accessToken,engineUrl:e.engineUrl,engineDigest:e.engineDigest,engine:n.engine}}async function Ga(e,t,n){let{currentOrgId:r}=await J(),i=await si(r);if(!r||!i?.refreshToken)return await Ha(e,t,n);let a=Wa(i,e);if(a)return g.debug(`Access token still valid and engine present — skipping refresh`),a;try{return await Va({requestedEngine:e,refreshToken:i.refreshToken,orgId:r})}catch(i){if(g.debug(`Authentication error details for org ${r}:`,ya(i)),i instanceof E)throw i;return g.info(`Your last Studio session has ended. Reconnect to continue.`),await Ha(e,t,n)}}function Ka(e){let{dashboardUrl:t}=P(),n=qa();return n?`${t}/studio/open?${new URLSearchParams({organizationId:n,to:e}).toString()}`:t}function qa(){try{return Z(H.getToken())?.org.id??null}catch{return null}}function Ja(e){let{stampEngineVersion:t}=P();return t?(Kt.debug(`Stamping data-engine="${t}" for local engine`),Vt(e,t)):e}const Ya={MISSING_API_KEY:"No Format API key found. Add `FORMAT_API_KEY` to your `.env` file or environment variables.",INVALID_API_KEY:"Your Format API key is invalid or revoked. Check `FORMAT_API_KEY` in your `.env` file or environment variables.",VERIFY_SERVICE_ERROR:`Could not verify your API key right now — the verification service is temporarily unavailable. Try again shortly.`},Xa=new Set([`MISSING_API_KEY`,`INVALID_API_KEY`]);function Za(){return Ka(`api-keys`)}function Qa(e){let t=e?.detail;if(!t||typeof t!=`object`)return null;let n=t;return!n.error||typeof n.error!=`object`?null:{code:n.error.code,message:n.error.message}}function $a(e){let t=Qa(e),n=t?.code?Xa.has(t.code):!1,r=t?.code?Ya[t.code]:void 0;if(n)return`${r??t?.message??Ya.INVALID_API_KEY}\n\nYou can generate a new API key [here](${Za()}).`;if(r)return r;if(t?.message)return t.message;let i=e?.message;return typeof i==`string`&&i?i:`Something went wrong generating the PDF. Check the server logs.`}function eo(e,t){let n=e?.[t];return Array.isArray(n)?n.filter(e=>typeof e==`string`):[]}function to(e){let t=eo(e,`missing`),n=eo(e,`brokenRemote`),r=[...t,...n];if(r.length===0)return $a(e);let i=r.map(e=>`- \`${e}\``).join(`
20
+ `),a=[];return t.length>0&&a.push("Add the missing files to your `sharedAssetsDir` or the document's assets folder."),n.length>0&&a.push(`Make sure any remote assets are reachable when generating the PDF.`),`Couldn't generate PDF due to the following assets being missing:\n\n${i}\n\n${a.join(` `)}`}function no(e,t){e.statusCode=t instanceof O?t.status:500,e.setHeader(`Content-Type`,`text/html; charset=utf-8`),e.setHeader(`Cache-Control`,`no-store`),e.end(`<!doctype html><title>PDF failed</title><script>window.close()<\/script><p>The PDF couldn't be generated. Check Studio for details.</p>`)}function ro(e){return async(t,n,r)=>{let i=new URL(t.url??``,`http://localhost`),a=i.pathname.match(/^\/api\/download\/([^\/]+)\/([^\/]+)$/);if(!a)return r();let o=i.searchParams.has(`inline`),s=i.searchParams.has(`check`),c=e=>o?no(n,e):k(n,e);if(H.isAuthFailed())return c(new O(401,j));let[,l,u]=a,d=t.url??`/api/download/${l}/${u}`,f=t=>{A(e,{path:d,...t})};if(!process.env.FORMAT_API_KEY?.trim())return f({title:`PDF downloads require an API key`,message:`Create an API key [here](${Za()}) then add as \`FORMAT_API_KEY\` to your \`.env\` file. No restart needed.`}),c(new O(400,`Missing API key`));if(s){n.statusCode=204,n.end();return}let p=async e=>{let t=e.getReader(),n=[],r=0;try{for(;;){let{done:e,value:i}=await t.read();if(e)break;i&&(n.push(i),r+=i.length)}}finally{t.releaseLock()}let i=new Uint8Array(r),a=0;for(let e of n)i.set(e,a),a+=e.length;return i},m=performance.now();try{let{config:e}=await he();if(!e)throw new T(`Could not find Format config file`);let t=P().apiUrl,r=new Gt({baseUrl:t}),{bytes:i,cached:a}=await Ir({documentName:l,variant:u,config:e,stampHtml:Ja,cachePdf:!P().stampEngineVersion,generatePdf:async e=>{Kt.debug(`Sending PDF request to API with HTML`,e.html);let t=await r.pdf(e.html,e.assets?{assets:e.assets}:void 0);if(!t.isPdf)throw new O(500,`Failed to generate PDF`);if(!t.body)throw new O(500,`No PDF content received`);return p(t.body)}}),s=`${l}-${u}.pdf`,c=o?`inline`:`attachment`,d=o?`Opened`:`Downloaded`,f=a?`from cache`:`in ${(performance.now()-m).toFixed(2)}ms`;Kt.info(`${d} "${l}" (${u}) PDF ${f}`),n.statusCode=200,n.setHeader(`Content-Type`,`application/pdf`),n.setHeader(`Content-Disposition`,`${c}; filename="${s}"`),n.setHeader(`Cache-Control`,`no-store, no-cache, must-revalidate, max-age=0`),n.setHeader(`Pragma`,`no-cache`),n.setHeader(`Expires`,`0`),n.setHeader(`Content-Length`,i.length.toString()),n.setHeader(`x-format-studio-cache`,a?`hit`:`miss`),n.end(Buffer.from(i));return}catch(e){console.error(`Download error:`,e),f({title:`PDF generation error`,message:to(e)}),n.headersSent?n.end():c(e)}}}function io(){return async(e,t)=>{try{D({res:t,status:200,data:H.getDiagnostics()})}catch(e){k(t,e)}}}function ao(e,n,r){let i=t.join(e,`app`,`manifest.json`);if(!u(i))throw new T(`Manifest file not found`);try{let a=JSON.parse(d(i,`utf-8`))[r];if(!a)throw new T(`Entry '${r}' not found in manifest`);return t.join(e,n,a)}catch(e){Kt.warn(`Failed to read manifest file:`,e)}}var oo=`if (import.meta.hot) {
21
+ let hasReportedDisconnect = false
22
+
23
+ const removeEnginePages = () => {
24
+ const existing = document.querySelector('#format-pages')
25
+ existing && existing.remove()
26
+ }
27
+
28
+ const reportAuthFailure = async () => {
29
+ try {
30
+ await fetch('/api/auth/failed', {
31
+ method: 'POST',
32
+ headers: {
33
+ 'Content-Type': 'application/json'
34
+ },
35
+ body: JSON.stringify({ reason: 'set_licence_failed' })
36
+ })
37
+ } catch {
38
+ // Best-effort only.
39
+ }
40
+ }
41
+
42
+ const markAuthFailed = (notifyServer = false) => {
43
+ removeEnginePages()
44
+
45
+ if (window.engine) {
46
+ window.engine = null
47
+ }
48
+
49
+ if (notifyServer) {
50
+ reportAuthFailure()
51
+ }
52
+ }
53
+
54
+ const emitAuthError = () => {
55
+ window.dispatchEvent(
56
+ new CustomEvent('studio:error', {
57
+ detail: {
58
+ data: {
59
+ kind: 'auth',
60
+ message: 'Your Studio session has expired. Reconnect to continue.',
61
+ title: 'Authentication error',
62
+ link: {
63
+ href: '/api/auth/login',
64
+ label: 'Reconnect Studio'
65
+ }
66
+ }
67
+ }
68
+ })
69
+ )
70
+ }
71
+
72
+ import.meta.hot.on('studio-server-error', data => {
73
+ const title = data.title || 'Server error'
74
+
75
+ window.dispatchEvent(
76
+ new CustomEvent('studio:error', {
77
+ detail: { data: { ...data, title } }
78
+ })
79
+ )
80
+ })
81
+
82
+ import.meta.hot.on('vite:ws:connect', async () => {
83
+ if (!window.engine) {
84
+ return
85
+ }
86
+
87
+ try {
88
+ const res = await fetch('/api/engine-token')
89
+ const { token } = await res.json()
90
+
91
+ if (token) {
92
+ window.engine.set_licence(token)
93
+ console.log('[format] Token refreshed on WebSocket reconnect')
94
+ }
95
+ } catch {
96
+ // Best-effort — the next scheduled refresh will retry.
97
+ }
98
+ })
99
+
100
+ import.meta.hot.on('vite:ws:disconnect', () => {
101
+ if (hasReportedDisconnect) {
102
+ return
103
+ }
104
+
105
+ hasReportedDisconnect = true
106
+
107
+ window.dispatchEvent(
108
+ new CustomEvent('studio:error', {
109
+ detail: {
110
+ data: {
111
+ kind: 'server-disconnected',
112
+ message: 'Format Studio server not connected. Close this tab and restart the server.',
113
+ title: 'Server not connected'
114
+ }
115
+ }
116
+ })
117
+ )
118
+ })
119
+
120
+ // A page restored from the back/forward cache comes back with a closed
121
+ // socket and the disconnect error above already on screen. Its state is
122
+ // stale either way, so it starts again from the server.
123
+ window.addEventListener('pageshow', event => {
124
+ if (event.persisted) {
125
+ window.location.reload()
126
+ }
127
+ })
128
+
129
+ import.meta.hot.on('hmr', data => {
130
+ window.dispatchEvent(new CustomEvent('studio:hmr', { detail: data }))
131
+ })
132
+
133
+ import.meta.hot.on('pdf-build-status', data => {
134
+ window.dispatchEvent(new CustomEvent('studio:pdf-build-status', { detail: data }))
135
+ })
136
+
137
+ import.meta.hot.on('documents-changed', () => {
138
+ window.dispatchEvent(new CustomEvent('studio:documents-changed'))
139
+ })
140
+
141
+ import.meta.hot.on('token-refresh-failed', data => {
142
+ markAuthFailed()
143
+ emitAuthError()
144
+ })
145
+
146
+ import.meta.hot.on('auth-restored', () => {
147
+ window.dispatchEvent(new CustomEvent('studio:auth-restored', { detail: { restartEngine: true } }))
148
+ })
149
+
150
+ import.meta.hot.on('org-linked', data => {
151
+ window.dispatchEvent(new CustomEvent('studio:org-linked', { detail: data }))
152
+ })
153
+
154
+ import.meta.hot.on('org-link-failed', data => {
155
+ window.dispatchEvent(new CustomEvent('studio:org-link-failed', { detail: data }))
156
+ })
157
+
158
+ // The dashboard closed the request because every organisation is already
159
+ // connected. Nothing failed, so the app stops waiting without reporting anything.
160
+ import.meta.hot.on('org-link-cancelled', data => {
161
+ window.dispatchEvent(new CustomEvent('studio:org-link-cancelled', { detail: data }))
162
+ })
163
+
164
+ import.meta.hot.on('token-refreshed', jwt => {
165
+ // Reload organisation metadata even if the engine has not loaded.
166
+ window.dispatchEvent(new CustomEvent('studio:token-refreshed'))
167
+
168
+ if (!window.engine) {
169
+ return
170
+ }
171
+
172
+ try {
173
+ window.engine.set_licence(jwt)
174
+ } catch (error) {
175
+ console.error('Failed to set licence', error)
176
+ markAuthFailed(true)
177
+ emitAuthError()
178
+ }
179
+ })
180
+ }
181
+ `;function so(){try{let e=ao(I,`app`,`index.css`);if(e&&u(a(I,`public`,n(e))))return`/@studio/${n(e)}`}catch{}return`/@studio/index.css`}function co(e){return`
182
+ <!DOCTYPE html>
183
+ <html lang="en" class="html is-loading">
184
+ <head>
185
+ <meta charset="utf-8" />
186
+ <meta name="viewport" content="width=device-width,initial-scale=1,shrink-to-fit=no" />
187
+ <title>Format Studio</title>
188
+ <base href="${fn}:${e}/" />
189
+ <link rel="stylesheet" href="${so()}" />
190
+ <link rel="icon" type="image/png" href="/@studio/favicon-96x96.png" sizes="96x96" />
191
+ <link rel="icon" type="image/svg+xml" href="/@studio/favicon.svg" />
192
+ <link rel="shortcut icon" href="/@studio/favicon.ico" />
193
+ <link rel="apple-touch-icon" sizes="180x180" href="/@studio/apple-touch-icon.png" />
194
+ <meta name="apple-mobile-web-app-title" content="Format Studio" />
195
+ <link rel="manifest" href="/@studio/site.webmanifest" />
196
+ </head>
197
+ <body class="body">
198
+ <div id="loader">
199
+ <div class="spinner"></div>
200
+ </div>
201
+ <div id="studio-ui" class="studio-ui"></div>
202
+ <div id="user-root" inert></div>
203
+
204
+ <script type="module" src="${Dn}"><\/script>
205
+ <script type="module">${oo}<\/script>
206
+ </body>
207
+ </html>
208
+ `}function lo(e){return async(t,n,r,i)=>{if(!(t.url===`/`||t.url?.match(/^\/[^/.]+$/)))return r();let a=co(e),o=await i.transformIndexHtml(`/@studio`,a);n.setHeader(`Content-Type`,`text/html`),n.end(o)}}const uo=[...new Set([...Object.values(tt).flat(),...Object.values(et)])];async function fo(){try{let e=await Pe(x());return uo.filter(t=>e.has(t))}catch{return[]}}function po(){return async(e,t)=>{try{let e=H.getEngineResolved();D({res:t,status:200,data:{...await J(),engineVersion:e,enginePath:Nn(e),framework:S.getConfig().framework,projectName:n(x()),webUrl:P().webUrl,installedDependencies:await fo()}})}catch(e){k(t,e)}}}function mo(){return async(e,t,n)=>{if(e.method===`GET`){try{D({res:t,status:200,data:await M()})}catch(e){k(t,e)}return}if(e.method===`PUT`||e.method===`PATCH`){try{let n=await un(e),r={...await M(),...n};await vn(r),D({res:t,status:200,data:r})}catch(e){k(t,e)}return}n?n():D({res:t,status:405,data:{error:`Method not allowed`}})}}function ho(){return{platform:w.platform(),arch:w.arch(),release:w.release(),type:w.type(),hostname:w.hostname(),userInfo:{username:w.userInfo().username,homedir:w.userInfo().homedir}}}function go(){return async(e,t)=>{try{D({res:t,status:200,data:{os:ho()}})}catch(e){k(t,e)}}}function _o(){return async(e,t)=>{D({res:t,status:200,data:{token:H.getToken()}})}}function vo(){return(e,t,n)=>{if(e.url!==`/health`)return n();t.statusCode=200,t.end(`ok`)}}function yo(){return async(e,t)=>{try{D({res:t,status:200,data:(await q()).map(e=>({...e.org,email:Z(e.accessToken)?.email}))})}catch(e){k(t,e)}}}async function bo(e,t,n){let r=s(B,t),i=vi(e,n);if(g.debug(`Engine directory: ${B}`),g.debug(`Engine version directory: ${r}`),i!==null&&mi(t,i))return g.debug(`Engine already downloaded`),r;g.debug(`Downloading engine`);let{data:o,error:c}=await Ht(e,{responseType:`arrayBuffer`});if(c)throw g.error(`Failed to download engine. Are you connected to the internet?`),new T(`Engine download error: ${c}`);if(!o)throw new T(`Engine download error: No data returned`);let l=Buffer.from(o);if(i!==null){let e=C(`sha256`).update(l).digest(`hex`);if(e!==i)throw new T(`Engine ${t} failed verification: expected SHA-256 ${i}, downloaded bytes hash to ${e}. Nothing was installed.`)}let u=s(B,`.tmp-${t}-${process.pid}-${Date.now()}`);m(u,{recursive:!0,force:!0});try{new qt(l).extractAllTo(u,!0),xo(u);let e=f(u,{withFileTypes:!0}).filter(e=>e.isDirectory());if(e.length!==1)throw new T(`Unexpected engine archive layout: ${e.length} top-level directories`);i!==null&&pi(a(u,e[0].name),i),m(r,{recursive:!0,force:!0}),p(a(u,e[0].name),r)}finally{m(u,{recursive:!0,force:!0})}for(let e of f(B,{withFileTypes:!0}))e.isDirectory()&&e.name!==t&&!e.name.startsWith(`.`)&&m(a(B,e.name),{recursive:!0,force:!0});return r}function xo(e){for(let t of f(e,{withFileTypes:!0})){if(!t.isDirectory())continue;let n=a(e,t.name);if(t.name===`__MACOSX`){m(n,{recursive:!0,force:!0});continue}xo(n)}}var So=class extends T{constructor(e,t){super(t),this.problem=e,this.name=`ConnectionPreparationError`}};async function Co(e,t,n){let r,i;try{let a=ja({accessToken:e.accessToken,requestedEngine:t,expectedOrgId:n});r=a.engine,i=a.org}catch(e){throw new So(`mismatch`,`Format returned credentials that do not match: ${String(e)}`)}if(e.engineUrl)try{await bo(e.engineUrl,r,e.engineDigest)}catch(e){throw new So(`engine`,`The engine could not be downloaded: ${String(e)}`)}return{org:i,accessToken:e.accessToken,requestedEngine:t,engine:r}}async function wo(e){await bi(e.org.id),H.setToken(e.accessToken),H.setEngineVersions({requested:e.requestedEngine,resolved:e.engine})}const To=`Reconnect Studio to this organization. If your access has changed, contact an organization admin.`;function Eo(){return async(e,t)=>{try{let{orgId:n}=await un(e);if(!n)throw new O(400,`Select an organization to continue.`);let r=await si(n);if(!r?.refreshToken)throw new O(404,To);let i=H.getEngineRequested(),a;try{a=await Va({refreshToken:r.refreshToken,requestedEngine:i,orgId:n})}catch(e){throw e instanceof E?new O(503,`Studio couldn't connect to Format. Check your connection and try again.`):new O(401,To)}let o;try{o=await Co(a,i,n)}catch(e){throw new O(502,e instanceof So&&e.problem===`engine`?`Studio couldn't download the rendering engine. Try again.`:`Studio couldn't verify this connection. Try again.`)}await wo(o),D({res:t,status:200,data:{success:!0,org:o.org}})}catch(e){k(t,e)}}}let Q=null;function Do(e){return Q===e?(Q=null,!0):!1}function Oo(){let e=Q;Q=null,e?.controller.abort()}function ko(e){return async(t,n)=>{Oo();let r={id:Lt(),controller:new AbortController};Q=r;try{let t=H.getEngineRequested(),{loginUrl:i,waitForLogin:a}=await Aa(t,{linkedOrganizationIds:(await q()).map(e=>e.org.id),signal:r.controller.signal}),o=!1;a.then(async n=>{if(Q!==r)return;let i=await Co(n,t);Do(r)&&(o=!0,await wo(i),_a(),H.clearAuthFailed(),e.ws.send({type:`custom`,event:`org-linked`,data:i.org}))}).catch(t=>{if(!(!o&&!Do(r))){if(t instanceof X){g.debug(`Nothing left to link`);let n=t instanceof Ki?t.message:void 0;e.ws.send({type:`custom`,event:`org-link-cancelled`,data:{attemptId:r.id,message:n}});return}g.error(`Link organization failed`,t),e.ws.send({type:`custom`,event:`org-link-failed`,data:{message:jo(t),attemptId:r.id}})}}),D({res:n,status:200,data:{loginUrl:i,attemptId:r.id}})}catch(e){Do(r),k(n,e)}}}function Ao(){return async(e,t)=>{try{let{attemptId:n}=await un(e),r=Q!==null&&Q.id===n;r&&Oo(),D({res:t,status:200,data:{cancelled:r}})}catch(e){k(t,e)}}}function jo(e){return e instanceof Error&&e.message===Sa?Sa:e instanceof So?`Organization connected, but Studio couldn't finish switching. Your current organization is still active. Try switching again.`:`Couldn't connect the organization. Try again.`}function Mo(e){return async(t,n,r)=>t.method===`GET`&&t.url===`/api/organizations`?yo()(t,n):t.method===`POST`&&t.url===`/api/organizations/switch`?Eo()(t,n):t.method===`POST`&&t.url===`/api/organizations/add`?ko(e)(t,n):t.method===`POST`&&t.url===`/api/organizations/add/cancel`?Ao()(t,n):r()}let $=null;async function No(e){if($)return $;let t=H.getEngineRequested(),n=(await J()).currentOrgId,r=e.resolvedUrls?.local[0]??null;return $=await Aa(t,{returnTo:Promise.resolve(r)}),$.waitForLogin.then(async r=>{let i=H.isAuthFailed(),a=await Co(r,t);if(await wo(a),_a(),H.clearAuthFailed(),a.org.id!==n){e.ws.send({type:`custom`,event:`org-linked`,data:a.org});return}e.ws.send({type:`custom`,event:`token-refreshed`,data:a.accessToken}),i&&e.ws.send({type:`custom`,event:`auth-restored`})}).catch(e=>{g.error(`Login flow failed`,e)}).finally(()=>{$=null}),$}function Po(e){return async(t,n,r)=>{let i=t.url?.split(`?`)[0];if(t.method!==`GET`||i!==`/api/auth/login`)return r();try{let t=await No(e);n.statusCode=302,n.setHeader(`Location`,t.loginUrl),n.end()}catch(e){k(n,e)}}}function Fo(){return async(e,t,n)=>{let r=e.url?.split(`?`)[0];if(e.method!==`POST`||r!==`/api/auth/failed`)return n();try{Number(e.headers[`content-length`]??0)>0&&await un(e),H.setAuthFailed(),D({res:t,status:200,data:{ok:!0}})}catch(e){k(t,e)}}}function Io(e){return async(t,n,r)=>{let i=t.url?.split(`?`)[0];if(t.method!==`POST`||i!==`/api/auth/refresh`)return r();try{let t=await Ia(),r=H.isAuthFailed()||va();_a(),H.clearAuthFailed(),e.ws.send({type:`custom`,event:`token-refreshed`,data:t}),r&&e.ws.send({type:`custom`,event:`auth-restored`}),D({res:n,status:200,data:{token:t}})}catch(e){g.error(`On-demand token refresh failed`,e);let t=e instanceof E;D({res:n,status:t?503:401,data:{error:t?pn:j}})}}}function Lo(e,t){return{name:`format-studio-middleware`,apply:`serve`,configureServer(n){n.middlewares.use(vo()),n.middlewares.use(Po(n)),n.middlewares.use(Fo()),n.middlewares.use(Io(n)),n.middlewares.use(`/@studio/fonts.css`,qr()),n.middlewares.use(`/@studio/fonts`,Jr()),n.middlewares.use(`/@studio`,Kr()),n.middlewares.use(ti(n)),n.middlewares.use(`/api/engine-token`,_o()),n.middlewares.use(Pn(n)),n.middlewares.use(ei()),n.middlewares.use(`/api/documents`,Bn(t)),n.middlewares.use(`/api/documents`,Fn()),n.middlewares.use(Gr(n,t)),n.middlewares.use(`/api/diagnostics`,io()),n.middlewares.use(`/api/state`,po()),n.middlewares.use(`/api/settings`,mo()),n.middlewares.use(`/api/system`,go()),n.middlewares.use(Mo(n)),n.middlewares.use(ro(n)),n.middlewares.use((t,r,i)=>lo(e)(t,r,i,n))}}}const Ro={parser:`typescript`},zo=e=>`${`/`.replace(/\/$/,``)}/${e.replace(/^\.?\//,``)}`,Bo=`
209
+ export const loadDocumentData = async (documentName, variant = 'default') => {
210
+ try {
211
+ const baseUrl = window.location.origin
212
+ const response = await fetch(\`\${baseUrl}/api/documents/\${documentName}/data/\${variant}\`)
213
+
214
+ if (!response.ok) {
215
+ throw new Error(\`Failed to load data for \${documentName}/\${variant}\`)
216
+ }
217
+
218
+ return await response.json()
219
+ } catch (error) {
220
+ console.error('Failed to load document data:', error)
221
+ return {}
222
+ }
223
+ }
224
+ `;function Vo(){return`const globs = import.meta.glob("${zo(`*/index.${`{${Le.join(`,`).replace(/\./g,``)}}`}`)}");`}function Ho(e){return e.map(e=>{let t=zo(`./${e.name}/index${e.extension}`);return`"${e.name}": () => {
225
+ const loader = globs["${t}"];
226
+
227
+ if (!loader) {
228
+ throw new Error("Component not found for ${t}");
229
+ }
230
+
231
+ return loader();
232
+ }`}).join(`,
233
+ `)}async function Uo(e){if(e.length===0)throw new T(Je);let t=`
234
+ import React from "react"
235
+ import ReactDOM from "react-dom/client"
236
+
237
+ ${Bo}
238
+
239
+ ${Vo()}
240
+
241
+ export const components = {
242
+ ${Ho(e)}
243
+ }
244
+ `;return await Jt.format(t,Ro)}async function Wo(e){if(e.length===0)throw new T(Je);let t=`
245
+ import { createApp } from "vue"
246
+
247
+ ${Bo}
248
+
249
+ ${Vo()}
250
+
251
+ export const components = {
252
+ ${Ho(e)}
253
+ }
254
+ `;return await Jt.format(t,Ro)}async function Go(e){if(e.length===0)throw new T(Je);let t=`
255
+ import { Eta } from 'eta'
256
+ const eta = new Eta({ varName: 'data' })
257
+
258
+ ${Bo}
259
+
260
+ ${Vo()}
261
+
262
+ export const components = {
263
+ ${Ho(e)}
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.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"./Oh4HdbFz.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
- `){a(()=>n(i.trim()));return}if(t===``||t===`\b`){i=i.slice(0,-1);continue}i+=t}};t.write(`Paste the code from Dash 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(`
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"./Oh4HdbFz.js";export{e as serve};
1
+ import{t as e}from"./DJhtSY7k.js";export{e as serve};