@stacksjs/actions 0.70.353 → 0.70.355
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.
- package/dist/dev/dashboard.js +2 -2
- package/dist/helpers/utils.d.ts +1 -0
- package/dist/helpers/utils.js +1 -1
- package/dist/release.js +1 -1
- package/package.json +18 -18
package/dist/dev/dashboard.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import process from"node:process";import{randomUUID}from"node:crypto";import{existsSync,renameSync,unlinkSync,writeFileSync}from"node:fs";import{bold,cyan,dim,green}from"@stacksjs/cli";import{projectPath,storagePath}from"@stacksjs/path";import{seedCsrfPageResponse,validateDevCsrfRequest}from"./csrf";import{shouldDelegateDashboardRequest}from"./dashboard-request-routing";import{buildDashboardUrl,buildManifest,discoverModels,findAvailablePort,waitForServer}from"./dashboard-utils";const verboseIdx=process.argv.indexOf("--verbose"),verbose=verboseIdx!==-1&&process.argv[verboseIdx+1]!=="false",startTime=Bun.nanoseconds(),originalConsoleLog=console.log,originalConsoleWarn=console.warn,bufferedLogs=[];console.log=(...args)=>{bufferedLogs.push(args.map(String).join(" "))};console.warn=(...args)=>{bufferedLogs.push(args.map(String).join(" "))};const dashboardPath=storagePath("framework/defaults/views/dashboard"),userDashboardPath=projectPath("resources/views/dashboard"),preferredPort=Number(process.env.PORT_ADMIN)||3002,dashboardPort=await findAvailablePort(preferredPort),appUrl=process.env.APP_URL||"",hasCustomDomain=appUrl!==""&&appUrl!=="localhost"&&!appUrl.includes("localhost:"),domain=hasCustomDomain?appUrl.replace(/^https?:\/\//,""):null,dashboardDomain=domain?`dashboard.${domain}`:null,sslBasePath=`${process.env.HOME}/.stacks/ssl`;function restoreConsole(){console.log=originalConsoleLog;console.warn=(...args)=>{const msg=args.map(String).join(" ");if(msg.includes("[STX] DOM API violation")||msg.includes("unsafe expression"))return;originalConsoleWarn(...args)}}async function startStxServer(){await import("@stacksjs/orm");let serve;try{const localServe=process.env.BUN_PLUGIN_STX_SRC||`${process.env.HOME}/Code/Tools/stx/packages/bun-plugin/src/serve.ts`;if(!await Bun.file(localServe).exists())throw Error("local bun-plugin-stx source not found");serve=(await import(localServe)).serve}catch{try{serve=(await import("bun-plugin-stx/serve")).serve}catch{serve=(await import(projectPath("pantry/bun-plugin-stx/dist/serve.js"))).serve}}let stxModule;try{const localStx=process.env.STX_SRC||`${process.env.HOME}/Code/Tools/stx/packages/stx/src/index.ts`;if(await Bun.file(localStx).exists()){const localCrosswind=`${process.env.HOME}/Code/Tools/crosswind/packages/crosswind/src/index.ts`;if(!process.env.CROSSWIND_SRC&&await Bun.file(localCrosswind).exists())process.env.CROSSWIND_SRC=localCrosswind;stxModule=await import(localStx)}}catch{}if(stxModule&&verbose)console.log("[Dashboard] Using local stx checkout");if(!stxModule)try{const vendoredStx=projectPath("pantry/@stacksjs/stx/dist/index.js");if(await Bun.file(vendoredStx).exists())stxModule=await import(vendoredStx)}catch{}const{listConfigFiles,readConfig,updateConfigKeys}=await import(storagePath("framework/defaults/resources/functions/dashboard/config-io.ts")),localTsChartsRoot=process.env.TS_CHARTS_SRC||`${process.env.HOME}/Code/Libraries/ts-charts`,dependencyBundles=new Map;function resolveTsChartsSource(packageName){return[`${localTsChartsRoot}/packages/${packageName}/src/index.ts`,projectPath(`node_modules/@ts-charts/${packageName}/src/index.ts`),projectPath(`pantry/@ts-charts/${packageName}/src/index.ts`)].find(existsSync)||null}const tsChartsEntry=[`${localTsChartsRoot}/packages/ts-charts/src/index.ts`,projectPath("node_modules/ts-charts/src/index.ts"),projectPath("pantry/ts-charts/src/index.ts")].find(existsSync);async function buildDashboardDependency(entrypoint){const cached=dependencyBundles.get(entrypoint);if(cached)return cached;const build=(async()=>{const result=await Bun.build({entrypoints:[entrypoint],target:"browser",format:"esm",minify:!0,plugins:[{name:"dashboard-ts-charts-source",setup(builder){builder.onResolve({filter:/^@ts-charts\/[a-z0-9-]+$/},(args)=>{const packageName=args.path.slice(11),source=resolveTsChartsSource(packageName);if(source)return{path:source};return null})}}]});if(!result.success){const errors=result.logs.filter((log)=>log.level==="error").map((log)=>log.message).join(`
|
|
2
|
-
`);throw Error(errors||`Failed to bundle ${entrypoint}`)}const output=result.outputs.find((file)=>file.path.endsWith(".js"));if(!output)throw Error(`No JavaScript output produced for ${entrypoint}`);return output.text()})();dependencyBundles.set(entrypoint,build);return build}function browserDependencyRoute(entrypoint){return async()=>{try{return new Response(await buildDashboardDependency(entrypoint),{headers:{"content-type":"text/javascript; charset=utf-8","cache-control":"no-cache"}})}catch(error){dependencyBundles.delete(entrypoint);return new Response(`throw new Error(${JSON.stringify(error.message)})`,{status:500,headers:{"content-type":"text/javascript; charset=utf-8"}})}}}let dashboardIconCss=null;async function buildDashboardIconCss(){const{generateCrosswindCSS}=await import("@stacksjs/stx"),dirs=[dashboardPath,userDashboardPath,storagePath("framework/defaults/resources/components/Dashboard")],icons=new Set;for(const dir of dirs){if(!existsSync(dir))continue;const glob=new Bun.Glob("**/*.{stx,ts}");for await(const file of glob.scan({cwd:dir,absolute:!0})){const text=await Bun.file(file).text();for(const match of text.matchAll(/\bi-[a-z][a-z0-9]*(?:-[a-z0-9]+)+/g))icons.add(match[0])}}if(icons.size===0)return"";return generateCrosswindCSS(`<div class="${[...icons].join(" ")}"></div>`,process.cwd())}const configRoutes={"/__deps/charts.js":browserDependencyRoute(storagePath("framework/core/charts/src/index.ts")),"/__deps/ts-charts.js":browserDependencyRoute(tsChartsEntry||`${localTsChartsRoot}/packages/ts-charts/src/index.ts`),"/__deps/dashboard-icons.css":async()=>{if(!dashboardIconCss)dashboardIconCss=buildDashboardIconCss();return new Response(await dashboardIconCss,{headers:{"content-type":"text/css; charset=utf-8","cache-control":"no-cache"}})},"/api/config/list":async()=>{try{return Response.json({ok:!0,files:listConfigFiles()})}catch(e){return Response.json({ok:!1,error:e?.message},{status:500})}},"/api/config/read":async(req)=>{try{const name=new URL(req.url).searchParams.get("name")||"";if(!/^[\w-]+$/.test(name))return Response.json({ok:!1,error:"Invalid config name"},{status:400});const result=await readConfig(name);if(!result)return Response.json({ok:!1,error:"Not found"},{status:404});return Response.json({ok:!0,name,fields:result.fields})}catch(e){return Response.json({ok:!1,error:e?.message},{status:500})}},"/api/config/source":async(req)=>{try{const name=new URL(req.url).searchParams.get("name")||"";if(!/^[\w-]+$/.test(name))return Response.json({ok:!1,error:"Invalid config name"},{status:400});const result=await readConfig(name);if(!result)return Response.json({ok:!1,error:"Not found"},{status:404});return new Response(result.source,{headers:{"content-type":"text/plain; charset=utf-8"}})}catch(e){return Response.json({ok:!1,error:e?.message},{status:500})}},"/api/config/update":async(req)=>{if(req.method!=="POST")return Response.json({ok:!1,error:"Method not allowed"},{status:405});try{await validateDevCsrfRequest(req);const body=await req.json(),file=body.file?.replace(/\.ts$/,"");if(!file||!/^[\w-]+$/.test(file))return Response.json({ok:!1,error:"Invalid file"},{status:400});const updates=[];if(Array.isArray(body.updates))for(const u of body.updates){const k=u.key??u.path;if(typeof k==="string")updates.push({key:k,value:u.value})}else if(body.key)updates.push({key:body.key,value:body.value});if(updates.length===0)return Response.json({ok:!1,error:"No updates supplied"},{status:400});const invalid=updates.find((update)=>!/^[A-Za-z_$][\w$]*$/.test(update.key)||typeof update.value!=="string"&&typeof update.value!=="number"&&typeof update.value!=="boolean"||typeof update.value==="number"&&!Number.isFinite(update.value));if(invalid)return Response.json({ok:!1,error:`Invalid value for configuration key "${invalid.key}"`},{status:400});const typedUpdates=updates;try{await updateConfigKeys(file,typedUpdates)}catch(err){const error=err?.message||"Configuration values could not be updated.",results=typedUpdates.map((update)=>({key:update.key,ok:!1,error}));return Response.json({ok:!1,file,results,error},{status:422})}const results=typedUpdates.map((update)=>({key:update.key,ok:!0,newValue:update.value}));return Response.json({ok:!0,file,results})}catch(e){if(e?.status===403)return Response.json({ok:!1,error:"Forbidden",message:"CSRF token mismatch"},{status:403});return Response.json({ok:!1,error:e?.message},{status:500})}}},router=await import("@stacksjs/router"),routeRegistry=(await import(projectPath("app/Routes.ts"))).default;await router.loadRoutes(routeRegistry);const stacksRoute=router.route;serve({patterns:[userDashboardPath,dashboardPath],port:dashboardPort,componentsDir:storagePath("framework/defaults/resources/components/Dashboard"),layoutsDir:dashboardPath,partialsDir:dashboardPath,renderCache:!0,renderCacheVary:"source",prewarmRenderCache:4,watchDirs:[projectPath("resources/functions"),storagePath("framework/defaults/resources/functions")],quiet:!0,routes:configRoutes,onRequest:async(req)=>{const pathname=new URL(req.url).pathname;if(shouldDelegateDashboardRequest(pathname,req.method))return stacksRoute.handleRequest(req);return null},onResponse:seedCsrfPageResponse,auth:!1,...stxModule&&{stxModule}}).catch((err)=>{restoreConsole();console.error(`
|
|
1
|
+
import process from"node:process";import{randomUUID}from"node:crypto";import{existsSync,renameSync,unlinkSync,writeFileSync}from"node:fs";import{bold,cyan,dim,green}from"@stacksjs/cli";import{projectPath,publicPath,storagePath}from"@stacksjs/path";import{seedCsrfPageResponse,validateDevCsrfRequest}from"./csrf";import{shouldDelegateDashboardRequest}from"./dashboard-request-routing";import{buildDashboardUrl,buildManifest,discoverModels,findAvailablePort,waitForServer}from"./dashboard-utils";const verboseIdx=process.argv.indexOf("--verbose"),verbose=verboseIdx!==-1&&process.argv[verboseIdx+1]!=="false",startTime=Bun.nanoseconds(),originalConsoleLog=console.log,originalConsoleWarn=console.warn,bufferedLogs=[];console.log=(...args)=>{bufferedLogs.push(args.map(String).join(" "))};console.warn=(...args)=>{bufferedLogs.push(args.map(String).join(" "))};const dashboardPath=storagePath("framework/defaults/views/dashboard"),userDashboardPath=projectPath("resources/views/dashboard"),preferredPort=Number(process.env.PORT_ADMIN)||3002,dashboardPort=await findAvailablePort(preferredPort),appUrl=process.env.APP_URL||"",hasCustomDomain=appUrl!==""&&appUrl!=="localhost"&&!appUrl.includes("localhost:"),domain=hasCustomDomain?appUrl.replace(/^https?:\/\//,""):null,dashboardDomain=domain?`dashboard.${domain}`:null,sslBasePath=`${process.env.HOME}/.stacks/ssl`;function restoreConsole(){console.log=originalConsoleLog;console.warn=(...args)=>{const msg=args.map(String).join(" ");if(msg.includes("[STX] DOM API violation")||msg.includes("unsafe expression"))return;originalConsoleWarn(...args)}}async function startStxServer(){await import("@stacksjs/orm");let serve;try{const localServe=process.env.BUN_PLUGIN_STX_SRC||`${process.env.HOME}/Code/Tools/stx/packages/bun-plugin/src/serve.ts`;if(!await Bun.file(localServe).exists())throw Error("local bun-plugin-stx source not found");serve=(await import(localServe)).serve}catch{try{serve=(await import("bun-plugin-stx/serve")).serve}catch{serve=(await import(projectPath("pantry/bun-plugin-stx/dist/serve.js"))).serve}}let stxModule;try{const localStx=process.env.STX_SRC||`${process.env.HOME}/Code/Tools/stx/packages/stx/src/index.ts`;if(await Bun.file(localStx).exists()){const localCrosswind=`${process.env.HOME}/Code/Tools/crosswind/packages/crosswind/src/index.ts`;if(!process.env.CROSSWIND_SRC&&await Bun.file(localCrosswind).exists())process.env.CROSSWIND_SRC=localCrosswind;stxModule=await import(localStx)}}catch{}if(stxModule&&verbose)console.log("[Dashboard] Using local stx checkout");if(!stxModule)try{const vendoredStx=projectPath("pantry/@stacksjs/stx/dist/index.js");if(await Bun.file(vendoredStx).exists())stxModule=await import(vendoredStx)}catch{}const{listConfigFiles,readConfig,updateConfigKeys}=await import(storagePath("framework/defaults/resources/functions/dashboard/config-io.ts")),localTsChartsRoot=process.env.TS_CHARTS_SRC||`${process.env.HOME}/Code/Libraries/ts-charts`,dependencyBundles=new Map;function resolveTsChartsSource(packageName){return[`${localTsChartsRoot}/packages/${packageName}/src/index.ts`,projectPath(`node_modules/@ts-charts/${packageName}/src/index.ts`),projectPath(`pantry/@ts-charts/${packageName}/src/index.ts`)].find(existsSync)||null}const tsChartsEntry=[`${localTsChartsRoot}/packages/ts-charts/src/index.ts`,projectPath("node_modules/ts-charts/src/index.ts"),projectPath("pantry/ts-charts/src/index.ts")].find(existsSync);async function buildDashboardDependency(entrypoint){const cached=dependencyBundles.get(entrypoint);if(cached)return cached;const build=(async()=>{const result=await Bun.build({entrypoints:[entrypoint],target:"browser",format:"esm",minify:!0,plugins:[{name:"dashboard-ts-charts-source",setup(builder){builder.onResolve({filter:/^@ts-charts\/[a-z0-9-]+$/},(args)=>{const packageName=args.path.slice(11),source=resolveTsChartsSource(packageName);if(source)return{path:source};return null})}}]});if(!result.success){const errors=result.logs.filter((log)=>log.level==="error").map((log)=>log.message).join(`
|
|
2
|
+
`);throw Error(errors||`Failed to bundle ${entrypoint}`)}const output=result.outputs.find((file)=>file.path.endsWith(".js"));if(!output)throw Error(`No JavaScript output produced for ${entrypoint}`);return output.text()})();dependencyBundles.set(entrypoint,build);return build}function browserDependencyRoute(entrypoint){return async()=>{try{return new Response(await buildDashboardDependency(entrypoint),{headers:{"content-type":"text/javascript; charset=utf-8","cache-control":"no-cache"}})}catch(error){dependencyBundles.delete(entrypoint);return new Response(`throw new Error(${JSON.stringify(error.message)})`,{status:500,headers:{"content-type":"text/javascript; charset=utf-8"}})}}}let dashboardIconCss=null;async function buildDashboardIconCss(){const{generateCrosswindCSS}=await import("@stacksjs/stx"),dirs=[dashboardPath,userDashboardPath,storagePath("framework/defaults/resources/components/Dashboard")],icons=new Set;for(const dir of dirs){if(!existsSync(dir))continue;const glob=new Bun.Glob("**/*.{stx,ts}");for await(const file of glob.scan({cwd:dir,absolute:!0})){const text=await Bun.file(file).text();for(const match of text.matchAll(/\bi-[a-z][a-z0-9]*(?:-[a-z0-9]+)+/g))icons.add(match[0])}}if(icons.size===0)return"";return generateCrosswindCSS(`<div class="${[...icons].join(" ")}"></div>`,process.cwd())}const configRoutes={"/__deps/charts.js":browserDependencyRoute(storagePath("framework/core/charts/src/index.ts")),"/__deps/ts-charts.js":browserDependencyRoute(tsChartsEntry||`${localTsChartsRoot}/packages/ts-charts/src/index.ts`),"/__deps/dashboard-icons.css":async()=>{if(!dashboardIconCss)dashboardIconCss=buildDashboardIconCss();return new Response(await dashboardIconCss,{headers:{"content-type":"text/css; charset=utf-8","cache-control":"no-cache"}})},"/api/config/list":async()=>{try{return Response.json({ok:!0,files:listConfigFiles()})}catch(e){return Response.json({ok:!1,error:e?.message},{status:500})}},"/api/config/read":async(req)=>{try{const name=new URL(req.url).searchParams.get("name")||"";if(!/^[\w-]+$/.test(name))return Response.json({ok:!1,error:"Invalid config name"},{status:400});const result=await readConfig(name);if(!result)return Response.json({ok:!1,error:"Not found"},{status:404});return Response.json({ok:!0,name,fields:result.fields})}catch(e){return Response.json({ok:!1,error:e?.message},{status:500})}},"/api/config/source":async(req)=>{try{const name=new URL(req.url).searchParams.get("name")||"";if(!/^[\w-]+$/.test(name))return Response.json({ok:!1,error:"Invalid config name"},{status:400});const result=await readConfig(name);if(!result)return Response.json({ok:!1,error:"Not found"},{status:404});return new Response(result.source,{headers:{"content-type":"text/plain; charset=utf-8"}})}catch(e){return Response.json({ok:!1,error:e?.message},{status:500})}},"/api/config/update":async(req)=>{if(req.method!=="POST")return Response.json({ok:!1,error:"Method not allowed"},{status:405});try{await validateDevCsrfRequest(req);const body=await req.json(),file=body.file?.replace(/\.ts$/,"");if(!file||!/^[\w-]+$/.test(file))return Response.json({ok:!1,error:"Invalid file"},{status:400});const updates=[];if(Array.isArray(body.updates))for(const u of body.updates){const k=u.key??u.path;if(typeof k==="string")updates.push({key:k,value:u.value})}else if(body.key)updates.push({key:body.key,value:body.value});if(updates.length===0)return Response.json({ok:!1,error:"No updates supplied"},{status:400});const invalid=updates.find((update)=>!/^[A-Za-z_$][\w$]*$/.test(update.key)||typeof update.value!=="string"&&typeof update.value!=="number"&&typeof update.value!=="boolean"||typeof update.value==="number"&&!Number.isFinite(update.value));if(invalid)return Response.json({ok:!1,error:`Invalid value for configuration key "${invalid.key}"`},{status:400});const typedUpdates=updates;try{await updateConfigKeys(file,typedUpdates)}catch(err){const error=err?.message||"Configuration values could not be updated.",results=typedUpdates.map((update)=>({key:update.key,ok:!1,error}));return Response.json({ok:!1,file,results,error},{status:422})}const results=typedUpdates.map((update)=>({key:update.key,ok:!0,newValue:update.value}));return Response.json({ok:!0,file,results})}catch(e){if(e?.status===403)return Response.json({ok:!1,error:"Forbidden",message:"CSRF token mismatch"},{status:403});return Response.json({ok:!1,error:e?.message},{status:500})}}},router=await import("@stacksjs/router"),routeRegistry=(await import(projectPath("app/Routes.ts"))).default;await router.loadRoutes(routeRegistry);const stacksRoute=router.route;serve({patterns:[userDashboardPath,dashboardPath],port:dashboardPort,componentsDir:storagePath("framework/defaults/resources/components/Dashboard"),layoutsDir:dashboardPath,partialsDir:dashboardPath,publicDir:publicPath(),renderCache:!0,renderCacheVary:"source",prewarmRenderCache:4,watchDirs:[projectPath("resources/functions"),storagePath("framework/defaults/resources/functions")],quiet:!0,routes:configRoutes,onRequest:async(req)=>{const pathname=new URL(req.url).pathname;if(shouldDelegateDashboardRequest(pathname,req.method))return stacksRoute.handleRequest(req);return null},onResponse:seedCsrfPageResponse,auth:!1,...stxModule&&{stxModule}}).catch((err)=>{restoreConsole();console.error(`
|
|
3
3
|
Failed to start dashboard server: ${err?.message||err}
|
|
4
4
|
`);process.exit(1)})}async function startReverseProxy(){if(!dashboardDomain)return!1;if(process.env.STACKS_PROXY_MANAGED)return!1;try{const{startProxies}=await import("@stacksjs/rpx");await startProxies({proxies:[{from:`localhost:${dashboardPort}`,to:dashboardDomain,cleanUrls:!1}],https:{basePath:sslBasePath,validityDays:825},regenerateUntrustedCerts:!1,verbose});return!0}catch(error){if(verbose)originalConsoleLog(` ${dim(`Proxy: ${error}`)}`);return!1}}const[,discoveredModels]=await Promise.all([startStxServer(),discoverModels(projectPath("app/Models"),storagePath("framework/defaults/app/Models"))]),{loadDashboardToggles}=await import(storagePath("framework/defaults/resources/functions/dashboard/toggles.ts")),dashboardToggles=await loadDashboardToggles(projectPath("config/dashboard.ts")),manifestPath=storagePath("framework/defaults/views/dashboard/.discovered-models.json"),manifestPayload={models:buildManifest(discoveredModels),sections:dashboardToggles},manifestTempPath=`${manifestPath}.${process.pid}.${randomUUID()}.tmp`;try{writeFileSync(manifestTempPath,JSON.stringify(manifestPayload,null,2),{flag:"wx"});renameSync(manifestTempPath,manifestPath)}finally{if(existsSync(manifestTempPath))unlinkSync(manifestTempPath)}const serverReady=await waitForServer(dashboardPort);restoreConsole();let proxyStarted=Boolean(process.env.STACKS_PROXY_MANAGED);if(!proxyStarted)proxyStarted=await startReverseProxy().catch((err)=>{if(verbose)console.warn("[Dashboard] Reverse proxy failed:",err);return!1});const dashboardHttpsUrl=dashboardDomain?`https://${dashboardDomain}`:null,dashboardLocalUrl=`http://localhost:${dashboardPort}`,initialUrl=dashboardHttpsUrl&&proxyStarted?`${dashboardHttpsUrl}/`:`${dashboardLocalUrl}/`,elapsedMs=(Bun.nanoseconds()-startTime)/1e6;console.log();console.log(` ${bold(cyan("stacks dashboard"))}`);console.log();if(dashboardHttpsUrl){console.log(` ${green("\u279C")} ${bold("Local")}: ${cyan(dashboardHttpsUrl)}`);console.log(` ${dim("\u279C")} ${dim("Origin")}: ${dim(dashboardLocalUrl)}`)}else console.log(` ${green("\u279C")} ${bold("Local")}: ${cyan(dashboardLocalUrl)}`);console.log(` ${green("\u279C")} ${bold("Window")}: ${dim("Stacks Dashboard")} ${dim("1400\xD7900")}`);console.log(` ${green("\u279C")} ${bold("Models")}: ${dim(`${discoveredModels.length} discovered`)}`);if(dashboardPort!==preferredPort)console.log(` ${dim("\u279C")} ${dim(`Port ${preferredPort} in use, using ${dashboardPort}`)}`);if(!serverReady)console.log(` ${dim("\u26A0")} ${dim("Dev server may not be ready yet")}`);console.log();console.log(` ${dim(`ready in ${elapsedMs.toFixed(0)} ms`)}`);if(verbose){console.log();console.log(` ${dim("\u279C")} ${dim("URL")}: ${dim(initialUrl)}`);if(dashboardDomain){console.log(` ${dim("\u279C")} ${dim("SSL")}: ${dim(sslBasePath)}`);console.log(` ${dim("\u279C")} ${dim("Proxy")}: ${dim(`localhost:${dashboardPort} \u2192 ${dashboardDomain}`)}`)}if(bufferedLogs.length>0){console.log();for(const line of bufferedLogs)console.log(` ${dim(line)}`)}}console.log();let createApp;const localCraftSdk=process.env.HOME?`${process.env.HOME}/Code/Tools/craft/packages/typescript/src/index.ts`:void 0;if(localCraftSdk&&existsSync(localCraftSdk))try{({createApp}=await import(localCraftSdk))}catch{}if(!createApp){const packageNames=["craft-native","@craft-native/craft","@stacksjs/ts-craft"];for(const packageName of packageNames)try{({createApp}=await import(packageName));if(createApp)break}catch{}}if(createApp){const userIconPath=projectPath("resources/assets/images/app-icon.png"),defaultIconPath=storagePath("framework/defaults/resources/assets/images/app-icon.png"),appIconPath=await Bun.file(userIconPath).exists()?userIconPath:await Bun.file(defaultIconPath).exists()?defaultIconPath:void 0,craftBinaryPath=(()=>{const explicit=process.env.CRAFT_BIN;if(explicit)return existsSync(explicit)?explicit:void 0;const codeTools=`${process.env.HOME}/Code/Tools/craft/craft`;if(existsSync(codeTools))return codeTools;const codeToolsBin=`${process.env.HOME}/Code/Tools/craft/bin/craft`;if(existsSync(codeToolsBin))return codeToolsBin;const codeToolsZig=`${process.env.HOME}/Code/Tools/craft/packages/zig/zig-out/bin/craft`;if(existsSync(codeToolsZig))return codeToolsZig;const homeRel=`${process.env.HOME}/Documents/Projects/craft/packages/zig/zig-out/bin/craft`;if(existsSync(homeRel))return homeRel;return})();if(!craftBinaryPath)createApp=void 0;if(!createApp){console.log(` ${dim("Native window unavailable. Set CRAFT_BIN to a craft binary, or open the URL above in a browser.")}
|
|
5
5
|
`);await new Promise(()=>{})}const app=createApp({url:initialUrl,quiet:!verbose,...craftBinaryPath&&{craftPath:craftBinaryPath},window:{title:"Stacks Dashboard",width:1400,height:900,titlebarHidden:!0,webSidebarMaterial:!0,webSidebarWidth:250,...appIconPath&&{icon:appIconPath}}});process.on("SIGINT",()=>{app.close();process.exit(0)});process.on("SIGTERM",()=>{app.close();process.exit(0)});try{await app.show();process.exit(0)}catch{const fallbackUrl=dashboardHttpsUrl||dashboardLocalUrl;console.log(` ${dim("Dashboard available at:")} ${cyan(fallbackUrl)}
|
package/dist/helpers/utils.d.ts
CHANGED
|
@@ -19,6 +19,7 @@ export declare function actionNodePath(projectRoot: string, existingNodePath?: s
|
|
|
19
19
|
* @returns The result of the command.
|
|
20
20
|
*/
|
|
21
21
|
export declare function runAction(action: Action, options?: ActionOptions): Promise<Result<Subprocess, CommandError>>;
|
|
22
|
+
export declare function developmentWatchFlag(action: Action): string;
|
|
22
23
|
/**
|
|
23
24
|
* Run Actions the Stacks way.
|
|
24
25
|
*
|
package/dist/helpers/utils.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var {require}=import.meta;import{existsSync}from"node:fs";import{homedir}from"node:os";import{delimiter,join}from"node:path";import process from"node:process";import{buddyOptions,runCommand}from"@stacksjs/cli";import{err}from"@stacksjs/error-handling";import{log}from"@stacksjs/logging";import*as p from"@stacksjs/path";export function publishedActionCandidates(action,packageRoot){let root=packageRoot;if(!root)try{const pkgUrl=import.meta.resolve("@stacksjs/actions/package.json");if(pkgUrl){const pkgPath=new URL(pkgUrl).pathname;root=pkgPath.slice(0,pkgPath.lastIndexOf("/"))}}catch{return[]}if(!root)return[];return[`${root}/dist/${action}.js`,`${root}/dist/src/${action}.js`,`${root}/src/${action}.ts`]}export function developmentConditionForProject(projectRoot){return existsSync(join(projectRoot,"storage/framework/core"))&&existsSync(join(projectRoot,"node_modules/@stacksjs/env/src/index.ts"))?"--conditions development":""}export function actionNodePath(projectRoot,existingNodePath){const nodeModulesPath=join(projectRoot,"node_modules"),pantryPath=join(projectRoot,"pantry"),paths=[nodeModulesPath];for(const entry of existingNodePath?.split(delimiter)??[])if(entry&&entry!==nodeModulesPath&&entry!==pantryPath&&!paths.includes(entry))paths.push(entry);paths.push(pantryPath);return paths.join(delimiter)}async function resolveActionFile(action,projectRoot){const candidates=[];if(projectRoot)candidates.push(join(projectRoot,`storage/framework/core/actions/src/${action}.ts`));candidates.push(p.actionsPath(`src/${action}.ts`));candidates.push(...publishedActionCandidates(action));for(const candidate of candidates)if(await Bun.file(candidate).exists())return candidate;return null}export async function runAction(action,options){log.debug(`[action] Running: ${action}`);if(action==="dev/views")try{const nodePath=actionNodePath(p.projectPath(),process.env.NODE_PATH);if(process.env.NODE_PATH!==nodePath){process.env.NODE_PATH=nodePath;require("module").Module._initPaths?.()}const viewsEntries=[p.projectPath("storage/framework/core/actions/src/dev/views.ts"),p.frameworkPath("actions/src/dev/views.ts"),...publishedActionCandidates("dev/views")];for(const entry of viewsEntries)if(existsSync(entry)){await import(entry);return{ok:!0,value:{}}}return err("dev/views entry not found")}catch(error){return err(`Failed to start dev server: ${error}`)}const isLikelyCoreAction=action.includes("/")||["dev","build","install","upgrade","migrate"].some((prefix)=>action.startsWith(prefix)),userActionsBase=options?.cwd?join(String(options.cwd),"app/Actions"):p.userActionsPath();if(!isLikelyCoreAction&&existsSync(userActionsBase)){const glob=new Bun.Glob("**/*.{ts,js}"),scanOptions={cwd:userActionsBase,onlyFiles:!0,absolute:!0},matchingFiles=[],basePath=userActionsBase;for await(const file of glob.scan(scanOptions)){if(file.replace(`${basePath}/`,"").replace(/\.(ts|js)$/,"")===action||file.endsWith(`${action}.ts`)||file.endsWith(`${action}.js`)){log.debug(`[action] Resolved: ${action} \u2192 ${file}`);return await(await import(file)).default.handle(void 0)}matchingFiles.push(file)}for(const file of matchingFiles)try{const a=await import(file);if(a.name===action){log.debug(`[action] Resolved: ${action} \u2192 ${file}`);return await a.handle()}}catch(error){}}const path=await resolveActionFile(action,options?.cwd?String(options.cwd):void 0);if(!path)return err(`Action '${action}' not found in storage/framework/core/actions/src or @stacksjs/actions`);log.debug(`[action] Resolved: ${action} \u2192 ${path}`);const isDevAction=action.startsWith("dev/"),watchFlag=
|
|
1
|
+
var {require}=import.meta;import{existsSync}from"node:fs";import{homedir}from"node:os";import{delimiter,join}from"node:path";import process from"node:process";import{buddyOptions,runCommand}from"@stacksjs/cli";import{err}from"@stacksjs/error-handling";import{log}from"@stacksjs/logging";import*as p from"@stacksjs/path";export function publishedActionCandidates(action,packageRoot){let root=packageRoot;if(!root)try{const pkgUrl=import.meta.resolve("@stacksjs/actions/package.json");if(pkgUrl){const pkgPath=new URL(pkgUrl).pathname;root=pkgPath.slice(0,pkgPath.lastIndexOf("/"))}}catch{return[]}if(!root)return[];return[`${root}/dist/${action}.js`,`${root}/dist/src/${action}.js`,`${root}/src/${action}.ts`]}export function developmentConditionForProject(projectRoot){return existsSync(join(projectRoot,"storage/framework/core"))&&existsSync(join(projectRoot,"node_modules/@stacksjs/env/src/index.ts"))?"--conditions development":""}export function actionNodePath(projectRoot,existingNodePath){const nodeModulesPath=join(projectRoot,"node_modules"),pantryPath=join(projectRoot,"pantry"),paths=[nodeModulesPath];for(const entry of existingNodePath?.split(delimiter)??[])if(entry&&entry!==nodeModulesPath&&entry!==pantryPath&&!paths.includes(entry))paths.push(entry);paths.push(pantryPath);return paths.join(delimiter)}async function resolveActionFile(action,projectRoot){const candidates=[];if(projectRoot)candidates.push(join(projectRoot,`storage/framework/core/actions/src/${action}.ts`));candidates.push(p.actionsPath(`src/${action}.ts`));candidates.push(...publishedActionCandidates(action));for(const candidate of candidates)if(await Bun.file(candidate).exists())return candidate;return null}export async function runAction(action,options){log.debug(`[action] Running: ${action}`);if(action==="dev/views")try{const nodePath=actionNodePath(p.projectPath(),process.env.NODE_PATH);if(process.env.NODE_PATH!==nodePath){process.env.NODE_PATH=nodePath;require("module").Module._initPaths?.()}const viewsEntries=[p.projectPath("storage/framework/core/actions/src/dev/views.ts"),p.frameworkPath("actions/src/dev/views.ts"),...publishedActionCandidates("dev/views")];for(const entry of viewsEntries)if(existsSync(entry)){await import(entry);return{ok:!0,value:{}}}return err("dev/views entry not found")}catch(error){return err(`Failed to start dev server: ${error}`)}const isLikelyCoreAction=action.includes("/")||["dev","build","install","upgrade","migrate"].some((prefix)=>action.startsWith(prefix)),userActionsBase=options?.cwd?join(String(options.cwd),"app/Actions"):p.userActionsPath();if(!isLikelyCoreAction&&existsSync(userActionsBase)){const glob=new Bun.Glob("**/*.{ts,js}"),scanOptions={cwd:userActionsBase,onlyFiles:!0,absolute:!0},matchingFiles=[],basePath=userActionsBase;for await(const file of glob.scan(scanOptions)){if(file.replace(`${basePath}/`,"").replace(/\.(ts|js)$/,"")===action||file.endsWith(`${action}.ts`)||file.endsWith(`${action}.js`)){log.debug(`[action] Resolved: ${action} \u2192 ${file}`);return await(await import(file)).default.handle(void 0)}matchingFiles.push(file)}for(const file of matchingFiles)try{const a=await import(file);if(a.name===action){log.debug(`[action] Resolved: ${action} \u2192 ${file}`);return await a.handle()}}catch(error){}}const path=await resolveActionFile(action,options?.cwd?String(options.cwd):void 0);if(!path)return err(`Action '${action}' not found in storage/framework/core/actions/src or @stacksjs/actions`);log.debug(`[action] Resolved: ${action} \u2192 ${path}`);const isDevAction=action.startsWith("dev/"),watchFlag=developmentWatchFlag(action),developmentCondition=developmentConditionForProject(p.projectPath()),opts=isDevAction?"":buddyOptions(options)||"",cmd=["bun",developmentCondition,watchFlag,path,opts].filter(Boolean).join(" "),nodePath=actionNodePath(p.projectPath(),process.env.NODE_PATH),shouldInherit=options?.verbose||isDevAction&&!options?.quiet,optionsWithCwd={cwd:options?.cwd||p.projectPath(),...options,stdout:shouldInherit?"inherit":void 0,stderr:shouldInherit?"inherit":void 0,env:{...options?.env,NODE_PATH:nodePath,...isDevAction?{STACKS_DEV_SERVER:"1"}:{}}},result=await runCommand(cmd,optionsWithCwd);log.debug(`[action] Completed: ${action}`);return result}export function developmentWatchFlag(action){if(!action.startsWith("dev/"))return"";return action==="dev/dashboard"||action==="dev/desktop"?"":"--watch"}export async function runActions(actions,options){if(!actions.length)return err("No actions were specified");for(const action of actions)if(!hasAction(action))return err(`The specified action "${action}" does not exist`);return await runActionSequence(actions,options)}export async function runActionSequence(actions,options,runner=runAction){let result;for(const action of actions){result=await runner(action,options);if(result?.isErr)return result}return result}export function hasAction(action){const userActionPatterns=[`${action}.ts`,`${action}`,`Dashboard/${action}.ts`,`Dashboard/${action}`,`Buddy/${action}.ts`,`Buddy/${action}`],actionPatterns=[`src/${action}.ts`,`src/${action}`,`${action}.ts`,`${action}`];return[...userActionPatterns.map((pattern)=>p.userActionsPath(pattern)),...actionPatterns.map((pattern)=>p.actionsPath(pattern)),...publishedActionCandidates(action)].some((candidate)=>existsSync(candidate))}
|
package/dist/release.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{parseOptions}from"@stacksjs/cli";import{app}from"@stacksjs/config";import{Action}from"@stacksjs/enums";import{log}from"@stacksjs/logging";import{projectPath}from"@stacksjs/path";import{runActions}from".";import{BYPASS_ENV,formatPreflightFailure,runPinnedChecks}from"./release-preflight";const raw=parseOptions()??{},passthrough={};for(const[k,v]of Object.entries(raw)){if(k==="--"||k==="_")continue;passthrough[k]=v}const isDryRun=passthrough.dryRun===!0||passthrough.dryRun==="true",actions=isDryRun?[Action.GenerateLibraryEntries,Action.Bump]:[Action.GenerateLibraryEntries,Action.LintFix,Action.Bump],preflight=await runPinnedChecks({cwd:projectPath()});if(preflight.bypassed)log.warn(`${BYPASS_ENV} is set, so the pinned checks were skipped for this release.`);else if(preflight.failures.length>0)
|
|
1
|
+
import{parseOptions}from"@stacksjs/cli";import{app}from"@stacksjs/config";import{Action}from"@stacksjs/enums";import{log}from"@stacksjs/logging";import{projectPath}from"@stacksjs/path";import{runActions}from".";import{BYPASS_ENV,formatPreflightFailure,runPinnedChecks}from"./release-preflight";const raw=parseOptions()??{},passthrough={};for(const[k,v]of Object.entries(raw)){if(k==="--"||k==="_")continue;passthrough[k]=v}const isDryRun=passthrough.dryRun===!0||passthrough.dryRun==="true",actions=isDryRun?[Action.GenerateLibraryEntries,Action.Bump]:[Action.GenerateLibraryEntries,Action.LintFix,Action.Bump],preflight=await runPinnedChecks({cwd:projectPath()});if(preflight.bypassed)log.warn(`${BYPASS_ENV} is set, so the pinned checks were skipped for this release.`);else if(preflight.failures.length>0)await log.exit(formatPreflightFailure(preflight.failures),1);const result=await runActions(actions,{cwd:projectPath(),...passthrough});if(result&&result.isErr)await log.exit(`Release failed: ${result.error?.message??String(result.error)}`,1);log.success(`Successfully released ${app.name}`);
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@stacksjs/actions",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.70.
|
|
5
|
+
"version": "0.70.355",
|
|
6
6
|
"description": "The Stacks actions.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -59,33 +59,33 @@
|
|
|
59
59
|
"prepublishOnly": "bun run build"
|
|
60
60
|
},
|
|
61
61
|
"dependencies": {
|
|
62
|
-
"@stacksjs/config": "0.70.
|
|
62
|
+
"@stacksjs/config": "0.70.355",
|
|
63
63
|
"@stacksjs/bumpx": "^0.2.6",
|
|
64
64
|
"@stacksjs/bunpress": "^0.1.18",
|
|
65
65
|
"@stacksjs/logsmith": "^0.2.3",
|
|
66
|
-
"@stacksjs/registry": "0.70.
|
|
66
|
+
"@stacksjs/registry": "0.70.355",
|
|
67
67
|
"@stacksjs/stx": "^0.2.148",
|
|
68
68
|
"@stacksjs/ts-cloud": "^0.7.103",
|
|
69
69
|
"@stacksjs/ts-md": "^0.1.1"
|
|
70
70
|
},
|
|
71
71
|
"devDependencies": {
|
|
72
|
-
"@stacksjs/api": "0.70.
|
|
73
|
-
"@stacksjs/cli": "0.70.
|
|
74
|
-
"@stacksjs/database": "0.70.
|
|
72
|
+
"@stacksjs/api": "0.70.355",
|
|
73
|
+
"@stacksjs/cli": "0.70.355",
|
|
74
|
+
"@stacksjs/database": "0.70.355",
|
|
75
75
|
"@stacksjs/tlsx": "^0.13.2",
|
|
76
76
|
"better-dx": "^0.2.17",
|
|
77
|
-
"@stacksjs/dns": "0.70.
|
|
78
|
-
"@stacksjs/enums": "0.70.
|
|
79
|
-
"@stacksjs/env": "0.70.
|
|
80
|
-
"@stacksjs/error-handling": "0.70.
|
|
81
|
-
"@stacksjs/image": "0.70.
|
|
82
|
-
"@stacksjs/logging": "0.70.
|
|
83
|
-
"@stacksjs/path": "0.70.
|
|
84
|
-
"@stacksjs/security": "0.70.
|
|
85
|
-
"@stacksjs/storage": "0.70.
|
|
86
|
-
"@stacksjs/strings": "0.70.
|
|
87
|
-
"@stacksjs/utils": "0.70.
|
|
88
|
-
"@stacksjs/validation": "0.70.
|
|
77
|
+
"@stacksjs/dns": "0.70.355",
|
|
78
|
+
"@stacksjs/enums": "0.70.355",
|
|
79
|
+
"@stacksjs/env": "0.70.355",
|
|
80
|
+
"@stacksjs/error-handling": "0.70.355",
|
|
81
|
+
"@stacksjs/image": "0.70.355",
|
|
82
|
+
"@stacksjs/logging": "0.70.355",
|
|
83
|
+
"@stacksjs/path": "0.70.355",
|
|
84
|
+
"@stacksjs/security": "0.70.355",
|
|
85
|
+
"@stacksjs/storage": "0.70.355",
|
|
86
|
+
"@stacksjs/strings": "0.70.355",
|
|
87
|
+
"@stacksjs/utils": "0.70.355",
|
|
88
|
+
"@stacksjs/validation": "0.70.355"
|
|
89
89
|
},
|
|
90
90
|
"peerDependencies": {
|
|
91
91
|
"pickier": "^0.1.35"
|