@stacksjs/server 0.74.70 → 0.75.0

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/imports.js CHANGED
@@ -6,10 +6,10 @@ export * from './functions'
6
6
  export * from './models'
7
7
  export * from './jobs'
8
8
  export * from './controllers'
9
- `;await writeGeneratedFile(`${outputDir}/index.ts`,combinedContent);const globalsPath=`${outputDir}/globals.ts`;await generateGlobalsScript(existingDirs([functionsPath]),globalsPath,`${outputDir}/index.ts`);if(options.declarations!==!1){await generateServerAutoImportTypes();const pruned=await pruneBrowserAutoImportTypes();if(pruned.length>0)log.debug(`[auto-imports] dropped ${pruned.length} browser globals that resolve to nothing`);await invalidateTypeScriptBuildInfo()}log.debug("Auto-import files generated successfully")}async function invalidateTypeScriptBuildInfo(){const cacheDir=path.storagePath("framework/.cache/typescript");try{const{readdirSync,rmSync}=await import("node:fs");for(const entry of readdirSync(cacheDir)){if(!entry.endsWith(".tsbuildinfo"))continue;rmSync(`${cacheDir}/${entry}`,{force:!0});log.debug(`[auto-imports] dropped stale ${entry}`)}}catch{}}export function initiateImports(){const functionsPath=path.resourcesPath("functions"),defaultFunctionsPath=frameworkDefaultsDir("functions"),userModelsPath=path.userModelsPath(),defaultModelDirs=resolveDefaultModelDirs(),[defaultsRoot,...enabledSubdirs]=defaultModelDirs,userJobsPath=path.userJobsPath(),userControllersPath=path.userControllersPath(),defaultControllersPath=frameworkDefaultsDir("app/Controllers"),defineModelExports=[...scanDefineModelExports(userModelsPath),...packageModelDirs().flatMap((dir)=>scanDefineModelExports(dir)),...defaultsRoot?scanDefineModelExports(defaultsRoot,{recursive:!1}):[],...enabledSubdirs.flatMap((d)=>scanDefineModelExports(d))],seenJobs=new Set,jobExports=[...scanDefineModelExports(userJobsPath),...packageJobDirs().flatMap((dir)=>scanDefineModelExports(dir))].filter((exp)=>{if(seenJobs.has(exp.name))return!1;seenJobs.add(exp.name);return!0}),seen=new Set,uniqueDefineModelExports=defineModelExports.filter((exp)=>{if(seen.has(exp.name))return!1;seen.add(exp.name);return!0}),dtsDir=dirname(path.storagePath("framework/types/server-auto-imports.d.ts")),defineModelImports=uniqueDefineModelExports.map((exp)=>({from:`./${relative(dtsDir,exp.file).replace(/\\/g,"/").replace(/\.ts$/,"")}`,name:"default",as:exp.name})),jobImports=jobExports.map((exp)=>({from:`./${relative(dtsDir,exp.file).replace(/\\/g,"/").replace(/\.ts$/,"")}`,name:"default",as:exp.name})),controllerExports=[...scanDefineModelExports(userControllersPath),...defaultControllersPath?scanDefineModelExports(defaultControllersPath):[]],seenControllers=new Set,controllerImports=controllerExports.filter((exp)=>{if(seenControllers.has(exp.name))return!1;seenControllers.add(exp.name);return!0}).map((exp)=>({from:`./${relative(dtsDir,exp.file).replace(/\\/g,"/").replace(/\.ts$/,"")}`,name:"default",as:exp.name})),options={dts:path.storagePath("framework/types/server-auto-imports.d.ts"),imports:[...primitiveAutoImportEntries(),...defineModelImports,...jobImports,...controllerImports],dirs:existingDirs([functionsPath,defaultFunctionsPath]),eslint:{enabled:!0,filepath:path.storagePath("framework/server-auto-imports.json")}};plugin(autoImports(options));generateAutoImportFiles().catch((err)=>{console.error("[Server] Failed to generate auto-import files:",err)})}export async function generateServerAutoImportTypes(){const seen=new Set,valueExports=[...barrelExports("models"),...barrelExports("jobs"),...barrelExports("controllers"),...await ormModelGlobals()].filter((exp)=>!GLOBAL_SHADOW_BLOCKLIST.has(exp.name)).filter((exp)=>{if(seen.has(exp.name))return!1;seen.add(exp.name);return!0}),outputPath=path.storagePath("framework/types/server-auto-imports.d.ts"),outputDir=dirname(outputPath),declaredValues=new Set(valueExports.map((exp)=>exp.name)),lines=["// Generated by Stacks server auto-imports","// This file is regenerated automatically when the API starts.","export {}","declare global {"];for(const{from,name,as}of primitiveAutoImportEntries())if(!declaredValues.has(as))lines.push(` const ${as}: typeof import('${from}')['${name}']`);for(const exp of valueExports){if(!exp.isDefault){lines.push(` const ${exp.name}: typeof import('${exp.file}')['${exp.name}']`);continue}const importPath=relative(outputDir,exp.file).replace(/\\/g,"/").replace(/\.ts$/,""),relativePath=importPath.startsWith(".")?importPath:`./${importPath}`;lines.push(` const ${exp.name}: typeof import('${relativePath}')['default']`)}lines.push("}","");await writeGeneratedFile(outputPath,lines.join(`
9
+ `;await writeGeneratedFile(`${outputDir}/index.ts`,combinedContent);const globalsPath=`${outputDir}/globals.ts`;await generateGlobalsScript(existingDirs([functionsPath]),globalsPath,`${outputDir}/index.ts`);if(options.declarations!==!1){await generateServerAutoImportTypes();const pruned=await pruneBrowserAutoImportTypes();if(pruned.length>0)log.debug(`[auto-imports] dropped ${pruned.length} browser globals that nothing injects`);await invalidateTypeScriptBuildInfo()}log.debug("Auto-import files generated successfully")}async function invalidateTypeScriptBuildInfo(){const cacheDir=path.storagePath("framework/.cache/typescript");try{const{readdirSync,rmSync}=await import("node:fs");for(const entry of readdirSync(cacheDir)){if(!entry.endsWith(".tsbuildinfo"))continue;rmSync(`${cacheDir}/${entry}`,{force:!0});log.debug(`[auto-imports] dropped stale ${entry}`)}}catch{}}export function initiateImports(){const functionsPath=path.resourcesPath("functions"),defaultFunctionsPath=frameworkDefaultsDir("functions"),userModelsPath=path.userModelsPath(),defaultModelDirs=resolveDefaultModelDirs(),[defaultsRoot,...enabledSubdirs]=defaultModelDirs,userJobsPath=path.userJobsPath(),userControllersPath=path.userControllersPath(),defaultControllersPath=frameworkDefaultsDir("app/Controllers"),defineModelExports=[...scanDefineModelExports(userModelsPath),...packageModelDirs().flatMap((dir)=>scanDefineModelExports(dir)),...defaultsRoot?scanDefineModelExports(defaultsRoot,{recursive:!1}):[],...enabledSubdirs.flatMap((d)=>scanDefineModelExports(d))],seenJobs=new Set,jobExports=[...scanDefineModelExports(userJobsPath),...packageJobDirs().flatMap((dir)=>scanDefineModelExports(dir))].filter((exp)=>{if(seenJobs.has(exp.name))return!1;seenJobs.add(exp.name);return!0}),seen=new Set,uniqueDefineModelExports=defineModelExports.filter((exp)=>{if(seen.has(exp.name))return!1;seen.add(exp.name);return!0}),dtsDir=dirname(path.storagePath("framework/types/server-auto-imports.d.ts")),defineModelImports=uniqueDefineModelExports.map((exp)=>({from:`./${relative(dtsDir,exp.file).replace(/\\/g,"/").replace(/\.ts$/,"")}`,name:"default",as:exp.name})),jobImports=jobExports.map((exp)=>({from:`./${relative(dtsDir,exp.file).replace(/\\/g,"/").replace(/\.ts$/,"")}`,name:"default",as:exp.name})),controllerExports=[...scanDefineModelExports(userControllersPath),...defaultControllersPath?scanDefineModelExports(defaultControllersPath):[]],seenControllers=new Set,controllerImports=controllerExports.filter((exp)=>{if(seenControllers.has(exp.name))return!1;seenControllers.add(exp.name);return!0}).map((exp)=>({from:`./${relative(dtsDir,exp.file).replace(/\\/g,"/").replace(/\.ts$/,"")}`,name:"default",as:exp.name})),options={dts:path.storagePath("framework/types/server-auto-imports.d.ts"),imports:[...primitiveAutoImportEntries(),...defineModelImports,...jobImports,...controllerImports],dirs:existingDirs([functionsPath,defaultFunctionsPath]),eslint:{enabled:!0,filepath:path.storagePath("framework/server-auto-imports.json")}};plugin(autoImports(options));generateAutoImportFiles().catch((err)=>{console.error("[Server] Failed to generate auto-import files:",err)})}export async function generateServerAutoImportTypes(){const seen=new Set,valueExports=[...barrelExports("models"),...barrelExports("jobs"),...barrelExports("controllers"),...await ormModelGlobals()].filter((exp)=>!GLOBAL_SHADOW_BLOCKLIST.has(exp.name)).filter((exp)=>{if(seen.has(exp.name))return!1;seen.add(exp.name);return!0}),outputPath=path.storagePath("framework/types/server-auto-imports.d.ts"),outputDir=dirname(outputPath),declaredValues=new Set(valueExports.map((exp)=>exp.name)),lines=["// Generated by Stacks server auto-imports","// This file is regenerated automatically when the API starts.","export {}","declare global {"];for(const{from,name,as}of primitiveAutoImportEntries())if(!declaredValues.has(as))lines.push(` const ${as}: typeof import('${from}')['${name}']`);for(const exp of valueExports){if(!exp.isDefault){lines.push(` const ${exp.name}: typeof import('${exp.file}')['${exp.name}']`);continue}const importPath=relative(outputDir,exp.file).replace(/\\/g,"/").replace(/\.ts$/,""),relativePath=importPath.startsWith(".")?importPath:`./${importPath}`;lines.push(` const ${exp.name}: typeof import('${relativePath}')['default']`)}lines.push("}","");await writeGeneratedFile(outputPath,lines.join(`
10
10
  `));const globals={};for(const{as}of primitiveAutoImportEntries())if(!declaredValues.has(as))globals[as]=!0;for(const exp of valueExports)globals[exp.name]=!0;await Bun.write(path.storagePath("framework/server-auto-imports.json"),`${JSON.stringify({globals:Object.fromEntries(Object.keys(globals).sort().map((k)=>[k,!0]))},null,2)}
