chore: remove Gitea Actions workflows - using direct webhooks instead

This commit is contained in:
pius-coder
2026-04-15 23:31:12 +01:00
parent 325d9063e8
commit f648637569
4825 changed files with 1183398 additions and 0 deletions

3
.env Normal file
View File

@@ -0,0 +1,3 @@
NODE_ENV=development
PORT=3000
DATABASE_URL=postgres://postgres:postgres@localhost:5432/importex

5
.env.example Normal file
View File

@@ -0,0 +1,5 @@
NODE_ENV=development
PORT=3000
DATABASE_URL=postgres://postgres:postgres@localhost:5432/importex
COOLIFY_TOKEN=
COOLIFY_WEBHOOK_URL=

1
node_modules/.bin/drizzle-kit generated vendored Symbolic link
View File

@@ -0,0 +1 @@
../drizzle-kit/bin.cjs

1
node_modules/.bin/esbuild generated vendored Symbolic link
View File

@@ -0,0 +1 @@
../@esbuild/linux-x64/bin/esbuild

1
node_modules/.bin/tsc generated vendored Symbolic link
View File

@@ -0,0 +1 @@
../typescript/bin/tsc

1
node_modules/.bin/tsserver generated vendored Symbolic link
View File

@@ -0,0 +1 @@
../typescript/bin/tsserver

1
node_modules/.bin/tsx generated vendored Symbolic link
View File

@@ -0,0 +1 @@
../tsx/dist/cli.mjs

464
node_modules/@drizzle-team/brocli/README.md generated vendored Executable file
View File

