@stacksjs/server 0.75.514 → 0.75.518
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/auto-import-reference.js +1 -1
- package/dist/config-production.js +1 -1
- package/dist/config.js +1 -1
- package/dist/controllers/base.js +1 -1
- package/dist/default-import-specifier.js +1 -1
- package/dist/imports.js +13 -13
- package/dist/maintenance.js +2 -2
- package/dist/proxy.js +2 -2
- package/dist/redirects.js +1 -1
- package/dist/request-body.js +1 -1
- package/dist/response-headers.js +1 -1
- package/dist/rewrites.js +1 -1
- package/dist/security-headers.js +1 -1
- package/dist/shadowed-defaults.js +2 -2
- package/dist/start.js +1 -1
- package/package.json +12 -12
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export async function browserAutoImportSurface(){try{const[runtime,demand,caching]=await Promise.all([import("@stacksjs/stx/runtime-globals"),import("@stacksjs/stx/unresolved-identifiers"),import("@stacksjs/stx/caching")])
|
|
1
|
+
export async function browserAutoImportSurface(){try{const[runtime,demand,caching]=await Promise.all([import("@stacksjs/stx/runtime-globals"),import("@stacksjs/stx/unresolved-identifiers"),import("@stacksjs/stx/caching")]);const source=await caching.getCachedSignalsRuntime(false);const aliases=[...source.matchAll(/window\.([A-Za-z_$][\w$]*)\s*=/g)].map((match)=>match[1]).filter((name)=>!name.startsWith("__")&&!name.startsWith("$"));return{runtime:[...new Set([...runtime.STX_RUNTIME_GLOBALS,...aliases])],macros:runtime.COMPILE_TIME_ONLY_GLOBALS,demand:demand.SERVER_ONLY_COMPOSABLES}}catch{return}}function names(values){return[...new Set(values)].sort().map((name)=>`\`${name}\``).join(", ")||"(none)"}export function renderAutoImportReference(server,browser){const lines=["# Available auto-imports","","<!-- Generated by buddy generate:auto-imports. Edit runtime sources, then regenerate. -->","","Use these names without imports in the context listed below. This project reference","is refreshed by buddy generate, buddy generate:types and buddy generate:auto-imports.","Read only the relevant section; package exports outside these lists need imports.","","## Server after Stacks boot","","Available in actions, routes, jobs, controllers and server-rendered templates after","injectGlobalAutoImports completes. Standalone scripts, tests and framework packages","that do not boot Stacks use explicit imports. Type-only exports always need type imports.","Models may require an enabled feature or database readiness for operations.","App definitions override defaults; explicit app-model imports retain exact inference.","If boot reports a failed package or barrel, its names are unavailable until it loads.","","| Runtime source | Names available without imports |","| --- | --- |",...server.filter((group)=>group.names.length).map((group)=>`| ${group.source} | ${names(group.names)} |`),"","Platform globals keep their built-in meaning. Import colliding app exports explicitly.","","## STX client scripts","","These names belong to `<script client>` and component client scripts. A TypeScript","module imported by a client script declares its own imports; template bindings do","not leak into module scope. Server helpers and resources/functions exports are not","automatically browser globals. Bare STX helpers can differ from imported Stacks APIs;","read stacks-composables/BROWSER.md for signatures before using them.",""];if(browser){const macros=new Set(browser.macros);const runtime=new Set(browser.runtime);lines.push("### Runtime and compiler bindings","",names(browser.runtime.filter((name)=>!macros.has(name))),"","### Compiler macros","",names(browser.macros),"","### Demand-delivered calls","","The installed STX compiler emits these helpers when it detects an authored call.","Call them directly in the client script; do not assume an unused helper exists on window.","",names(browser.demand.filter((name)=>!runtime.has(name))),"")}else{lines.push("Installed STX delivery registries are unavailable. Check the installed STX","runtime/compiler before omitting browser imports; ambient declarations are insufficient.","")}return lines.join(`
|
|
2
2
|
`)}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
export const config={app:{name:process.env.APP_NAME||"Stacks",env:process.env.APP_ENV||"production",debug:process.env.APP_DEBUG==="true"
|
|
1
|
+
export const config={app:{name:process.env.APP_NAME||"Stacks",env:process.env.APP_ENV||"production",debug:process.env.APP_DEBUG==="true"||false,url:process.env.APP_URL||"https://stacksjs.com"},server:{port:Number(process.env.PORT)||3000,host:"0.0.0.0"},logging:{level:process.env.LOG_LEVEL||"info"}};export default config;
|
package/dist/config.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{ports}from"@stacksjs/config/runtime";export function config(options){const serversMap={frontend:{host:"localhost",port:ports.frontend},backend:{host:"localhost",port:ports.backend},api:{host:"localhost",port:ports.api},admin:{host:"localhost",port:ports.admin},library:{host:"localhost",port:ports.library},desktop:{host:"localhost",port:ports.desktop},docs:{host:"localhost",port:ports.docs},email:{host:"localhost",port:ports.email},inspect:{host:"localhost",port:ports.inspect},"system-tray":{host:"localhost",port:ports.systemTray},database:{host:"localhost",port:ports.database}};if(options.type&&options.type in serversMap)return{host:serversMap[options.type].host,port:serversMap[options.type].port,open
|
|
1
|
+
import{ports}from"@stacksjs/config/runtime";export function config(options){const serversMap={frontend:{host:"localhost",port:ports.frontend},backend:{host:"localhost",port:ports.backend},api:{host:"localhost",port:ports.api},admin:{host:"localhost",port:ports.admin},library:{host:"localhost",port:ports.library},desktop:{host:"localhost",port:ports.desktop},docs:{host:"localhost",port:ports.docs},email:{host:"localhost",port:ports.email},inspect:{host:"localhost",port:ports.inspect},"system-tray":{host:"localhost",port:ports.systemTray},database:{host:"localhost",port:ports.database}};if(options.type&&options.type in serversMap){return{host:serversMap[options.type].host,port:serversMap[options.type].port,open:false}}return{host:options.host||"stacks.localhost",port:options.port||3000,open:false}}
|
package/dist/controllers/base.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{log}from"@stacksjs/logging/runtime";import{response}from"@stacksjs/router/response";export class Controller{json(data,status=200){return response.json(data,status)}success(data){return this.json(data,200)}created(data){return this.json(data,201)}noContent(){return response.noContent()}error(message,status=500){return this.json({error:message},status)}notFound(message="Resource not found"){return this.error(message,404)}unauthorized(message="Unauthorized"){return this.error(message,401)}forbidden(message="Forbidden"){return this.error(message,403)}async validate(request,rules){if(typeof request.validate!=="function")throw TypeError("This request does not carry the validation macro.");const result=await request.validate(rules);log.info("Validation result:",result)}}
|
|
1
|
+
import{log}from"@stacksjs/logging/runtime";import{response}from"@stacksjs/router/response";export class Controller{json(data,status=200){return response.json(data,status)}success(data){return this.json(data,200)}created(data){return this.json(data,201)}noContent(){return response.noContent()}error(message,status=500){return this.json({error:message},status)}notFound(message="Resource not found"){return this.error(message,404)}unauthorized(message="Unauthorized"){return this.error(message,401)}forbidden(message="Forbidden"){return this.error(message,403)}async validate(request,rules){if(typeof request.validate!=="function")throw new TypeError("This request does not carry the validation macro.");const result=await request.validate(rules);log.info("Validation result:",result)}}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync,readFileSync}from"node:fs";import{isAbsolute,relative,resolve,sep}from"node:path";export function isFrameworkSourceCheckout(projectRoot){try{const core=resolve(projectRoot,"storage/framework/core");return JSON.parse(readFileSync(resolve(core,"package.json"),"utf8")).name==="stacks"&&existsSync(resolve(core,"defaults/package.json"))}catch{return
|
|
1
|
+
import{existsSync,readFileSync}from"node:fs";import{isAbsolute,relative,resolve,sep}from"node:path";export function isFrameworkSourceCheckout(projectRoot){try{const core=resolve(projectRoot,"storage/framework/core");return JSON.parse(readFileSync(resolve(core,"package.json"),"utf8")).name==="stacks"&&existsSync(resolve(core,"defaults/package.json"))}catch{return false}}export function defaultImportSpecifier(file,roots,sourceCheckout=false){if(sourceCheckout)return;for(const root of roots){const subpath=relative(resolve(root),resolve(file));if(!subpath||subpath===".."||subpath.startsWith(`..${sep}`)||isAbsolute(subpath))continue;return`@stacksjs/defaults/${subpath.replace(/\\/g,"/")}`}return}
|
package/dist/imports.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
|
-
|
|
1
|
+
import{existsSync,readFileSync,renameSync,statSync,unlinkSync}from"node:fs";import{dirname,isAbsolute,relative,resolve as resolvePath}from"node:path";import{fileURLToPath}from"node:url";import{plugin}from"bun";import{log}from"@stacksjs/logging/runtime";import{path}from"@stacksjs/path";import{autoImports,generateRuntimeIndex,generateGlobalsScript}from"bun-plugin-auto-imports";import{globSync}from"@stacksjs/storage/glob";import{primitiveAutoImportEntries,primitiveModules}from"./primitive-imports";import{defaultImportSpecifier,isFrameworkSourceCheckout}from"./default-import-specifier";import{browserAutoImportSurface,renderAutoImportReference}from"./auto-import-reference";const OPTIONAL_MODEL_MODULES={commerce:["config/commerce.ts"],Content:["config/cms.ts","config/blog.ts"],Forms:["config/forms.ts"],realtime:["config/realtime.ts"]};function configEnabled(configRelPaths){if(process.env.STACKS_CANONICAL_FEATURES==="1")return true;return configRelPaths.some((rel)=>existsSync(path.projectPath(rel)))}export function frameworkDefaultsDir(sub){const vendored=path.storagePath(`framework/defaults/${sub}`);return resolveDefaultsDir(existsSync(vendored)?vendored:undefined,packagedDefaultsDir(sub),vendoredDefaultsAreStale())}export function resolveDefaultsDir(vendored,packaged,vendoredIsStale){if(packaged&&vendoredIsStale)return packaged;return vendored??packaged}function packagedDefaultsDir(sub){try{const packageRoot=dirname(fileURLToPath(import.meta.resolve("@stacksjs/defaults/package.json")));const packaged=`${packageRoot}/${sub}`;return existsSync(packaged)?packaged:undefined}catch{return}}function defaultsModuleSpecifier(){const roots=existingDirs([path.storagePath("framework/defaults"),packagedDefaultsDir("")]);const sourceCheckout=isFrameworkSourceCheckout(path.projectPath());return(file)=>defaultImportSpecifier(file,roots,sourceCheckout)}function declarationModuleSpecifier(file,outputPath,mapper=defaultsModuleSpecifier()){if(!isAbsolute(file)&&!file.startsWith("."))return file;const canonical=mapper(file,outputPath);if(canonical)return canonical;const local=relative(dirname(outputPath),file).replace(/\\/g,"/").replace(/\.ts$/,"");return local.startsWith(".")?local:`./${local}`}let defaultsAreStale;function vendoredDefaultsAreStale(){if(defaultsAreStale===undefined)defaultsAreStale=path.inspectDefaultsProvenance().status==="stale";return defaultsAreStale}function existingDirs(dirs){return dirs.filter((dir)=>Boolean(dir)&&existsSync(dir))}function packageModelDirs(){try{const{packageModelRoots}=require("@stacksjs/config");return packageModelRoots().map((root)=>root.dir)}catch{return[]}}async function writeGeneratedFile(outputPath,contents){const temp=`${outputPath}.${process.pid}.tmp`;try{await Bun.write(temp,contents);renameSync(temp,outputPath)}catch(error){try{unlinkSync(temp)}catch{}throw error}}function packageJobDirs(){try{const{packageJobRoots}=require("@stacksjs/config");return packageJobRoots().map((root)=>root.dir)}catch{return[]}}function resolveDefaultModelDirs(){const root=frameworkDefaultsDir("app/Models");if(!root)return[];const dirs=[root];for(const[subdir,configPaths]of Object.entries(OPTIONAL_MODEL_MODULES)){if(configEnabled(configPaths))dirs.push(`${root}/${subdir}`)}return dirs}function scanDirTopLevel(dir){try{return globSync(`${dir}/*.ts`,{ignore:["**/*.d.ts","**/index.ts","**/README*"]}).sort()}catch{return[]}}function scanDefineModelExports(dir,opts={}){const{recursive=true}=opts;let files=[];try{const pattern=recursive?`${dir}/**/*.ts`:`${dir}/*.ts`;files=globSync(pattern,{ignore:["**/*.d.ts","**/index.ts","**/README*"]}).sort()}catch{return[]}const exports=[];const seen=new Set;for(const file of files){const basename=file.split("/").pop()?.replace(".ts","")||"";if(basename&&!seen.has(basename)){seen.add(basename);exports.push({name:basename,file,isDefault:true})}}return exports}const GLOBAL_SHADOW_BLOCKLIST=new Set(["Error","Request","Response","URL","Map","Set","Object","Array","Number","String","Date","Promise","Symbol"]);async function generateDefineModelIndex(entries,outputPath){const lines=["// Generated by bun-plugin-auto-imports"];const seen=new Set;const moduleSpecifier=defaultsModuleSpecifier();for(const entry of entries){const dir=typeof entry==="string"?entry:entry.dir;const recursive=typeof entry==="string"?true:entry.recursive;let files=[];try{const pattern=recursive?`${dir}/**/*.ts`:`${dir}/*.ts`;files=globSync(pattern,{ignore:["**/*.d.ts","**/index.ts","**/README*"]}).sort()}catch{continue}for(const file of files){const basename=file.split("/").pop()?.replace(".ts","")||"";if(!basename||seen.has(basename))continue;seen.add(basename);const relativePath=moduleSpecifier(file,outputPath)??relative(dirname(outputPath),file).replace(/\\/g,"/").replace(/\.ts$/,"");if(GLOBAL_SHADOW_BLOCKLIST.has(basename)){lines.push(`// Skipped '${basename}' - would shadow a built-in global. Import directly if needed.`);lines.push(`// export { default as ${basename} } from '${relativePath}'`);continue}lines.push(`export { default as ${basename} } from '${relativePath}'`)}}await writeGeneratedFile(outputPath,`${lines.join(`
|
|
2
2
|
`)}
|
|
3
|
-
`)}async function generatePathIndex(entries,outputPath,options){const prefix=options.prefix??""
|
|
4
|
-
`))}export function autoImportSourceDirs(){return existingDirs([path.resourcesPath("functions"),frameworkDefaultsDir("functions"),path.userModelsPath(),...resolveDefaultModelDirs(),path.userJobsPath(),frameworkDefaultsDir("app/Jobs"),...packageJobDirs(),path.userControllersPath(),frameworkDefaultsDir("app/Controllers"),path.appPath("Actions"),frameworkDefaultsDir("app/Actions"),path.appPath("Listeners"),frameworkDefaultsDir("app/Listeners"),path.appPath("Policies"),frameworkDefaultsDir("app/Policies"),path.appPath("Middleware"),frameworkDefaultsDir("app/Middleware"),path.resourcesPath("emails"),frameworkDefaultsDir("resources/emails")])}export function autoImportsAreStale(){const manifest=path.storagePath("framework/auto-imports/functions.ts");if(!existsSync(manifest))return
|
|
5
|
-
`)).update("\x00").update(packages).digest("hex")}function recordedSourceFingerprint(){try{return JSON.parse(readFileSync(path.storagePath("framework/auto-imports/sources.json"),"utf8")).fingerprint}catch{return}}export async function generateAutoImportFiles(options={}){const moduleSpecifier=defaultsModuleSpecifier()
|
|
6
|
-
`);const globalsPath=`${outputDir}/globals.ts`;await generateGlobalsScript(existingDirs([functionsPath]),globalsPath,`${outputDir}/index.ts`,{moduleSpecifier});if(options.declarations
|
|
7
|
-
`)){const match=/^export (type )?\{([^}]*)\} from /.exec(line.trim());if(!match)continue;const lineIsType=Boolean(match[1]);for(const raw of match[2].split(",")){let specifier=raw.trim();if(!specifier)continue;const specifierIsType=specifier.startsWith("type ");if(specifierIsType)specifier=specifier.slice(
|
|
3
|
+
`)}async function generatePathIndex(entries,outputPath,options){const prefix=options.prefix??"";const extensions=options.extensions??[".ts"];const found=new Map;const moduleSpecifier=defaultsModuleSpecifier();for(const entry of entries){const dir=typeof entry==="string"?entry:entry.dir;const recursive=typeof entry==="string"?true:entry.recursive;let files=[];try{for(const extension of extensions){const pattern=recursive?`${dir}/**/*${extension}`:`${dir}/*${extension}`;files.push(...globSync(pattern).sort())}}catch{continue}const rank=(file)=>extensions.findIndex((extension)=>file.endsWith(extension));files=files.sort((left,right)=>{const byRank=rank(left)-rank(right);if(byRank!==0)return byRank;return left<right?-1:left>right?1:0});for(const file of files){const basename=file.split("/").pop()??"";if(basename.endsWith(".d.ts")||basename.endsWith(".test.ts")||basename.endsWith(".spec.ts")||basename==="index.ts")continue;const extension=extensions.find((candidate)=>file.endsWith(candidate))??"";const key=prefix+relative(dir,file).slice(0,extension.length?-extension.length:undefined);if(found.has(key))continue;found.set(key,moduleSpecifier(file,outputPath)??relative(dirname(outputPath),file).replace(/\\/g,"/"))}}const lines=["// Generated by bun-plugin-auto-imports","//","// Name to package export or relative file. The resolvers read it, and the name","// types are `keyof` over it - so a name that type-checks is a name that","// resolves. Values are paths rather than import thunks on purpose: thunks","// would make every compilation that touches a name resolve every module.",`export const ${options.exportName} = {`,...[...found.entries()].map(([key,file])=>` '${key}': '${file}',`),"} as const",""];await writeGeneratedFile(outputPath,lines.join(`
|
|
4
|
+
`))}export function autoImportSourceDirs(){return existingDirs([path.resourcesPath("functions"),frameworkDefaultsDir("functions"),path.userModelsPath(),...resolveDefaultModelDirs(),path.userJobsPath(),frameworkDefaultsDir("app/Jobs"),...packageJobDirs(),path.userControllersPath(),frameworkDefaultsDir("app/Controllers"),path.appPath("Actions"),frameworkDefaultsDir("app/Actions"),path.appPath("Listeners"),frameworkDefaultsDir("app/Listeners"),path.appPath("Policies"),frameworkDefaultsDir("app/Policies"),path.appPath("Middleware"),frameworkDefaultsDir("app/Middleware"),path.resourcesPath("emails"),frameworkDefaultsDir("resources/emails")])}export function autoImportsAreStale(){const manifest=path.storagePath("framework/auto-imports/functions.ts");if(!existsSync(manifest))return true;let manifestTime;try{manifestTime=statSync(manifest).mtimeMs}catch{return true}const discovered=path.storagePath("framework/discovered-packages.json");try{if(existsSync(discovered)&&statSync(discovered).mtimeMs>manifestTime)return true}catch{}for(const dir of autoImportSourceDirs()){if(!existsSync(dir))continue;try{if(statSync(dir).mtimeMs>manifestTime)return true;for(const file of globSync(`${dir}/**/*.ts`,{ignore:["**/*.d.ts"]})){if(statSync(file).mtimeMs>manifestTime)return true}}catch{continue}}return recordedSourceFingerprint()!==autoImportSourceFingerprint()}export function autoImportSourceFingerprint(){const root=path.projectPath();const files=[];for(const dir of autoImportSourceDirs()){for(const file of globSync(`${dir}/**/*.ts`,{ignore:["**/*.d.ts"]}))files.push(relative(root,file))}files.sort();let packages="";try{const manifest=JSON.parse(readFileSync(path.storagePath("framework/discovered-packages.json"),"utf8"));packages=JSON.stringify(Object.keys(manifest.packages??{}).sort().map((name)=>[name,manifest.packages[name]]))}catch{}return new Bun.CryptoHasher("sha256").update(files.join(`
|
|
5
|
+
`)).update("\x00").update(packages).digest("hex")}function recordedSourceFingerprint(){try{return JSON.parse(readFileSync(path.storagePath("framework/auto-imports/sources.json"),"utf8")).fingerprint}catch{return}}export async function generateAutoImportFiles(options={}){const moduleSpecifier=defaultsModuleSpecifier();const userFunctionsPath=path.resourcesPath("functions");const defaultFunctionsPath=frameworkDefaultsDir("functions");const functionsPath=userFunctionsPath;const outputDir=path.storagePath("framework/auto-imports");const userModelsPath=path.userModelsPath();const defaultModelDirs=resolveDefaultModelDirs();const[defaultsRoot,...enabledSubdirs]=defaultModelDirs;const userJobsPath=path.userJobsPath();const userControllersPath=path.userControllersPath();const defaultControllersPath=frameworkDefaultsDir("app/Controllers");await Bun.write(`${outputDir}/.gitkeep`,"");const functionsIndexPath=`${outputDir}/functions.ts`;await generateRuntimeIndex(existingDirs([userFunctionsPath,defaultFunctionsPath]),functionsIndexPath,{moduleSpecifier});const modelsIndexPath=`${outputDir}/models.ts`;const modelScan=[userModelsPath,...packageModelDirs().map((dir)=>({dir,recursive:true})),...defaultsRoot?[{dir:defaultsRoot,recursive:false}]:[],...defaultModelDirs.slice(1).map((d)=>({dir:d,recursive:true}))];await generateDefineModelIndex(modelScan,modelsIndexPath);const jobsIndexPath=`${outputDir}/jobs.ts`;await generateDefineModelIndex(existingDirs([userJobsPath,frameworkDefaultsDir("app/Jobs"),...packageJobDirs()]),jobsIndexPath);await generatePathIndex(existingDirs([path.appPath("Actions"),frameworkDefaultsDir("app/Actions")]),`${outputDir}/actions.ts`,{exportName:"actions",prefix:"Actions/"});await generatePathIndex(existingDirs([path.appPath("Listeners"),frameworkDefaultsDir("app/Listeners")]),`${outputDir}/listeners.ts`,{exportName:"listeners"});await generatePathIndex(existingDirs([path.appPath("Policies"),frameworkDefaultsDir("app/Policies")]),`${outputDir}/policies.ts`,{exportName:"policies"});await generatePathIndex(existingDirs([path.appPath("Middleware"),frameworkDefaultsDir("app/Middleware")]),`${outputDir}/middleware.ts`,{exportName:"middleware"});await generatePathIndex(existingDirs([path.resourcesPath("emails"),frameworkDefaultsDir("resources/emails")]),`${outputDir}/emails.ts`,{exportName:"emails",extensions:[".stx",".html"]});const controllersIndexPath=`${outputDir}/controllers.ts`;await generateDefineModelIndex(existingDirs([userControllersPath,defaultControllersPath]),controllersIndexPath);const combinedContent=combinedBarrel(COMBINED_BARRELS.map((name)=>({name,source:existsSync(`${outputDir}/${name}.ts`)?readFileSync(`${outputDir}/${name}.ts`,"utf8"):""})));await writeGeneratedFile(`${outputDir}/index.ts`,combinedContent);await writeGeneratedFile(`${outputDir}/sources.json`,`${JSON.stringify({fingerprint:autoImportSourceFingerprint()},null,2)}
|
|
6
|
+
`);const globalsPath=`${outputDir}/globals.ts`;await generateGlobalsScript(existingDirs([functionsPath]),globalsPath,`${outputDir}/index.ts`,{moduleSpecifier});if(options.declarations!==false){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")}const COMBINED_BARRELS=["functions","models","jobs","controllers"];export function barrelExportNames(source){const names=new Map;for(const line of source.split(`
|
|
7
|
+
`)){const match=/^export (type )?\{([^}]*)\} from /.exec(line.trim());if(!match)continue;const lineIsType=Boolean(match[1]);for(const raw of match[2].split(",")){let specifier=raw.trim();if(!specifier)continue;const specifierIsType=specifier.startsWith("type ");if(specifierIsType)specifier=specifier.slice("type ".length).trim();const name=specifier.split(/\s+as\s+/).pop().trim();const typeOnly=lineIsType||specifierIsType;const previous=names.get(name);names.set(name,{typeOnly:typeOnly&&(previous?.typeOnly??true)})}}return names}export function combinedBarrel(barrels){const lines=["// Generated by bun-plugin-auto-imports",...barrels.map((b)=>`export * from './${b.name}'`)];const owners=new Map;const exported=barrels.map((b)=>({name:b.name,names:barrelExportNames(b.source)}));for(const barrel of exported){for(const name of barrel.names.keys())owners.set(name,[...owners.get(name)??[],barrel.name])}const winners=new Map;for(const[name,from]of[...owners].sort(([a],[b])=>a.localeCompare(b))){if(from.length<2)continue;const winner=from.at(-1);const typeOnly=exported.find((b)=>b.name===winner).names.get(name).typeOnly;const entry=winners.get(winner)??{value:[],type:[]};entry[typeOnly?"type":"value"].push(name);winners.set(winner,entry)}if(winners.size>0){lines.push("");lines.push("// Names more than one barrel exports, which `export *` would drop (TS2308).");for(const barrel of barrels){const entry=winners.get(barrel.name);if(entry?.value.length)lines.push(`export { ${entry.value.join(", ")} } from './${barrel.name}'`);if(entry?.type.length)lines.push(`export type { ${entry.type.join(", ")} } from './${barrel.name}'`)}}return`${lines.join(`
|
|
8
8
|
`)}
|
|
9
|
-
`}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
|
|
10
|
-
`));const globals={};for(const{as}of primitiveAutoImportEntries())if(!declaredValues.has(as))globals[as]
|
|
11
|
-
`);const groups=primitiveModules.map(([source,names])=>({source:`\`${source}\``,names:[...names]}));for(const barrel of COMBINED_BARRELS){const file=path.storagePath(`framework/auto-imports/${barrel}.ts`)
|
|
12
|
-
`)){const match=/^export \{ default as (\w+) \} from '([^']+)'/.exec(line.trim());if(!match)continue;const[,name,relativePath]=match
|
|
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."])
|
|
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
|
|
15
|
-
`);return removed}async function ormModelGlobals(){try{const{modelGlobalNames}=await import("@stacksjs/orm");return(modelGlobalNames??[]).map((name)=>({name,file:"@stacksjs/orm",isDefault
|
|
9
|
+
`}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:true});log.debug(`[auto-imports] dropped stale ${entry}`)}}catch{}}export function initiateImports(){const moduleSpecifier=defaultsModuleSpecifier();const functionsPath=path.resourcesPath("functions");const defaultFunctionsPath=frameworkDefaultsDir("functions");const userModelsPath=path.userModelsPath();const defaultModelDirs=resolveDefaultModelDirs();const[defaultsRoot,...enabledSubdirs]=defaultModelDirs;const userJobsPath=path.userJobsPath();const userControllersPath=path.userControllersPath();const defaultControllersPath=frameworkDefaultsDir("app/Controllers");const defineModelExports=[...scanDefineModelExports(userModelsPath),...packageModelDirs().flatMap((dir)=>scanDefineModelExports(dir)),...defaultsRoot?scanDefineModelExports(defaultsRoot,{recursive:false}):[],...enabledSubdirs.flatMap((d)=>scanDefineModelExports(d))];const seenJobs=new Set;const jobExports=[...scanDefineModelExports(userJobsPath),...packageJobDirs().flatMap((dir)=>scanDefineModelExports(dir))].filter((exp)=>{if(seenJobs.has(exp.name))return false;seenJobs.add(exp.name);return true});const seen=new Set;const uniqueDefineModelExports=defineModelExports.filter((exp)=>{if(seen.has(exp.name))return false;seen.add(exp.name);return true});const dtsDir=dirname(path.storagePath("framework/types/server-auto-imports.d.ts"));const defineModelImports=uniqueDefineModelExports.map((exp)=>({from:declarationModuleSpecifier(exp.file,`${dtsDir}/server-auto-imports.d.ts`,moduleSpecifier),name:"default",as:exp.name}));const jobImports=jobExports.map((exp)=>({from:declarationModuleSpecifier(exp.file,`${dtsDir}/server-auto-imports.d.ts`,moduleSpecifier),name:"default",as:exp.name}));const controllerExports=[...scanDefineModelExports(userControllersPath),...defaultControllersPath?scanDefineModelExports(defaultControllersPath):[]];const seenControllers=new Set;const uniqueControllerExports=controllerExports.filter((exp)=>{if(seenControllers.has(exp.name))return false;seenControllers.add(exp.name);return true});const controllerImports=uniqueControllerExports.map((exp)=>({from:declarationModuleSpecifier(exp.file,`${dtsDir}/server-auto-imports.d.ts`,moduleSpecifier),name:"default",as:exp.name}));const options={moduleSpecifier,dts:path.storagePath("framework/types/server-auto-imports.d.ts"),imports:[...primitiveAutoImportEntries(),...defineModelImports,...jobImports,...controllerImports],dirs:existingDirs([functionsPath,defaultFunctionsPath]),eslint:{enabled:true,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 moduleSpecifier=defaultsModuleSpecifier();const seen=new Set;const 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 false;seen.add(exp.name);return true});const outputPath=path.storagePath("framework/types/server-auto-imports.d.ts");const declaredValues=new Set(valueExports.map((exp)=>exp.name));const 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 relativePath=declarationModuleSpecifier(exp.file,outputPath,moduleSpecifier);lines.push(` const ${exp.name}: typeof import('${relativePath}')['default']`)}lines.push("}","");await writeGeneratedFile(outputPath,lines.join(`
|
|
10
|
+
`));const globals={};for(const{as}of primitiveAutoImportEntries()){if(!declaredValues.has(as))globals[as]=true}for(const exp of valueExports)globals[exp.name]=true;await Bun.write(path.storagePath("framework/server-auto-imports.json"),`${JSON.stringify({globals:Object.fromEntries(Object.keys(globals).sort().map((k)=>[k,true]))},null,2)}
|
|
11
|
+
`);const groups=primitiveModules.map(([source,names])=>({source:`\`${source}\``,names:[...names]}));for(const barrel of COMBINED_BARRELS){const file=path.storagePath(`framework/auto-imports/${barrel}.ts`);const exported=existsSync(file)?barrelExportNames(readFileSync(file,"utf8")):new Map;const names=[...exported].filter(([name,info])=>!info.typeOnly&&!GLOBAL_SHADOW_BLOCKLIST.has(name)).map(([name])=>name);if(barrel==="models"){names.push(...valueExports.filter((exp)=>!exp.isDefault).map((exp)=>exp.name))}groups.push({source:`\`auto-imports/${barrel}.ts\`${barrel==="models"?" + ORM proxies":""}`,names})}const claimed=new Set;for(const group of[...groups].reverse()){group.names=group.names.filter((name)=>{if(claimed.has(name))return false;claimed.add(name);return true})}await writeGeneratedFile(path.storagePath("framework/auto-imports/RUNTIME.md"),renderAutoImportReference(groups,await browserAutoImportSurface()))}function barrelExports(barrel){const file=path.storagePath(`framework/auto-imports/${barrel}.ts`);if(!existsSync(file))return[];const source=readFileSync(file,"utf8");const outputDir=dirname(file);const 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;const specifier=relativePath;const file=specifier.startsWith(".")||isAbsolute(specifier)?resolvePath(outputDir,specifier.endsWith(".ts")?specifier:`${specifier}.ts`):specifier;found.push({name,file,isDefault:true})}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");const removed=[];const 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."]);const 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,true]))},null,2)}
|
|
15
|
+
`);return removed}async function ormModelGlobals(){try{const{modelGlobalNames}=await import("@stacksjs/orm");return(modelGlobalNames??[]).map((name)=>({name,file:"@stacksjs/orm",isDefault:false}))}catch{return[]}}let platformGlobalNames=null;export function assignBarrelGlobals(target,mod,platformNames){const skipped=[];for(const[name,value]of Object.entries(mod)){if(platformNames.has(name)){skipped.push(name);continue}target[name]=value}return skipped}export async function injectGlobalAutoImports(){if(globalThis.__stacksAutoImportsInjected)return;globalThis.__stacksAutoImportsInjected=true;platformGlobalNames??=new Set(Object.getOwnPropertyNames(globalThis));const errors=[];const importWithTimeout=async(pkg)=>{let timer;try{return await Promise.race([import(pkg),new Promise((_,reject)=>{timer=setTimeout(()=>reject(new Error(`auto-import timed out: ${pkg}`)),4000)})])}finally{if(timer!==undefined)clearTimeout(timer)}};await Promise.all(primitiveModules.map(async([pkg,names])=>{try{const mod=await importWithTimeout(pkg);for(const name of names){if(mod[name]!==undefined)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=COMBINED_BARRELS;const 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);const kept=assignBarrelGlobals(globalThis,mod,platformGlobalNames);if(kept.length){log.warn(`[auto-imports] ${kept.join(", ")} from ${barrel}.ts ${kept.length===1?"is":"are"} not global: ${kept.length===1?"it":"they"} would replace the platform's own, which libraries rely on. Import ${kept.length===1?"it":"them"} where used.`)}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{bootAppListeners}=await import("@stacksjs/events");await bootAppListeners({base:path.projectPath()})}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/maintenance.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{clientAddress}from"@stacksjs/bun-router";import{log}from"@stacksjs/logging/runtime";import*as p from"@stacksjs/path";import{existsSync}from"node:fs";const DEFAULT_MAINTENANCE_PAYLOAD={mode:"maintenance",status:503,message:"We are currently performing maintenance. Please check back soon."}
|
|
1
|
+
import{clientAddress}from"@stacksjs/bun-router";import{log}from"@stacksjs/logging/runtime";import*as p from"@stacksjs/path";import{existsSync}from"node:fs";const DEFAULT_MAINTENANCE_PAYLOAD={mode:"maintenance",status:503,message:"We are currently performing maintenance. Please check back soon."};const DEFAULT_COMING_SOON_PAYLOAD={mode:"coming-soon",status:200,message:"We are getting ready to launch. Check back soon.",redirect:"/coming-soon"};function defaultsForMode(mode){return mode==="coming-soon"?DEFAULT_COMING_SOON_PAYLOAD:DEFAULT_MAINTENANCE_PAYLOAD}let siteModePaths;function currentSiteModePaths(){const cwd=process.cwd();if(siteModePaths?.cwd!==cwd)siteModePaths={cwd};return siteModePaths}export function maintenanceFilePath(){return currentSiteModePaths().maintenance??=p.storagePath("framework/down")}export function comingSoonFilePath(){return currentSiteModePaths().comingSoon??=p.storagePath("framework/coming-soon")}export function siteModeFilePath(mode){return mode==="coming-soon"?comingSoonFilePath():maintenanceFilePath()}export async function isDownForMaintenance(){try{return existsSync(maintenanceFilePath())}catch{return false}}export async function isComingSoon(){try{return existsSync(comingSoonFilePath())}catch{return false}}export async function maintenancePayload(){return siteModePayload("maintenance")}export async function comingSoonPayload(){return siteModePayload("coming-soon")}function readSiteModePayload(mode){if(p.isCompiledBinary())return null;try{const filePath=siteModeFilePath(mode);if(!existsSync(filePath))return null;return Bun.file(filePath).text().then((content)=>({...defaultsForMode(mode),...JSON.parse(content),mode})).catch(()=>null)}catch{return null}}export async function siteModePayload(mode){return readSiteModePayload(mode)}function comingSoonPayloadResult(){const payload=readSiteModePayload("coming-soon");return payload?payload.then((value)=>value??envSiteModePayload()):envSiteModePayload()}function activeSiteModePayloadResult(){const payload=readSiteModePayload("maintenance");return payload?payload.then((value)=>value??comingSoonPayloadResult()):comingSoonPayloadResult()}export async function activeSiteModePayload(){return activeSiteModePayloadResult()}function envSiteModePayload(){if(isTruthy(process.env.APP_MAINTENANCE)){return{...DEFAULT_MAINTENANCE_PAYLOAD,mode:"maintenance",time:Date.now(),secret:process.env.APP_MAINTENANCE_SECRET||undefined}}if(isTruthy(process.env.APP_COMING_SOON)){return{...DEFAULT_COMING_SOON_PAYLOAD,mode:"coming-soon",time:Date.now(),secret:process.env.APP_COMING_SOON_SECRET||undefined}}return null}function isTruthy(value){const normalized=value?.toLowerCase();return normalized==="1"||normalized==="true"||normalized==="yes"||normalized==="on"}export async function down(options={}){const payload={...DEFAULT_MAINTENANCE_PAYLOAD,...options,mode:"maintenance",time:Date.now()};const frameworkDir=p.storagePath("framework");const{mkdirSync,existsSync}=await import("@stacksjs/storage");if(!existsSync(frameworkDir)){mkdirSync(frameworkDir,{recursive:true})}await Bun.write(maintenanceFilePath(),JSON.stringify(payload,null,2));log.info("Application is now in maintenance mode.");if(payload.secret){log.info("Maintenance bypass secret has been configured")}}export async function comingSoon(options={}){const payload={...DEFAULT_COMING_SOON_PAYLOAD,...options,mode:"coming-soon",time:Date.now()};const frameworkDir=p.storagePath("framework");const{mkdirSync,existsSync}=await import("@stacksjs/storage");if(!existsSync(frameworkDir)){mkdirSync(frameworkDir,{recursive:true})}await Bun.write(comingSoonFilePath(),JSON.stringify(payload,null,2));log.info("Application is now in coming soon mode.");if(payload.secret){log.info("Coming soon bypass secret has been configured")}}export async function up(){const{unlinkSync,existsSync}=await import("node:fs");const filePath=maintenanceFilePath();if(existsSync(filePath)){unlinkSync(filePath);log.info("Application is now live.")}else{log.info("Application is already live.")}}export async function launch(){const{unlinkSync,existsSync}=await import("node:fs");const filePath=comingSoonFilePath();if(existsSync(filePath)){unlinkSync(filePath);log.info("Application is out of coming soon mode.")}else{log.info("Application is not in coming soon mode.")}}export function isAllowedIp(ip,allowed=[],trustLocalhost=true){const localhostIps=["127.0.0.1","::1","localhost"];if(trustLocalhost&&localhostIps.includes(ip)){return true}if(allowed.length===0){return false}return allowed.includes(ip)}export function bypassCookieName(mode="maintenance"){return mode==="coming-soon"?"stacks_coming_soon_bypass":"stacks_maintenance_bypass"}export function hasValidBypassCookie(cookies,secret,mode="maintenance"){const bypassCookie=cookies[bypassCookieName(mode)];return bypassCookie===secret}export function isSecretPath(path,secret){return path===`/${secret}`||path.startsWith(`/${secret}/`)}export function maintenanceHtml(payload){const mode=payload.mode??"maintenance";const defaults=defaultsForMode(mode);const message=escapeHtml(payload.message||defaults.message||"");const title=escapeHtml(payload.title||(mode==="coming-soon"?"Coming soon":"Down for maintenance"));const appName=escapeHtml((process.env.APP_NAME||"").trim());return`<!DOCTYPE html>
|
|
2
2
|
<html lang="en">
|
|
3
3
|
<head>
|
|
4
4
|
<meta charset="UTF-8">
|
|
@@ -74,4 +74,4 @@ import{clientAddress}from"@stacksjs/bun-router";import{log}from"@stacksjs/loggin
|
|
|
74
74
|
${payload.retry?`<p class="retry">Expected back in about ${Math.ceil(payload.retry/60)} minutes.</p>`:""}
|
|
75
75
|
</main>
|
|
76
76
|
</body>
|
|
77
|
-
</html>`}function escapeHtml(value){return value.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}export function maintenanceResponse(payload){return siteModeResponse(payload)}export function siteModeResponse(payload){const headers={"Content-Type":"text/html; charset=utf-8"};if(payload.retry)headers["Retry-After"]=String(payload.retry)
|
|
77
|
+
</html>`}function escapeHtml(value){return value.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}export function maintenanceResponse(payload){return siteModeResponse(payload)}export function siteModeResponse(payload){const headers={"Content-Type":"text/html; charset=utf-8"};if(payload.retry){headers["Retry-After"]=String(payload.retry)}if(payload.redirect){return new Response(null,{status:302,headers:{Location:payload.redirect}})}return new Response(maintenanceHtml(payload),{status:payload.status||(payload.mode==="coming-soon"?200:503),headers})}export function bypassCookieValue(secret,mode="maintenance"){return`${bypassCookieName(mode)}=${secret}; Path=/; HttpOnly; SameSite=Lax`}const ALWAYS_ALLOWED_PATHS=new Set(["/coming-soon","/api/email/subscribe","/favicon.ico"]);const ALWAYS_ALLOWED_PREFIXES=["/css/","/js/","/images/","/fonts/","/assets/","/_stx/","/_modules/","/@vite/","/@fs/","/__deps/"];const ALWAYS_ALLOWED_EXTENSIONS=[".css",".js",".mjs",".map",".woff",".woff2",".ttf",".otf",".eot",".svg",".png",".jpg",".jpeg",".gif",".webp",".avif",".ico"];function configuredAllowList(){const raw=process.env.APP_MAINTENANCE_ALLOW??process.env.APP_COMING_SOON_ALLOW??"";return raw.split(",").map((entry)=>entry.trim()).filter(Boolean)}function isConfiguredAllowed(path){for(const entry of configuredAllowList()){if(entry.endsWith("*")){if(path.startsWith(entry.slice(0,-1)))return true;continue}if(entry.endsWith("/")){if(path.startsWith(entry))return true;continue}if(path===entry)return true}return false}export function isAlwaysAllowed(path){if(ALWAYS_ALLOWED_PATHS.has(path))return true;if(isConfiguredAllowed(path))return true;if(ALWAYS_ALLOWED_PREFIXES.some((p)=>path.startsWith(p)))return true;const lower=path.toLowerCase();return ALWAYS_ALLOWED_EXTENSIONS.some((ext)=>lower.endsWith(ext))}function parseCookieHeader(header){const out={};if(!header)return out;for(const part of header.split(";")){const trimmed=part.trim();const eq=trimmed.indexOf("=");if(eq===-1)continue;const k=trimmed.slice(0,eq).trim();const v=trimmed.slice(eq+1).trim();if(k)out[k]=v}return out}function clientIp(req){return clientAddress(req)??"127.0.0.1"}export function maintenanceGate(req){const payloadResult=activeSiteModePayloadResult();return payloadResult instanceof Promise?payloadResult.then((payload)=>applyMaintenanceGate(req,payload)):applyMaintenanceGate(req,payloadResult)}function applyMaintenanceGate(req,payload){if(!payload)return null;const mode=payload.mode??"maintenance";const url=new URL(req.url);const path=url.pathname;if(isAlwaysAllowed(path))return null;if(payload.secret&&isSecretPath(path,payload.secret)){const location=mode==="coming-soon"?`/?preview=${encodeURIComponent(payload.secret)}`:"/";return new Response(null,{status:302,headers:{Location:location,"Set-Cookie":bypassCookieValue(payload.secret,mode)}})}const cookies=parseCookieHeader(req.headers.get("cookie"));const hasCookie=!!payload.secret&&hasValidBypassCookie(cookies,payload.secret,mode);const appEnv=(process.env.APP_ENV||process.env.NODE_ENV||"").toLowerCase();const trustLocalhost=!["production","staging"].includes(appEnv);const ipAllowed=isAllowedIp(clientIp(req),payload.allowed,trustLocalhost);if(hasCookie||ipAllowed)return null;return siteModeResponse(payload)}
|
package/dist/proxy.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{clientAddress,peerAddress,registerPeerSource}from"@stacksjs/bun-router";import{skipRequestCapture}from"@stacksjs/router/request-capture";export const DEFAULT_API_PREFIX="/api/"
|
|
2
|
-
`)}export function viewClientAddress(req,server){registerPeerSource(server);return clientAddress(req)}export async function proxyToBackend(req,backendBase,stripPrefix,peerOf=req){const incoming=new URL(req.url);let pathname=incoming.pathname;if(stripPrefix&&(pathname===stripPrefix||pathname.startsWith(`${stripPrefix}/`)))pathname=pathname.slice(stripPrefix.length)||"/"
|
|
1
|
+
import{clientAddress,peerAddress,registerPeerSource}from"@stacksjs/bun-router";import{skipRequestCapture}from"@stacksjs/router/request-capture";export const DEFAULT_API_PREFIX="/api/";export const DEFAULT_API_METHODS=["POST","PUT","PATCH","DELETE"];export function resolveApiProxyRules(input={}){const prefixes=[DEFAULT_API_PREFIX];for(const raw of input.prefixes??[]){const prefix=String(raw).trim();if(!prefix||!prefix.startsWith("/"))continue;const normalized=prefix.endsWith("/")?prefix:`${prefix}/`;if(!prefixes.includes(normalized))prefixes.push(normalized)}const paths=[];for(const raw of input.paths??[]){const path=String(raw).trim();if(!path||!path.startsWith("/"))continue;const normalized=path.length>1&&path.endsWith("/")?path.slice(0,-1):path;if(!paths.includes(normalized))paths.push(normalized)}const methods=new Set((input.methods??DEFAULT_API_METHODS).map((method)=>String(method).toUpperCase()));return{prefixes,paths,methods}}function matchesPrefix(pathname,prefix){return pathname.startsWith(prefix)||pathname===prefix.slice(0,-1)}export function isApiBoundRequest(req,pathname,rules){return isApiBoundPath(req.method,pathname,rules)}export function isApiBoundPath(method,pathname,rules){const verb=method.toUpperCase();if(!rules)return pathname.startsWith(DEFAULT_API_PREFIX)||DEFAULT_API_METHODS.includes(verb);if(rules.methods.has(verb))return true;if(rules.paths.includes(pathname))return true;return rules.prefixes.some((prefix)=>matchesPrefix(pathname,prefix))}export function describeApiProxyRules(rules){const parts=[`prefixes ${rules.prefixes.join(" ")}`,`methods ${[...rules.methods].sort().join("/")}`];if(rules.paths.length>0)parts.push(`paths ${rules.paths.join(" ")}`);return parts.join(", ")}export function unforwardableRoutes(routes,rules){return routes.filter((route)=>!isApiBoundPath(route.method,route.path,rules))}export function describeUnforwardableRoutes(routes){const lines=routes.map((route)=>{const origin=route.file?` (${route.file})`:"";return` ${route.method} ${route.path}${origin}`});return[`${routes.length} root-mounted route${routes.length===1?"":"s"} the views server will not forward, so ${routes.length===1?"it":"they"} will answer the view 404 rather than reaching the handler:`,...lines,`Add them to \`proxy.paths\` in config/server.ts (or their prefix to \`proxy.prefixes\`) so the views server forwards them to the API.`].join(`
|
|
2
|
+
`)}export function viewClientAddress(req,server){registerPeerSource(server);return clientAddress(req)}export async function proxyToBackend(req,backendBase,stripPrefix,peerOf=req){const incoming=new URL(req.url);let pathname=incoming.pathname;if(stripPrefix&&(pathname===stripPrefix||pathname.startsWith(`${stripPrefix}/`))){pathname=pathname.slice(stripPrefix.length)||"/"}const target=`${backendBase}${pathname}${incoming.search}`;const fwd=new Headers(req.headers);fwd.delete("host");fwd.delete("content-length");const peer=peerAddress(peerOf);if(peer){const forwardedFor=fwd.get("x-forwarded-for");fwd.set("x-forwarded-for",forwardedFor?`${forwardedFor}, ${peer}`:peer)}fwd.set("x-forwarded-host",incoming.host);fwd.set("x-forwarded-proto",incoming.protocol.replace(":",""));const body=req.method==="GET"||req.method==="HEAD"?undefined:await req.arrayBuffer();const upstream=await fetch(target,{method:req.method,headers:fwd,body,redirect:"manual",signal:peerOf.signal});skipRequestCapture(peerOf);const out=new Headers(upstream.headers);out.delete("content-length");out.delete("content-encoding");return new Response(upstream.body,{status:upstream.status,statusText:upstream.statusText,headers:out})}export function resolveApiBase(configuredPort,env=process.env){if(env.API_URL)return env.API_URL;const explicitPort=Number(env.PORT_API);if(explicitPort)return`http://127.0.0.1:${explicitPort}`;const deployed=["production","staging","development"].includes((env.APP_ENV||"").toLowerCase());if(deployed)return null;return`http://127.0.0.1:${configuredPort||3008}`}
|
package/dist/redirects.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{existsSync}from"node:fs";import{path as p}from"@stacksjs/path";const PROTECTED_PREFIX="/api/";export const DEFAULT_REDIRECT_STATUS=301;function normalizePath(value){const path=String(value).trim();if(!path.startsWith("/"))return"";return path.length>1&&path.endsWith("/")?path.replace(/\/+$/,""):path}export function resolveRedirectRules(input={}){const rules=new Map;for(const[rawFrom,rawTarget]of Object.entries(input??{})){const subtree=rawFrom.endsWith("/*")
|
|
1
|
+
import{existsSync}from"node:fs";import{path as p}from"@stacksjs/path";const PROTECTED_PREFIX="/api/";export const DEFAULT_REDIRECT_STATUS=301;function normalizePath(value){const path=String(value).trim();if(!path.startsWith("/"))return"";return path.length>1&&path.endsWith("/")?path.replace(/\/+$/,""):path}export function resolveRedirectRules(input={}){const rules=new Map;for(const[rawFrom,rawTarget]of Object.entries(input??{})){const subtree=rawFrom.endsWith("/*");const from=normalizePath(subtree?rawFrom.slice(0,-2)||"/":rawFrom);if(!from)continue;if(from===PROTECTED_PREFIX.slice(0,-1)||from.startsWith(PROTECTED_PREFIX))continue;const target=typeof rawTarget==="string"?{to:rawTarget}:rawTarget;const to=String(target?.to??"").trim();if(!to)continue;if(!/^https?:\/\//i.test(to)&&normalizePath(to)===from)continue;rules.set(subtree?`${from}/*`:from,{from,to,status:Number(target?.status)||DEFAULT_REDIRECT_STATUS,preserveQuery:target?.preserveQuery!==false,subtree})}return rules}export async function loadRouteRedirects(file=p.storagePath("framework/auto-imports/routes.ts")){if(!existsSync(file))return{};try{const generated=await import(file);const redirects={};for(const[from,target]of Object.entries(generated.routeRedirects??{})){if(from.includes("{")||!target?.to)continue;redirects[from]={to:target.to,status:target.status}}return redirects}catch{return{}}}export function resolveRedirect(url,rules){if(!rules?.size)return;const pathname=normalizePath(url.pathname);const rule=rules.get(pathname)??matchSubtree(pathname,rules);if(!rule)return;let location=rule.to;if(rule.subtree){const remainder=pathname.slice(rule.from.length);if(remainder)location=location.replace(/\/$/,"")+remainder}if(rule.preserveQuery&&url.search){location+=location.includes("?")?`&${url.search.slice(1)}`:url.search}return new Response(null,{status:rule.status,headers:{Location:location,"Cache-Control":rule.status===301||rule.status===308?"public, max-age=3600":"no-store"}})}function matchSubtree(pathname,rules){let best;for(const rule of rules.values()){if(!rule.subtree)continue;if(pathname!==rule.from&&!pathname.startsWith(`${rule.from}/`))continue;if(!best||rule.from.length>best.from.length)best=rule}return best}export function describeRedirectRules(rules){if(!rules.size)return"none";const shown=[...rules.values()].slice(0,3).map((rule)=>`${rule.from} → ${rule.to}`);const rest=rules.size-shown.length;return rest>0?`${shown.join(", ")} (+${rest} more)`:shown.join(", ")}
|
package/dist/request-body.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export function serverRequestBodyOptions(value){if(value===
|
|
1
|
+
export function serverRequestBodyOptions(value){if(value===undefined)return{};if(typeof value!=="number"||!Number.isSafeInteger(value)||value<=0)throw new RangeError("server.maxRequestBodySize must be a positive safe integer of bytes");return{maxRequestBodySize:value}}
|
package/dist/response-headers.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export function applyResponseHeaders(request,response,rules){if(!rules||response.status===101)return;const pathname=new URL(request.url).pathname
|
|
1
|
+
export function applyResponseHeaders(request,response,rules){if(!rules||response.status===101)return;const pathname=new URL(request.url).pathname;const values=Object.entries(rules).filter(([pattern])=>pattern.endsWith("/*")?pathname.startsWith(pattern.slice(0,-1)):pathname===pattern).flatMap(([,headers])=>Object.entries(headers));if(!values.length)return;try{for(const[key,value]of values)response.headers.set(key,value)}catch{const headers=new Headers(response.headers);for(const[key,value]of values)headers.set(key,value);return new Response(response.body,{status:response.status,statusText:response.statusText,headers})}}
|
package/dist/rewrites.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
const PROTECTED_PREFIX="/api/";function normalizePath(value){const path=String(value).trim();if(!path.startsWith("/"))return"";return path.length>1&&path.endsWith("/")?path.replace(/\/+$/,""):path}export function resolveRewriteRules(input={}){const rules=new Map;for(const[rawFrom,rawTo]of Object.entries(input??{})){const prefix=rawFrom.endsWith("*")
|
|
1
|
+
const PROTECTED_PREFIX="/api/";function normalizePath(value){const path=String(value).trim();if(!path.startsWith("/"))return"";return path.length>1&&path.endsWith("/")?path.replace(/\/+$/,""):path}export function resolveRewriteRules(input={}){const rules=new Map;for(const[rawFrom,rawTo]of Object.entries(input??{})){const prefix=rawFrom.endsWith("*");const from=normalizePath(prefix?rawFrom.slice(0,-1):rawFrom);if(!from)continue;if(from===PROTECTED_PREFIX.slice(0,-1)||from.startsWith(PROTECTED_PREFIX))continue;const to=normalizePath(prefix&&rawTo.endsWith("*")?rawTo.slice(0,-1):rawTo);if(!to||to===from)continue;rules.set(from,{from,to,prefix})}return rules}export function resolveRewrite(pathname,rules){if(!rules||rules.size===0)return;const path=normalizePath(pathname);if(!path)return;const exact=rules.get(path);if(exact&&!exact.prefix)return exact.to;let best;for(const rule of rules.values()){if(!rule.prefix||!path.startsWith(rule.from))continue;if(!best||rule.from.length>best.from.length)best=rule}if(!best)return;return`${best.to}${path.slice(best.from.length)}`}export function describeRewriteRules(rules){if(!rules||rules.size===0)return"";return[...rules.values()].map((rule)=>`${rule.from}${rule.prefix?"*":""} → ${rule.to}${rule.prefix?"*":""}`).join(", ")}
|
package/dist/security-headers.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import process from"node:process";let _isDisabledCache;function isDisabled(){if(_isDisabledCache!==
|
|
1
|
+
import process from"node:process";let _isDisabledCache;function isDisabled(){if(_isDisabledCache!==undefined)return _isDisabledCache;_isDisabledCache=process.env.STACKS_SECURITY_HEADERS_DISABLE==="true";return _isDisabledCache}export function resolveEmbeddableRules(input){const paths=[];const prefixes=[];for(const raw of input??[]){const entry=String(raw).trim();if(!entry||!entry.startsWith("/"))continue;if(entry.endsWith("/")&&entry.length>1){if(!prefixes.includes(entry))prefixes.push(entry);continue}if(!paths.includes(entry))paths.push(entry)}return{paths,prefixes}}function matchesPrefix(pathname,prefix){return pathname.startsWith(prefix)||pathname===prefix.slice(0,-1)}export function isEmbeddablePath(pathname,rules){if(rules.paths.includes(pathname))return true;return rules.prefixes.some((prefix)=>matchesPrefix(pathname,prefix))}export function applyViewSecurityHeaders(req,response,rules){if(isDisabled())return;const embeddable=isEmbeddablePath(new URL(req.url).pathname,rules);const wanted=[["X-Content-Type-Options","nosniff"],["Referrer-Policy","strict-origin-when-cross-origin"]];if(!embeddable)wanted.push(["X-Frame-Options","SAMEORIGIN"]);const missing=wanted.filter(([name])=>!response.headers.has(name));if(missing.length===0)return;try{for(const[name,value]of missing)response.headers.set(name,value);return}catch{const headers=new Headers(response.headers);for(const[name,value]of missing)headers.set(name,value);return new Response(response.body,{status:response.status,statusText:response.statusText,headers})}}export function __resetViewSecurityHeadersCache(){_isDisabledCache=undefined}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{createHash}from"node:crypto";import{existsSync,readFileSync,statSync}from"node:fs";import{join}from"node:path";import process from"node:process";import{log}from"@stacksjs/logging/runtime";import{path}from"@stacksjs/path";import{frameworkDefaultsDir}from"./imports";export const SECURITY_DEFAULT_FILES=Object.freeze(["Middleware/Auth.ts","Middleware/Guest.ts","Middleware/Csrf.ts","Middleware/Cors.ts","Middleware/Throttle.ts","Middleware/Signed.ts","Middleware/Abilities.ts","Middleware/Can.ts","Middleware/Permission.ts","Middleware/Role.ts","Middleware/EnsureEmailIsVerified.ts","Actions/Auth/LoginAction.ts","Actions/Auth/LogoutAction.ts","Actions/Auth/LogoutAllAction.ts","Actions/Auth/RegisterAction.ts","Actions/Auth/RefreshTokenAction.ts","Actions/Auth/VerifyTwoFactorLoginAction.ts","Actions/Auth/VerifyEmailAction.ts","Actions/Auth/MagicLinkSendAction.ts","Actions/Auth/MagicLinkConsumeAction.ts","Actions/Auth/PasskeyAuthenticationAction.ts","Actions/Auth/VerifyAuthenticationAction.ts","Actions/Auth/SocialRedirectAction.ts","Actions/Auth/SocialCallbackAction.ts","Actions/Auth/SessionHandoffAction.ts","Actions/Auth/social-flow.ts","Actions/Auth/token-request.ts","Actions/Auth/CreateTokenAction.ts","Actions/Auth/RevokeTokenAction.ts","Actions/Auth/OAuthAuthorizationAction.ts","Actions/Auth/OAuthTokenAction.ts","Actions/Auth/oauth-request.ts","Actions/Password/SendPasswordResetEmailAction.ts","Actions/Password/VerifyResetTokenAction.ts","Actions/Password/PasswordResetAction.ts"])
|
|
2
|
-
`)}let warned
|
|
1
|
+
import{createHash}from"node:crypto";import{existsSync,readFileSync,statSync}from"node:fs";import{join}from"node:path";import process from"node:process";import{log}from"@stacksjs/logging/runtime";import{path}from"@stacksjs/path";import{frameworkDefaultsDir}from"./imports";export const SECURITY_DEFAULT_FILES=Object.freeze(["Middleware/Auth.ts","Middleware/Guest.ts","Middleware/Csrf.ts","Middleware/Cors.ts","Middleware/Throttle.ts","Middleware/Signed.ts","Middleware/Abilities.ts","Middleware/Can.ts","Middleware/Permission.ts","Middleware/Role.ts","Middleware/EnsureEmailIsVerified.ts","Actions/Auth/LoginAction.ts","Actions/Auth/LogoutAction.ts","Actions/Auth/LogoutAllAction.ts","Actions/Auth/RegisterAction.ts","Actions/Auth/RefreshTokenAction.ts","Actions/Auth/VerifyTwoFactorLoginAction.ts","Actions/Auth/VerifyEmailAction.ts","Actions/Auth/MagicLinkSendAction.ts","Actions/Auth/MagicLinkConsumeAction.ts","Actions/Auth/PasskeyAuthenticationAction.ts","Actions/Auth/VerifyAuthenticationAction.ts","Actions/Auth/SocialRedirectAction.ts","Actions/Auth/SocialCallbackAction.ts","Actions/Auth/SessionHandoffAction.ts","Actions/Auth/social-flow.ts","Actions/Auth/token-request.ts","Actions/Auth/CreateTokenAction.ts","Actions/Auth/RevokeTokenAction.ts","Actions/Auth/OAuthAuthorizationAction.ts","Actions/Auth/OAuthTokenAction.ts","Actions/Auth/oauth-request.ts","Actions/Password/SendPasswordResetEmailAction.ts","Actions/Password/VerifyResetTokenAction.ts","Actions/Password/PasswordResetAction.ts"]);export const SHADOWED_DEFAULT_REVIEW_MARKER="stacks-reviewed-default:";export const SHADOWED_DEFAULTS_ENV="STACKS_SHADOWED_DEFAULTS_WARN";export function defaultFingerprint(contents){return createHash("sha256").update(contents).digest("hex").slice(0,16)}function isFile(file){try{return statSync(file).isFile()}catch{return false}}function sameBytes(a,b){if(a.byteLength!==b.byteLength)return false;for(let i=0;i<a.byteLength;i++){if(a[i]!==b[i])return false}return true}export function findShadowedSecurityDefaults(appDir,defaultsDir,files=SECURITY_DEFAULT_FILES){const found=[];for(const relative of files){const appFile=join(appDir,relative);const defaultFile=join(defaultsDir,relative);try{if(!isFile(appFile)||!isFile(defaultFile))continue;const own=readFileSync(appFile);const framework=readFileSync(defaultFile);const fingerprint=defaultFingerprint(framework);if(sameBytes(own,framework)){found.push({path:relative,kind:"identical",appFile,defaultFile,fingerprint});continue}if(own.toString("utf8").includes(`${SHADOWED_DEFAULT_REVIEW_MARKER} ${fingerprint}`))continue;found.push({path:relative,kind:"modified",appFile,defaultFile,fingerprint})}catch{}}return found}export function describeShadowedSecurityDefaults(entries){const lines=entries.map((entry)=>{if(entry.kind==="identical")return` - app/${entry.path} is an unchanged copy of the framework default. Delete it to receive security fixes.`;return` - app/${entry.path} differs from the framework default (${entry.defaultFile}). `+`Review it against the current default; once reviewed, add the comment \`// ${SHADOWED_DEFAULT_REVIEW_MARKER} ${entry.fingerprint}\` to it.`});return[`[security] ${entries.length} app/ file${entries.length===1?"":"s"} shadow${entries.length===1?"s":""} a framework security default, so framework security fixes to ${entries.length===1?"it do":"them do"} not reach this app:`,...lines,` Set ${SHADOWED_DEFAULTS_ENV}=false to silence this warning.`].join(`
|
|
2
|
+
`)}let warned=false;export function warnShadowedSecurityDefaults(options={}){if(warned&&!options.force)return[];warned=true;if(String(process.env[SHADOWED_DEFAULTS_ENV]??"").toLowerCase()==="false")return[];try{const appDir=options.appDir??path.appPath();const defaultsDir=options.defaultsDir??frameworkDefaultsDir("app");if(!appDir||!defaultsDir||!existsSync(appDir)||!existsSync(defaultsDir))return[];const found=findShadowedSecurityDefaults(appDir,defaultsDir);if(found.length>0)(options.warn??((message)=>log.warn(message)))(describeShadowedSecurityDefaults(found));return found}catch{return[]}}
|
package/dist/start.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
globalThis.__STACKS_BINARY_MODE__
|
|
1
|
+
globalThis.__STACKS_BINARY_MODE__=true;import{appRouteRegistry,assertRouteMiddlewareResolvable,loadRoutes,serve}from"@stacksjs/router";import{reportStripeAvailability}from"@stacksjs/payments";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)}reportStripeAvailability();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.75.
|
|
5
|
+
"version": "0.75.518",
|
|
6
6
|
"description": "Local development and production-ready.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -58,22 +58,22 @@
|
|
|
58
58
|
"prepublishOnly": "bun run build"
|
|
59
59
|
},
|
|
60
60
|
"dependencies": {
|
|
61
|
-
"@stacksjs/auth": "0.75.
|
|
61
|
+
"@stacksjs/auth": "0.75.518",
|
|
62
62
|
"@stacksjs/bun-router": "^0.1.24",
|
|
63
|
-
"@stacksjs/config": "0.75.
|
|
64
|
-
"@stacksjs/events": "0.75.
|
|
65
|
-
"@stacksjs/i18n": "0.75.
|
|
66
|
-
"@stacksjs/logging": "0.75.
|
|
67
|
-
"@stacksjs/orm": "0.75.
|
|
68
|
-
"@stacksjs/path": "0.75.
|
|
69
|
-
"@stacksjs/payments": "0.75.
|
|
70
|
-
"@stacksjs/router": "0.75.
|
|
71
|
-
"@stacksjs/storage": "0.75.
|
|
63
|
+
"@stacksjs/config": "0.75.518",
|
|
64
|
+
"@stacksjs/events": "0.75.518",
|
|
65
|
+
"@stacksjs/i18n": "0.75.518",
|
|
66
|
+
"@stacksjs/logging": "0.75.518",
|
|
67
|
+
"@stacksjs/orm": "0.75.518",
|
|
68
|
+
"@stacksjs/path": "0.75.518",
|
|
69
|
+
"@stacksjs/payments": "0.75.518",
|
|
70
|
+
"@stacksjs/router": "0.75.518",
|
|
71
|
+
"@stacksjs/storage": "0.75.518",
|
|
72
72
|
"@stacksjs/stx": "0.2.807",
|
|
73
73
|
"bun-plugin-auto-imports": "^0.4.4"
|
|
74
74
|
},
|
|
75
75
|
"devDependencies": {
|
|
76
|
-
"@stacksjs/validation": "0.75.
|
|
76
|
+
"@stacksjs/validation": "0.75.518",
|
|
77
77
|
"better-dx": "^0.2.24"
|
|
78
78
|
}
|
|
79
79
|
}
|