11
11
  `)}function barrelExports(barrel){const file=path.storagePath(`framework/auto-imports/${barrel}.ts`);if(!existsSync(file))return[];const source=readFileSync(file,"utf8"),outputDir=dirname(file),found=[];for(const line of source.split(`
12
- `)){const match=/^export \{ default as (\w+) \} from '([^']+)'/.exec(line.trim());if(!match)continue;const[,name,relativePath]=match;found.push({name,file:resolvePath(outputDir,`${relativePath}.ts`),isDefault:!0})}return found}export async function pruneBrowserAutoImportTypes(){const outputPath=path.storagePath("framework/types/browser-auto-imports.d.ts");if(!existsSync(outputPath))return[];const source=readFileSync(outputPath,"utf8"),outputDir=dirname(outputPath),exportsOf=new Map;async function moduleExports(specifier){const cached=exportsOf.get(specifier);if(cached!==void 0)return cached;let names;try{const resolved=specifier.startsWith(".")?resolvePath(outputDir,specifier):specifier;names=new Set(Object.keys(await import(resolved)))}catch{names=null}exportsOf.set(specifier,names);return names}const removed=[],kept=[];for(const line of source.split(`
13
- `)){const match=/^ {2}const (\w+): typeof import\('([^']+)'\)\['(\w+)'\]/.exec(line);if(!match){kept.push(line);continue}const[,declaredAs,specifier,exported]=match;if(specifier==="@stacksjs/stx"){removed.push(declaredAs);continue}const names=await moduleExports(specifier);if(names&&!names.has(exported)){removed.push(declaredAs);continue}kept.push(line)}if(removed.length===0)return[];const pruned=kept.filter((line)=>line.trim()!=="// @ts-nocheck").map((line)=>line.trim()==="// Generated by unplugin-auto-import"?"// Pruned by Stacks: every name below is exported by the module beside it.":line).join(`
14
- `);await Bun.write(outputPath,pruned);const globals=[...pruned.matchAll(/^ {2}const (\w+):/gm)].map((match)=>match[1]).sort();await Bun.write(path.storagePath("framework/browser-auto-imports.json"),`${JSON.stringify({globals:Object.fromEntries(globals.map((name)=>[name,!0]))},null,2)}
12
+ `)){const match=/^export \{ default as (\w+) \} from '([^']+)'/.exec(line.trim());if(!match)continue;const[,name,relativePath]=match;found.push({name,file:resolvePath(outputDir,`${relativePath}.ts`),isDefault:!0})}return found}export async function pruneBrowserAutoImportTypes(){const outputPath=path.storagePath("framework/types/browser-auto-imports.d.ts");if(!existsSync(outputPath))return[];const source=readFileSync(outputPath,"utf8"),removed=[],kept=[];for(const line of source.split(`
13
+ `)){const match=/^ {2}const (\w+): typeof import\('([^']+)'\)\['(\w+)'\]/.exec(line);if(!match){kept.push(line);continue}const[,declaredAs]=match;removed.push(declaredAs)}const staleHeaders=new Set(["// Generated by unplugin-auto-import","// Pruned by Stacks: every name below is exported by the module beside it."]),pruned=kept.filter((line)=>line.trim()!=="// @ts-nocheck").map((line)=>staleHeaders.has(line.trim())?"// Emptied by Stacks: nothing injects a bare name into a template. See stacksjs/stacks#2585.":line).join(`
14
+ `);if(pruned===source)return removed;await Bun.write(outputPath,pruned);const globals=[...pruned.matchAll(/^ {2}const (\w+):/gm)].map((match)=>match[1]).sort();await Bun.write(path.storagePath("framework/browser-auto-imports.json"),`${JSON.stringify({globals:Object.fromEntries(globals.map((name)=>[name,!0]))},null,2)}
15
15
  `);return removed}async function ormModelGlobals(){try{const{modelGlobalNames}=await import("@stacksjs/orm");return(modelGlobalNames??[]).map((name)=>({name,file:"@stacksjs/orm",isDefault:!1}))}catch{return[]}}export async function injectGlobalAutoImports(){if(globalThis.__stacksAutoImportsInjected)return;globalThis.__stacksAutoImportsInjected=!0;const errors=[],importWithTimeout=async(pkg)=>{let timer;try{return await Promise.race([import(pkg),new Promise((_,reject)=>{timer=setTimeout(()=>reject(Error(`auto-import timed out: ${pkg}`)),4000)})])}finally{if(timer!==void 0)clearTimeout(timer)}};await Promise.all(primitiveModules.map(async([pkg,names])=>{try{const mod=await importWithTimeout(pkg);for(const name of names)if(mod[name]!==void 0)globalThis[name]=mod[name]}catch(err){errors.push(err)}}));try{const{ensureLocalesLoaded}=await import("@stacksjs/i18n");await ensureLocalesLoaded()}catch(err){errors.push(err)}const barrels=["functions","models","jobs","controllers"],injected=[];for(const barrel of barrels){const barrelPath=path.storagePath(`framework/auto-imports/${barrel}.ts`);if(!existsSync(barrelPath))continue;try{const mod=await import(barrelPath);Object.assign(globalThis,mod);injected.push(barrel)}catch(err){log.warn(`[auto-imports] ${barrel}.ts failed to load, so nothing it exports is available. Views and actions referencing them will throw "is not defined". Cause: ${err.message}`)}}if(!injected.includes("models")&&existsSync(path.storagePath("framework/auto-imports/models.ts")))log.warn("[auto-imports] No models were injected. Every model reference in stx views and actions will be undefined.");try{const{registerAppListeners}=await import("@stacksjs/events");await registerAppListeners()}catch(err){errors.push(err)}try{const{initializeAuthorization}=await import("@stacksjs/auth");await initializeAuthorization()}catch(err){errors.push(err)}if(errors.length)for(const err of errors)console.warn("[auto-imports]",err.message)}
package/dist/start.js CHANGED
@@ -1 +1 @@
1
- globalThis.__STACKS_BINARY_MODE__=!0;import{assertRouteMiddlewareResolvable,loadRoutes,serve}from"@stacksjs/router";import{log,report}from"@stacksjs/logging/runtime";import config from"./config-production";import routeRegistry from"../../../../../app/Routes";process.on("unhandledRejection",(reason)=>{report(reason,{label:"[server] unhandledRejection"})});process.on("uncaughtException",(error)=>{report(error,{label:"[server] uncaughtException"});log.flush().finally(()=>process.exit(1))});console.log("[START] Application starting...");console.log("[START] Node version:",process.version);console.log("[START] Working directory:",process.cwd());console.log("[START] Environment:",process.env.APP_ENV||"not set");process.env.SKIP_CONFIG_LOADING="true";console.log("[START] Config loaded:",{port:config.server.port,host:config.server.host,appName:config.app.name,appUrl:config.app.url});console.log("[START] Loading routes from registry...");loadRoutes(routeRegistry).then(async()=>{console.log("[START] Routes loaded successfully");try{const ormRoutesPackage="@stacksjs/orm/routes";try{await import(ormRoutesPackage)}catch{await import("../../orm/routes")}console.log("[START] ORM routes loaded successfully")}catch(ormError){console.warn("[START] ORM routes skipped:",ormError instanceof Error?ormError.message:String(ormError))}try{await assertRouteMiddlewareResolvable();console.log("[START] Route middleware validated")}catch(middlewareError){console.error("[START] FATAL: unresolvable route middleware - refusing to serve unprotected routes:",middlewareError instanceof Error?middlewareError.message:String(middlewareError));process.exit(1)}console.log("[START] Calling serve()...");try{serve({port:config.server.port,hostname:config.server.host});console.log("[START] serve() called successfully")}catch(error){console.error("[START] ERROR calling serve():",error);process.exit(1)}}).catch((error)=>{console.error("[START] ERROR loading routes:",error);process.exit(1)});
1
+ globalThis.__STACKS_BINARY_MODE__=!0;import{appRouteRegistry,assertRouteMiddlewareResolvable,loadRoutes,serve}from"@stacksjs/router";import{log,report}from"@stacksjs/logging/runtime";import config from"./config-production";process.on("unhandledRejection",(reason)=>{report(reason,{label:"[server] unhandledRejection"})});process.on("uncaughtException",(error)=>{report(error,{label:"[server] uncaughtException"});log.flush().finally(()=>process.exit(1))});console.log("[START] Application starting...");console.log("[START] Node version:",process.version);console.log("[START] Working directory:",process.cwd());console.log("[START] Environment:",process.env.APP_ENV||"not set");process.env.SKIP_CONFIG_LOADING="true";console.log("[START] Config loaded:",{port:config.server.port,host:config.server.host,appName:config.app.name,appUrl:config.app.url});console.log("[START] Loading routes from registry...");appRouteRegistry().then(loadRoutes).then(async()=>{console.log("[START] Routes loaded successfully");try{const ormRoutesPackage="@stacksjs/orm/routes";try{await import(ormRoutesPackage)}catch{await import("../../orm/routes")}console.log("[START] ORM routes loaded successfully")}catch(ormError){console.warn("[START] ORM routes skipped:",ormError instanceof Error?ormError.message:String(ormError))}try{await assertRouteMiddlewareResolvable();console.log("[START] Route middleware validated")}catch(middlewareError){console.error("[START] FATAL: unresolvable route middleware - refusing to serve unprotected routes:",middlewareError instanceof Error?middlewareError.message:String(middlewareError));process.exit(1)}console.log("[START] Calling serve()...");try{serve({port:config.server.port,hostname:config.server.host});console.log("[START] serve() called successfully")}catch(error){console.error("[START] ERROR calling serve():",error);process.exit(1)}}).catch((error)=>{console.error("[START] ERROR loading routes:",error);process.exit(1)});
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@stacksjs/server",
3
3
  "type": "module",
4
4
  "sideEffects": false,
5
- "version": "0.74.70",
5
+ "version": "0.75.0",
6
6
  "description": "Local development and production-ready.",
7
7
  "author": "Chris Breuer",
8
8
  "contributors": [
@@ -58,19 +58,19 @@
58
58
  "prepublishOnly": "bun run build"
59
59
  },
60
60
  "dependencies": {
61
- "@stacksjs/auth": "0.74.70",
62
- "@stacksjs/config": "0.74.70",
63
- "@stacksjs/events": "0.74.70",
64
- "@stacksjs/i18n": "0.74.70",
65
- "@stacksjs/logging": "0.74.70",
66
- "@stacksjs/orm": "0.74.70",
67
- "@stacksjs/path": "0.74.70",
68
- "@stacksjs/router": "0.74.70",
69
- "@stacksjs/storage": "0.74.70",
61
+ "@stacksjs/auth": "0.75.0",
62
+ "@stacksjs/config": "0.75.0",
63
+ "@stacksjs/events": "0.75.0",
64
+ "@stacksjs/i18n": "0.75.0",
65
+ "@stacksjs/logging": "0.75.0",
66
+ "@stacksjs/orm": "0.75.0",
67
+ "@stacksjs/path": "0.75.0",
68
+ "@stacksjs/router": "0.75.0",
69
+ "@stacksjs/storage": "0.75.0",
70
70
  "bun-plugin-auto-imports": "^0.4.3"
71
71
  },
72
72
  "devDependencies": {
73
- "@stacksjs/validation": "0.74.70",
73
+ "@stacksjs/validation": "0.75.0",
74
74
  "better-dx": "^0.2.24"
75
75
  }
76
76
  }