@eslym/sveltekit-adapter-bun 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,943 @@
1
+ // @bun
2
+ // src/files/server.ts
3
+ import {Server} from "SERVER";
4
+ import {manifest} from "MANIFEST";
5
+ var server = new Server(manifest);
6
+ await server.init({
7
+ env: Bun.env,
8
+ read(file) {
9
+ return Bun.file(file).stream();
10
+ }
11
+ });
12
+
13
+ // node_modules/cac/dist/index.mjs
14
+ import {EventEmitter} from "events";
15
+ var toArr = function(any) {
16
+ return any == null ? [] : Array.isArray(any) ? any : [any];
17
+ };
18
+ var toVal = function(out, key, val, opts) {
19
+ var x, old = out[key], nxt = ~opts.string.indexOf(key) ? val == null || val === true ? "" : String(val) : typeof val === "boolean" ? val : ~opts.boolean.indexOf(key) ? val === "false" ? false : val === "true" || (out._.push((x = +val, x * 0 === 0) ? x : val), !!val) : (x = +val, x * 0 === 0) ? x : val;
20
+ out[key] = old == null ? nxt : Array.isArray(old) ? old.concat(nxt) : [old, nxt];
21
+ };
22
+ var mri2 = function(args, opts) {
23
+ args = args || [];
24
+ opts = opts || {};
25
+ var k, arr, arg, name, val, out = { _: [] };
26
+ var i = 0, j = 0, idx = 0, len = args.length;
27
+ const alibi = opts.alias !== undefined;
28
+ const strict = opts.unknown !== undefined;
29
+ const defaults = opts.default !== undefined;
30
+ opts.alias = opts.alias || {};
31
+ opts.string = toArr(opts.string);
32
+ opts.boolean = toArr(opts.boolean);
33
+ if (alibi) {
34
+ for (k in opts.alias) {
35
+ arr = opts.alias[k] = toArr(opts.alias[k]);
36
+ for (i = 0;i < arr.length; i++) {
37
+ (opts.alias[arr[i]] = arr.concat(k)).splice(i, 1);
38
+ }
39
+ }
40
+ }
41
+ for (i = opts.boolean.length;i-- > 0; ) {
42
+ arr = opts.alias[opts.boolean[i]] || [];
43
+ for (j = arr.length;j-- > 0; )
44
+ opts.boolean.push(arr[j]);
45
+ }
46
+ for (i = opts.string.length;i-- > 0; ) {
47
+ arr = opts.alias[opts.string[i]] || [];
48
+ for (j = arr.length;j-- > 0; )
49
+ opts.string.push(arr[j]);
50
+ }
51
+ if (defaults) {
52
+ for (k in opts.default) {
53
+ name = typeof opts.default[k];
54
+ arr = opts.alias[k] = opts.alias[k] || [];
55
+ if (opts[name] !== undefined) {
56
+ opts[name].push(k);
57
+ for (i = 0;i < arr.length; i++) {
58
+ opts[name].push(arr[i]);
59
+ }
60
+ }
61
+ }
62
+ }
63
+ const keys = strict ? Object.keys(opts.alias) : [];
64
+ for (i = 0;i < len; i++) {
65
+ arg = args[i];
66
+ if (arg === "--") {
67
+ out._ = out._.concat(args.slice(++i));
68
+ break;
69
+ }
70
+ for (j = 0;j < arg.length; j++) {
71
+ if (arg.charCodeAt(j) !== 45)
72
+ break;
73
+ }
74
+ if (j === 0) {
75
+ out._.push(arg);
76
+ } else if (arg.substring(j, j + 3) === "no-") {
77
+ name = arg.substring(j + 3);
78
+ if (strict && !~keys.indexOf(name)) {
79
+ return opts.unknown(arg);
80
+ }
81
+ out[name] = false;
82
+ } else {
83
+ for (idx = j + 1;idx < arg.length; idx++) {
84
+ if (arg.charCodeAt(idx) === 61)
85
+ break;
86
+ }
87
+ name = arg.substring(j, idx);
88
+ val = arg.substring(++idx) || (i + 1 === len || ("" + args[i + 1]).charCodeAt(0) === 45 || args[++i]);
89
+ arr = j === 2 ? [name] : name;
90
+ for (idx = 0;idx < arr.length; idx++) {
91
+ name = arr[idx];
92
+ if (strict && !~keys.indexOf(name))
93
+ return opts.unknown("-".repeat(j) + name);
94
+ toVal(out, name, idx + 1 < arr.length || val, opts);
95
+ }
96
+ }
97
+ }
98
+ if (defaults) {
99
+ for (k in opts.default) {
100
+ if (out[k] === undefined) {
101
+ out[k] = opts.default[k];
102
+ }
103
+ }
104
+ }
105
+ if (alibi) {
106
+ for (k in out) {
107
+ arr = opts.alias[k] || [];
108
+ while (arr.length > 0) {
109
+ out[arr.shift()] = out[k];
110
+ }
111
+ }
112
+ }
113
+ return out;
114
+ };
115
+ var removeBrackets = (v) => v.replace(/[<[].+/, "").trim();
116
+ var findAllBrackets = (v) => {
117
+ const ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g;
118
+ const SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g;
119
+ const res = [];
120
+ const parse = (match) => {
121
+ let variadic = false;
122
+ let value = match[1];
123
+ if (value.startsWith("...")) {
124
+ value = value.slice(3);
125
+ variadic = true;
126
+ }
127
+ return {
128
+ required: match[0].startsWith("<"),
129
+ value,
130
+ variadic
131
+ };
132
+ };
133
+ let angledMatch;
134
+ while (angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v)) {
135
+ res.push(parse(angledMatch));
136
+ }
137
+ let squareMatch;
138
+ while (squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v)) {
139
+ res.push(parse(squareMatch));
140
+ }
141
+ return res;
142
+ };
143
+ var getMriOptions = (options) => {
144
+ const result = { alias: {}, boolean: [] };
145
+ for (const [index, option] of options.entries()) {
146
+ if (option.names.length > 1) {
147
+ result.alias[option.names[0]] = option.names.slice(1);
148
+ }
149
+ if (option.isBoolean) {
150
+ if (option.negated) {
151
+ const hasStringTypeOption = options.some((o, i) => {
152
+ return i !== index && o.names.some((name) => option.names.includes(name)) && typeof o.required === "boolean";
153
+ });
154
+ if (!hasStringTypeOption) {
155
+ result.boolean.push(option.names[0]);
156
+ }
157
+ } else {
158
+ result.boolean.push(option.names[0]);
159
+ }
160
+ }
161
+ }
162
+ return result;
163
+ };
164
+ var findLongest = (arr) => {
165
+ return arr.sort((a, b) => {
166
+ return a.length > b.length ? -1 : 1;
167
+ })[0];
168
+ };
169
+ var padRight = (str, length) => {
170
+ return str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`;
171
+ };
172
+ var camelcase = (input) => {
173
+ return input.replace(/([a-z])-([a-z])/g, (_, p1, p2) => {
174
+ return p1 + p2.toUpperCase();
175
+ });
176
+ };
177
+ var setDotProp = (obj, keys, val) => {
178
+ let i = 0;
179
+ let length = keys.length;
180
+ let t = obj;
181
+ let x;
182
+ for (;i < length; ++i) {
183
+ x = t[keys[i]];
184
+ t = t[keys[i]] = i === length - 1 ? val : x != null ? x : !!~keys[i + 1].indexOf(".") || !(+keys[i + 1] > -1) ? {} : [];
185
+ }
186
+ };
187
+ var setByType = (obj, transforms) => {
188
+ for (const key of Object.keys(transforms)) {
189
+ const transform = transforms[key];
190
+ if (transform.shouldTransform) {
191
+ obj[key] = Array.prototype.concat.call([], obj[key]);
192
+ if (typeof transform.transformFunction === "function") {
193
+ obj[key] = obj[key].map(transform.transformFunction);
194
+ }
195
+ }
196
+ }
197
+ };
198
+ var getFileName = (input) => {
199
+ const m = /([^\\\/]+)$/.exec(input);
200
+ return m ? m[1] : "";
201
+ };
202
+ var camelcaseOptionName = (name) => {
203
+ return name.split(".").map((v, i) => {
204
+ return i === 0 ? camelcase(v) : v;
205
+ }).join(".");
206
+ };
207
+
208
+ class CACError extends Error {
209
+ constructor(message) {
210
+ super(message);
211
+ this.name = this.constructor.name;
212
+ if (typeof Error.captureStackTrace === "function") {
213
+ Error.captureStackTrace(this, this.constructor);
214
+ } else {
215
+ this.stack = new Error(message).stack;
216
+ }
217
+ }
218
+ }
219
+
220
+ class Option {
221
+ constructor(rawName, description, config) {
222
+ this.rawName = rawName;
223
+ this.description = description;
224
+ this.config = Object.assign({}, config);
225
+ rawName = rawName.replace(/\.\*/g, "");
226
+ this.negated = false;
227
+ this.names = removeBrackets(rawName).split(",").map((v) => {
228
+ let name = v.trim().replace(/^-{1,2}/, "");
229
+ if (name.startsWith("no-")) {
230
+ this.negated = true;
231
+ name = name.replace(/^no-/, "");
232
+ }
233
+ return camelcaseOptionName(name);
234
+ }).sort((a, b) => a.length > b.length ? 1 : -1);
235
+ this.name = this.names[this.names.length - 1];
236
+ if (this.negated && this.config.default == null) {
237
+ this.config.default = true;
238
+ }
239
+ if (rawName.includes("<")) {
240
+ this.required = true;
241
+ } else if (rawName.includes("[")) {
242
+ this.required = false;
243
+ } else {
244
+ this.isBoolean = true;
245
+ }
246
+ }
247
+ }
248
+ var processArgs = process.argv;
249
+ var platformInfo = `${process.platform}-${process.arch} node-${process.version}`;
250
+
251
+ class Command {
252
+ constructor(rawName, description, config = {}, cli) {
253
+ this.rawName = rawName;
254
+ this.description = description;
255
+ this.config = config;
256
+ this.cli = cli;
257
+ this.options = [];
258
+ this.aliasNames = [];
259
+ this.name = removeBrackets(rawName);
260
+ this.args = findAllBrackets(rawName);
261
+ this.examples = [];
262
+ }
263
+ usage(text) {
264
+ this.usageText = text;
265
+ return this;
266
+ }
267
+ allowUnknownOptions() {
268
+ this.config.allowUnknownOptions = true;
269
+ return this;
270
+ }
271
+ ignoreOptionDefaultValue() {
272
+ this.config.ignoreOptionDefaultValue = true;
273
+ return this;
274
+ }
275
+ version(version, customFlags = "-v, --version") {
276
+ this.versionNumber = version;
277
+ this.option(customFlags, "Display version number");
278
+ return this;
279
+ }
280
+ example(example) {
281
+ this.examples.push(example);
282
+ return this;
283
+ }
284
+ option(rawName, description, config) {
285
+ const option = new Option(rawName, description, config);
286
+ this.options.push(option);
287
+ return this;
288
+ }
289
+ alias(name) {
290
+ this.aliasNames.push(name);
291
+ return this;
292
+ }
293
+ action(callback) {
294
+ this.commandAction = callback;
295
+ return this;
296
+ }
297
+ isMatched(name) {
298
+ return this.name === name || this.aliasNames.includes(name);
299
+ }
300
+ get isDefaultCommand() {
301
+ return this.name === "" || this.aliasNames.includes("!");
302
+ }
303
+ get isGlobalCommand() {
304
+ return this instanceof GlobalCommand;
305
+ }
306
+ hasOption(name) {
307
+ name = name.split(".")[0];
308
+ return this.options.find((option) => {
309
+ return option.names.includes(name);
310
+ });
311
+ }
312
+ outputHelp() {
313
+ const { name, commands } = this.cli;
314
+ const {
315
+ versionNumber,
316
+ options: globalOptions,
317
+ helpCallback
318
+ } = this.cli.globalCommand;
319
+ let sections = [
320
+ {
321
+ body: `${name}${versionNumber ? `/${versionNumber}` : ""}`
322
+ }
323
+ ];
324
+ sections.push({
325
+ title: "Usage",
326
+ body: ` \$ ${name} ${this.usageText || this.rawName}`
327
+ });
328
+ const showCommands = (this.isGlobalCommand || this.isDefaultCommand) && commands.length > 0;
329
+ if (showCommands) {
330
+ const longestCommandName = findLongest(commands.map((command) => command.rawName));
331
+ sections.push({
332
+ title: "Commands",
333
+ body: commands.map((command) => {
334
+ return ` ${padRight(command.rawName, longestCommandName.length)} ${command.description}`;
335
+ }).join("\n")
336
+ });
337
+ sections.push({
338
+ title: `For more info, run any command with the \`--help\` flag`,
339
+ body: commands.map((command) => ` \$ ${name}${command.name === "" ? "" : ` ${command.name}`} --help`).join("\n")
340
+ });
341
+ }
342
+ let options = this.isGlobalCommand ? globalOptions : [...this.options, ...globalOptions || []];
343
+ if (!this.isGlobalCommand && !this.isDefaultCommand) {
344
+ options = options.filter((option) => option.name !== "version");
345
+ }
346
+ if (options.length > 0) {
347
+ const longestOptionName = findLongest(options.map((option) => option.rawName));
348
+ sections.push({
349
+ title: "Options",
350
+ body: options.map((option) => {
351
+ return ` ${padRight(option.rawName, longestOptionName.length)} ${option.description} ${option.config.default === undefined ? "" : `(default: ${option.config.default})`}`;
352
+ }).join("\n")
353
+ });
354
+ }
355
+ if (this.examples.length > 0) {
356
+ sections.push({
357
+ title: "Examples",
358
+ body: this.examples.map((example) => {
359
+ if (typeof example === "function") {
360
+ return example(name);
361
+ }
362
+ return example;
363
+ }).join("\n")
364
+ });
365
+ }
366
+ if (helpCallback) {
367
+ sections = helpCallback(sections) || sections;
368
+ }
369
+ console.log(sections.map((section) => {
370
+ return section.title ? `${section.title}:
371
+ ${section.body}` : section.body;
372
+ }).join("\n\n"));
373
+ }
374
+ outputVersion() {
375
+ const { name } = this.cli;
376
+ const { versionNumber } = this.cli.globalCommand;
377
+ if (versionNumber) {
378
+ console.log(`${name}/${versionNumber} ${platformInfo}`);
379
+ }
380
+ }
381
+ checkRequiredArgs() {
382
+ const minimalArgsCount = this.args.filter((arg) => arg.required).length;
383
+ if (this.cli.args.length < minimalArgsCount) {
384
+ throw new CACError(`missing required args for command \`${this.rawName}\``);
385
+ }
386
+ }
387
+ checkUnknownOptions() {
388
+ const { options, globalCommand } = this.cli;
389
+ if (!this.config.allowUnknownOptions) {
390
+ for (const name of Object.keys(options)) {
391
+ if (name !== "--" && !this.hasOption(name) && !globalCommand.hasOption(name)) {
392
+ throw new CACError(`Unknown option \`${name.length > 1 ? `--${name}` : `-${name}`}\``);
393
+ }
394
+ }
395
+ }
396
+ }
397
+ checkOptionValue() {
398
+ const { options: parsedOptions, globalCommand } = this.cli;
399
+ const options = [...globalCommand.options, ...this.options];
400
+ for (const option of options) {
401
+ const value = parsedOptions[option.name.split(".")[0]];
402
+ if (option.required) {
403
+ const hasNegated = options.some((o) => o.negated && o.names.includes(option.name));
404
+ if (value === true || value === false && !hasNegated) {
405
+ throw new CACError(`option \`${option.rawName}\` value is missing`);
406
+ }
407
+ }
408
+ }
409
+ }
410
+ }
411
+
412
+ class GlobalCommand extends Command {
413
+ constructor(cli) {
414
+ super("@@global@@", "", {}, cli);
415
+ }
416
+ }
417
+ var __assign = Object.assign;
418
+
419
+ class CAC extends EventEmitter {
420
+ constructor(name = "") {
421
+ super();
422
+ this.name = name;
423
+ this.commands = [];
424
+ this.rawArgs = [];
425
+ this.args = [];
426
+ this.options = {};
427
+ this.globalCommand = new GlobalCommand(this);
428
+ this.globalCommand.usage("<command> [options]");
429
+ }
430
+ usage(text) {
431
+ this.globalCommand.usage(text);
432
+ return this;
433
+ }
434
+ command(rawName, description, config) {
435
+ const command = new Command(rawName, description || "", config, this);
436
+ command.globalCommand = this.globalCommand;
437
+ this.commands.push(command);
438
+ return command;
439
+ }
440
+ option(rawName, description, config) {
441
+ this.globalCommand.option(rawName, description, config);
442
+ return this;
443
+ }
444
+ help(callback) {
445
+ this.globalCommand.option("-h, --help", "Display this message");
446
+ this.globalCommand.helpCallback = callback;
447
+ this.showHelpOnExit = true;
448
+ return this;
449
+ }
450
+ version(version, customFlags = "-v, --version") {
451
+ this.globalCommand.version(version, customFlags);
452
+ this.showVersionOnExit = true;
453
+ return this;
454
+ }
455
+ example(example) {
456
+ this.globalCommand.example(example);
457
+ return this;
458
+ }
459
+ outputHelp() {
460
+ if (this.matchedCommand) {
461
+ this.matchedCommand.outputHelp();
462
+ } else {
463
+ this.globalCommand.outputHelp();
464
+ }
465
+ }
466
+ outputVersion() {
467
+ this.globalCommand.outputVersion();
468
+ }
469
+ setParsedInfo({ args, options }, matchedCommand, matchedCommandName) {
470
+ this.args = args;
471
+ this.options = options;
472
+ if (matchedCommand) {
473
+ this.matchedCommand = matchedCommand;
474
+ }
475
+ if (matchedCommandName) {
476
+ this.matchedCommandName = matchedCommandName;
477
+ }
478
+ return this;
479
+ }
480
+ unsetMatchedCommand() {
481
+ this.matchedCommand = undefined;
482
+ this.matchedCommandName = undefined;
483
+ }
484
+ parse(argv = processArgs, {
485
+ run = true
486
+ } = {}) {
487
+ this.rawArgs = argv;
488
+ if (!this.name) {
489
+ this.name = argv[1] ? getFileName(argv[1]) : "cli";
490
+ }
491
+ let shouldParse = true;
492
+ for (const command of this.commands) {
493
+ const parsed = this.mri(argv.slice(2), command);
494
+ const commandName = parsed.args[0];
495
+ if (command.isMatched(commandName)) {
496
+ shouldParse = false;
497
+ const parsedInfo = __assign(__assign({}, parsed), {
498
+ args: parsed.args.slice(1)
499
+ });
500
+ this.setParsedInfo(parsedInfo, command, commandName);
501
+ this.emit(`command:${commandName}`, command);
502
+ }
503
+ }
504
+ if (shouldParse) {
505
+ for (const command of this.commands) {
506
+ if (command.name === "") {
507
+ shouldParse = false;
508
+ const parsed = this.mri(argv.slice(2), command);
509
+ this.setParsedInfo(parsed, command);
510
+ this.emit(`command:!`, command);
511
+ }
512
+ }
513
+ }
514
+ if (shouldParse) {
515
+ const parsed = this.mri(argv.slice(2));
516
+ this.setParsedInfo(parsed);
517
+ }
518
+ if (this.options.help && this.showHelpOnExit) {
519
+ this.outputHelp();
520
+ run = false;
521
+ this.unsetMatchedCommand();
522
+ }
523
+ if (this.options.version && this.showVersionOnExit && this.matchedCommandName == null) {
524
+ this.outputVersion();
525
+ run = false;
526
+ this.unsetMatchedCommand();
527
+ }
528
+ const parsedArgv = { args: this.args, options: this.options };
529
+ if (run) {
530
+ this.runMatchedCommand();
531
+ }
532
+ if (!this.matchedCommand && this.args[0]) {
533
+ this.emit("command:*");
534
+ }
535
+ return parsedArgv;
536
+ }
537
+ mri(argv, command) {
538
+ const cliOptions = [
539
+ ...this.globalCommand.options,
540
+ ...command ? command.options : []
541
+ ];
542
+ const mriOptions = getMriOptions(cliOptions);
543
+ let argsAfterDoubleDashes = [];
544
+ const doubleDashesIndex = argv.indexOf("--");
545
+ if (doubleDashesIndex > -1) {
546
+ argsAfterDoubleDashes = argv.slice(doubleDashesIndex + 1);
547
+ argv = argv.slice(0, doubleDashesIndex);
548
+ }
549
+ let parsed = mri2(argv, mriOptions);
550
+ parsed = Object.keys(parsed).reduce((res, name) => {
551
+ return __assign(__assign({}, res), {
552
+ [camelcaseOptionName(name)]: parsed[name]
553
+ });
554
+ }, { _: [] });
555
+ const args = parsed._;
556
+ const options = {
557
+ "--": argsAfterDoubleDashes
558
+ };
559
+ const ignoreDefault = command && command.config.ignoreOptionDefaultValue ? command.config.ignoreOptionDefaultValue : this.globalCommand.config.ignoreOptionDefaultValue;
560
+ let transforms = Object.create(null);
561
+ for (const cliOption of cliOptions) {
562
+ if (!ignoreDefault && cliOption.config.default !== undefined) {
563
+ for (const name of cliOption.names) {
564
+ options[name] = cliOption.config.default;
565
+ }
566
+ }
567
+ if (Array.isArray(cliOption.config.type)) {
568
+ if (transforms[cliOption.name] === undefined) {
569
+ transforms[cliOption.name] = Object.create(null);
570
+ transforms[cliOption.name]["shouldTransform"] = true;
571
+ transforms[cliOption.name]["transformFunction"] = cliOption.config.type[0];
572
+ }
573
+ }
574
+ }
575
+ for (const key of Object.keys(parsed)) {
576
+ if (key !== "_") {
577
+ const keys = key.split(".");
578
+ setDotProp(options, keys, parsed[key]);
579
+ setByType(options, transforms);
580
+ }
581
+ }
582
+ return {
583
+ args,
584
+ options
585
+ };
586
+ }
587
+ runMatchedCommand() {
588
+ const { args, options, matchedCommand: command } = this;
589
+ if (!command || !command.commandAction)
590
+ return;
591
+ command.checkUnknownOptions();
592
+ command.checkOptionValue();
593
+ command.checkRequiredArgs();
594
+ const actionArgs = [];
595
+ command.args.forEach((arg, index) => {
596
+ if (arg.variadic) {
597
+ actionArgs.push(args.slice(index));
598
+ } else {
599
+ actionArgs.push(args[index]);
600
+ }
601
+ });
602
+ actionArgs.push(options);
603
+ return command.commandAction.apply(this, actionArgs);
604
+ }
605
+ }
606
+ var cac = (name = "") => new CAC(name);
607
+ var dist_default = cac;
608
+
609
+ // src/files/utils.ts
610
+ function get_url(request) {
611
+ if (!urls.has(request)) {
612
+ urls.set(request, new URL(request.url));
613
+ }
614
+ return urls.get(request);
615
+ }
616
+ function set_url(request, url) {
617
+ urls.set(request, url);
618
+ return url;
619
+ }
620
+ function get_basepath() {
621
+ return basePath;
622
+ }
623
+ function set_basepath(path) {
624
+ basePath = path;
625
+ }
626
+ var urls = new WeakMap;
627
+ var basePath;
628
+
629
+ // src/files/static.ts
630
+ import {normalize} from "path/posix";
631
+
632
+ // src/mapping.ts
633
+ var mapping = {
634
+ path: 0,
635
+ immutable: 1,
636
+ headers: 2,
637
+ compression: 3,
638
+ c: {
639
+ gzip: 0,
640
+ brotli: 1
641
+ },
642
+ h: {
643
+ modified: 0,
644
+ etag: 1,
645
+ size: 2
646
+ }
647
+ };
648
+
649
+ // src/files/static.ts
650
+ var lookup = function(pathname) {
651
+ pathname = normalize(pathname);
652
+ let res = lookupTables.get(pathname);
653
+ if (res)
654
+ return [false, res];
655
+ let tryFiles;
656
+ if (pathname === "/") {
657
+ tryFiles = ["/index.html", "/index.htm"];
658
+ } else {
659
+ const stripped = pathname.endsWith("/") ? pathname.slice(0, -1) : pathname;
660
+ tryFiles = [
661
+ `${stripped}.html`,
662
+ `${stripped}.htm`,
663
+ `${stripped}/index.html`,
664
+ `${stripped}/index.htm`
665
+ ];
666
+ }
667
+ for (let i = 0;i < tryFiles.length; i++) {
668
+ res = lookupTables.get(tryFiles[i]);
669
+ if (res)
670
+ return [false, res];
671
+ }
672
+ pathname = pathname.at(-1) === "/" ? pathname.slice(0, -1) : pathname + "/";
673
+ if (lookupTables.has(pathname))
674
+ return [pathname];
675
+ };
676
+ var parse_range = function(header) {
677
+ if (!header.has("range"))
678
+ return false;
679
+ const range = header.get("range");
680
+ const match = /^bytes=(?:(\d+)\-(\d+)?|(\-\d+))/.exec(range);
681
+ if (!match)
682
+ return [false];
683
+ if (match[3])
684
+ return [true, +match[3], null];
685
+ return [true, +match[1], match[2] ? +match[2] + 1 : null];
686
+ };
687
+ function serve_static(request, basePath2) {
688
+ if (!methods.has(request.method))
689
+ return;
690
+ const url = get_url(request);
691
+ const pathname = decodeURIComponent(url.pathname);
692
+ const res = lookup(pathname);
693
+ if (!res)
694
+ return;
695
+ if (res[0] !== false) {
696
+ return new Response(null, {
697
+ status: 302,
698
+ headers: {
699
+ location: res[0] + url.search
700
+ }
701
+ });
702
+ }
703
+ const [_, data] = res;
704
+ const headers = new Headers(data[mapping.headers].map((h, i) => [headersMap[i], h]));
705
+ const range = parse_range(request.headers);
706
+ const filePath = basePath2 + data[mapping.path];
707
+ const file = Bun.file(filePath);
708
+ headers.set("content-type", file.type);
709
+ if (range) {
710
+ const size = data[mapping.headers][mapping.h.size];
711
+ if (!range[0]) {
712
+ headers.set("content-range", `bytes */${size}`);
713
+ headers.set("content-length", "0");
714
+ return new Response(null, {
715
+ status: 416,
716
+ headers
717
+ });
718
+ }
719
+ const [_2, rangeStart, rangeEnd] = range;
720
+ let startBytes = 0;
721
+ let endBytes = size;
722
+ if (rangeStart < 0) {
723
+ startBytes = size + rangeStart;
724
+ } else {
725
+ startBytes = rangeStart;
726
+ if (rangeEnd)
727
+ endBytes = rangeEnd + 1;
728
+ }
729
+ if (endBytes <= startBytes || startBytes < 0 || endBytes > size) {
730
+ headers.set("content-range", `bytes */${size}`);
731
+ headers.set("content-length", "0");
732
+ return new Response(null, {
733
+ status: 416,
734
+ headers
735
+ });
736
+ }
737
+ headers.set("content-range", `bytes ${startBytes}-${endBytes - 1}/${size}`);
738
+ headers.set("content-length", `${endBytes - startBytes}`);
739
+ headers.set("accept-range", "bytes");
740
+ return new Response(file.slice(startBytes, endBytes), {
741
+ status: 206,
742
+ headers
743
+ });
744
+ }
745
+ headers.set("cache-control", data[mapping.immutable] ? "public,max-age=604800,immutable" : "public,max-age=14400");
746
+ if (request.headers.has("if-none-match") && request.headers.get("if-none-match") === data[mapping.headers][mapping.h.etag]) {
747
+ return new Response(null, {
748
+ status: 304,
749
+ headers
750
+ });
751
+ }
752
+ if (request.headers.has("if-modified-since") && request.headers.get("if-modified-since") === data[mapping.headers][mapping.h.modified]) {
753
+ return new Response(null, {
754
+ status: 304,
755
+ headers
756
+ });
757
+ }
758
+ if (!request.headers.has("accept-encoding")) {
759
+ return new Response(file, {
760
+ headers
761
+ });
762
+ }
763
+ const ae = request.headers.get("accept-encoding");
764
+ if (ae.includes("br") && data[mapping.compression][mapping.c.brotli]) {
765
+ headers.set("content-encoding", "br");
766
+ headers.set("content-length", data[mapping.compression][mapping.c.brotli]);
767
+ return new Response(Bun.file(filePath + ".br"), {
768
+ headers
769
+ });
770
+ }
771
+ if (ae.includes("gzip") && data[mapping.compression][mapping.c.gzip]) {
772
+ headers.set("content-encoding", "gzip");
773
+ headers.set("content-length", data[mapping.compression][mapping.c.gzip]);
774
+ return new Response(Bun.file(filePath + ".gz"), {
775
+ headers
776
+ });
777
+ }
778
+ return new Response(file, {
779
+ headers
780
+ });
781
+ }
782
+ var headersMap = ["last-modified", "etag", "content-length"];
783
+ var lookupTables = new Map(PRE_RESOLVE_STATIC);
784
+ var methods = new Set(["HEAD", "GET"]);
785
+
786
+ // src/files/handle.ts
787
+ var clone_req = function(url, request) {
788
+ return new Request(url, {
789
+ method: request.method,
790
+ headers: request.headers,
791
+ body: request.body,
792
+ referrer: request.referrer,
793
+ referrerPolicy: request.referrerPolicy,
794
+ mode: request.mode,
795
+ credentials: request.credentials,
796
+ cache: request.cache,
797
+ redirect: request.redirect,
798
+ integrity: request.integrity
799
+ });
800
+ };
801
+ async function first_resolve(request, resolvers) {
802
+ for (let i = 0;i < resolvers.length; i++) {
803
+ const _r = resolvers[i]({ request });
804
+ const response = _r instanceof Promise ? await _r : _r;
805
+ if (response)
806
+ return response;
807
+ }
808
+ }
809
+ var override_origin = function(args, origin) {
810
+ const url = get_url(args.request);
811
+ const newUrl = new URL(url.pathname + url.search, origin);
812
+ args.request = clone_req(newUrl, args.request);
813
+ set_url(args.request, newUrl);
814
+ };
815
+ var override_origin_with_header = function(args, hostHeader, protocolHeader) {
816
+ const url = get_url(args.request);
817
+ let newUrl = new URL(url);
818
+ if (hostHeader && args.request.headers.has(hostHeader)) {
819
+ newUrl.host = args.request.headers.get(hostHeader);
820
+ }
821
+ if (protocolHeader && args.request.headers.has(protocolHeader)) {
822
+ newUrl.protocol = args.request.headers.get(protocolHeader) + ":";
823
+ }
824
+ if (newUrl.href !== url.href) {
825
+ args.request = clone_req(newUrl, args.request);
826
+ set_url(args.request, newUrl);
827
+ }
828
+ };
829
+ var resolve_xff_ip = function(request, depth) {
830
+ if (!request.headers.has("x-forwarded-for"))
831
+ return;
832
+ const ips = request.headers.get("x-forwarded-for").split(",");
833
+ return ips.at(-depth) || undefined;
834
+ };
835
+ function create_fetch({
836
+ overrideOrigin,
837
+ hostHeader,
838
+ protocolHeader,
839
+ ipHeader,
840
+ xffDepth
841
+ }) {
842
+ const basePath2 = get_basepath();
843
+ let getIp = undefined;
844
+ if (ipHeader === "x-forwarded-for") {
845
+ getIp = (req, fallback) => resolve_xff_ip(req, xffDepth) ?? fallback;
846
+ } else if (ipHeader) {
847
+ getIp = (req, fallback) => req.headers.get(ipHeader) ?? fallback;
848
+ }
849
+ const resolvers = [];
850
+ const upgrades = new WeakMap;
851
+ function markUpgrade(response, ws) {
852
+ upgrades.set(response, ws);
853
+ return response;
854
+ }
855
+ if (overrideOrigin) {
856
+ resolvers.push((args) => override_origin(args, new URL(overrideOrigin)));
857
+ } else if (hostHeader || protocolHeader) {
858
+ resolvers.push((args) => override_origin_with_header(args, hostHeader, protocolHeader));
859
+ }
860
+ resolvers.push(({ request }) => serve_static(request, basePath2));
861
+ return async (request, srv) => {
862
+ const request_ip = srv.requestIP(request)?.address;
863
+ const try_get_ip = getIp ? () => getIp(request, request_ip) : () => request_ip;
864
+ return await first_resolve(request, [
865
+ ...resolvers,
866
+ async (args) => {
867
+ const res = await server.respond(args.request, {
868
+ getClientAddress() {
869
+ const ip = try_get_ip();
870
+ if (ip)
871
+ return ip;
872
+ throw new Error("Unable to determine client IP address");
873
+ },
874
+ platform: {
875
+ get originalRequest() {
876
+ return request;
877
+ },
878
+ get bunServer() {
879
+ return srv;
880
+ },
881
+ get markForUpgrade() {
882
+ return markUpgrade;
883
+ }
884
+ }
885
+ });
886
+ if (upgrades.has(res) && srv.upgrade(request, { headers: res.headers, data: upgrades.get(res) })) {
887
+ return;
888
+ }
889
+ return res;
890
+ }
891
+ ]);
892
+ };
893
+ }
894
+
895
+ // src/files/index.ts
896
+ import {get_hooks} from "SERVER";
897
+ set_basepath(import.meta.dir);
898
+ var hooks = await get_hooks();
899
+ var cli = dist_default(CLI_NAME);
900
+ cli.command("", "Serve the app").alias("serve").option("--port, -p <port>", "Port to listen on", { default: 3000 }).option("--host, -h <host>", "Host to listen on", { default: "localhost" }).option("--unix-socket, -u <unix-socket>", "Serve on a unix socket instead.").option("--protocol-header, -P <protocol-header>", "Protocol header to use").option("--override-origin, -O <override-origin>", "Override the origin").option("--host-header, -H <host-header>", "Host header to use").option("--ip-header, -i <ip-header>", "IP header to use").option("--xff-depth, -x <xff-depth>", "X-Forwarded-For depth", { default: 1 }).action(async (options) => {
901
+ await hooks.beforeServe?.(options);
902
+ const serverOptions = options.unixSocket ? {
903
+ unix: options.unixSocket
904
+ } : {
905
+ hostname: options.host,
906
+ port: options.port
907
+ };
908
+ const server4 = Bun.serve({
909
+ ...serverOptions,
910
+ fetch: create_fetch(options),
911
+ websocket: {
912
+ ...WEBSOCKET_OPTIONS,
913
+ message(ws, message) {
914
+ return ws.data.message(ws, message);
915
+ },
916
+ open(ws) {
917
+ return ws.data.open?.(ws);
918
+ },
919
+ close(ws, code, reason) {
920
+ return ws.data.close?.(ws, code, reason);
921
+ },
922
+ ping(ws, data) {
923
+ return ws.data.ping?.(ws, data);
924
+ },
925
+ pong(ws, data) {
926
+ return ws.data.pong?.(ws, data);
927
+ },
928
+ drain(ws) {
929
+ return ws.data.drain?.(ws);
930
+ }
931
+ }
932
+ });
933
+ await hooks.afterServe?.(server4, options);
934
+ console.log(`Serving on ${server4.url}`);
935
+ });
936
+ cli.help();
937
+ await hooks.setupCLI?.(cli);
938
+ if (Bun.main === Bun.fileURLToPath(import.meta.url)) {
939
+ cli.parse();
940
+ }
941
+ export {
942
+ cli
943
+ };