Erster Docker-Stand
This commit is contained in:
357
_node_modules/@hono/node-server/README.md
generated
Normal file
357
_node_modules/@hono/node-server/README.md
generated
Normal file
@@ -0,0 +1,357 @@
|
||||
# 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>
|
||||
|
||||
## Author
|
||||
|
||||
Yusuke Wada <https://github.com/yusukebe>
|
||||
|
||||
## License
|
||||
|
||||
MIT
|
||||
10
_node_modules/@hono/node-server/dist/conninfo.d.mts
generated
vendored
Normal file
10
_node_modules/@hono/node-server/dist/conninfo.d.mts
generated
vendored
Normal 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
10
_node_modules/@hono/node-server/dist/conninfo.d.ts
generated
vendored
Normal 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
42
_node_modules/@hono/node-server/dist/conninfo.js
generated
vendored
Normal 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
17
_node_modules/@hono/node-server/dist/conninfo.mjs
generated
vendored
Normal 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
2
_node_modules/@hono/node-server/dist/globals.d.mts
generated
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
|
||||
export { }
|
||||
2
_node_modules/@hono/node-server/dist/globals.d.ts
generated
vendored
Normal file
2
_node_modules/@hono/node-server/dist/globals.d.ts
generated
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
|
||||
export { }
|
||||
29
_node_modules/@hono/node-server/dist/globals.js
generated
vendored
Normal file
29
_node_modules/@hono/node-server/dist/globals.js
generated
vendored
Normal 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
5
_node_modules/@hono/node-server/dist/globals.mjs
generated
vendored
Normal 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
8
_node_modules/@hono/node-server/dist/index.d.mts
generated
vendored
Normal 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
8
_node_modules/@hono/node-server/dist/index.d.ts
generated
vendored
Normal 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';
|
||||
613
_node_modules/@hono/node-server/dist/index.js
generated
vendored
Normal file
613
_node_modules/@hono/node-server/dist/index.js
generated
vendored
Normal file
@@ -0,0 +1,613 @@
|
||||
"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.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) {
|
||||
headers ||= init?.headers || { "content-type": "text/plain; charset=UTF-8" };
|
||||
this[cacheKey] = [init?.status || 200, body, headers];
|
||||
}
|
||||
}
|
||||
get headers() {
|
||||
const cache = this[cacheKey];
|
||||
if (cache) {
|
||||
if (!(cache[2] instanceof Headers)) {
|
||||
cache[2] = new Headers(cache[2]);
|
||||
}
|
||||
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.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 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];
|
||||
if (header instanceof Headers) {
|
||||
header = buildOutgoingHttpHeaders(header);
|
||||
}
|
||||
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(() => {
|
||||
incoming.destroy();
|
||||
outgoing.destroy();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
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(() => {
|
||||
incoming.destroy();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
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
|
||||
});
|
||||
573
_node_modules/@hono/node-server/dist/index.mjs
generated
vendored
Normal file
573
_node_modules/@hono/node-server/dist/index.mjs
generated
vendored
Normal file
@@ -0,0 +1,573 @@
|
||||
// src/server.ts
|
||||
import { createServer as createServerHTTP } from "http";
|
||||
|
||||
// src/listener.ts
|
||||
import { Http2ServerRequest as Http2ServerRequest2 } 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.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) {
|
||||
headers ||= init?.headers || { "content-type": "text/plain; charset=UTF-8" };
|
||||
this[cacheKey] = [init?.status || 200, body, headers];
|
||||
}
|
||||
}
|
||||
get headers() {
|
||||
const cache = this[cacheKey];
|
||||
if (cache) {
|
||||
if (!(cache[2] instanceof Headers)) {
|
||||
cache[2] = new Headers(cache[2]);
|
||||
}
|
||||
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.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 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];
|
||||
if (header instanceof Headers) {
|
||||
header = buildOutgoingHttpHeaders(header);
|
||||
}
|
||||
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(() => {
|
||||
incoming.destroy();
|
||||
outgoing.destroy();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
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(() => {
|
||||
incoming.destroy();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
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
13
_node_modules/@hono/node-server/dist/listener.d.mts
generated
vendored
Normal 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
13
_node_modules/@hono/node-server/dist/listener.d.ts
generated
vendored
Normal 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 };
|
||||
581
_node_modules/@hono/node-server/dist/listener.js
generated
vendored
Normal file
581
_node_modules/@hono/node-server/dist/listener.js
generated
vendored
Normal file
@@ -0,0 +1,581 @@
|
||||
"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.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) {
|
||||
headers ||= init?.headers || { "content-type": "text/plain; charset=UTF-8" };
|
||||
this[cacheKey] = [init?.status || 200, body, headers];
|
||||
}
|
||||
}
|
||||
get headers() {
|
||||
const cache = this[cacheKey];
|
||||
if (cache) {
|
||||
if (!(cache[2] instanceof Headers)) {
|
||||
cache[2] = new Headers(cache[2]);
|
||||
}
|
||||
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.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 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];
|
||||
if (header instanceof Headers) {
|
||||
header = buildOutgoingHttpHeaders(header);
|
||||
}
|
||||
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(() => {
|
||||
incoming.destroy();
|
||||
outgoing.destroy();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
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(() => {
|
||||
incoming.destroy();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
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
|
||||
});
|
||||
546
_node_modules/@hono/node-server/dist/listener.mjs
generated
vendored
Normal file
546
_node_modules/@hono/node-server/dist/listener.mjs
generated
vendored
Normal file
@@ -0,0 +1,546 @@
|
||||
// src/listener.ts
|
||||
import { Http2ServerRequest as Http2ServerRequest2 } 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.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) {
|
||||
headers ||= init?.headers || { "content-type": "text/plain; charset=UTF-8" };
|
||||
this[cacheKey] = [init?.status || 200, body, headers];
|
||||
}
|
||||
}
|
||||
get headers() {
|
||||
const cache = this[cacheKey];
|
||||
if (cache) {
|
||||
if (!(cache[2] instanceof Headers)) {
|
||||
cache[2] = new Headers(cache[2]);
|
||||
}
|
||||
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.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 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];
|
||||
if (header instanceof Headers) {
|
||||
header = buildOutgoingHttpHeaders(header);
|
||||
}
|
||||
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(() => {
|
||||
incoming.destroy();
|
||||
outgoing.destroy();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
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(() => {
|
||||
incoming.destroy();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
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
25
_node_modules/@hono/node-server/dist/request.d.mts
generated
vendored
Normal 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, IncomingMessageWithWrapBodyStream, Request, RequestError, abortControllerKey, getAbortController, newRequest, toRequestError, wrapBodyStream };
|
||||
25
_node_modules/@hono/node-server/dist/request.d.ts
generated
vendored
Normal file
25
_node_modules/@hono/node-server/dist/request.d.ts
generated
vendored
Normal 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, IncomingMessageWithWrapBodyStream, Request, RequestError, abortControllerKey, getAbortController, newRequest, toRequestError, wrapBodyStream };
|
||||
227
_node_modules/@hono/node-server/dist/request.js
generated
vendored
Normal file
227
_node_modules/@hono/node-server/dist/request.js
generated
vendored
Normal file
@@ -0,0 +1,227 @@
|
||||
"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.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
|
||||
});
|
||||
195
_node_modules/@hono/node-server/dist/request.mjs
generated
vendored
Normal file
195
_node_modules/@hono/node-server/dist/request.mjs
generated
vendored
Normal file
@@ -0,0 +1,195 @@
|
||||
// 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.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
26
_node_modules/@hono/node-server/dist/response.d.mts
generated
vendored
Normal 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> | Headers | OutgoingHttpHeaders
|
||||
];
|
||||
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, InternalCache, Response, cacheKey };
|
||||
26
_node_modules/@hono/node-server/dist/response.d.ts
generated
vendored
Normal file
26
_node_modules/@hono/node-server/dist/response.d.ts
generated
vendored
Normal 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> | Headers | OutgoingHttpHeaders
|
||||
];
|
||||
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, InternalCache, Response, cacheKey };
|
||||
99
_node_modules/@hono/node-server/dist/response.js
generated
vendored
Normal file
99
_node_modules/@hono/node-server/dist/response.js
generated
vendored
Normal 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/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) {
|
||||
headers ||= init?.headers || { "content-type": "text/plain; charset=UTF-8" };
|
||||
this[cacheKey] = [init?.status || 200, body, headers];
|
||||
}
|
||||
}
|
||||
get headers() {
|
||||
const cache = this[cacheKey];
|
||||
if (cache) {
|
||||
if (!(cache[2] instanceof Headers)) {
|
||||
cache[2] = new Headers(cache[2]);
|
||||
}
|
||||
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.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
|
||||
});
|
||||
72
_node_modules/@hono/node-server/dist/response.mjs
generated
vendored
Normal file
72
_node_modules/@hono/node-server/dist/response.mjs
generated
vendored
Normal file
@@ -0,0 +1,72 @@
|
||||
// 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) {
|
||||
headers ||= init?.headers || { "content-type": "text/plain; charset=UTF-8" };
|
||||
this[cacheKey] = [init?.status || 200, body, headers];
|
||||
}
|
||||
}
|
||||
get headers() {
|
||||
const cache = this[cacheKey];
|
||||
if (cache) {
|
||||
if (!(cache[2] instanceof Headers)) {
|
||||
cache[2] = new Headers(cache[2]);
|
||||
}
|
||||
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.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
17
_node_modules/@hono/node-server/dist/serve-static.d.mts
generated
vendored
Normal 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 { ServeStaticOptions, serveStatic };
|
||||
17
_node_modules/@hono/node-server/dist/serve-static.d.ts
generated
vendored
Normal file
17
_node_modules/@hono/node-server/dist/serve-static.d.ts
generated
vendored
Normal 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 { ServeStaticOptions, serveStatic };
|
||||
163
_node_modules/@hono/node-server/dist/serve-static.js
generated
vendored
Normal file
163
_node_modules/@hono/node-server/dist/serve-static.js
generated
vendored
Normal file
@@ -0,0 +1,163 @@
|
||||
"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 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 = decodeURIComponent(c.req.path);
|
||||
if (/(?:^|[\/\\])\.\.(?:$|[\/\\])/.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
|
||||
});
|
||||
138
_node_modules/@hono/node-server/dist/serve-static.mjs
generated
vendored
Normal file
138
_node_modules/@hono/node-server/dist/serve-static.mjs
generated
vendored
Normal file
@@ -0,0 +1,138 @@
|
||||
// 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 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 = decodeURIComponent(c.req.path);
|
||||
if (/(?:^|[\/\\])\.\.(?:$|[\/\\])/.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
10
_node_modules/@hono/node-server/dist/server.d.mts
generated
vendored
Normal 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
10
_node_modules/@hono/node-server/dist/server.d.ts
generated
vendored
Normal 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 };
|
||||
607
_node_modules/@hono/node-server/dist/server.js
generated
vendored
Normal file
607
_node_modules/@hono/node-server/dist/server.js
generated
vendored
Normal file
@@ -0,0 +1,607 @@
|
||||
"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.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) {
|
||||
headers ||= init?.headers || { "content-type": "text/plain; charset=UTF-8" };
|
||||
this[cacheKey] = [init?.status || 200, body, headers];
|
||||
}
|
||||
}
|
||||
get headers() {
|
||||
const cache = this[cacheKey];
|
||||
if (cache) {
|
||||
if (!(cache[2] instanceof Headers)) {
|
||||
cache[2] = new Headers(cache[2]);
|
||||
}
|
||||
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.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 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];
|
||||
if (header instanceof Headers) {
|
||||
header = buildOutgoingHttpHeaders(header);
|
||||
}
|
||||
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(() => {
|
||||
incoming.destroy();
|
||||
outgoing.destroy();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
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(() => {
|
||||
incoming.destroy();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
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
|
||||
});
|
||||
571
_node_modules/@hono/node-server/dist/server.mjs
generated
vendored
Normal file
571
_node_modules/@hono/node-server/dist/server.mjs
generated
vendored
Normal file
@@ -0,0 +1,571 @@
|
||||
// src/server.ts
|
||||
import { createServer as createServerHTTP } from "http";
|
||||
|
||||
// src/listener.ts
|
||||
import { Http2ServerRequest as Http2ServerRequest2 } 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.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) {
|
||||
headers ||= init?.headers || { "content-type": "text/plain; charset=UTF-8" };
|
||||
this[cacheKey] = [init?.status || 200, body, headers];
|
||||
}
|
||||
}
|
||||
get headers() {
|
||||
const cache = this[cacheKey];
|
||||
if (cache) {
|
||||
if (!(cache[2] instanceof Headers)) {
|
||||
cache[2] = new Headers(cache[2]);
|
||||
}
|
||||
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.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 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];
|
||||
if (header instanceof Headers) {
|
||||
header = buildOutgoingHttpHeaders(header);
|
||||
}
|
||||
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(() => {
|
||||
incoming.destroy();
|
||||
outgoing.destroy();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
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(() => {
|
||||
incoming.destroy();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
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
44
_node_modules/@hono/node-server/dist/types.d.mts
generated
vendored
Normal file
@@ -0,0 +1,44 @@
|
||||
import { IncomingMessage, ServerResponse, Server, ServerOptions as ServerOptions$1, createServer } from 'node:http';
|
||||
import { Http2ServerRequest, Http2ServerResponse, Http2Server, Http2SecureServer, ServerOptions as ServerOptions$3, createServer as createServer$2, SecureServerOptions, createSecureServer } 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 { CustomErrorHandler, FetchCallback, Http2Bindings, HttpBindings, NextHandlerOption, Options, ServerOptions, ServerType };
|
||||
44
_node_modules/@hono/node-server/dist/types.d.ts
generated
vendored
Normal file
44
_node_modules/@hono/node-server/dist/types.d.ts
generated
vendored
Normal file
@@ -0,0 +1,44 @@
|
||||
import { IncomingMessage, ServerResponse, Server, ServerOptions as ServerOptions$1, createServer } from 'node:http';
|
||||
import { Http2ServerRequest, Http2ServerResponse, Http2Server, Http2SecureServer, ServerOptions as ServerOptions$3, createServer as createServer$2, SecureServerOptions, createSecureServer } 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 { CustomErrorHandler, FetchCallback, Http2Bindings, HttpBindings, NextHandlerOption, Options, ServerOptions, ServerType };
|
||||
18
_node_modules/@hono/node-server/dist/types.js
generated
vendored
Normal file
18
_node_modules/@hono/node-server/dist/types.js
generated
vendored
Normal 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
0
_node_modules/@hono/node-server/dist/types.mjs
generated
vendored
Normal file
9
_node_modules/@hono/node-server/dist/utils.d.mts
generated
vendored
Normal file
9
_node_modules/@hono/node-server/dist/utils.d.mts
generated
vendored
Normal 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<void>;
|
||||
declare function writeFromReadableStream(stream: ReadableStream<Uint8Array>, writable: Writable): Promise<void> | 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
9
_node_modules/@hono/node-server/dist/utils.d.ts
generated
vendored
Normal 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<void>;
|
||||
declare function writeFromReadableStream(stream: ReadableStream<Uint8Array>, writable: Writable): Promise<void> | 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
99
_node_modules/@hono/node-server/dist/utils.js
generated
vendored
Normal 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
71
_node_modules/@hono/node-server/dist/utils.mjs
generated
vendored
Normal 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
|
||||
};
|
||||
3
_node_modules/@hono/node-server/dist/utils/response.d.mts
generated
vendored
Normal file
3
_node_modules/@hono/node-server/dist/utils/response.d.mts
generated
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
declare const RESPONSE_ALREADY_SENT: Response;
|
||||
|
||||
export { RESPONSE_ALREADY_SENT };
|
||||
3
_node_modules/@hono/node-server/dist/utils/response.d.ts
generated
vendored
Normal file
3
_node_modules/@hono/node-server/dist/utils/response.d.ts
generated
vendored
Normal 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
37
_node_modules/@hono/node-server/dist/utils/response.js
generated
vendored
Normal 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
10
_node_modules/@hono/node-server/dist/utils/response.mjs
generated
vendored
Normal 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
|
||||
};
|
||||
3
_node_modules/@hono/node-server/dist/utils/response/constants.d.mts
generated
vendored
Normal file
3
_node_modules/@hono/node-server/dist/utils/response/constants.d.mts
generated
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
declare const X_ALREADY_SENT = "x-hono-already-sent";
|
||||
|
||||
export { X_ALREADY_SENT };
|
||||
3
_node_modules/@hono/node-server/dist/utils/response/constants.d.ts
generated
vendored
Normal file
3
_node_modules/@hono/node-server/dist/utils/response/constants.d.ts
generated
vendored
Normal file
@@ -0,0 +1,3 @@
|
||||
declare const X_ALREADY_SENT = "x-hono-already-sent";
|
||||
|
||||
export { X_ALREADY_SENT };
|
||||
30
_node_modules/@hono/node-server/dist/utils/response/constants.js
generated
vendored
Normal file
30
_node_modules/@hono/node-server/dist/utils/response/constants.js
generated
vendored
Normal 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
|
||||
});
|
||||
5
_node_modules/@hono/node-server/dist/utils/response/constants.mjs
generated
vendored
Normal file
5
_node_modules/@hono/node-server/dist/utils/response/constants.mjs
generated
vendored
Normal 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
7
_node_modules/@hono/node-server/dist/vercel.d.mts
generated
vendored
Normal 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
7
_node_modules/@hono/node-server/dist/vercel.d.ts
generated
vendored
Normal 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 };
|
||||
588
_node_modules/@hono/node-server/dist/vercel.js
generated
vendored
Normal file
588
_node_modules/@hono/node-server/dist/vercel.js
generated
vendored
Normal file
@@ -0,0 +1,588 @@
|
||||
"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.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) {
|
||||
headers ||= init?.headers || { "content-type": "text/plain; charset=UTF-8" };
|
||||
this[cacheKey] = [init?.status || 200, body, headers];
|
||||
}
|
||||
}
|
||||
get headers() {
|
||||
const cache = this[cacheKey];
|
||||
if (cache) {
|
||||
if (!(cache[2] instanceof Headers)) {
|
||||
cache[2] = new Headers(cache[2]);
|
||||
}
|
||||
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.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 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];
|
||||
if (header instanceof Headers) {
|
||||
header = buildOutgoingHttpHeaders(header);
|
||||
}
|
||||
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(() => {
|
||||
incoming.destroy();
|
||||
outgoing.destroy();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
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(() => {
|
||||
incoming.destroy();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
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
|
||||
});
|
||||
551
_node_modules/@hono/node-server/dist/vercel.mjs
generated
vendored
Normal file
551
_node_modules/@hono/node-server/dist/vercel.mjs
generated
vendored
Normal file
@@ -0,0 +1,551 @@
|
||||
// src/listener.ts
|
||||
import { Http2ServerRequest as Http2ServerRequest2 } 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.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) {
|
||||
headers ||= init?.headers || { "content-type": "text/plain; charset=UTF-8" };
|
||||
this[cacheKey] = [init?.status || 200, body, headers];
|
||||
}
|
||||
}
|
||||
get headers() {
|
||||
const cache = this[cacheKey];
|
||||
if (cache) {
|
||||
if (!(cache[2] instanceof Headers)) {
|
||||
cache[2] = new Headers(cache[2]);
|
||||
}
|
||||
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.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 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];
|
||||
if (header instanceof Headers) {
|
||||
header = buildOutgoingHttpHeaders(header);
|
||||
}
|
||||
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(() => {
|
||||
incoming.destroy();
|
||||
outgoing.destroy();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
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(() => {
|
||||
incoming.destroy();
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
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
Normal file
103
_node_modules/@hono/node-server/package.json
generated
Normal file
@@ -0,0 +1,103 @@
|
||||
{
|
||||
"name": "@hono/node-server",
|
||||
"version": "1.19.9",
|
||||
"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"
|
||||
}
|
||||
Reference in New Issue
Block a user