@@ -0,0 +1,464 @@
# Brocli 🥦
Modern type-safe way of building CLIs with TypeScript or JavaScript
by [Drizzle Team](https://drizzle.team)
```ts
import { command, string, boolean, run } from "@drizzle-team/brocli";
const push = command({
name: "push",
options: {
dialect: string().enum("postgresql", "mysql", "sqlite"),
databaseSchema: string().required(),
databaseUrl: string().required(),
strict: boolean().default(false),
},
handler: (opts) => {
...
},
});
run([push]); // parse shell arguments and run command
```
### Why?
Brocli is meant to solve a list of challenges we've faced while building
[Drizzle ORM](https://orm.drizzle.team) CLI companion for generating and running SQL schema migrations:
- [x] Explicit, straightforward and discoverable API
- [x] Typed options(arguments) with built in validation
- [x] Ability to reuse options(or option sets) across commands
- [x] Transformer hook to decouple runtime config consumption from command business logic
- [x] `--version`, `-v` as either string or callback
- [x] Command hooks to run common stuff before/after command
- [x] Explicit global params passthrough
- [x] Testability, the most important part for us to iterate without breaking
- [x] Themes, simple API to style global/command helps
- [x] Docs generation API to eliminate docs drifting
### Learn by examples
If you need API referece - [see here](#api-reference), this list of practical example
is meant to a be a zero to hero walk through for you to learn Brocli 🚀
Simple echo command with positional argument:
```ts
import { run, command, positional } from "@drizzle-team/brocli";
const echo = command({
name: "echo",
options: {
text: positional().desc("Text to echo").default("echo"),
},
handler: (opts) => {
console.log(opts.text);
},
});
run([echo])
```
```bash
~ bun run index.ts echo
echo
~ bun run index.ts echo text
text
```
Print version with `--version -v`:
```ts
...
run([echo], {
version: "1.0.0",
);
```
```bash
~ bun run index.ts --version
1.0.0
```
Version accepts async callback for you to do any kind of io if necessary before printing cli version:
```ts
import { run, command, positional } from "@drizzle-team/brocli";
const version = async () => {
// you can run async here, for example fetch version of runtime-dependend library
const envVersion = process.env.CLI_VERSION;
console.log(chalk.gray(envVersion), "\n");
};
const echo = command({ ... });
run([echo], {
version: version,
);
```
# API reference
[**`command`**](#command)
- [`command → name`](#command-name)
- [`command → desc`](#command-desc)
- [`command → shortDesc`](#command-shortDesc)
- [`command → aliases`](#command-aliases)
- [`command → options`](#command-options)
- [`command → transform`](#command-transform)
- [`command → handler`](#command-handler)
- [`command → help`](#command-help)
- [`command → hidden`](#command-hidden)
- [`command → metadata`](#command-metadata)
[**`options`**](#options)
- [`string`](#options-string)
- [`boolean`](#options-boolean)
- [`number`](#options-number)
- [`enum`](#options-enum)
- [`positional`](#options-positional)
- [`required`](#options-required)
- [`alias`](#options-alias)
- [`desc`](#options-desc)
- [`default`](#options-default)
- [`hidden`](#options-hidden)
[**`run`**](#run)
- [`string`](#options-string)
Brocli **`command`** declaration has:
`name` - command name, will be listed in `help`
`desc` - optional description, will be listed in the command `help`
`shortDesc` - optional short description, will be listed in the all commands/all subcommands `help`
`aliases` - command name aliases
`hidden` - flag to hide command from `help`
`help` - command help text or a callback to print help text with dynamically provided config
`options` - typed list of shell arguments to be parsed and provided to `transform` or `handler`
`transform` - optional hook, will be called before handler to modify CLI params
`handler` - called with either typed `options` or `transform` params, place to run your command business logic
`metadata` - optional meta information for docs generation flow
`name`, `desc`, `shortDesc` and `metadata` are provided to docs generation step
```ts
import { command, string, boolean } from "@drizzle-team/brocli";
const push = command({
name: "push",
options: {
dialect: string().enum("postgresql", "mysql", "sqlite"),
databaseSchema: string().required(),
databaseUrl: string().required(),
strict: boolean().default(false),
},
transform: (opts) => {
},
handler: (opts) => {
...
},
});
```
```ts
import { command } from "@drizzle-team/brocli";
const cmd = command({
name: "cmd",
options: {
dialect: string().enum("postgresql", "mysql", "sqlite"),
schema: string().required(),
url: string().required(),
},
handler: (opts) => {
...
},
});
```
### Option builder
Initial builder functions:
- `string(name?: string)` - defines option as a string-type option which requires data to be passed as `--option=value` or `--option value`
- `name` - name by which option is passed in cli args
If not specified, defaults to key of this option
:warning: - must not contain `=` character, not be in `--help`,`-h`,`--version`,`-v` and be unique per each command
:speech_balloon: - will be automatically prefixed with `-` if one character long, `--` if longer
If you wish to have only single hyphen as a prefix on multi character name - simply specify name with it: `string('-longname')`
- `number(name?: string)` - defines option as a number-type option which requires data to be passed as `--option=value` or `--option value`
- `name` - name by which option is passed in cli args
If not specified, defaults to key of this option
:warning: - must not contain `=` character, not be in `--help`,`-h`,`--version`,`-v` and be unique per each command
:speech_balloon: - will be automatically prefixed with `-` if one character long, `--` if longer
If you wish to have only single hyphen as a prefix on multi character name - simply specify name with it: `number('-longname')`
- `boolean(name?: string)` - defines option as a boolean-type option which requires data to be passed as `--option`
- `name` - name by which option is passed in cli args
If not specified, defaults to key of this option
:warning: - must not contain `=` character, not be in `--help`,`-h`,`--version`,`-v` and be unique per each command
:speech_balloon: - will be automatically prefixed with `-` if one character long, `--` if longer
If you wish to have only single hyphen as a prefix on multi character name - simply specify name with it: `boolean('-longname')`
- `positional(displayName?: string)` - defines option as a positional-type option which requires data to be passed after a command as `command value`
- `displayName` - name by which option is passed in cli args
If not specified, defaults to key of this option
:warning: - does not consume options and data that starts with
Extensions:
- `.alias(...aliases: string[])` - defines aliases for option
- `aliases` - aliases by which option is passed in cli args
:warning: - must not contain `=` character, not be in `--help`,`-h`,`--version`,`-v` and be unique per each command
:speech_balloon: - will be automatically prefixed with `-` if one character long, `--` if longer
If you wish to have only single hyphen as a prefix on multi character alias - simply specify alias with it: `.alias('-longname')`
- `.desc(description: string)` - defines description for option to be displayed in `help` command
- `.required()` - sets option as required, which means that application will print an error if it is not present in cli args
- `.default(value: string | boolean)` - sets default value for option which will be assigned to it in case it is not present in cli args
- `.hidden()` - sets option as hidden - option will be omitted from being displayed in `help` command
- `.enum(values: [string, ...string[]])` - limits values of string to one of specified here
- `values` - allowed enum values
- `.int()` - ensures that number is an integer
- `.min(value: number)` - specified minimal allowed value for numbers
- `value` - minimal allowed value
:warning: - does not limit defaults
- `.max(value: number)` - specified maximal allowed value for numbers
- `value` - maximal allowed value
:warning: - does not limit defaults
### Creating handlers
Normally, you can write handlers right in the `command()` function, however there might be cases where you'd want to define your handlers separately.
For such cases, you'd want to infer type of `options` that will be passes inside your handler.
You can do it using `TypeOf` type:
```Typescript
import { string, boolean, type TypeOf } from '@drizzle-team/brocli'
const commandOptions = {
opt1: string(),
opt2: boolean('flag').alias('f'),
// And so on...
}
export const commandHandler = (options: TypeOf<typeof commandOptions>) => {
// Your logic goes here...
}
```
Or by using `handler(options, myHandler () => {...})`
```Typescript
import { string, boolean, handler } from '@drizzle-team/brocli'
const commandOptions = {
opt1: string(),
opt2: boolean('flag').alias('f'),
// And so on...
}
export const commandHandler = handler(commandOptions, (options) => {
// Your logic goes here...
});
```
### Defining commands
To define commands, use `command()` function:
```Typescript
import { command, type Command, string, boolean, type TypeOf } from '@drizzle-team/brocli'
const commandOptions = {
opt1: string(),
opt2: boolean('flag').alias('f'),
// And so on...
}
const commands: Command[] = []
commands.push(command({
name: 'command',
aliases: ['c', 'cmd'],
desc: 'Description goes here',
shortDesc: 'Short description'
hidden: false,
options: commandOptions,
transform: (options) => {
// Preprocess options here...
return processedOptions
},
handler: (processedOptions) => {
// Your logic goes here...
},
help: () => 'This command works like this: ...',
subcommands: [
command(
// You can define subcommands like this
)
]
}));
```
Parameters:
- `name` - name by which command is searched in cli args
:warning: - must not start with `-` character, be equal to [`true`, `false`, `0`, `1`] (case-insensitive) and be unique per command collection
- `aliases` - aliases by which command is searched in cli args
:warning: - must not start with `-` character, be equal to [`true`, `false`, `0`, `1`] (case-insensitive) and be unique per command collection
- `desc` - description for command to be displayed in `help` command
- `shortDesc` - short description for command to be displayed in `help` command
- `hidden` - sets command as hidden - if `true`, command will be omitted from being displayed in `help` command
- `options` - object containing command options created using `string` and `boolean` functions
- `transform` - optional function to preprocess options before they are passed to handler
:warning: - type of return mutates type of handler's input
- `handler` - function, which will be executed in case of successful option parse
:warning: - must be present if your command doesn't have subcommands
If command has subcommands but no handler, help for this command is going to be called instead of handler
- `help` - function or string, which will be executed or printed when help is called for this command
:warning: - if passed, takes prevalence over theme's `commandHelp` event
- `subcommands` - subcommands for command
:warning: - command can't have subcommands and `positional` options at the same time
- `metadata` - any data that you want to attach to command to later use in docs generation step
### Running commands
After defining commands, you're going to need to execute `run` function to start command execution
```Typescript
import { command, type Command, run, string, boolean, type TypeOf } from '@drizzle-team/brocli'
const commandOptions = {
opt1: string(),
opt2: boolean('flag').alias('f'),
// And so on...
}
const commandHandler = (options: TypeOf<typeof commandOptions>) => {
// Your logic goes here...
}
const commands: Command[] = []
commands.push(command({
name: 'command',
aliases: ['c', 'cmd'],
desc: 'Description goes here',
hidden: false,
options: commandOptions,
handler: commandHandler,
}));
// And so on...
run(commands, {
name: 'mysoft',
description: 'MySoft CLI',
omitKeysOfUndefinedOptions: true,
argSource: customEnvironmentArgvStorage,
version: '1.0.0',
help: () => {
console.log('Command list:');
commands.forEach(c => console.log('This command does ... and has options ...'));
},
theme: async (event) => {
if (event.type === 'commandHelp') {
await myCustomUniversalCommandHelp(event.command);
return true;
}
if (event.type === 'unknownError') {
console.log('Something went wrong...');
return true;
}
return false;
},
hook: (event, command) => {
if(event === 'before') console.log(`Command '${command.name}' started`)
if(event === 'after') console.log(`Command '${command.name}' succesfully finished it's work`)
}
})
```
Parameters:
- `name` - name that's used to invoke your application from cli.
Used for themes that print usage examples, example:
`app do-task --help` results in `Usage: app do-task <positional> [flags] ...`
Default: `undefined`
- `description` - description of your app
Used for themes, example:
`myapp --help` results in
```
MyApp CLI
Usage: myapp [command]...
```
Default: `undefined`
- `omitKeysOfUndefinedOptions` - flag that determines whether undefined options will be passed to transform\handler or not
Default: `false`
- `argSource` - location of array of args in your environment
:warning: - first two items of this storage will be ignored as they typically contain executable and executed file paths
Default: `process.argv`
- `version` - string or handler used to print your app version
:warning: - if passed, takes prevalence over theme's version event
- `help` - string or handler used to print your app's global help
:warning: - if passed, takes prevalence over theme's `globalHelp` event
- `theme(event: BroCliEvent)` - function that's used to customize messages that are printed on various events
Return:
`true` | `Promise<true>` if you consider event processed
`false` | `Promise<false>` to redirect event to default theme
- `hook(event: EventType, command: Command)` - function that's used to execute code before and after every command's `transform` and `handler` execution
### Additional functions
- `commandsInfo(commands: Command[])` - get simplified representation of your command collection
Can be used to generate docs
- `test(command: Command, args: string)` - test behaviour for command with specified arguments
:warning: - if command has `transform`, it will get called, however `handler` won't
- `getCommandNameWithParents(command: Command)` - get subcommand's name with parent command names
## CLI
In `BroCLI`, command doesn't have to be the first argument, instead it may be passed in any order.
To make this possible, hovewer, option that's passed right before command should have an explicit value, even if it is a flag: `--verbose true <command-name>` (does not apply to reserved flags: [ `--help` | `-h` | `--version` | `-v`])
Options are parsed in strict mode, meaning that having any unrecognized options will result in an error.

1509
node_modules/@drizzle-team/brocli/index.cjs generated vendored Normal file

File diff suppressed because it is too large Load Diff

1
node_modules/@drizzle-team/brocli/index.cjs.map generated vendored Normal file

File diff suppressed because one or more lines are too long

298
node_modules/@drizzle-team/brocli/index.d.cts generated vendored Normal file
View File

@@ -0,0 +1,298 @@
type OptionType = 'string' | 'boolean' | 'number' | 'positional';
type OutputType = string | boolean | number | undefined;
type BuilderConfig<TType extends OptionType = OptionType> = {
name?: string | undefined;
aliases: string[];
type: TType;
description?: string;
default?: OutputType;
isHidden?: boolean;
isRequired?: boolean;
isInt?: boolean;
minVal?: number;
maxVal?: number;
enumVals?: [string, ...string[]];
};
type ProcessedBuilderConfig = {
name: string;
aliases: string[];
type: OptionType;
description?: string;
default?: OutputType;
isHidden?: boolean;
isRequired?: boolean;
isInt?: boolean;
minVal?: number;
maxVal?: number;
enumVals?: [string, ...string[]];
};
type BuilderConfigLimited = BuilderConfig & {
type: Exclude<OptionType, 'positional'>;
};
declare class OptionBuilderBase<TBuilderConfig extends BuilderConfig = BuilderConfig, TOutput extends OutputType = string, TOmit extends string = '', TEnums extends string | undefined = undefined> {
_: {
config: TBuilderConfig;
/**
* Type-level only field
*
* Do not attempt to access at a runtime
*/
$output: TOutput;
};
private config;
constructor(config?: TBuilderConfig);
string<TName extends string>(name: TName): Omit<OptionBuilderBase<BuilderConfig<'string'>, string | undefined, TOmit | OptionType | 'min' | 'max' | 'int'>, TOmit | OptionType | 'min' | 'max' | 'int'>;
string(): Omit<OptionBuilderBase<BuilderConfig<'string'>, string | undefined, TOmit | OptionType | 'min' | 'max' | 'int'>, TOmit | OptionType | 'min' | 'max' | 'int'>;
number<TName extends string>(name: TName): Omit<OptionBuilderBase<BuilderConfig<'number'>, number | undefined, TOmit | OptionType | 'enum'>, TOmit | OptionType | 'enum'>;
number(): Omit<OptionBuilderBase<BuilderConfig<'number'>, string | undefined, TOmit | OptionType | 'enum'>, TOmit | OptionType | 'enum'>;
boolean<TName extends string>(name: TName): Omit<OptionBuilderBase<BuilderConfig<'boolean'>, boolean | undefined, TOmit | OptionType | 'min' | 'max' | 'enum' | 'int'>, TOmit | OptionType | 'min' | 'max' | 'enum' | 'int'>;
boolean(): Omit<OptionBuilderBase<BuilderConfig<'boolean'>, boolean | undefined, TOmit | OptionType | 'min' | 'max' | 'enum' | 'int'>, TOmit | OptionType | 'min' | 'max' | 'enum' | 'int'>;
positional<TName extends string>(displayName: TName): Omit<OptionBuilderBase<BuilderConfig<'positional'>, string | undefined, TOmit | OptionType | 'min' | 'max' | 'int' | 'alias'>, TOmit | OptionType | 'min' | 'max' | 'int' | 'alias'>;
positional(): Omit<OptionBuilderBase<BuilderConfig<'positional'>, string | undefined, TOmit | OptionType | 'min' | 'max' | 'int' | 'alias'>, TOmit | OptionType | 'min' | 'max' | 'int' | 'alias'>;
alias(...aliases: string[]): Omit<OptionBuilderBase<TBuilderConfig, TOutput, TOmit | 'alias'>, TOmit | 'alias'>;
desc<TDescription extends string>(description: TDescription): Omit<OptionBuilderBase<TBuilderConfig, TOutput, TOmit | 'desc'>, TOmit | 'desc'>;
hidden(): Omit<OptionBuilderBase<TBuilderConfig, TOutput, TOmit | 'hidden'>, TOmit | 'hidden'>;
required(): Omit<OptionBuilderBase<TBuilderConfig, Exclude<TOutput, undefined>, TOmit | 'required' | 'default'>, TOmit | 'required' | 'default'>;
default<TDefVal extends TEnums extends undefined ? Exclude<TOutput, undefined> : TEnums>(value: TDefVal): Omit<OptionBuilderBase<TBuilderConfig, Exclude<TOutput, undefined>, TOmit | 'enum' | 'required' | 'default', TEnums>, TOmit | 'enum' | 'required' | 'default'>;
enum<TValues extends [string, ...string[]], TUnion extends TValues[number] = TValues[number]>(...values: TValues): Omit<OptionBuilderBase<TBuilderConfig, TUnion | (TOutput extends undefined ? undefined : never), TOmit | 'enum', TUnion>, TOmit | 'enum'>;
min(value: number): Omit<OptionBuilderBase<TBuilderConfig, TOutput, TOmit | 'min'>, TOmit | 'min'>;
max(value: number): Omit<OptionBuilderBase<TBuilderConfig, TOutput, TOmit | 'max'>, TOmit | 'max'>;
int(): Omit<OptionBuilderBase<TBuilderConfig, TOutput, TOmit | 'int'>, TOmit | 'int'>;
}
type GenericBuilderInternalsFields = {
/**
* Type-level only field
*
* Do not attempt to access at a runtime
*/
$output: OutputType;
config: BuilderConfig;
};
type GenericBuilderInternals = {
_: GenericBuilderInternalsFields;
};
type GenericBuilderInternalsFieldsLimited = {
/**
* Type-level only field
*
* Do not attempt to access at a runtime
*/
$output: OutputType;
config: BuilderConfigLimited;
};
type GenericBuilderInternalsLimited = {
_: GenericBuilderInternalsFieldsLimited;
};
type ProcessedOptions<TOptionConfig extends Record<string, GenericBuilderInternals> = Record<string, GenericBuilderInternals>> = {
[K in keyof TOptionConfig]: K extends string ? {
config: ProcessedBuilderConfig;
/**
* Type-level only field
*
* Do not attempt to access at a runtime
*/
$output: TOptionConfig[K]['_']['$output'];
} : never;
};
type Simplify<T> = {
[K in keyof T]: T[K];
} & {};
type TypeOf<TOptions extends Record<string, GenericBuilderInternals>> = Simplify<{
[K in keyof TOptions]: TOptions[K]['_']['$output'];
}>;
declare function string<TName extends string>(name: TName): Omit<OptionBuilderBase<BuilderConfig<'string'>, string | undefined, OptionType | 'min' | 'max' | 'int'>, OptionType | 'min' | 'max' | 'int'>;
declare function string(): Omit<OptionBuilderBase<BuilderConfig<'string'>, string | undefined, OptionType | 'min' | 'max' | 'int'>, OptionType | 'min' | 'max' | 'int'>;
declare function number<TName extends string>(name: TName): Omit<OptionBuilderBase<BuilderConfig<'number'>, number | undefined, OptionType | 'enum'>, OptionType | 'enum'>;
declare function number(): Omit<OptionBuilderBase<BuilderConfig<'number'>, number | undefined, OptionType | 'enum'>, OptionType | 'enum'>;
declare function boolean<TName extends string>(name: TName): Omit<OptionBuilderBase<BuilderConfig<'boolean'>, boolean | undefined, OptionType | 'min' | 'max' | 'int' | 'enum'>, OptionType | 'min' | 'max' | 'int' | 'enum'>;
declare function boolean(): Omit<OptionBuilderBase<BuilderConfig<'boolean'>, boolean | undefined, OptionType | 'min' | 'max' | 'int' | 'enum'>, OptionType | 'min' | 'max' | 'int' | 'enum'>;
declare function positional<TName extends string>(displayName: TName): Omit<OptionBuilderBase<BuilderConfig<'positional'>, string | undefined, OptionType | 'min' | 'max' | 'int' | 'alias'>, OptionType | 'min' | 'max' | 'int' | 'alias'>;
declare function positional(): Omit<OptionBuilderBase<BuilderConfig<'positional'>, string | undefined, OptionType | 'min' | 'max' | 'int' | 'alias'>, OptionType | 'min' | 'max' | 'int' | 'alias'>;
type CommandHandler<TOpts extends Record<string, GenericBuilderInternals> | undefined = Record<string, GenericBuilderInternals> | undefined> = (options: TOpts extends Record<string, GenericBuilderInternals> ? TypeOf<TOpts> : undefined) => any;
type CommandInfo = {
name: string;
aliases?: [string, ...string[]];
desc?: string;
shortDesc?: string;
hidden?: boolean;
options?: Record<string, ProcessedBuilderConfig>;
metadata?: any;
subcommands?: CommandsInfo;
};
type CommandsInfo = Record<string, CommandInfo>;
type EventType = 'before' | 'after';
type BroCliConfig = {
name?: string;
description?: string;
argSource?: string[];
help?: string | Function;
version?: string | Function;
omitKeysOfUndefinedOptions?: boolean;
hook?: (event: EventType, command: Command) => any;
theme?: EventHandler;
};
type GenericCommandHandler = (options?: Record<string, OutputType> | undefined) => any;
type RawCommand<TOpts extends Record<string, GenericBuilderInternals> | undefined = Record<string, GenericBuilderInternals> | undefined, TOptsData = TOpts extends Record<string, GenericBuilderInternals> ? TypeOf<TOpts> : undefined, TTransformed = TOptsData extends undefined ? undefined : TOptsData> = {
name?: string;
aliases?: [string, ...string[]];
desc?: string;
shortDesc?: string;
hidden?: boolean;
options?: TOpts;
help?: string | Function;
transform?: (options: TOptsData) => TTransformed;
handler?: (options: Awaited<TTransformed>) => any;
subcommands?: [Command, ...Command[]];
metadata?: any;
};
type AnyRawCommand<TOpts extends Record<string, GenericBuilderInternals> | undefined = Record<string, GenericBuilderInternals> | undefined> = {
name?: string;
aliases?: [string, ...string[]];
desc?: string;
shortDesc?: string;
hidden?: boolean;
options?: TOpts;
help?: string | Function;
transform?: GenericCommandHandler;
handler?: GenericCommandHandler;
subcommands?: [Command, ...Command[]];
metadata?: any;
};
type Command<TOptsType = any, TTransformedType = any> = {
name: string;
aliases?: [string, ...string[]];
desc?: string;
shortDesc?: string;
hidden?: boolean;
options?: ProcessedOptions;
help?: string | Function;
transform?: GenericCommandHandler;
handler?: GenericCommandHandler;
subcommands?: [Command, ...Command[]];
parent?: Command;
metadata?: any;
};
type CommandCandidate = {
data: string;
originalIndex: number;
};
type InnerCommandParseRes = {
command: Command | undefined;
args: string[];
};
type TestResult<THandlerInput> = {
type: 'handler';
options: THandlerInput;
} | {
type: 'help' | 'version';
} | {
type: 'error';
error: unknown;
};
declare const command: <TOpts extends Record<string, GenericBuilderInternals> | undefined, TOptsData = TOpts extends Record<string, GenericBuilderInternals> ? { [K_1 in keyof { [K in keyof TOpts]: TOpts[K]["_"]["$output"]; }]: { [K in keyof TOpts]: TOpts[K]["_"]["$output"]; }[K_1]; } : undefined, TTransformed = TOptsData>(command: RawCommand<TOpts, TOptsData, TTransformed>) => Command<TOptsData, Awaited<TTransformed>>;
declare const getCommandNameWithParents: (command: Command) => string;
/**
* Runs CLI commands
*
* @param commands - command collection
*
* @param config - additional settings
*/
declare const run: (commands: Command[], config?: BroCliConfig) => Promise<void>;
declare const handler: <TOpts extends Record<string, GenericBuilderInternals>>(options: TOpts, handler: CommandHandler<TOpts>) => CommandHandler<TOpts>;
declare const test: <TOpts, THandlerInput>(command: Command<TOpts, THandlerInput>, args: string) => Promise<TestResult<THandlerInput>>;
declare const commandsInfo: (commands: Command[]) => CommandsInfo;
type CommandHelpEvent = {
type: 'command_help';
name: string | undefined;
description: string | undefined;
command: Command;
};
type GlobalHelpEvent = {
type: 'global_help';
description: string | undefined;
name: string | undefined;
commands: Command[];
};
type MissingArgsEvent = {
type: 'error';
violation: 'missing_args_error';
name: string | undefined;
description: string | undefined;
command: Command;
missing: [string[], ...string[][]];
};
type UnrecognizedArgsEvent = {
type: 'error';
violation: 'unrecognized_args_error';
name: string | undefined;
description: string | undefined;
command: Command;
unrecognized: [string, ...string[]];
};
type UnknownCommandEvent = {
type: 'error';
violation: 'unknown_command_error';
name: string | undefined;
description: string | undefined;
commands: Command[];
offender: string;
};
type UnknownSubcommandEvent = {
type: 'error';
violation: 'unknown_subcommand_error';
name: string | undefined;
description: string | undefined;
command: Command;
offender: string;
};
type UnknownErrorEvent = {
type: 'error';
violation: 'unknown_error';
name: string | undefined;
description: string | undefined;
error: unknown;
};
type VersionEvent = {
type: 'version';
name: string | undefined;
description: string | undefined;
};
type GenericValidationViolation = 'above_max' | 'below_min' | 'expected_int' | 'invalid_boolean_syntax' | 'invalid_string_syntax' | 'invalid_number_syntax' | 'invalid_number_value' | 'enum_violation';
type ValidationViolation = BroCliEvent extends infer Event ? Event extends {
violation: string;
} ? Event['violation'] : never : never;
type ValidationErrorEvent = {
type: 'error';
violation: GenericValidationViolation;
name: string | undefined;
description: string | undefined;
command: Command;
option: ProcessedBuilderConfig;
offender: {
namePart?: string;
dataPart?: string;
};
};
type BroCliEvent = CommandHelpEvent | GlobalHelpEvent | MissingArgsEvent | UnrecognizedArgsEvent | UnknownCommandEvent | UnknownSubcommandEvent | ValidationErrorEvent | VersionEvent | UnknownErrorEvent;
type BroCliEventType = BroCliEvent['type'];
/**
* Return `true` if your handler processes the event
*
* Return `false` to process event with a built-in handler
*/
type EventHandler = (event: BroCliEvent) => boolean | Promise<boolean>;
/**
* Internal error class used to bypass runCli's logging without stack trace
*
* Used only for malformed commands and options
*/
declare class BroCliError extends Error {
event?: BroCliEvent | undefined;
constructor(message: string | undefined, event?: BroCliEvent | undefined);
}
export { type AnyRawCommand, type BroCliConfig, BroCliError, type BroCliEvent, type BroCliEventType, type BuilderConfig, type BuilderConfigLimited, type Command, type CommandCandidate, type CommandHandler, type CommandHelpEvent, type CommandInfo, type CommandsInfo, type EventHandler, type EventType, type GenericBuilderInternals, type GenericBuilderInternalsFields, type GenericBuilderInternalsFieldsLimited, type GenericBuilderInternalsLimited, type GenericCommandHandler, type GenericValidationViolation, type GlobalHelpEvent, type InnerCommandParseRes, type MissingArgsEvent, OptionBuilderBase, type OptionType, type OutputType, type ProcessedBuilderConfig, type ProcessedOptions, type RawCommand, type Simplify, type TestResult, type TypeOf, type UnknownCommandEvent, type UnknownErrorEvent, type UnknownSubcommandEvent, type UnrecognizedArgsEvent, type ValidationErrorEvent, type ValidationViolation, type VersionEvent, boolean, command, commandsInfo, getCommandNameWithParents, handler, number, positional, run, string, test };

298
node_modules/@drizzle-team/brocli/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,298 @@
type OptionType = 'string' | 'boolean' | 'number' | 'positional';
type OutputType = string | boolean | number | undefined;
type BuilderConfig<TType extends OptionType = OptionType> = {
name?: string | undefined;
aliases: string[];
type: TType;
description?: string;
default?: OutputType;
isHidden?: boolean;
isRequired?: boolean;
isInt?: boolean;
minVal?: number;
maxVal?: number;
enumVals?: [string, ...string[]];
};
type ProcessedBuilderConfig = {
name: string;
aliases: string[];
type: OptionType;
description?: string;
default?: OutputType;
isHidden?: boolean;
isRequired?: boolean;
isInt?: boolean;
minVal?: number;
maxVal?: number;
enumVals?: [string, ...string[]];
};
type BuilderConfigLimited = BuilderConfig & {
type: Exclude<OptionType, 'positional'>;
};
declare class OptionBuilderBase<TBuilderConfig extends BuilderConfig = BuilderConfig, TOutput extends OutputType = string, TOmit extends string = '', TEnums extends string | undefined = undefined> {
_: {
config: TBuilderConfig;
/**
* Type-level only field
*
* Do not attempt to access at a runtime
*/
$output: TOutput;
};
private config;
constructor(config?: TBuilderConfig);
string<TName extends string>(name: TName): Omit<OptionBuilderBase<BuilderConfig<'string'>, string | undefined, TOmit | OptionType | 'min' | 'max' | 'int'>, TOmit | OptionType | 'min' | 'max' | 'int'>;
string(): Omit<OptionBuilderBase<BuilderConfig<'string'>, string | undefined, TOmit | OptionType | 'min' | 'max' | 'int'>, TOmit | OptionType | 'min' | 'max' | 'int'>;
number<TName extends string>(name: TName): Omit<OptionBuilderBase<BuilderConfig<'number'>, number | undefined, TOmit | OptionType | 'enum'>, TOmit | OptionType | 'enum'>;
number(): Omit<OptionBuilderBase<BuilderConfig<'number'>, string | undefined, TOmit | OptionType | 'enum'>, TOmit | OptionType | 'enum'>;
boolean<TName extends string>(name: TName): Omit<OptionBuilderBase<BuilderConfig<'boolean'>, boolean | undefined, TOmit | OptionType | 'min' | 'max' | 'enum' | 'int'>, TOmit | OptionType | 'min' | 'max' | 'enum' | 'int'>;
boolean(): Omit<OptionBuilderBase<BuilderConfig<'boolean'>, boolean | undefined, TOmit | OptionType | 'min' | 'max' | 'enum' | 'int'>, TOmit | OptionType | 'min' | 'max' | 'enum' | 'int'>;
positional<TName extends string>(displayName: TName): Omit<OptionBuilderBase<BuilderConfig<'positional'>, string | undefined, TOmit | OptionType | 'min' | 'max' | 'int' | 'alias'>, TOmit | OptionType | 'min' | 'max' | 'int' | 'alias'>;
positional(): Omit<OptionBuilderBase<BuilderConfig<'positional'>, string | undefined, TOmit | OptionType | 'min' | 'max' | 'int' | 'alias'>, TOmit | OptionType | 'min' | 'max' | 'int' | 'alias'>;
alias(...aliases: string[]): Omit<OptionBuilderBase<TBuilderConfig, TOutput, TOmit | 'alias'>, TOmit | 'alias'>;
desc<TDescription extends string>(description: TDescription): Omit<OptionBuilderBase<TBuilderConfig, TOutput, TOmit | 'desc'>, TOmit | 'desc'>;
hidden(): Omit<OptionBuilderBase<TBuilderConfig, TOutput, TOmit | 'hidden'>, TOmit | 'hidden'>;
required(): Omit<OptionBuilderBase<TBuilderConfig, Exclude<TOutput, undefined>, TOmit | 'required' | 'default'>, TOmit | 'required' | 'default'>;
default<TDefVal extends TEnums extends undefined ? Exclude<TOutput, undefined> : TEnums>(value: TDefVal): Omit<OptionBuilderBase<TBuilderConfig, Exclude<TOutput, undefined>, TOmit | 'enum' | 'required' | 'default', TEnums>, TOmit | 'enum' | 'required' | 'default'>;
enum<TValues extends [string, ...string[]], TUnion extends TValues[number] = TValues[number]>(...values: TValues): Omit<OptionBuilderBase<TBuilderConfig, TUnion | (TOutput extends undefined ? undefined : never), TOmit | 'enum', TUnion>, TOmit | 'enum'>;
min(value: number): Omit<OptionBuilderBase<TBuilderConfig, TOutput, TOmit | 'min'>, TOmit | 'min'>;
max(value: number): Omit<OptionBuilderBase<TBuilderConfig, TOutput, TOmit | 'max'>, TOmit | 'max'>;
int(): Omit<OptionBuilderBase<TBuilderConfig, TOutput, TOmit | 'int'>, TOmit | 'int'>;
}
type GenericBuilderInternalsFields = {
/**
* Type-level only field
*
* Do not attempt to access at a runtime
*/
$output: OutputType;
config: BuilderConfig;
};
type GenericBuilderInternals = {
_: GenericBuilderInternalsFields;
};
type GenericBuilderInternalsFieldsLimited = {
/**
* Type-level only field
*
* Do not attempt to access at a runtime
*/
$output: OutputType;
config: BuilderConfigLimited;
};
type GenericBuilderInternalsLimited = {
_: GenericBuilderInternalsFieldsLimited;
};
type ProcessedOptions<TOptionConfig extends Record<string, GenericBuilderInternals> = Record<string, GenericBuilderInternals>> = {
[K in keyof TOptionConfig]: K extends string ? {
config: ProcessedBuilderConfig;
/**
* Type-level only field
*
* Do not attempt to access at a runtime
*/
$output: TOptionConfig[K]['_']['$output'];
} : never;
};
type Simplify<T> = {
[K in keyof T]: T[K];
} & {};
type TypeOf<TOptions extends Record<string, GenericBuilderInternals>> = Simplify<{
[K in keyof TOptions]: TOptions[K]['_']['$output'];
}>;
declare function string<TName extends string>(name: TName): Omit<OptionBuilderBase<BuilderConfig<'string'>, string | undefined, OptionType | 'min' | 'max' | 'int'>, OptionType | 'min' | 'max' | 'int'>;
declare function string(): Omit<OptionBuilderBase<BuilderConfig<'string'>, string | undefined, OptionType | 'min' | 'max' | 'int'>, OptionType | 'min' | 'max' | 'int'>;
declare function number<TName extends string>(name: TName): Omit<OptionBuilderBase<BuilderConfig<'number'>, number | undefined, OptionType | 'enum'>, OptionType | 'enum'>;
declare function number(): Omit<OptionBuilderBase<BuilderConfig<'number'>, number | undefined, OptionType | 'enum'>, OptionType | 'enum'>;
declare function boolean<TName extends string>(name: TName): Omit<OptionBuilderBase<BuilderConfig<'boolean'>, boolean | undefined, OptionType | 'min' | 'max' | 'int' | 'enum'>, OptionType | 'min' | 'max' | 'int' | 'enum'>;
declare function boolean(): Omit<OptionBuilderBase<BuilderConfig<'boolean'>, boolean | undefined, OptionType | 'min' | 'max' | 'int' | 'enum'>, OptionType | 'min' | 'max' | 'int' | 'enum'>;
declare function positional<TName extends string>(displayName: TName): Omit<OptionBuilderBase<BuilderConfig<'positional'>, string | undefined, OptionType | 'min' | 'max' | 'int' | 'alias'>, OptionType | 'min' | 'max' | 'int' | 'alias'>;
declare function positional(): Omit<OptionBuilderBase<BuilderConfig<'positional'>, string | undefined, OptionType | 'min' | 'max' | 'int' | 'alias'>, OptionType | 'min' | 'max' | 'int' | 'alias'>;
type CommandHandler<TOpts extends Record<string, GenericBuilderInternals> | undefined = Record<string, GenericBuilderInternals> | undefined> = (options: TOpts extends Record<string, GenericBuilderInternals> ? TypeOf<TOpts> : undefined) => any;
type CommandInfo = {
name: string;
aliases?: [string, ...string[]];
desc?: string;
shortDesc?: string;
hidden?: boolean;
options?: Record<string, ProcessedBuilderConfig>;
metadata?: any;
subcommands?: CommandsInfo;
};
type CommandsInfo = Record<string, CommandInfo>;
type EventType = 'before' | 'after';
type BroCliConfig = {
name?: string;
description?: string;
argSource?: string[];
help?: string | Function;
version?: string | Function;
omitKeysOfUndefinedOptions?: boolean;
hook?: (event: EventType, command: Command) => any;
theme?: EventHandler;
};
type GenericCommandHandler = (options?: Record<string, OutputType> | undefined) => any;
type RawCommand<TOpts extends Record<string, GenericBuilderInternals> | undefined = Record<string, GenericBuilderInternals> | undefined, TOptsData = TOpts extends Record<string, GenericBuilderInternals> ? TypeOf<TOpts> : undefined, TTransformed = TOptsData extends undefined ? undefined : TOptsData> = {
name?: string;
aliases?: [string, ...string[]];
desc?: string;
shortDesc?: string;
hidden?: boolean;
options?: TOpts;
help?: string | Function;
transform?: (options: TOptsData) => TTransformed;
handler?: (options: Awaited<TTransformed>) => any;
subcommands?: [Command, ...Command[]];
metadata?: any;
};
type AnyRawCommand<TOpts extends Record<string, GenericBuilderInternals> | undefined = Record<string, GenericBuilderInternals> | undefined> = {
name?: string;
aliases?: [string, ...string[]];
desc?: string;
shortDesc?: string;
hidden?: boolean;
options?: TOpts;
help?: string | Function;
transform?: GenericCommandHandler;
handler?: GenericCommandHandler;
subcommands?: [Command, ...Command[]];
metadata?: any;
};
type Command<TOptsType = any, TTransformedType = any> = {
name: string;
aliases?: [string, ...string[]];
desc?: string;
shortDesc?: string;
hidden?: boolean;
options?: ProcessedOptions;
help?: string | Function;
transform?: GenericCommandHandler;
handler?: GenericCommandHandler;
subcommands?: [Command, ...Command[]];
parent?: Command;
metadata?: any;
};
type CommandCandidate = {
data: string;
originalIndex: number;
};
type InnerCommandParseRes = {
command: Command | undefined;
args: string[];
};
type TestResult<THandlerInput> = {
type: 'handler';
options: THandlerInput;
} | {
type: 'help' | 'version';
} | {
type: 'error';
error: unknown;
};
declare const command: <TOpts extends Record<string, GenericBuilderInternals> | undefined, TOptsData = TOpts extends Record<string, GenericBuilderInternals> ? { [K_1 in keyof { [K in keyof TOpts]: TOpts[K]["_"]["$output"]; }]: { [K in keyof TOpts]: TOpts[K]["_"]["$output"]; }[K_1]; } : undefined, TTransformed = TOptsData>(command: RawCommand<TOpts, TOptsData, TTransformed>) => Command<TOptsData, Awaited<TTransformed>>;
declare const getCommandNameWithParents: (command: Command) => string;
/**
* Runs CLI commands
*
* @param commands - command collection
*
* @param config - additional settings
*/
declare const run: (commands: Command[], config?: BroCliConfig) => Promise<void>;
declare const handler: <TOpts extends Record<string, GenericBuilderInternals>>(options: TOpts, handler: CommandHandler<TOpts>) => CommandHandler<TOpts>;
declare const test: <TOpts, THandlerInput>(command: Command<TOpts, THandlerInput>, args: string) => Promise<TestResult<THandlerInput>>;
declare const commandsInfo: (commands: Command[]) => CommandsInfo;
type CommandHelpEvent = {
type: 'command_help';
name: string | undefined;
description: string | undefined;
command: Command;
};
type GlobalHelpEvent = {
type: 'global_help';
description: string | undefined;
name: string | undefined;
commands: Command[];
};
type MissingArgsEvent = {
type: 'error';
violation: 'missing_args_error';
name: string | undefined;
description: string | undefined;
command: Command;
missing: [string[], ...string[][]];
};
type UnrecognizedArgsEvent = {
type: 'error';
violation: 'unrecognized_args_error';
name: string | undefined;
description: string | undefined;
command: Command;
unrecognized: [string, ...string[]];
};
type UnknownCommandEvent = {
type: 'error';
violation: 'unknown_command_error';
name: string | undefined;
description: string | undefined;
commands: Command[];
offender: string;
};
type UnknownSubcommandEvent = {
type: 'error';
violation: 'unknown_subcommand_error';
name: string | undefined;
description: string | undefined;
command: Command;
offender: string;
};
type UnknownErrorEvent = {
type: 'error';
violation: 'unknown_error';
name: string | undefined;
description: string | undefined;
error: unknown;
};
type VersionEvent = {
type: 'version';
name: string | undefined;
description: string | undefined;
};
type GenericValidationViolation = 'above_max' | 'below_min' | 'expected_int' | 'invalid_boolean_syntax' | 'invalid_string_syntax' | 'invalid_number_syntax' | 'invalid_number_value' | 'enum_violation';
type ValidationViolation = BroCliEvent extends infer Event ? Event extends {
violation: string;
} ? Event['violation'] : never : never;
type ValidationErrorEvent = {
type: 'error';
violation: GenericValidationViolation;
name: string | undefined;
description: string | undefined;
command: Command;
option: ProcessedBuilderConfig;
offender: {
namePart?: string;
dataPart?: string;
};
};
type BroCliEvent = CommandHelpEvent | GlobalHelpEvent | MissingArgsEvent | UnrecognizedArgsEvent | UnknownCommandEvent | UnknownSubcommandEvent | ValidationErrorEvent | VersionEvent | UnknownErrorEvent;
type BroCliEventType = BroCliEvent['type'];
/**
* Return `true` if your handler processes the event
*
* Return `false` to process event with a built-in handler
*/
type EventHandler = (event: BroCliEvent) => boolean | Promise<boolean>;
/**
* Internal error class used to bypass runCli's logging without stack trace
*
* Used only for malformed commands and options
*/
declare class BroCliError extends Error {
event?: BroCliEvent | undefined;
constructor(message: string | undefined, event?: BroCliEvent | undefined);
}
export { type AnyRawCommand, type BroCliConfig, BroCliError, type BroCliEvent, type BroCliEventType, type BuilderConfig, type BuilderConfigLimited, type Command, type CommandCandidate, type CommandHandler, type CommandHelpEvent, type CommandInfo, type CommandsInfo, type EventHandler, type EventType, type GenericBuilderInternals, type GenericBuilderInternalsFields, type GenericBuilderInternalsFieldsLimited, type GenericBuilderInternalsLimited, type GenericCommandHandler, type GenericValidationViolation, type GlobalHelpEvent, type InnerCommandParseRes, type MissingArgsEvent, OptionBuilderBase, type OptionType, type OutputType, type ProcessedBuilderConfig, type ProcessedOptions, type RawCommand, type Simplify, type TestResult, type TypeOf, type UnknownCommandEvent, type UnknownErrorEvent, type UnknownSubcommandEvent, type UnrecognizedArgsEvent, type ValidationErrorEvent, type ValidationViolation, type VersionEvent, boolean, command, commandsInfo, getCommandNameWithParents, handler, number, positional, run, string, test };

1485
node_modules/@drizzle-team/brocli/index.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

1
node_modules/@drizzle-team/brocli/index.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

59
node_modules/@drizzle-team/brocli/package.json generated vendored Executable file
View File

@@ -0,0 +1,59 @@
{
"name": "@drizzle-team/brocli",
"type": "module",
"author": "Drizzle Team",
"version": "0.10.2",
"description": "Modern type-safe way of building CLIs",
"license": "Apache-2.0",
"sideEffects": false,
"publishConfig": {
"provenance": true
},
"repository": {
"type": "git",
"url": "git+https://github.com/drizzle-team/brocli.git"
},
"homepage": "https://github.com/drizzle-team/brocli",
"scripts": {
"build": "pnpm tsx scripts/build.ts",
"b": "pnpm build",
"pack": "(cd dist && npm pack --pack-destination ..) && rm -f package.tgz && mv *.tgz package.tgz",
"publish": "npm publish package.tgz",
"test": "vitest run && npx tsc --noEmit",
"mtest": "npx tsx tests/manual.ts",
"lint": "dprint check --list-different"
},
"devDependencies": {
"@arethetypeswrong/cli": "^0.15.3",
"@originjs/vite-plugin-commonjs": "^1.0.3",
"@types/clone": "^2.1.4",
"@types/node": "^20.12.13",
"@types/shell-quote": "^1.7.5",
"clone": "^2.1.2",
"dprint": "^0.46.2",
"shell-quote": "^1.8.1",
"tsup": "^8.1.0",
"tsx": "^4.7.0",
"typescript": "latest",
"vite-tsconfig-paths": "^4.3.2",
"vitest": "^1.6.0",
"zx": "^8.1.2"
},
"main": "./index.cjs",
"module": "./index.js",
"types": "./index.d.ts",
"exports": {
".": {
"import": {
"types": "./index.d.ts",
"default": "./index.js"
},
"require": {
"types": "./index.d.cjs",
"default": "./index.cjs"
},
"types": "./index.d.ts",
"default": "./index.js"
}
}
}

21
node_modules/@esbuild-kit/core-utils/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) Hiroki Osame <hiroki.osame@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

11
node_modules/@esbuild-kit/core-utils/README.md generated vendored Normal file
View File

@@ -0,0 +1,11 @@
# @esbuild-kit/core-utils
Core utility functions used by [@esbuild-kit/cjs-loader](https://github.com/esbuild-kit/cjs-loader) and [@esbuild-kit/esm-loader](https://github.com/esbuild-kit/esm-loader).
## Library
### esbuild
Transform defaults, caching, and source-map handling.
### Source map support
Uses [native source-map](https://nodejs.org/api/process.html#processsetsourcemapsenabledval) if available, fallsback to [source-map-support](https://www.npmjs.com/package/source-map-support).

32
node_modules/@esbuild-kit/core-utils/dist/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,32 @@
import { MessagePort } from 'node:worker_threads';
import { UrlAndMap } from 'source-map-support';
import { TransformOptions } from 'esbuild';
type Transformed = {
code: string;
map: RawSourceMap;
warnings?: unknown[];
};
type RawSourceMap = UrlAndMap['map'];
declare function installSourceMapSupport(
/**
* To support Node v20 where loaders are executed in its own thread
* https://nodejs.org/docs/latest-v20.x/api/esm.html#globalpreload
*/
loaderPort?: MessagePort): ({ code, map }: Transformed, filePath: string, mainThreadPort?: MessagePort) => string;
declare function transformDynamicImport(filePath: string, code: string): {
code: string;
map: any;
} | undefined;
declare function transformSync(code: string, filePath: string, extendOptions?: TransformOptions): Transformed;
declare function transform(code: string, filePath: string, extendOptions?: TransformOptions): Promise<Transformed>;
declare const resolveTsPath: (filePath: string) => string | undefined;
type Version = [number, number, number];
declare const compareNodeVersion: (version: Version) => number;
export { RawSourceMap, compareNodeVersion, installSourceMapSupport, resolveTsPath, transform, transformDynamicImport, transformSync };

23
node_modules/@esbuild-kit/core-utils/dist/index.js generated vendored Executable file

File diff suppressed because one or more lines are too long

View File

@@ -0,0 +1 @@
../esbuild/bin/esbuild

View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2020 Evan Wallace
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,3 @@
# esbuild
This is a JavaScript bundler and minifier. See https://github.com/evanw/esbuild and the [JavaScript API documentation](https://esbuild.github.io/api/) for details.

Binary file not shown.

View File

@@ -0,0 +1,287 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
// lib/npm/node-platform.ts
var fs = require("fs");
var os = require("os");
var path = require("path");
var ESBUILD_BINARY_PATH = process.env.ESBUILD_BINARY_PATH || ESBUILD_BINARY_PATH;
var isValidBinaryPath = (x) => !!x && x !== "/usr/bin/esbuild";
var knownWindowsPackages = {
"win32 arm64 LE": "@esbuild/win32-arm64",
"win32 ia32 LE": "@esbuild/win32-ia32",
"win32 x64 LE": "@esbuild/win32-x64"
};
var knownUnixlikePackages = {
"android arm64 LE": "@esbuild/android-arm64",
"darwin arm64 LE": "@esbuild/darwin-arm64",
"darwin x64 LE": "@esbuild/darwin-x64",
"freebsd arm64 LE": "@esbuild/freebsd-arm64",
"freebsd x64 LE": "@esbuild/freebsd-x64",
"linux arm LE": "@esbuild/linux-arm",
"linux arm64 LE": "@esbuild/linux-arm64",
"linux ia32 LE": "@esbuild/linux-ia32",
"linux mips64el LE": "@esbuild/linux-mips64el",
"linux ppc64 LE": "@esbuild/linux-ppc64",
"linux riscv64 LE": "@esbuild/linux-riscv64",
"linux s390x BE": "@esbuild/linux-s390x",
"linux x64 LE": "@esbuild/linux-x64",
"linux loong64 LE": "@esbuild/linux-loong64",
"netbsd x64 LE": "@esbuild/netbsd-x64",
"openbsd x64 LE": "@esbuild/openbsd-x64",
"sunos x64 LE": "@esbuild/sunos-x64"
};
var knownWebAssemblyFallbackPackages = {
"android arm LE": "@esbuild/android-arm",
"android x64 LE": "@esbuild/android-x64"
};
function pkgAndSubpathForCurrentPlatform() {
let pkg;
let subpath;
let isWASM = false;
let platformKey = `${process.platform} ${os.arch()} ${os.endianness()}`;
if (platformKey in knownWindowsPackages) {
pkg = knownWindowsPackages[platformKey];
subpath = "esbuild.exe";
} else if (platformKey in knownUnixlikePackages) {
pkg = knownUnixlikePackages[platformKey];
subpath = "bin/esbuild";
} else if (platformKey in knownWebAssemblyFallbackPackages) {
pkg = knownWebAssemblyFallbackPackages[platformKey];
subpath = "bin/esbuild";
isWASM = true;
} else {
throw new Error(`Unsupported platform: ${platformKey}`);
}
return { pkg, subpath, isWASM };
}
function downloadedBinPath(pkg, subpath) {
const esbuildLibDir = path.dirname(require.resolve("esbuild"));
return path.join(esbuildLibDir, `downloaded-${pkg.replace("/", "-")}-${path.basename(subpath)}`);
}
// lib/npm/node-install.ts
var fs2 = require("fs");
var os2 = require("os");
var path2 = require("path");
var zlib = require("zlib");
var https = require("https");
var child_process = require("child_process");
var versionFromPackageJSON = require(path2.join(__dirname, "package.json")).version;
var toPath = path2.join(__dirname, "bin", "esbuild");
var isToPathJS = true;
function validateBinaryVersion(...command) {
command.push("--version");
let stdout;
try {
stdout = child_process.execFileSync(command.shift(), command, {
// Without this, this install script strangely crashes with the error
// "EACCES: permission denied, write" but only on Ubuntu Linux when node is
// installed from the Snap Store. This is not a problem when you download
// the official version of node. The problem appears to be that stderr
// (i.e. file descriptor 2) isn't writable?
//
// More info:
// - https://snapcraft.io/ (what the Snap Store is)
// - https://nodejs.org/dist/ (download the official version of node)
// - https://github.com/evanw/esbuild/issues/1711#issuecomment-1027554035
//
stdio: "pipe"
}).toString().trim();
} catch (err) {
if (os2.platform() === "darwin" && /_SecTrustEvaluateWithError/.test(err + "")) {
let os3 = "this version of macOS";
try {
os3 = "macOS " + child_process.execFileSync("sw_vers", ["-productVersion"]).toString().trim();
} catch {
}
throw new Error(`The "esbuild" package cannot be installed because ${os3} is too outdated.
The Go compiler (which esbuild relies on) no longer supports ${os3},
which means the "esbuild" binary executable can't be run. You can either:
* Update your version of macOS to one that the Go compiler supports
* Use the "esbuild-wasm" package instead of the "esbuild" package
* Build esbuild yourself using an older version of the Go compiler
`);
}
throw err;
}
if (stdout !== versionFromPackageJSON) {
throw new Error(`Expected ${JSON.stringify(versionFromPackageJSON)} but got ${JSON.stringify(stdout)}`);
}
}
function isYarn() {
const { npm_config_user_agent } = process.env;
if (npm_config_user_agent) {
return /\byarn\//.test(npm_config_user_agent);
}
return false;
}
function fetch(url) {
return new Promise((resolve, reject) => {
https.get(url, (res) => {
if ((res.statusCode === 301 || res.statusCode === 302) && res.headers.location)
return fetch(res.headers.location).then(resolve, reject);
if (res.statusCode !== 200)
return reject(new Error(`Server responded with ${res.statusCode}`));
let chunks = [];
res.on("data", (chunk) => chunks.push(chunk));
res.on("end", () => resolve(Buffer.concat(chunks)));
}).on("error", reject);
});
}
function extractFileFromTarGzip(buffer, subpath) {
try {
buffer = zlib.unzipSync(buffer);
} catch (err) {
throw new Error(`Invalid gzip data in archive: ${err && err.message || err}`);
}
let str = (i, n) => String.fromCharCode(...buffer.subarray(i, i + n)).replace(/\0.*$/, "");
let offset = 0;
subpath = `package/${subpath}`;
while (offset < buffer.length) {
let name = str(offset, 100);
let size = parseInt(str(offset + 124, 12), 8);
offset += 512;
if (!isNaN(size)) {
if (name === subpath)
return buffer.subarray(offset, offset + size);
offset += size + 511 & ~511;
}
}
throw new Error(`Could not find ${JSON.stringify(subpath)} in archive`);
}
function installUsingNPM(pkg, subpath, binPath) {
const env = { ...process.env, npm_config_global: void 0 };
const esbuildLibDir = path2.dirname(require.resolve("esbuild"));
const installDir = path2.join(esbuildLibDir, "npm-install");
fs2.mkdirSync(installDir);
try {
fs2.writeFileSync(path2.join(installDir, "package.json"), "{}");
child_process.execSync(
`npm install --loglevel=error --prefer-offline --no-audit --progress=false ${pkg}@${versionFromPackageJSON}`,
{ cwd: installDir, stdio: "pipe", env }
);
const installedBinPath = path2.join(installDir, "node_modules", pkg, subpath);
fs2.renameSync(installedBinPath, binPath);
} finally {
try {
removeRecursive(installDir);
} catch {
}
}
}
function removeRecursive(dir) {
for (const entry of fs2.readdirSync(dir)) {
const entryPath = path2.join(dir, entry);
let stats;
try {
stats = fs2.lstatSync(entryPath);
} catch {
continue;
}
if (stats.isDirectory())
removeRecursive(entryPath);
else
fs2.unlinkSync(entryPath);
}
fs2.rmdirSync(dir);
}
function applyManualBinaryPathOverride(overridePath) {
const pathString = JSON.stringify(overridePath);
fs2.writeFileSync(toPath, `#!/usr/bin/env node
require('child_process').execFileSync(${pathString}, process.argv.slice(2), { stdio: 'inherit' });
`);
const libMain = path2.join(__dirname, "lib", "main.js");
const code = fs2.readFileSync(libMain, "utf8");
fs2.writeFileSync(libMain, `var ESBUILD_BINARY_PATH = ${pathString};
${code}`);
}
function maybeOptimizePackage(binPath) {
if (os2.platform() !== "win32" && !isYarn()) {
const tempPath = path2.join(__dirname, "bin-esbuild");
try {
fs2.linkSync(binPath, tempPath);
fs2.renameSync(tempPath, toPath);
isToPathJS = false;
fs2.unlinkSync(tempPath);
} catch {
}
}
}
async function downloadDirectlyFromNPM(pkg, subpath, binPath) {
const url = `https://registry.npmjs.org/${pkg}/-/${pkg.replace("@esbuild/", "")}-${versionFromPackageJSON}.tgz`;
console.error(`[esbuild] Trying to download ${JSON.stringify(url)}`);
try {
fs2.writeFileSync(binPath, extractFileFromTarGzip(await fetch(url), subpath));
fs2.chmodSync(binPath, 493);
} catch (e) {
console.error(`[esbuild] Failed to download ${JSON.stringify(url)}: ${e && e.message || e}`);
throw e;
}
}
async function checkAndPreparePackage() {
if (isValidBinaryPath(ESBUILD_BINARY_PATH)) {
if (!fs2.existsSync(ESBUILD_BINARY_PATH)) {
console.warn(`[esbuild] Ignoring bad configuration: ESBUILD_BINARY_PATH=${ESBUILD_BINARY_PATH}`);
} else {
applyManualBinaryPathOverride(ESBUILD_BINARY_PATH);
return;
}
}
const { pkg, subpath } = pkgAndSubpathForCurrentPlatform();
let binPath;
try {
binPath = require.resolve(`${pkg}/${subpath}`);
} catch (e) {
console.error(`[esbuild] Failed to find package "${pkg}" on the file system
This can happen if you use the "--no-optional" flag. The "optionalDependencies"
package.json feature is used by esbuild to install the correct binary executable
for your current platform. This install script will now attempt to work around
this. If that fails, you need to remove the "--no-optional" flag to use esbuild.
`);
binPath = downloadedBinPath(pkg, subpath);
try {
console.error(`[esbuild] Trying to install package "${pkg}" using npm`);
installUsingNPM(pkg, subpath, binPath);
} catch (e2) {
console.error(`[esbuild] Failed to install package "${pkg}" using npm: ${e2 && e2.message || e2}`);
try {
await downloadDirectlyFromNPM(pkg, subpath, binPath);
} catch (e3) {
throw new Error(`Failed to install package "${pkg}"`);
}
}
}
maybeOptimizePackage(binPath);
}
checkAndPreparePackage().then(() => {
if (isToPathJS) {
validateBinaryVersion(process.execPath, toPath);
} else {
validateBinaryVersion(toPath);
}
});

View File

@@ -0,0 +1,660 @@
export type Platform = 'browser' | 'node' | 'neutral'
export type Format = 'iife' | 'cjs' | 'esm'
export type Loader = 'base64' | 'binary' | 'copy' | 'css' | 'dataurl' | 'default' | 'empty' | 'file' | 'js' | 'json' | 'jsx' | 'local-css' | 'text' | 'ts' | 'tsx'
export type LogLevel = 'verbose' | 'debug' | 'info' | 'warning' | 'error' | 'silent'
export type Charset = 'ascii' | 'utf8'
export type Drop = 'console' | 'debugger'
interface CommonOptions {
/** Documentation: https://esbuild.github.io/api/#sourcemap */
sourcemap?: boolean | 'linked' | 'inline' | 'external' | 'both'
/** Documentation: https://esbuild.github.io/api/#legal-comments */
legalComments?: 'none' | 'inline' | 'eof' | 'linked' | 'external'
/** Documentation: https://esbuild.github.io/api/#source-root */
sourceRoot?: string
/** Documentation: https://esbuild.github.io/api/#sources-content */
sourcesContent?: boolean
/** Documentation: https://esbuild.github.io/api/#format */
format?: Format
/** Documentation: https://esbuild.github.io/api/#global-name */
globalName?: string
/** Documentation: https://esbuild.github.io/api/#target */
target?: string | string[]
/** Documentation: https://esbuild.github.io/api/#supported */
supported?: Record<string, boolean>
/** Documentation: https://esbuild.github.io/api/#platform */
platform?: Platform
/** Documentation: https://esbuild.github.io/api/#mangle-props */
mangleProps?: RegExp
/** Documentation: https://esbuild.github.io/api/#mangle-props */
reserveProps?: RegExp
/** Documentation: https://esbuild.github.io/api/#mangle-props */
mangleQuoted?: boolean
/** Documentation: https://esbuild.github.io/api/#mangle-props */
mangleCache?: Record<string, string | false>
/** Documentation: https://esbuild.github.io/api/#drop */
drop?: Drop[]
/** Documentation: https://esbuild.github.io/api/#drop-labels */
dropLabels?: string[]
/** Documentation: https://esbuild.github.io/api/#minify */
minify?: boolean
/** Documentation: https://esbuild.github.io/api/#minify */
minifyWhitespace?: boolean
/** Documentation: https://esbuild.github.io/api/#minify */
minifyIdentifiers?: boolean
/** Documentation: https://esbuild.github.io/api/#minify */
minifySyntax?: boolean
/** Documentation: https://esbuild.github.io/api/#line-limit */
lineLimit?: number
/** Documentation: https://esbuild.github.io/api/#charset */
charset?: Charset
/** Documentation: https://esbuild.github.io/api/#tree-shaking */
treeShaking?: boolean
/** Documentation: https://esbuild.github.io/api/#ignore-annotations */
ignoreAnnotations?: boolean
/** Documentation: https://esbuild.github.io/api/#jsx */
jsx?: 'transform' | 'preserve' | 'automatic'
/** Documentation: https://esbuild.github.io/api/#jsx-factory */
jsxFactory?: string
/** Documentation: https://esbuild.github.io/api/#jsx-fragment */
jsxFragment?: string
/** Documentation: https://esbuild.github.io/api/#jsx-import-source */
jsxImportSource?: string
/** Documentation: https://esbuild.github.io/api/#jsx-development */
jsxDev?: boolean
/** Documentation: https://esbuild.github.io/api/#jsx-side-effects */
jsxSideEffects?: boolean
/** Documentation: https://esbuild.github.io/api/#define */
define?: { [key: string]: string }
/** Documentation: https://esbuild.github.io/api/#pure */
pure?: string[]
/** Documentation: https://esbuild.github.io/api/#keep-names */
keepNames?: boolean
/** Documentation: https://esbuild.github.io/api/#color */
color?: boolean
/** Documentation: https://esbuild.github.io/api/#log-level */
logLevel?: LogLevel
/** Documentation: https://esbuild.github.io/api/#log-limit */
logLimit?: number
/** Documentation: https://esbuild.github.io/api/#log-override */
logOverride?: Record<string, LogLevel>
/** Documentation: https://esbuild.github.io/api/#tsconfig-raw */
tsconfigRaw?: string | TsconfigRaw
}
export interface TsconfigRaw {
compilerOptions?: {
alwaysStrict?: boolean
baseUrl?: boolean
experimentalDecorators?: boolean
importsNotUsedAsValues?: 'remove' | 'preserve' | 'error'
jsx?: 'preserve' | 'react-native' | 'react' | 'react-jsx' | 'react-jsxdev'
jsxFactory?: string
jsxFragmentFactory?: string
jsxImportSource?: string
paths?: Record<string, string[]>
preserveValueImports?: boolean
strict?: boolean
target?: string
useDefineForClassFields?: boolean
verbatimModuleSyntax?: boolean
}
}
export interface BuildOptions extends CommonOptions {
/** Documentation: https://esbuild.github.io/api/#bundle */
bundle?: boolean
/** Documentation: https://esbuild.github.io/api/#splitting */
splitting?: boolean
/** Documentation: https://esbuild.github.io/api/#preserve-symlinks */
preserveSymlinks?: boolean
/** Documentation: https://esbuild.github.io/api/#outfile */
outfile?: string
/** Documentation: https://esbuild.github.io/api/#metafile */
metafile?: boolean
/** Documentation: https://esbuild.github.io/api/#outdir */
outdir?: string
/** Documentation: https://esbuild.github.io/api/#outbase */
outbase?: string
/** Documentation: https://esbuild.github.io/api/#external */
external?: string[]
/** Documentation: https://esbuild.github.io/api/#packages */
packages?: 'external'
/** Documentation: https://esbuild.github.io/api/#alias */
alias?: Record<string, string>
/** Documentation: https://esbuild.github.io/api/#loader */
loader?: { [ext: string]: Loader }
/** Documentation: https://esbuild.github.io/api/#resolve-extensions */
resolveExtensions?: string[]
/** Documentation: https://esbuild.github.io/api/#main-fields */
mainFields?: string[]
/** Documentation: https://esbuild.github.io/api/#conditions */
conditions?: string[]
/** Documentation: https://esbuild.github.io/api/#write */
write?: boolean
/** Documentation: https://esbuild.github.io/api/#allow-overwrite */
allowOverwrite?: boolean
/** Documentation: https://esbuild.github.io/api/#tsconfig */
tsconfig?: string
/** Documentation: https://esbuild.github.io/api/#out-extension */
outExtension?: { [ext: string]: string }
/** Documentation: https://esbuild.github.io/api/#public-path */
publicPath?: string
/** Documentation: https://esbuild.github.io/api/#entry-names */
entryNames?: string
/** Documentation: https://esbuild.github.io/api/#chunk-names */
chunkNames?: string
/** Documentation: https://esbuild.github.io/api/#asset-names */
assetNames?: string
/** Documentation: https://esbuild.github.io/api/#inject */
inject?: string[]
/** Documentation: https://esbuild.github.io/api/#banner */
banner?: { [type: string]: string }
/** Documentation: https://esbuild.github.io/api/#footer */
footer?: { [type: string]: string }
/** Documentation: https://esbuild.github.io/api/#entry-points */
entryPoints?: string[] | Record<string, string> | { in: string, out: string }[]
/** Documentation: https://esbuild.github.io/api/#stdin */
stdin?: StdinOptions
/** Documentation: https://esbuild.github.io/plugins/ */
plugins?: Plugin[]
/** Documentation: https://esbuild.github.io/api/#working-directory */
absWorkingDir?: string
/** Documentation: https://esbuild.github.io/api/#node-paths */
nodePaths?: string[]; // The "NODE_PATH" variable from Node.js
}
export interface StdinOptions {
contents: string | Uint8Array
resolveDir?: string
sourcefile?: string
loader?: Loader
}
export interface Message {
id: string
pluginName: string
text: string
location: Location | null
notes: Note[]
/**
* Optional user-specified data that is passed through unmodified. You can
* use this to stash the original error, for example.
*/
detail: any
}
export interface Note {
text: string
location: Location | null
}
export interface Location {
file: string
namespace: string
/** 1-based */
line: number
/** 0-based, in bytes */
column: number
/** in bytes */
length: number
lineText: string
suggestion: string
}
export interface OutputFile {
path: string
contents: Uint8Array
hash: string
/** "contents" as text (changes automatically with "contents") */
readonly text: string
}
export interface BuildResult<ProvidedOptions extends BuildOptions = BuildOptions> {
errors: Message[]
warnings: Message[]
/** Only when "write: false" */
outputFiles: OutputFile[] | (ProvidedOptions['write'] extends false ? never : undefined)
/** Only when "metafile: true" */
metafile: Metafile | (ProvidedOptions['metafile'] extends true ? never : undefined)
/** Only when "mangleCache" is present */
mangleCache: Record<string, string | false> | (ProvidedOptions['mangleCache'] extends Object ? never : undefined)
}
export interface BuildFailure extends Error {
errors: Message[]
warnings: Message[]
}
/** Documentation: https://esbuild.github.io/api/#serve-arguments */
export interface ServeOptions {
port?: number
host?: string
servedir?: string
keyfile?: string
certfile?: string
fallback?: string
onRequest?: (args: ServeOnRequestArgs) => void
}
export interface ServeOnRequestArgs {
remoteAddress: string
method: string
path: string
status: number
/** The time to generate the response, not to send it */
timeInMS: number
}
/** Documentation: https://esbuild.github.io/api/#serve-return-values */
export interface ServeResult {
port: number
host: string
}
export interface TransformOptions extends CommonOptions {
/** Documentation: https://esbuild.github.io/api/#sourcefile */
sourcefile?: string
/** Documentation: https://esbuild.github.io/api/#loader */
loader?: Loader
/** Documentation: https://esbuild.github.io/api/#banner */
banner?: string
/** Documentation: https://esbuild.github.io/api/#footer */
footer?: string
}
export interface TransformResult<ProvidedOptions extends TransformOptions = TransformOptions> {
code: string
map: string
warnings: Message[]
/** Only when "mangleCache" is present */
mangleCache: Record<string, string | false> | (ProvidedOptions['mangleCache'] extends Object ? never : undefined)
/** Only when "legalComments" is "external" */
legalComments: string | (ProvidedOptions['legalComments'] extends 'external' ? never : undefined)
}
export interface TransformFailure extends Error {
errors: Message[]
warnings: Message[]
}
export interface Plugin {
name: string
setup: (build: PluginBuild) => (void | Promise<void>)
}
export interface PluginBuild {
/** Documentation: https://esbuild.github.io/plugins/#build-options */
initialOptions: BuildOptions
/** Documentation: https://esbuild.github.io/plugins/#resolve */
resolve(path: string, options?: ResolveOptions): Promise<ResolveResult>
/** Documentation: https://esbuild.github.io/plugins/#on-start */
onStart(callback: () =>
(OnStartResult | null | void | Promise<OnStartResult | null | void>)): void
/** Documentation: https://esbuild.github.io/plugins/#on-end */
onEnd(callback: (result: BuildResult) =>
(OnEndResult | null | void | Promise<OnEndResult | null | void>)): void
/** Documentation: https://esbuild.github.io/plugins/#on-resolve */
onResolve(options: OnResolveOptions, callback: (args: OnResolveArgs) =>
(OnResolveResult | null | undefined | Promise<OnResolveResult | null | undefined>)): void
/** Documentation: https://esbuild.github.io/plugins/#on-load */
onLoad(options: OnLoadOptions, callback: (args: OnLoadArgs) =>
(OnLoadResult | null | undefined | Promise<OnLoadResult | null | undefined>)): void
/** Documentation: https://esbuild.github.io/plugins/#on-dispose */
onDispose(callback: () => void): void
// This is a full copy of the esbuild library in case you need it
esbuild: {
context: typeof context,
build: typeof build,
buildSync: typeof buildSync,
transform: typeof transform,
transformSync: typeof transformSync,
formatMessages: typeof formatMessages,
formatMessagesSync: typeof formatMessagesSync,
analyzeMetafile: typeof analyzeMetafile,
analyzeMetafileSync: typeof analyzeMetafileSync,
initialize: typeof initialize,
version: typeof version,
}
}
/** Documentation: https://esbuild.github.io/plugins/#resolve-options */
export interface ResolveOptions {
pluginName?: string
importer?: string
namespace?: string
resolveDir?: string
kind?: ImportKind
pluginData?: any
}
/** Documentation: https://esbuild.github.io/plugins/#resolve-results */
export interface ResolveResult {
errors: Message[]
warnings: Message[]
path: string
external: boolean
sideEffects: boolean
namespace: string
suffix: string
pluginData: any
}
export interface OnStartResult {
errors?: PartialMessage[]
warnings?: PartialMessage[]
}
export interface OnEndResult {
errors?: PartialMessage[]
warnings?: PartialMessage[]
}
/** Documentation: https://esbuild.github.io/plugins/#on-resolve-options */
export interface OnResolveOptions {
filter: RegExp
namespace?: string
}
/** Documentation: https://esbuild.github.io/plugins/#on-resolve-arguments */
export interface OnResolveArgs {
path: string
importer: string
namespace: string
resolveDir: string
kind: ImportKind
pluginData: any
}
export type ImportKind =
| 'entry-point'
// JS
| 'import-statement'
| 'require-call'
| 'dynamic-import'
| 'require-resolve'
// CSS
| 'import-rule'
| 'composes-from'
| 'url-token'
/** Documentation: https://esbuild.github.io/plugins/#on-resolve-results */
export interface OnResolveResult {
pluginName?: string
errors?: PartialMessage[]
warnings?: PartialMessage[]
path?: string
external?: boolean
sideEffects?: boolean
namespace?: string
suffix?: string
pluginData?: any
watchFiles?: string[]
watchDirs?: string[]
}
/** Documentation: https://esbuild.github.io/plugins/#on-load-options */
export interface OnLoadOptions {
filter: RegExp
namespace?: string
}
/** Documentation: https://esbuild.github.io/plugins/#on-load-arguments */
export interface OnLoadArgs {
path: string
namespace: string
suffix: string
pluginData: any
}
/** Documentation: https://esbuild.github.io/plugins/#on-load-results */
export interface OnLoadResult {
pluginName?: string
errors?: PartialMessage[]
warnings?: PartialMessage[]
contents?: string | Uint8Array
resolveDir?: string
loader?: Loader
pluginData?: any
watchFiles?: string[]
watchDirs?: string[]
}
export interface PartialMessage {
id?: string
pluginName?: string
text?: string
location?: Partial<Location> | null
notes?: PartialNote[]
detail?: any
}
export interface PartialNote {
text?: string
location?: Partial<Location> | null
}
/** Documentation: https://esbuild.github.io/api/#metafile */
export interface Metafile {
inputs: {
[path: string]: {
bytes: number
imports: {
path: string
kind: ImportKind
external?: boolean
original?: string
}[]
format?: 'cjs' | 'esm'
}
}
outputs: {
[path: string]: {
bytes: number
inputs: {
[path: string]: {
bytesInOutput: number
}
}
imports: {
path: string
kind: ImportKind | 'file-loader'
external?: boolean
}[]
exports: string[]
entryPoint?: string
cssBundle?: string
}
}
}
export interface FormatMessagesOptions {
kind: 'error' | 'warning'
color?: boolean
terminalWidth?: number
}
export interface AnalyzeMetafileOptions {
color?: boolean
verbose?: boolean
}
export interface WatchOptions {
}
export interface BuildContext<ProvidedOptions extends BuildOptions = BuildOptions> {
/** Documentation: https://esbuild.github.io/api/#rebuild */
rebuild(): Promise<BuildResult<ProvidedOptions>>
/** Documentation: https://esbuild.github.io/api/#watch */
watch(options?: WatchOptions): Promise<void>
/** Documentation: https://esbuild.github.io/api/#serve */
serve(options?: ServeOptions): Promise<ServeResult>
cancel(): Promise<void>
dispose(): Promise<void>
}
// This is a TypeScript type-level function which replaces any keys in "In"
// that aren't in "Out" with "never". We use this to reject properties with
// typos in object literals. See: https://stackoverflow.com/questions/49580725
type SameShape<Out, In extends Out> = In & { [Key in Exclude<keyof In, keyof Out>]: never }
/**
* This function invokes the "esbuild" command-line tool for you. It returns a
* promise that either resolves with a "BuildResult" object or rejects with a
* "BuildFailure" object.
*
* - Works in node: yes
* - Works in browser: yes
*
* Documentation: https://esbuild.github.io/api/#build
*/
export declare function build<T extends BuildOptions>(options: SameShape<BuildOptions, T>): Promise<BuildResult<T>>
/**
* This is the advanced long-running form of "build" that supports additional
* features such as watch mode and a local development server.
*
* - Works in node: yes
* - Works in browser: no
*
* Documentation: https://esbuild.github.io/api/#build
*/
export declare function context<T extends BuildOptions>(options: SameShape<BuildOptions, T>): Promise<BuildContext<T>>
/**
* This function transforms a single JavaScript file. It can be used to minify
* JavaScript, convert TypeScript/JSX to JavaScript, or convert newer JavaScript
* to older JavaScript. It returns a promise that is either resolved with a
* "TransformResult" object or rejected with a "TransformFailure" object.
*
* - Works in node: yes
* - Works in browser: yes
*
* Documentation: https://esbuild.github.io/api/#transform
*/
export declare function transform<T extends TransformOptions>(input: string | Uint8Array, options?: SameShape<TransformOptions, T>): Promise<TransformResult<T>>
/**
* Converts log messages to formatted message strings suitable for printing in
* the terminal. This allows you to reuse the built-in behavior of esbuild's
* log message formatter. This is a batch-oriented API for efficiency.
*
* - Works in node: yes
* - Works in browser: yes
*/
export declare function formatMessages(messages: PartialMessage[], options: FormatMessagesOptions): Promise<string[]>
/**
* Pretty-prints an analysis of the metafile JSON to a string. This is just for
* convenience to be able to match esbuild's pretty-printing exactly. If you want
* to customize it, you can just inspect the data in the metafile yourself.
*
* - Works in node: yes
* - Works in browser: yes
*
* Documentation: https://esbuild.github.io/api/#analyze
*/
export declare function analyzeMetafile(metafile: Metafile | string, options?: AnalyzeMetafileOptions): Promise<string>
/**
* A synchronous version of "build".
*
* - Works in node: yes
* - Works in browser: no
*
* Documentation: https://esbuild.github.io/api/#build
*/
export declare function buildSync<T extends BuildOptions>(options: SameShape<BuildOptions, T>): BuildResult<T>
/**
* A synchronous version of "transform".
*
* - Works in node: yes
* - Works in browser: no
*
* Documentation: https://esbuild.github.io/api/#transform
*/
export declare function transformSync<T extends TransformOptions>(input: string | Uint8Array, options?: SameShape<TransformOptions, T>): TransformResult<T>
/**
* A synchronous version of "formatMessages".
*
* - Works in node: yes
* - Works in browser: no
*/
export declare function formatMessagesSync(messages: PartialMessage[], options: FormatMessagesOptions): string[]
/**
* A synchronous version of "analyzeMetafile".
*
* - Works in node: yes
* - Works in browser: no
*
* Documentation: https://esbuild.github.io/api/#analyze
*/
export declare function analyzeMetafileSync(metafile: Metafile | string, options?: AnalyzeMetafileOptions): string
/**
* This configures the browser-based version of esbuild. It is necessary to
* call this first and wait for the returned promise to be resolved before
* making other API calls when using esbuild in the browser.
*
* - Works in node: yes
* - Works in browser: yes ("options" is required)
*
* Documentation: https://esbuild.github.io/api/#browser
*/
export declare function initialize(options: InitializeOptions): Promise<void>
export interface InitializeOptions {
/**
* The URL of the "esbuild.wasm" file. This must be provided when running
* esbuild in the browser.
*/
wasmURL?: string | URL
/**
* The result of calling "new WebAssembly.Module(buffer)" where "buffer"
* is a typed array or ArrayBuffer containing the binary code of the
* "esbuild.wasm" file.
*
* You can use this as an alternative to "wasmURL" for environments where it's
* not possible to download the WebAssembly module.
*/
wasmModule?: WebAssembly.Module
/**
* By default esbuild runs the WebAssembly-based browser API in a web worker
* to avoid blocking the UI thread. This can be disabled by setting "worker"
* to false.
*/
worker?: boolean
}
export let version: string

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,3 @@
# esbuild
This is the Linux 64-bit binary for esbuild, a JavaScript bundler and minifier. See https://github.com/evanw/esbuild for details.

View File

@@ -0,0 +1,17 @@
{
"name": "@esbuild/linux-x64",
"version": "0.18.20",
"description": "The Linux 64-bit binary for esbuild, a JavaScript bundler.",
"repository": "https://github.com/evanw/esbuild",
"license": "MIT",
"preferUnplugged": true,
"engines": {
"node": ">=12"
},
"os": [
"linux"
],
"cpu": [
"x64"
]
}

View File

@@ -0,0 +1,42 @@
{
"name": "esbuild",
"version": "0.18.20",
"description": "An extremely fast JavaScript and CSS bundler and minifier.",
"repository": "https://github.com/evanw/esbuild",
"scripts": {
"postinstall": "node install.js"
},
"main": "lib/main.js",
"types": "lib/main.d.ts",
"engines": {
"node": ">=12"
},
"bin": {
"esbuild": "bin/esbuild"
},
"optionalDependencies": {
"@esbuild/android-arm": "0.18.20",
"@esbuild/android-arm64": "0.18.20",
"@esbuild/android-x64": "0.18.20",
"@esbuild/darwin-arm64": "0.18.20",
"@esbuild/darwin-x64": "0.18.20",
"@esbuild/freebsd-arm64": "0.18.20",
"@esbuild/freebsd-x64": "0.18.20",
"@esbuild/linux-arm": "0.18.20",
"@esbuild/linux-arm64": "0.18.20",
"@esbuild/linux-ia32": "0.18.20",
"@esbuild/linux-loong64": "0.18.20",
"@esbuild/linux-mips64el": "0.18.20",
"@esbuild/linux-ppc64": "0.18.20",
"@esbuild/linux-riscv64": "0.18.20",
"@esbuild/linux-s390x": "0.18.20",
"@esbuild/linux-x64": "0.18.20",
"@esbuild/netbsd-x64": "0.18.20",
"@esbuild/openbsd-x64": "0.18.20",
"@esbuild/sunos-x64": "0.18.20",
"@esbuild/win32-arm64": "0.18.20",
"@esbuild/win32-ia32": "0.18.20",
"@esbuild/win32-x64": "0.18.20"
},
"license": "MIT"
}

33
node_modules/@esbuild-kit/core-utils/package.json generated vendored Normal file
View File

@@ -0,0 +1,33 @@
{
"name": "@esbuild-kit/core-utils",
"version": "3.3.2",
"publishConfig": {
"access": "public"
},
"license": "MIT",
"repository": "esbuild-kit/core-utils",
"author": {
"name": "Hiroki Osame",
"email": "hiroki.osame@gmail.com"
},
"files": [
"dist"
],
"main": "./dist/index.js",
"types": "./dist/index.d.ts",
"exports": {
"types": "./dist/index.d.ts",
"default": "./dist/index.js"
},
"imports": {
"#esbuild-kit/core-utils": {
"types": "./src/index.ts",
"development": "./src/index.ts",
"default": "./dist/index.js"
}
},
"dependencies": {
"esbuild": "~0.18.20",
"source-map-support": "^0.5.21"
}
}

21
node_modules/@esbuild-kit/esm-loader/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) Hiroki Osame <hiroki.osame@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

155
node_modules/@esbuild-kit/esm-loader/README.md generated vendored Normal file
View File

@@ -0,0 +1,155 @@
# esm-loader
[Node.js loader](https://nodejs.org/api/esm.html#loaders) for loading TypeScript files.
### Features
- Transforms TypeScript to ESM on demand
- Classic Node.js resolution (extensionless & directory imports)
- Cached for performance boost
- Supports Node.js v12.20.0+
- Handles `node:` import prefixes
- Resolves `tsconfig.json` [`paths`](https://www.typescriptlang.org/tsconfig#paths)
- Named imports from JSON modules
> **Protip: use with _cjs-loader_ or _tsx_**
>
> _esm-loader_ only transforms ES modules (`.mjs`/`.mts` extensions or `.js` files in `module` type packages).
>
> To transform CommonJS files (`.cjs`/`.cts` extensions or `.js` files in `commonjs` type packages), use this with [_cjs-loader_](https://github.com/esbuild-kit/cjs-loader).
>
> Alternatively, use [tsx](https://github.com/esbuild-kit/tsx) to handle them both automatically.
<br>
<p align="center">
<a href="https://privatenumber-sponsors.vercel.app/api/sponsor?tier=platinum">
<picture>
<source width="830" media="(prefers-color-scheme: dark)" srcset="https://privatenumber-sponsors.vercel.app/api/sponsor?tier=platinum&image=dark">
<source width="830" media="(prefers-color-scheme: light)" srcset="https://privatenumber-sponsors.vercel.app/api/sponsor?tier=platinum&image">
<img width="830" src="https://privatenumber-sponsors.vercel.app/api/sponsor?tier=platinum&image" alt="Premium sponsor banner">
</picture>
</a>
</p>
## Install
```sh
npm install --save-dev @esbuild-kit/esm-loader
```
## Usage
Pass `@esbuild-kit/esm-loader` into the [`--loader`](https://nodejs.org/api/cli.html#--experimental-loadermodule) flag.
```sh
node --loader @esbuild-kit/esm-loader ./file.ts
```
### TypeScript configuration
The following properties are used from `tsconfig.json` in the working directory:
- [`strict`](https://www.typescriptlang.org/tsconfig#strict): Whether to transform to strict mode
- [`jsx`](https://esbuild.github.io/api/#jsx): Whether to transform JSX
> **Warning:** When set to `preserve`, the JSX syntax will remain untransformed. To prevent Node.js from throwing a syntax error, chain another Node.js loader that can transform JSX to JS.
- [`jsxFactory`](https://esbuild.github.io/api/#jsx-factory): How to transform JSX
- [`jsxFragmentFactory`](https://esbuild.github.io/api/#jsx-fragment): How to transform JSX Fragments
- [`jsxImportSource`](https://www.typescriptlang.org/tsconfig#jsxImportSource): Where to import JSX functions from
- [`allowJs`](https://www.typescriptlang.org/tsconfig#allowJs): Whether to apply the tsconfig to JS files
- [`paths`](https://www.typescriptlang.org/tsconfig#paths): For resolving aliases
#### Custom `tsconfig.json` path
By default, `tsconfig.json` will be detected from the current working directory.
To set a custom path, use the `ESBK_TSCONFIG_PATH` environment variable:
```sh
ESBK_TSCONFIG_PATH=./path/to/tsconfig.custom.json node --loader @esbuild-kit/esm-loader ./file.ts
```
### Cache
Modules transformations are cached in the system cache directory ([`TMPDIR`](https://en.wikipedia.org/wiki/TMPDIR)). Transforms are cached by content hash so duplicate dependencies are not re-transformed.
Set environment variable `ESBK_DISABLE_CACHE` to a truthy value to disable the cache:
```sh
ESBK_DISABLE_CACHE=1 node --loader @esbuild-kit/esm-loader ./file.ts
```
<br>
<p align="center">
<a href="https://privatenumber-sponsors.vercel.app/api/sponsor?tier=gold">
<picture>
<source width="830" media="(prefers-color-scheme: dark)" srcset="https://privatenumber-sponsors.vercel.app/api/sponsor?tier=gold&image=dark">
<source width="830" media="(prefers-color-scheme: light)" srcset="https://privatenumber-sponsors.vercel.app/api/sponsor?tier=gold&image">
<img width="830" src="https://privatenumber-sponsors.vercel.app/api/sponsor?tier=gold&image" alt="Premium sponsor banner">
</picture>
</a>
</p>
## FAQ
### Can it import JSON modules?
Yes. This loader transpiles JSON modules so it's also compatible with named imports.
### Can it import ESM modules over network?
Node.js has built-in support for network imports [behind the `--experimental-network-imports` flag](https://nodejs.org/api/esm.html#network-based-loading-is-not-enabled-by-default).
You can pass it in with `esm-loader`:
```sh
node --loader @esbuild-kit/esm-loader --experimental-network-imports ./file.ts
```
### Can it resolve files without an extension?
In ESM, import paths must be explicit (must include file name and extension).
For backwards compatibility, this loader adds support for classic Node resolution for extensions: `.js`, `.json`, `.ts`, `.tsx`, `.jsx`. Resolving a `index` file by the directory name works too.
```js
import file from './file' // -> ./file.js
import directory from './directory' // -> ./directory/index.js
```
### Can it use Node.js's CommonJS resolution algorithm?
ESM import resolution expects explicit import paths, whereas CommonJS resolution expects implicit imports (eg. extensionless & directory imports).
As a result of this change, Node.js changes how it imports a path that matches both a file and directory. In ESM, the directory would be imported, but in CJS, the file would be imported.
To use to the CommonJS resolution algorithm, use the [`--experimental-specifier-resolution=node`](https://nodejs.org/api/cli.html#--experimental-specifier-resolutionmode) flag.
```sh
node --loader @esbuild-kit/esm-loader --experimental-specifier-resolution=node ./file.ts
```
## Related
- [tsx](https://github.com/esbuild-kit/tsx) - Node.js runtime powered by esbuild using [`@esbuild-kit/cjs-loader`](https://github.com/esbuild-kit/cjs-loader) and [`@esbuild-kit/esm-loader`](https://github.com/esbuild-kit/esm-loader).
- [@esbuild-kit/cjs-loader](https://github.com/esbuild-kit/cjs-loader) - TypeScript & ESM to CJS transpiler using the Node.js loader API.
## Sponsors
<p align="center">
<a href="https://privatenumber-sponsors.vercel.app/api/sponsor?tier=silver1">
<picture>
<source width="410" media="(prefers-color-scheme: dark)" srcset="https://privatenumber-sponsors.vercel.app/api/sponsor?tier=silver1&image=dark">
<source width="410" media="(prefers-color-scheme: light)" srcset="https://privatenumber-sponsors.vercel.app/api/sponsor?tier=silver1&image">
<img width="410" src="https://privatenumber-sponsors.vercel.app/api/sponsor?tier=silver1&image" alt="Premium sponsor banner">
</picture>
</a>
<a href="https://privatenumber-sponsors.vercel.app/api/sponsor?tier=silver2">
<picture>
<source width="410" media="(prefers-color-scheme: dark)" srcset="https://privatenumber-sponsors.vercel.app/api/sponsor?tier=silver2&image=dark">
<source width="410" media="(prefers-color-scheme: light)" srcset="https://privatenumber-sponsors.vercel.app/api/sponsor?tier=silver2&image">
<img width="410" src="https://privatenumber-sponsors.vercel.app/api/sponsor?tier=silver2&image" alt="Premium sponsor banner">
</picture>
</a>
</p>
<p align="center">
<a href="https://github.com/sponsors/privatenumber">
<img src="https://cdn.jsdelivr.net/gh/privatenumber/sponsors/sponsorkit/sponsors.svg">
</a>
</p>

12
node_modules/@esbuild-kit/esm-loader/dist/index.js generated vendored Executable file
View File

@@ -0,0 +1,12 @@
import l from"path";import{fileURLToPath as y,pathToFileURL as U}from"url";import{installSourceMapSupport as I,compareNodeVersion as m,resolveTsPath as M,transform as S,transformDynamicImport as k}from"@esbuild-kit/core-utils";import{parseTsconfig as A,getTsconfig as J,createFilesMatcher as L,createPathsMatcher as W}from"get-tsconfig";import R from"fs";const f=new Map;async function b(t){if(f.has(t))return f.get(t);if(!await R.promises.access(t).then(()=>!0,()=>!1)){f.set(t,void 0);return}const e=await R.promises.readFile(t,"utf8");try{const n=JSON.parse(e);return f.set(t,n),n}catch{throw new Error(`Error parsing: ${t}`)}}async function $(t){let s=new URL("package.json",t);for(;!s.pathname.endsWith("/node_modules/package.json");){const e=y(s),n=await b(e);if(n)return n;const r=s;if(s=new URL("../package.json",s),s.pathname===r.pathname)break}}async function x(t){var s;const e=await $(t);return(s=e==null?void 0:e.type)!=null?s:"commonjs"}const u=I(),d=process.env.ESBK_TSCONFIG_PATH?{path:l.resolve(process.env.ESBK_TSCONFIG_PATH),config:A(process.env.ESBK_TSCONFIG_PATH)}:J(),N=d&&L(d),O=d&&W(d),w="file://",g=/\.([cm]?ts|[tj]sx)($|\?)/,_=/\.json(?:$|\?)/,C=t=>{const s=l.extname(t);if(s===".json")return"json";if(s===".mjs"||s===".mts")return"module";if(s===".cjs"||s===".cts")return"commonjs"},j=t=>{const s=C(t);if(s)return s;if(g.test(t))return x(t)},v=/\/(?:$|\?)/,K=m([20,0,0])>=0;let P=process.send?process.send.bind(process):void 0,E;const q=({port:t})=>(E=t,P=t.postMessage.bind(t),`
const require = getBuiltin('module').createRequire("${import.meta.url}");
require('@esbuild-kit/core-utils').installSourceMapSupport(port);
if (process.send) {
port.addListener('message', (message) => {
if (message.type === 'dependency') {
process.send(message);
}
});
}
port.unref(); // Allows process to exit without waiting for port to close
`),B=K?q:void 0,G=[".js",".json",".ts",".tsx",".jsx"];async function T(t,s,e){const[n,r]=t.split("?");let i;for(const a of G)try{return await h(n+a+(r?`?${r}`:""),s,e,!0)}catch(o){if(i===void 0&&o instanceof Error){const{message:c}=o;o.message=o.message.replace(`${a}'`,"'"),o.stack=o.stack.replace(c,o.message),i=o}}throw i}async function F(t,s,e){const n=v.test(t),r=n?"index":"/index",[i,a]=t.split("?");try{return await T(i+r+(a?`?${a}`:""),s,e)}catch(o){if(!n)try{return await T(t,s,e)}catch{}const c=o,{message:p}=c;throw c.message=c.message.replace(`${r.replace("/",l.sep)}'`,"'"),c.stack=c.stack.replace(p,c.message),c}}const H=/^\.{1,2}\//,Q=m([14,13,1])>=0||m([12,20,0])>=0,h=async function(t,s,e,n){var r;if(!Q&&t.startsWith("node:")&&(t=t.slice(5)),v.test(t))return await F(t,s,e);const i=t.startsWith(w)||H.test(t);if(O&&!i&&!((r=s.parentURL)!=null&&r.includes("/node_modules/"))){const o=O(t);for(const c of o)try{return await h(U(c).toString(),s,e)}catch{}}if(g.test(s.parentURL)){const o=M(t);if(o)try{return await h(o,s,e,!0)}catch(c){const{code:p}=c;if(p!=="ERR_MODULE_NOT_FOUND"&&p!=="ERR_PACKAGE_PATH_NOT_EXPORTED")throw c}}let a;try{a=await e(t,s)}catch(o){if(o instanceof Error&&!n){const{code:c}=o;if(c==="ERR_UNSUPPORTED_DIR_IMPORT")try{return await F(t,s,e)}catch(p){if(p.code!=="ERR_PACKAGE_IMPORT_NOT_DEFINED")throw p}if(c==="ERR_MODULE_NOT_FOUND")try{return await T(t,s,e)}catch{}}throw o}return!a.format&&a.url.startsWith(w)&&(a.format=await j(a.url)),a},X=async function(t,s,e){var n;P&&P({type:"dependency",path:t}),_.test(t)&&(s.importAssertions||(s.importAssertions={}),s.importAssertions.type="json");const r=await e(t,s);if(!r.source)return r;const i=t.startsWith("file://")?y(t):t,a=r.source.toString();if(r.format==="json"||g.test(t)){const o=await S(a,i,{tsconfigRaw:(n=N)==null?void 0:n(i)});return{format:"module",source:u(o,t,E)}}if(r.format==="module"){const o=k(i,a);o&&(r.source=u(o,t,E))}return r},V=async function(t,s,e){if(_.test(t))return{format:"module"};try{return await e(t,s,e)}catch(n){if(n.code==="ERR_UNKNOWN_FILE_EXTENSION"&&t.startsWith(w)){const r=await j(t);if(r)return{format:r}}throw n}},z=async function(t,s,e){var n;const{url:r}=s,i=r.startsWith("file://")?y(r):r;if(process.send&&process.send({type:"dependency",path:r}),_.test(r)||g.test(r)){const o=await S(t.toString(),i,{tsconfigRaw:(n=N)==null?void 0:n(i)});return{source:u(o,r)}}const a=await e(t,s,e);if(s.format==="module"){const o=k(i,a.source.toString());o&&(a.source=u(o,r))}return a},D=m([16,12,0])<0,Y=D?V:void 0,Z=D?z:void 0;export{Y as getFormat,B as globalPreload,X as load,h as resolve,Z as transformSource};

31
node_modules/@esbuild-kit/esm-loader/package.json generated vendored Normal file
View File

@@ -0,0 +1,31 @@
{
"name": "@esbuild-kit/esm-loader",
"version": "2.6.5",
"publishConfig": {
"access": "public"
},
"description": "Node.js loader for compiling TypeScript modules to ESM",
"keywords": [
"esbuild",
"loader",
"node",
"esm",
"typescript"
],
"license": "MIT",
"repository": "esbuild-kit/esm-loader",
"author": {
"name": "Hiroki Osame",
"email": "hiroki.osame@gmail.com"
},
"type": "module",
"files": [
"dist"
],
"main": "./dist/index.js",
"exports": "./dist/index.js",
"dependencies": {
"@esbuild-kit/core-utils": "^3.3.2",
"get-tsconfig": "^4.7.0"
}
}

3
node_modules/@esbuild/linux-x64/README.md generated vendored Normal file
View File

@@ -0,0 +1,3 @@
# esbuild
This is the Linux 64-bit binary for esbuild, a JavaScript bundler and minifier. See https://github.com/evanw/esbuild for details.

BIN
node_modules/@esbuild/linux-x64/bin/esbuild generated vendored Executable file

Binary file not shown.

20
node_modules/@esbuild/linux-x64/package.json generated vendored Normal file
View File

@@ -0,0 +1,20 @@
{
"name": "@esbuild/linux-x64",
"version": "0.25.12",
"description": "The Linux 64-bit binary for esbuild, a JavaScript bundler.",
"repository": {
"type": "git",
"url": "git+https://github.com/evanw/esbuild.git"
},
"license": "MIT",
"preferUnplugged": true,
"engines": {
"node": ">=18"
},
"os": [
"linux"
],
"cpu": [
"x64"
]
}

21
node_modules/@hono/node-server/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2022 - present, Yusuke Wada and Hono contributors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

358
node_modules/@hono/node-server/README.md generated vendored Normal file
View File

@@ -0,0 +1,358 @@
# Node.js Adapter for Hono
This adapter `@hono/node-server` allows you to run your Hono application on Node.js.
Initially, Hono wasn't designed for Node.js, but with this adapter, you can now use Hono on Node.js.
It utilizes web standard APIs implemented in Node.js version 18 or higher.
## Benchmarks
Hono is 3.5 times faster than Express.
Express:
```txt
$ bombardier -d 10s --fasthttp http://localhost:3000/
Statistics Avg Stdev Max
Reqs/sec 16438.94 1603.39 19155.47
Latency 7.60ms 7.51ms 559.89ms
HTTP codes:
1xx - 0, 2xx - 164494, 3xx - 0, 4xx - 0, 5xx - 0
others - 0
Throughput: 4.55MB/s
```
Hono + `@hono/node-server`:
```txt
$ bombardier -d 10s --fasthttp http://localhost:3000/
Statistics Avg Stdev Max
Reqs/sec 58296.56 5512.74 74403.56
Latency 2.14ms 1.46ms 190.92ms
HTTP codes:
1xx - 0, 2xx - 583059, 3xx - 0, 4xx - 0, 5xx - 0
others - 0
Throughput: 12.56MB/s
```
## Requirements
It works on Node.js versions greater than 18.x. The specific required Node.js versions are as follows:
- 18.x => 18.14.1+
- 19.x => 19.7.0+
- 20.x => 20.0.0+
Essentially, you can simply use the latest version of each major release.
## Installation
You can install it from the npm registry with `npm` command:
```sh
npm install @hono/node-server
```
Or use `yarn`:
```sh
yarn add @hono/node-server
```
## Usage
Just import `@hono/node-server` at the top and write the code as usual.
The same code that runs on Cloudflare Workers, Deno, and Bun will work.
```ts
import { serve } from '@hono/node-server'
import { Hono } from 'hono'
const app = new Hono()
app.get('/', (c) => c.text('Hono meets Node.js'))
serve(app, (info) => {
console.log(`Listening on http://localhost:${info.port}`) // Listening on http://localhost:3000
})
```
For example, run it using `ts-node`. Then an HTTP server will be launched. The default port is `3000`.
```sh
ts-node ./index.ts
```
Open `http://localhost:3000` with your browser.
## Options
### `port`
```ts
serve({
fetch: app.fetch,
port: 8787, // Port number, default is 3000
})
```
### `createServer`
```ts
import { createServer } from 'node:https'
import fs from 'node:fs'
//...
serve({
fetch: app.fetch,
createServer: createServer,
serverOptions: {
key: fs.readFileSync('test/fixtures/keys/agent1-key.pem'),
cert: fs.readFileSync('test/fixtures/keys/agent1-cert.pem'),
},
})
```
### `overrideGlobalObjects`
The default value is `true`. The Node.js Adapter rewrites the global Request/Response and uses a lightweight Request/Response to improve performance. If you don't want to do that, set `false`.
```ts
serve({
fetch: app.fetch,
overrideGlobalObjects: false,
})
```
### `autoCleanupIncoming`
The default value is `true`. The Node.js Adapter automatically cleans up (explicitly call `destroy()` method) if application is not finished to consume the incoming request. If you don't want to do that, set `false`.
If the application accepts connections from arbitrary clients, this cleanup must be done otherwise incomplete requests from clients may cause the application to stop responding. If your application only accepts connections from trusted clients, such as in a reverse proxy environment and there is no process that returns a response without reading the body of the POST request all the way through, you can improve performance by setting it to `false`.
```ts
serve({
fetch: app.fetch,
autoCleanupIncoming: false,
})
```
## Middleware
Most built-in middleware also works with Node.js.
Read [the documentation](https://hono.dev/middleware/builtin/basic-auth) and use the Middleware of your liking.
```ts
import { serve } from '@hono/node-server'
import { Hono } from 'hono'
import { prettyJSON } from 'hono/pretty-json'
const app = new Hono()
app.get('*', prettyJSON())
app.get('/', (c) => c.json({ 'Hono meets': 'Node.js' }))
serve(app)
```
## Serve Static Middleware
Use Serve Static Middleware that has been created for Node.js.
```ts
import { serveStatic } from '@hono/node-server/serve-static'
//...
app.use('/static/*', serveStatic({ root: './' }))
```
If using a relative path, `root` will be relative to the current working directory from which the app was started.
This can cause confusion when running your application locally.
Imagine your project structure is:
```
my-hono-project/
src/
index.ts
static/
index.html
```
Typically, you would run your app from the project's root directory (`my-hono-project`),
so you would need the following code to serve the `static` folder:
```ts
app.use('/static/*', serveStatic({ root: './static' }))
```
Notice that `root` here is not relative to `src/index.ts`, rather to `my-hono-project`.
### Options
#### `rewriteRequestPath`
If you want to serve files in `./.foojs` with the request path `/__foo/*`, you can write like the following.
```ts
app.use(
'/__foo/*',
serveStatic({
root: './.foojs/',
rewriteRequestPath: (path: string) => path.replace(/^\/__foo/, ''),
})
)
```
#### `onFound`
You can specify handling when the requested file is found with `onFound`.
```ts
app.use(
'/static/*',
serveStatic({
// ...
onFound: (_path, c) => {
c.header('Cache-Control', `public, immutable, max-age=31536000`)
},
})
)
```
#### `onNotFound`
The `onNotFound` is useful for debugging. You can write a handle for when a file is not found.
```ts
app.use(
'/static/*',
serveStatic({
root: './non-existent-dir',
onNotFound: (path, c) => {
console.log(`${path} is not found, request to ${c.req.path}`)
},
})
)
```
#### `precompressed`
The `precompressed` option checks if files with extensions like `.br` or `.gz` are available and serves them based on the `Accept-Encoding` header. It prioritizes Brotli, then Zstd, and Gzip. If none are available, it serves the original file.
```ts
app.use(
'/static/*',
serveStatic({
precompressed: true,
})
)
```
## ConnInfo Helper
You can use the [ConnInfo Helper](https://hono.dev/docs/helpers/conninfo) by importing `getConnInfo` from `@hono/node-server/conninfo`.
```ts
import { getConnInfo } from '@hono/node-server/conninfo'
app.get('/', (c) => {
const info = getConnInfo(c) // info is `ConnInfo`
return c.text(`Your remote address is ${info.remote.address}`)
})
```
## Accessing Node.js API
You can access the Node.js API from `c.env` in Node.js. For example, if you want to specify a type, you can write the following.
```ts
import { serve } from '@hono/node-server'
import type { HttpBindings } from '@hono/node-server'
import { Hono } from 'hono'
const app = new Hono<{ Bindings: HttpBindings }>()
app.get('/', (c) => {
return c.json({
remoteAddress: c.env.incoming.socket.remoteAddress,
})
})
serve(app)
```
The APIs that you can get from `c.env` are as follows.
```ts
type HttpBindings = {
incoming: IncomingMessage
outgoing: ServerResponse
}
type Http2Bindings = {
incoming: Http2ServerRequest
outgoing: Http2ServerResponse
}
```
## Direct response from Node.js API
You can directly respond to the client from the Node.js API.
In that case, the response from Hono should be ignored, so return `RESPONSE_ALREADY_SENT`.
> [!NOTE]
> This feature can be used when migrating existing Node.js applications to Hono, but we recommend using Hono's API for new applications.
```ts
import { serve } from '@hono/node-server'
import type { HttpBindings } from '@hono/node-server'
import { RESPONSE_ALREADY_SENT } from '@hono/node-server/utils/response'
import { Hono } from 'hono'
const app = new Hono<{ Bindings: HttpBindings }>()
app.get('/', (c) => {
const { outgoing } = c.env
outgoing.writeHead(200, { 'Content-Type': 'text/plain' })
outgoing.end('Hello World\n')
return RESPONSE_ALREADY_SENT
})
serve(app)
```
## Listen to a UNIX domain socket
You can configure the HTTP server to listen to a UNIX domain socket instead of a TCP port.
```ts
import { createAdaptorServer } from '@hono/node-server'
// ...
const socketPath = '/tmp/example.sock'
const server = createAdaptorServer(app)
server.listen(socketPath, () => {
console.log(`Listening on ${socketPath}`)
})
```
## Related projects
- Hono - <https://hono.dev>
- Hono GitHub repository - <https://github.com/honojs/hono>
## Authors
- Yusuke Wada <https://github.com/yusukebe>
- Taku Amano <https://github.com/usualoma>
## License
MIT

10
node_modules/@hono/node-server/dist/conninfo.d.mts generated vendored Normal file
View File

@@ -0,0 +1,10 @@
import { GetConnInfo } from 'hono/conninfo';
/**
* ConnInfo Helper for Node.js
* @param c Context
* @returns ConnInfo
*/
declare const getConnInfo: GetConnInfo;
export { getConnInfo };

10
node_modules/@hono/node-server/dist/conninfo.d.ts generated vendored Normal file
View File

@@ -0,0 +1,10 @@
import { GetConnInfo } from 'hono/conninfo';
/**
* ConnInfo Helper for Node.js
* @param c Context
* @returns ConnInfo
*/
declare const getConnInfo: GetConnInfo;
export { getConnInfo };

42
node_modules/@hono/node-server/dist/conninfo.js generated vendored Normal file
View File

@@ -0,0 +1,42 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/conninfo.ts
var conninfo_exports = {};
__export(conninfo_exports, {
getConnInfo: () => getConnInfo
});
module.exports = __toCommonJS(conninfo_exports);
var getConnInfo = (c) => {
const bindings = c.env.server ? c.env.server : c.env;
const address = bindings.incoming.socket.remoteAddress;
const port = bindings.incoming.socket.remotePort;
const family = bindings.incoming.socket.remoteFamily;
return {
remote: {
address,
port,
addressType: family === "IPv4" ? "IPv4" : family === "IPv6" ? "IPv6" : void 0
}
};
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
getConnInfo
});

17
node_modules/@hono/node-server/dist/conninfo.mjs generated vendored Normal file
View File

@@ -0,0 +1,17 @@
// src/conninfo.ts
var getConnInfo = (c) => {
const bindings = c.env.server ? c.env.server : c.env;
const address = bindings.incoming.socket.remoteAddress;
const port = bindings.incoming.socket.remotePort;
const family = bindings.incoming.socket.remoteFamily;
return {
remote: {
address,
port,
addressType: family === "IPv4" ? "IPv4" : family === "IPv6" ? "IPv6" : void 0
}
};
};
export {
getConnInfo
};

2
node_modules/@hono/node-server/dist/globals.d.mts generated vendored Normal file
View File

@@ -0,0 +1,2 @@
export { }

2
node_modules/@hono/node-server/dist/globals.d.ts generated vendored Normal file
View File

@@ -0,0 +1,2 @@
export { }

29
node_modules/@hono/node-server/dist/globals.js generated vendored Normal file
View File

@@ -0,0 +1,29 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
// src/globals.ts
var import_node_crypto = __toESM(require("crypto"));
if (typeof global.crypto === "undefined") {
global.crypto = import_node_crypto.default;
}

5
node_modules/@hono/node-server/dist/globals.mjs generated vendored Normal file
View File

@@ -0,0 +1,5 @@
// src/globals.ts
import crypto from "crypto";
if (typeof global.crypto === "undefined") {
global.crypto = crypto;
}

8
node_modules/@hono/node-server/dist/index.d.mts generated vendored Normal file
View File

@@ -0,0 +1,8 @@
export { createAdaptorServer, serve } from './server.mjs';
export { getRequestListener } from './listener.mjs';
export { RequestError } from './request.mjs';
export { Http2Bindings, HttpBindings, ServerType } from './types.mjs';
import 'node:net';
import 'node:http';
import 'node:http2';
import 'node:https';

8
node_modules/@hono/node-server/dist/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,8 @@
export { createAdaptorServer, serve } from './server.js';
export { getRequestListener } from './listener.js';
export { RequestError } from './request.js';
export { Http2Bindings, HttpBindings, ServerType } from './types.js';
import 'node:net';
import 'node:http';
import 'node:http2';
import 'node:https';

702
node_modules/@hono/node-server/dist/index.js generated vendored Normal file
View File

@@ -0,0 +1,702 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/index.ts
var src_exports = {};
__export(src_exports, {
RequestError: () => RequestError,
createAdaptorServer: () => createAdaptorServer,
getRequestListener: () => getRequestListener,
serve: () => serve
});
module.exports = __toCommonJS(src_exports);
// src/server.ts
var import_node_http = require("http");
// src/listener.ts
var import_node_http22 = require("http2");
// src/request.ts
var import_node_http2 = require("http2");
var import_node_stream = require("stream");
var RequestError = class extends Error {
constructor(message, options) {
super(message, options);
this.name = "RequestError";
}
};
var toRequestError = (e) => {
if (e instanceof RequestError) {
return e;
}
return new RequestError(e.message, { cause: e });
};
var GlobalRequest = global.Request;
var Request = class extends GlobalRequest {
constructor(input, options) {
if (typeof input === "object" && getRequestCache in input) {
input = input[getRequestCache]();
}
if (typeof options?.body?.getReader !== "undefined") {
;
options.duplex ??= "half";
}
super(input, options);
}
};
var newHeadersFromIncoming = (incoming) => {
const headerRecord = [];
const rawHeaders = incoming.rawHeaders;
for (let i = 0; i < rawHeaders.length; i += 2) {
const { [i]: key, [i + 1]: value } = rawHeaders;
if (key.charCodeAt(0) !== /*:*/
58) {
headerRecord.push([key, value]);
}
}
return new Headers(headerRecord);
};
var wrapBodyStream = Symbol("wrapBodyStream");
var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
const init = {
method,
headers,
signal: abortController.signal
};
if (method === "TRACE") {
init.method = "GET";
const req = new Request(url, init);
Object.defineProperty(req, "method", {
get() {
return "TRACE";
}
});
return req;
}
if (!(method === "GET" || method === "HEAD")) {
if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
init.body = new ReadableStream({
start(controller) {
controller.enqueue(incoming.rawBody);
controller.close();
}
});
} else if (incoming[wrapBodyStream]) {
let reader;
init.body = new ReadableStream({
async pull(controller) {
try {
reader ||= import_node_stream.Readable.toWeb(incoming).getReader();
const { done, value } = await reader.read();
if (done) {
controller.close();
} else {
controller.enqueue(value);
}
} catch (error) {
controller.error(error);
}
}
});
} else {
init.body = import_node_stream.Readable.toWeb(incoming);
}
}
return new Request(url, init);
};
var getRequestCache = Symbol("getRequestCache");
var requestCache = Symbol("requestCache");
var incomingKey = Symbol("incomingKey");
var urlKey = Symbol("urlKey");
var headersKey = Symbol("headersKey");
var abortControllerKey = Symbol("abortControllerKey");
var getAbortController = Symbol("getAbortController");
var requestPrototype = {
get method() {
return this[incomingKey].method || "GET";
},
get url() {
return this[urlKey];
},
get headers() {
return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
},
[getAbortController]() {
this[getRequestCache]();
return this[abortControllerKey];
},
[getRequestCache]() {
this[abortControllerKey] ||= new AbortController();
return this[requestCache] ||= newRequestFromIncoming(
this.method,
this[urlKey],
this.headers,
this[incomingKey],
this[abortControllerKey]
);
}
};
[
"body",
"bodyUsed",
"cache",
"credentials",
"destination",
"integrity",
"mode",
"redirect",
"referrer",
"referrerPolicy",
"signal",
"keepalive"
].forEach((k) => {
Object.defineProperty(requestPrototype, k, {
get() {
return this[getRequestCache]()[k];
}
});
});
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
Object.defineProperty(requestPrototype, k, {
value: function() {
return this[getRequestCache]()[k]();
}
});
});
Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), {
value: function(depth, options, inspectFn) {
const props = {
method: this.method,
url: this.url,
headers: this.headers,
nativeRequest: this[requestCache]
};
return `Request (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
}
});
Object.setPrototypeOf(requestPrototype, Request.prototype);
var newRequest = (incoming, defaultHostname) => {
const req = Object.create(requestPrototype);
req[incomingKey] = incoming;
const incomingUrl = incoming.url || "";
if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
(incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
if (incoming instanceof import_node_http2.Http2ServerRequest) {
throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
}
try {
const url2 = new URL(incomingUrl);
req[urlKey] = url2.href;
} catch (e) {
throw new RequestError("Invalid absolute URL", { cause: e });
}
return req;
}
const host = (incoming instanceof import_node_http2.Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
if (!host) {
throw new RequestError("Missing host header");
}
let scheme;
if (incoming instanceof import_node_http2.Http2ServerRequest) {
scheme = incoming.scheme;
if (!(scheme === "http" || scheme === "https")) {
throw new RequestError("Unsupported scheme");
}
} else {
scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
}
const url = new URL(`${scheme}://${host}${incomingUrl}`);
if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
throw new RequestError("Invalid host header");
}
req[urlKey] = url.href;
return req;
};
// src/response.ts
var responseCache = Symbol("responseCache");
var getResponseCache = Symbol("getResponseCache");
var cacheKey = Symbol("cache");
var GlobalResponse = global.Response;
var Response2 = class _Response {
#body;
#init;
[getResponseCache]() {
delete this[cacheKey];
return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
}
constructor(body, init) {
let headers;
this.#body = body;
if (init instanceof _Response) {
const cachedGlobalResponse = init[responseCache];
if (cachedGlobalResponse) {
this.#init = cachedGlobalResponse;
this[getResponseCache]();
return;
} else {
this.#init = init.#init;
headers = new Headers(init.#init.headers);
}
} else {
this.#init = init;
}
if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
;
this[cacheKey] = [init?.status || 200, body, headers || init?.headers];
}
}
get headers() {
const cache = this[cacheKey];
if (cache) {
if (!(cache[2] instanceof Headers)) {
cache[2] = new Headers(
cache[2] || { "content-type": "text/plain; charset=UTF-8" }
);
}
return cache[2];
}
return this[getResponseCache]().headers;
}
get status() {
return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
}
get ok() {
const status = this.status;
return status >= 200 && status < 300;
}
};
["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
Object.defineProperty(Response2.prototype, k, {
get() {
return this[getResponseCache]()[k];
}
});
});
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
Object.defineProperty(Response2.prototype, k, {
value: function() {
return this[getResponseCache]()[k]();
}
});
});
Object.defineProperty(Response2.prototype, Symbol.for("nodejs.util.inspect.custom"), {
value: function(depth, options, inspectFn) {
const props = {
status: this.status,
headers: this.headers,
ok: this.ok,
nativeResponse: this[responseCache]
};
return `Response (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
}
});
Object.setPrototypeOf(Response2, GlobalResponse);
Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
// src/utils.ts
async function readWithoutBlocking(readPromise) {
return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
}
function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
const cancel = (error) => {
reader.cancel(error).catch(() => {
});
};
writable.on("close", cancel);
writable.on("error", cancel);
(currentReadPromise ?? reader.read()).then(flow, handleStreamError);
return reader.closed.finally(() => {
writable.off("close", cancel);
writable.off("error", cancel);
});
function handleStreamError(error) {
if (error) {
writable.destroy(error);
}
}
function onDrain() {
reader.read().then(flow, handleStreamError);
}
function flow({ done, value }) {
try {
if (done) {
writable.end();
} else if (!writable.write(value)) {
writable.once("drain", onDrain);
} else {
return reader.read().then(flow, handleStreamError);
}
} catch (e) {
handleStreamError(e);
}
}
}
function writeFromReadableStream(stream, writable) {
if (stream.locked) {
throw new TypeError("ReadableStream is locked.");
} else if (writable.destroyed) {
return;
}
return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
}
var buildOutgoingHttpHeaders = (headers) => {
const res = {};
if (!(headers instanceof Headers)) {
headers = new Headers(headers ?? void 0);
}
const cookies = [];
for (const [k, v] of headers) {
if (k === "set-cookie") {
cookies.push(v);
} else {
res[k] = v;
}
}
if (cookies.length > 0) {
res["set-cookie"] = cookies;
}
res["content-type"] ??= "text/plain; charset=UTF-8";
return res;
};
// src/utils/response/constants.ts
var X_ALREADY_SENT = "x-hono-already-sent";
// src/globals.ts
var import_node_crypto = __toESM(require("crypto"));
if (typeof global.crypto === "undefined") {
global.crypto = import_node_crypto.default;
}
// src/listener.ts
var outgoingEnded = Symbol("outgoingEnded");
var incomingDraining = Symbol("incomingDraining");
var DRAIN_TIMEOUT_MS = 500;
var MAX_DRAIN_BYTES = 64 * 1024 * 1024;
var drainIncoming = (incoming) => {
const incomingWithDrainState = incoming;
if (incoming.destroyed || incomingWithDrainState[incomingDraining]) {
return;
}
incomingWithDrainState[incomingDraining] = true;
if (incoming instanceof import_node_http22.Http2ServerRequest) {
try {
;
incoming.stream?.close?.(import_node_http22.constants.NGHTTP2_NO_ERROR);
} catch {
}
return;
}
let bytesRead = 0;
const cleanup = () => {
clearTimeout(timer);
incoming.off("data", onData);
incoming.off("end", cleanup);
incoming.off("error", cleanup);
};
const forceClose = () => {
cleanup();
const socket = incoming.socket;
if (socket && !socket.destroyed) {
socket.destroySoon();
}
};
const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
timer.unref?.();
const onData = (chunk) => {
bytesRead += chunk.length;
if (bytesRead > MAX_DRAIN_BYTES) {
forceClose();
}
};
incoming.on("data", onData);
incoming.on("end", cleanup);
incoming.on("error", cleanup);
incoming.resume();
};
var handleRequestError = () => new Response(null, {
status: 400
});
var handleFetchError = (e) => new Response(null, {
status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
});
var handleResponseError = (e, outgoing) => {
const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
console.info("The user aborted a request.");
} else {
console.error(e);
if (!outgoing.headersSent) {
outgoing.writeHead(500, { "Content-Type": "text/plain" });
}
outgoing.end(`Error: ${err.message}`);
outgoing.destroy(err);
}
};
var flushHeaders = (outgoing) => {
if ("flushHeaders" in outgoing && outgoing.writable) {
outgoing.flushHeaders();
}
};
var responseViaCache = async (res, outgoing) => {
let [status, body, header] = res[cacheKey];
let hasContentLength = false;
if (!header) {
header = { "content-type": "text/plain; charset=UTF-8" };
} else if (header instanceof Headers) {
hasContentLength = header.has("content-length");
header = buildOutgoingHttpHeaders(header);
} else if (Array.isArray(header)) {
const headerObj = new Headers(header);
hasContentLength = headerObj.has("content-length");
header = buildOutgoingHttpHeaders(headerObj);
} else {
for (const key in header) {
if (key.length === 14 && key.toLowerCase() === "content-length") {
hasContentLength = true;
break;
}
}
}
if (!hasContentLength) {
if (typeof body === "string") {
header["Content-Length"] = Buffer.byteLength(body);
} else if (body instanceof Uint8Array) {
header["Content-Length"] = body.byteLength;
} else if (body instanceof Blob) {
header["Content-Length"] = body.size;
}
}
outgoing.writeHead(status, header);
if (typeof body === "string" || body instanceof Uint8Array) {
outgoing.end(body);
} else if (body instanceof Blob) {
outgoing.end(new Uint8Array(await body.arrayBuffer()));
} else {
flushHeaders(outgoing);
await writeFromReadableStream(body, outgoing)?.catch(
(e) => handleResponseError(e, outgoing)
);
}
;
outgoing[outgoingEnded]?.();
};
var isPromise = (res) => typeof res.then === "function";
var responseViaResponseObject = async (res, outgoing, options = {}) => {
if (isPromise(res)) {
if (options.errorHandler) {
try {
res = await res;
} catch (err) {
const errRes = await options.errorHandler(err);
if (!errRes) {
return;
}
res = errRes;
}
} else {
res = await res.catch(handleFetchError);
}
}
if (cacheKey in res) {
return responseViaCache(res, outgoing);
}
const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
if (res.body) {
const reader = res.body.getReader();
const values = [];
let done = false;
let currentReadPromise = void 0;
if (resHeaderRecord["transfer-encoding"] !== "chunked") {
let maxReadCount = 2;
for (let i = 0; i < maxReadCount; i++) {
currentReadPromise ||= reader.read();
const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
console.error(e);
done = true;
});
if (!chunk) {
if (i === 1) {
await new Promise((resolve) => setTimeout(resolve));
maxReadCount = 3;
continue;
}
break;
}
currentReadPromise = void 0;
if (chunk.value) {
values.push(chunk.value);
}
if (chunk.done) {
done = true;
break;
}
}
if (done && !("content-length" in resHeaderRecord)) {
resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
}
}
outgoing.writeHead(res.status, resHeaderRecord);
values.forEach((value) => {
;
outgoing.write(value);
});
if (done) {
outgoing.end();
} else {
if (values.length === 0) {
flushHeaders(outgoing);
}
await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
}
} else if (resHeaderRecord[X_ALREADY_SENT]) {
} else {
outgoing.writeHead(res.status, resHeaderRecord);
outgoing.end();
}
;
outgoing[outgoingEnded]?.();
};
var getRequestListener = (fetchCallback, options = {}) => {
const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
if (options.overrideGlobalObjects !== false && global.Request !== Request) {
Object.defineProperty(global, "Request", {
value: Request
});
Object.defineProperty(global, "Response", {
value: Response2
});
}
return async (incoming, outgoing) => {
let res, req;
try {
req = newRequest(incoming, options.hostname);
let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
if (!incomingEnded) {
;
incoming[wrapBodyStream] = true;
incoming.on("end", () => {
incomingEnded = true;
});
if (incoming instanceof import_node_http22.Http2ServerRequest) {
;
outgoing[outgoingEnded] = () => {
if (!incomingEnded) {
setTimeout(() => {
if (!incomingEnded) {
setTimeout(() => {
drainIncoming(incoming);
});
}
});
}
};
}
outgoing.on("finish", () => {
if (!incomingEnded) {
drainIncoming(incoming);
}
});
}
outgoing.on("close", () => {
const abortController = req[abortControllerKey];
if (abortController) {
if (incoming.errored) {
req[abortControllerKey].abort(incoming.errored.toString());
} else if (!outgoing.writableFinished) {
req[abortControllerKey].abort("Client connection prematurely closed.");
}
}
if (!incomingEnded) {
setTimeout(() => {
if (!incomingEnded) {
setTimeout(() => {
drainIncoming(incoming);
});
}
});
}
});
res = fetchCallback(req, { incoming, outgoing });
if (cacheKey in res) {
return responseViaCache(res, outgoing);
}
} catch (e) {
if (!res) {
if (options.errorHandler) {
res = await options.errorHandler(req ? e : toRequestError(e));
if (!res) {
return;
}
} else if (!req) {
res = handleRequestError();
} else {
res = handleFetchError(e);
}
} else {
return handleResponseError(e, outgoing);
}
}
try {
return await responseViaResponseObject(res, outgoing, options);
} catch (e) {
return handleResponseError(e, outgoing);
}
};
};
// src/server.ts
var createAdaptorServer = (options) => {
const fetchCallback = options.fetch;
const requestListener = getRequestListener(fetchCallback, {
hostname: options.hostname,
overrideGlobalObjects: options.overrideGlobalObjects,
autoCleanupIncoming: options.autoCleanupIncoming
});
const createServer = options.createServer || import_node_http.createServer;
const server = createServer(options.serverOptions || {}, requestListener);
return server;
};
var serve = (options, listeningListener) => {
const server = createAdaptorServer(options);
server.listen(options?.port ?? 3e3, options.hostname, () => {
const serverInfo = server.address();
listeningListener && listeningListener(serverInfo);
});
return server;
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
RequestError,
createAdaptorServer,
getRequestListener,
serve
});

662
node_modules/@hono/node-server/dist/index.mjs generated vendored Normal file
View File

@@ -0,0 +1,662 @@
// src/server.ts
import { createServer as createServerHTTP } from "http";
// src/listener.ts
import { Http2ServerRequest as Http2ServerRequest2, constants as h2constants } from "http2";
// src/request.ts
import { Http2ServerRequest } from "http2";
import { Readable } from "stream";
var RequestError = class extends Error {
constructor(message, options) {
super(message, options);
this.name = "RequestError";
}
};
var toRequestError = (e) => {
if (e instanceof RequestError) {
return e;
}
return new RequestError(e.message, { cause: e });
};
var GlobalRequest = global.Request;
var Request = class extends GlobalRequest {
constructor(input, options) {
if (typeof input === "object" && getRequestCache in input) {
input = input[getRequestCache]();
}
if (typeof options?.body?.getReader !== "undefined") {
;
options.duplex ??= "half";
}
super(input, options);
}
};
var newHeadersFromIncoming = (incoming) => {
const headerRecord = [];
const rawHeaders = incoming.rawHeaders;
for (let i = 0; i < rawHeaders.length; i += 2) {
const { [i]: key, [i + 1]: value } = rawHeaders;
if (key.charCodeAt(0) !== /*:*/
58) {
headerRecord.push([key, value]);
}
}
return new Headers(headerRecord);
};
var wrapBodyStream = Symbol("wrapBodyStream");
var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
const init = {
method,
headers,
signal: abortController.signal
};
if (method === "TRACE") {
init.method = "GET";
const req = new Request(url, init);
Object.defineProperty(req, "method", {
get() {
return "TRACE";
}
});
return req;
}
if (!(method === "GET" || method === "HEAD")) {
if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
init.body = new ReadableStream({
start(controller) {
controller.enqueue(incoming.rawBody);
controller.close();
}
});
} else if (incoming[wrapBodyStream]) {
let reader;
init.body = new ReadableStream({
async pull(controller) {
try {
reader ||= Readable.toWeb(incoming).getReader();
const { done, value } = await reader.read();
if (done) {
controller.close();
} else {
controller.enqueue(value);
}
} catch (error) {
controller.error(error);
}
}
});
} else {
init.body = Readable.toWeb(incoming);
}
}
return new Request(url, init);
};
var getRequestCache = Symbol("getRequestCache");
var requestCache = Symbol("requestCache");
var incomingKey = Symbol("incomingKey");
var urlKey = Symbol("urlKey");
var headersKey = Symbol("headersKey");
var abortControllerKey = Symbol("abortControllerKey");
var getAbortController = Symbol("getAbortController");
var requestPrototype = {
get method() {
return this[incomingKey].method || "GET";
},
get url() {
return this[urlKey];
},
get headers() {
return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
},
[getAbortController]() {
this[getRequestCache]();
return this[abortControllerKey];
},
[getRequestCache]() {
this[abortControllerKey] ||= new AbortController();
return this[requestCache] ||= newRequestFromIncoming(
this.method,
this[urlKey],
this.headers,
this[incomingKey],
this[abortControllerKey]
);
}
};
[
"body",
"bodyUsed",
"cache",
"credentials",
"destination",
"integrity",
"mode",
"redirect",
"referrer",
"referrerPolicy",
"signal",
"keepalive"
].forEach((k) => {
Object.defineProperty(requestPrototype, k, {
get() {
return this[getRequestCache]()[k];
}
});
});
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
Object.defineProperty(requestPrototype, k, {
value: function() {
return this[getRequestCache]()[k]();
}
});
});
Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), {
value: function(depth, options, inspectFn) {
const props = {
method: this.method,
url: this.url,
headers: this.headers,
nativeRequest: this[requestCache]
};
return `Request (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
}
});
Object.setPrototypeOf(requestPrototype, Request.prototype);
var newRequest = (incoming, defaultHostname) => {
const req = Object.create(requestPrototype);
req[incomingKey] = incoming;
const incomingUrl = incoming.url || "";
if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
(incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
if (incoming instanceof Http2ServerRequest) {
throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
}
try {
const url2 = new URL(incomingUrl);
req[urlKey] = url2.href;
} catch (e) {
throw new RequestError("Invalid absolute URL", { cause: e });
}
return req;
}
const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
if (!host) {
throw new RequestError("Missing host header");
}
let scheme;
if (incoming instanceof Http2ServerRequest) {
scheme = incoming.scheme;
if (!(scheme === "http" || scheme === "https")) {
throw new RequestError("Unsupported scheme");
}
} else {
scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
}
const url = new URL(`${scheme}://${host}${incomingUrl}`);
if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
throw new RequestError("Invalid host header");
}
req[urlKey] = url.href;
return req;
};
// src/response.ts
var responseCache = Symbol("responseCache");
var getResponseCache = Symbol("getResponseCache");
var cacheKey = Symbol("cache");
var GlobalResponse = global.Response;
var Response2 = class _Response {
#body;
#init;
[getResponseCache]() {
delete this[cacheKey];
return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
}
constructor(body, init) {
let headers;
this.#body = body;
if (init instanceof _Response) {
const cachedGlobalResponse = init[responseCache];
if (cachedGlobalResponse) {
this.#init = cachedGlobalResponse;
this[getResponseCache]();
return;
} else {
this.#init = init.#init;
headers = new Headers(init.#init.headers);
}
} else {
this.#init = init;
}
if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
;
this[cacheKey] = [init?.status || 200, body, headers || init?.headers];
}
}
get headers() {
const cache = this[cacheKey];
if (cache) {
if (!(cache[2] instanceof Headers)) {
cache[2] = new Headers(
cache[2] || { "content-type": "text/plain; charset=UTF-8" }
);
}
return cache[2];
}
return this[getResponseCache]().headers;
}
get status() {
return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
}
get ok() {
const status = this.status;
return status >= 200 && status < 300;
}
};
["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
Object.defineProperty(Response2.prototype, k, {
get() {
return this[getResponseCache]()[k];
}
});
});
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
Object.defineProperty(Response2.prototype, k, {
value: function() {
return this[getResponseCache]()[k]();
}
});
});
Object.defineProperty(Response2.prototype, Symbol.for("nodejs.util.inspect.custom"), {
value: function(depth, options, inspectFn) {
const props = {
status: this.status,
headers: this.headers,
ok: this.ok,
nativeResponse: this[responseCache]
};
return `Response (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
}
});
Object.setPrototypeOf(Response2, GlobalResponse);
Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
// src/utils.ts
async function readWithoutBlocking(readPromise) {
return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
}
function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
const cancel = (error) => {
reader.cancel(error).catch(() => {
});
};
writable.on("close", cancel);
writable.on("error", cancel);
(currentReadPromise ?? reader.read()).then(flow, handleStreamError);
return reader.closed.finally(() => {
writable.off("close", cancel);
writable.off("error", cancel);
});
function handleStreamError(error) {
if (error) {
writable.destroy(error);
}
}
function onDrain() {
reader.read().then(flow, handleStreamError);
}
function flow({ done, value }) {
try {
if (done) {
writable.end();
} else if (!writable.write(value)) {
writable.once("drain", onDrain);
} else {
return reader.read().then(flow, handleStreamError);
}
} catch (e) {
handleStreamError(e);
}
}
}
function writeFromReadableStream(stream, writable) {
if (stream.locked) {
throw new TypeError("ReadableStream is locked.");
} else if (writable.destroyed) {
return;
}
return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
}
var buildOutgoingHttpHeaders = (headers) => {
const res = {};
if (!(headers instanceof Headers)) {
headers = new Headers(headers ?? void 0);
}
const cookies = [];
for (const [k, v] of headers) {
if (k === "set-cookie") {
cookies.push(v);
} else {
res[k] = v;
}
}
if (cookies.length > 0) {
res["set-cookie"] = cookies;
}
res["content-type"] ??= "text/plain; charset=UTF-8";
return res;
};
// src/utils/response/constants.ts
var X_ALREADY_SENT = "x-hono-already-sent";
// src/globals.ts
import crypto from "crypto";
if (typeof global.crypto === "undefined") {
global.crypto = crypto;
}
// src/listener.ts
var outgoingEnded = Symbol("outgoingEnded");
var incomingDraining = Symbol("incomingDraining");
var DRAIN_TIMEOUT_MS = 500;
var MAX_DRAIN_BYTES = 64 * 1024 * 1024;
var drainIncoming = (incoming) => {
const incomingWithDrainState = incoming;
if (incoming.destroyed || incomingWithDrainState[incomingDraining]) {
return;
}
incomingWithDrainState[incomingDraining] = true;
if (incoming instanceof Http2ServerRequest2) {
try {
;
incoming.stream?.close?.(h2constants.NGHTTP2_NO_ERROR);
} catch {
}
return;
}
let bytesRead = 0;
const cleanup = () => {
clearTimeout(timer);
incoming.off("data", onData);
incoming.off("end", cleanup);
incoming.off("error", cleanup);
};
const forceClose = () => {
cleanup();
const socket = incoming.socket;
if (socket && !socket.destroyed) {
socket.destroySoon();
}
};
const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
timer.unref?.();
const onData = (chunk) => {
bytesRead += chunk.length;
if (bytesRead > MAX_DRAIN_BYTES) {
forceClose();
}
};
incoming.on("data", onData);
incoming.on("end", cleanup);
incoming.on("error", cleanup);
incoming.resume();
};
var handleRequestError = () => new Response(null, {
status: 400
});
var handleFetchError = (e) => new Response(null, {
status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
});
var handleResponseError = (e, outgoing) => {
const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
console.info("The user aborted a request.");
} else {
console.error(e);
if (!outgoing.headersSent) {
outgoing.writeHead(500, { "Content-Type": "text/plain" });
}
outgoing.end(`Error: ${err.message}`);
outgoing.destroy(err);
}
};
var flushHeaders = (outgoing) => {
if ("flushHeaders" in outgoing && outgoing.writable) {
outgoing.flushHeaders();
}
};
var responseViaCache = async (res, outgoing) => {
let [status, body, header] = res[cacheKey];
let hasContentLength = false;
if (!header) {
header = { "content-type": "text/plain; charset=UTF-8" };
} else if (header instanceof Headers) {
hasContentLength = header.has("content-length");
header = buildOutgoingHttpHeaders(header);
} else if (Array.isArray(header)) {
const headerObj = new Headers(header);
hasContentLength = headerObj.has("content-length");
header = buildOutgoingHttpHeaders(headerObj);
} else {
for (const key in header) {
if (key.length === 14 && key.toLowerCase() === "content-length") {
hasContentLength = true;
break;
}
}
}
if (!hasContentLength) {
if (typeof body === "string") {
header["Content-Length"] = Buffer.byteLength(body);
} else if (body instanceof Uint8Array) {
header["Content-Length"] = body.byteLength;
} else if (body instanceof Blob) {
header["Content-Length"] = body.size;
}
}
outgoing.writeHead(status, header);
if (typeof body === "string" || body instanceof Uint8Array) {
outgoing.end(body);
} else if (body instanceof Blob) {
outgoing.end(new Uint8Array(await body.arrayBuffer()));
} else {
flushHeaders(outgoing);
await writeFromReadableStream(body, outgoing)?.catch(
(e) => handleResponseError(e, outgoing)
);
}
;
outgoing[outgoingEnded]?.();
};
var isPromise = (res) => typeof res.then === "function";
var responseViaResponseObject = async (res, outgoing, options = {}) => {
if (isPromise(res)) {
if (options.errorHandler) {
try {
res = await res;
} catch (err) {
const errRes = await options.errorHandler(err);
if (!errRes) {
return;
}
res = errRes;
}
} else {
res = await res.catch(handleFetchError);
}
}
if (cacheKey in res) {
return responseViaCache(res, outgoing);
}
const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
if (res.body) {
const reader = res.body.getReader();
const values = [];
let done = false;
let currentReadPromise = void 0;
if (resHeaderRecord["transfer-encoding"] !== "chunked") {
let maxReadCount = 2;
for (let i = 0; i < maxReadCount; i++) {
currentReadPromise ||= reader.read();
const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
console.error(e);
done = true;
});
if (!chunk) {
if (i === 1) {
await new Promise((resolve) => setTimeout(resolve));
maxReadCount = 3;
continue;
}
break;
}
currentReadPromise = void 0;
if (chunk.value) {
values.push(chunk.value);
}
if (chunk.done) {
done = true;
break;
}
}
if (done && !("content-length" in resHeaderRecord)) {
resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
}
}
outgoing.writeHead(res.status, resHeaderRecord);
values.forEach((value) => {
;
outgoing.write(value);
});
if (done) {
outgoing.end();
} else {
if (values.length === 0) {
flushHeaders(outgoing);
}
await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
}
} else if (resHeaderRecord[X_ALREADY_SENT]) {
} else {
outgoing.writeHead(res.status, resHeaderRecord);
outgoing.end();
}
;
outgoing[outgoingEnded]?.();
};
var getRequestListener = (fetchCallback, options = {}) => {
const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
if (options.overrideGlobalObjects !== false && global.Request !== Request) {
Object.defineProperty(global, "Request", {
value: Request
});
Object.defineProperty(global, "Response", {
value: Response2
});
}
return async (incoming, outgoing) => {
let res, req;
try {
req = newRequest(incoming, options.hostname);
let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
if (!incomingEnded) {
;
incoming[wrapBodyStream] = true;
incoming.on("end", () => {
incomingEnded = true;
});
if (incoming instanceof Http2ServerRequest2) {
;
outgoing[outgoingEnded] = () => {
if (!incomingEnded) {
setTimeout(() => {
if (!incomingEnded) {
setTimeout(() => {
drainIncoming(incoming);
});
}
});
}
};
}
outgoing.on("finish", () => {
if (!incomingEnded) {
drainIncoming(incoming);
}
});
}
outgoing.on("close", () => {
const abortController = req[abortControllerKey];
if (abortController) {
if (incoming.errored) {
req[abortControllerKey].abort(incoming.errored.toString());
} else if (!outgoing.writableFinished) {
req[abortControllerKey].abort("Client connection prematurely closed.");
}
}
if (!incomingEnded) {
setTimeout(() => {
if (!incomingEnded) {
setTimeout(() => {
drainIncoming(incoming);
});
}
});
}
});
res = fetchCallback(req, { incoming, outgoing });
if (cacheKey in res) {
return responseViaCache(res, outgoing);
}
} catch (e) {
if (!res) {
if (options.errorHandler) {
res = await options.errorHandler(req ? e : toRequestError(e));
if (!res) {
return;
}
} else if (!req) {
res = handleRequestError();
} else {
res = handleFetchError(e);
}
} else {
return handleResponseError(e, outgoing);
}
}
try {
return await responseViaResponseObject(res, outgoing, options);
} catch (e) {
return handleResponseError(e, outgoing);
}
};
};
// src/server.ts
var createAdaptorServer = (options) => {
const fetchCallback = options.fetch;
const requestListener = getRequestListener(fetchCallback, {
hostname: options.hostname,
overrideGlobalObjects: options.overrideGlobalObjects,
autoCleanupIncoming: options.autoCleanupIncoming
});
const createServer = options.createServer || createServerHTTP;
const server = createServer(options.serverOptions || {}, requestListener);
return server;
};
var serve = (options, listeningListener) => {
const server = createAdaptorServer(options);
server.listen(options?.port ?? 3e3, options.hostname, () => {
const serverInfo = server.address();
listeningListener && listeningListener(serverInfo);
});
return server;
};
export {
RequestError,
createAdaptorServer,
getRequestListener,
serve
};

13
node_modules/@hono/node-server/dist/listener.d.mts generated vendored Normal file
View File

@@ -0,0 +1,13 @@
import { IncomingMessage, ServerResponse } from 'node:http';
import { Http2ServerRequest, Http2ServerResponse } from 'node:http2';
import { FetchCallback, CustomErrorHandler } from './types.mjs';
import 'node:https';
declare const getRequestListener: (fetchCallback: FetchCallback, options?: {
hostname?: string;
errorHandler?: CustomErrorHandler;
overrideGlobalObjects?: boolean;
autoCleanupIncoming?: boolean;
}) => (incoming: IncomingMessage | Http2ServerRequest, outgoing: ServerResponse | Http2ServerResponse) => Promise<void>;
export { getRequestListener };

13
node_modules/@hono/node-server/dist/listener.d.ts generated vendored Normal file
View File

@@ -0,0 +1,13 @@
import { IncomingMessage, ServerResponse } from 'node:http';
import { Http2ServerRequest, Http2ServerResponse } from 'node:http2';
import { FetchCallback, CustomErrorHandler } from './types.js';
import 'node:https';
declare const getRequestListener: (fetchCallback: FetchCallback, options?: {
hostname?: string;
errorHandler?: CustomErrorHandler;
overrideGlobalObjects?: boolean;
autoCleanupIncoming?: boolean;
}) => (incoming: IncomingMessage | Http2ServerRequest, outgoing: ServerResponse | Http2ServerResponse) => Promise<void>;
export { getRequestListener };

670
node_modules/@hono/node-server/dist/listener.js generated vendored Normal file
View File

@@ -0,0 +1,670 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/listener.ts
var listener_exports = {};
__export(listener_exports, {
getRequestListener: () => getRequestListener
});
module.exports = __toCommonJS(listener_exports);
var import_node_http22 = require("http2");
// src/request.ts
var import_node_http2 = require("http2");
var import_node_stream = require("stream");
var RequestError = class extends Error {
constructor(message, options) {
super(message, options);
this.name = "RequestError";
}
};
var toRequestError = (e) => {
if (e instanceof RequestError) {
return e;
}
return new RequestError(e.message, { cause: e });
};
var GlobalRequest = global.Request;
var Request = class extends GlobalRequest {
constructor(input, options) {
if (typeof input === "object" && getRequestCache in input) {
input = input[getRequestCache]();
}
if (typeof options?.body?.getReader !== "undefined") {
;
options.duplex ??= "half";
}
super(input, options);
}
};
var newHeadersFromIncoming = (incoming) => {
const headerRecord = [];
const rawHeaders = incoming.rawHeaders;
for (let i = 0; i < rawHeaders.length; i += 2) {
const { [i]: key, [i + 1]: value } = rawHeaders;
if (key.charCodeAt(0) !== /*:*/
58) {
headerRecord.push([key, value]);
}
}
return new Headers(headerRecord);
};
var wrapBodyStream = Symbol("wrapBodyStream");
var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
const init = {
method,
headers,
signal: abortController.signal
};
if (method === "TRACE") {
init.method = "GET";
const req = new Request(url, init);
Object.defineProperty(req, "method", {
get() {
return "TRACE";
}
});
return req;
}
if (!(method === "GET" || method === "HEAD")) {
if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
init.body = new ReadableStream({
start(controller) {
controller.enqueue(incoming.rawBody);
controller.close();
}
});
} else if (incoming[wrapBodyStream]) {
let reader;
init.body = new ReadableStream({
async pull(controller) {
try {
reader ||= import_node_stream.Readable.toWeb(incoming).getReader();
const { done, value } = await reader.read();
if (done) {
controller.close();
} else {
controller.enqueue(value);
}
} catch (error) {
controller.error(error);
}
}
});
} else {
init.body = import_node_stream.Readable.toWeb(incoming);
}
}
return new Request(url, init);
};
var getRequestCache = Symbol("getRequestCache");
var requestCache = Symbol("requestCache");
var incomingKey = Symbol("incomingKey");
var urlKey = Symbol("urlKey");
var headersKey = Symbol("headersKey");
var abortControllerKey = Symbol("abortControllerKey");
var getAbortController = Symbol("getAbortController");
var requestPrototype = {
get method() {
return this[incomingKey].method || "GET";
},
get url() {
return this[urlKey];
},
get headers() {
return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
},
[getAbortController]() {
this[getRequestCache]();
return this[abortControllerKey];
},
[getRequestCache]() {
this[abortControllerKey] ||= new AbortController();
return this[requestCache] ||= newRequestFromIncoming(
this.method,
this[urlKey],
this.headers,
this[incomingKey],
this[abortControllerKey]
);
}
};
[
"body",
"bodyUsed",
"cache",
"credentials",
"destination",
"integrity",
"mode",
"redirect",
"referrer",
"referrerPolicy",
"signal",
"keepalive"
].forEach((k) => {
Object.defineProperty(requestPrototype, k, {
get() {
return this[getRequestCache]()[k];
}
});
});
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
Object.defineProperty(requestPrototype, k, {
value: function() {
return this[getRequestCache]()[k]();
}
});
});
Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), {
value: function(depth, options, inspectFn) {
const props = {
method: this.method,
url: this.url,
headers: this.headers,
nativeRequest: this[requestCache]
};
return `Request (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
}
});
Object.setPrototypeOf(requestPrototype, Request.prototype);
var newRequest = (incoming, defaultHostname) => {
const req = Object.create(requestPrototype);
req[incomingKey] = incoming;
const incomingUrl = incoming.url || "";
if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
(incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
if (incoming instanceof import_node_http2.Http2ServerRequest) {
throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
}
try {
const url2 = new URL(incomingUrl);
req[urlKey] = url2.href;
} catch (e) {
throw new RequestError("Invalid absolute URL", { cause: e });
}
return req;
}
const host = (incoming instanceof import_node_http2.Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
if (!host) {
throw new RequestError("Missing host header");
}
let scheme;
if (incoming instanceof import_node_http2.Http2ServerRequest) {
scheme = incoming.scheme;
if (!(scheme === "http" || scheme === "https")) {
throw new RequestError("Unsupported scheme");
}
} else {
scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
}
const url = new URL(`${scheme}://${host}${incomingUrl}`);
if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
throw new RequestError("Invalid host header");
}
req[urlKey] = url.href;
return req;
};
// src/response.ts
var responseCache = Symbol("responseCache");
var getResponseCache = Symbol("getResponseCache");
var cacheKey = Symbol("cache");
var GlobalResponse = global.Response;
var Response2 = class _Response {
#body;
#init;
[getResponseCache]() {
delete this[cacheKey];
return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
}
constructor(body, init) {
let headers;
this.#body = body;
if (init instanceof _Response) {
const cachedGlobalResponse = init[responseCache];
if (cachedGlobalResponse) {
this.#init = cachedGlobalResponse;
this[getResponseCache]();
return;
} else {
this.#init = init.#init;
headers = new Headers(init.#init.headers);
}
} else {
this.#init = init;
}
if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
;
this[cacheKey] = [init?.status || 200, body, headers || init?.headers];
}
}
get headers() {
const cache = this[cacheKey];
if (cache) {
if (!(cache[2] instanceof Headers)) {
cache[2] = new Headers(
cache[2] || { "content-type": "text/plain; charset=UTF-8" }
);
}
return cache[2];
}
return this[getResponseCache]().headers;
}
get status() {
return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
}
get ok() {
const status = this.status;
return status >= 200 && status < 300;
}
};
["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
Object.defineProperty(Response2.prototype, k, {
get() {
return this[getResponseCache]()[k];
}
});
});
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
Object.defineProperty(Response2.prototype, k, {
value: function() {
return this[getResponseCache]()[k]();
}
});
});
Object.defineProperty(Response2.prototype, Symbol.for("nodejs.util.inspect.custom"), {
value: function(depth, options, inspectFn) {
const props = {
status: this.status,
headers: this.headers,
ok: this.ok,
nativeResponse: this[responseCache]
};
return `Response (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
}
});
Object.setPrototypeOf(Response2, GlobalResponse);
Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
// src/utils.ts
async function readWithoutBlocking(readPromise) {
return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
}
function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
const cancel = (error) => {
reader.cancel(error).catch(() => {
});
};
writable.on("close", cancel);
writable.on("error", cancel);
(currentReadPromise ?? reader.read()).then(flow, handleStreamError);
return reader.closed.finally(() => {
writable.off("close", cancel);
writable.off("error", cancel);
});
function handleStreamError(error) {
if (error) {
writable.destroy(error);
}
}
function onDrain() {
reader.read().then(flow, handleStreamError);
}
function flow({ done, value }) {
try {
if (done) {
writable.end();
} else if (!writable.write(value)) {
writable.once("drain", onDrain);
} else {
return reader.read().then(flow, handleStreamError);
}
} catch (e) {
handleStreamError(e);
}
}
}
function writeFromReadableStream(stream, writable) {
if (stream.locked) {
throw new TypeError("ReadableStream is locked.");
} else if (writable.destroyed) {
return;
}
return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
}
var buildOutgoingHttpHeaders = (headers) => {
const res = {};
if (!(headers instanceof Headers)) {
headers = new Headers(headers ?? void 0);
}
const cookies = [];
for (const [k, v] of headers) {
if (k === "set-cookie") {
cookies.push(v);
} else {
res[k] = v;
}
}
if (cookies.length > 0) {
res["set-cookie"] = cookies;
}
res["content-type"] ??= "text/plain; charset=UTF-8";
return res;
};
// src/utils/response/constants.ts
var X_ALREADY_SENT = "x-hono-already-sent";
// src/globals.ts
var import_node_crypto = __toESM(require("crypto"));
if (typeof global.crypto === "undefined") {
global.crypto = import_node_crypto.default;
}
// src/listener.ts
var outgoingEnded = Symbol("outgoingEnded");
var incomingDraining = Symbol("incomingDraining");
var DRAIN_TIMEOUT_MS = 500;
var MAX_DRAIN_BYTES = 64 * 1024 * 1024;
var drainIncoming = (incoming) => {
const incomingWithDrainState = incoming;
if (incoming.destroyed || incomingWithDrainState[incomingDraining]) {
return;
}
incomingWithDrainState[incomingDraining] = true;
if (incoming instanceof import_node_http22.Http2ServerRequest) {
try {
;
incoming.stream?.close?.(import_node_http22.constants.NGHTTP2_NO_ERROR);
} catch {
}
return;
}
let bytesRead = 0;
const cleanup = () => {
clearTimeout(timer);
incoming.off("data", onData);
incoming.off("end", cleanup);
incoming.off("error", cleanup);
};
const forceClose = () => {
cleanup();
const socket = incoming.socket;
if (socket && !socket.destroyed) {
socket.destroySoon();
}
};
const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
timer.unref?.();
const onData = (chunk) => {
bytesRead += chunk.length;
if (bytesRead > MAX_DRAIN_BYTES) {
forceClose();
}
};
incoming.on("data", onData);
incoming.on("end", cleanup);
incoming.on("error", cleanup);
incoming.resume();
};
var handleRequestError = () => new Response(null, {
status: 400
});
var handleFetchError = (e) => new Response(null, {
status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
});
var handleResponseError = (e, outgoing) => {
const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
console.info("The user aborted a request.");
} else {
console.error(e);
if (!outgoing.headersSent) {
outgoing.writeHead(500, { "Content-Type": "text/plain" });
}
outgoing.end(`Error: ${err.message}`);
outgoing.destroy(err);
}
};
var flushHeaders = (outgoing) => {
if ("flushHeaders" in outgoing && outgoing.writable) {
outgoing.flushHeaders();
}
};
var responseViaCache = async (res, outgoing) => {
let [status, body, header] = res[cacheKey];
let hasContentLength = false;
if (!header) {
header = { "content-type": "text/plain; charset=UTF-8" };
} else if (header instanceof Headers) {
hasContentLength = header.has("content-length");
header = buildOutgoingHttpHeaders(header);
} else if (Array.isArray(header)) {
const headerObj = new Headers(header);
hasContentLength = headerObj.has("content-length");
header = buildOutgoingHttpHeaders(headerObj);
} else {
for (const key in header) {
if (key.length === 14 && key.toLowerCase() === "content-length") {
hasContentLength = true;
break;
}
}
}
if (!hasContentLength) {
if (typeof body === "string") {
header["Content-Length"] = Buffer.byteLength(body);
} else if (body instanceof Uint8Array) {
header["Content-Length"] = body.byteLength;
} else if (body instanceof Blob) {
header["Content-Length"] = body.size;
}
}
outgoing.writeHead(status, header);
if (typeof body === "string" || body instanceof Uint8Array) {
outgoing.end(body);
} else if (body instanceof Blob) {
outgoing.end(new Uint8Array(await body.arrayBuffer()));
} else {
flushHeaders(outgoing);
await writeFromReadableStream(body, outgoing)?.catch(
(e) => handleResponseError(e, outgoing)
);
}
;
outgoing[outgoingEnded]?.();
};
var isPromise = (res) => typeof res.then === "function";
var responseViaResponseObject = async (res, outgoing, options = {}) => {
if (isPromise(res)) {
if (options.errorHandler) {
try {
res = await res;
} catch (err) {
const errRes = await options.errorHandler(err);
if (!errRes) {
return;
}
res = errRes;
}
} else {
res = await res.catch(handleFetchError);
}
}
if (cacheKey in res) {
return responseViaCache(res, outgoing);
}
const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
if (res.body) {
const reader = res.body.getReader();
const values = [];
let done = false;
let currentReadPromise = void 0;
if (resHeaderRecord["transfer-encoding"] !== "chunked") {
let maxReadCount = 2;
for (let i = 0; i < maxReadCount; i++) {
currentReadPromise ||= reader.read();
const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
console.error(e);
done = true;
});
if (!chunk) {
if (i === 1) {
await new Promise((resolve) => setTimeout(resolve));
maxReadCount = 3;
continue;
}
break;
}
currentReadPromise = void 0;
if (chunk.value) {
values.push(chunk.value);
}
if (chunk.done) {
done = true;
break;
}
}
if (done && !("content-length" in resHeaderRecord)) {
resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
}
}
outgoing.writeHead(res.status, resHeaderRecord);
values.forEach((value) => {
;
outgoing.write(value);
});
if (done) {
outgoing.end();
} else {
if (values.length === 0) {
flushHeaders(outgoing);
}
await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
}
} else if (resHeaderRecord[X_ALREADY_SENT]) {
} else {
outgoing.writeHead(res.status, resHeaderRecord);
outgoing.end();
}
;
outgoing[outgoingEnded]?.();
};
var getRequestListener = (fetchCallback, options = {}) => {
const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
if (options.overrideGlobalObjects !== false && global.Request !== Request) {
Object.defineProperty(global, "Request", {
value: Request
});
Object.defineProperty(global, "Response", {
value: Response2
});
}
return async (incoming, outgoing) => {
let res, req;
try {
req = newRequest(incoming, options.hostname);
let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
if (!incomingEnded) {
;
incoming[wrapBodyStream] = true;
incoming.on("end", () => {
incomingEnded = true;
});
if (incoming instanceof import_node_http22.Http2ServerRequest) {
;
outgoing[outgoingEnded] = () => {
if (!incomingEnded) {
setTimeout(() => {
if (!incomingEnded) {
setTimeout(() => {
drainIncoming(incoming);
});
}
});
}
};
}
outgoing.on("finish", () => {
if (!incomingEnded) {
drainIncoming(incoming);
}
});
}
outgoing.on("close", () => {
const abortController = req[abortControllerKey];
if (abortController) {
if (incoming.errored) {
req[abortControllerKey].abort(incoming.errored.toString());
} else if (!outgoing.writableFinished) {
req[abortControllerKey].abort("Client connection prematurely closed.");
}
}
if (!incomingEnded) {
setTimeout(() => {
if (!incomingEnded) {
setTimeout(() => {
drainIncoming(incoming);
});
}
});
}
});
res = fetchCallback(req, { incoming, outgoing });
if (cacheKey in res) {
return responseViaCache(res, outgoing);
}
} catch (e) {
if (!res) {
if (options.errorHandler) {
res = await options.errorHandler(req ? e : toRequestError(e));
if (!res) {
return;
}
} else if (!req) {
res = handleRequestError();
} else {
res = handleFetchError(e);
}
} else {
return handleResponseError(e, outgoing);
}
}
try {
return await responseViaResponseObject(res, outgoing, options);
} catch (e) {
return handleResponseError(e, outgoing);
}
};
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
getRequestListener
});

635
node_modules/@hono/node-server/dist/listener.mjs generated vendored Normal file
View File

@@ -0,0 +1,635 @@
// src/listener.ts
import { Http2ServerRequest as Http2ServerRequest2, constants as h2constants } from "http2";
// src/request.ts
import { Http2ServerRequest } from "http2";
import { Readable } from "stream";
var RequestError = class extends Error {
constructor(message, options) {
super(message, options);
this.name = "RequestError";
}
};
var toRequestError = (e) => {
if (e instanceof RequestError) {
return e;
}
return new RequestError(e.message, { cause: e });
};
var GlobalRequest = global.Request;
var Request = class extends GlobalRequest {
constructor(input, options) {
if (typeof input === "object" && getRequestCache in input) {
input = input[getRequestCache]();
}
if (typeof options?.body?.getReader !== "undefined") {
;
options.duplex ??= "half";
}
super(input, options);
}
};
var newHeadersFromIncoming = (incoming) => {
const headerRecord = [];
const rawHeaders = incoming.rawHeaders;
for (let i = 0; i < rawHeaders.length; i += 2) {
const { [i]: key, [i + 1]: value } = rawHeaders;
if (key.charCodeAt(0) !== /*:*/
58) {
headerRecord.push([key, value]);
}
}
return new Headers(headerRecord);
};
var wrapBodyStream = Symbol("wrapBodyStream");
var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
const init = {
method,
headers,
signal: abortController.signal
};
if (method === "TRACE") {
init.method = "GET";
const req = new Request(url, init);
Object.defineProperty(req, "method", {
get() {
return "TRACE";
}
});
return req;
}
if (!(method === "GET" || method === "HEAD")) {
if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
init.body = new ReadableStream({
start(controller) {
controller.enqueue(incoming.rawBody);
controller.close();
}
});
} else if (incoming[wrapBodyStream]) {
let reader;
init.body = new ReadableStream({
async pull(controller) {
try {
reader ||= Readable.toWeb(incoming).getReader();
const { done, value } = await reader.read();
if (done) {
controller.close();
} else {
controller.enqueue(value);
}
} catch (error) {
controller.error(error);
}
}
});
} else {
init.body = Readable.toWeb(incoming);
}
}
return new Request(url, init);
};
var getRequestCache = Symbol("getRequestCache");
var requestCache = Symbol("requestCache");
var incomingKey = Symbol("incomingKey");
var urlKey = Symbol("urlKey");
var headersKey = Symbol("headersKey");
var abortControllerKey = Symbol("abortControllerKey");
var getAbortController = Symbol("getAbortController");
var requestPrototype = {
get method() {
return this[incomingKey].method || "GET";
},
get url() {
return this[urlKey];
},
get headers() {
return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
},
[getAbortController]() {
this[getRequestCache]();
return this[abortControllerKey];
},
[getRequestCache]() {
this[abortControllerKey] ||= new AbortController();
return this[requestCache] ||= newRequestFromIncoming(
this.method,
this[urlKey],
this.headers,
this[incomingKey],
this[abortControllerKey]
);
}
};
[
"body",
"bodyUsed",
"cache",
"credentials",
"destination",
"integrity",
"mode",
"redirect",
"referrer",
"referrerPolicy",
"signal",
"keepalive"
].forEach((k) => {
Object.defineProperty(requestPrototype, k, {
get() {
return this[getRequestCache]()[k];
}
});
});
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
Object.defineProperty(requestPrototype, k, {
value: function() {
return this[getRequestCache]()[k]();
}
});
});
Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), {
value: function(depth, options, inspectFn) {
const props = {
method: this.method,
url: this.url,
headers: this.headers,
nativeRequest: this[requestCache]
};
return `Request (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
}
});
Object.setPrototypeOf(requestPrototype, Request.prototype);
var newRequest = (incoming, defaultHostname) => {
const req = Object.create(requestPrototype);
req[incomingKey] = incoming;
const incomingUrl = incoming.url || "";
if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
(incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
if (incoming instanceof Http2ServerRequest) {
throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
}
try {
const url2 = new URL(incomingUrl);
req[urlKey] = url2.href;
} catch (e) {
throw new RequestError("Invalid absolute URL", { cause: e });
}
return req;
}
const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
if (!host) {
throw new RequestError("Missing host header");
}
let scheme;
if (incoming instanceof Http2ServerRequest) {
scheme = incoming.scheme;
if (!(scheme === "http" || scheme === "https")) {
throw new RequestError("Unsupported scheme");
}
} else {
scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
}
const url = new URL(`${scheme}://${host}${incomingUrl}`);
if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
throw new RequestError("Invalid host header");
}
req[urlKey] = url.href;
return req;
};
// src/response.ts
var responseCache = Symbol("responseCache");
var getResponseCache = Symbol("getResponseCache");
var cacheKey = Symbol("cache");
var GlobalResponse = global.Response;
var Response2 = class _Response {
#body;
#init;
[getResponseCache]() {
delete this[cacheKey];
return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
}
constructor(body, init) {
let headers;
this.#body = body;
if (init instanceof _Response) {
const cachedGlobalResponse = init[responseCache];
if (cachedGlobalResponse) {
this.#init = cachedGlobalResponse;
this[getResponseCache]();
return;
} else {
this.#init = init.#init;
headers = new Headers(init.#init.headers);
}
} else {
this.#init = init;
}
if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
;
this[cacheKey] = [init?.status || 200, body, headers || init?.headers];
}
}
get headers() {
const cache = this[cacheKey];
if (cache) {
if (!(cache[2] instanceof Headers)) {
cache[2] = new Headers(
cache[2] || { "content-type": "text/plain; charset=UTF-8" }
);
}
return cache[2];
}
return this[getResponseCache]().headers;
}
get status() {
return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
}
get ok() {
const status = this.status;
return status >= 200 && status < 300;
}
};
["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
Object.defineProperty(Response2.prototype, k, {
get() {
return this[getResponseCache]()[k];
}
});
});
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
Object.defineProperty(Response2.prototype, k, {
value: function() {
return this[getResponseCache]()[k]();
}
});
});
Object.defineProperty(Response2.prototype, Symbol.for("nodejs.util.inspect.custom"), {
value: function(depth, options, inspectFn) {
const props = {
status: this.status,
headers: this.headers,
ok: this.ok,
nativeResponse: this[responseCache]
};
return `Response (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
}
});
Object.setPrototypeOf(Response2, GlobalResponse);
Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
// src/utils.ts
async function readWithoutBlocking(readPromise) {
return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
}
function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
const cancel = (error) => {
reader.cancel(error).catch(() => {
});
};
writable.on("close", cancel);
writable.on("error", cancel);
(currentReadPromise ?? reader.read()).then(flow, handleStreamError);
return reader.closed.finally(() => {
writable.off("close", cancel);
writable.off("error", cancel);
});
function handleStreamError(error) {
if (error) {
writable.destroy(error);
}
}
function onDrain() {
reader.read().then(flow, handleStreamError);
}
function flow({ done, value }) {
try {
if (done) {
writable.end();
} else if (!writable.write(value)) {
writable.once("drain", onDrain);
} else {
return reader.read().then(flow, handleStreamError);
}
} catch (e) {
handleStreamError(e);
}
}
}
function writeFromReadableStream(stream, writable) {
if (stream.locked) {
throw new TypeError("ReadableStream is locked.");
} else if (writable.destroyed) {
return;
}
return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
}
var buildOutgoingHttpHeaders = (headers) => {
const res = {};
if (!(headers instanceof Headers)) {
headers = new Headers(headers ?? void 0);
}
const cookies = [];
for (const [k, v] of headers) {
if (k === "set-cookie") {
cookies.push(v);
} else {
res[k] = v;
}
}
if (cookies.length > 0) {
res["set-cookie"] = cookies;
}
res["content-type"] ??= "text/plain; charset=UTF-8";
return res;
};
// src/utils/response/constants.ts
var X_ALREADY_SENT = "x-hono-already-sent";
// src/globals.ts
import crypto from "crypto";
if (typeof global.crypto === "undefined") {
global.crypto = crypto;
}
// src/listener.ts
var outgoingEnded = Symbol("outgoingEnded");
var incomingDraining = Symbol("incomingDraining");
var DRAIN_TIMEOUT_MS = 500;
var MAX_DRAIN_BYTES = 64 * 1024 * 1024;
var drainIncoming = (incoming) => {
const incomingWithDrainState = incoming;
if (incoming.destroyed || incomingWithDrainState[incomingDraining]) {
return;
}
incomingWithDrainState[incomingDraining] = true;
if (incoming instanceof Http2ServerRequest2) {
try {
;
incoming.stream?.close?.(h2constants.NGHTTP2_NO_ERROR);
} catch {
}
return;
}
let bytesRead = 0;
const cleanup = () => {
clearTimeout(timer);
incoming.off("data", onData);
incoming.off("end", cleanup);
incoming.off("error", cleanup);
};
const forceClose = () => {
cleanup();
const socket = incoming.socket;
if (socket && !socket.destroyed) {
socket.destroySoon();
}
};
const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
timer.unref?.();
const onData = (chunk) => {
bytesRead += chunk.length;
if (bytesRead > MAX_DRAIN_BYTES) {
forceClose();
}
};
incoming.on("data", onData);
incoming.on("end", cleanup);
incoming.on("error", cleanup);
incoming.resume();
};
var handleRequestError = () => new Response(null, {
status: 400
});
var handleFetchError = (e) => new Response(null, {
status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
});
var handleResponseError = (e, outgoing) => {
const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
console.info("The user aborted a request.");
} else {
console.error(e);
if (!outgoing.headersSent) {
outgoing.writeHead(500, { "Content-Type": "text/plain" });
}
outgoing.end(`Error: ${err.message}`);
outgoing.destroy(err);
}
};
var flushHeaders = (outgoing) => {
if ("flushHeaders" in outgoing && outgoing.writable) {
outgoing.flushHeaders();
}
};
var responseViaCache = async (res, outgoing) => {
let [status, body, header] = res[cacheKey];
let hasContentLength = false;
if (!header) {
header = { "content-type": "text/plain; charset=UTF-8" };
} else if (header instanceof Headers) {
hasContentLength = header.has("content-length");
header = buildOutgoingHttpHeaders(header);
} else if (Array.isArray(header)) {
const headerObj = new Headers(header);
hasContentLength = headerObj.has("content-length");
header = buildOutgoingHttpHeaders(headerObj);
} else {
for (const key in header) {
if (key.length === 14 && key.toLowerCase() === "content-length") {
hasContentLength = true;
break;
}
}
}
if (!hasContentLength) {
if (typeof body === "string") {
header["Content-Length"] = Buffer.byteLength(body);
} else if (body instanceof Uint8Array) {
header["Content-Length"] = body.byteLength;
} else if (body instanceof Blob) {
header["Content-Length"] = body.size;
}
}
outgoing.writeHead(status, header);
if (typeof body === "string" || body instanceof Uint8Array) {
outgoing.end(body);
} else if (body instanceof Blob) {
outgoing.end(new Uint8Array(await body.arrayBuffer()));
} else {
flushHeaders(outgoing);
await writeFromReadableStream(body, outgoing)?.catch(
(e) => handleResponseError(e, outgoing)
);
}
;
outgoing[outgoingEnded]?.();
};
var isPromise = (res) => typeof res.then === "function";
var responseViaResponseObject = async (res, outgoing, options = {}) => {
if (isPromise(res)) {
if (options.errorHandler) {
try {
res = await res;
} catch (err) {
const errRes = await options.errorHandler(err);
if (!errRes) {
return;
}
res = errRes;
}
} else {
res = await res.catch(handleFetchError);
}
}
if (cacheKey in res) {
return responseViaCache(res, outgoing);
}
const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
if (res.body) {
const reader = res.body.getReader();
const values = [];
let done = false;
let currentReadPromise = void 0;
if (resHeaderRecord["transfer-encoding"] !== "chunked") {
let maxReadCount = 2;
for (let i = 0; i < maxReadCount; i++) {
currentReadPromise ||= reader.read();
const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
console.error(e);
done = true;
});
if (!chunk) {
if (i === 1) {
await new Promise((resolve) => setTimeout(resolve));
maxReadCount = 3;
continue;
}
break;
}
currentReadPromise = void 0;
if (chunk.value) {
values.push(chunk.value);
}
if (chunk.done) {
done = true;
break;
}
}
if (done && !("content-length" in resHeaderRecord)) {
resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
}
}
outgoing.writeHead(res.status, resHeaderRecord);
values.forEach((value) => {
;
outgoing.write(value);
});
if (done) {
outgoing.end();
} else {
if (values.length === 0) {
flushHeaders(outgoing);
}
await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
}
} else if (resHeaderRecord[X_ALREADY_SENT]) {
} else {
outgoing.writeHead(res.status, resHeaderRecord);
outgoing.end();
}
;
outgoing[outgoingEnded]?.();
};
var getRequestListener = (fetchCallback, options = {}) => {
const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
if (options.overrideGlobalObjects !== false && global.Request !== Request) {
Object.defineProperty(global, "Request", {
value: Request
});
Object.defineProperty(global, "Response", {
value: Response2
});
}
return async (incoming, outgoing) => {
let res, req;
try {
req = newRequest(incoming, options.hostname);
let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
if (!incomingEnded) {
;
incoming[wrapBodyStream] = true;
incoming.on("end", () => {
incomingEnded = true;
});
if (incoming instanceof Http2ServerRequest2) {
;
outgoing[outgoingEnded] = () => {
if (!incomingEnded) {
setTimeout(() => {
if (!incomingEnded) {
setTimeout(() => {
drainIncoming(incoming);
});
}
});
}
};
}
outgoing.on("finish", () => {
if (!incomingEnded) {
drainIncoming(incoming);
}
});
}
outgoing.on("close", () => {
const abortController = req[abortControllerKey];
if (abortController) {
if (incoming.errored) {
req[abortControllerKey].abort(incoming.errored.toString());
} else if (!outgoing.writableFinished) {
req[abortControllerKey].abort("Client connection prematurely closed.");
}
}
if (!incomingEnded) {
setTimeout(() => {
if (!incomingEnded) {
setTimeout(() => {
drainIncoming(incoming);
});
}
});
}
});
res = fetchCallback(req, { incoming, outgoing });
if (cacheKey in res) {
return responseViaCache(res, outgoing);
}
} catch (e) {
if (!res) {
if (options.errorHandler) {
res = await options.errorHandler(req ? e : toRequestError(e));
if (!res) {
return;
}
} else if (!req) {
res = handleRequestError();
} else {
res = handleFetchError(e);
}
} else {
return handleResponseError(e, outgoing);
}
}
try {
return await responseViaResponseObject(res, outgoing, options);
} catch (e) {
return handleResponseError(e, outgoing);
}
};
};
export {
getRequestListener
};

25
node_modules/@hono/node-server/dist/request.d.mts generated vendored Normal file
View File

@@ -0,0 +1,25 @@
import { IncomingMessage } from 'node:http';
import { Http2ServerRequest } from 'node:http2';
declare class RequestError extends Error {
constructor(message: string, options?: {
cause?: unknown;
});
}
declare const toRequestError: (e: unknown) => RequestError;
declare const GlobalRequest: {
new (input: RequestInfo | URL, init?: RequestInit): globalThis.Request;
prototype: globalThis.Request;
};
declare class Request extends GlobalRequest {
constructor(input: string | Request, options?: RequestInit);
}
type IncomingMessageWithWrapBodyStream = IncomingMessage & {
[wrapBodyStream]: boolean;
};
declare const wrapBodyStream: unique symbol;
declare const abortControllerKey: unique symbol;
declare const getAbortController: unique symbol;
declare const newRequest: (incoming: IncomingMessage | Http2ServerRequest, defaultHostname?: string) => any;
export { GlobalRequest, type IncomingMessageWithWrapBodyStream, Request, RequestError, abortControllerKey, getAbortController, newRequest, toRequestError, wrapBodyStream };

25
node_modules/@hono/node-server/dist/request.d.ts generated vendored Normal file
View File

@@ -0,0 +1,25 @@
import { IncomingMessage } from 'node:http';
import { Http2ServerRequest } from 'node:http2';
declare class RequestError extends Error {
constructor(message: string, options?: {
cause?: unknown;
});
}
declare const toRequestError: (e: unknown) => RequestError;
declare const GlobalRequest: {
new (input: RequestInfo | URL, init?: RequestInit): globalThis.Request;
prototype: globalThis.Request;
};
declare class Request extends GlobalRequest {
constructor(input: string | Request, options?: RequestInit);
}
type IncomingMessageWithWrapBodyStream = IncomingMessage & {
[wrapBodyStream]: boolean;
};
declare const wrapBodyStream: unique symbol;
declare const abortControllerKey: unique symbol;
declare const getAbortController: unique symbol;
declare const newRequest: (incoming: IncomingMessage | Http2ServerRequest, defaultHostname?: string) => any;
export { GlobalRequest, type IncomingMessageWithWrapBodyStream, Request, RequestError, abortControllerKey, getAbortController, newRequest, toRequestError, wrapBodyStream };

238
node_modules/@hono/node-server/dist/request.js generated vendored Normal file
View File

@@ -0,0 +1,238 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/request.ts
var request_exports = {};
__export(request_exports, {
GlobalRequest: () => GlobalRequest,
Request: () => Request,
RequestError: () => RequestError,
abortControllerKey: () => abortControllerKey,
getAbortController: () => getAbortController,
newRequest: () => newRequest,
toRequestError: () => toRequestError,
wrapBodyStream: () => wrapBodyStream
});
module.exports = __toCommonJS(request_exports);
var import_node_http2 = require("http2");
var import_node_stream = require("stream");
var RequestError = class extends Error {
constructor(message, options) {
super(message, options);
this.name = "RequestError";
}
};
var toRequestError = (e) => {
if (e instanceof RequestError) {
return e;
}
return new RequestError(e.message, { cause: e });
};
var GlobalRequest = global.Request;
var Request = class extends GlobalRequest {
constructor(input, options) {
if (typeof input === "object" && getRequestCache in input) {
input = input[getRequestCache]();
}
if (typeof options?.body?.getReader !== "undefined") {
;
options.duplex ??= "half";
}
super(input, options);
}
};
var newHeadersFromIncoming = (incoming) => {
const headerRecord = [];
const rawHeaders = incoming.rawHeaders;
for (let i = 0; i < rawHeaders.length; i += 2) {
const { [i]: key, [i + 1]: value } = rawHeaders;
if (key.charCodeAt(0) !== /*:*/
58) {
headerRecord.push([key, value]);
}
}
return new Headers(headerRecord);
};
var wrapBodyStream = Symbol("wrapBodyStream");
var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
const init = {
method,
headers,
signal: abortController.signal
};
if (method === "TRACE") {
init.method = "GET";
const req = new Request(url, init);
Object.defineProperty(req, "method", {
get() {
return "TRACE";
}
});
return req;
}
if (!(method === "GET" || method === "HEAD")) {
if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
init.body = new ReadableStream({
start(controller) {
controller.enqueue(incoming.rawBody);
controller.close();
}
});
} else if (incoming[wrapBodyStream]) {
let reader;
init.body = new ReadableStream({
async pull(controller) {
try {
reader ||= import_node_stream.Readable.toWeb(incoming).getReader();
const { done, value } = await reader.read();
if (done) {
controller.close();
} else {
controller.enqueue(value);
}
} catch (error) {
controller.error(error);
}
}
});
} else {
init.body = import_node_stream.Readable.toWeb(incoming);
}
}
return new Request(url, init);
};
var getRequestCache = Symbol("getRequestCache");
var requestCache = Symbol("requestCache");
var incomingKey = Symbol("incomingKey");
var urlKey = Symbol("urlKey");
var headersKey = Symbol("headersKey");
var abortControllerKey = Symbol("abortControllerKey");
var getAbortController = Symbol("getAbortController");
var requestPrototype = {
get method() {
return this[incomingKey].method || "GET";
},
get url() {
return this[urlKey];
},
get headers() {
return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
},
[getAbortController]() {
this[getRequestCache]();
return this[abortControllerKey];
},
[getRequestCache]() {
this[abortControllerKey] ||= new AbortController();
return this[requestCache] ||= newRequestFromIncoming(
this.method,
this[urlKey],
this.headers,
this[incomingKey],
this[abortControllerKey]
);
}
};
[
"body",
"bodyUsed",
"cache",
"credentials",
"destination",
"integrity",
"mode",
"redirect",
"referrer",
"referrerPolicy",
"signal",
"keepalive"
].forEach((k) => {
Object.defineProperty(requestPrototype, k, {
get() {
return this[getRequestCache]()[k];
}
});
});
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
Object.defineProperty(requestPrototype, k, {
value: function() {
return this[getRequestCache]()[k]();
}
});
});
Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), {
value: function(depth, options, inspectFn) {
const props = {
method: this.method,
url: this.url,
headers: this.headers,
nativeRequest: this[requestCache]
};
return `Request (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
}
});
Object.setPrototypeOf(requestPrototype, Request.prototype);
var newRequest = (incoming, defaultHostname) => {
const req = Object.create(requestPrototype);
req[incomingKey] = incoming;
const incomingUrl = incoming.url || "";
if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
(incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
if (incoming instanceof import_node_http2.Http2ServerRequest) {
throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
}
try {
const url2 = new URL(incomingUrl);
req[urlKey] = url2.href;
} catch (e) {
throw new RequestError("Invalid absolute URL", { cause: e });
}
return req;
}
const host = (incoming instanceof import_node_http2.Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
if (!host) {
throw new RequestError("Missing host header");
}
let scheme;
if (incoming instanceof import_node_http2.Http2ServerRequest) {
scheme = incoming.scheme;
if (!(scheme === "http" || scheme === "https")) {
throw new RequestError("Unsupported scheme");
}
} else {
scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
}
const url = new URL(`${scheme}://${host}${incomingUrl}`);
if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
throw new RequestError("Invalid host header");
}
req[urlKey] = url.href;
return req;
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
GlobalRequest,
Request,
RequestError,
abortControllerKey,
getAbortController,
newRequest,
toRequestError,
wrapBodyStream
});

206
node_modules/@hono/node-server/dist/request.mjs generated vendored Normal file
View File

@@ -0,0 +1,206 @@
// src/request.ts
import { Http2ServerRequest } from "http2";
import { Readable } from "stream";
var RequestError = class extends Error {
constructor(message, options) {
super(message, options);
this.name = "RequestError";
}
};
var toRequestError = (e) => {
if (e instanceof RequestError) {
return e;
}
return new RequestError(e.message, { cause: e });
};
var GlobalRequest = global.Request;
var Request = class extends GlobalRequest {
constructor(input, options) {
if (typeof input === "object" && getRequestCache in input) {
input = input[getRequestCache]();
}
if (typeof options?.body?.getReader !== "undefined") {
;
options.duplex ??= "half";
}
super(input, options);
}
};
var newHeadersFromIncoming = (incoming) => {
const headerRecord = [];
const rawHeaders = incoming.rawHeaders;
for (let i = 0; i < rawHeaders.length; i += 2) {
const { [i]: key, [i + 1]: value } = rawHeaders;
if (key.charCodeAt(0) !== /*:*/
58) {
headerRecord.push([key, value]);
}
}
return new Headers(headerRecord);
};
var wrapBodyStream = Symbol("wrapBodyStream");
var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
const init = {
method,
headers,
signal: abortController.signal
};
if (method === "TRACE") {
init.method = "GET";
const req = new Request(url, init);
Object.defineProperty(req, "method", {
get() {
return "TRACE";
}
});
return req;
}
if (!(method === "GET" || method === "HEAD")) {
if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
init.body = new ReadableStream({
start(controller) {
controller.enqueue(incoming.rawBody);
controller.close();
}
});
} else if (incoming[wrapBodyStream]) {
let reader;
init.body = new ReadableStream({
async pull(controller) {
try {
reader ||= Readable.toWeb(incoming).getReader();
const { done, value } = await reader.read();
if (done) {
controller.close();
} else {
controller.enqueue(value);
}
} catch (error) {
controller.error(error);
}
}
});
} else {
init.body = Readable.toWeb(incoming);
}
}
return new Request(url, init);
};
var getRequestCache = Symbol("getRequestCache");
var requestCache = Symbol("requestCache");
var incomingKey = Symbol("incomingKey");
var urlKey = Symbol("urlKey");
var headersKey = Symbol("headersKey");
var abortControllerKey = Symbol("abortControllerKey");
var getAbortController = Symbol("getAbortController");
var requestPrototype = {
get method() {
return this[incomingKey].method || "GET";
},
get url() {
return this[urlKey];
},
get headers() {
return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
},
[getAbortController]() {
this[getRequestCache]();
return this[abortControllerKey];
},
[getRequestCache]() {
this[abortControllerKey] ||= new AbortController();
return this[requestCache] ||= newRequestFromIncoming(
this.method,
this[urlKey],
this.headers,
this[incomingKey],
this[abortControllerKey]
);
}
};
[
"body",
"bodyUsed",
"cache",
"credentials",
"destination",
"integrity",
"mode",
"redirect",
"referrer",
"referrerPolicy",
"signal",
"keepalive"
].forEach((k) => {
Object.defineProperty(requestPrototype, k, {
get() {
return this[getRequestCache]()[k];
}
});
});
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
Object.defineProperty(requestPrototype, k, {
value: function() {
return this[getRequestCache]()[k]();
}
});
});
Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), {
value: function(depth, options, inspectFn) {
const props = {
method: this.method,
url: this.url,
headers: this.headers,
nativeRequest: this[requestCache]
};
return `Request (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
}
});
Object.setPrototypeOf(requestPrototype, Request.prototype);
var newRequest = (incoming, defaultHostname) => {
const req = Object.create(requestPrototype);
req[incomingKey] = incoming;
const incomingUrl = incoming.url || "";
if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
(incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
if (incoming instanceof Http2ServerRequest) {
throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
}
try {
const url2 = new URL(incomingUrl);
req[urlKey] = url2.href;
} catch (e) {
throw new RequestError("Invalid absolute URL", { cause: e });
}
return req;
}
const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
if (!host) {
throw new RequestError("Missing host header");
}
let scheme;
if (incoming instanceof Http2ServerRequest) {
scheme = incoming.scheme;
if (!(scheme === "http" || scheme === "https")) {
throw new RequestError("Unsupported scheme");
}
} else {
scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
}
const url = new URL(`${scheme}://${host}${incomingUrl}`);
if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
throw new RequestError("Invalid host header");
}
req[urlKey] = url.href;
return req;
};
export {
GlobalRequest,
Request,
RequestError,
abortControllerKey,
getAbortController,
newRequest,
toRequestError,
wrapBodyStream
};

26
node_modules/@hono/node-server/dist/response.d.mts generated vendored Normal file
View File

@@ -0,0 +1,26 @@
import { OutgoingHttpHeaders } from 'node:http';
declare const getResponseCache: unique symbol;
declare const cacheKey: unique symbol;
type InternalCache = [
number,
string | ReadableStream,
Record<string, string> | [string, string][] | Headers | OutgoingHttpHeaders | undefined
];
declare const GlobalResponse: {
new (body?: BodyInit | null, init?: ResponseInit): globalThis.Response;
prototype: globalThis.Response;
error(): globalThis.Response;
json(data: any, init?: ResponseInit): globalThis.Response;
redirect(url: string | URL, status?: number): globalThis.Response;
};
declare class Response {
#private;
[getResponseCache](): globalThis.Response;
constructor(body?: BodyInit | null, init?: ResponseInit);
get headers(): Headers;
get status(): number;
get ok(): boolean;
}
export { GlobalResponse, type InternalCache, Response, cacheKey };

26
node_modules/@hono/node-server/dist/response.d.ts generated vendored Normal file
View File

@@ -0,0 +1,26 @@
import { OutgoingHttpHeaders } from 'node:http';
declare const getResponseCache: unique symbol;
declare const cacheKey: unique symbol;
type InternalCache = [
number,
string | ReadableStream,
Record<string, string> | [string, string][] | Headers | OutgoingHttpHeaders | undefined
];
declare const GlobalResponse: {
new (body?: BodyInit | null, init?: ResponseInit): globalThis.Response;
prototype: globalThis.Response;
error(): globalThis.Response;
json(data: any, init?: ResponseInit): globalThis.Response;
redirect(url: string | URL, status?: number): globalThis.Response;
};
declare class Response {
#private;
[getResponseCache](): globalThis.Response;
constructor(body?: BodyInit | null, init?: ResponseInit);
get headers(): Headers;
get status(): number;
get ok(): boolean;
}
export { GlobalResponse, type InternalCache, Response, cacheKey };

112
node_modules/@hono/node-server/dist/response.js generated vendored Normal file
View File

@@ -0,0 +1,112 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/response.ts
var response_exports = {};
__export(response_exports, {
GlobalResponse: () => GlobalResponse,
Response: () => Response,
cacheKey: () => cacheKey
});
module.exports = __toCommonJS(response_exports);
var responseCache = Symbol("responseCache");
var getResponseCache = Symbol("getResponseCache");
var cacheKey = Symbol("cache");
var GlobalResponse = global.Response;
var Response = class _Response {
#body;
#init;
[getResponseCache]() {
delete this[cacheKey];
return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
}
constructor(body, init) {
let headers;
this.#body = body;
if (init instanceof _Response) {
const cachedGlobalResponse = init[responseCache];
if (cachedGlobalResponse) {
this.#init = cachedGlobalResponse;
this[getResponseCache]();
return;
} else {
this.#init = init.#init;
headers = new Headers(init.#init.headers);
}
} else {
this.#init = init;
}
if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
;
this[cacheKey] = [init?.status || 200, body, headers || init?.headers];
}
}
get headers() {
const cache = this[cacheKey];
if (cache) {
if (!(cache[2] instanceof Headers)) {
cache[2] = new Headers(
cache[2] || { "content-type": "text/plain; charset=UTF-8" }
);
}
return cache[2];
}
return this[getResponseCache]().headers;
}
get status() {
return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
}
get ok() {
const status = this.status;
return status >= 200 && status < 300;
}
};
["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
Object.defineProperty(Response.prototype, k, {
get() {
return this[getResponseCache]()[k];
}
});
});
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
Object.defineProperty(Response.prototype, k, {
value: function() {
return this[getResponseCache]()[k]();
}
});
});
Object.defineProperty(Response.prototype, Symbol.for("nodejs.util.inspect.custom"), {
value: function(depth, options, inspectFn) {
const props = {
status: this.status,
headers: this.headers,
ok: this.ok,
nativeResponse: this[responseCache]
};
return `Response (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
}
});
Object.setPrototypeOf(Response, GlobalResponse);
Object.setPrototypeOf(Response.prototype, GlobalResponse.prototype);
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
GlobalResponse,
Response,
cacheKey
});

85
node_modules/@hono/node-server/dist/response.mjs generated vendored Normal file
View File

@@ -0,0 +1,85 @@
// src/response.ts
var responseCache = Symbol("responseCache");
var getResponseCache = Symbol("getResponseCache");
var cacheKey = Symbol("cache");
var GlobalResponse = global.Response;
var Response = class _Response {
#body;
#init;
[getResponseCache]() {
delete this[cacheKey];
return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
}
constructor(body, init) {
let headers;
this.#body = body;
if (init instanceof _Response) {
const cachedGlobalResponse = init[responseCache];
if (cachedGlobalResponse) {
this.#init = cachedGlobalResponse;
this[getResponseCache]();
return;
} else {
this.#init = init.#init;
headers = new Headers(init.#init.headers);
}
} else {
this.#init = init;
}
if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
;
this[cacheKey] = [init?.status || 200, body, headers || init?.headers];
}
}
get headers() {
const cache = this[cacheKey];
if (cache) {
if (!(cache[2] instanceof Headers)) {
cache[2] = new Headers(
cache[2] || { "content-type": "text/plain; charset=UTF-8" }
);
}
return cache[2];
}
return this[getResponseCache]().headers;
}
get status() {
return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
}
get ok() {
const status = this.status;
return status >= 200 && status < 300;
}
};
["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
Object.defineProperty(Response.prototype, k, {
get() {
return this[getResponseCache]()[k];
}
});
});
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
Object.defineProperty(Response.prototype, k, {
value: function() {
return this[getResponseCache]()[k]();
}
});
});
Object.defineProperty(Response.prototype, Symbol.for("nodejs.util.inspect.custom"), {
value: function(depth, options, inspectFn) {
const props = {
status: this.status,
headers: this.headers,
ok: this.ok,
nativeResponse: this[responseCache]
};
return `Response (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
}
});
Object.setPrototypeOf(Response, GlobalResponse);
Object.setPrototypeOf(Response.prototype, GlobalResponse.prototype);
export {
GlobalResponse,
Response,
cacheKey
};

17
node_modules/@hono/node-server/dist/serve-static.d.mts generated vendored Normal file
View File

@@ -0,0 +1,17 @@
import { Env, Context, MiddlewareHandler } from 'hono';
type ServeStaticOptions<E extends Env = Env> = {
/**
* Root path, relative to current working directory from which the app was started. Absolute paths are not supported.
*/
root?: string;
path?: string;
index?: string;
precompressed?: boolean;
rewriteRequestPath?: (path: string, c: Context<E>) => string;
onFound?: (path: string, c: Context<E>) => void | Promise<void>;
onNotFound?: (path: string, c: Context<E>) => void | Promise<void>;
};
declare const serveStatic: <E extends Env = any>(options?: ServeStaticOptions<E>) => MiddlewareHandler<E>;
export { type ServeStaticOptions, serveStatic };

17
node_modules/@hono/node-server/dist/serve-static.d.ts generated vendored Normal file
View File

@@ -0,0 +1,17 @@
import { Env, Context, MiddlewareHandler } from 'hono';
type ServeStaticOptions<E extends Env = Env> = {
/**
* Root path, relative to current working directory from which the app was started. Absolute paths are not supported.
*/
root?: string;
path?: string;
index?: string;
precompressed?: boolean;
rewriteRequestPath?: (path: string, c: Context<E>) => string;
onFound?: (path: string, c: Context<E>) => void | Promise<void>;
onNotFound?: (path: string, c: Context<E>) => void | Promise<void>;
};
declare const serveStatic: <E extends Env = any>(options?: ServeStaticOptions<E>) => MiddlewareHandler<E>;
export { type ServeStaticOptions, serveStatic };

177
node_modules/@hono/node-server/dist/serve-static.js generated vendored Normal file
View File

@@ -0,0 +1,177 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/serve-static.ts
var serve_static_exports = {};
__export(serve_static_exports, {
serveStatic: () => serveStatic
});
module.exports = __toCommonJS(serve_static_exports);
var import_mime = require("hono/utils/mime");
var import_node_fs = require("fs");
var import_node_path = require("path");
var import_node_process = require("process");
var import_node_stream = require("stream");
var COMPRESSIBLE_CONTENT_TYPE_REGEX = /^\s*(?:text\/[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i;
var ENCODINGS = {
br: ".br",
zstd: ".zst",
gzip: ".gz"
};
var ENCODINGS_ORDERED_KEYS = Object.keys(ENCODINGS);
var pr54206Applied = () => {
const [major, minor] = import_node_process.versions.node.split(".").map((component) => parseInt(component));
return major >= 23 || major === 22 && minor >= 7 || major === 20 && minor >= 18;
};
var useReadableToWeb = pr54206Applied();
var createStreamBody = (stream) => {
if (useReadableToWeb) {
return import_node_stream.Readable.toWeb(stream);
}
const body = new ReadableStream({
start(controller) {
stream.on("data", (chunk) => {
controller.enqueue(chunk);
});
stream.on("error", (err) => {
controller.error(err);
});
stream.on("end", () => {
controller.close();
});
},
cancel() {
stream.destroy();
}
});
return body;
};
var getStats = (path) => {
let stats;
try {
stats = (0, import_node_fs.statSync)(path);
} catch {
}
return stats;
};
var tryDecode = (str, decoder) => {
try {
return decoder(str);
} catch {
return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {
try {
return decoder(match);
} catch {
return match;
}
});
}
};
var tryDecodeURI = (str) => tryDecode(str, decodeURI);
var serveStatic = (options = { root: "" }) => {
const root = options.root || "";
const optionPath = options.path;
if (root !== "" && !(0, import_node_fs.existsSync)(root)) {
console.error(`serveStatic: root path '${root}' is not found, are you sure it's correct?`);
}
return async (c, next) => {
if (c.finalized) {
return next();
}
let filename;
if (optionPath) {
filename = optionPath;
} else {
try {
filename = tryDecodeURI(c.req.path);
if (/(?:^|[\/\\])\.{1,2}(?:$|[\/\\])|[\/\\]{2,}/.test(filename)) {
throw new Error();
}
} catch {
await options.onNotFound?.(c.req.path, c);
return next();
}
}
let path = (0, import_node_path.join)(
root,
!optionPath && options.rewriteRequestPath ? options.rewriteRequestPath(filename, c) : filename
);
let stats = getStats(path);
if (stats && stats.isDirectory()) {
const indexFile = options.index ?? "index.html";
path = (0, import_node_path.join)(path, indexFile);
stats = getStats(path);
}
if (!stats) {
await options.onNotFound?.(path, c);
return next();
}
const mimeType = (0, import_mime.getMimeType)(path);
c.header("Content-Type", mimeType || "application/octet-stream");
if (options.precompressed && (!mimeType || COMPRESSIBLE_CONTENT_TYPE_REGEX.test(mimeType))) {
const acceptEncodingSet = new Set(
c.req.header("Accept-Encoding")?.split(",").map((encoding) => encoding.trim())
);
for (const encoding of ENCODINGS_ORDERED_KEYS) {
if (!acceptEncodingSet.has(encoding)) {
continue;
}
const precompressedStats = getStats(path + ENCODINGS[encoding]);
if (precompressedStats) {
c.header("Content-Encoding", encoding);
c.header("Vary", "Accept-Encoding", { append: true });
stats = precompressedStats;
path = path + ENCODINGS[encoding];
break;
}
}
}
let result;
const size = stats.size;
const range = c.req.header("range") || "";
if (c.req.method == "HEAD" || c.req.method == "OPTIONS") {
c.header("Content-Length", size.toString());
c.status(200);
result = c.body(null);
} else if (!range) {
c.header("Content-Length", size.toString());
result = c.body(createStreamBody((0, import_node_fs.createReadStream)(path)), 200);
} else {
c.header("Accept-Ranges", "bytes");
c.header("Date", stats.birthtime.toUTCString());
const parts = range.replace(/bytes=/, "").split("-", 2);
const start = parseInt(parts[0], 10) || 0;
let end = parseInt(parts[1], 10) || size - 1;
if (size < end - start + 1) {
end = size - 1;
}
const chunksize = end - start + 1;
const stream = (0, import_node_fs.createReadStream)(path, { start, end });
c.header("Content-Length", chunksize.toString());
c.header("Content-Range", `bytes ${start}-${end}/${stats.size}`);
result = c.body(createStreamBody(stream), 206);
}
await options.onFound?.(path, c);
return result;
};
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
serveStatic
});

152
node_modules/@hono/node-server/dist/serve-static.mjs generated vendored Normal file
View File

@@ -0,0 +1,152 @@
// src/serve-static.ts
import { getMimeType } from "hono/utils/mime";
import { createReadStream, statSync, existsSync } from "fs";
import { join } from "path";
import { versions } from "process";
import { Readable } from "stream";
var COMPRESSIBLE_CONTENT_TYPE_REGEX = /^\s*(?:text\/[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i;
var ENCODINGS = {
br: ".br",
zstd: ".zst",
gzip: ".gz"
};
var ENCODINGS_ORDERED_KEYS = Object.keys(ENCODINGS);
var pr54206Applied = () => {
const [major, minor] = versions.node.split(".").map((component) => parseInt(component));
return major >= 23 || major === 22 && minor >= 7 || major === 20 && minor >= 18;
};
var useReadableToWeb = pr54206Applied();
var createStreamBody = (stream) => {
if (useReadableToWeb) {
return Readable.toWeb(stream);
}
const body = new ReadableStream({
start(controller) {
stream.on("data", (chunk) => {
controller.enqueue(chunk);
});
stream.on("error", (err) => {
controller.error(err);
});
stream.on("end", () => {
controller.close();
});
},
cancel() {
stream.destroy();
}
});
return body;
};
var getStats = (path) => {
let stats;
try {
stats = statSync(path);
} catch {
}
return stats;
};
var tryDecode = (str, decoder) => {
try {
return decoder(str);
} catch {
return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {
try {
return decoder(match);
} catch {
return match;
}
});
}
};
var tryDecodeURI = (str) => tryDecode(str, decodeURI);
var serveStatic = (options = { root: "" }) => {
const root = options.root || "";
const optionPath = options.path;
if (root !== "" && !existsSync(root)) {
console.error(`serveStatic: root path '${root}' is not found, are you sure it's correct?`);
}
return async (c, next) => {
if (c.finalized) {
return next();
}
let filename;
if (optionPath) {
filename = optionPath;
} else {
try {
filename = tryDecodeURI(c.req.path);
if (/(?:^|[\/\\])\.{1,2}(?:$|[\/\\])|[\/\\]{2,}/.test(filename)) {
throw new Error();
}
} catch {
await options.onNotFound?.(c.req.path, c);
return next();
}
}
let path = join(
root,
!optionPath && options.rewriteRequestPath ? options.rewriteRequestPath(filename, c) : filename
);
let stats = getStats(path);
if (stats && stats.isDirectory()) {
const indexFile = options.index ?? "index.html";
path = join(path, indexFile);
stats = getStats(path);
}
if (!stats) {
await options.onNotFound?.(path, c);
return next();
}
const mimeType = getMimeType(path);
c.header("Content-Type", mimeType || "application/octet-stream");
if (options.precompressed && (!mimeType || COMPRESSIBLE_CONTENT_TYPE_REGEX.test(mimeType))) {
const acceptEncodingSet = new Set(
c.req.header("Accept-Encoding")?.split(",").map((encoding) => encoding.trim())
);
for (const encoding of ENCODINGS_ORDERED_KEYS) {
if (!acceptEncodingSet.has(encoding)) {
continue;
}
const precompressedStats = getStats(path + ENCODINGS[encoding]);
if (precompressedStats) {
c.header("Content-Encoding", encoding);
c.header("Vary", "Accept-Encoding", { append: true });
stats = precompressedStats;
path = path + ENCODINGS[encoding];
break;
}
}
}
let result;
const size = stats.size;
const range = c.req.header("range") || "";
if (c.req.method == "HEAD" || c.req.method == "OPTIONS") {
c.header("Content-Length", size.toString());
c.status(200);
result = c.body(null);
} else if (!range) {
c.header("Content-Length", size.toString());
result = c.body(createStreamBody(createReadStream(path)), 200);
} else {
c.header("Accept-Ranges", "bytes");
c.header("Date", stats.birthtime.toUTCString());
const parts = range.replace(/bytes=/, "").split("-", 2);
const start = parseInt(parts[0], 10) || 0;
let end = parseInt(parts[1], 10) || size - 1;
if (size < end - start + 1) {
end = size - 1;
}
const chunksize = end - start + 1;
const stream = createReadStream(path, { start, end });
c.header("Content-Length", chunksize.toString());
c.header("Content-Range", `bytes ${start}-${end}/${stats.size}`);
result = c.body(createStreamBody(stream), 206);
}
await options.onFound?.(path, c);
return result;
};
};
export {
serveStatic
};

10
node_modules/@hono/node-server/dist/server.d.mts generated vendored Normal file
View File

@@ -0,0 +1,10 @@
import { AddressInfo } from 'node:net';
import { Options, ServerType } from './types.mjs';
import 'node:http';
import 'node:http2';
import 'node:https';
declare const createAdaptorServer: (options: Options) => ServerType;
declare const serve: (options: Options, listeningListener?: (info: AddressInfo) => void) => ServerType;
export { createAdaptorServer, serve };

10
node_modules/@hono/node-server/dist/server.d.ts generated vendored Normal file
View File

@@ -0,0 +1,10 @@
import { AddressInfo } from 'node:net';
import { Options, ServerType } from './types.js';
import 'node:http';
import 'node:http2';
import 'node:https';
declare const createAdaptorServer: (options: Options) => ServerType;
declare const serve: (options: Options, listeningListener?: (info: AddressInfo) => void) => ServerType;
export { createAdaptorServer, serve };

696
node_modules/@hono/node-server/dist/server.js generated vendored Normal file
View File

@@ -0,0 +1,696 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/server.ts
var server_exports = {};
__export(server_exports, {
createAdaptorServer: () => createAdaptorServer,
serve: () => serve
});
module.exports = __toCommonJS(server_exports);
var import_node_http = require("http");
// src/listener.ts
var import_node_http22 = require("http2");
// src/request.ts
var import_node_http2 = require("http2");
var import_node_stream = require("stream");
var RequestError = class extends Error {
constructor(message, options) {
super(message, options);
this.name = "RequestError";
}
};
var toRequestError = (e) => {
if (e instanceof RequestError) {
return e;
}
return new RequestError(e.message, { cause: e });
};
var GlobalRequest = global.Request;
var Request = class extends GlobalRequest {
constructor(input, options) {
if (typeof input === "object" && getRequestCache in input) {
input = input[getRequestCache]();
}
if (typeof options?.body?.getReader !== "undefined") {
;
options.duplex ??= "half";
}
super(input, options);
}
};
var newHeadersFromIncoming = (incoming) => {
const headerRecord = [];
const rawHeaders = incoming.rawHeaders;
for (let i = 0; i < rawHeaders.length; i += 2) {
const { [i]: key, [i + 1]: value } = rawHeaders;
if (key.charCodeAt(0) !== /*:*/
58) {
headerRecord.push([key, value]);
}
}
return new Headers(headerRecord);
};
var wrapBodyStream = Symbol("wrapBodyStream");
var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
const init = {
method,
headers,
signal: abortController.signal
};
if (method === "TRACE") {
init.method = "GET";
const req = new Request(url, init);
Object.defineProperty(req, "method", {
get() {
return "TRACE";
}
});
return req;
}
if (!(method === "GET" || method === "HEAD")) {
if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
init.body = new ReadableStream({
start(controller) {
controller.enqueue(incoming.rawBody);
controller.close();
}
});
} else if (incoming[wrapBodyStream]) {
let reader;
init.body = new ReadableStream({
async pull(controller) {
try {
reader ||= import_node_stream.Readable.toWeb(incoming).getReader();
const { done, value } = await reader.read();
if (done) {
controller.close();
} else {
controller.enqueue(value);
}
} catch (error) {
controller.error(error);
}
}
});
} else {
init.body = import_node_stream.Readable.toWeb(incoming);
}
}
return new Request(url, init);
};
var getRequestCache = Symbol("getRequestCache");
var requestCache = Symbol("requestCache");
var incomingKey = Symbol("incomingKey");
var urlKey = Symbol("urlKey");
var headersKey = Symbol("headersKey");
var abortControllerKey = Symbol("abortControllerKey");
var getAbortController = Symbol("getAbortController");
var requestPrototype = {
get method() {
return this[incomingKey].method || "GET";
},
get url() {
return this[urlKey];
},
get headers() {
return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
},
[getAbortController]() {
this[getRequestCache]();
return this[abortControllerKey];
},
[getRequestCache]() {
this[abortControllerKey] ||= new AbortController();
return this[requestCache] ||= newRequestFromIncoming(
this.method,
this[urlKey],
this.headers,
this[incomingKey],
this[abortControllerKey]
);
}
};
[
"body",
"bodyUsed",
"cache",
"credentials",
"destination",
"integrity",
"mode",
"redirect",
"referrer",
"referrerPolicy",
"signal",
"keepalive"
].forEach((k) => {
Object.defineProperty(requestPrototype, k, {
get() {
return this[getRequestCache]()[k];
}
});
});
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
Object.defineProperty(requestPrototype, k, {
value: function() {
return this[getRequestCache]()[k]();
}
});
});
Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), {
value: function(depth, options, inspectFn) {
const props = {
method: this.method,
url: this.url,
headers: this.headers,
nativeRequest: this[requestCache]
};
return `Request (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
}
});
Object.setPrototypeOf(requestPrototype, Request.prototype);
var newRequest = (incoming, defaultHostname) => {
const req = Object.create(requestPrototype);
req[incomingKey] = incoming;
const incomingUrl = incoming.url || "";
if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
(incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
if (incoming instanceof import_node_http2.Http2ServerRequest) {
throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
}
try {
const url2 = new URL(incomingUrl);
req[urlKey] = url2.href;
} catch (e) {
throw new RequestError("Invalid absolute URL", { cause: e });
}
return req;
}
const host = (incoming instanceof import_node_http2.Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
if (!host) {
throw new RequestError("Missing host header");
}
let scheme;
if (incoming instanceof import_node_http2.Http2ServerRequest) {
scheme = incoming.scheme;
if (!(scheme === "http" || scheme === "https")) {
throw new RequestError("Unsupported scheme");
}
} else {
scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
}
const url = new URL(`${scheme}://${host}${incomingUrl}`);
if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
throw new RequestError("Invalid host header");
}
req[urlKey] = url.href;
return req;
};
// src/response.ts
var responseCache = Symbol("responseCache");
var getResponseCache = Symbol("getResponseCache");
var cacheKey = Symbol("cache");
var GlobalResponse = global.Response;
var Response2 = class _Response {
#body;
#init;
[getResponseCache]() {
delete this[cacheKey];
return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
}
constructor(body, init) {
let headers;
this.#body = body;
if (init instanceof _Response) {
const cachedGlobalResponse = init[responseCache];
if (cachedGlobalResponse) {
this.#init = cachedGlobalResponse;
this[getResponseCache]();
return;
} else {
this.#init = init.#init;
headers = new Headers(init.#init.headers);
}
} else {
this.#init = init;
}
if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
;
this[cacheKey] = [init?.status || 200, body, headers || init?.headers];
}
}
get headers() {
const cache = this[cacheKey];
if (cache) {
if (!(cache[2] instanceof Headers)) {
cache[2] = new Headers(
cache[2] || { "content-type": "text/plain; charset=UTF-8" }
);
}
return cache[2];
}
return this[getResponseCache]().headers;
}
get status() {
return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
}
get ok() {
const status = this.status;
return status >= 200 && status < 300;
}
};
["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
Object.defineProperty(Response2.prototype, k, {
get() {
return this[getResponseCache]()[k];
}
});
});
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
Object.defineProperty(Response2.prototype, k, {
value: function() {
return this[getResponseCache]()[k]();
}
});
});
Object.defineProperty(Response2.prototype, Symbol.for("nodejs.util.inspect.custom"), {
value: function(depth, options, inspectFn) {
const props = {
status: this.status,
headers: this.headers,
ok: this.ok,
nativeResponse: this[responseCache]
};
return `Response (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
}
});
Object.setPrototypeOf(Response2, GlobalResponse);
Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
// src/utils.ts
async function readWithoutBlocking(readPromise) {
return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
}
function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
const cancel = (error) => {
reader.cancel(error).catch(() => {
});
};
writable.on("close", cancel);
writable.on("error", cancel);
(currentReadPromise ?? reader.read()).then(flow, handleStreamError);
return reader.closed.finally(() => {
writable.off("close", cancel);
writable.off("error", cancel);
});
function handleStreamError(error) {
if (error) {
writable.destroy(error);
}
}
function onDrain() {
reader.read().then(flow, handleStreamError);
}
function flow({ done, value }) {
try {
if (done) {
writable.end();
} else if (!writable.write(value)) {
writable.once("drain", onDrain);
} else {
return reader.read().then(flow, handleStreamError);
}
} catch (e) {
handleStreamError(e);
}
}
}
function writeFromReadableStream(stream, writable) {
if (stream.locked) {
throw new TypeError("ReadableStream is locked.");
} else if (writable.destroyed) {
return;
}
return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
}
var buildOutgoingHttpHeaders = (headers) => {
const res = {};
if (!(headers instanceof Headers)) {
headers = new Headers(headers ?? void 0);
}
const cookies = [];
for (const [k, v] of headers) {
if (k === "set-cookie") {
cookies.push(v);
} else {
res[k] = v;
}
}
if (cookies.length > 0) {
res["set-cookie"] = cookies;
}
res["content-type"] ??= "text/plain; charset=UTF-8";
return res;
};
// src/utils/response/constants.ts
var X_ALREADY_SENT = "x-hono-already-sent";
// src/globals.ts
var import_node_crypto = __toESM(require("crypto"));
if (typeof global.crypto === "undefined") {
global.crypto = import_node_crypto.default;
}
// src/listener.ts
var outgoingEnded = Symbol("outgoingEnded");
var incomingDraining = Symbol("incomingDraining");
var DRAIN_TIMEOUT_MS = 500;
var MAX_DRAIN_BYTES = 64 * 1024 * 1024;
var drainIncoming = (incoming) => {
const incomingWithDrainState = incoming;
if (incoming.destroyed || incomingWithDrainState[incomingDraining]) {
return;
}
incomingWithDrainState[incomingDraining] = true;
if (incoming instanceof import_node_http22.Http2ServerRequest) {
try {
;
incoming.stream?.close?.(import_node_http22.constants.NGHTTP2_NO_ERROR);
} catch {
}
return;
}
let bytesRead = 0;
const cleanup = () => {
clearTimeout(timer);
incoming.off("data", onData);
incoming.off("end", cleanup);
incoming.off("error", cleanup);
};
const forceClose = () => {
cleanup();
const socket = incoming.socket;
if (socket && !socket.destroyed) {
socket.destroySoon();
}
};
const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
timer.unref?.();
const onData = (chunk) => {
bytesRead += chunk.length;
if (bytesRead > MAX_DRAIN_BYTES) {
forceClose();
}
};
incoming.on("data", onData);
incoming.on("end", cleanup);
incoming.on("error", cleanup);
incoming.resume();
};
var handleRequestError = () => new Response(null, {
status: 400
});
var handleFetchError = (e) => new Response(null, {
status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
});
var handleResponseError = (e, outgoing) => {
const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
console.info("The user aborted a request.");
} else {
console.error(e);
if (!outgoing.headersSent) {
outgoing.writeHead(500, { "Content-Type": "text/plain" });
}
outgoing.end(`Error: ${err.message}`);
outgoing.destroy(err);
}
};
var flushHeaders = (outgoing) => {
if ("flushHeaders" in outgoing && outgoing.writable) {
outgoing.flushHeaders();
}
};
var responseViaCache = async (res, outgoing) => {
let [status, body, header] = res[cacheKey];
let hasContentLength = false;
if (!header) {
header = { "content-type": "text/plain; charset=UTF-8" };
} else if (header instanceof Headers) {
hasContentLength = header.has("content-length");
header = buildOutgoingHttpHeaders(header);
} else if (Array.isArray(header)) {
const headerObj = new Headers(header);
hasContentLength = headerObj.has("content-length");
header = buildOutgoingHttpHeaders(headerObj);
} else {
for (const key in header) {
if (key.length === 14 && key.toLowerCase() === "content-length") {
hasContentLength = true;
break;
}
}
}
if (!hasContentLength) {
if (typeof body === "string") {
header["Content-Length"] = Buffer.byteLength(body);
} else if (body instanceof Uint8Array) {
header["Content-Length"] = body.byteLength;
} else if (body instanceof Blob) {
header["Content-Length"] = body.size;
}
}
outgoing.writeHead(status, header);
if (typeof body === "string" || body instanceof Uint8Array) {
outgoing.end(body);
} else if (body instanceof Blob) {
outgoing.end(new Uint8Array(await body.arrayBuffer()));
} else {
flushHeaders(outgoing);
await writeFromReadableStream(body, outgoing)?.catch(
(e) => handleResponseError(e, outgoing)
);
}
;
outgoing[outgoingEnded]?.();
};
var isPromise = (res) => typeof res.then === "function";
var responseViaResponseObject = async (res, outgoing, options = {}) => {
if (isPromise(res)) {
if (options.errorHandler) {
try {
res = await res;
} catch (err) {
const errRes = await options.errorHandler(err);
if (!errRes) {
return;
}
res = errRes;
}
} else {
res = await res.catch(handleFetchError);
}
}
if (cacheKey in res) {
return responseViaCache(res, outgoing);
}
const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
if (res.body) {
const reader = res.body.getReader();
const values = [];
let done = false;
let currentReadPromise = void 0;
if (resHeaderRecord["transfer-encoding"] !== "chunked") {
let maxReadCount = 2;
for (let i = 0; i < maxReadCount; i++) {
currentReadPromise ||= reader.read();
const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
console.error(e);
done = true;
});
if (!chunk) {
if (i === 1) {
await new Promise((resolve) => setTimeout(resolve));
maxReadCount = 3;
continue;
}
break;
}
currentReadPromise = void 0;
if (chunk.value) {
values.push(chunk.value);
}
if (chunk.done) {
done = true;
break;
}
}
if (done && !("content-length" in resHeaderRecord)) {
resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
}
}
outgoing.writeHead(res.status, resHeaderRecord);
values.forEach((value) => {
;
outgoing.write(value);
});
if (done) {
outgoing.end();
} else {
if (values.length === 0) {
flushHeaders(outgoing);
}
await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
}
} else if (resHeaderRecord[X_ALREADY_SENT]) {
} else {
outgoing.writeHead(res.status, resHeaderRecord);
outgoing.end();
}
;
outgoing[outgoingEnded]?.();
};
var getRequestListener = (fetchCallback, options = {}) => {
const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
if (options.overrideGlobalObjects !== false && global.Request !== Request) {
Object.defineProperty(global, "Request", {
value: Request
});
Object.defineProperty(global, "Response", {
value: Response2
});
}
return async (incoming, outgoing) => {
let res, req;
try {
req = newRequest(incoming, options.hostname);
let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
if (!incomingEnded) {
;
incoming[wrapBodyStream] = true;
incoming.on("end", () => {
incomingEnded = true;
});
if (incoming instanceof import_node_http22.Http2ServerRequest) {
;
outgoing[outgoingEnded] = () => {
if (!incomingEnded) {
setTimeout(() => {
if (!incomingEnded) {
setTimeout(() => {
drainIncoming(incoming);
});
}
});
}
};
}
outgoing.on("finish", () => {
if (!incomingEnded) {
drainIncoming(incoming);
}
});
}
outgoing.on("close", () => {
const abortController = req[abortControllerKey];
if (abortController) {
if (incoming.errored) {
req[abortControllerKey].abort(incoming.errored.toString());
} else if (!outgoing.writableFinished) {
req[abortControllerKey].abort("Client connection prematurely closed.");
}
}
if (!incomingEnded) {
setTimeout(() => {
if (!incomingEnded) {
setTimeout(() => {
drainIncoming(incoming);
});
}
});
}
});
res = fetchCallback(req, { incoming, outgoing });
if (cacheKey in res) {
return responseViaCache(res, outgoing);
}
} catch (e) {
if (!res) {
if (options.errorHandler) {
res = await options.errorHandler(req ? e : toRequestError(e));
if (!res) {
return;
}
} else if (!req) {
res = handleRequestError();
} else {
res = handleFetchError(e);
}
} else {
return handleResponseError(e, outgoing);
}
}
try {
return await responseViaResponseObject(res, outgoing, options);
} catch (e) {
return handleResponseError(e, outgoing);
}
};
};
// src/server.ts
var createAdaptorServer = (options) => {
const fetchCallback = options.fetch;
const requestListener = getRequestListener(fetchCallback, {
hostname: options.hostname,
overrideGlobalObjects: options.overrideGlobalObjects,
autoCleanupIncoming: options.autoCleanupIncoming
});
const createServer = options.createServer || import_node_http.createServer;
const server = createServer(options.serverOptions || {}, requestListener);
return server;
};
var serve = (options, listeningListener) => {
const server = createAdaptorServer(options);
server.listen(options?.port ?? 3e3, options.hostname, () => {
const serverInfo = server.address();
listeningListener && listeningListener(serverInfo);
});
return server;
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
createAdaptorServer,
serve
});

660
node_modules/@hono/node-server/dist/server.mjs generated vendored Normal file
View File

@@ -0,0 +1,660 @@
// src/server.ts
import { createServer as createServerHTTP } from "http";
// src/listener.ts
import { Http2ServerRequest as Http2ServerRequest2, constants as h2constants } from "http2";
// src/request.ts
import { Http2ServerRequest } from "http2";
import { Readable } from "stream";
var RequestError = class extends Error {
constructor(message, options) {
super(message, options);
this.name = "RequestError";
}
};
var toRequestError = (e) => {
if (e instanceof RequestError) {
return e;
}
return new RequestError(e.message, { cause: e });
};
var GlobalRequest = global.Request;
var Request = class extends GlobalRequest {
constructor(input, options) {
if (typeof input === "object" && getRequestCache in input) {
input = input[getRequestCache]();
}
if (typeof options?.body?.getReader !== "undefined") {
;
options.duplex ??= "half";
}
super(input, options);
}
};
var newHeadersFromIncoming = (incoming) => {
const headerRecord = [];
const rawHeaders = incoming.rawHeaders;
for (let i = 0; i < rawHeaders.length; i += 2) {
const { [i]: key, [i + 1]: value } = rawHeaders;
if (key.charCodeAt(0) !== /*:*/
58) {
headerRecord.push([key, value]);
}
}
return new Headers(headerRecord);
};
var wrapBodyStream = Symbol("wrapBodyStream");
var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
const init = {
method,
headers,
signal: abortController.signal
};
if (method === "TRACE") {
init.method = "GET";
const req = new Request(url, init);
Object.defineProperty(req, "method", {
get() {
return "TRACE";
}
});
return req;
}
if (!(method === "GET" || method === "HEAD")) {
if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
init.body = new ReadableStream({
start(controller) {
controller.enqueue(incoming.rawBody);
controller.close();
}
});
} else if (incoming[wrapBodyStream]) {
let reader;
init.body = new ReadableStream({
async pull(controller) {
try {
reader ||= Readable.toWeb(incoming).getReader();
const { done, value } = await reader.read();
if (done) {
controller.close();
} else {
controller.enqueue(value);
}
} catch (error) {
controller.error(error);
}
}
});
} else {
init.body = Readable.toWeb(incoming);
}
}
return new Request(url, init);
};
var getRequestCache = Symbol("getRequestCache");
var requestCache = Symbol("requestCache");
var incomingKey = Symbol("incomingKey");
var urlKey = Symbol("urlKey");
var headersKey = Symbol("headersKey");
var abortControllerKey = Symbol("abortControllerKey");
var getAbortController = Symbol("getAbortController");
var requestPrototype = {
get method() {
return this[incomingKey].method || "GET";
},
get url() {
return this[urlKey];
},
get headers() {
return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
},
[getAbortController]() {
this[getRequestCache]();
return this[abortControllerKey];
},
[getRequestCache]() {
this[abortControllerKey] ||= new AbortController();
return this[requestCache] ||= newRequestFromIncoming(
this.method,
this[urlKey],
this.headers,
this[incomingKey],
this[abortControllerKey]
);
}
};
[
"body",
"bodyUsed",
"cache",
"credentials",
"destination",
"integrity",
"mode",
"redirect",
"referrer",
"referrerPolicy",
"signal",
"keepalive"
].forEach((k) => {
Object.defineProperty(requestPrototype, k, {
get() {
return this[getRequestCache]()[k];
}
});
});
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
Object.defineProperty(requestPrototype, k, {
value: function() {
return this[getRequestCache]()[k]();
}
});
});
Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), {
value: function(depth, options, inspectFn) {
const props = {
method: this.method,
url: this.url,
headers: this.headers,
nativeRequest: this[requestCache]
};
return `Request (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
}
});
Object.setPrototypeOf(requestPrototype, Request.prototype);
var newRequest = (incoming, defaultHostname) => {
const req = Object.create(requestPrototype);
req[incomingKey] = incoming;
const incomingUrl = incoming.url || "";
if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
(incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
if (incoming instanceof Http2ServerRequest) {
throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
}
try {
const url2 = new URL(incomingUrl);
req[urlKey] = url2.href;
} catch (e) {
throw new RequestError("Invalid absolute URL", { cause: e });
}
return req;
}
const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
if (!host) {
throw new RequestError("Missing host header");
}
let scheme;
if (incoming instanceof Http2ServerRequest) {
scheme = incoming.scheme;
if (!(scheme === "http" || scheme === "https")) {
throw new RequestError("Unsupported scheme");
}
} else {
scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
}
const url = new URL(`${scheme}://${host}${incomingUrl}`);
if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
throw new RequestError("Invalid host header");
}
req[urlKey] = url.href;
return req;
};
// src/response.ts
var responseCache = Symbol("responseCache");
var getResponseCache = Symbol("getResponseCache");
var cacheKey = Symbol("cache");
var GlobalResponse = global.Response;
var Response2 = class _Response {
#body;
#init;
[getResponseCache]() {
delete this[cacheKey];
return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
}
constructor(body, init) {
let headers;
this.#body = body;
if (init instanceof _Response) {
const cachedGlobalResponse = init[responseCache];
if (cachedGlobalResponse) {
this.#init = cachedGlobalResponse;
this[getResponseCache]();
return;
} else {
this.#init = init.#init;
headers = new Headers(init.#init.headers);
}
} else {
this.#init = init;
}
if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
;
this[cacheKey] = [init?.status || 200, body, headers || init?.headers];
}
}
get headers() {
const cache = this[cacheKey];
if (cache) {
if (!(cache[2] instanceof Headers)) {
cache[2] = new Headers(
cache[2] || { "content-type": "text/plain; charset=UTF-8" }
);
}
return cache[2];
}
return this[getResponseCache]().headers;
}
get status() {
return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
}
get ok() {
const status = this.status;
return status >= 200 && status < 300;
}
};
["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
Object.defineProperty(Response2.prototype, k, {
get() {
return this[getResponseCache]()[k];
}
});
});
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
Object.defineProperty(Response2.prototype, k, {
value: function() {
return this[getResponseCache]()[k]();
}
});
});
Object.defineProperty(Response2.prototype, Symbol.for("nodejs.util.inspect.custom"), {
value: function(depth, options, inspectFn) {
const props = {
status: this.status,
headers: this.headers,
ok: this.ok,
nativeResponse: this[responseCache]
};
return `Response (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
}
});
Object.setPrototypeOf(Response2, GlobalResponse);
Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
// src/utils.ts
async function readWithoutBlocking(readPromise) {
return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
}
function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
const cancel = (error) => {
reader.cancel(error).catch(() => {
});
};
writable.on("close", cancel);
writable.on("error", cancel);
(currentReadPromise ?? reader.read()).then(flow, handleStreamError);
return reader.closed.finally(() => {
writable.off("close", cancel);
writable.off("error", cancel);
});
function handleStreamError(error) {
if (error) {
writable.destroy(error);
}
}
function onDrain() {
reader.read().then(flow, handleStreamError);
}
function flow({ done, value }) {
try {
if (done) {
writable.end();
} else if (!writable.write(value)) {
writable.once("drain", onDrain);
} else {
return reader.read().then(flow, handleStreamError);
}
} catch (e) {
handleStreamError(e);
}
}
}
function writeFromReadableStream(stream, writable) {
if (stream.locked) {
throw new TypeError("ReadableStream is locked.");
} else if (writable.destroyed) {
return;
}
return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
}
var buildOutgoingHttpHeaders = (headers) => {
const res = {};
if (!(headers instanceof Headers)) {
headers = new Headers(headers ?? void 0);
}
const cookies = [];
for (const [k, v] of headers) {
if (k === "set-cookie") {
cookies.push(v);
} else {
res[k] = v;
}
}
if (cookies.length > 0) {
res["set-cookie"] = cookies;
}
res["content-type"] ??= "text/plain; charset=UTF-8";
return res;
};
// src/utils/response/constants.ts
var X_ALREADY_SENT = "x-hono-already-sent";
// src/globals.ts
import crypto from "crypto";
if (typeof global.crypto === "undefined") {
global.crypto = crypto;
}
// src/listener.ts
var outgoingEnded = Symbol("outgoingEnded");
var incomingDraining = Symbol("incomingDraining");
var DRAIN_TIMEOUT_MS = 500;
var MAX_DRAIN_BYTES = 64 * 1024 * 1024;
var drainIncoming = (incoming) => {
const incomingWithDrainState = incoming;
if (incoming.destroyed || incomingWithDrainState[incomingDraining]) {
return;
}
incomingWithDrainState[incomingDraining] = true;
if (incoming instanceof Http2ServerRequest2) {
try {
;
incoming.stream?.close?.(h2constants.NGHTTP2_NO_ERROR);
} catch {
}
return;
}
let bytesRead = 0;
const cleanup = () => {
clearTimeout(timer);
incoming.off("data", onData);
incoming.off("end", cleanup);
incoming.off("error", cleanup);
};
const forceClose = () => {
cleanup();
const socket = incoming.socket;
if (socket && !socket.destroyed) {
socket.destroySoon();
}
};
const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
timer.unref?.();
const onData = (chunk) => {
bytesRead += chunk.length;
if (bytesRead > MAX_DRAIN_BYTES) {
forceClose();
}
};
incoming.on("data", onData);
incoming.on("end", cleanup);
incoming.on("error", cleanup);
incoming.resume();
};
var handleRequestError = () => new Response(null, {
status: 400
});
var handleFetchError = (e) => new Response(null, {
status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
});
var handleResponseError = (e, outgoing) => {
const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
console.info("The user aborted a request.");
} else {
console.error(e);
if (!outgoing.headersSent) {
outgoing.writeHead(500, { "Content-Type": "text/plain" });
}
outgoing.end(`Error: ${err.message}`);
outgoing.destroy(err);
}
};
var flushHeaders = (outgoing) => {
if ("flushHeaders" in outgoing && outgoing.writable) {
outgoing.flushHeaders();
}
};
var responseViaCache = async (res, outgoing) => {
let [status, body, header] = res[cacheKey];
let hasContentLength = false;
if (!header) {
header = { "content-type": "text/plain; charset=UTF-8" };
} else if (header instanceof Headers) {
hasContentLength = header.has("content-length");
header = buildOutgoingHttpHeaders(header);
} else if (Array.isArray(header)) {
const headerObj = new Headers(header);
hasContentLength = headerObj.has("content-length");
header = buildOutgoingHttpHeaders(headerObj);
} else {
for (const key in header) {
if (key.length === 14 && key.toLowerCase() === "content-length") {
hasContentLength = true;
break;
}
}
}
if (!hasContentLength) {
if (typeof body === "string") {
header["Content-Length"] = Buffer.byteLength(body);
} else if (body instanceof Uint8Array) {
header["Content-Length"] = body.byteLength;
} else if (body instanceof Blob) {
header["Content-Length"] = body.size;
}
}
outgoing.writeHead(status, header);
if (typeof body === "string" || body instanceof Uint8Array) {
outgoing.end(body);
} else if (body instanceof Blob) {
outgoing.end(new Uint8Array(await body.arrayBuffer()));
} else {
flushHeaders(outgoing);
await writeFromReadableStream(body, outgoing)?.catch(
(e) => handleResponseError(e, outgoing)
);
}
;
outgoing[outgoingEnded]?.();
};
var isPromise = (res) => typeof res.then === "function";
var responseViaResponseObject = async (res, outgoing, options = {}) => {
if (isPromise(res)) {
if (options.errorHandler) {
try {
res = await res;
} catch (err) {
const errRes = await options.errorHandler(err);
if (!errRes) {
return;
}
res = errRes;
}
} else {
res = await res.catch(handleFetchError);
}
}
if (cacheKey in res) {
return responseViaCache(res, outgoing);
}
const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
if (res.body) {
const reader = res.body.getReader();
const values = [];
let done = false;
let currentReadPromise = void 0;
if (resHeaderRecord["transfer-encoding"] !== "chunked") {
let maxReadCount = 2;
for (let i = 0; i < maxReadCount; i++) {
currentReadPromise ||= reader.read();
const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
console.error(e);
done = true;
});
if (!chunk) {
if (i === 1) {
await new Promise((resolve) => setTimeout(resolve));
maxReadCount = 3;
continue;
}
break;
}
currentReadPromise = void 0;
if (chunk.value) {
values.push(chunk.value);
}
if (chunk.done) {
done = true;
break;
}
}
if (done && !("content-length" in resHeaderRecord)) {
resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
}
}
outgoing.writeHead(res.status, resHeaderRecord);
values.forEach((value) => {
;
outgoing.write(value);
});
if (done) {
outgoing.end();
} else {
if (values.length === 0) {
flushHeaders(outgoing);
}
await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
}
} else if (resHeaderRecord[X_ALREADY_SENT]) {
} else {
outgoing.writeHead(res.status, resHeaderRecord);
outgoing.end();
}
;
outgoing[outgoingEnded]?.();
};
var getRequestListener = (fetchCallback, options = {}) => {
const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
if (options.overrideGlobalObjects !== false && global.Request !== Request) {
Object.defineProperty(global, "Request", {
value: Request
});
Object.defineProperty(global, "Response", {
value: Response2
});
}
return async (incoming, outgoing) => {
let res, req;
try {
req = newRequest(incoming, options.hostname);
let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
if (!incomingEnded) {
;
incoming[wrapBodyStream] = true;
incoming.on("end", () => {
incomingEnded = true;
});
if (incoming instanceof Http2ServerRequest2) {
;
outgoing[outgoingEnded] = () => {
if (!incomingEnded) {
setTimeout(() => {
if (!incomingEnded) {
setTimeout(() => {
drainIncoming(incoming);
});
}
});
}
};
}
outgoing.on("finish", () => {
if (!incomingEnded) {
drainIncoming(incoming);
}
});
}
outgoing.on("close", () => {
const abortController = req[abortControllerKey];
if (abortController) {
if (incoming.errored) {
req[abortControllerKey].abort(incoming.errored.toString());
} else if (!outgoing.writableFinished) {
req[abortControllerKey].abort("Client connection prematurely closed.");
}
}
if (!incomingEnded) {
setTimeout(() => {
if (!incomingEnded) {
setTimeout(() => {
drainIncoming(incoming);
});
}
});
}
});
res = fetchCallback(req, { incoming, outgoing });
if (cacheKey in res) {
return responseViaCache(res, outgoing);
}
} catch (e) {
if (!res) {
if (options.errorHandler) {
res = await options.errorHandler(req ? e : toRequestError(e));
if (!res) {
return;
}
} else if (!req) {
res = handleRequestError();
} else {
res = handleFetchError(e);
}
} else {
return handleResponseError(e, outgoing);
}
}
try {
return await responseViaResponseObject(res, outgoing, options);
} catch (e) {
return handleResponseError(e, outgoing);
}
};
};
// src/server.ts
var createAdaptorServer = (options) => {
const fetchCallback = options.fetch;
const requestListener = getRequestListener(fetchCallback, {
hostname: options.hostname,
overrideGlobalObjects: options.overrideGlobalObjects,
autoCleanupIncoming: options.autoCleanupIncoming
});
const createServer = options.createServer || createServerHTTP;
const server = createServer(options.serverOptions || {}, requestListener);
return server;
};
var serve = (options, listeningListener) => {
const server = createAdaptorServer(options);
server.listen(options?.port ?? 3e3, options.hostname, () => {
const serverInfo = server.address();
listeningListener && listeningListener(serverInfo);
});
return server;
};
export {
createAdaptorServer,
serve
};

44
node_modules/@hono/node-server/dist/types.d.mts generated vendored Normal file
View File

@@ -0,0 +1,44 @@
import { IncomingMessage, ServerResponse, ServerOptions as ServerOptions$1, createServer, Server } from 'node:http';
import { Http2ServerRequest, Http2ServerResponse, ServerOptions as ServerOptions$3, createServer as createServer$2, SecureServerOptions, createSecureServer, Http2Server, Http2SecureServer } from 'node:http2';
import { ServerOptions as ServerOptions$2, createServer as createServer$1 } from 'node:https';
type HttpBindings = {
incoming: IncomingMessage;
outgoing: ServerResponse;
};
type Http2Bindings = {
incoming: Http2ServerRequest;
outgoing: Http2ServerResponse;
};
type FetchCallback = (request: Request, env: HttpBindings | Http2Bindings) => Promise<unknown> | unknown;
type NextHandlerOption = {
fetch: FetchCallback;
};
type ServerType = Server | Http2Server | Http2SecureServer;
type createHttpOptions = {
serverOptions?: ServerOptions$1;
createServer?: typeof createServer;
};
type createHttpsOptions = {
serverOptions?: ServerOptions$2;
createServer?: typeof createServer$1;
};
type createHttp2Options = {
serverOptions?: ServerOptions$3;
createServer?: typeof createServer$2;
};
type createSecureHttp2Options = {
serverOptions?: SecureServerOptions;
createServer?: typeof createSecureServer;
};
type ServerOptions = createHttpOptions | createHttpsOptions | createHttp2Options | createSecureHttp2Options;
type Options = {
fetch: FetchCallback;
overrideGlobalObjects?: boolean;
autoCleanupIncoming?: boolean;
port?: number;
hostname?: string;
} & ServerOptions;
type CustomErrorHandler = (err: unknown) => void | Response | Promise<void | Response>;
export type { CustomErrorHandler, FetchCallback, Http2Bindings, HttpBindings, NextHandlerOption, Options, ServerOptions, ServerType };

44
node_modules/@hono/node-server/dist/types.d.ts generated vendored Normal file
View File

@@ -0,0 +1,44 @@
import { IncomingMessage, ServerResponse, ServerOptions as ServerOptions$1, createServer, Server } from 'node:http';
import { Http2ServerRequest, Http2ServerResponse, ServerOptions as ServerOptions$3, createServer as createServer$2, SecureServerOptions, createSecureServer, Http2Server, Http2SecureServer } from 'node:http2';
import { ServerOptions as ServerOptions$2, createServer as createServer$1 } from 'node:https';
type HttpBindings = {
incoming: IncomingMessage;
outgoing: ServerResponse;
};
type Http2Bindings = {
incoming: Http2ServerRequest;
outgoing: Http2ServerResponse;
};
type FetchCallback = (request: Request, env: HttpBindings | Http2Bindings) => Promise<unknown> | unknown;
type NextHandlerOption = {
fetch: FetchCallback;
};
type ServerType = Server | Http2Server | Http2SecureServer;
type createHttpOptions = {
serverOptions?: ServerOptions$1;
createServer?: typeof createServer;
};
type createHttpsOptions = {
serverOptions?: ServerOptions$2;
createServer?: typeof createServer$1;
};
type createHttp2Options = {
serverOptions?: ServerOptions$3;
createServer?: typeof createServer$2;
};
type createSecureHttp2Options = {
serverOptions?: SecureServerOptions;
createServer?: typeof createSecureServer;
};
type ServerOptions = createHttpOptions | createHttpsOptions | createHttp2Options | createSecureHttp2Options;
type Options = {
fetch: FetchCallback;
overrideGlobalObjects?: boolean;
autoCleanupIncoming?: boolean;
port?: number;
hostname?: string;
} & ServerOptions;
type CustomErrorHandler = (err: unknown) => void | Response | Promise<void | Response>;
export type { CustomErrorHandler, FetchCallback, Http2Bindings, HttpBindings, NextHandlerOption, Options, ServerOptions, ServerType };

18
node_modules/@hono/node-server/dist/types.js generated vendored Normal file
View File

@@ -0,0 +1,18 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/types.ts
var types_exports = {};
module.exports = __toCommonJS(types_exports);

0
node_modules/@hono/node-server/dist/types.mjs generated vendored Normal file
View File

9
node_modules/@hono/node-server/dist/utils.d.mts generated vendored Normal file
View File

@@ -0,0 +1,9 @@
import { OutgoingHttpHeaders } from 'node:http';
import { Writable } from 'node:stream';
declare function readWithoutBlocking(readPromise: Promise<ReadableStreamReadResult<Uint8Array>>): Promise<ReadableStreamReadResult<Uint8Array> | undefined>;
declare function writeFromReadableStreamDefaultReader(reader: ReadableStreamDefaultReader<Uint8Array>, writable: Writable, currentReadPromise?: Promise<ReadableStreamReadResult<Uint8Array>> | undefined): Promise<undefined>;
declare function writeFromReadableStream(stream: ReadableStream<Uint8Array>, writable: Writable): Promise<undefined> | undefined;
declare const buildOutgoingHttpHeaders: (headers: Headers | HeadersInit | null | undefined) => OutgoingHttpHeaders;
export { buildOutgoingHttpHeaders, readWithoutBlocking, writeFromReadableStream, writeFromReadableStreamDefaultReader };

9
node_modules/@hono/node-server/dist/utils.d.ts generated vendored Normal file
View File

@@ -0,0 +1,9 @@
import { OutgoingHttpHeaders } from 'node:http';
import { Writable } from 'node:stream';
declare function readWithoutBlocking(readPromise: Promise<ReadableStreamReadResult<Uint8Array>>): Promise<ReadableStreamReadResult<Uint8Array> | undefined>;
declare function writeFromReadableStreamDefaultReader(reader: ReadableStreamDefaultReader<Uint8Array>, writable: Writable, currentReadPromise?: Promise<ReadableStreamReadResult<Uint8Array>> | undefined): Promise<undefined>;
declare function writeFromReadableStream(stream: ReadableStream<Uint8Array>, writable: Writable): Promise<undefined> | undefined;
declare const buildOutgoingHttpHeaders: (headers: Headers | HeadersInit | null | undefined) => OutgoingHttpHeaders;
export { buildOutgoingHttpHeaders, readWithoutBlocking, writeFromReadableStream, writeFromReadableStreamDefaultReader };

99
node_modules/@hono/node-server/dist/utils.js generated vendored Normal file
View File

@@ -0,0 +1,99 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/utils.ts
var utils_exports = {};
__export(utils_exports, {
buildOutgoingHttpHeaders: () => buildOutgoingHttpHeaders,
readWithoutBlocking: () => readWithoutBlocking,
writeFromReadableStream: () => writeFromReadableStream,
writeFromReadableStreamDefaultReader: () => writeFromReadableStreamDefaultReader
});
module.exports = __toCommonJS(utils_exports);
async function readWithoutBlocking(readPromise) {
return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
}
function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
const cancel = (error) => {
reader.cancel(error).catch(() => {
});
};
writable.on("close", cancel);
writable.on("error", cancel);
(currentReadPromise ?? reader.read()).then(flow, handleStreamError);
return reader.closed.finally(() => {
writable.off("close", cancel);
writable.off("error", cancel);
});
function handleStreamError(error) {
if (error) {
writable.destroy(error);
}
}
function onDrain() {
reader.read().then(flow, handleStreamError);
}
function flow({ done, value }) {
try {
if (done) {
writable.end();
} else if (!writable.write(value)) {
writable.once("drain", onDrain);
} else {
return reader.read().then(flow, handleStreamError);
}
} catch (e) {
handleStreamError(e);
}
}
}
function writeFromReadableStream(stream, writable) {
if (stream.locked) {
throw new TypeError("ReadableStream is locked.");
} else if (writable.destroyed) {
return;
}
return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
}
var buildOutgoingHttpHeaders = (headers) => {
const res = {};
if (!(headers instanceof Headers)) {
headers = new Headers(headers ?? void 0);
}
const cookies = [];
for (const [k, v] of headers) {
if (k === "set-cookie") {
cookies.push(v);
} else {
res[k] = v;
}
}
if (cookies.length > 0) {
res["set-cookie"] = cookies;
}
res["content-type"] ??= "text/plain; charset=UTF-8";
return res;
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
buildOutgoingHttpHeaders,
readWithoutBlocking,
writeFromReadableStream,
writeFromReadableStreamDefaultReader
});

71
node_modules/@hono/node-server/dist/utils.mjs generated vendored Normal file
View File

@@ -0,0 +1,71 @@
// src/utils.ts
async function readWithoutBlocking(readPromise) {
return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
}
function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
const cancel = (error) => {
reader.cancel(error).catch(() => {
});
};
writable.on("close", cancel);
writable.on("error", cancel);
(currentReadPromise ?? reader.read()).then(flow, handleStreamError);
return reader.closed.finally(() => {
writable.off("close", cancel);
writable.off("error", cancel);
});
function handleStreamError(error) {
if (error) {
writable.destroy(error);
}
}
function onDrain() {
reader.read().then(flow, handleStreamError);
}
function flow({ done, value }) {
try {
if (done) {
writable.end();
} else if (!writable.write(value)) {
writable.once("drain", onDrain);
} else {
return reader.read().then(flow, handleStreamError);
}
} catch (e) {
handleStreamError(e);
}
}
}
function writeFromReadableStream(stream, writable) {
if (stream.locked) {
throw new TypeError("ReadableStream is locked.");
} else if (writable.destroyed) {
return;
}
return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
}
var buildOutgoingHttpHeaders = (headers) => {
const res = {};
if (!(headers instanceof Headers)) {
headers = new Headers(headers ?? void 0);
}
const cookies = [];
for (const [k, v] of headers) {
if (k === "set-cookie") {
cookies.push(v);
} else {
res[k] = v;
}
}
if (cookies.length > 0) {
res["set-cookie"] = cookies;
}
res["content-type"] ??= "text/plain; charset=UTF-8";
return res;
};
export {
buildOutgoingHttpHeaders,
readWithoutBlocking,
writeFromReadableStream,
writeFromReadableStreamDefaultReader
};

View File

@@ -0,0 +1,3 @@
declare const RESPONSE_ALREADY_SENT: Response;
export { RESPONSE_ALREADY_SENT };

View File

@@ -0,0 +1,3 @@
declare const RESPONSE_ALREADY_SENT: Response;
export { RESPONSE_ALREADY_SENT };

37
node_modules/@hono/node-server/dist/utils/response.js generated vendored Normal file
View File

@@ -0,0 +1,37 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/utils/response.ts
var response_exports = {};
__export(response_exports, {
RESPONSE_ALREADY_SENT: () => RESPONSE_ALREADY_SENT
});
module.exports = __toCommonJS(response_exports);
// src/utils/response/constants.ts
var X_ALREADY_SENT = "x-hono-already-sent";
// src/utils/response.ts
var RESPONSE_ALREADY_SENT = new Response(null, {
headers: { [X_ALREADY_SENT]: "true" }
});
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
RESPONSE_ALREADY_SENT
});

10
node_modules/@hono/node-server/dist/utils/response.mjs generated vendored Normal file
View File

@@ -0,0 +1,10 @@
// src/utils/response/constants.ts
var X_ALREADY_SENT = "x-hono-already-sent";
// src/utils/response.ts
var RESPONSE_ALREADY_SENT = new Response(null, {
headers: { [X_ALREADY_SENT]: "true" }
});
export {
RESPONSE_ALREADY_SENT
};

View File

@@ -0,0 +1,3 @@
declare const X_ALREADY_SENT = "x-hono-already-sent";
export { X_ALREADY_SENT };

View File

@@ -0,0 +1,3 @@
declare const X_ALREADY_SENT = "x-hono-already-sent";
export { X_ALREADY_SENT };

View File

@@ -0,0 +1,30 @@
"use strict";
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/utils/response/constants.ts
var constants_exports = {};
__export(constants_exports, {
X_ALREADY_SENT: () => X_ALREADY_SENT
});
module.exports = __toCommonJS(constants_exports);
var X_ALREADY_SENT = "x-hono-already-sent";
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
X_ALREADY_SENT
});

View File

@@ -0,0 +1,5 @@
// src/utils/response/constants.ts
var X_ALREADY_SENT = "x-hono-already-sent";
export {
X_ALREADY_SENT
};

7
node_modules/@hono/node-server/dist/vercel.d.mts generated vendored Normal file
View File

@@ -0,0 +1,7 @@
import * as http2 from 'http2';
import * as http from 'http';
import { Hono } from 'hono';
declare const handle: (app: Hono<any, any, any>) => (incoming: http.IncomingMessage | http2.Http2ServerRequest, outgoing: http.ServerResponse | http2.Http2ServerResponse) => Promise<void>;
export { handle };

7
node_modules/@hono/node-server/dist/vercel.d.ts generated vendored Normal file
View File

@@ -0,0 +1,7 @@
import * as http2 from 'http2';
import * as http from 'http';
import { Hono } from 'hono';
declare const handle: (app: Hono<any, any, any>) => (incoming: http.IncomingMessage | http2.Http2ServerRequest, outgoing: http.ServerResponse | http2.Http2ServerResponse) => Promise<void>;
export { handle };

677
node_modules/@hono/node-server/dist/vercel.js generated vendored Normal file
View File

@@ -0,0 +1,677 @@
"use strict";
var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
for (var name in all)
__defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
if (from && typeof from === "object" || typeof from === "function") {
for (let key of __getOwnPropNames(from))
if (!__hasOwnProp.call(to, key) && key !== except)
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
}
return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
// If the importer is in node compatibility mode or this is not an ESM
// file that has been converted to a CommonJS file using a Babel-
// compatible transform (i.e. "__esModule" has not been set), then set
// "default" to the CommonJS "module.exports" for node compatibility.
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
// src/vercel.ts
var vercel_exports = {};
__export(vercel_exports, {
handle: () => handle
});
module.exports = __toCommonJS(vercel_exports);
// src/listener.ts
var import_node_http22 = require("http2");
// src/request.ts
var import_node_http2 = require("http2");
var import_node_stream = require("stream");
var RequestError = class extends Error {
constructor(message, options) {
super(message, options);
this.name = "RequestError";
}
};
var toRequestError = (e) => {
if (e instanceof RequestError) {
return e;
}
return new RequestError(e.message, { cause: e });
};
var GlobalRequest = global.Request;
var Request = class extends GlobalRequest {
constructor(input, options) {
if (typeof input === "object" && getRequestCache in input) {
input = input[getRequestCache]();
}
if (typeof options?.body?.getReader !== "undefined") {
;
options.duplex ??= "half";
}
super(input, options);
}
};
var newHeadersFromIncoming = (incoming) => {
const headerRecord = [];
const rawHeaders = incoming.rawHeaders;
for (let i = 0; i < rawHeaders.length; i += 2) {
const { [i]: key, [i + 1]: value } = rawHeaders;
if (key.charCodeAt(0) !== /*:*/
58) {
headerRecord.push([key, value]);
}
}
return new Headers(headerRecord);
};
var wrapBodyStream = Symbol("wrapBodyStream");
var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
const init = {
method,
headers,
signal: abortController.signal
};
if (method === "TRACE") {
init.method = "GET";
const req = new Request(url, init);
Object.defineProperty(req, "method", {
get() {
return "TRACE";
}
});
return req;
}
if (!(method === "GET" || method === "HEAD")) {
if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
init.body = new ReadableStream({
start(controller) {
controller.enqueue(incoming.rawBody);
controller.close();
}
});
} else if (incoming[wrapBodyStream]) {
let reader;
init.body = new ReadableStream({
async pull(controller) {
try {
reader ||= import_node_stream.Readable.toWeb(incoming).getReader();
const { done, value } = await reader.read();
if (done) {
controller.close();
} else {
controller.enqueue(value);
}
} catch (error) {
controller.error(error);
}
}
});
} else {
init.body = import_node_stream.Readable.toWeb(incoming);
}
}
return new Request(url, init);
};
var getRequestCache = Symbol("getRequestCache");
var requestCache = Symbol("requestCache");
var incomingKey = Symbol("incomingKey");
var urlKey = Symbol("urlKey");
var headersKey = Symbol("headersKey");
var abortControllerKey = Symbol("abortControllerKey");
var getAbortController = Symbol("getAbortController");
var requestPrototype = {
get method() {
return this[incomingKey].method || "GET";
},
get url() {
return this[urlKey];
},
get headers() {
return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
},
[getAbortController]() {
this[getRequestCache]();
return this[abortControllerKey];
},
[getRequestCache]() {
this[abortControllerKey] ||= new AbortController();
return this[requestCache] ||= newRequestFromIncoming(
this.method,
this[urlKey],
this.headers,
this[incomingKey],
this[abortControllerKey]
);
}
};
[
"body",
"bodyUsed",
"cache",
"credentials",
"destination",
"integrity",
"mode",
"redirect",
"referrer",
"referrerPolicy",
"signal",
"keepalive"
].forEach((k) => {
Object.defineProperty(requestPrototype, k, {
get() {
return this[getRequestCache]()[k];
}
});
});
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
Object.defineProperty(requestPrototype, k, {
value: function() {
return this[getRequestCache]()[k]();
}
});
});
Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), {
value: function(depth, options, inspectFn) {
const props = {
method: this.method,
url: this.url,
headers: this.headers,
nativeRequest: this[requestCache]
};
return `Request (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
}
});
Object.setPrototypeOf(requestPrototype, Request.prototype);
var newRequest = (incoming, defaultHostname) => {
const req = Object.create(requestPrototype);
req[incomingKey] = incoming;
const incomingUrl = incoming.url || "";
if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
(incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
if (incoming instanceof import_node_http2.Http2ServerRequest) {
throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
}
try {
const url2 = new URL(incomingUrl);
req[urlKey] = url2.href;
} catch (e) {
throw new RequestError("Invalid absolute URL", { cause: e });
}
return req;
}
const host = (incoming instanceof import_node_http2.Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
if (!host) {
throw new RequestError("Missing host header");
}
let scheme;
if (incoming instanceof import_node_http2.Http2ServerRequest) {
scheme = incoming.scheme;
if (!(scheme === "http" || scheme === "https")) {
throw new RequestError("Unsupported scheme");
}
} else {
scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
}
const url = new URL(`${scheme}://${host}${incomingUrl}`);
if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
throw new RequestError("Invalid host header");
}
req[urlKey] = url.href;
return req;
};
// src/response.ts
var responseCache = Symbol("responseCache");
var getResponseCache = Symbol("getResponseCache");
var cacheKey = Symbol("cache");
var GlobalResponse = global.Response;
var Response2 = class _Response {
#body;
#init;
[getResponseCache]() {
delete this[cacheKey];
return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
}
constructor(body, init) {
let headers;
this.#body = body;
if (init instanceof _Response) {
const cachedGlobalResponse = init[responseCache];
if (cachedGlobalResponse) {
this.#init = cachedGlobalResponse;
this[getResponseCache]();
return;
} else {
this.#init = init.#init;
headers = new Headers(init.#init.headers);
}
} else {
this.#init = init;
}
if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
;
this[cacheKey] = [init?.status || 200, body, headers || init?.headers];
}
}
get headers() {
const cache = this[cacheKey];
if (cache) {
if (!(cache[2] instanceof Headers)) {
cache[2] = new Headers(
cache[2] || { "content-type": "text/plain; charset=UTF-8" }
);
}
return cache[2];
}
return this[getResponseCache]().headers;
}
get status() {
return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
}
get ok() {
const status = this.status;
return status >= 200 && status < 300;
}
};
["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
Object.defineProperty(Response2.prototype, k, {
get() {
return this[getResponseCache]()[k];
}
});
});
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
Object.defineProperty(Response2.prototype, k, {
value: function() {
return this[getResponseCache]()[k]();
}
});
});
Object.defineProperty(Response2.prototype, Symbol.for("nodejs.util.inspect.custom"), {
value: function(depth, options, inspectFn) {
const props = {
status: this.status,
headers: this.headers,
ok: this.ok,
nativeResponse: this[responseCache]
};
return `Response (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
}
});
Object.setPrototypeOf(Response2, GlobalResponse);
Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
// src/utils.ts
async function readWithoutBlocking(readPromise) {
return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
}
function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
const cancel = (error) => {
reader.cancel(error).catch(() => {
});
};
writable.on("close", cancel);
writable.on("error", cancel);
(currentReadPromise ?? reader.read()).then(flow, handleStreamError);
return reader.closed.finally(() => {
writable.off("close", cancel);
writable.off("error", cancel);
});
function handleStreamError(error) {
if (error) {
writable.destroy(error);
}
}
function onDrain() {
reader.read().then(flow, handleStreamError);
}
function flow({ done, value }) {
try {
if (done) {
writable.end();
} else if (!writable.write(value)) {
writable.once("drain", onDrain);
} else {
return reader.read().then(flow, handleStreamError);
}
} catch (e) {
handleStreamError(e);
}
}
}
function writeFromReadableStream(stream, writable) {
if (stream.locked) {
throw new TypeError("ReadableStream is locked.");
} else if (writable.destroyed) {
return;
}
return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
}
var buildOutgoingHttpHeaders = (headers) => {
const res = {};
if (!(headers instanceof Headers)) {
headers = new Headers(headers ?? void 0);
}
const cookies = [];
for (const [k, v] of headers) {
if (k === "set-cookie") {
cookies.push(v);
} else {
res[k] = v;
}
}
if (cookies.length > 0) {
res["set-cookie"] = cookies;
}
res["content-type"] ??= "text/plain; charset=UTF-8";
return res;
};
// src/utils/response/constants.ts
var X_ALREADY_SENT = "x-hono-already-sent";
// src/globals.ts
var import_node_crypto = __toESM(require("crypto"));
if (typeof global.crypto === "undefined") {
global.crypto = import_node_crypto.default;
}
// src/listener.ts
var outgoingEnded = Symbol("outgoingEnded");
var incomingDraining = Symbol("incomingDraining");
var DRAIN_TIMEOUT_MS = 500;
var MAX_DRAIN_BYTES = 64 * 1024 * 1024;
var drainIncoming = (incoming) => {
const incomingWithDrainState = incoming;
if (incoming.destroyed || incomingWithDrainState[incomingDraining]) {
return;
}
incomingWithDrainState[incomingDraining] = true;
if (incoming instanceof import_node_http22.Http2ServerRequest) {
try {
;
incoming.stream?.close?.(import_node_http22.constants.NGHTTP2_NO_ERROR);
} catch {
}
return;
}
let bytesRead = 0;
const cleanup = () => {
clearTimeout(timer);
incoming.off("data", onData);
incoming.off("end", cleanup);
incoming.off("error", cleanup);
};
const forceClose = () => {
cleanup();
const socket = incoming.socket;
if (socket && !socket.destroyed) {
socket.destroySoon();
}
};
const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
timer.unref?.();
const onData = (chunk) => {
bytesRead += chunk.length;
if (bytesRead > MAX_DRAIN_BYTES) {
forceClose();
}
};
incoming.on("data", onData);
incoming.on("end", cleanup);
incoming.on("error", cleanup);
incoming.resume();
};
var handleRequestError = () => new Response(null, {
status: 400
});
var handleFetchError = (e) => new Response(null, {
status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
});
var handleResponseError = (e, outgoing) => {
const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
console.info("The user aborted a request.");
} else {
console.error(e);
if (!outgoing.headersSent) {
outgoing.writeHead(500, { "Content-Type": "text/plain" });
}
outgoing.end(`Error: ${err.message}`);
outgoing.destroy(err);
}
};
var flushHeaders = (outgoing) => {
if ("flushHeaders" in outgoing && outgoing.writable) {
outgoing.flushHeaders();
}
};
var responseViaCache = async (res, outgoing) => {
let [status, body, header] = res[cacheKey];
let hasContentLength = false;
if (!header) {
header = { "content-type": "text/plain; charset=UTF-8" };
} else if (header instanceof Headers) {
hasContentLength = header.has("content-length");
header = buildOutgoingHttpHeaders(header);
} else if (Array.isArray(header)) {
const headerObj = new Headers(header);
hasContentLength = headerObj.has("content-length");
header = buildOutgoingHttpHeaders(headerObj);
} else {
for (const key in header) {
if (key.length === 14 && key.toLowerCase() === "content-length") {
hasContentLength = true;
break;
}
}
}
if (!hasContentLength) {
if (typeof body === "string") {
header["Content-Length"] = Buffer.byteLength(body);
} else if (body instanceof Uint8Array) {
header["Content-Length"] = body.byteLength;
} else if (body instanceof Blob) {
header["Content-Length"] = body.size;
}
}
outgoing.writeHead(status, header);
if (typeof body === "string" || body instanceof Uint8Array) {
outgoing.end(body);
} else if (body instanceof Blob) {
outgoing.end(new Uint8Array(await body.arrayBuffer()));
} else {
flushHeaders(outgoing);
await writeFromReadableStream(body, outgoing)?.catch(
(e) => handleResponseError(e, outgoing)
);
}
;
outgoing[outgoingEnded]?.();
};
var isPromise = (res) => typeof res.then === "function";
var responseViaResponseObject = async (res, outgoing, options = {}) => {
if (isPromise(res)) {
if (options.errorHandler) {
try {
res = await res;
} catch (err) {
const errRes = await options.errorHandler(err);
if (!errRes) {
return;
}
res = errRes;
}
} else {
res = await res.catch(handleFetchError);
}
}
if (cacheKey in res) {
return responseViaCache(res, outgoing);
}
const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
if (res.body) {
const reader = res.body.getReader();
const values = [];
let done = false;
let currentReadPromise = void 0;
if (resHeaderRecord["transfer-encoding"] !== "chunked") {
let maxReadCount = 2;
for (let i = 0; i < maxReadCount; i++) {
currentReadPromise ||= reader.read();
const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
console.error(e);
done = true;
});
if (!chunk) {
if (i === 1) {
await new Promise((resolve) => setTimeout(resolve));
maxReadCount = 3;
continue;
}
break;
}
currentReadPromise = void 0;
if (chunk.value) {
values.push(chunk.value);
}
if (chunk.done) {
done = true;
break;
}
}
if (done && !("content-length" in resHeaderRecord)) {
resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
}
}
outgoing.writeHead(res.status, resHeaderRecord);
values.forEach((value) => {
;
outgoing.write(value);
});
if (done) {
outgoing.end();
} else {
if (values.length === 0) {
flushHeaders(outgoing);
}
await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
}
} else if (resHeaderRecord[X_ALREADY_SENT]) {
} else {
outgoing.writeHead(res.status, resHeaderRecord);
outgoing.end();
}
;
outgoing[outgoingEnded]?.();
};
var getRequestListener = (fetchCallback, options = {}) => {
const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
if (options.overrideGlobalObjects !== false && global.Request !== Request) {
Object.defineProperty(global, "Request", {
value: Request
});
Object.defineProperty(global, "Response", {
value: Response2
});
}
return async (incoming, outgoing) => {
let res, req;
try {
req = newRequest(incoming, options.hostname);
let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
if (!incomingEnded) {
;
incoming[wrapBodyStream] = true;
incoming.on("end", () => {
incomingEnded = true;
});
if (incoming instanceof import_node_http22.Http2ServerRequest) {
;
outgoing[outgoingEnded] = () => {
if (!incomingEnded) {
setTimeout(() => {
if (!incomingEnded) {
setTimeout(() => {
drainIncoming(incoming);
});
}
});
}
};
}
outgoing.on("finish", () => {
if (!incomingEnded) {
drainIncoming(incoming);
}
});
}
outgoing.on("close", () => {
const abortController = req[abortControllerKey];
if (abortController) {
if (incoming.errored) {
req[abortControllerKey].abort(incoming.errored.toString());
} else if (!outgoing.writableFinished) {
req[abortControllerKey].abort("Client connection prematurely closed.");
}
}
if (!incomingEnded) {
setTimeout(() => {
if (!incomingEnded) {
setTimeout(() => {
drainIncoming(incoming);
});
}
});
}
});
res = fetchCallback(req, { incoming, outgoing });
if (cacheKey in res) {
return responseViaCache(res, outgoing);
}
} catch (e) {
if (!res) {
if (options.errorHandler) {
res = await options.errorHandler(req ? e : toRequestError(e));
if (!res) {
return;
}
} else if (!req) {
res = handleRequestError();
} else {
res = handleFetchError(e);
}
} else {
return handleResponseError(e, outgoing);
}
}
try {
return await responseViaResponseObject(res, outgoing, options);
} catch (e) {
return handleResponseError(e, outgoing);
}
};
};
// src/vercel.ts
var handle = (app) => {
return getRequestListener(app.fetch);
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
handle
});

640
node_modules/@hono/node-server/dist/vercel.mjs generated vendored Normal file
View File

@@ -0,0 +1,640 @@
// src/listener.ts
import { Http2ServerRequest as Http2ServerRequest2, constants as h2constants } from "http2";
// src/request.ts
import { Http2ServerRequest } from "http2";
import { Readable } from "stream";
var RequestError = class extends Error {
constructor(message, options) {
super(message, options);
this.name = "RequestError";
}
};
var toRequestError = (e) => {
if (e instanceof RequestError) {
return e;
}
return new RequestError(e.message, { cause: e });
};
var GlobalRequest = global.Request;
var Request = class extends GlobalRequest {
constructor(input, options) {
if (typeof input === "object" && getRequestCache in input) {
input = input[getRequestCache]();
}
if (typeof options?.body?.getReader !== "undefined") {
;
options.duplex ??= "half";
}
super(input, options);
}
};
var newHeadersFromIncoming = (incoming) => {
const headerRecord = [];
const rawHeaders = incoming.rawHeaders;
for (let i = 0; i < rawHeaders.length; i += 2) {
const { [i]: key, [i + 1]: value } = rawHeaders;
if (key.charCodeAt(0) !== /*:*/
58) {
headerRecord.push([key, value]);
}
}
return new Headers(headerRecord);
};
var wrapBodyStream = Symbol("wrapBodyStream");
var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
const init = {
method,
headers,
signal: abortController.signal
};
if (method === "TRACE") {
init.method = "GET";
const req = new Request(url, init);
Object.defineProperty(req, "method", {
get() {
return "TRACE";
}
});
return req;
}
if (!(method === "GET" || method === "HEAD")) {
if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
init.body = new ReadableStream({
start(controller) {
controller.enqueue(incoming.rawBody);
controller.close();
}
});
} else if (incoming[wrapBodyStream]) {
let reader;
init.body = new ReadableStream({
async pull(controller) {
try {
reader ||= Readable.toWeb(incoming).getReader();
const { done, value } = await reader.read();
if (done) {
controller.close();
} else {
controller.enqueue(value);
}
} catch (error) {
controller.error(error);
}
}
});
} else {
init.body = Readable.toWeb(incoming);
}
}
return new Request(url, init);
};
var getRequestCache = Symbol("getRequestCache");
var requestCache = Symbol("requestCache");
var incomingKey = Symbol("incomingKey");
var urlKey = Symbol("urlKey");
var headersKey = Symbol("headersKey");
var abortControllerKey = Symbol("abortControllerKey");
var getAbortController = Symbol("getAbortController");
var requestPrototype = {
get method() {
return this[incomingKey].method || "GET";
},
get url() {
return this[urlKey];
},
get headers() {
return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
},
[getAbortController]() {
this[getRequestCache]();
return this[abortControllerKey];
},
[getRequestCache]() {
this[abortControllerKey] ||= new AbortController();
return this[requestCache] ||= newRequestFromIncoming(
this.method,
this[urlKey],
this.headers,
this[incomingKey],
this[abortControllerKey]
);
}
};
[
"body",
"bodyUsed",
"cache",
"credentials",
"destination",
"integrity",
"mode",
"redirect",
"referrer",
"referrerPolicy",
"signal",
"keepalive"
].forEach((k) => {
Object.defineProperty(requestPrototype, k, {
get() {
return this[getRequestCache]()[k];
}
});
});
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
Object.defineProperty(requestPrototype, k, {
value: function() {
return this[getRequestCache]()[k]();
}
});
});
Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), {
value: function(depth, options, inspectFn) {
const props = {
method: this.method,
url: this.url,
headers: this.headers,
nativeRequest: this[requestCache]
};
return `Request (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
}
});
Object.setPrototypeOf(requestPrototype, Request.prototype);
var newRequest = (incoming, defaultHostname) => {
const req = Object.create(requestPrototype);
req[incomingKey] = incoming;
const incomingUrl = incoming.url || "";
if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
(incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
if (incoming instanceof Http2ServerRequest) {
throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
}
try {
const url2 = new URL(incomingUrl);
req[urlKey] = url2.href;
} catch (e) {
throw new RequestError("Invalid absolute URL", { cause: e });
}
return req;
}
const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
if (!host) {
throw new RequestError("Missing host header");
}
let scheme;
if (incoming instanceof Http2ServerRequest) {
scheme = incoming.scheme;
if (!(scheme === "http" || scheme === "https")) {
throw new RequestError("Unsupported scheme");
}
} else {
scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
}
const url = new URL(`${scheme}://${host}${incomingUrl}`);
if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
throw new RequestError("Invalid host header");
}
req[urlKey] = url.href;
return req;
};
// src/response.ts
var responseCache = Symbol("responseCache");
var getResponseCache = Symbol("getResponseCache");
var cacheKey = Symbol("cache");
var GlobalResponse = global.Response;
var Response2 = class _Response {
#body;
#init;
[getResponseCache]() {
delete this[cacheKey];
return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
}
constructor(body, init) {
let headers;
this.#body = body;
if (init instanceof _Response) {
const cachedGlobalResponse = init[responseCache];
if (cachedGlobalResponse) {
this.#init = cachedGlobalResponse;
this[getResponseCache]();
return;
} else {
this.#init = init.#init;
headers = new Headers(init.#init.headers);
}
} else {
this.#init = init;
}
if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
;
this[cacheKey] = [init?.status || 200, body, headers || init?.headers];
}
}
get headers() {
const cache = this[cacheKey];
if (cache) {
if (!(cache[2] instanceof Headers)) {
cache[2] = new Headers(
cache[2] || { "content-type": "text/plain; charset=UTF-8" }
);
}
return cache[2];
}
return this[getResponseCache]().headers;
}
get status() {
return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
}
get ok() {
const status = this.status;
return status >= 200 && status < 300;
}
};
["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
Object.defineProperty(Response2.prototype, k, {
get() {
return this[getResponseCache]()[k];
}
});
});
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
Object.defineProperty(Response2.prototype, k, {
value: function() {
return this[getResponseCache]()[k]();
}
});
});
Object.defineProperty(Response2.prototype, Symbol.for("nodejs.util.inspect.custom"), {
value: function(depth, options, inspectFn) {
const props = {
status: this.status,
headers: this.headers,
ok: this.ok,
nativeResponse: this[responseCache]
};
return `Response (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
}
});
Object.setPrototypeOf(Response2, GlobalResponse);
Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
// src/utils.ts
async function readWithoutBlocking(readPromise) {
return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
}
function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
const cancel = (error) => {
reader.cancel(error).catch(() => {
});
};
writable.on("close", cancel);
writable.on("error", cancel);
(currentReadPromise ?? reader.read()).then(flow, handleStreamError);
return reader.closed.finally(() => {
writable.off("close", cancel);
writable.off("error", cancel);
});
function handleStreamError(error) {
if (error) {
writable.destroy(error);
}
}
function onDrain() {
reader.read().then(flow, handleStreamError);
}
function flow({ done, value }) {
try {
if (done) {
writable.end();
} else if (!writable.write(value)) {
writable.once("drain", onDrain);
} else {
return reader.read().then(flow, handleStreamError);
}
} catch (e) {
handleStreamError(e);
}
}
}
function writeFromReadableStream(stream, writable) {
if (stream.locked) {
throw new TypeError("ReadableStream is locked.");
} else if (writable.destroyed) {
return;
}
return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
}
var buildOutgoingHttpHeaders = (headers) => {
const res = {};
if (!(headers instanceof Headers)) {
headers = new Headers(headers ?? void 0);
}
const cookies = [];
for (const [k, v] of headers) {
if (k === "set-cookie") {
cookies.push(v);
} else {
res[k] = v;
}
}
if (cookies.length > 0) {
res["set-cookie"] = cookies;
}
res["content-type"] ??= "text/plain; charset=UTF-8";
return res;
};
// src/utils/response/constants.ts
var X_ALREADY_SENT = "x-hono-already-sent";
// src/globals.ts
import crypto from "crypto";
if (typeof global.crypto === "undefined") {
global.crypto = crypto;
}
// src/listener.ts
var outgoingEnded = Symbol("outgoingEnded");
var incomingDraining = Symbol("incomingDraining");
var DRAIN_TIMEOUT_MS = 500;
var MAX_DRAIN_BYTES = 64 * 1024 * 1024;
var drainIncoming = (incoming) => {
const incomingWithDrainState = incoming;
if (incoming.destroyed || incomingWithDrainState[incomingDraining]) {
return;
}
incomingWithDrainState[incomingDraining] = true;
if (incoming instanceof Http2ServerRequest2) {
try {
;
incoming.stream?.close?.(h2constants.NGHTTP2_NO_ERROR);
} catch {
}
return;
}
let bytesRead = 0;
const cleanup = () => {
clearTimeout(timer);
incoming.off("data", onData);
incoming.off("end", cleanup);
incoming.off("error", cleanup);
};
const forceClose = () => {
cleanup();
const socket = incoming.socket;
if (socket && !socket.destroyed) {
socket.destroySoon();
}
};
const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
timer.unref?.();
const onData = (chunk) => {
bytesRead += chunk.length;
if (bytesRead > MAX_DRAIN_BYTES) {
forceClose();
}
};
incoming.on("data", onData);
incoming.on("end", cleanup);
incoming.on("error", cleanup);
incoming.resume();
};
var handleRequestError = () => new Response(null, {
status: 400
});
var handleFetchError = (e) => new Response(null, {
status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
});
var handleResponseError = (e, outgoing) => {
const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
console.info("The user aborted a request.");
} else {
console.error(e);
if (!outgoing.headersSent) {
outgoing.writeHead(500, { "Content-Type": "text/plain" });
}
outgoing.end(`Error: ${err.message}`);
outgoing.destroy(err);
}
};
var flushHeaders = (outgoing) => {
if ("flushHeaders" in outgoing && outgoing.writable) {
outgoing.flushHeaders();
}
};
var responseViaCache = async (res, outgoing) => {
let [status, body, header] = res[cacheKey];
let hasContentLength = false;
if (!header) {
header = { "content-type": "text/plain; charset=UTF-8" };
} else if (header instanceof Headers) {
hasContentLength = header.has("content-length");
header = buildOutgoingHttpHeaders(header);
} else if (Array.isArray(header)) {
const headerObj = new Headers(header);
hasContentLength = headerObj.has("content-length");
header = buildOutgoingHttpHeaders(headerObj);
} else {
for (const key in header) {
if (key.length === 14 && key.toLowerCase() === "content-length") {
hasContentLength = true;
break;
}
}
}
if (!hasContentLength) {
if (typeof body === "string") {
header["Content-Length"] = Buffer.byteLength(body);
} else if (body instanceof Uint8Array) {
header["Content-Length"] = body.byteLength;
} else if (body instanceof Blob) {
header["Content-Length"] = body.size;
}
}
outgoing.writeHead(status, header);
if (typeof body === "string" || body instanceof Uint8Array) {
outgoing.end(body);
} else if (body instanceof Blob) {
outgoing.end(new Uint8Array(await body.arrayBuffer()));
} else {
flushHeaders(outgoing);
await writeFromReadableStream(body, outgoing)?.catch(
(e) => handleResponseError(e, outgoing)
);
}
;
outgoing[outgoingEnded]?.();
};
var isPromise = (res) => typeof res.then === "function";
var responseViaResponseObject = async (res, outgoing, options = {}) => {
if (isPromise(res)) {
if (options.errorHandler) {
try {
res = await res;
} catch (err) {
const errRes = await options.errorHandler(err);
if (!errRes) {
return;
}
res = errRes;
}
} else {
res = await res.catch(handleFetchError);
}
}
if (cacheKey in res) {
return responseViaCache(res, outgoing);
}
const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
if (res.body) {
const reader = res.body.getReader();
const values = [];
let done = false;
let currentReadPromise = void 0;
if (resHeaderRecord["transfer-encoding"] !== "chunked") {
let maxReadCount = 2;
for (let i = 0; i < maxReadCount; i++) {
currentReadPromise ||= reader.read();
const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
console.error(e);
done = true;
});
if (!chunk) {
if (i === 1) {
await new Promise((resolve) => setTimeout(resolve));
maxReadCount = 3;
continue;
}
break;
}
currentReadPromise = void 0;
if (chunk.value) {
values.push(chunk.value);
}
if (chunk.done) {
done = true;
break;
}
}
if (done && !("content-length" in resHeaderRecord)) {
resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
}
}
outgoing.writeHead(res.status, resHeaderRecord);
values.forEach((value) => {
;
outgoing.write(value);
});
if (done) {
outgoing.end();
} else {
if (values.length === 0) {
flushHeaders(outgoing);
}
await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
}
} else if (resHeaderRecord[X_ALREADY_SENT]) {
} else {
outgoing.writeHead(res.status, resHeaderRecord);
outgoing.end();
}
;
outgoing[outgoingEnded]?.();
};
var getRequestListener = (fetchCallback, options = {}) => {
const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
if (options.overrideGlobalObjects !== false && global.Request !== Request) {
Object.defineProperty(global, "Request", {
value: Request
});
Object.defineProperty(global, "Response", {
value: Response2
});
}
return async (incoming, outgoing) => {
let res, req;
try {
req = newRequest(incoming, options.hostname);
let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
if (!incomingEnded) {
;
incoming[wrapBodyStream] = true;
incoming.on("end", () => {
incomingEnded = true;
});
if (incoming instanceof Http2ServerRequest2) {
;
outgoing[outgoingEnded] = () => {
if (!incomingEnded) {
setTimeout(() => {
if (!incomingEnded) {
setTimeout(() => {
drainIncoming(incoming);
});
}
});
}
};
}
outgoing.on("finish", () => {
if (!incomingEnded) {
drainIncoming(incoming);
}
});
}
outgoing.on("close", () => {
const abortController = req[abortControllerKey];
if (abortController) {
if (incoming.errored) {
req[abortControllerKey].abort(incoming.errored.toString());
} else if (!outgoing.writableFinished) {
req[abortControllerKey].abort("Client connection prematurely closed.");
}
}
if (!incomingEnded) {
setTimeout(() => {
if (!incomingEnded) {
setTimeout(() => {
drainIncoming(incoming);
});
}
});
}
});
res = fetchCallback(req, { incoming, outgoing });
if (cacheKey in res) {
return responseViaCache(res, outgoing);
}
} catch (e) {
if (!res) {
if (options.errorHandler) {
res = await options.errorHandler(req ? e : toRequestError(e));
if (!res) {
return;
}
} else if (!req) {
res = handleRequestError();
} else {
res = handleFetchError(e);
}
} else {
return handleResponseError(e, outgoing);
}
}
try {
return await responseViaResponseObject(res, outgoing, options);
} catch (e) {
return handleResponseError(e, outgoing);
}
};
};
// src/vercel.ts
var handle = (app) => {
return getRequestListener(app.fetch);
};
export {
handle
};

103
node_modules/@hono/node-server/package.json generated vendored Normal file
View File

@@ -0,0 +1,103 @@
{
"name": "@hono/node-server",
"version": "1.19.14",
"description": "Node.js Adapter for Hono",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"files": [
"dist"
],
"exports": {
".": {
"types": "./dist/index.d.ts",
"require": "./dist/index.js",
"import": "./dist/index.mjs"
},
"./serve-static": {
"types": "./dist/serve-static.d.ts",
"require": "./dist/serve-static.js",
"import": "./dist/serve-static.mjs"
},
"./vercel": {
"types": "./dist/vercel.d.ts",
"require": "./dist/vercel.js",
"import": "./dist/vercel.mjs"
},
"./utils/*": {
"types": "./dist/utils/*.d.ts",
"require": "./dist/utils/*.js",
"import": "./dist/utils/*.mjs"
},
"./conninfo": {
"types": "./dist/conninfo.d.ts",
"require": "./dist/conninfo.js",
"import": "./dist/conninfo.mjs"
}
},
"typesVersions": {
"*": {
".": [
"./dist/index.d.ts"
],
"serve-static": [
"./dist/serve-static.d.ts"
],
"vercel": [
"./dist/vercel.d.ts"
],
"utils/*": [
"./dist/utils/*.d.ts"
],
"conninfo": [
"./dist/conninfo.d.ts"
]
}
},
"scripts": {
"test": "node --expose-gc node_modules/jest/bin/jest.js",
"build": "tsup --external hono",
"watch": "tsup --watch",
"postbuild": "publint",
"prerelease": "bun run build && bun run test",
"release": "np",
"lint": "eslint src test",
"lint:fix": "eslint src test --fix",
"format": "prettier --check \"src/**/*.{js,ts}\" \"test/**/*.{js,ts}\"",
"format:fix": "prettier --write \"src/**/*.{js,ts}\" \"test/**/*.{js,ts}\""
},
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/honojs/node-server.git"
},
"homepage": "https://github.com/honojs/node-server",
"author": "Yusuke Wada <yusuke@kamawada.com> (https://github.com/yusukebe)",
"publishConfig": {
"registry": "https://registry.npmjs.org",
"access": "public"
},
"engines": {
"node": ">=18.14.1"
},
"devDependencies": {
"@hono/eslint-config": "^1.0.1",
"@types/jest": "^29.5.3",
"@types/node": "^20.10.0",
"@types/supertest": "^2.0.12",
"@whatwg-node/fetch": "^0.9.14",
"eslint": "^9.10.0",
"hono": "^4.4.10",
"jest": "^29.6.1",
"np": "^7.7.0",
"prettier": "^3.2.4",
"publint": "^0.1.16",
"supertest": "^6.3.3",
"ts-jest": "^29.1.1",
"tsup": "^7.2.0",
"typescript": "^5.3.2"
},
"peerDependencies": {
"hono": "^4"
},
"packageManager": "bun@1.2.20"
}

21
node_modules/@types/bun/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) Microsoft Corporation.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE

20
node_modules/@types/bun/README.md generated vendored Normal file
View File

@@ -0,0 +1,20 @@
# Installation
> `npm install --save @types/bun`
# Summary
This package contains type definitions for bun (https://bun.com).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/bun.
## [index.d.ts](https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/bun/index.d.ts)
````ts
/// <reference types="bun-types" />
````
### Additional Details
* Last updated: Fri, 10 Apr 2026 18:46:38 GMT
* Dependencies: [bun-types](https://npmjs.com/package/bun-types)
# Credits
These definitions were written by [Jarred Sumner](https://github.com/Jarred-Sumner), [Robobun](https://github.com/robobun), [Dylan Conway](https://github.com/dylan-conway), [Ciro Spaciari](https://github.com/cirospaciari), [Sosuke Suzuki](https://github.com/sosukesuzuki), and [Alistair Smith](https://github.com/alii).

1
node_modules/@types/bun/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1 @@
/// <reference types="bun-types" />

53
node_modules/@types/bun/package.json generated vendored Normal file
View File

@@ -0,0 +1,53 @@
{
"name": "@types/bun",
"version": "1.3.12",
"description": "TypeScript definitions for bun",
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/bun",
"license": "MIT",
"contributors": [
{
"name": "Jarred Sumner",
"githubUsername": "Jarred-Sumner",
"url": "https://github.com/Jarred-Sumner"
},
{
"name": "Robobun",
"githubUsername": "robobun",
"url": "https://github.com/robobun"
},
{
"name": "Dylan Conway",
"githubUsername": "dylan-conway",
"url": "https://github.com/dylan-conway"
},
{
"name": "Ciro Spaciari",
"githubUsername": "cirospaciari",
"url": "https://github.com/cirospaciari"
},
{
"name": "Sosuke Suzuki",
"githubUsername": "sosukesuzuki",
"url": "https://github.com/sosukesuzuki"
},
{
"name": "Alistair Smith",
"githubUsername": "alii",
"url": "https://github.com/alii"
}
],
"main": "",
"types": "index.d.ts",
"repository": {
"type": "git",
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git",
"directory": "types/bun"
},
"scripts": {},
"dependencies": {
"bun-types": "1.3.12"
},
"peerDependencies": {},
"typesPublisherContentHash": "a3d81260cf01df4eb9a9374e2d820145e98659c605f9b92d158e9df1d0a1fe61",
"typeScriptVersion": "5.3"
}

21
node_modules/@types/node/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) Microsoft Corporation.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE

15
node_modules/@types/node/README.md generated vendored Normal file
View File

@@ -0,0 +1,15 @@
# Installation
> `npm install --save @types/node`
# Summary
This package contains type definitions for node (https://nodejs.org/).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node.
### Additional Details
* Last updated: Fri, 10 Apr 2026 03:39:58 GMT
* Dependencies: [undici-types](https://npmjs.com/package/undici-types)
# Credits
These definitions were written by [Microsoft TypeScript](https://github.com/Microsoft), [Alberto Schiabel](https://github.com/jkomyno), [Andrew Makarov](https://github.com/r3nya), [Benjamin Toueg](https://github.com/btoueg), [David Junger](https://github.com/touffy), [Mohsen Azimi](https://github.com/mohsen1), [Nikita Galkin](https://github.com/galkin), [Sebastian Silbermann](https://github.com/eps1lon), [Wilco Bakker](https://github.com/WilcoBakker), [Marcin Kopacz](https://github.com/chyzwar), [Trivikram Kamat](https://github.com/trivikr), [Junxiao Shi](https://github.com/yoursunny), [Ilia Baryshnikov](https://github.com/qwelias), [ExE Boss](https://github.com/ExE-Boss), [Piotr Błażejewicz](https://github.com/peterblazejewicz), [Anna Henningsen](https://github.com/addaleax), [Victor Perin](https://github.com/victorperin), [NodeJS Contributors](https://github.com/NodeJS), [Linus Unnebäck](https://github.com/LinusU), [wafuwafu13](https://github.com/wafuwafu13), [Matteo Collina](https://github.com/mcollina), [Dmitry Semigradsky](https://github.com/Semigradsky), [René](https://github.com/Renegade334), and [Yagiz Nizipli](https://github.com/anonrig).

950
node_modules/@types/node/assert.d.ts generated vendored Normal file
View File

@@ -0,0 +1,950 @@
declare module "node:assert" {
import strict = require("node:assert/strict");
/**
* An alias of {@link assert.ok}.
* @since v0.5.9
* @param value The input that is checked for being truthy.
*/
function assert(value: unknown, message?: string | Error): asserts value;
const kOptions: unique symbol;
namespace assert {
type AssertMethodNames =
| "deepEqual"
| "deepStrictEqual"
| "doesNotMatch"
| "doesNotReject"
| "doesNotThrow"
| "equal"
| "fail"
| "ifError"
| "match"
| "notDeepEqual"
| "notDeepStrictEqual"
| "notEqual"
| "notStrictEqual"
| "ok"
| "partialDeepStrictEqual"
| "rejects"
| "strictEqual"
| "throws";
interface AssertOptions {
/**
* If set to `'full'`, shows the full diff in assertion errors.
* @default 'simple'
*/
diff?: "simple" | "full" | undefined;
/**
* If set to `true`, non-strict methods behave like their
* corresponding strict methods.
* @default true
*/
strict?: boolean | undefined;
/**
* If set to `true`, skips prototype and constructor
* comparison in deep equality checks.
* @since v24.9.0
* @default false
*/
skipPrototype?: boolean | undefined;
}
interface Assert extends Pick<typeof assert, AssertMethodNames> {
readonly [kOptions]: AssertOptions & { strict: false };
}
interface AssertStrict extends Pick<typeof strict, AssertMethodNames> {
readonly [kOptions]: AssertOptions & { strict: true };
}
/**
* The `Assert` class allows creating independent assertion instances with custom options.
* @since v24.6.0
*/
var Assert: {
/**
* Creates a new assertion instance. The `diff` option controls the verbosity of diffs in assertion error messages.
*
* ```js
* const { Assert } = require('node:assert');
* const assertInstance = new Assert({ diff: 'full' });
* assertInstance.deepStrictEqual({ a: 1 }, { a: 2 });
* // Shows a full diff in the error message.
* ```
*
* **Important**: When destructuring assertion methods from an `Assert` instance,
* the methods lose their connection to the instance's configuration options (such
* as `diff`, `strict`, and `skipPrototype` settings).
* The destructured methods will fall back to default behavior instead.
*
* ```js
* const myAssert = new Assert({ diff: 'full' });
*
* // This works as expected - uses 'full' diff
* myAssert.strictEqual({ a: 1 }, { b: { c: 1 } });
*
* // This loses the 'full' diff setting - falls back to default 'simple' diff
* const { strictEqual } = myAssert;
* strictEqual({ a: 1 }, { b: { c: 1 } });
* ```
*
* The `skipPrototype` option affects all deep equality methods:
*
* ```js
* class Foo {
* constructor(a) {
* this.a = a;
* }
* }
*
* class Bar {
* constructor(a) {
* this.a = a;
* }
* }
*
* const foo = new Foo(1);
* const bar = new Bar(1);
*
* // Default behavior - fails due to different constructors
* const assert1 = new Assert();
* assert1.deepStrictEqual(foo, bar); // AssertionError
*
* // Skip prototype comparison - passes if properties are equal
* const assert2 = new Assert({ skipPrototype: true });
* assert2.deepStrictEqual(foo, bar); // OK
* ```
*
* When destructured, methods lose access to the instance's `this` context and revert to default assertion behavior
* (diff: 'simple', non-strict mode).
* To maintain custom options when using destructured methods, avoid
* destructuring and call methods directly on the instance.
* @since v24.6.0
*/
new(
options?: AssertOptions & { strict?: true | undefined },
): AssertStrict;
new(
options: AssertOptions,
): Assert;
};
interface AssertionErrorOptions {
/**
* If provided, the error message is set to this value.
*/
message?: string | undefined;
/**
* The `actual` property on the error instance.
*/
actual?: unknown;
/**
* The `expected` property on the error instance.
*/
expected?: unknown;
/**
* The `operator` property on the error instance.
*/
operator?: string | undefined;
/**
* If provided, the generated stack trace omits frames before this function.
*/
stackStartFn?: Function | undefined;
/**
* If set to `'full'`, shows the full diff in assertion errors.
* @default 'simple'
*/
diff?: "simple" | "full" | undefined;
}
/**
* Indicates the failure of an assertion. All errors thrown by the `node:assert` module will be instances of the `AssertionError` class.
*/
class AssertionError extends Error {
constructor(options: AssertionErrorOptions);
/**
* Set to the `actual` argument for methods such as {@link assert.strictEqual()}.
*/
actual: unknown;
/**
* Set to the `expected` argument for methods such as {@link assert.strictEqual()}.
*/
expected: unknown;
/**
* Indicates if the message was auto-generated (`true`) or not.
*/
generatedMessage: boolean;
/**
* Value is always `ERR_ASSERTION` to show that the error is an assertion error.
*/
code: "ERR_ASSERTION";
/**
* Set to the passed in operator value.
*/
operator: string;
}
type AssertPredicate = RegExp | (new() => object) | ((thrown: unknown) => boolean) | object | Error;
/**
* Throws an `AssertionError` with the provided error message or a default
* error message. If the `message` parameter is an instance of an `Error` then
* it will be thrown instead of the `AssertionError`.
*
* ```js
* import assert from 'node:assert/strict';
*
* assert.fail();
* // AssertionError [ERR_ASSERTION]: Failed
*
* assert.fail('boom');
* // AssertionError [ERR_ASSERTION]: boom
*
* assert.fail(new TypeError('need array'));
* // TypeError: need array
* ```
* @since v0.1.21
* @param [message='Failed']
*/
function fail(message?: string | Error): never;
/**
* Tests if `value` is truthy. It is equivalent to `assert.equal(!!value, true, message)`.
*
* If `value` is not truthy, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is `undefined`, a default
* error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown instead of the `AssertionError`.
* If no arguments are passed in at all `message` will be set to the string:`` 'No value argument passed to `assert.ok()`' ``.
*
* Be aware that in the `repl` the error message will be different to the one
* thrown in a file! See below for further details.
*
* ```js
* import assert from 'node:assert/strict';
*
* assert.ok(true);
* // OK
* assert.ok(1);
* // OK
*
* assert.ok();
* // AssertionError: No value argument passed to `assert.ok()`
*
* assert.ok(false, 'it\'s false');
* // AssertionError: it's false
*
* // In the repl:
* assert.ok(typeof 123 === 'string');
* // AssertionError: false == true
*
* // In a file (e.g. test.js):
* assert.ok(typeof 123 === 'string');
* // AssertionError: The expression evaluated to a falsy value:
* //
* // assert.ok(typeof 123 === 'string')
*
* assert.ok(false);
* // AssertionError: The expression evaluated to a falsy value:
* //
* // assert.ok(false)
*
* assert.ok(0);
* // AssertionError: The expression evaluated to a falsy value:
* //
* // assert.ok(0)
* ```
*
* ```js
* import assert from 'node:assert/strict';
*
* // Using `assert()` works the same:
* assert(2 + 2 > 5);;
* // AssertionError: The expression evaluated to a falsy value:
* //
* // assert(2 + 2 > 5)
* ```
* @since v0.1.21
*/
function ok(value: unknown, message?: string | Error): asserts value;
/**
* **Strict assertion mode**
*
* An alias of {@link strictEqual}.
*
* **Legacy assertion mode**
*
* > Stability: 3 - Legacy: Use {@link strictEqual} instead.
*
* Tests shallow, coercive equality between the `actual` and `expected` parameters
* using the [`==` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality). `NaN` is specially handled
* and treated as being identical if both sides are `NaN`.
*
* ```js
* import assert from 'node:assert';
*
* assert.equal(1, 1);
* // OK, 1 == 1
* assert.equal(1, '1');
* // OK, 1 == '1'
* assert.equal(NaN, NaN);
* // OK
*
* assert.equal(1, 2);
* // AssertionError: 1 == 2
* assert.equal({ a: { b: 1 } }, { a: { b: 1 } });
* // AssertionError: { a: { b: 1 } } == { a: { b: 1 } }
* ```
*
* If the values are not equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a default
* error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown instead of the `AssertionError`.
* @since v0.1.21
*/
function equal(actual: unknown, expected: unknown, message?: string | Error): void;
/**
* **Strict assertion mode**
*
* An alias of {@link notStrictEqual}.
*
* **Legacy assertion mode**
*
* > Stability: 3 - Legacy: Use {@link notStrictEqual} instead.
*
* Tests shallow, coercive inequality with the [`!=` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Inequality). `NaN` is
* specially handled and treated as being identical if both sides are `NaN`.
*
* ```js
* import assert from 'node:assert';
*
* assert.notEqual(1, 2);
* // OK
*
* assert.notEqual(1, 1);
* // AssertionError: 1 != 1
*
* assert.notEqual(1, '1');
* // AssertionError: 1 != '1'
* ```
*
* If the values are equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a default error
* message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown instead of the `AssertionError`.
* @since v0.1.21
*/
function notEqual(actual: unknown, expected: unknown, message?: string | Error): void;
/**
* **Strict assertion mode**
*
* An alias of {@link deepStrictEqual}.
*
* **Legacy assertion mode**
*
* > Stability: 3 - Legacy: Use {@link deepStrictEqual} instead.
*
* Tests for deep equality between the `actual` and `expected` parameters. Consider
* using {@link deepStrictEqual} instead. {@link deepEqual} can have
* surprising results.
*
* _Deep equality_ means that the enumerable "own" properties of child objects
* are also recursively evaluated by the following rules.
* @since v0.1.21
*/
function deepEqual(actual: unknown, expected: unknown, message?: string | Error): void;
/**
* **Strict assertion mode**
*
* An alias of {@link notDeepStrictEqual}.
*
* **Legacy assertion mode**
*
* > Stability: 3 - Legacy: Use {@link notDeepStrictEqual} instead.
*
* Tests for any deep inequality. Opposite of {@link deepEqual}.
*
* ```js
* import assert from 'node:assert';
*
* const obj1 = {
* a: {
* b: 1,
* },
* };
* const obj2 = {
* a: {
* b: 2,
* },
* };
* const obj3 = {
* a: {
* b: 1,
* },
* };
* const obj4 = { __proto__: obj1 };
*
* assert.notDeepEqual(obj1, obj1);
* // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }
*
* assert.notDeepEqual(obj1, obj2);
* // OK
*
* assert.notDeepEqual(obj1, obj3);
* // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } }
*
* assert.notDeepEqual(obj1, obj4);
* // OK
* ```
*
* If the values are deeply equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a default
* error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown
* instead of the `AssertionError`.
* @since v0.1.21
*/
function notDeepEqual(actual: unknown, expected: unknown, message?: string | Error): void;
/**
* Tests strict equality between the `actual` and `expected` parameters as
* determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is).
*
* ```js
* import assert from 'node:assert/strict';
*
* assert.strictEqual(1, 2);
* // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
* //
* // 1 !== 2
*
* assert.strictEqual(1, 1);
* // OK
*
* assert.strictEqual('Hello foobar', 'Hello World!');
* // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal:
* // + actual - expected
* //
* // + 'Hello foobar'
* // - 'Hello World!'
* // ^
*
* const apples = 1;
* const oranges = 2;
* assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`);
* // AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2
*
* assert.strictEqual(1, '1', new TypeError('Inputs are not identical'));
* // TypeError: Inputs are not identical
* ```
*
* If the values are not strictly equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a
* default error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown
* instead of the `AssertionError`.
* @since v0.1.21
*/
function strictEqual<T>(actual: unknown, expected: T, message?: string | Error): asserts actual is T;
/**
* Tests strict inequality between the `actual` and `expected` parameters as
* determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is).
*
* ```js
* import assert from 'node:assert/strict';
*
* assert.notStrictEqual(1, 2);
* // OK
*
* assert.notStrictEqual(1, 1);
* // AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to:
* //
* // 1
*
* assert.notStrictEqual(1, '1');
* // OK
* ```
*
* If the values are strictly equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a
* default error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown
* instead of the `AssertionError`.
* @since v0.1.21
*/
function notStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void;
/**
* Tests for deep equality between the `actual` and `expected` parameters.
* "Deep" equality means that the enumerable "own" properties of child objects
* are recursively evaluated also by the following rules.
* @since v1.2.0
*/
function deepStrictEqual<T>(actual: unknown, expected: T, message?: string | Error): asserts actual is T;
/**
* Tests for deep strict inequality. Opposite of {@link deepStrictEqual}.
*
* ```js
* import assert from 'node:assert/strict';
*
* assert.notDeepStrictEqual({ a: 1 }, { a: '1' });
* // OK
* ```
*
* If the values are deeply and strictly equal, an `AssertionError` is thrown
* with a `message` property set equal to the value of the `message` parameter. If
* the `message` parameter is undefined, a default error message is assigned. If
* the `message` parameter is an instance of an `Error` then it will be thrown
* instead of the `AssertionError`.
* @since v1.2.0
*/
function notDeepStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void;
/**
* Expects the function `fn` to throw an error.
*
* If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes),
* [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function,
* a validation object where each property will be tested for strict deep equality,
* or an instance of error where each property will be tested for strict deep
* equality including the non-enumerable `message` and `name` properties. When
* using an object, it is also possible to use a regular expression, when
* validating against a string property. See below for examples.
*
* If specified, `message` will be appended to the message provided by the `AssertionError` if the `fn` call fails to throw or in case the error validation
* fails.
*
* Custom validation object/error instance:
*
* ```js
* import assert from 'node:assert/strict';
*
* const err = new TypeError('Wrong value');
* err.code = 404;
* err.foo = 'bar';
* err.info = {
* nested: true,
* baz: 'text',
* };
* err.reg = /abc/i;
*
* assert.throws(
* () => {
* throw err;
* },
* {
* name: 'TypeError',
* message: 'Wrong value',
* info: {
* nested: true,
* baz: 'text',
* },
* // Only properties on the validation object will be tested for.
* // Using nested objects requires all properties to be present. Otherwise
* // the validation is going to fail.
* },
* );
*
* // Using regular expressions to validate error properties:
* assert.throws(
* () => {
* throw err;
* },
* {
* // The `name` and `message` properties are strings and using regular
* // expressions on those will match against the string. If they fail, an
* // error is thrown.
* name: /^TypeError$/,
* message: /Wrong/,
* foo: 'bar',
* info: {
* nested: true,
* // It is not possible to use regular expressions for nested properties!
* baz: 'text',
* },
* // The `reg` property contains a regular expression and only if the
* // validation object contains an identical regular expression, it is going
* // to pass.
* reg: /abc/i,
* },
* );
*
* // Fails due to the different `message` and `name` properties:
* assert.throws(
* () => {
* const otherErr = new Error('Not found');
* // Copy all enumerable properties from `err` to `otherErr`.
* for (const [key, value] of Object.entries(err)) {
* otherErr[key] = value;
* }
* throw otherErr;
* },
* // The error's `message` and `name` properties will also be checked when using
* // an error as validation object.
* err,
* );
* ```
*
* Validate instanceof using constructor:
*
* ```js
* import assert from 'node:assert/strict';
*
* assert.throws(
* () => {
* throw new Error('Wrong value');
* },
* Error,
* );
* ```
*
* Validate error message using [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions):
*
* Using a regular expression runs `.toString` on the error object, and will
* therefore also include the error name.
*
* ```js
* import assert from 'node:assert/strict';
*
* assert.throws(
* () => {
* throw new Error('Wrong value');
* },
* /^Error: Wrong value$/,
* );
* ```
*
* Custom error validation:
*
* The function must return `true` to indicate all internal validations passed.
* It will otherwise fail with an `AssertionError`.
*
* ```js
* import assert from 'node:assert/strict';
*
* assert.throws(
* () => {
* throw new Error('Wrong value');
* },
* (err) => {
* assert(err instanceof Error);
* assert(/value/.test(err));
* // Avoid returning anything from validation functions besides `true`.
* // Otherwise, it's not clear what part of the validation failed. Instead,
* // throw an error about the specific validation that failed (as done in this
* // example) and add as much helpful debugging information to that error as
* // possible.
* return true;
* },
* 'unexpected error',
* );
* ```
*
* `error` cannot be a string. If a string is provided as the second
* argument, then `error` is assumed to be omitted and the string will be used for `message` instead. This can lead to easy-to-miss mistakes. Using the same
* message as the thrown error message is going to result in an `ERR_AMBIGUOUS_ARGUMENT` error. Please read the example below carefully if using
* a string as the second argument gets considered:
*
* ```js
* import assert from 'node:assert/strict';
*
* function throwingFirst() {
* throw new Error('First');
* }
*
* function throwingSecond() {
* throw new Error('Second');
* }
*
* function notThrowing() {}
*
* // The second argument is a string and the input function threw an Error.
* // The first case will not throw as it does not match for the error message
* // thrown by the input function!
* assert.throws(throwingFirst, 'Second');
* // In the next example the message has no benefit over the message from the
* // error and since it is not clear if the user intended to actually match
* // against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error.
* assert.throws(throwingSecond, 'Second');
* // TypeError [ERR_AMBIGUOUS_ARGUMENT]
*
* // The string is only used (as message) in case the function does not throw:
* assert.throws(notThrowing, 'Second');
* // AssertionError [ERR_ASSERTION]: Missing expected exception: Second
*
* // If it was intended to match for the error message do this instead:
* // It does not throw because the error messages match.
* assert.throws(throwingSecond, /Second$/);
*
* // If the error message does not match, an AssertionError is thrown.
* assert.throws(throwingFirst, /Second$/);
* // AssertionError [ERR_ASSERTION]
* ```
*
* Due to the confusing error-prone notation, avoid a string as the second
* argument.
* @since v0.1.21
*/
function throws(block: () => unknown, message?: string | Error): void;
function throws(block: () => unknown, error: AssertPredicate, message?: string | Error): void;
/**
* Asserts that the function `fn` does not throw an error.
*
* Using `assert.doesNotThrow()` is actually not useful because there
* is no benefit in catching an error and then rethrowing it. Instead, consider
* adding a comment next to the specific code path that should not throw and keep
* error messages as expressive as possible.
*
* When `assert.doesNotThrow()` is called, it will immediately call the `fn` function.
*
* If an error is thrown and it is the same type as that specified by the `error` parameter, then an `AssertionError` is thrown. If the error is of a
* different type, or if the `error` parameter is undefined, the error is
* propagated back to the caller.
*
* If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes),
* [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), or a validation
* function. See {@link throws} for more details.
*
* The following, for instance, will throw the `TypeError` because there is no
* matching error type in the assertion:
*
* ```js
* import assert from 'node:assert/strict';
*
* assert.doesNotThrow(
* () => {
* throw new TypeError('Wrong value');
* },
* SyntaxError,
* );
* ```
*
* However, the following will result in an `AssertionError` with the message
* 'Got unwanted exception...':
*
* ```js
* import assert from 'node:assert/strict';
*
* assert.doesNotThrow(
* () => {
* throw new TypeError('Wrong value');
* },
* TypeError,
* );
* ```
*
* If an `AssertionError` is thrown and a value is provided for the `message` parameter, the value of `message` will be appended to the `AssertionError` message:
*
* ```js
* import assert from 'node:assert/strict';
*
* assert.doesNotThrow(
* () => {
* throw new TypeError('Wrong value');
* },
* /Wrong value/,
* 'Whoops',
* );
* // Throws: AssertionError: Got unwanted exception: Whoops
* ```
* @since v0.1.21
*/
function doesNotThrow(block: () => unknown, message?: string | Error): void;
function doesNotThrow(block: () => unknown, error: AssertPredicate, message?: string | Error): void;
/**
* Throws `value` if `value` is not `undefined` or `null`. This is useful when
* testing the `error` argument in callbacks. The stack trace contains all frames
* from the error passed to `ifError()` including the potential new frames for `ifError()` itself.
*
* ```js
* import assert from 'node:assert/strict';
*
* assert.ifError(null);
* // OK
* assert.ifError(0);
* // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0
* assert.ifError('error');
* // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error'
* assert.ifError(new Error());
* // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error
*
* // Create some random error frames.
* let err;
* (function errorFrame() {
* err = new Error('test error');
* })();
*
* (function ifErrorFrame() {
* assert.ifError(err);
* })();
* // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error
* // at ifErrorFrame
* // at errorFrame
* ```
* @since v0.1.97
*/
function ifError(value: unknown): asserts value is null | undefined;
/**
* Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately
* calls the function and awaits the returned promise to complete. It will then
* check that the promise is rejected.
*
* If `asyncFn` is a function and it throws an error synchronously, `assert.rejects()` will return a rejected `Promise` with that error. If the
* function does not return a promise, `assert.rejects()` will return a rejected `Promise` with an [ERR_INVALID_RETURN_VALUE](https://nodejs.org/docs/latest-v25.x/api/errors.html#err_invalid_return_value)
* error. In both cases the error handler is skipped.
*
* Besides the async nature to await the completion behaves identically to {@link throws}.
*
* If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes),
* [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function,
* an object where each property will be tested for, or an instance of error where
* each property will be tested for including the non-enumerable `message` and `name` properties.
*
* If specified, `message` will be the message provided by the `{@link AssertionError}` if the `asyncFn` fails to reject.
*
* ```js
* import assert from 'node:assert/strict';
*
* await assert.rejects(
* async () => {
* throw new TypeError('Wrong value');
* },
* {
* name: 'TypeError',
* message: 'Wrong value',
* },
* );
* ```
*
* ```js
* import assert from 'node:assert/strict';
*
* await assert.rejects(
* async () => {
* throw new TypeError('Wrong value');
* },
* (err) => {
* assert.strictEqual(err.name, 'TypeError');
* assert.strictEqual(err.message, 'Wrong value');
* return true;
* },
* );
* ```
*
* ```js
* import assert from 'node:assert/strict';
*
* assert.rejects(
* Promise.reject(new Error('Wrong value')),
* Error,
* ).then(() => {
* // ...
* });
* ```
*
* `error` cannot be a string. If a string is provided as the second argument, then `error` is assumed to
* be omitted and the string will be used for `message` instead. This can lead to easy-to-miss mistakes. Please read the
* example in {@link throws} carefully if using a string as the second argument gets considered.
* @since v10.0.0
*/
function rejects(block: (() => Promise<unknown>) | Promise<unknown>, message?: string | Error): Promise<void>;
function rejects(
block: (() => Promise<unknown>) | Promise<unknown>,
error: AssertPredicate,
message?: string | Error,
): Promise<void>;
/**
* Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately
* calls the function and awaits the returned promise to complete. It will then
* check that the promise is not rejected.
*
* If `asyncFn` is a function and it throws an error synchronously, `assert.doesNotReject()` will return a rejected `Promise` with that error. If
* the function does not return a promise, `assert.doesNotReject()` will return a
* rejected `Promise` with an [ERR_INVALID_RETURN_VALUE](https://nodejs.org/docs/latest-v25.x/api/errors.html#err_invalid_return_value) error. In both cases
* the error handler is skipped.
*
* Using `assert.doesNotReject()` is actually not useful because there is little
* benefit in catching a rejection and then rejecting it again. Instead, consider
* adding a comment next to the specific code path that should not reject and keep
* error messages as expressive as possible.
*
* If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes),
* [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), or a validation
* function. See {@link throws} for more details.
*
* Besides the async nature to await the completion behaves identically to {@link doesNotThrow}.
*
* ```js
* import assert from 'node:assert/strict';
*
* await assert.doesNotReject(
* async () => {
* throw new TypeError('Wrong value');
* },
* SyntaxError,
* );
* ```
*
* ```js
* import assert from 'node:assert/strict';
*
* assert.doesNotReject(Promise.reject(new TypeError('Wrong value')))
* .then(() => {
* // ...
* });
* ```
* @since v10.0.0
*/
function doesNotReject(
block: (() => Promise<unknown>) | Promise<unknown>,
message?: string | Error,
): Promise<void>;
function doesNotReject(
block: (() => Promise<unknown>) | Promise<unknown>,
error: AssertPredicate,
message?: string | Error,
): Promise<void>;
/**
* Expects the `string` input to match the regular expression.
*
* ```js
* import assert from 'node:assert/strict';
*
* assert.match('I will fail', /pass/);
* // AssertionError [ERR_ASSERTION]: The input did not match the regular ...
*
* assert.match(123, /pass/);
* // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.
*
* assert.match('I will pass', /pass/);
* // OK
* ```
*
* If the values do not match, or if the `string` argument is of another type than `string`, an `{@link AssertionError}` is thrown with a `message` property set equal
* to the value of the `message` parameter. If the `message` parameter is
* undefined, a default error message is assigned. If the `message` parameter is an
* instance of an [Error](https://nodejs.org/docs/latest-v25.x/api/errors.html#class-error) then it will be thrown instead of the `{@link AssertionError}`.
* @since v13.6.0, v12.16.0
*/
function match(value: string, regExp: RegExp, message?: string | Error): void;
/**
* Expects the `string` input not to match the regular expression.
*
* ```js
* import assert from 'node:assert/strict';
*
* assert.doesNotMatch('I will fail', /fail/);
* // AssertionError [ERR_ASSERTION]: The input was expected to not match the ...
*
* assert.doesNotMatch(123, /pass/);
* // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string.
*
* assert.doesNotMatch('I will pass', /different/);
* // OK
* ```
*
* If the values do match, or if the `string` argument is of another type than `string`, an `{@link AssertionError}` is thrown with a `message` property set equal
* to the value of the `message` parameter. If the `message` parameter is
* undefined, a default error message is assigned. If the `message` parameter is an
* instance of an [Error](https://nodejs.org/docs/latest-v25.x/api/errors.html#class-error) then it will be thrown instead of the `{@link AssertionError}`.
* @since v13.6.0, v12.16.0
*/
function doesNotMatch(value: string, regExp: RegExp, message?: string | Error): void;
/**
* Tests for partial deep equality between the `actual` and `expected` parameters.
* "Deep" equality means that the enumerable "own" properties of child objects
* are recursively evaluated also by the following rules. "Partial" equality means
* that only properties that exist on the `expected` parameter are going to be
* compared.
*
* This method always passes the same test cases as `assert.deepStrictEqual()`,
* behaving as a super set of it.
* @since v22.13.0
*/
function partialDeepStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void;
}
namespace assert {
export { strict };
}
export = assert;
}
declare module "assert" {
import assert = require("node:assert");
export = assert;
}

Some files were not shown because too many files have changed in this diff Show More