@coreframe/preview 0.1.15 → 0.1.17

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.
@@ -1 +1 @@
1
- import{preparePreviewAccess as e}from"./cloudflare-access.js";import{keyring as t}from"./keyring.js";import{mkdir as n,mkdtemp as r,readFile as i,rm as a,writeFile as o}from"node:fs/promises";import{tmpdir as s}from"node:os";import{join as c}from"node:path";import l from"nano-spawn";const u=process.platform===`win32`?`cloudflared.exe`:`cloudflared`,d=`dev.coreframe.preview.cloudflare.account`,f=`dev.coreframe.preview.cloudflare.tunnel`;async function p({appOrigin:t,access:n,accessEnv:i,config:l,cwd:u,env:d=process.env,now:f=()=>new Date().toISOString(),request:p,run:g=M}){let _=await m({config:l,env:d,now:f,run:g}),y=await h({account:_,config:l,cwd:u,env:d,now:f,run:g});l.dns===`managed`&&await v({account:_,config:l,cwd:u,env:d,run:g,tunnel:y});let b=n?await e({accountId:y.accountTag,appOrigin:t??`https://${l.hostname}/`,config:n,env:i??d,hostname:l.hostname,request:p,tunnel:{name:y.name,profile:y.profile}}):void 0,x=await r(c(s(),`coreframe-preview-tunnel-`)),S=c(x,`tunnel.json`),C=!1;try{await o(S,`${JSON.stringify(y.credentials)}\n`,{mode:384})}catch(e){throw await a(x,{force:!0,recursive:!0}),e}return{access:b,credentialsFile:S,async dispose(){C||(C=!0,await a(x,{force:!0,recursive:!0}))},tunnel:{name:y.name,profile:y.profile,tunnelId:y.tunnelId}}}async function m({config:e,env:n,now:r,run:i}){let a=await t.get(d,e.profile);if(a)return w(a,e.profile);console.log([`Cloudflare authentication is required for preview tunnel "${e.profile}/${e.name}".`,"Coreframe will run `cloudflared tunnel login` now.",`Follow the browser prompt or URL, sign in to Cloudflare, and authorize the zone for ${e.hostname}.`,`Coreframe will store the resulting credentials in your operating system credential store.`].join(` `));let o=await y({env:n,run:i}),s={createdAt:r(),profile:e.profile,originCertificate:o,version:1};return await t.set(d,e.profile,JSON.stringify(s)),s}async function h({account:e,config:n,cwd:r,env:i,now:a,run:o}){let s=j(n.profile,n.name),c=await t.get(f,s);if(c)return T(c,n);let l=(await g({account:e,cwd:r,env:i,run:o})).find(e=>e.name===n.name);if(l)throw Error(`Cloudflare tunnel "${n.name}" already exists as ${l.id}, but Coreframe has no Keychain credentials for it. Coreframe will not adopt an existing tunnel; choose a new preview.tunnel.name.`);console.log(`Creating Cloudflare tunnel ${JSON.stringify(`${n.profile}/${n.name}`)}...`);let u=await _({account:e,config:n,cwd:r,env:i,run:o}),p={accountTag:u.AccountTag,createdAt:a(),credentials:u,hostname:n.hostname,name:n.name,profile:n.profile,tunnelId:u.TunnelID,version:1};return await t.set(f,s,JSON.stringify(p)),await t.set(d,n.profile,JSON.stringify({...e,lastAccountTag:p.accountTag,lastTunnelId:p.tunnelId,lastTunnelName:p.name})),p}async function g({account:e,cwd:t,env:n,run:r}){return b(e,async e=>O((await r([`tunnel`,`--origincert`,e,`list`,`--output`,`json`],{cwd:t,env:n})).stdout))}async function _({account:e,config:t,cwd:n,env:r,run:a}){return x(`coreframe-cloudflared-create-`,async o=>{let s=c(o,`cert.pem`),l=c(o,`tunnel.json`);return await S(s,e.originCertificate),await a([`tunnel`,`--origincert`,s,`create`,`--credentials-file`,l,t.name],{cwd:n,env:r}),E(D(await i(l,`utf8`),`tunnel credentials`))})}async function v({account:e,config:t,cwd:n,env:r,run:i,tunnel:a}){await b(e,async e=>{await i([`tunnel`,`--origincert`,e,`route`,`dns`,`--overwrite-dns`,a.tunnelId,t.hostname],{cwd:n,env:r})})}async function y({env:e,run:t}){let o=await r(c(s(),`coreframe-cloudflared-login-`)),l=c(o,`.cloudflared`);await n(l,{mode:448});try{await t([`tunnel`,`login`],{cwd:o,env:C(e,o),stdio:`inherit`});let n=await i(c(l,`cert.pem`),`utf8`);if(!n.trim())throw Error(`Cloudflare login completed without producing an origin certificate.`);return n}finally{await a(o,{force:!0,recursive:!0})}}async function b(e,t){return x(`coreframe-cloudflared-command-`,async n=>{let r=c(n,`cert.pem`);return await S(r,e.originCertificate),t(r)})}async function x(e,t){let n=await r(c(s(),e));try{return await t(n)}finally{await a(n,{force:!0,recursive:!0})}}async function S(e,t){await o(e,t,{mode:384})}function C(e,t){let n={...e};return delete n.TUNNEL_ORIGIN_CERT,{...n,HOME:t,USERPROFILE:t}}function w(e,t){let n;try{n=JSON.parse(e)}catch{throw A(`account`,t)}if(!k(n)||n.version!==1||n.profile!==t||typeof n.createdAt!=`string`||typeof n.originCertificate!=`string`||!n.originCertificate.trim())throw A(`account`,t);return n}function T(e,t){let n;try{n=JSON.parse(e)}catch{throw A(`tunnel`,`${t.profile}/${t.name}`)}if(!k(n)||n.version!==1||n.profile!==t.profile||n.name!==t.name||n.hostname!==t.hostname||typeof n.accountTag!=`string`||typeof n.createdAt!=`string`||typeof n.tunnelId!=`string`)throw A(`tunnel`,`${t.profile}/${t.name}`);let r=E(n.credentials);if(r.TunnelID!==n.tunnelId||r.AccountTag!==n.accountTag)throw A(`tunnel`,`${t.profile}/${t.name}`);return{...n,credentials:r}}function E(e){if(!k(e)||typeof e.AccountTag!=`string`||!e.AccountTag.trim()||typeof e.TunnelID!=`string`||!e.TunnelID.trim()||typeof e.TunnelSecret!=`string`||!e.TunnelSecret.trim()||e.Endpoint!==void 0&&typeof e.Endpoint!=`string`)throw Error(`Cloudflare returned invalid tunnel credentials.`);return{AccountTag:e.AccountTag,Endpoint:e.Endpoint,TunnelID:e.TunnelID,TunnelSecret:e.TunnelSecret}}function D(e,t){try{return JSON.parse(e)}catch{throw Error(`Cloudflare returned invalid ${t}.`)}}function O(e){let t;try{t=JSON.parse(e)}catch{throw Error(`Cloudflare returned an invalid tunnel list.`)}if(t===null)return[];let n=Array.isArray(t)?t:k(t)&&Array.isArray(t.result)?t.result:void 0;if(!n)throw Error(`Cloudflare returned an invalid tunnel list.`);return n.map(e=>{if(!k(e)||typeof e.id!=`string`||!e.id.trim()||typeof e.name!=`string`||!e.name.trim())throw Error(`Cloudflare returned an invalid tunnel list.`);return{id:e.id,name:e.name}})}function k(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function A(e,t){return Error(`The Coreframe Cloudflare ${e} credential for "${t}" is invalid. Clear the matching Coreframe Keychain entry and run coreframe preview again.`)}function j(e,t){return`${e}/${t}`}async function M(e,{cwd:t,env:n,stdio:r=`pipe`}){let i=await l(u,e,{cwd:t,env:n,stdio:r});return{stderr:i.stderr,stdout:i.stdout}}export{p as preparePreviewTunnel};
1
+ import{preparePreviewAccess as e}from"./cloudflare-access.js";import{keyring as t}from"./keyring.js";import{mkdir as n,mkdtemp as r,readFile as i,rm as a,writeFile as o}from"node:fs/promises";import{tmpdir as s}from"node:os";import{join as c}from"node:path";import l from"nano-spawn";const u=process.platform===`win32`?`cloudflared.exe`:`cloudflared`,d=`dev.coreframe.preview.cloudflare.account`,f=`dev.coreframe.preview.cloudflare.tunnel`;async function p({appOrigin:t,access:n,accessEnv:i,config:l,cwd:u,env:d=process.env,now:f=()=>new Date().toISOString(),request:p,run:g=M}){let _=new URL(t).hostname,y={...l,hostname:_},b=await m({config:y,env:d,now:f,run:g}),x=await h({account:b,config:y,cwd:u,env:d,now:f,run:g});y.dns===`managed`&&await v({account:b,config:y,cwd:u,env:d,run:g,tunnel:x});let S=n?await e({accountId:x.accountTag,appOrigin:t,config:n,env:i??d,hostname:_,request:p,tunnel:{name:x.name,profile:x.profile}}):void 0,C=await r(c(s(),`coreframe-preview-tunnel-`)),w=c(C,`tunnel.json`),T=!1;try{await o(w,`${JSON.stringify(x.credentials)}\n`,{mode:384})}catch(e){throw await a(C,{force:!0,recursive:!0}),e}return{access:S,credentialsFile:w,async dispose(){T||(T=!0,await a(C,{force:!0,recursive:!0}))},tunnel:{name:x.name,profile:x.profile,tunnelId:x.tunnelId}}}async function m({config:e,env:n,now:r,run:i}){let a=await t.get(d,e.profile);if(a)return w(a,e.profile);console.log([`Cloudflare authentication is required for preview tunnel "${e.profile}/${e.name}".`,"Coreframe will run `cloudflared tunnel login` now.",`Follow the browser prompt or URL, sign in to Cloudflare, and authorize the zone for ${e.hostname}.`,`Coreframe will store the resulting credentials in your operating system credential store.`].join(` `));let o=await y({env:n,run:i}),s={createdAt:r(),profile:e.profile,originCertificate:o,version:1};return await t.set(d,e.profile,JSON.stringify(s)),s}async function h({account:e,config:n,cwd:r,env:i,now:a,run:o}){let s=j(n.profile,n.name),c=await t.get(f,s);if(c)return T(c,n);let l=(await g({account:e,cwd:r,env:i,run:o})).find(e=>e.name===n.name);if(l)throw Error(`Cloudflare tunnel "${n.name}" already exists as ${l.id}, but Coreframe has no Keychain credentials for it. Coreframe will not adopt an existing tunnel; choose a new preview.tunnel.name.`);console.log(`Creating Cloudflare tunnel ${JSON.stringify(`${n.profile}/${n.name}`)}...`);let u=await _({account:e,config:n,cwd:r,env:i,run:o}),p={accountTag:u.AccountTag,createdAt:a(),credentials:u,hostname:n.hostname,name:n.name,profile:n.profile,tunnelId:u.TunnelID,version:1};return await t.set(f,s,JSON.stringify(p)),await t.set(d,n.profile,JSON.stringify({...e,lastAccountTag:p.accountTag,lastTunnelId:p.tunnelId,lastTunnelName:p.name})),p}async function g({account:e,cwd:t,env:n,run:r}){return b(e,async e=>O((await r([`tunnel`,`--origincert`,e,`list`,`--output`,`json`],{cwd:t,env:n})).stdout))}async function _({account:e,config:t,cwd:n,env:r,run:a}){return x(`coreframe-cloudflared-create-`,async o=>{let s=c(o,`cert.pem`),l=c(o,`tunnel.json`);return await S(s,e.originCertificate),await a([`tunnel`,`--origincert`,s,`create`,`--credentials-file`,l,t.name],{cwd:n,env:r}),E(D(await i(l,`utf8`),`tunnel credentials`))})}async function v({account:e,config:t,cwd:n,env:r,run:i,tunnel:a}){await b(e,async e=>{await i([`tunnel`,`--origincert`,e,`route`,`dns`,`--overwrite-dns`,a.tunnelId,t.hostname],{cwd:n,env:r})})}async function y({env:e,run:t}){let o=await r(c(s(),`coreframe-cloudflared-login-`)),l=c(o,`.cloudflared`);await n(l,{mode:448});try{await t([`tunnel`,`login`],{cwd:o,env:C(e,o),stdio:`inherit`});let n=await i(c(l,`cert.pem`),`utf8`);if(!n.trim())throw Error(`Cloudflare login completed without producing an origin certificate.`);return n}finally{await a(o,{force:!0,recursive:!0})}}async function b(e,t){return x(`coreframe-cloudflared-command-`,async n=>{let r=c(n,`cert.pem`);return await S(r,e.originCertificate),t(r)})}async function x(e,t){let n=await r(c(s(),e));try{return await t(n)}finally{await a(n,{force:!0,recursive:!0})}}async function S(e,t){await o(e,t,{mode:384})}function C(e,t){let n={...e};return delete n.TUNNEL_ORIGIN_CERT,{...n,HOME:t,USERPROFILE:t}}function w(e,t){let n;try{n=JSON.parse(e)}catch{throw A(`account`,t)}if(!k(n)||n.version!==1||n.profile!==t||typeof n.createdAt!=`string`||typeof n.originCertificate!=`string`||!n.originCertificate.trim())throw A(`account`,t);return n}function T(e,t){let n;try{n=JSON.parse(e)}catch{throw A(`tunnel`,`${t.profile}/${t.name}`)}if(!k(n)||n.version!==1||n.profile!==t.profile||n.name!==t.name||n.hostname!==t.hostname||typeof n.accountTag!=`string`||typeof n.createdAt!=`string`||typeof n.tunnelId!=`string`)throw A(`tunnel`,`${t.profile}/${t.name}`);let r=E(n.credentials);if(r.TunnelID!==n.tunnelId||r.AccountTag!==n.accountTag)throw A(`tunnel`,`${t.profile}/${t.name}`);return{...n,credentials:r}}function E(e){if(!k(e)||typeof e.AccountTag!=`string`||!e.AccountTag.trim()||typeof e.TunnelID!=`string`||!e.TunnelID.trim()||typeof e.TunnelSecret!=`string`||!e.TunnelSecret.trim()||e.Endpoint!==void 0&&typeof e.Endpoint!=`string`)throw Error(`Cloudflare returned invalid tunnel credentials.`);return{AccountTag:e.AccountTag,Endpoint:e.Endpoint,TunnelID:e.TunnelID,TunnelSecret:e.TunnelSecret}}function D(e,t){try{return JSON.parse(e)}catch{throw Error(`Cloudflare returned invalid ${t}.`)}}function O(e){let t;try{t=JSON.parse(e)}catch{throw Error(`Cloudflare returned an invalid tunnel list.`)}if(t===null)return[];let n=Array.isArray(t)?t:k(t)&&Array.isArray(t.result)?t.result:void 0;if(!n)throw Error(`Cloudflare returned an invalid tunnel list.`);return n.map(e=>{if(!k(e)||typeof e.id!=`string`||!e.id.trim()||typeof e.name!=`string`||!e.name.trim())throw Error(`Cloudflare returned an invalid tunnel list.`);return{id:e.id,name:e.name}})}function k(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function A(e,t){return Error(`The Coreframe Cloudflare ${e} credential for "${t}" is invalid. Clear the matching Coreframe Keychain entry and run coreframe preview again.`)}function j(e,t){return`${e}/${t}`}async function M(e,{cwd:t,env:n,stdio:r=`pipe`}){let i=await l(u,e,{cwd:t,env:n,stdio:r});return{stderr:i.stderr,stdout:i.stdout}}export{p as preparePreviewTunnel};
package/dist/index.d.ts CHANGED
@@ -31,6 +31,7 @@ type PreviewApi = {
31
31
  build(): Promise<void>;
32
32
  report(label: string, value?: string): void;
33
33
  run(command: string, args?: string[]): Promise<void>;
34
+ runScript(name: string, args?: string[]): Promise<void>;
34
35
  serve(): Promise<void>;
35
36
  stageArtifact(options: PreviewArtifactOptions): Promise<string>;
36
37
  url(pathname?: string): string;
package/dist/index.js CHANGED
@@ -1 +1 @@
1
- import{preparePreviewTunnel as e}from"./cloudflare.js";import{copyFile as t,glob as n,mkdir as r,mkdtemp as i,open as a,readFile as o,stat as s}from"node:fs/promises";import{tmpdir as c}from"node:os";import l from"node:path";import u from"node:process";import{parseEnv as d}from"node:util";import{coreframeLocalWorkerVariables as f,readProjectConfig as p}from"@coreframe/config";import{migrateLocalDb as m,runProjectSeed as h,startProjectPostgres as g,startProjectTurso as _}from"@coreframe/db";import v from"nano-spawn";import{supervise as y}from"procband";const b=[`DATABASE_URL`,`PGDATABASE`,`PGHOST`,`PGPASSWORD`,`PGPORT`,`PGUSER`,`TURSO_AUTH_TOKEN`,`TURSO_DATABASE_URL`],x=[`POSTHOG_`,`VITE_POSTHOG_`,`VITE_GA_`],S=[`CI`,`COLORTERM`,`COMSPEC`,`ComSpec`,`FORCE_COLOR`,`HOME`,`LANG`,`NODE_EXTRA_CA_CERTS`,`NODE_OPTIONS`,`NO_COLOR`,`PATH`,`PATHEXT`,`PNPM_HOME`,`SHELL`,`SSL_CERT_DIR`,`SSL_CERT_FILE`,`SYSTEMROOT`,`SystemRoot`,`TEMP`,`TERM`,`TMP`,`TMPDIR`,`USERPROFILE`],C=u.platform===`win32`?`pnpm.cmd`:`pnpm`;async function w({cwd:e=u.cwd(),env:t=u.env,host:n,port:r},i={}){let a=await p({cwd:e}),o=T(a,{host:n,port:r}),s=await M(e),c=D({appOrigin:o.appOrigin,config:a,env:t,environmentFiles:s}),l=o.access?{CLOUDFLARE_API_TOKEN:t.CLOUDFLARE_API_TOKEN??s.CLOUDFLARE_API_TOKEN}:void 0,d=j({config:a,cwd:e,env:c}),f=await k();console.log(`Preview output: ${f.path}`);let m,h,g=new Set,_=!1,v,y=()=>{if(!_){_=!0;for(let e of g)e.nodeChildProcess.then(e=>e.kill(`SIGTERM`)).catch(()=>void 0);m?.kill(`SIGTERM`),d.stop()}},b=[`SIGINT`,`SIGTERM`].map(e=>{let t=()=>{v??=e,y()};return u.on(e,t),{handler:t,signal:e}});try{await d.start();let n=O({config:o,cwd:e,database:d,env:c,accessEnvironment:l,output:f,processEnvironment:t,commands:g,onServe(e){m=e.server,h=e.disposeTunnel},isStopping:()=>_,onStop:y});await n.database.migrate(),await n.database.seed(),await i.beforeBuild?.(n),await n.build(),await i.afterBuild?.(n),await n.serve()}finally{let e=[...g];y();try{await d.dispose()}finally{try{await Promise.allSettled([...e,m?.wait()].filter(Boolean)),await h?.()}finally{try{await f.close()}finally{for(let{handler:e,signal:t}of b)u.off(t,e)}}v&&(u.exitCode??=v===`SIGINT`?130:143)}}}function T(e,t={}){let n=e.preview??{},r=t.host??n.host??`127.0.0.1`,i=t.port??n.port??4173,a=n.strictPort??!0,o=n.appOrigin;if(!Number.isInteger(i)||i<1||i>65535)throw Error(`Preview port must be an integer between 1 and 65535.`);if(!r.trim())throw Error(`Preview host must not be empty.`);return o&&I(o),n.tunnel&&P(n.tunnel,o,a),n.access&&F(n.access,n.tunnel,o),{access:n.access,appOrigin:o,host:r,port:i,strictPort:a,tunnel:n.tunnel}}async function E({appOrigin:e,config:t,cwd:n,env:r}){return D({appOrigin:e,config:t,env:r,environmentFiles:await M(n)})}function D({appOrigin:e,config:t,env:n,environmentFiles:r}){let i=Object.keys(t.worker?.environment??{}).filter(e=>!x.some(t=>e.startsWith(t))),a=new Set([...f,...b,...i]),o={},s=new Set([...Object.keys(n),...Object.keys(r)].filter(e=>e.startsWith(`VITE_`)&&!x.some(t=>e.startsWith(t))));for(let e of[...S,...Object.keys(n).filter(e=>e.startsWith(`LC_`))])n[e]!==void 0&&(o[e]=n[e]);for(let e of a){let t=n[e]??r[e];t!==void 0&&(o[e]=t)}for(let e of s){let t=n[e]??r[e];t!==void 0&&(o[e]=t)}return e!==void 0&&(a.add(`APP_ORIGIN`),o.APP_ORIGIN=e),o.CLOUDFLARE_ENV=`preview`,o.COREFRAME_ENV=`preview`,o.COREFRAME_PLATFORM=`web`,o.COREFRAME_PREVIEW_WORKER_VARIABLES=JSON.stringify([...a].filter(e=>!x.some(t=>e.startsWith(t)))),o}function O({accessEnvironment:i,config:a,cwd:o,database:c,env:d,output:f,processEnvironment:p,commands:m,onServe:h,isStopping:g,onStop:_}){let b=!1,x={cwd:o,database:c,env:d,host:a.host,origin:a.appOrigin??R(a.host,a.port),port:a.port,async build(){await x.run(C,[`run`,`build`,`--mode`,`preview`])},report(e,t){console.log(t===void 0?e:`${e}: ${t}`)},async run(e,t=[]){let n=v(e,t,{cwd:o,env:d,stdin:`inherit`,stderr:f.fd,stdout:f.fd});m.add(n);try{await n}finally{m.delete(n)}},async serve(){if(b)throw Error(`Preview serving can only be started once.`);b=!0;let t,n,r;try{if(t=a.tunnel?await e({appOrigin:a.appOrigin,access:a.access,accessEnv:i,config:a.tunnel,cwd:o,env:p}):void 0,g()){await t?.dispose();return}n=y({name:`preview`,command:C,args:[`exec`,`vite`,`preview`,`--mode`,`preview`,`--outDir`,`dist/client`,`--host`,a.host,`--port`,String(a.port),...a.strictPort?[`--strictPort`]:[]],cwd:o,env:d,prefix:!1,stdin:u.stdin}),r=t?v(u.platform===`win32`?`cloudflared.exe`:`cloudflared`,[`tunnel`,`run`,`--url`,`http://${B(z(a.host))}:${a.port}`,`--credentials-file`,t.credentialsFile,t.tunnel.tunnelId],{cwd:o,env:d,stdin:`ignore`,stderr:f.fd,stdout:f.fd}):void 0,r&&m.add(r)}catch(e){throw n?.kill(`SIGTERM`),await n?.wait(),await t?.dispose(),e}try{h({disposeTunnel:t?.dispose,server:n}),x.report(`Preview`,x.url(`/`)),t&&(x.report(`Cloudflare tunnel`,`${t.tunnel.name} (${t.tunnel.tunnelId})`),t.access&&x.report(`Cloudflare Access bypass`,t.access.policyName)),await Promise.race(r?[n.expectSuccess(),r]:[n.expectSuccess()])}catch(e){if(g()||_(),await t?.dispose(),g())return;throw e}},async stageArtifact({label:e,pathname:i,source:a}){let c=A(o,i),u=[];for await(let e of n(a,{cwd:o}))(await s(l.resolve(o,e))).isFile()&&u.push(e);if(u.length===0)throw Error(`Preview artifact source ${JSON.stringify(a)} did not match a file.`);if(u.length>1)throw Error(`Preview artifact source ${JSON.stringify(a)} matched multiple files: ${u.sort().join(`, `)}.`);await r(l.dirname(c),{recursive:!0}),await t(l.resolve(o,u[0]),c);let d=x.url(i);return x.report(e,d),d},url(e=`/`){return new URL(e,`${x.origin.replace(/\/$/u,``)}/`).toString()}};return x}async function k(){let e=await i(l.join(c(),`coreframe-preview-`)),t=l.join(e,`preview.log`),n=await a(t,`wx`,384);return{close:()=>n.close(),fd:n.fd,path:t}}function A(e,t){let n=new URL(t,`https://coreframe.invalid`);if(!t.startsWith(`/`)||t===`/`||t.includes(`\\`)||t.includes(`?`)||t.includes(`#`)||n.origin!==`https://coreframe.invalid`||n.pathname!==t||l.posix.normalize(t)!==t)throw Error(`Preview artifact pathname must be a normalized absolute URL path.`);return l.resolve(e,`dist/client`,`.${t}`)}function j({config:e,cwd:t,env:n}){let r=e.database?.dialect??`postgres`,i,a,o,s,c=!1,l=n,u=()=>a?(s??=a[Symbol.asyncDispose](),s):Promise.resolve(),d=()=>{c||(c=!0,u().catch(()=>void 0))};return{dialect:r,get env(){return l},async migrate(){await m({config:e,cwd:t,env:l})},async seed(){await h(`default`,{cwd:t,env:l,seedEntryPoint:e.database?.seed})},async start(){if(r===`sqlite`){a=await _({config:e,cwd:t,env:l,useSupervisorLease:!0}),Object.assign(l,a.env);return}i=await g({config:e,cwd:t,env:l,failIfRunning:!0,postgresOutput:`on-error`,useSupervisorLease:!0}),Object.assign(l,i.env)},stop:d,async dispose(){o??=(async()=>{d(),await Promise.allSettled([i?.[Symbol.asyncDispose](),u()]),i=void 0,a=void 0})(),await o}}}async function M(e){let t={};for(let n of[`.env`,`.env.local`,`.env.preview`,`.env.preview.local`]){let r=await N(l.resolve(e,n));r&&(t={...t,...r})}let n=await N(l.resolve(e,`.dev.vars`));n&&(t={...t,...n});let r=await N(l.resolve(e,`.dev.vars.preview`));return r&&(t={...t,...r}),t}async function N(e){try{return Object.fromEntries(Object.entries(d(await o(e,`utf8`))).filter(e=>e[1]!==void 0))}catch(e){if(e.code===`ENOENT`)return;throw e}}function P(e,t,n){if(!t)throw Error(`preview.appOrigin is required when preview.tunnel is configured.`);if(!n)throw Error(`preview.strictPort must be true when preview.tunnel is configured.`);let r=[`credentialsFile`,`tokenEnv`,`tokenFile`],i=e,a=r.find(e=>e in i);if(a)throw Error(`preview.tunnel.${a} is no longer supported. Coreframe preview now provisions Cloudflare credentials through the operating system credential store.`);if(!e.name.trim())throw Error(`preview.tunnel.name must not be empty.`);if(!/^[a-z0-9][a-z0-9._-]*$/u.test(e.profile))throw Error(`preview.tunnel.profile must start with a lowercase letter or number and contain only lowercase letters, numbers, dots, underscores, or hyphens.`);if(e.dns!==`managed`&&e.dns!==`external`)throw Error(`preview.tunnel.dns must be either "managed" or "external".`);let o=L(e.hostname);if(new URL(t).hostname!==o)throw Error(`preview.appOrigin hostname must match preview.tunnel.hostname.`)}function F(e,t,n){if(!t)throw Error(`preview.tunnel is required when preview.access is configured.`);if(!n)throw Error(`preview.appOrigin is required when preview.access is configured.`);if(e.applicationId!==void 0&&!e.applicationId.trim())throw Error(`preview.access.applicationId must not be empty.`);if(!e.bypass||typeof e.bypass!=`object`)throw Error(`preview.access.bypass must be configured.`);if(e.bypass.policyName!==void 0&&!e.bypass.policyName.trim())throw Error(`preview.access.bypass.policyName must not be empty.`);let{ips:r}=e.bypass;if(typeof r!=`string`&&!Array.isArray(r)&&typeof r!=`function`)throw Error(`preview.access.bypass.ips must be an IP, an array of IPs, or a resolver.`);if(Array.isArray(r)&&r.length===0)throw Error(`preview.access.bypass.ips must contain at least one IP.`)}function I(e){let t;try{t=new URL(e)}catch{throw Error(`preview.appOrigin must be an exact HTTPS browser origin.`)}if(t.protocol!==`https:`||t.origin!==e||t.pathname!==`/`||t.search||t.hash||t.username||t.password)throw Error(`preview.appOrigin must be an exact HTTPS browser origin.`);return t}function L(e){let t;try{t=new URL(`https://${e}`)}catch{throw Error(`preview.tunnel.hostname must be an exact hostname.`)}if(t.hostname!==e||t.origin!==`https://${e}`)throw Error(`preview.tunnel.hostname must be an exact hostname.`);return t.hostname}function R(e,t){return`http://${B(z(e))}:${t}`}function z(e){return e===`0.0.0.0`||e===`::`?`127.0.0.1`:e}function B(e){return e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e}export{E as createPreviewEnvironment,T as resolvePreviewConfig,w as runPreview};
1
+ import{preparePreviewTunnel as e}from"./cloudflare.js";import{chmod as t,copyFile as n,glob as r,mkdir as i,mkdtemp as a,open as o,readFile as s,stat as c,writeFile as l}from"node:fs/promises";import{tmpdir as u}from"node:os";import d from"node:path";import f from"node:process";import{parseEnv as p}from"node:util";import{coreframeLocalWorkerVariables as m,readProjectConfig as h}from"@coreframe/config";import{migrateLocalDb as g,runProjectSeed as _,startProjectPostgres as v,startProjectTurso as y}from"@coreframe/db";import b from"nano-spawn";import{supervise as x}from"procband";const S=[`DATABASE_URL`,`PGDATABASE`,`PGHOST`,`PGPASSWORD`,`PGPORT`,`PGUSER`,`TURSO_AUTH_TOKEN`,`TURSO_DATABASE_URL`],C=[`POSTHOG_`,`VITE_POSTHOG_`,`VITE_GA_`],w=[`CI`,`COLORTERM`,`COMSPEC`,`ComSpec`,`FORCE_COLOR`,`HOME`,`LANG`,`NODE_EXTRA_CA_CERTS`,`NODE_OPTIONS`,`NO_COLOR`,`PATH`,`PATHEXT`,`PNPM_HOME`,`SHELL`,`SSL_CERT_DIR`,`SSL_CERT_FILE`,`SYSTEMROOT`,`SystemRoot`,`TEMP`,`TERM`,`TMP`,`TMPDIR`,`USERPROFILE`],T=f.platform===`win32`?`pnpm.cmd`:`pnpm`;async function E({cwd:e=f.cwd(),env:t=f.env,host:n,port:r},i={}){let a=await h({cwd:e}),o=D(a,{host:n,port:r}),s=await I(e),c=k({appOrigin:o.appOrigin,config:a,env:t,environmentFiles:s}),l=o.access?{CLOUDFLARE_API_TOKEN:t.CLOUDFLARE_API_TOKEN??s.CLOUDFLARE_API_TOKEN}:void 0,u=F({config:a,cwd:e,env:c}),d=await N();console.log(`Preview output: ${d.path}`);let p,m,g=new Set,_=!1,v,y=()=>{if(!_){_=!0;for(let e of g)e.nodeChildProcess.then(e=>e.kill(`SIGTERM`)).catch(()=>void 0);p?.kill(`SIGTERM`),u.stop()}},b=[`SIGINT`,`SIGTERM`].map(e=>{let t=()=>{v??=e,y()};return f.on(e,t),{handler:t,signal:e}});try{await u.start();let n=A({config:o,cwd:e,database:u,env:c,accessEnvironment:l,output:d,processEnvironment:t,commands:g,onServe(e){p=e.server,m=e.disposeTunnel},isStopping:()=>_,onStop:y});await n.database.migrate(),await n.database.seed(),await i.beforeBuild?.(n),await n.build(),await i.afterBuild?.(n),await j(e,c),await n.serve()}finally{let e=[...g];y();try{await u.dispose()}finally{try{await Promise.allSettled([...e,p?.wait()].filter(Boolean)),await m?.()}finally{try{await d.close()}finally{for(let{handler:e,signal:t}of b)f.off(t,e)}}v&&(f.exitCode??=v===`SIGINT`?130:143)}}}function D(e,t={}){let n=e.preview??{},r=t.host??n.host??`127.0.0.1`,i=t.port??n.port??4173,a=n.strictPort??!0,o=n.appOrigin;if(!Number.isInteger(i)||i<1||i>65535)throw Error(`Preview port must be an integer between 1 and 65535.`);if(!r.trim())throw Error(`Preview host must not be empty.`);return o&&B(o),n.tunnel&&R(n.tunnel,o,a),n.access&&z(n.access,n.tunnel,o),{access:n.access,appOrigin:o,host:r,port:i,strictPort:a,tunnel:n.tunnel}}async function O({appOrigin:e,config:t,cwd:n,env:r}){return k({appOrigin:e,config:t,env:r,environmentFiles:await I(n)})}function k({appOrigin:e,config:t,env:n,environmentFiles:r}){let i=Object.keys(t.worker?.environment??{}).filter(e=>!C.some(t=>e.startsWith(t))),a=new Set([...m,...S,...i]),o={},s=new Set([...Object.keys(n),...Object.keys(r)].filter(e=>e.startsWith(`VITE_`)&&!C.some(t=>e.startsWith(t))));for(let e of[...w,...Object.keys(n).filter(e=>e.startsWith(`LC_`))])n[e]!==void 0&&(o[e]=n[e]);for(let e of a){let t=n[e]??r[e];t!==void 0&&(o[e]=t)}for(let e of s){let t=n[e]??r[e];t!==void 0&&(o[e]=t)}return e!==void 0&&(a.add(`APP_ORIGIN`),o.APP_ORIGIN=e),o.CLOUDFLARE_ENV=`preview`,o.COREFRAME_ENV=`preview`,o.COREFRAME_PLATFORM=`web`,o.COREFRAME_PREVIEW_WORKER_VARIABLES=JSON.stringify([...a].filter(e=>!C.some(t=>e.startsWith(t)))),o}function A({accessEnvironment:t,config:a,cwd:o,database:s,env:l,output:u,processEnvironment:p,commands:m,onServe:h,isStopping:g,onStop:_}){let v=!1,y={cwd:o,database:s,env:l,host:a.host,origin:a.appOrigin??V(a.host,a.port),port:a.port,async build(){await y.runScript(`build`,[`--mode`,`preview`])},report(e,t){console.log(t===void 0?e:`${e}: ${t}`)},async run(e,t=[]){let n=b(e,t,{cwd:o,env:l,stdin:`inherit`,stderr:u.fd,stdout:u.fd});m.add(n);try{await n}finally{m.delete(n)}},async runScript(e,t=[]){await y.run(T,[`run`,e,...t])},async serve(){if(v)throw Error(`Preview serving can only be started once.`);v=!0;let n,r,i;try{if(n=a.tunnel?await e({appOrigin:a.appOrigin,access:a.access,accessEnv:t,config:a.tunnel,cwd:o,env:p}):void 0,g()){await n?.dispose();return}r=x({name:`preview`,command:T,args:[`exec`,`vite`,`preview`,`--mode`,`preview`,`--outDir`,`dist/client`,`--host`,a.host,`--port`,String(a.port),...a.strictPort?[`--strictPort`]:[]],cwd:o,env:l,prefix:!1,stdin:f.stdin}),i=n?b(f.platform===`win32`?`cloudflared.exe`:`cloudflared`,[`tunnel`,`run`,`--url`,`http://${U(H(a.host))}:${a.port}`,`--credentials-file`,n.credentialsFile,n.tunnel.tunnelId],{cwd:o,env:l,stdin:`ignore`,stderr:u.fd,stdout:u.fd}):void 0,i&&m.add(i)}catch(e){throw r?.kill(`SIGTERM`),await r?.wait(),await n?.dispose(),e}try{h({disposeTunnel:n?.dispose,server:r}),y.report(`Preview`,y.url(`/`)),n&&(y.report(`Cloudflare tunnel`,`${n.tunnel.name} (${n.tunnel.tunnelId})`),n.access&&y.report(`Cloudflare Access bypass`,n.access.policyName)),await Promise.race(i?[r.expectSuccess(),i]:[r.expectSuccess()])}catch(e){if(g()||_(),await n?.dispose(),g())return;throw e}},async stageArtifact({label:e,pathname:t,source:a}){let s=P(o,t),l=[];for await(let e of r(a,{cwd:o}))(await c(d.resolve(o,e))).isFile()&&l.push(e);if(l.length===0)throw Error(`Preview artifact source ${JSON.stringify(a)} did not match a file.`);if(l.length>1)throw Error(`Preview artifact source ${JSON.stringify(a)} matched multiple files: ${l.sort().join(`, `)}.`);await i(d.dirname(s),{recursive:!0}),await n(d.resolve(o,l[0]),s);let u=y.url(t);return y.report(e,u),u},url(e=`/`){return new URL(e,`${y.origin.replace(/\/$/u,``)}/`).toString()}};return y}async function j(e,n){for await(let i of r(`dist/**/.dev.vars`,{cwd:e})){let r=d.resolve(e,i);if((await c(r)).isFile()){let e=p(await s(r,`utf8`));for(let t of S){let r=n[t];r===void 0?delete e[t]:e[t]=r}await l(r,Object.entries(e).flatMap(([e,t])=>t===void 0?[]:[`${e}=${M(t)}\n`]).join(``)),await t(r,384)}}}function M(e){if(!e.includes(`'`))return`'${e}'`;if(!e.includes("`"))return`\`${e}\``;if(!e.includes(`"`)&&!/[\\\n\r]/u.test(e))return`"${e}"`;throw Error(`Unable to serialize preview Worker variable to .dev.vars.`)}async function N(){let e=await a(d.join(u(),`coreframe-preview-`)),t=d.join(e,`preview.log`),n=await o(t,`wx`,384);return{close:()=>n.close(),fd:n.fd,path:t}}function P(e,t){let n=new URL(t,`https://coreframe.invalid`);if(!t.startsWith(`/`)||t===`/`||t.includes(`\\`)||t.includes(`?`)||t.includes(`#`)||n.origin!==`https://coreframe.invalid`||n.pathname!==t||d.posix.normalize(t)!==t)throw Error(`Preview artifact pathname must be a normalized absolute URL path.`);return d.resolve(e,`dist/client`,`.${t}`)}function F({config:e,cwd:t,env:n}){let r=e.database?.dialect??`postgres`,i,a,o,s,c=!1,l=n,u=()=>a?(s??=a[Symbol.asyncDispose](),s):Promise.resolve(),d=()=>{c||(c=!0,u().catch(()=>void 0))};return{dialect:r,get env(){return l},async migrate(){await g({config:e,cwd:t,env:l})},async seed(){await _(`default`,{cwd:t,env:l,seedEntryPoint:e.database?.seed})},async start(){if(r===`sqlite`){a=await y({config:e,cwd:t,env:l,useSupervisorLease:!0}),Object.assign(l,a.env);return}i=await v({config:e,cwd:t,env:l,failIfRunning:!0,postgresOutput:`on-error`,useSupervisorLease:!0}),Object.assign(l,i.env)},stop:d,async dispose(){o??=(async()=>{d(),await Promise.allSettled([i?.[Symbol.asyncDispose](),u()]),i=void 0,a=void 0})(),await o}}}async function I(e){let t={};for(let n of[`.env`,`.env.local`,`.env.preview`,`.env.preview.local`]){let r=await L(d.resolve(e,n));r&&(t={...t,...r})}let n=await L(d.resolve(e,`.dev.vars`));n&&(t={...t,...n});let r=await L(d.resolve(e,`.dev.vars.preview`));return r&&(t={...t,...r}),t}async function L(e){try{return Object.fromEntries(Object.entries(p(await s(e,`utf8`))).filter(e=>e[1]!==void 0))}catch(e){if(e.code===`ENOENT`)return;throw e}}function R(e,t,n){if(!t)throw Error(`preview.appOrigin is required when preview.tunnel is configured.`);if(!n)throw Error(`preview.strictPort must be true when preview.tunnel is configured.`);let r=[`credentialsFile`,`tokenEnv`,`tokenFile`],i=e,a=r.find(e=>e in i);if(a)throw Error(`preview.tunnel.${a} is no longer supported. Coreframe preview now provisions Cloudflare credentials through the operating system credential store.`);if(!e.name.trim())throw Error(`preview.tunnel.name must not be empty.`);if(!/^[a-z0-9][a-z0-9._-]*$/u.test(e.profile))throw Error(`preview.tunnel.profile must start with a lowercase letter or number and contain only lowercase letters, numbers, dots, underscores, or hyphens.`);if(e.dns!==`managed`&&e.dns!==`external`)throw Error(`preview.tunnel.dns must be either "managed" or "external".`)}function z(e,t,n){if(!t)throw Error(`preview.tunnel is required when preview.access is configured.`);if(!n)throw Error(`preview.appOrigin is required when preview.access is configured.`);if(e.applicationId!==void 0&&!e.applicationId.trim())throw Error(`preview.access.applicationId must not be empty.`);if(!e.bypass||typeof e.bypass!=`object`)throw Error(`preview.access.bypass must be configured.`);if(e.bypass.policyName!==void 0&&!e.bypass.policyName.trim())throw Error(`preview.access.bypass.policyName must not be empty.`);let{ips:r}=e.bypass;if(typeof r!=`string`&&!Array.isArray(r)&&typeof r!=`function`)throw Error(`preview.access.bypass.ips must be an IP, an array of IPs, or a resolver.`);if(Array.isArray(r)&&r.length===0)throw Error(`preview.access.bypass.ips must contain at least one IP.`)}function B(e){let t;try{t=new URL(e)}catch{throw Error(`preview.appOrigin must be an exact HTTPS browser origin.`)}if(t.protocol!==`https:`||t.origin!==e||t.pathname!==`/`||t.search||t.hash||t.username||t.password)throw Error(`preview.appOrigin must be an exact HTTPS browser origin.`);return t}function V(e,t){return`http://${U(H(e))}:${t}`}function H(e){return e===`0.0.0.0`||e===`::`?`127.0.0.1`:e}function U(e){return e.includes(`:`)&&!e.startsWith(`[`)?`[${e}]`:e}export{O as createPreviewEnvironment,D as resolvePreviewConfig,E as runPreview};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@coreframe/preview",
3
- "version": "0.1.15",
3
+ "version": "0.1.17",
4
4
  "description": "Production-like local preview lifecycle utilities for Coreframe apps",
5
5
  "repository": {
6
6
  "type": "git",
@@ -21,8 +21,8 @@
21
21
  "@napi-rs/keyring": "1.3.0",
22
22
  "nano-spawn": "^2.1.0",
23
23
  "procband": "^0.3.8",
24
- "@coreframe/config": "^0.1.12",
25
- "@coreframe/db": "^0.1.16"
24
+ "@coreframe/config": "^0.1.13",
25
+ "@coreframe/db": "^0.1.17"
26
26
  },
27
27
  "devDependencies": {
28
28
  "@types/node": "^26.1.0",