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/README.md +66 -37
- package/dist/index.js +208 -186
- package/dist/node.js +362 -0
- package/dist/types/core/bare.d.ts +19 -7
- package/dist/types/core/context.d.ts +24 -0
- package/dist/types/core/router.d.ts +1 -0
- package/dist/types/core/ws-match.d.ts +15 -0
- package/dist/types/index.d.ts +2 -2
- package/dist/types/node.d.ts +1 -0
- package/dist/types/runtime/bun.d.ts +2 -0
- package/dist/types/runtime/index.d.ts +10 -0
- package/dist/types/runtime/node.d.ts +2 -0
- package/dist/types/runtime/types.d.ts +44 -0
- package/llms.txt +7 -4
- package/package.json +43 -7
- package/src/core/bare.ts +227 -114
- package/src/core/context.ts +293 -1
- package/src/core/loader.ts +5 -3
- package/src/core/router.ts +6 -0
- package/src/core/ws-match.ts +60 -0
- package/src/index.ts +4 -2
- package/src/node.ts +6 -0
- package/src/runtime/bun.ts +87 -0
- package/src/runtime/index.ts +24 -0
- package/src/runtime/node.ts +333 -0
- package/src/runtime/types.ts +49 -0
- package/src/security/hash.ts +3 -6
- package/src/security/idempotency.ts +3 -1
- package/src/utils/compress.ts +4 -3
- package/src/utils/static.ts +3 -2
package/src/core/context.ts
CHANGED
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
import { createHmac, timingSafeEqual } from 'node:crypto';
|
|
2
2
|
|
|
3
|
+
const _peek: ((p: any) => any) | undefined = (globalThis as any).Bun?.peek;
|
|
4
|
+
|
|
3
5
|
let _userStreamsCreated = 0;
|
|
4
6
|
const _userStreams = new WeakSet<ReadableStream>();
|
|
5
7
|
if (typeof globalThis.ReadableStream === 'function' && !(globalThis.ReadableStream as any).__bareTracked) {
|
|
@@ -61,6 +63,27 @@ export interface UploadResult {
|
|
|
61
63
|
files: UploadedFile[];
|
|
62
64
|
}
|
|
63
65
|
|
|
66
|
+
export interface UploadStreamOptions {
|
|
67
|
+
/** Max size per file in bytes (default: 100MB) */
|
|
68
|
+
maxFileSize?: number;
|
|
69
|
+
/** Max number of uploaded files (default: 10) */
|
|
70
|
+
maxFiles?: number;
|
|
71
|
+
/** Max size per text field in bytes (default: 1MB) */
|
|
72
|
+
maxFieldSize?: number;
|
|
73
|
+
/** Allowed MIME types (e.g. ['image/png', 'application/octet-stream']) */
|
|
74
|
+
allowedTypes?: string[];
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export interface UploadStreamPart {
|
|
78
|
+
type: 'file' | 'field';
|
|
79
|
+
fieldName: string;
|
|
80
|
+
filename?: string;
|
|
81
|
+
safeName?: string;
|
|
82
|
+
contentType?: string;
|
|
83
|
+
stream?: ReadableStream<Uint8Array>;
|
|
84
|
+
value?: string;
|
|
85
|
+
}
|
|
86
|
+
|
|
64
87
|
export class Context {
|
|
65
88
|
public req!: Request;
|
|
66
89
|
public params: Params = {};
|
|
@@ -333,7 +356,7 @@ export class Context {
|
|
|
333
356
|
);
|
|
334
357
|
}
|
|
335
358
|
const tp = this.req.text();
|
|
336
|
-
const peeked =
|
|
359
|
+
const peeked = _peek !== undefined ? _peek(tp) : tp;
|
|
337
360
|
if (typeof peeked === "string") {
|
|
338
361
|
try {
|
|
339
362
|
return this._parseAndSanitizeJson(peeked, maxBytes);
|
|
@@ -656,4 +679,273 @@ export class Context {
|
|
|
656
679
|
|
|
657
680
|
return { fields, files };
|
|
658
681
|
}
|
|
682
|
+
|
|
683
|
+
/**
|
|
684
|
+
* True streaming multipart/form-data parser.
|
|
685
|
+
* Streams file parts chunk-by-chunk with backpressure and constant O(chunk) memory usage.
|
|
686
|
+
*/
|
|
687
|
+
public async *uploadStream(options: UploadStreamOptions = {}): AsyncGenerator<UploadStreamPart> {
|
|
688
|
+
const maxFileSize = options.maxFileSize ?? 100 * 1024 * 1024;
|
|
689
|
+
const maxFiles = options.maxFiles ?? 10;
|
|
690
|
+
const maxFieldSize = options.maxFieldSize ?? 1024 * 1024;
|
|
691
|
+
const allowed = options.allowedTypes
|
|
692
|
+
? new Set(options.allowedTypes.map((t) => t.trim().toLowerCase()))
|
|
693
|
+
: null;
|
|
694
|
+
|
|
695
|
+
const ct = this.req?.headers?.get('content-type') || '';
|
|
696
|
+
if (!ct.toLowerCase().includes('multipart/form-data')) {
|
|
697
|
+
throw Object.assign(new Error('Expected multipart/form-data'), { status: 400 });
|
|
698
|
+
}
|
|
699
|
+
const bMatch = ct.match(/boundary=(?:"([^"]+)"|([^;\s]+))/i);
|
|
700
|
+
const boundary = bMatch?.[1] || bMatch?.[2];
|
|
701
|
+
if (!boundary) {
|
|
702
|
+
throw Object.assign(new Error('Missing multipart boundary'), { status: 400 });
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
if (!this.req.body) return;
|
|
706
|
+
|
|
707
|
+
const encoder = new TextEncoder();
|
|
708
|
+
const firstBoundary = encoder.encode(`--${boundary}`);
|
|
709
|
+
const partBoundary = encoder.encode(`\r\n--${boundary}`);
|
|
710
|
+
const crlfcrlf = encoder.encode('\r\n\r\n');
|
|
711
|
+
|
|
712
|
+
const indexOfBytes = (haystack: Uint8Array, needle: Uint8Array, from = 0): number => {
|
|
713
|
+
const nLen = needle.byteLength;
|
|
714
|
+
const limit = haystack.byteLength - nLen;
|
|
715
|
+
const first = needle[0]!;
|
|
716
|
+
let i = from;
|
|
717
|
+
while (i <= limit) {
|
|
718
|
+
const pos = haystack.indexOf(first, i);
|
|
719
|
+
if (pos === -1 || pos > limit) return -1;
|
|
720
|
+
let match = true;
|
|
721
|
+
for (let j = 1; j < nLen; j++) {
|
|
722
|
+
if (haystack[pos + j] !== needle[j]) {
|
|
723
|
+
match = false;
|
|
724
|
+
break;
|
|
725
|
+
}
|
|
726
|
+
}
|
|
727
|
+
if (match) return pos;
|
|
728
|
+
i = pos + 1;
|
|
729
|
+
}
|
|
730
|
+
return -1;
|
|
731
|
+
};
|
|
732
|
+
|
|
733
|
+
const concatBytes = (a: Uint8Array, b: Uint8Array): Uint8Array => {
|
|
734
|
+
if (a.byteLength === 0) return b;
|
|
735
|
+
if (b.byteLength === 0) return a;
|
|
736
|
+
const out = new Uint8Array(a.byteLength + b.byteLength);
|
|
737
|
+
out.set(a, 0);
|
|
738
|
+
out.set(b, a.byteLength);
|
|
739
|
+
return out;
|
|
740
|
+
};
|
|
741
|
+
|
|
742
|
+
const reader = this.req.body.getReader();
|
|
743
|
+
let buf: Uint8Array = new Uint8Array(0);
|
|
744
|
+
let eof = false;
|
|
745
|
+
|
|
746
|
+
const readMore = async (): Promise<boolean> => {
|
|
747
|
+
if (eof) return false;
|
|
748
|
+
const { done, value } = await reader.read();
|
|
749
|
+
if (done || !value) {
|
|
750
|
+
eof = true;
|
|
751
|
+
return false;
|
|
752
|
+
}
|
|
753
|
+
buf = concatBytes(buf, value);
|
|
754
|
+
return true;
|
|
755
|
+
};
|
|
756
|
+
|
|
757
|
+
const ensureBytes = async (minLen: number): Promise<boolean> => {
|
|
758
|
+
while (buf.byteLength < minLen) {
|
|
759
|
+
if (!(await readMore())) return false;
|
|
760
|
+
}
|
|
761
|
+
return true;
|
|
762
|
+
};
|
|
763
|
+
|
|
764
|
+
let fileCount = 0;
|
|
765
|
+
|
|
766
|
+
try {
|
|
767
|
+
// 1. Find initial boundary
|
|
768
|
+
while (true) {
|
|
769
|
+
const idx = indexOfBytes(buf, firstBoundary);
|
|
770
|
+
if (idx !== -1) {
|
|
771
|
+
buf = buf.subarray(idx + firstBoundary.byteLength);
|
|
772
|
+
break;
|
|
773
|
+
}
|
|
774
|
+
if (buf.byteLength > firstBoundary.byteLength) {
|
|
775
|
+
buf = buf.subarray(buf.byteLength - firstBoundary.byteLength);
|
|
776
|
+
}
|
|
777
|
+
if (!(await readMore())) {
|
|
778
|
+
throw Object.assign(new Error('Malformed multipart/form-data payload'), { status: 400 });
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
|
|
782
|
+
// Check for immediate closing "--" or "\r\n"
|
|
783
|
+
while (true) {
|
|
784
|
+
if (!(await ensureBytes(2))) {
|
|
785
|
+
throw Object.assign(new Error('Malformed multipart/form-data payload'), { status: 400 });
|
|
786
|
+
}
|
|
787
|
+
if (buf[0] === 0x2d && buf[1] === 0x2d) {
|
|
788
|
+
return; // "--" end of multipart
|
|
789
|
+
}
|
|
790
|
+
if (buf[0] === 0x0d && buf[1] === 0x0a) {
|
|
791
|
+
buf = buf.subarray(2);
|
|
792
|
+
} else if (buf[0] === 0x0a) {
|
|
793
|
+
buf = buf.subarray(1);
|
|
794
|
+
} else {
|
|
795
|
+
throw Object.assign(new Error('Malformed multipart/form-data payload'), { status: 400 });
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
// 2. Read part headers up to \r\n\r\n (cap at 16KB)
|
|
799
|
+
let hdrEnd = -1;
|
|
800
|
+
while (true) {
|
|
801
|
+
hdrEnd = indexOfBytes(buf, crlfcrlf);
|
|
802
|
+
if (hdrEnd !== -1) break;
|
|
803
|
+
if (buf.byteLength > 16384) {
|
|
804
|
+
throw Object.assign(new Error('Multipart header too large'), { status: 400 });
|
|
805
|
+
}
|
|
806
|
+
if (!(await readMore())) {
|
|
807
|
+
throw Object.assign(new Error('Malformed multipart/form-data payload'), { status: 400 });
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
|
|
811
|
+
const headerText = _sharedTextDecoder.decode(buf.subarray(0, hdrEnd));
|
|
812
|
+
buf = buf.subarray(hdrEnd + 4);
|
|
813
|
+
|
|
814
|
+
let fieldName = '';
|
|
815
|
+
let filename: string | undefined;
|
|
816
|
+
let partContentType = 'application/octet-stream';
|
|
817
|
+
|
|
818
|
+
for (const line of headerText.split('\r\n')) {
|
|
819
|
+
const colon = line.indexOf(':');
|
|
820
|
+
if (colon === -1) continue;
|
|
821
|
+
const k = line.slice(0, colon).trim().toLowerCase();
|
|
822
|
+
const v = line.slice(colon + 1).trim();
|
|
823
|
+
if (k === 'content-disposition') {
|
|
824
|
+
const nameMatch = v.match(/;\s*name="([^"]*)"/i);
|
|
825
|
+
if (nameMatch) fieldName = nameMatch[1]!;
|
|
826
|
+
const fileMatch = v.match(/;\s*filename="([^"]*)"/i);
|
|
827
|
+
if (fileMatch) filename = fileMatch[1]!;
|
|
828
|
+
} else if (k === 'content-type') {
|
|
829
|
+
partContentType = v;
|
|
830
|
+
}
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
if (filename === undefined) {
|
|
834
|
+
// 3a. Text field part
|
|
835
|
+
while (true) {
|
|
836
|
+
const bIdx = indexOfBytes(buf, partBoundary);
|
|
837
|
+
if (bIdx !== -1) {
|
|
838
|
+
if (bIdx > maxFieldSize) {
|
|
839
|
+
throw Object.assign(new Error(`Field size exceeds ${maxFieldSize} bytes`), { status: 413 });
|
|
840
|
+
}
|
|
841
|
+
const val = _sharedTextDecoder.decode(buf.subarray(0, bIdx));
|
|
842
|
+
buf = buf.subarray(bIdx + partBoundary.byteLength);
|
|
843
|
+
if (fieldName !== '__proto__' && fieldName !== 'constructor' && fieldName !== 'prototype') {
|
|
844
|
+
yield { type: 'field', fieldName, value: val };
|
|
845
|
+
}
|
|
846
|
+
break;
|
|
847
|
+
}
|
|
848
|
+
if (buf.byteLength - partBoundary.byteLength > maxFieldSize) {
|
|
849
|
+
throw Object.assign(new Error(`Field size exceeds ${maxFieldSize} bytes`), { status: 413 });
|
|
850
|
+
}
|
|
851
|
+
if (!(await readMore())) {
|
|
852
|
+
throw Object.assign(new Error('Malformed multipart/form-data payload'), { status: 400 });
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
} else {
|
|
856
|
+
// 3b. File part (streamed with backpressure)
|
|
857
|
+
if (fileCount >= maxFiles) {
|
|
858
|
+
throw Object.assign(new Error(`Too many files (max ${maxFiles})`), { status: 413 });
|
|
859
|
+
}
|
|
860
|
+
fileCount++;
|
|
861
|
+
|
|
862
|
+
const mime = (partContentType || '').split(';')[0]!.trim().toLowerCase();
|
|
863
|
+
if (allowed && !allowed.has(mime)) {
|
|
864
|
+
throw Object.assign(new Error(`Unsupported file type: ${partContentType || 'unknown'}`), { status: 415 });
|
|
865
|
+
}
|
|
866
|
+
|
|
867
|
+
const baseName = filename.split(/[\\/]/).pop() || 'file';
|
|
868
|
+
const safeName = baseName.replace(/[^a-zA-Z0-9._-]/g, '_').replace(/^\.+/, '') || 'file';
|
|
869
|
+
|
|
870
|
+
let fileBytes = 0;
|
|
871
|
+
let streamDone = false;
|
|
872
|
+
let streamErrored: any = null;
|
|
873
|
+
const keepTail = partBoundary.byteLength - 1;
|
|
874
|
+
|
|
875
|
+
const stream = new ReadableStream<Uint8Array>({
|
|
876
|
+
async pull(controller) {
|
|
877
|
+
while (true) {
|
|
878
|
+
const bIdx = indexOfBytes(buf, partBoundary);
|
|
879
|
+
if (bIdx !== -1) {
|
|
880
|
+
const slice = buf.subarray(0, bIdx);
|
|
881
|
+
fileBytes += slice.byteLength;
|
|
882
|
+
if (fileBytes > maxFileSize) {
|
|
883
|
+
streamErrored = Object.assign(new Error(`File exceeds max size of ${maxFileSize} bytes`), { status: 413 });
|
|
884
|
+
controller.error(streamErrored);
|
|
885
|
+
return;
|
|
886
|
+
}
|
|
887
|
+
if (slice.byteLength > 0) controller.enqueue(slice);
|
|
888
|
+
buf = buf.subarray(bIdx + partBoundary.byteLength);
|
|
889
|
+
streamDone = true;
|
|
890
|
+
controller.close();
|
|
891
|
+
return;
|
|
892
|
+
}
|
|
893
|
+
|
|
894
|
+
const safeLen = buf.byteLength - keepTail;
|
|
895
|
+
if (safeLen > 0) {
|
|
896
|
+
const slice = buf.subarray(0, safeLen);
|
|
897
|
+
fileBytes += slice.byteLength;
|
|
898
|
+
if (fileBytes > maxFileSize) {
|
|
899
|
+
streamErrored = Object.assign(new Error(`File exceeds max size of ${maxFileSize} bytes`), { status: 413 });
|
|
900
|
+
controller.error(streamErrored);
|
|
901
|
+
return;
|
|
902
|
+
}
|
|
903
|
+
buf = buf.subarray(safeLen);
|
|
904
|
+
controller.enqueue(slice);
|
|
905
|
+
return;
|
|
906
|
+
}
|
|
907
|
+
|
|
908
|
+
if (!(await readMore())) {
|
|
909
|
+
streamErrored = Object.assign(new Error('Malformed multipart/form-data payload'), { status: 400 });
|
|
910
|
+
controller.error(streamErrored);
|
|
911
|
+
return;
|
|
912
|
+
}
|
|
913
|
+
}
|
|
914
|
+
},
|
|
915
|
+
cancel() {
|
|
916
|
+
streamDone = true;
|
|
917
|
+
}
|
|
918
|
+
});
|
|
919
|
+
|
|
920
|
+
yield {
|
|
921
|
+
type: 'file',
|
|
922
|
+
fieldName,
|
|
923
|
+
filename,
|
|
924
|
+
safeName,
|
|
925
|
+
contentType: partContentType,
|
|
926
|
+
stream
|
|
927
|
+
};
|
|
928
|
+
|
|
929
|
+
if (streamErrored) throw streamErrored;
|
|
930
|
+
|
|
931
|
+
// If consumer didn't drain the stream, skip remaining bytes up to next boundary
|
|
932
|
+
if (!streamDone) {
|
|
933
|
+
try {
|
|
934
|
+
const sr = stream.getReader();
|
|
935
|
+
while (true) {
|
|
936
|
+
const { done } = await sr.read();
|
|
937
|
+
if (done) break;
|
|
938
|
+
}
|
|
939
|
+
sr.releaseLock();
|
|
940
|
+
} catch (e) {
|
|
941
|
+
if (streamErrored) throw streamErrored;
|
|
942
|
+
throw e;
|
|
943
|
+
}
|
|
944
|
+
}
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
} finally {
|
|
948
|
+
try { reader.releaseLock(); } catch { /* ignore */ }
|
|
949
|
+
}
|
|
950
|
+
}
|
|
659
951
|
}
|
package/src/core/loader.ts
CHANGED
|
@@ -7,8 +7,10 @@ import { initConfig } from "./config";
|
|
|
7
7
|
const req = createRequire(import.meta.url);
|
|
8
8
|
|
|
9
9
|
export async function bootstrapConfig() {
|
|
10
|
-
const
|
|
11
|
-
|
|
10
|
+
const cwd = process.cwd();
|
|
11
|
+
const candidates = ["bare.config.ts", "bare.config.js", "bare.config.mjs"];
|
|
12
|
+
const configPath = candidates.map((f) => join(cwd, f)).find((p) => existsSync(p));
|
|
13
|
+
if (!configPath) {
|
|
12
14
|
return initConfig();
|
|
13
15
|
}
|
|
14
16
|
try {
|
|
@@ -17,7 +19,7 @@ export async function bootstrapConfig() {
|
|
|
17
19
|
const userModule = req(resolved);
|
|
18
20
|
return initConfig(userModule?.default ?? userModule);
|
|
19
21
|
} catch (err: any) {
|
|
20
|
-
console.warn(`[BareJS] Failed to load
|
|
22
|
+
console.warn(`[BareJS] Failed to load ${configPath}:`, err?.message || err);
|
|
21
23
|
return initConfig();
|
|
22
24
|
}
|
|
23
25
|
}
|
package/src/core/router.ts
CHANGED
|
@@ -70,6 +70,7 @@ type AddRouterRoute<Routes extends RouteSchema, M extends string> = {
|
|
|
70
70
|
export class BareRouter<Routes extends RouteSchema = {}> {
|
|
71
71
|
declare readonly __routes: Routes;
|
|
72
72
|
public routes: any[] = [];
|
|
73
|
+
protected _onRouteMutate?(): void;
|
|
73
74
|
|
|
74
75
|
constructor(
|
|
75
76
|
public prefix: string = "",
|
|
@@ -97,6 +98,7 @@ export class BareRouter<Routes extends RouteSchema = {}> {
|
|
|
97
98
|
path: fullPath || "",
|
|
98
99
|
handlers: [...this.groupMiddleware, ...resolvedHandlers]
|
|
99
100
|
});
|
|
101
|
+
this._onRouteMutate?.();
|
|
100
102
|
return this;
|
|
101
103
|
}
|
|
102
104
|
|
|
@@ -123,6 +125,7 @@ export class BareRouter<Routes extends RouteSchema = {}> {
|
|
|
123
125
|
|
|
124
126
|
callback(subRouter);
|
|
125
127
|
this.routes.push(...subRouter.routes);
|
|
128
|
+
this._onRouteMutate?.();
|
|
126
129
|
return this;
|
|
127
130
|
};
|
|
128
131
|
|
|
@@ -137,6 +140,7 @@ export class BareRouter<Routes extends RouteSchema = {}> {
|
|
|
137
140
|
handlers: [...this.groupMiddleware, ...r.handlers]
|
|
138
141
|
});
|
|
139
142
|
}
|
|
143
|
+
this._onRouteMutate?.();
|
|
140
144
|
}
|
|
141
145
|
|
|
142
146
|
public route<P extends string, R2 extends RouteSchema = {}>(
|
|
@@ -174,6 +178,7 @@ export class BareRouter<Routes extends RouteSchema = {}> {
|
|
|
174
178
|
}
|
|
175
179
|
}
|
|
176
180
|
}
|
|
181
|
+
this._onRouteMutate?.();
|
|
177
182
|
return this;
|
|
178
183
|
}
|
|
179
184
|
|
|
@@ -188,6 +193,7 @@ export class BareRouter<Routes extends RouteSchema = {}> {
|
|
|
188
193
|
this.groupMiddleware.push(item);
|
|
189
194
|
}
|
|
190
195
|
}
|
|
196
|
+
this._onRouteMutate?.();
|
|
191
197
|
return this;
|
|
192
198
|
}
|
|
193
199
|
}
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
export interface WebSocketRouteHandler {
|
|
2
|
+
open?: (ws: any) => void;
|
|
3
|
+
message?: (ws: any, message: string | Buffer) => void;
|
|
4
|
+
close?: (ws: any, code: number, reason: string) => void;
|
|
5
|
+
drain?: (ws: any) => void;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
export interface WsMatchResult {
|
|
9
|
+
handler: WebSocketRouteHandler;
|
|
10
|
+
params?: Record<string, string>;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Matches a request URL (or path) against registered WebSocket route patterns
|
|
15
|
+
* supporting exact paths, `:param` segments, and `*` catch-all wildcards.
|
|
16
|
+
*/
|
|
17
|
+
export function matchWsRoute(
|
|
18
|
+
wsRoutes: Map<string, WebSocketRouteHandler>,
|
|
19
|
+
urlOrPath: string
|
|
20
|
+
): WsMatchResult | undefined {
|
|
21
|
+
let path = urlOrPath;
|
|
22
|
+
if (urlOrPath.startsWith('http://') || urlOrPath.startsWith('https://') || urlOrPath.startsWith('ws://') || urlOrPath.startsWith('wss://')) {
|
|
23
|
+
const s = urlOrPath.indexOf('/', 8);
|
|
24
|
+
const q = s === -1 ? -1 : urlOrPath.indexOf('?', s);
|
|
25
|
+
path = s === -1 ? '/' : (q === -1 ? urlOrPath.slice(s) : urlOrPath.slice(s, q));
|
|
26
|
+
} else {
|
|
27
|
+
const q = urlOrPath.indexOf('?');
|
|
28
|
+
if (q !== -1) path = urlOrPath.slice(0, q);
|
|
29
|
+
}
|
|
30
|
+
const collapsed = path.replace(/\/+/g, '/');
|
|
31
|
+
const normalized = collapsed.length > 1 && collapsed.endsWith('/') ? collapsed.slice(0, -1) : collapsed;
|
|
32
|
+
|
|
33
|
+
const exact = wsRoutes.get(normalized);
|
|
34
|
+
if (exact) return { handler: exact };
|
|
35
|
+
|
|
36
|
+
const reqParts = normalized.split('/').filter(Boolean);
|
|
37
|
+
for (const [pattern, h] of wsRoutes) {
|
|
38
|
+
if (!pattern.includes(':') && !pattern.includes('*')) continue;
|
|
39
|
+
const patParts = pattern.split('/').filter(Boolean);
|
|
40
|
+
const matched: Record<string, string> = {};
|
|
41
|
+
let ok = true;
|
|
42
|
+
for (let i = 0; i < patParts.length; i++) {
|
|
43
|
+
const pp = patParts[i]!;
|
|
44
|
+
if (pp === '*') {
|
|
45
|
+
matched['*'] = reqParts.slice(i).join('/');
|
|
46
|
+
break;
|
|
47
|
+
}
|
|
48
|
+
if (i >= reqParts.length) { ok = false; break; }
|
|
49
|
+
if (pp.startsWith(':')) {
|
|
50
|
+
matched[pp.slice(1)] = reqParts[i]!;
|
|
51
|
+
} else if (pp !== reqParts[i]) {
|
|
52
|
+
ok = false; break;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
if (ok && (patParts.includes('*') || patParts.length === reqParts.length)) {
|
|
56
|
+
return { handler: h, params: matched };
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
return undefined;
|
|
60
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
8
|
// --- 1. Core Engine ---
|
|
9
|
-
export { BareJS, type WebSocketRouteHandler, type CronOptions, type NotFoundResponse } from './core/bare';
|
|
9
|
+
export { BareJS, normalizePoolSize, type WebSocketRouteHandler, type CronOptions, type NotFoundResponse } from './core/bare';
|
|
10
10
|
export { BareRouter, type InferSchema, type PrefixRoutes } from './core/router';
|
|
11
11
|
|
|
12
12
|
/**
|
|
@@ -27,7 +27,9 @@ export type {
|
|
|
27
27
|
CookieOptions,
|
|
28
28
|
UploadOptions,
|
|
29
29
|
UploadedFile,
|
|
30
|
-
UploadResult
|
|
30
|
+
UploadResult,
|
|
31
|
+
UploadStreamOptions,
|
|
32
|
+
UploadStreamPart
|
|
31
33
|
} from './core/context';
|
|
32
34
|
|
|
33
35
|
// --- 3. The Validation Suite (Builders - สำหรับสร้าง Schema) ---
|
package/src/node.ts
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
import type { RuntimeDriver, RuntimeFileHandle, RuntimePasswordConfig, ServeOptions, ServerHandle } from './types';
|
|
2
|
+
import { matchWsRoute, type WebSocketRouteHandler } from '../core/ws-match';
|
|
3
|
+
|
|
4
|
+
const _zstd = typeof (globalThis as any).Bun?.zstdCompressSync === 'function'
|
|
5
|
+
? (data: Uint8Array): Uint8Array => (globalThis as any).Bun.zstdCompressSync(data)
|
|
6
|
+
: undefined;
|
|
7
|
+
|
|
8
|
+
export const bunDriver: RuntimeDriver = {
|
|
9
|
+
name: 'bun',
|
|
10
|
+
|
|
11
|
+
serve(opts: ServeOptions): ServerHandle {
|
|
12
|
+
const wsCfg = opts.ws;
|
|
13
|
+
const server = wsCfg
|
|
14
|
+
? Bun.serve<WebSocketRouteHandler>({
|
|
15
|
+
port: opts.port,
|
|
16
|
+
hostname: opts.hostname,
|
|
17
|
+
reusePort: opts.reusePort,
|
|
18
|
+
maxRequestBodySize: opts.maxRequestBodySize,
|
|
19
|
+
fetch(req: Request, srv: any) {
|
|
20
|
+
if (req.headers.get('upgrade')?.toLowerCase() === 'websocket') {
|
|
21
|
+
const matched = matchWsRoute(wsCfg.routes, req.url);
|
|
22
|
+
if (
|
|
23
|
+
matched &&
|
|
24
|
+
srv.upgrade(req, {
|
|
25
|
+
data: matched.params ? { ...matched.handler, params: matched.params } : matched.handler
|
|
26
|
+
})
|
|
27
|
+
) {
|
|
28
|
+
return undefined as any;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
return opts.fetch(req, srv?.requestIP?.(req)?.address);
|
|
32
|
+
},
|
|
33
|
+
websocket: wsCfg.adapter
|
|
34
|
+
})
|
|
35
|
+
: Bun.serve({
|
|
36
|
+
port: opts.port,
|
|
37
|
+
hostname: opts.hostname,
|
|
38
|
+
reusePort: opts.reusePort,
|
|
39
|
+
maxRequestBodySize: opts.maxRequestBodySize,
|
|
40
|
+
fetch(req: Request, srv: any) {
|
|
41
|
+
return opts.fetch(req, srv?.requestIP?.(req)?.address);
|
|
42
|
+
}
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
return {
|
|
46
|
+
stop(closeActiveConnections = false) {
|
|
47
|
+
server.stop(closeActiveConnections);
|
|
48
|
+
},
|
|
49
|
+
port: server.port ?? opts.port,
|
|
50
|
+
raw: server
|
|
51
|
+
};
|
|
52
|
+
},
|
|
53
|
+
|
|
54
|
+
gzip(data: Uint8Array, level: number): Uint8Array {
|
|
55
|
+
return Bun.gzipSync(data as any, { level: level as any });
|
|
56
|
+
},
|
|
57
|
+
|
|
58
|
+
zstd: _zstd,
|
|
59
|
+
|
|
60
|
+
openFile(path: string): RuntimeFileHandle {
|
|
61
|
+
const file = Bun.file(path);
|
|
62
|
+
return {
|
|
63
|
+
get type() {
|
|
64
|
+
return file.type;
|
|
65
|
+
},
|
|
66
|
+
full() {
|
|
67
|
+
return file;
|
|
68
|
+
},
|
|
69
|
+
slice(start: number, endExclusive: number) {
|
|
70
|
+
return file.slice(start, endExclusive);
|
|
71
|
+
}
|
|
72
|
+
};
|
|
73
|
+
},
|
|
74
|
+
|
|
75
|
+
password: {
|
|
76
|
+
hash(data: string, cfg: RuntimePasswordConfig): Promise<string> {
|
|
77
|
+
if (cfg.algorithm === 'bcrypt') {
|
|
78
|
+
const cost = Math.max(4, Math.min(31, cfg.timeCost));
|
|
79
|
+
return Bun.password.hash(data, { algorithm: 'bcrypt', cost });
|
|
80
|
+
}
|
|
81
|
+
return Bun.password.hash(data, cfg);
|
|
82
|
+
},
|
|
83
|
+
verify(data: string, hash: string): Promise<boolean> {
|
|
84
|
+
return Bun.password.verify(data, hash);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { RuntimeDriver } from './types';
|
|
2
|
+
import { bunDriver } from './bun';
|
|
3
|
+
import { nodeDriver } from './node';
|
|
4
|
+
|
|
5
|
+
export type {
|
|
6
|
+
RuntimeDriver,
|
|
7
|
+
RuntimeFileHandle,
|
|
8
|
+
RuntimePasswordConfig,
|
|
9
|
+
ServeOptions,
|
|
10
|
+
ServerHandle
|
|
11
|
+
} from './types';
|
|
12
|
+
export { bunDriver } from './bun';
|
|
13
|
+
export { nodeDriver } from './node';
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Active runtime driver, resolved ONCE at module load.
|
|
17
|
+
* Bun gets bunDriver with zero per-request overhead; Node.js / Deno get nodeDriver.
|
|
18
|
+
*/
|
|
19
|
+
export let runtime: RuntimeDriver =
|
|
20
|
+
typeof (globalThis as any).Bun !== 'undefined' ? bunDriver : nodeDriver;
|
|
21
|
+
|
|
22
|
+
export function setRuntime(driver: RuntimeDriver): void {
|
|
23
|
+
runtime = driver;
|
|
24
|
+
}
|