barejs 0.1.57 → 0.1.59

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/src/core/bare.ts CHANGED
@@ -9,6 +9,19 @@ import { BARE_CONFIG } from "./config";
9
9
  import { generateOpenAPISpec, renderDocsHTML, type OpenAPIOptions } from "../utils/openapi";
10
10
  import type { RouteSchemas } from "../security/validators";
11
11
  import type { RouteSchema } from "../client/index";
12
+ import { runtime, type ServerHandle } from "../runtime";
13
+ import { type WebSocketRouteHandler } from "./ws-match";
14
+
15
+ export type { WebSocketRouteHandler };
16
+
17
+ export function normalizePoolSize(
18
+ poolSize: number,
19
+ defaultSize = 1024,
20
+ maximumSize = 65_536
21
+ ): number {
22
+ const requested = Number.isFinite(poolSize) ? Math.floor(poolSize) : defaultSize;
23
+ return Math.min(maximumSize, Math.max(0, requested));
24
+ }
12
25
 
13
26
  export interface CronOptions {
14
27
  /** Execute the cron job immediately upon registration (default: false) */
@@ -17,13 +30,6 @@ export interface CronOptions {
17
30
  onError?: (err: any) => void;
18
31
  }
19
32
 
20
- export interface WebSocketRouteHandler {
21
- open?: (ws: any) => void;
22
- message?: (ws: any, message: string | Buffer) => void;
23
- close?: (ws: any, code: number, reason: string) => void;
24
- drain?: (ws: any) => void;
25
- }
26
-
27
33
  export interface NotFoundResponse {
28
34
  status: number;
29
35
  message: string;
@@ -64,19 +70,31 @@ export class BareJS<
64
70
  > extends BareRouter<Routes> {
65
71
  declare readonly __routes: Routes;
66
72
  private tree = new RadixNode();
67
- private pool: Context[] = [];
73
+ private pool: Array<Context | undefined> = [];
74
+ private readonly _poolState = { top: 0 };
75
+ private readonly maxPool: number;
68
76
  // private poolIdx = 0;
69
77
  private hotFetch?: (req: Request, peerIp?: string) => any;
70
78
  private compiled = false;
71
79
  private _useLog: boolean = false;
72
80
  private _trustProxyBox = { val: false };
81
+
82
+ protected override _onRouteMutate(): void {
83
+ if (this.compiled) {
84
+ this.compiled = false;
85
+ this.fetch = this._lazyFetch;
86
+ }
87
+ }
73
88
  private errorHandler?: (err: any, ctx: Context) => any;
74
89
  private wsRoutes = new Map<string, WebSocketRouteHandler>();
75
90
  private startHooks: (() => void | Promise<void>)[] = [];
76
91
  private stopHooks: (() => void | Promise<void>)[] = [];
92
+ private drainHooks: (() => void | Promise<void>)[] = [];
77
93
  private crons: Array<{ name: string; timer: ReturnType<typeof setInterval> }> = [];
78
- private server?: ReturnType<typeof Bun.serve>;
94
+ private server?: ServerHandle;
79
95
  private shutdownHandler?: () => Promise<void>;
96
+ private ipcDrainHandler?: (msg: any) => void;
97
+ private _draining = false;
80
98
  private wsAdapter = {
81
99
  open(ws: any) { ws.data?.open?.(ws); },
82
100
  message(ws: any, msg: any) { ws.data?.message?.(ws, msg); },
@@ -86,6 +104,7 @@ export class BareJS<
86
104
 
87
105
  public useLog(enabled: boolean = true): this {
88
106
  this._useLog = enabled;
107
+ this._onRouteMutate();
89
108
  return this;
90
109
  }
91
110
 
@@ -99,6 +118,28 @@ export class BareJS<
99
118
  return this;
100
119
  }
101
120
 
121
+ public onDrain(fn: () => void | Promise<void>): this {
122
+ this.drainHooks.push(fn);
123
+ return this;
124
+ }
125
+
126
+ /**
127
+ * Gracefully drains the server by running all onDrain hooks and stopping
128
+ * the server while allowing in-flight requests to complete.
129
+ */
130
+ public async drain(closeActiveConnections = false): Promise<void> {
131
+ if (this._draining) return;
132
+ this._draining = true;
133
+ for (const hook of this.drainHooks) {
134
+ try {
135
+ await hook();
136
+ } catch (e) {
137
+ console.error(`[${this.name}] onDrain error:`, e);
138
+ }
139
+ }
140
+ await this.stop(closeActiveConnections);
141
+ }
142
+
102
143
  /**
103
144
  * Built-in overlap-safe background interval scheduler.
104
145
  * Automatically cleared when app.stop() is called.
@@ -143,6 +184,10 @@ export class BareJS<
143
184
  process.off("SIGTERM", this.shutdownHandler);
144
185
  this.shutdownHandler = undefined;
145
186
  }
187
+ if (this.ipcDrainHandler) {
188
+ process.off("message", this.ipcDrainHandler);
189
+ this.ipcDrainHandler = undefined;
190
+ }
146
191
  if (this.server) {
147
192
  this.server.stop(closeActiveConnections);
148
193
  this.server = undefined;
@@ -155,13 +200,17 @@ export class BareJS<
155
200
  }
156
201
  }
157
202
  }
158
- constructor(poolSize: number = 1024) {
203
+ private static readonly DEFAULT_POOL_SIZE = 1024;
204
+ private static readonly MAX_POOL_SIZE = 65_536;
205
+
206
+ constructor(poolSize: number = BareJS.DEFAULT_POOL_SIZE) {
159
207
  super();
160
208
  bootstrapConfig();
161
- const size = Math.pow(2, Math.ceil(Math.log2(poolSize)));
162
- for (let i = 0; i < size; i++) {
163
- this.pool.push(new Context());
164
- }
209
+ this.maxPool = normalizePoolSize(
210
+ poolSize,
211
+ BareJS.DEFAULT_POOL_SIZE,
212
+ BareJS.MAX_POOL_SIZE
213
+ );
165
214
  try {
166
215
  const pkgPath = join(process.cwd(), "package.json");
167
216
  const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
@@ -182,10 +231,12 @@ export class BareJS<
182
231
  });
183
232
  public setNotFound(handler: () => NotFoundResponse) {
184
233
  this.notFoundHandler = handler;
234
+ this._onRouteMutate();
185
235
  }
186
236
 
187
237
  public onError(handler: (err: any, ctx: Context) => any): this {
188
238
  this.errorHandler = handler;
239
+ this._onRouteMutate();
189
240
  return this;
190
241
  }
191
242
 
@@ -662,9 +713,18 @@ export class BareJS<
662
713
  const isLog = this._useLog;
663
714
  this.tree = new RadixNode();
664
715
  const explicitOptionsPaths = new Set<string>();
716
+ const staticRoutesList: Array<{ path: string; method: string; fn: Function }> = [];
717
+ const normStatic = (p: string) => {
718
+ const c = p.replace(/\/+/g, '/');
719
+ return c.length > 1 && c.endsWith('/') ? c.slice(0, -1) : (c || '/');
720
+ };
665
721
  for (const route of this.routes) {
666
722
  if (route.method === 'OPTIONS') explicitOptionsPaths.add(route.path);
667
- this.tree.insert(route.path, route.method, this.compileHandler(route.handlers, isLog));
723
+ const compiledFn = this.compileHandler(route.handlers, isLog);
724
+ this.tree.insert(route.path, route.method, compiledFn);
725
+ if (!route.path.includes(':') && !route.path.includes('*')) {
726
+ staticRoutesList.push({ path: normStatic(route.path), method: route.method, fn: compiledFn });
727
+ }
668
728
  }
669
729
  for (const route of this.routes) {
670
730
  if (route.method === 'OPTIONS' || explicitOptionsPaths.has(route.path)) continue;
@@ -681,13 +741,17 @@ export class BareJS<
681
741
  ...route.handlers.slice(0, lastCorsIdx + 1).filter((h: any, idx: number) => idx === lastCorsIdx || !h?.__isCors),
682
742
  () => new Response(null, { status: 204 })
683
743
  ];
684
- this.tree.insert(route.path, 'OPTIONS', this.compileHandler(preflightPipeline, isLog));
744
+ const preflightFn = this.compileHandler(preflightPipeline, isLog);
745
+ this.tree.insert(route.path, 'OPTIONS', preflightFn);
746
+ if (!route.path.includes(':') && !route.path.includes('*')) {
747
+ staticRoutesList.push({ path: normStatic(route.path), method: 'OPTIONS', fn: preflightFn });
748
+ }
685
749
  }
686
750
  }
687
751
 
688
752
  const tree = this.tree;
689
753
  const pool = this.pool;
690
- const maxPool = pool.length;
754
+ const maxPool = this.maxPool;
691
755
  const hNotFound = this.notFoundHandler;
692
756
  const customError = this.errorHandler;
693
757
  const applyCtxHeaders = (res: Response, ctx: Context): Response => {
@@ -755,9 +819,13 @@ export class BareJS<
755
819
  };
756
820
 
757
821
  const hoistedHandlers: Function[] = [];
822
+ const handlerToName = new Map<Function, string>();
758
823
  const register = (h: Function) => {
824
+ const existing = handlerToName.get(h);
825
+ if (existing) return existing;
759
826
  const name = `h${hoistedHandlers.length}`;
760
827
  hoistedHandlers.push(h);
828
+ handlerToName.set(h, name);
761
829
  return name;
762
830
  };
763
831
 
@@ -773,26 +841,60 @@ export class BareJS<
773
841
  ? `if (ctx._idempotencyKey) { if (ctx._idemInFlight) ctx._idemInFlight.delete(ctx._idempotencyKey); ctx._idempotencyKey = undefined; ctx._idemInFlight = undefined; }`
774
842
  : '';
775
843
 
844
+ const isDevUaf = process.env.NODE_ENV === 'development' || !process.env.NODE_ENV;
845
+ const ctxVar = isDevUaf ? 'rawCtx' : 'ctx';
846
+ const wrapUaf = isDevUaf
847
+ ? (rawCtx: Context, state: { released: boolean }): Context => {
848
+ const warn = (prop: string | symbol) => {
849
+ console.warn(
850
+ `[BareJS] Use-after-free detected: Context.${String(prop)} accessed after response was sent and Context was released to pool.`
851
+ );
852
+ };
853
+ const proxy: any = new Proxy(rawCtx, {
854
+ get(target: any, prop) {
855
+ if (state.released && prop !== Symbol.toStringTag && prop !== 'then') {
856
+ warn(prop);
857
+ }
858
+ const val = target[prop];
859
+ if (typeof val === 'function') {
860
+ return function (this: any, ...args: any[]) {
861
+ const ret = val.apply(target, args);
862
+ return ret === target ? proxy : ret;
863
+ };
864
+ }
865
+ return val;
866
+ },
867
+ set(target: any, prop, value) {
868
+ if (state.released) warn(prop);
869
+ target[prop] = value;
870
+ return true;
871
+ }
872
+ });
873
+ return proxy;
874
+ }
875
+ : undefined;
876
+
776
877
  const releaseCode = `
777
- if (!ctx._detached) {
778
- if (ctx.store.size > 0) ctx.store.clear();
779
- ${deriveCleanup}
780
- ${idemCleanup}
781
- ctx.req = undefined;
782
- ctx._status = 200;
783
- ctx.body = undefined;
784
- ctx._query = undefined;
785
- ctx._cookies = undefined;
786
- ctx._setCookies = undefined;
787
- ctx._headers = undefined;
788
- ctx._requestId = undefined;
789
- ctx._peerIp = undefined;
790
- ctx.params = EMPTY_PARAMS;
791
- if (poolTop < maxPool) pool[poolTop++] = ctx;
878
+ if (!${ctxVar}._detached) {
879
+ ${isDevUaf ? '_uaf.released = true;' : ''}
880
+ if (${ctxVar}.store.size > 0) ${ctxVar}.store.clear();
881
+ ${deriveCleanup.replaceAll('ctx.', `${ctxVar}.`).replaceAll('[ctx.', `[${ctxVar}.`)}
882
+ ${idemCleanup.replaceAll('ctx.', `${ctxVar}.`)}
883
+ ${ctxVar}.req = undefined;
884
+ ${ctxVar}._status = 200;
885
+ ${ctxVar}.body = undefined;
886
+ ${ctxVar}._query = undefined;
887
+ ${ctxVar}._cookies = undefined;
888
+ ${ctxVar}._setCookies = undefined;
889
+ ${ctxVar}._headers = undefined;
890
+ ${ctxVar}._requestId = undefined;
891
+ ${ctxVar}._peerIp = undefined;
892
+ ${ctxVar}.params = EMPTY_PARAMS;
893
+ if (poolState.top < maxPool) pool[poolState.top++] = ${ctxVar};
792
894
  }
793
895
  `;
794
896
 
795
- const handleErrCode = `const errRes = hError(e, ctx);
897
+ const handleErrCode = `const errRes = hError(e, ${ctxVar});
796
898
  if (errRes && errRes.then) return errRes.then((r) => { ${isLog ? 'doLog(r.status || 500);' : ''} ${releaseCode} return r; });
797
899
  ${isLog ? 'doLog(errRes.status || 500);' : ''}
798
900
  ${releaseCode}
@@ -800,17 +902,54 @@ export class BareJS<
800
902
 
801
903
  const callSuffix = isLog ? '(ctx, doLog)' : '(ctx)';
802
904
  const useCompactEmit = this.routes.length > 16;
803
- const routerCode = tree.jitCompile(register, 0, 'url', 's', [], (hName: string) =>
905
+ const relArgs = isDevUaf ? 'rawCtx, _uaf' : 'ctx';
906
+ const errArgs = isDevUaf ? `e, rawCtx, _uaf${isLog ? ', doLog' : ''}` : `e, ctx${isLog ? ', doLog' : ''}`;
907
+ const emitInvoke = (hName: string) =>
804
908
  useCompactEmit
805
909
  ? `out = ${hName}${callSuffix};
806
- if (out && out.then) return out.then((v) => { _rel(ctx); return v; }, (e) => _onErr(e, ctx${isLog ? ', doLog' : ''}));
807
- _rel(ctx);
910
+ if (out && out.then) return out.then((v) => { _rel(${relArgs}); return v; }, (e) => _onErr(${errArgs}));
911
+ _rel(${relArgs});
808
912
  return out;`
809
913
  : `out = ${hName}${callSuffix};
810
914
  if (out && out.then) return out.then((v) => { ${releaseCode} return v; }, (e) => { ${handleErrCode} });
811
915
  ${releaseCode}
812
- return out;`
813
- );
916
+ return out;`;
917
+
918
+ const routerCode = tree.jitCompile(register, 0, 'url', 's', [], emitInvoke);
919
+
920
+ let staticFastPathCode = '';
921
+ if (staticRoutesList.length > 0) {
922
+ const grouped = new Map<string, Map<string, string>>();
923
+ for (const entry of staticRoutesList) {
924
+ const hName = handlerToName.get(entry.fn);
925
+ if (!hName) continue;
926
+ let mMap = grouped.get(entry.path);
927
+ if (!mMap) {
928
+ mMap = new Map<string, string>();
929
+ grouped.set(entry.path, mMap);
930
+ }
931
+ mMap.set(entry.method, hName);
932
+ }
933
+ if (grouped.size > 0) {
934
+ let cases = '';
935
+ for (const [p, mMap] of grouped) {
936
+ let mCases = '';
937
+ let allHandler: string | undefined;
938
+ for (const [m, hName] of mMap) {
939
+ if (m === 'ALL') {
940
+ allHandler = hName;
941
+ } else {
942
+ mCases += `case ${JSON.stringify(m)}: ${emitInvoke(hName)}\n`;
943
+ }
944
+ }
945
+ if (allHandler) {
946
+ mCases += `default: ${emitInvoke(allHandler)}\n`;
947
+ }
948
+ cases += `case ${JSON.stringify(p)}:\n switch (method) {\n ${mCases} }\n break;\n`;
949
+ }
950
+ staticFastPathCode = `switch (rawPath) {\n${cases}}`;
951
+ }
952
+ }
814
953
 
815
954
  const hNames = hoistedHandlers.map((_, i) => `h${i}`);
816
955
 
@@ -909,9 +1048,10 @@ export class BareJS<
909
1048
  }
910
1049
  : undefined;
911
1050
 
1051
+ const poolState = this._poolState;
912
1052
  const trustProxyBox = this._trustProxyBox;
913
- const args = ['pool', 'maxPool', 'Context', 'hNotFound', 'hError', 'applyCtxHeaders', 'EMPTY_PARAMS', 'trustProxyBox', ...(hasGlobalMw ? ['runGlobalOptions'] : []), ...(hasStaticMw ? ['runStatic'] : []), ...(apply404Cors ? ['apply404Cors'] : []), ...hNames];
914
- const values = [pool, maxPool, Context, hNotFound, hError, applyCtxHeaders, EMPTY_PARAMS, trustProxyBox, ...(hasGlobalMw ? [runGlobalOptions] : []), ...(hasStaticMw ? [runStatic] : []), ...(apply404Cors ? [apply404Cors] : []), ...hoistedHandlers];
1053
+ const args = ['pool', 'poolState', 'maxPool', 'Context', 'hNotFound', 'hError', 'applyCtxHeaders', 'EMPTY_PARAMS', 'trustProxyBox', ...(isDevUaf ? ['wrapUaf'] : []), ...(hasGlobalMw ? ['runGlobalOptions'] : []), ...(hasStaticMw ? ['runStatic'] : []), ...(apply404Cors ? ['apply404Cors'] : []), ...hNames];
1054
+ const values = [pool, poolState, maxPool, Context, hNotFound, hError, applyCtxHeaders, EMPTY_PARAMS, trustProxyBox, ...(isDevUaf ? [wrapUaf] : []), ...(hasGlobalMw ? [runGlobalOptions] : []), ...(hasStaticMw ? [runStatic] : []), ...(apply404Cors ? [apply404Cors] : []), ...hoistedHandlers];
915
1055
 
916
1056
  const logInit = isLog ? `
917
1057
  const start = performance.now();
@@ -928,27 +1068,37 @@ export class BareJS<
928
1068
 
929
1069
  const compactHelpers = useCompactEmit
930
1070
  ? `
931
- const _rel = (ctx) => { ${releaseCode} };
932
- const _onErr = (e, ctx${isLog ? ', doLog' : ''}) => { ${handleErrCode} };`
1071
+ const _rel = (${relArgs}) => { ${releaseCode} };
1072
+ const _onErr = (${errArgs}) => { ${handleErrCode} };`
933
1073
  : '';
934
- const fnBody = `
935
- let poolTop = maxPool;${compactHelpers}
1074
+ const fnBody = `${compactHelpers}
936
1075
  return function(req, peerIp) {
937
1076
  const url = req.url;
938
1077
  let s = url.indexOf('/', 8);
939
1078
  const q = s === -1 ? -1 : url.indexOf('?', s);
940
1079
  const urlLen = q === -1 ? url.length : q;
1080
+ ${staticFastPathCode ? "const rawPath = s === -1 ? '/' : url.slice(s, urlLen);" : ''}
941
1081
  if (s !== -1) s++;
942
1082
  else s = urlLen;
943
1083
 
944
1084
  const method = req.method;
945
- const ctx = poolTop > 0 ? pool[--poolTop] : new Context(trustProxyBox.val);
1085
+ let ${ctxVar};
1086
+ if (poolState.top > 0) {
1087
+ const slot = --poolState.top;
1088
+ ${ctxVar} = pool[slot];
1089
+ pool[slot] = undefined;
1090
+ } else {
1091
+ ${ctxVar} = new Context(trustProxyBox.val);
1092
+ }
1093
+ ${isDevUaf ? 'const _uaf = { released: false }; const ctx = wrapUaf(rawCtx, _uaf);' : ''}
946
1094
  let out;
947
1095
  ${logInit}
948
1096
 
949
1097
  try {
950
- ctx.req = req;
951
- ctx._peerIp = peerIp;
1098
+ ${ctxVar}.req = req;
1099
+ ${ctxVar}._peerIp = peerIp;
1100
+
1101
+ ${staticFastPathCode}
952
1102
 
953
1103
  ${routerCode}
954
1104
 
@@ -958,7 +1108,7 @@ export class BareJS<
958
1108
 
959
1109
  const errorBody = hNotFound();
960
1110
  const status = errorBody.status || 404;
961
- const nfRes = ${apply404Cors ? 'apply404Cors(Response.json(errorBody, { status }), ctx)' : 'applyCtxHeaders(Response.json(errorBody, { status }), ctx)'};
1111
+ const nfRes = ${apply404Cors ? `apply404Cors(Response.json(errorBody, { status }), ${ctxVar})` : `applyCtxHeaders(Response.json(errorBody, { status }), ${ctxVar})`};
962
1112
  ${isLog ? 'doLog(status);' : ''}
963
1113
  ${releaseCode}
964
1114
  return nfRes;
@@ -966,7 +1116,7 @@ export class BareJS<
966
1116
  } catch (e) {
967
1117
  ${handleErrCode}
968
1118
  }
969
- }
1119
+ };
970
1120
  `;
971
1121
 
972
1122
  this.hotFetch = new Function(...args, fnBody)(...values);
@@ -974,7 +1124,7 @@ export class BareJS<
974
1124
  this.fetch = this.hotFetch!;
975
1125
  }
976
1126
 
977
- public fetch = (req: Request, peerIp?: string): any => {
1127
+ private readonly _lazyFetch = (req: Request, peerIp?: string): any => {
978
1128
  if (!this.compiled) {
979
1129
  this.compile();
980
1130
  return this.hotFetch!(req, peerIp);
@@ -982,6 +1132,8 @@ export class BareJS<
982
1132
  return this.hotFetch!(req, peerIp);
983
1133
  };
984
1134
 
1135
+ public fetch = this._lazyFetch;
1136
+
985
1137
  /**
986
1138
  * Ergonomic in-memory request helper for testing or internal invocations.
987
1139
  * Normalizes relative paths to http://localhost and delegates to this.fetch(req).
@@ -1001,7 +1153,8 @@ export class BareJS<
1001
1153
  public trustProxy(enabled: boolean = true): this {
1002
1154
  this._trustProxyBox.val = enabled;
1003
1155
  for (let i = 0; i < this.pool.length; i++) {
1004
- this.pool[i]!._trustProxy = enabled;
1156
+ const ctx = this.pool[i];
1157
+ if (ctx) ctx._trustProxy = enabled;
1005
1158
  }
1006
1159
  return this;
1007
1160
  }
@@ -1030,75 +1183,25 @@ export class BareJS<
1030
1183
  \x1b[33m |____/ \\__,_|_| \\___| \\___/|_____|\x1b[0m
1031
1184
 
1032
1185
  \x1b[32m🚀 ${this.name} is running in development mode\x1b[0m
1033
- \x1b[90m⚙️ Pool Size: ${this.pool.length} | JIT: Enabled | Port: ${finalPort}\x1b[0m
1186
+ \x1b[90m⚙️ Runtime: ${runtime.name} | Pool Size: ${this.maxPool} | JIT: Enabled | Port: ${finalPort}\x1b[0m
1034
1187
  \x1b[36m🛡️ Hash: ${BARE_CONFIG.hash.algorithm} (${BARE_CONFIG.hash.memoryCost / 1024}MB) | Iterations: ${BARE_CONFIG.hash.timeCost}\x1b[0m
1035
1188
  `);
1036
1189
  }
1037
1190
 
1038
1191
  const wsRoutes = this.wsRoutes;
1039
- const baseFetch = this.fetch;
1192
+ const self = this;
1040
1193
  const hasWs = wsRoutes.size > 0;
1041
1194
 
1042
- const server = hasWs
1043
- ? Bun.serve<WebSocketRouteHandler>({
1044
- port: finalPort,
1045
- hostname,
1046
- reusePort,
1047
- maxRequestBodySize,
1048
- fetch(req: Request, srv: any) {
1049
- if (req.headers.get('upgrade')?.toLowerCase() === 'websocket') {
1050
- const url = req.url;
1051
- const s = url.indexOf('/', 8);
1052
- const q = s === -1 ? -1 : url.indexOf('?', s);
1053
- const path = s === -1 ? '/' : (q === -1 ? url.slice(s) : url.slice(s, q));
1054
- const collapsed = path.replace(/\/+/g, '/');
1055
- const normalized = collapsed.length > 1 && collapsed.endsWith('/') ? collapsed.slice(0, -1) : collapsed;
1056
- let handler = wsRoutes.get(normalized);
1057
- let params: Record<string, string> | undefined;
1058
- if (!handler) {
1059
- const reqParts = normalized.split('/').filter(Boolean);
1060
- for (const [pattern, h] of wsRoutes) {
1061
- if (!pattern.includes(':') && !pattern.includes('*')) continue;
1062
- const patParts = pattern.split('/').filter(Boolean);
1063
- const matched: Record<string, string> = {};
1064
- let ok = true;
1065
- for (let i = 0; i < patParts.length; i++) {
1066
- const pp = patParts[i]!;
1067
- if (pp === '*') {
1068
- matched['*'] = reqParts.slice(i).join('/');
1069
- break;
1070
- }
1071
- if (i >= reqParts.length) { ok = false; break; }
1072
- if (pp.startsWith(':')) {
1073
- matched[pp.slice(1)] = reqParts[i]!;
1074
- } else if (pp !== reqParts[i]) {
1075
- ok = false; break;
1076
- }
1077
- }
1078
- if (ok && (patParts.includes('*') || patParts.length === reqParts.length)) {
1079
- handler = h;
1080
- params = matched;
1081
- break;
1082
- }
1083
- }
1084
- }
1085
- if (handler && srv.upgrade(req, { data: params ? { ...handler, params } : handler })) {
1086
- return undefined as any;
1087
- }
1088
- }
1089
- return baseFetch(req, srv?.requestIP?.(req)?.address);
1090
- },
1091
- websocket: this.wsAdapter
1092
- })
1093
- : Bun.serve({
1094
- port: finalPort,
1095
- hostname,
1096
- reusePort,
1097
- maxRequestBodySize,
1098
- fetch(req: Request, srv: any) {
1099
- return baseFetch(req, srv?.requestIP?.(req)?.address);
1100
- }
1101
- });
1195
+ const server = runtime.serve({
1196
+ port: finalPort,
1197
+ hostname,
1198
+ reusePort,
1199
+ maxRequestBodySize,
1200
+ fetch(req: Request, peerIp?: string) {
1201
+ return self.fetch(req, peerIp);
1202
+ },
1203
+ ws: hasWs ? { routes: wsRoutes, adapter: this.wsAdapter } : undefined
1204
+ });
1102
1205
 
1103
1206
  this.server = server;
1104
1207
  for (const hook of this.startHooks) {
@@ -1123,10 +1226,20 @@ export class BareJS<
1123
1226
  process.exit(0);
1124
1227
  };
1125
1228
 
1229
+ this._draining = false;
1126
1230
  this.shutdownHandler = shutdown;
1127
1231
  process.on("SIGINT", shutdown);
1128
1232
  process.on("SIGTERM", shutdown);
1129
- return server;
1233
+
1234
+ const onIpcMessage = async (msg: any) => {
1235
+ if (msg === "DRAIN_REQUEST" || msg?.type === "DRAIN_REQUEST") {
1236
+ await this.drain(false);
1237
+ process.exit(0);
1238
+ }
1239
+ };
1240
+ this.ipcDrainHandler = onIpcMessage;
1241
+ process.on("message", onIpcMessage);
1242
+ return server.raw;
1130
1243
  }
1131
1244
  }
1132
1245