Initial commit
This commit is contained in:
2
index.d.ts
vendored
Normal file
2
index.d.ts
vendored
Normal file
@@ -0,0 +1,2 @@
|
|||||||
|
export {};
|
||||||
|
//# sourceMappingURL=index.d.ts.map
|
||||||
1
index.d.ts.map
Normal file
1
index.d.ts.map
Normal file
@@ -0,0 +1 @@
|
|||||||
|
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["index.ts"],"names":[],"mappings":""}
|
||||||
250
index.js
Normal file
250
index.js
Normal file
@@ -0,0 +1,250 @@
|
|||||||
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||||
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
||||||
|
import axios from "axios";
|
||||||
|
import { z } from "zod";
|
||||||
|
import * as dotenv from "dotenv";
|
||||||
|
dotenv.config();
|
||||||
|
const LISTMONK_URL = process.env.LISTMONK_URL || "https://listmonk.infra.mintel.me";
|
||||||
|
const LISTMONK_USERNAME = process.env.LISTMONK_USERNAME || "mmintel";
|
||||||
|
const LISTMONK_PASSWORD = process.env.LISTMONK_PASSWORD || "Tim300493.";
|
||||||
|
const apiClient = axios.create({
|
||||||
|
baseURL: LISTMONK_URL,
|
||||||
|
auth: {
|
||||||
|
username: LISTMONK_USERNAME,
|
||||||
|
password: LISTMONK_PASSWORD,
|
||||||
|
},
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const server = new McpServer({
|
||||||
|
name: "listmonk-mcp",
|
||||||
|
version: "1.0.0",
|
||||||
|
});
|
||||||
|
// GET /api/subscribers
|
||||||
|
server.tool("listmonk_list_subscribers", {
|
||||||
|
query: z.string().optional().describe("Search query (email or name)"),
|
||||||
|
page: z.number().optional().describe("Page number (default 1)"),
|
||||||
|
per_page: z.number().optional().describe("Results per page (default 20)"),
|
||||||
|
}, async ({ query, page, per_page }) => {
|
||||||
|
try {
|
||||||
|
const response = await apiClient.get("/api/subscribers", {
|
||||||
|
params: { query, page, per_page },
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
content: [{ type: "text", text: JSON.stringify(response.data, null, 2) }],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
return {
|
||||||
|
content: [{ type: "text", text: `Error: ${error.response?.data?.message || error.message}` }],
|
||||||
|
isError: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
// GET /api/subscribers/{id}
|
||||||
|
server.tool("listmonk_get_subscriber", { id: z.number().describe("Subscriber ID") }, async ({ id }) => {
|
||||||
|
try {
|
||||||
|
const response = await apiClient.get(`/api/subscribers/${id}`);
|
||||||
|
return {
|
||||||
|
content: [{ type: "text", text: JSON.stringify(response.data, null, 2) }],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
return {
|
||||||
|
content: [{ type: "text", text: `Error: ${error.response?.data?.message || error.message}` }],
|
||||||
|
isError: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
// POST /api/subscribers
|
||||||
|
server.tool("listmonk_create_subscriber", {
|
||||||
|
email: z.string().email().describe("Subscriber email address"),
|
||||||
|
name: z.string().describe("Subscriber name"),
|
||||||
|
status: z.enum(["enabled", "disabled", "blocklisted"]).describe("Subscriber status"),
|
||||||
|
lists: z.array(z.number()).describe("Array of list IDs to subscribe to"),
|
||||||
|
attribs: z.record(z.string(), z.any()).optional().describe("Optional JSON attributes"),
|
||||||
|
preconfirm_subscriptions: z.boolean().optional().describe("Mark subscriptions as confirmed (opt-in bypassed)"),
|
||||||
|
}, async ({ email, name, status, lists, attribs, preconfirm_subscriptions }) => {
|
||||||
|
try {
|
||||||
|
const response = await apiClient.post("/api/subscribers", {
|
||||||
|
email,
|
||||||
|
name,
|
||||||
|
status,
|
||||||
|
lists,
|
||||||
|
attribs,
|
||||||
|
preconfirm_subscriptions,
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
content: [{ type: "text", text: JSON.stringify(response.data, null, 2) }],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
return {
|
||||||
|
content: [{ type: "text", text: `Error: ${error.response?.data?.message || error.message}` }],
|
||||||
|
isError: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
// PUT /api/subscribers/{id}
|
||||||
|
server.tool("listmonk_update_subscriber", {
|
||||||
|
id: z.number().describe("Subscriber ID"),
|
||||||
|
email: z.string().email().optional().describe("Subscriber email address"),
|
||||||
|
name: z.string().optional().describe("Subscriber name"),
|
||||||
|
status: z.enum(["enabled", "disabled", "blocklisted"]).optional().describe("Subscriber status"),
|
||||||
|
lists: z.array(z.number()).optional().describe("Array of list IDs to subscribe to"),
|
||||||
|
attribs: z.record(z.string(), z.any()).optional().describe("Optional JSON attributes"),
|
||||||
|
}, async ({ id, email, name, status, lists, attribs }) => {
|
||||||
|
try {
|
||||||
|
const data = {};
|
||||||
|
if (email)
|
||||||
|
data.email = email;
|
||||||
|
if (name)
|
||||||
|
data.name = name;
|
||||||
|
if (status)
|
||||||
|
data.status = status;
|
||||||
|
if (lists)
|
||||||
|
data.lists = lists;
|
||||||
|
if (attribs)
|
||||||
|
data.attribs = attribs;
|
||||||
|
const response = await apiClient.put(`/api/subscribers/${id}`, data);
|
||||||
|
return {
|
||||||
|
content: [{ type: "text", text: JSON.stringify(response.data, null, 2) }],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
return {
|
||||||
|
content: [{ type: "text", text: `Error: ${error.response?.data?.message || error.message}` }],
|
||||||
|
isError: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
// GET /api/lists
|
||||||
|
server.tool("listmonk_list_lists", {}, async () => {
|
||||||
|
try {
|
||||||
|
const response = await apiClient.get("/api/lists");
|
||||||
|
return {
|
||||||
|
content: [{ type: "text", text: JSON.stringify(response.data, null, 2) }],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
return {
|
||||||
|
content: [{ type: "text", text: `Error: ${error.response?.data?.message || error.message}` }],
|
||||||
|
isError: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
// POST /api/lists
|
||||||
|
server.tool("listmonk_create_list", {
|
||||||
|
name: z.string().describe("List name"),
|
||||||
|
type: z.enum(["public", "private"]).describe("List type"),
|
||||||
|
optin: z.enum(["single", "double"]).describe("Opt-in type"),
|
||||||
|
description: z.string().optional().describe("Optional description"),
|
||||||
|
tags: z.array(z.string()).optional().describe("Optional tags"),
|
||||||
|
}, async ({ name, type, optin, description, tags }) => {
|
||||||
|
try {
|
||||||
|
const response = await apiClient.post("/api/lists", {
|
||||||
|
name,
|
||||||
|
type,
|
||||||
|
optin,
|
||||||
|
description,
|
||||||
|
tags,
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
content: [{ type: "text", text: JSON.stringify(response.data, null, 2) }],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
return {
|
||||||
|
content: [{ type: "text", text: `Error: ${error.response?.data?.message || error.message}` }],
|
||||||
|
isError: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
// GET /api/campaigns
|
||||||
|
server.tool("listmonk_list_campaigns", {
|
||||||
|
page: z.number().optional().describe("Page number"),
|
||||||
|
per_page: z.number().optional().describe("Results per page"),
|
||||||
|
}, async ({ page, per_page }) => {
|
||||||
|
try {
|
||||||
|
const response = await apiClient.get("/api/campaigns", {
|
||||||
|
params: { page, per_page },
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
content: [{ type: "text", text: JSON.stringify(response.data, null, 2) }],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
return {
|
||||||
|
content: [{ type: "text", text: `Error: ${error.response?.data?.message || error.message}` }],
|
||||||
|
isError: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
// POST /api/campaigns
|
||||||
|
server.tool("listmonk_create_campaign", {
|
||||||
|
name: z.string().describe("Internal campaign name"),
|
||||||
|
subject: z.string().describe("Email subject line"),
|
||||||
|
lists: z.array(z.number()).describe("Array of list IDs to send to"),
|
||||||
|
type: z.enum(["regular", "optin"]).describe("Campaign type"),
|
||||||
|
content_type: z.enum(["richtext", "html", "markdown", "plain"]).describe("Content type"),
|
||||||
|
body: z.string().describe("Email body content"),
|
||||||
|
altbody: z.string().optional().describe("Optional plain text alternative body"),
|
||||||
|
from_email: z.string().optional().describe("From email address"),
|
||||||
|
messenger: z.string().describe("Messenger to use (e.g. 'email')"),
|
||||||
|
template_id: z.number().optional().describe("Template ID to wrap the content"),
|
||||||
|
tags: z.array(z.string()).optional().describe("Optional tags"),
|
||||||
|
}, async (params) => {
|
||||||
|
try {
|
||||||
|
const response = await apiClient.post("/api/campaigns", params);
|
||||||
|
return {
|
||||||
|
content: [{ type: "text", text: JSON.stringify(response.data, null, 2) }],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
return {
|
||||||
|
content: [{ type: "text", text: `Error: ${error.response?.data?.message || error.message}` }],
|
||||||
|
isError: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
// POST /api/tx
|
||||||
|
server.tool("listmonk_send_tx", {
|
||||||
|
subscriber_email: z.string().email().describe("Subscriber email to send to"),
|
||||||
|
subscriber_id: z.number().optional().describe("Subscriber ID (optional, alternative to email)"),
|
||||||
|
template_id: z.number().describe("Template ID to use"),
|
||||||
|
data: z.record(z.string(), z.any()).describe("JSON data for template variables"),
|
||||||
|
messenger: z.string().optional().describe("Messenger type (default 'email')"),
|
||||||
|
}, async ({ subscriber_email, subscriber_id, template_id, data, messenger }) => {
|
||||||
|
try {
|
||||||
|
const payload = {
|
||||||
|
template_id,
|
||||||
|
data,
|
||||||
|
messenger: messenger || "email",
|
||||||
|
};
|
||||||
|
if (subscriber_email)
|
||||||
|
payload.subscriber_email = subscriber_email;
|
||||||
|
if (subscriber_id)
|
||||||
|
payload.subscriber_id = subscriber_id;
|
||||||
|
const response = await apiClient.post("/api/tx", payload);
|
||||||
|
return {
|
||||||
|
content: [{ type: "text", text: JSON.stringify(response.data, null, 2) }],
|
||||||
|
};
|
||||||
|
}
|
||||||
|
catch (error) {
|
||||||
|
return {
|
||||||
|
content: [{ type: "text", text: `Error: ${error.response?.data?.message || error.message}` }],
|
||||||
|
isError: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
});
|
||||||
|
async function main() {
|
||||||
|
const transport = new StdioServerTransport();
|
||||||
|
await server.connect(transport);
|
||||||
|
console.error("Listmonk MCP Server running on stdio");
|
||||||
|
}
|
||||||
|
main().catch((error) => {
|
||||||
|
console.error("Fatal error in main():", error);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
|
//# sourceMappingURL=index.js.map
|
||||||
1
index.js.map
Normal file
1
index.js.map
Normal file
File diff suppressed because one or more lines are too long
286
index.ts
Normal file
286
index.ts
Normal file
@@ -0,0 +1,286 @@
|
|||||||
|
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
||||||
|
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
|
||||||
|
import axios from "axios";
|
||||||
|
import { z } from "zod";
|
||||||
|
import * as dotenv from "dotenv";
|
||||||
|
|
||||||
|
dotenv.config();
|
||||||
|
|
||||||
|
const LISTMONK_URL = process.env.LISTMONK_URL || "https://listmonk.infra.mintel.me";
|
||||||
|
const LISTMONK_USERNAME = process.env.LISTMONK_USERNAME || "mmintel";
|
||||||
|
const LISTMONK_PASSWORD = process.env.LISTMONK_PASSWORD || "Tim300493.";
|
||||||
|
|
||||||
|
const apiClient = axios.create({
|
||||||
|
baseURL: LISTMONK_URL,
|
||||||
|
auth: {
|
||||||
|
username: LISTMONK_USERNAME,
|
||||||
|
password: LISTMONK_PASSWORD,
|
||||||
|
},
|
||||||
|
headers: {
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const server = new McpServer({
|
||||||
|
name: "listmonk-mcp",
|
||||||
|
version: "1.0.0",
|
||||||
|
});
|
||||||
|
|
||||||
|
// GET /api/subscribers
|
||||||
|
server.tool(
|
||||||
|
"listmonk_list_subscribers",
|
||||||
|
{
|
||||||
|
query: z.string().optional().describe("Search query (email or name)"),
|
||||||
|
page: z.number().optional().describe("Page number (default 1)"),
|
||||||
|
per_page: z.number().optional().describe("Results per page (default 20)"),
|
||||||
|
},
|
||||||
|
async ({ query, page, per_page }) => {
|
||||||
|
try {
|
||||||
|
const response = await apiClient.get("/api/subscribers", {
|
||||||
|
params: { query, page, per_page },
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
content: [{ type: "text", text: JSON.stringify(response.data, null, 2) }],
|
||||||
|
};
|
||||||
|
} catch (error: any) {
|
||||||
|
return {
|
||||||
|
content: [{ type: "text", text: `Error: ${error.response?.data?.message || error.message}` }],
|
||||||
|
isError: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
// GET /api/subscribers/{id}
|
||||||
|
server.tool(
|
||||||
|
"listmonk_get_subscriber",
|
||||||
|
{ id: z.number().describe("Subscriber ID") },
|
||||||
|
async ({ id }) => {
|
||||||
|
try {
|
||||||
|
const response = await apiClient.get(`/api/subscribers/${id}`);
|
||||||
|
return {
|
||||||
|
content: [{ type: "text", text: JSON.stringify(response.data, null, 2) }],
|
||||||
|
};
|
||||||
|
} catch (error: any) {
|
||||||
|
return {
|
||||||
|
content: [{ type: "text", text: `Error: ${error.response?.data?.message || error.message}` }],
|
||||||
|
isError: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
// POST /api/subscribers
|
||||||
|
server.tool(
|
||||||
|
"listmonk_create_subscriber",
|
||||||
|
{
|
||||||
|
email: z.string().email().describe("Subscriber email address"),
|
||||||
|
name: z.string().describe("Subscriber name"),
|
||||||
|
status: z.enum(["enabled", "disabled", "blocklisted"]).describe("Subscriber status"),
|
||||||
|
lists: z.array(z.number()).describe("Array of list IDs to subscribe to"),
|
||||||
|
attribs: z.record(z.string(), z.any()).optional().describe("Optional JSON attributes"),
|
||||||
|
preconfirm_subscriptions: z.boolean().optional().describe("Mark subscriptions as confirmed (opt-in bypassed)"),
|
||||||
|
},
|
||||||
|
async ({ email, name, status, lists, attribs, preconfirm_subscriptions }) => {
|
||||||
|
try {
|
||||||
|
const response = await apiClient.post("/api/subscribers", {
|
||||||
|
email,
|
||||||
|
name,
|
||||||
|
status,
|
||||||
|
lists,
|
||||||
|
attribs,
|
||||||
|
preconfirm_subscriptions,
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
content: [{ type: "text", text: JSON.stringify(response.data, null, 2) }],
|
||||||
|
};
|
||||||
|
} catch (error: any) {
|
||||||
|
return {
|
||||||
|
content: [{ type: "text", text: `Error: ${error.response?.data?.message || error.message}` }],
|
||||||
|
isError: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
// PUT /api/subscribers/{id}
|
||||||
|
server.tool(
|
||||||
|
"listmonk_update_subscriber",
|
||||||
|
{
|
||||||
|
id: z.number().describe("Subscriber ID"),
|
||||||
|
email: z.string().email().optional().describe("Subscriber email address"),
|
||||||
|
name: z.string().optional().describe("Subscriber name"),
|
||||||
|
status: z.enum(["enabled", "disabled", "blocklisted"]).optional().describe("Subscriber status"),
|
||||||
|
lists: z.array(z.number()).optional().describe("Array of list IDs to subscribe to"),
|
||||||
|
attribs: z.record(z.string(), z.any()).optional().describe("Optional JSON attributes"),
|
||||||
|
},
|
||||||
|
async ({ id, email, name, status, lists, attribs }) => {
|
||||||
|
try {
|
||||||
|
const data: any = {};
|
||||||
|
if (email) data.email = email;
|
||||||
|
if (name) data.name = name;
|
||||||
|
if (status) data.status = status;
|
||||||
|
if (lists) data.lists = lists;
|
||||||
|
if (attribs) data.attribs = attribs;
|
||||||
|
|
||||||
|
const response = await apiClient.put(`/api/subscribers/${id}`, data);
|
||||||
|
return {
|
||||||
|
content: [{ type: "text", text: JSON.stringify(response.data, null, 2) }],
|
||||||
|
};
|
||||||
|
} catch (error: any) {
|
||||||
|
return {
|
||||||
|
content: [{ type: "text", text: `Error: ${error.response?.data?.message || error.message}` }],
|
||||||
|
isError: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
// GET /api/lists
|
||||||
|
server.tool(
|
||||||
|
"listmonk_list_lists",
|
||||||
|
{},
|
||||||
|
async () => {
|
||||||
|
try {
|
||||||
|
const response = await apiClient.get("/api/lists");
|
||||||
|
return {
|
||||||
|
content: [{ type: "text", text: JSON.stringify(response.data, null, 2) }],
|
||||||
|
};
|
||||||
|
} catch (error: any) {
|
||||||
|
return {
|
||||||
|
content: [{ type: "text", text: `Error: ${error.response?.data?.message || error.message}` }],
|
||||||
|
isError: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
// POST /api/lists
|
||||||
|
server.tool(
|
||||||
|
"listmonk_create_list",
|
||||||
|
{
|
||||||
|
name: z.string().describe("List name"),
|
||||||
|
type: z.enum(["public", "private"]).describe("List type"),
|
||||||
|
optin: z.enum(["single", "double"]).describe("Opt-in type"),
|
||||||
|
description: z.string().optional().describe("Optional description"),
|
||||||
|
tags: z.array(z.string()).optional().describe("Optional tags"),
|
||||||
|
},
|
||||||
|
async ({ name, type, optin, description, tags }) => {
|
||||||
|
try {
|
||||||
|
const response = await apiClient.post("/api/lists", {
|
||||||
|
name,
|
||||||
|
type,
|
||||||
|
optin,
|
||||||
|
description,
|
||||||
|
tags,
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
content: [{ type: "text", text: JSON.stringify(response.data, null, 2) }],
|
||||||
|
};
|
||||||
|
} catch (error: any) {
|
||||||
|
return {
|
||||||
|
content: [{ type: "text", text: `Error: ${error.response?.data?.message || error.message}` }],
|
||||||
|
isError: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
// GET /api/campaigns
|
||||||
|
server.tool(
|
||||||
|
"listmonk_list_campaigns",
|
||||||
|
{
|
||||||
|
page: z.number().optional().describe("Page number"),
|
||||||
|
per_page: z.number().optional().describe("Results per page"),
|
||||||
|
},
|
||||||
|
async ({ page, per_page }) => {
|
||||||
|
try {
|
||||||
|
const response = await apiClient.get("/api/campaigns", {
|
||||||
|
params: { page, per_page },
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
content: [{ type: "text", text: JSON.stringify(response.data, null, 2) }],
|
||||||
|
};
|
||||||
|
} catch (error: any) {
|
||||||
|
return {
|
||||||
|
content: [{ type: "text", text: `Error: ${error.response?.data?.message || error.message}` }],
|
||||||
|
isError: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
// POST /api/campaigns
|
||||||
|
server.tool(
|
||||||
|
"listmonk_create_campaign",
|
||||||
|
{
|
||||||
|
name: z.string().describe("Internal campaign name"),
|
||||||
|
subject: z.string().describe("Email subject line"),
|
||||||
|
lists: z.array(z.number()).describe("Array of list IDs to send to"),
|
||||||
|
type: z.enum(["regular", "optin"]).describe("Campaign type"),
|
||||||
|
content_type: z.enum(["richtext", "html", "markdown", "plain"]).describe("Content type"),
|
||||||
|
body: z.string().describe("Email body content"),
|
||||||
|
altbody: z.string().optional().describe("Optional plain text alternative body"),
|
||||||
|
from_email: z.string().optional().describe("From email address"),
|
||||||
|
messenger: z.string().describe("Messenger to use (e.g. 'email')"),
|
||||||
|
template_id: z.number().optional().describe("Template ID to wrap the content"),
|
||||||
|
tags: z.array(z.string()).optional().describe("Optional tags"),
|
||||||
|
},
|
||||||
|
async (params) => {
|
||||||
|
try {
|
||||||
|
const response = await apiClient.post("/api/campaigns", params);
|
||||||
|
return {
|
||||||
|
content: [{ type: "text", text: JSON.stringify(response.data, null, 2) }],
|
||||||
|
};
|
||||||
|
} catch (error: any) {
|
||||||
|
return {
|
||||||
|
content: [{ type: "text", text: `Error: ${error.response?.data?.message || error.message}` }],
|
||||||
|
isError: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
// POST /api/tx
|
||||||
|
server.tool(
|
||||||
|
"listmonk_send_tx",
|
||||||
|
{
|
||||||
|
subscriber_email: z.string().email().describe("Subscriber email to send to"),
|
||||||
|
subscriber_id: z.number().optional().describe("Subscriber ID (optional, alternative to email)"),
|
||||||
|
template_id: z.number().describe("Template ID to use"),
|
||||||
|
data: z.record(z.string(), z.any()).describe("JSON data for template variables"),
|
||||||
|
messenger: z.string().optional().describe("Messenger type (default 'email')"),
|
||||||
|
},
|
||||||
|
async ({ subscriber_email, subscriber_id, template_id, data, messenger }) => {
|
||||||
|
try {
|
||||||
|
const payload: any = {
|
||||||
|
template_id,
|
||||||
|
data,
|
||||||
|
messenger: messenger || "email",
|
||||||
|
};
|
||||||
|
if (subscriber_email) payload.subscriber_email = subscriber_email;
|
||||||
|
if (subscriber_id) payload.subscriber_id = subscriber_id;
|
||||||
|
|
||||||
|
const response = await apiClient.post("/api/tx", payload);
|
||||||
|
return {
|
||||||
|
content: [{ type: "text", text: JSON.stringify(response.data, null, 2) }],
|
||||||
|
};
|
||||||
|
} catch (error: any) {
|
||||||
|
return {
|
||||||
|
content: [{ type: "text", text: `Error: ${error.response?.data?.message || error.message}` }],
|
||||||
|
isError: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const transport = new StdioServerTransport();
|
||||||
|
await server.connect(transport);
|
||||||
|
console.error("Listmonk MCP Server running on stdio");
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch((error) => {
|
||||||
|
console.error("Fatal error in main():", error);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
1
node_modules/.bin/acorn
generated
vendored
Symbolic link
1
node_modules/.bin/acorn
generated
vendored
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../acorn/bin/acorn
|
||||||
1
node_modules/.bin/node-which
generated
vendored
Symbolic link
1
node_modules/.bin/node-which
generated
vendored
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../which/bin/node-which
|
||||||
1
node_modules/.bin/ts-node
generated
vendored
Symbolic link
1
node_modules/.bin/ts-node
generated
vendored
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../ts-node/dist/bin.js
|
||||||
1
node_modules/.bin/ts-node-cwd
generated
vendored
Symbolic link
1
node_modules/.bin/ts-node-cwd
generated
vendored
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../ts-node/dist/bin-cwd.js
|
||||||
1
node_modules/.bin/ts-node-esm
generated
vendored
Symbolic link
1
node_modules/.bin/ts-node-esm
generated
vendored
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../ts-node/dist/bin-esm.js
|
||||||
1
node_modules/.bin/ts-node-script
generated
vendored
Symbolic link
1
node_modules/.bin/ts-node-script
generated
vendored
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../ts-node/dist/bin-script.js
|
||||||
1
node_modules/.bin/ts-node-transpile-only
generated
vendored
Symbolic link
1
node_modules/.bin/ts-node-transpile-only
generated
vendored
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../ts-node/dist/bin-transpile.js
|
||||||
1
node_modules/.bin/ts-script
generated
vendored
Symbolic link
1
node_modules/.bin/ts-script
generated
vendored
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../ts-node/dist/bin-script-deprecated.js
|
||||||
1
node_modules/.bin/tsc
generated
vendored
Symbolic link
1
node_modules/.bin/tsc
generated
vendored
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../typescript/bin/tsc
|
||||||
1
node_modules/.bin/tsserver
generated
vendored
Symbolic link
1
node_modules/.bin/tsserver
generated
vendored
Symbolic link
@@ -0,0 +1 @@
|
|||||||
|
../typescript/bin/tsserver
|
||||||
1538
node_modules/.package-lock.json
generated
vendored
Normal file
1538
node_modules/.package-lock.json
generated
vendored
Normal file
File diff suppressed because it is too large
Load Diff
21
node_modules/@cspotcode/source-map-support/LICENSE.md
generated
vendored
Normal file
21
node_modules/@cspotcode/source-map-support/LICENSE.md
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
The MIT License (MIT)
|
||||||
|
|
||||||
|
Copyright (c) 2014 Evan Wallace
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
289
node_modules/@cspotcode/source-map-support/README.md
generated
vendored
Normal file
289
node_modules/@cspotcode/source-map-support/README.md
generated
vendored
Normal file
@@ -0,0 +1,289 @@
|
|||||||
|
# Source Map Support
|
||||||
|
|
||||||
|
[](https://npmjs.org/package/@cspotcode/source-map-support)
|
||||||
|
[](https://npmjs.org/package/@cspotcode/source-map-support)
|
||||||
|
[](https://github.com/cspotcode/node-source-map-support/actions?query=workflow%3A%22Continuous+Integration%22)
|
||||||
|
|
||||||
|
This module provides source map support for stack traces in node via the [V8 stack trace API](https://github.com/v8/v8/wiki/Stack-Trace-API). It uses the [source-map](https://github.com/mozilla/source-map) module to replace the paths and line numbers of source-mapped files with their original paths and line numbers. The output mimics node's stack trace format with the goal of making every compile-to-JS language more of a first-class citizen. Source maps are completely general (not specific to any one language) so you can use source maps with multiple compile-to-JS languages in the same node process.
|
||||||
|
|
||||||
|
## Installation and Usage
|
||||||
|
|
||||||
|
#### Node support
|
||||||
|
|
||||||
|
```
|
||||||
|
$ npm install @cspotcode/source-map-support
|
||||||
|
```
|
||||||
|
|
||||||
|
Source maps can be generated using libraries such as [source-map-index-generator](https://github.com/twolfson/source-map-index-generator). Once you have a valid source map, place a source mapping comment somewhere in the file (usually done automatically or with an option by your transpiler):
|
||||||
|
|
||||||
|
```
|
||||||
|
//# sourceMappingURL=path/to/source.map
|
||||||
|
```
|
||||||
|
|
||||||
|
If multiple sourceMappingURL comments exist in one file, the last sourceMappingURL comment will be
|
||||||
|
respected (e.g. if a file mentions the comment in code, or went through multiple transpilers).
|
||||||
|
The path should either be absolute or relative to the compiled file.
|
||||||
|
|
||||||
|
From here you have two options.
|
||||||
|
|
||||||
|
##### CLI Usage
|
||||||
|
|
||||||
|
```bash
|
||||||
|
node -r @cspotcode/source-map-support/register compiled.js
|
||||||
|
# Or to enable hookRequire
|
||||||
|
node -r @cspotcode/source-map-support/register-hook-require compiled.js
|
||||||
|
```
|
||||||
|
|
||||||
|
##### Programmatic Usage
|
||||||
|
|
||||||
|
Put the following line at the top of the compiled file.
|
||||||
|
|
||||||
|
```js
|
||||||
|
require('@cspotcode/source-map-support').install();
|
||||||
|
```
|
||||||
|
|
||||||
|
It is also possible to install the source map support directly by
|
||||||
|
requiring the `register` module which can be handy with ES6:
|
||||||
|
|
||||||
|
```js
|
||||||
|
import '@cspotcode/source-map-support/register'
|
||||||
|
|
||||||
|
// Instead of:
|
||||||
|
import sourceMapSupport from '@cspotcode/source-map-support'
|
||||||
|
sourceMapSupport.install()
|
||||||
|
```
|
||||||
|
Note: if you're using babel-register, it includes source-map-support already.
|
||||||
|
|
||||||
|
It is also very useful with Mocha:
|
||||||
|
|
||||||
|
```
|
||||||
|
$ mocha --require @cspotcode/source-map-support/register tests/
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Browser support
|
||||||
|
|
||||||
|
This library also works in Chrome. While the DevTools console already supports source maps, the V8 engine doesn't and `Error.prototype.stack` will be incorrect without this library. Everything will just work if you deploy your source files using [browserify](http://browserify.org/). Just make sure to pass the `--debug` flag to the browserify command so your source maps are included in the bundled code.
|
||||||
|
|
||||||
|
This library also works if you use another build process or just include the source files directly. In this case, include the file `browser-source-map-support.js` in your page and call `sourceMapSupport.install()`. It contains the whole library already bundled for the browser using browserify.
|
||||||
|
|
||||||
|
```html
|
||||||
|
<script src="browser-source-map-support.js"></script>
|
||||||
|
<script>sourceMapSupport.install();</script>
|
||||||
|
```
|
||||||
|
|
||||||
|
This library also works if you use AMD (Asynchronous Module Definition), which is used in tools like [RequireJS](http://requirejs.org/). Just list `browser-source-map-support` as a dependency:
|
||||||
|
|
||||||
|
```html
|
||||||
|
<script>
|
||||||
|
define(['browser-source-map-support'], function(sourceMapSupport) {
|
||||||
|
sourceMapSupport.install();
|
||||||
|
});
|
||||||
|
</script>
|
||||||
|
```
|
||||||
|
|
||||||
|
## Options
|
||||||
|
|
||||||
|
This module installs two things: a change to the `stack` property on `Error` objects and a handler for uncaught exceptions that mimics node's default exception handler (the handler can be seen in the demos below). You may want to disable the handler if you have your own uncaught exception handler. This can be done by passing an argument to the installer:
|
||||||
|
|
||||||
|
```js
|
||||||
|
require('@cspotcode/source-map-support').install({
|
||||||
|
handleUncaughtExceptions: false
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
This module loads source maps from the filesystem by default. You can provide alternate loading behavior through a callback as shown below. For example, [Meteor](https://github.com/meteor) keeps all source maps cached in memory to avoid disk access.
|
||||||
|
|
||||||
|
```js
|
||||||
|
require('@cspotcode/source-map-support').install({
|
||||||
|
retrieveSourceMap: function(source) {
|
||||||
|
if (source === 'compiled.js') {
|
||||||
|
return {
|
||||||
|
url: 'original.js',
|
||||||
|
map: fs.readFileSync('compiled.js.map', 'utf8')
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
The module will by default assume a browser environment if XMLHttpRequest and window are defined. If either of these do not exist it will instead assume a node environment.
|
||||||
|
In some rare cases, e.g. when running a browser emulation and where both variables are also set, you can explictly specify the environment to be either 'browser' or 'node'.
|
||||||
|
|
||||||
|
```js
|
||||||
|
require('@cspotcode/source-map-support').install({
|
||||||
|
environment: 'node'
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
To support files with inline source maps, the `hookRequire` options can be specified, which will monitor all source files for inline source maps.
|
||||||
|
|
||||||
|
|
||||||
|
```js
|
||||||
|
require('@cspotcode/source-map-support').install({
|
||||||
|
hookRequire: true
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
This monkey patches the `require` module loading chain, so is not enabled by default and is not recommended for any sort of production usage.
|
||||||
|
|
||||||
|
## Demos
|
||||||
|
|
||||||
|
#### Basic Demo
|
||||||
|
|
||||||
|
original.js:
|
||||||
|
|
||||||
|
```js
|
||||||
|
throw new Error('test'); // This is the original code
|
||||||
|
```
|
||||||
|
|
||||||
|
compiled.js:
|
||||||
|
|
||||||
|
```js
|
||||||
|
require('@cspotcode/source-map-support').install();
|
||||||
|
|
||||||
|
throw new Error('test'); // This is the compiled code
|
||||||
|
// The next line defines the sourceMapping.
|
||||||
|
//# sourceMappingURL=compiled.js.map
|
||||||
|
```
|
||||||
|
|
||||||
|
compiled.js.map:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"version": 3,
|
||||||
|
"file": "compiled.js",
|
||||||
|
"sources": ["original.js"],
|
||||||
|
"names": [],
|
||||||
|
"mappings": ";;AAAA,MAAM,IAAI"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Run compiled.js using node (notice how the stack trace uses original.js instead of compiled.js):
|
||||||
|
|
||||||
|
```
|
||||||
|
$ node compiled.js
|
||||||
|
|
||||||
|
original.js:1
|
||||||
|
throw new Error('test'); // This is the original code
|
||||||
|
^
|
||||||
|
Error: test
|
||||||
|
at Object.<anonymous> (original.js:1:7)
|
||||||
|
at Module._compile (module.js:456:26)
|
||||||
|
at Object.Module._extensions..js (module.js:474:10)
|
||||||
|
at Module.load (module.js:356:32)
|
||||||
|
at Function.Module._load (module.js:312:12)
|
||||||
|
at Function.Module.runMain (module.js:497:10)
|
||||||
|
at startup (node.js:119:16)
|
||||||
|
at node.js:901:3
|
||||||
|
```
|
||||||
|
|
||||||
|
#### TypeScript Demo
|
||||||
|
|
||||||
|
demo.ts:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
declare function require(name: string);
|
||||||
|
require('@cspotcode/source-map-support').install();
|
||||||
|
class Foo {
|
||||||
|
constructor() { this.bar(); }
|
||||||
|
bar() { throw new Error('this is a demo'); }
|
||||||
|
}
|
||||||
|
new Foo();
|
||||||
|
```
|
||||||
|
|
||||||
|
Compile and run the file using the TypeScript compiler from the terminal:
|
||||||
|
|
||||||
|
```
|
||||||
|
$ npm install source-map-support typescript
|
||||||
|
$ node_modules/typescript/bin/tsc -sourcemap demo.ts
|
||||||
|
$ node demo.js
|
||||||
|
|
||||||
|
demo.ts:5
|
||||||
|
bar() { throw new Error('this is a demo'); }
|
||||||
|
^
|
||||||
|
Error: this is a demo
|
||||||
|
at Foo.bar (demo.ts:5:17)
|
||||||
|
at new Foo (demo.ts:4:24)
|
||||||
|
at Object.<anonymous> (demo.ts:7:1)
|
||||||
|
at Module._compile (module.js:456:26)
|
||||||
|
at Object.Module._extensions..js (module.js:474:10)
|
||||||
|
at Module.load (module.js:356:32)
|
||||||
|
at Function.Module._load (module.js:312:12)
|
||||||
|
at Function.Module.runMain (module.js:497:10)
|
||||||
|
at startup (node.js:119:16)
|
||||||
|
at node.js:901:3
|
||||||
|
```
|
||||||
|
|
||||||
|
There is also the option to use `-r source-map-support/register` with typescript, without the need add the `require('@cspotcode/source-map-support').install()` in the code base:
|
||||||
|
|
||||||
|
```
|
||||||
|
$ npm install source-map-support typescript
|
||||||
|
$ node_modules/typescript/bin/tsc -sourcemap demo.ts
|
||||||
|
$ node -r source-map-support/register demo.js
|
||||||
|
|
||||||
|
demo.ts:5
|
||||||
|
bar() { throw new Error('this is a demo'); }
|
||||||
|
^
|
||||||
|
Error: this is a demo
|
||||||
|
at Foo.bar (demo.ts:5:17)
|
||||||
|
at new Foo (demo.ts:4:24)
|
||||||
|
at Object.<anonymous> (demo.ts:7:1)
|
||||||
|
at Module._compile (module.js:456:26)
|
||||||
|
at Object.Module._extensions..js (module.js:474:10)
|
||||||
|
at Module.load (module.js:356:32)
|
||||||
|
at Function.Module._load (module.js:312:12)
|
||||||
|
at Function.Module.runMain (module.js:497:10)
|
||||||
|
at startup (node.js:119:16)
|
||||||
|
at node.js:901:3
|
||||||
|
```
|
||||||
|
|
||||||
|
#### CoffeeScript Demo
|
||||||
|
|
||||||
|
demo.coffee:
|
||||||
|
|
||||||
|
```coffee
|
||||||
|
require('@cspotcode/source-map-support').install()
|
||||||
|
foo = ->
|
||||||
|
bar = -> throw new Error 'this is a demo'
|
||||||
|
bar()
|
||||||
|
foo()
|
||||||
|
```
|
||||||
|
|
||||||
|
Compile and run the file using the CoffeeScript compiler from the terminal:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
$ npm install @cspotcode/source-map-support coffeescript
|
||||||
|
$ node_modules/.bin/coffee --map --compile demo.coffee
|
||||||
|
$ node demo.js
|
||||||
|
|
||||||
|
demo.coffee:3
|
||||||
|
bar = -> throw new Error 'this is a demo'
|
||||||
|
^
|
||||||
|
Error: this is a demo
|
||||||
|
at bar (demo.coffee:3:22)
|
||||||
|
at foo (demo.coffee:4:3)
|
||||||
|
at Object.<anonymous> (demo.coffee:5:1)
|
||||||
|
at Object.<anonymous> (demo.coffee:1:1)
|
||||||
|
at Module._compile (module.js:456:26)
|
||||||
|
at Object.Module._extensions..js (module.js:474:10)
|
||||||
|
at Module.load (module.js:356:32)
|
||||||
|
at Function.Module._load (module.js:312:12)
|
||||||
|
at Function.Module.runMain (module.js:497:10)
|
||||||
|
at startup (node.js:119:16)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Tests
|
||||||
|
|
||||||
|
This repo contains both automated tests for node and manual tests for the browser. The automated tests can be run using mocha (type `mocha` in the root directory). To run the manual tests:
|
||||||
|
|
||||||
|
* Build the tests using `build.js`
|
||||||
|
* Launch the HTTP server (`npm run serve-tests`) and visit
|
||||||
|
* http://127.0.0.1:1336/amd-test
|
||||||
|
* http://127.0.0.1:1336/browser-test
|
||||||
|
* http://127.0.0.1:1336/browserify-test - **Currently not working** due to a bug with browserify (see [pull request #66](https://github.com/evanw/node-source-map-support/pull/66) for details).
|
||||||
|
* For `header-test`, run `server.js` inside that directory and visit http://127.0.0.1:1337/
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
This code is available under the [MIT license](http://opensource.org/licenses/MIT).
|
||||||
114
node_modules/@cspotcode/source-map-support/browser-source-map-support.js
generated
vendored
Normal file
114
node_modules/@cspotcode/source-map-support/browser-source-map-support.js
generated
vendored
Normal file
@@ -0,0 +1,114 @@
|
|||||||
|
/*
|
||||||
|
* Support for source maps in V8 stack traces
|
||||||
|
* https://github.com/evanw/node-source-map-support
|
||||||
|
*/
|
||||||
|
/*
|
||||||
|
The buffer module from node.js, for the browser.
|
||||||
|
|
||||||
|
@author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
|
||||||
|
license MIT
|
||||||
|
*/
|
||||||
|
(this.define||function(R,U){this.sourceMapSupport=U()})("browser-source-map-support",function(R){(function e(C,J,A){function p(f,c){if(!J[f]){if(!C[f]){var l="function"==typeof require&&require;if(!c&&l)return l(f,!0);if(t)return t(f,!0);throw Error("Cannot find module '"+f+"'");}l=J[f]={exports:{}};C[f][0].call(l.exports,function(q){var r=C[f][1][q];return p(r?r:q)},l,l.exports,e,C,J,A)}return J[f].exports}for(var t="function"==typeof require&&require,m=0;m<A.length;m++)p(A[m]);return p})({1:[function(C,
|
||||||
|
J,A){R=C("./source-map-support")},{"./source-map-support":21}],2:[function(C,J,A){(function(e){function p(m){m=m.charCodeAt(0);if(43===m)return 62;if(47===m)return 63;if(48>m)return-1;if(58>m)return m-48+52;if(91>m)return m-65;if(123>m)return m-97+26}var t="undefined"!==typeof Uint8Array?Uint8Array:Array;e.toByteArray=function(m){function f(d){q[k++]=d}if(0<m.length%4)throw Error("Invalid string. Length must be a multiple of 4");var c=m.length;var l="="===m.charAt(c-2)?2:"="===m.charAt(c-1)?1:0;var q=
|
||||||
|
new t(3*m.length/4-l);var r=0<l?m.length-4:m.length;var k=0;for(c=0;c<r;c+=4){var u=p(m.charAt(c))<<18|p(m.charAt(c+1))<<12|p(m.charAt(c+2))<<6|p(m.charAt(c+3));f((u&16711680)>>16);f((u&65280)>>8);f(u&255)}2===l?(u=p(m.charAt(c))<<2|p(m.charAt(c+1))>>4,f(u&255)):1===l&&(u=p(m.charAt(c))<<10|p(m.charAt(c+1))<<4|p(m.charAt(c+2))>>2,f(u>>8&255),f(u&255));return q};e.fromByteArray=function(m){var f=m.length%3,c="",l;var q=0;for(l=m.length-f;q<l;q+=3){var r=(m[q]<<16)+(m[q+1]<<8)+m[q+2];r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>
|
||||||
|
18&63)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>12&63)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>6&63)+"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r&63);c+=r}switch(f){case 1:r=m[m.length-1];c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>2);c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r<<4&63);c+="==";break;case 2:r=(m[m.length-2]<<8)+
|
||||||
|
m[m.length-1],c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>10),c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r>>4&63),c+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(r<<2&63),c+="="}return c}})("undefined"===typeof A?this.base64js={}:A)},{}],3:[function(C,J,A){},{}],4:[function(C,J,A){(function(e){var p=Object.prototype.toString,t="function"===typeof e.alloc&&"function"===typeof e.allocUnsafe&&"function"===
|
||||||
|
typeof e.from;J.exports=function(m,f,c){if("number"===typeof m)throw new TypeError('"value" argument must not be a number');if("ArrayBuffer"===p.call(m).slice(8,-1)){f>>>=0;var l=m.byteLength-f;if(0>l)throw new RangeError("'offset' is out of bounds");if(void 0===c)c=l;else if(c>>>=0,c>l)throw new RangeError("'length' is out of bounds");return t?e.from(m.slice(f,f+c)):new e(new Uint8Array(m.slice(f,f+c)))}if("string"===typeof m){c=f;if("string"!==typeof c||""===c)c="utf8";if(!e.isEncoding(c))throw new TypeError('"encoding" must be a valid string encoding');
|
||||||
|
return t?e.from(m,c):new e(m,c)}return t?e.from(m):new e(m)}}).call(this,C("buffer").Buffer)},{buffer:5}],5:[function(C,J,A){function e(a,b,h){if(!(this instanceof e))return new e(a,b,h);var w=typeof a;if("number"===w)var y=0<a?a>>>0:0;else if("string"===w){if("base64"===b)for(a=(a.trim?a.trim():a.replace(/^\s+|\s+$/g,"")).replace(L,"");0!==a.length%4;)a+="=";y=e.byteLength(a,b)}else if("object"===w&&null!==a)"Buffer"===a.type&&z(a.data)&&(a=a.data),y=0<+a.length?Math.floor(+a.length):0;else throw new TypeError("must start with number, buffer, array or string");
|
||||||
|
if(this.length>G)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+G.toString(16)+" bytes");if(e.TYPED_ARRAY_SUPPORT)var I=e._augment(new Uint8Array(y));else I=this,I.length=y,I._isBuffer=!0;if(e.TYPED_ARRAY_SUPPORT&&"number"===typeof a.byteLength)I._set(a);else{var K=a;if(z(K)||e.isBuffer(K)||K&&"object"===typeof K&&"number"===typeof K.length)if(e.isBuffer(a))for(b=0;b<y;b++)I[b]=a.readUInt8(b);else for(b=0;b<y;b++)I[b]=(a[b]%256+256)%256;else if("string"===w)I.write(a,
|
||||||
|
0,b);else if("number"===w&&!e.TYPED_ARRAY_SUPPORT&&!h)for(b=0;b<y;b++)I[b]=0}return I}function p(a,b,h){var w="";for(h=Math.min(a.length,h);b<h;b++)w+=String.fromCharCode(a[b]);return w}function t(a,b,h){if(0!==a%1||0>a)throw new RangeError("offset is not uint");if(a+b>h)throw new RangeError("Trying to access beyond buffer length");}function m(a,b,h,w,y,I){if(!e.isBuffer(a))throw new TypeError("buffer must be a Buffer instance");if(b>y||b<I)throw new TypeError("value is out of bounds");if(h+w>a.length)throw new TypeError("index out of range");
|
||||||
|
}function f(a,b,h,w){0>b&&(b=65535+b+1);for(var y=0,I=Math.min(a.length-h,2);y<I;y++)a[h+y]=(b&255<<8*(w?y:1-y))>>>8*(w?y:1-y)}function c(a,b,h,w){0>b&&(b=4294967295+b+1);for(var y=0,I=Math.min(a.length-h,4);y<I;y++)a[h+y]=b>>>8*(w?y:3-y)&255}function l(a,b,h,w,y,I){if(b>y||b<I)throw new TypeError("value is out of bounds");if(h+w>a.length)throw new TypeError("index out of range");}function q(a,b,h,w,y){y||l(a,b,h,4,3.4028234663852886E38,-3.4028234663852886E38);v.write(a,b,h,w,23,4);return h+4}function r(a,
|
||||||
|
b,h,w,y){y||l(a,b,h,8,1.7976931348623157E308,-1.7976931348623157E308);v.write(a,b,h,w,52,8);return h+8}function k(a){for(var b=[],h=0;h<a.length;h++){var w=a.charCodeAt(h);if(127>=w)b.push(w);else{var y=h;55296<=w&&57343>=w&&h++;w=encodeURIComponent(a.slice(y,h+1)).substr(1).split("%");for(y=0;y<w.length;y++)b.push(parseInt(w[y],16))}}return b}function u(a){for(var b=[],h=0;h<a.length;h++)b.push(a.charCodeAt(h)&255);return b}function d(a,b,h,w,y){y&&(w-=w%y);for(y=0;y<w&&!(y+h>=b.length||y>=a.length);y++)b[y+
|
||||||
|
h]=a[y];return y}function g(a){try{return decodeURIComponent(a)}catch(b){return String.fromCharCode(65533)}}var n=C("base64-js"),v=C("ieee754"),z=C("is-array");A.Buffer=e;A.SlowBuffer=e;A.INSPECT_MAX_BYTES=50;e.poolSize=8192;var G=1073741823;e.TYPED_ARRAY_SUPPORT=function(){try{var a=new ArrayBuffer(0),b=new Uint8Array(a);b.foo=function(){return 42};return 42===b.foo()&&"function"===typeof b.subarray&&0===(new Uint8Array(1)).subarray(1,1).byteLength}catch(h){return!1}}();e.isBuffer=function(a){return!(null==
|
||||||
|
a||!a._isBuffer)};e.compare=function(a,b){if(!e.isBuffer(a)||!e.isBuffer(b))throw new TypeError("Arguments must be Buffers");for(var h=a.length,w=b.length,y=0,I=Math.min(h,w);y<I&&a[y]===b[y];y++);y!==I&&(h=a[y],w=b[y]);return h<w?-1:w<h?1:0};e.isEncoding=function(a){switch(String(a).toLowerCase()){case "hex":case "utf8":case "utf-8":case "ascii":case "binary":case "base64":case "raw":case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":return!0;default:return!1}};e.concat=function(a,b){if(!z(a))throw new TypeError("Usage: Buffer.concat(list[, length])");
|
||||||
|
if(0===a.length)return new e(0);if(1===a.length)return a[0];var h;if(void 0===b)for(h=b=0;h<a.length;h++)b+=a[h].length;var w=new e(b),y=0;for(h=0;h<a.length;h++){var I=a[h];I.copy(w,y);y+=I.length}return w};e.byteLength=function(a,b){a+="";switch(b||"utf8"){case "ascii":case "binary":case "raw":var h=a.length;break;case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":h=2*a.length;break;case "hex":h=a.length>>>1;break;case "utf8":case "utf-8":h=k(a).length;break;case "base64":h=n.toByteArray(a).length;
|
||||||
|
break;default:h=a.length}return h};e.prototype.length=void 0;e.prototype.parent=void 0;e.prototype.toString=function(a,b,h){var w=!1;b>>>=0;h=void 0===h||Infinity===h?this.length:h>>>0;a||(a="utf8");0>b&&(b=0);h>this.length&&(h=this.length);if(h<=b)return"";for(;;)switch(a){case "hex":a=b;b=h;h=this.length;if(!a||0>a)a=0;if(!b||0>b||b>h)b=h;w="";for(h=a;h<b;h++)a=w,w=this[h],w=16>w?"0"+w.toString(16):w.toString(16),w=a+w;return w;case "utf8":case "utf-8":w=a="";for(h=Math.min(this.length,h);b<h;b++)127>=
|
||||||
|
this[b]?(a+=g(w)+String.fromCharCode(this[b]),w=""):w+="%"+this[b].toString(16);return a+g(w);case "ascii":return p(this,b,h);case "binary":return p(this,b,h);case "base64":return b=0===b&&h===this.length?n.fromByteArray(this):n.fromByteArray(this.slice(b,h)),b;case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":b=this.slice(b,h);h="";for(a=0;a<b.length;a+=2)h+=String.fromCharCode(b[a]+256*b[a+1]);return h;default:if(w)throw new TypeError("Unknown encoding: "+a);a=(a+"").toLowerCase();w=!0}};
|
||||||
|
e.prototype.equals=function(a){if(!e.isBuffer(a))throw new TypeError("Argument must be a Buffer");return 0===e.compare(this,a)};e.prototype.inspect=function(){var a="",b=A.INSPECT_MAX_BYTES;0<this.length&&(a=this.toString("hex",0,b).match(/.{2}/g).join(" "),this.length>b&&(a+=" ... "));return"<Buffer "+a+">"};e.prototype.compare=function(a){if(!e.isBuffer(a))throw new TypeError("Argument must be a Buffer");return e.compare(this,a)};e.prototype.get=function(a){console.log(".get() is deprecated. Access using array indexes instead.");
|
||||||
|
return this.readUInt8(a)};e.prototype.set=function(a,b){console.log(".set() is deprecated. Access using array indexes instead.");return this.writeUInt8(a,b)};e.prototype.write=function(a,b,h,w){if(isFinite(b))isFinite(h)||(w=h,h=void 0);else{var y=w;w=b;b=h;h=y}b=Number(b)||0;y=this.length-b;h?(h=Number(h),h>y&&(h=y)):h=y;w=String(w||"utf8").toLowerCase();switch(w){case "hex":b=Number(b)||0;w=this.length-b;h?(h=Number(h),h>w&&(h=w)):h=w;w=a.length;if(0!==w%2)throw Error("Invalid hex string");h>w/
|
||||||
|
2&&(h=w/2);for(w=0;w<h;w++){y=parseInt(a.substr(2*w,2),16);if(isNaN(y))throw Error("Invalid hex string");this[b+w]=y}a=w;break;case "utf8":case "utf-8":a=d(k(a),this,b,h);break;case "ascii":a=d(u(a),this,b,h);break;case "binary":a=d(u(a),this,b,h);break;case "base64":a=d(n.toByteArray(a),this,b,h);break;case "ucs2":case "ucs-2":case "utf16le":case "utf-16le":y=[];for(var I=0;I<a.length;I++){var K=a.charCodeAt(I);w=K>>8;K%=256;y.push(K);y.push(w)}a=d(y,this,b,h,2);break;default:throw new TypeError("Unknown encoding: "+
|
||||||
|
w);}return a};e.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};e.prototype.slice=function(a,b){var h=this.length;a=~~a;b=void 0===b?h:~~b;0>a?(a+=h,0>a&&(a=0)):a>h&&(a=h);0>b?(b+=h,0>b&&(b=0)):b>h&&(b=h);b<a&&(b=a);if(e.TYPED_ARRAY_SUPPORT)return e._augment(this.subarray(a,b));h=b-a;for(var w=new e(h,void 0,!0),y=0;y<h;y++)w[y]=this[y+a];return w};e.prototype.readUInt8=function(a,b){b||t(a,1,this.length);return this[a]};e.prototype.readUInt16LE=
|
||||||
|
function(a,b){b||t(a,2,this.length);return this[a]|this[a+1]<<8};e.prototype.readUInt16BE=function(a,b){b||t(a,2,this.length);return this[a]<<8|this[a+1]};e.prototype.readUInt32LE=function(a,b){b||t(a,4,this.length);return(this[a]|this[a+1]<<8|this[a+2]<<16)+16777216*this[a+3]};e.prototype.readUInt32BE=function(a,b){b||t(a,4,this.length);return 16777216*this[a]+(this[a+1]<<16|this[a+2]<<8|this[a+3])};e.prototype.readInt8=function(a,b){b||t(a,1,this.length);return this[a]&128?-1*(255-this[a]+1):this[a]};
|
||||||
|
e.prototype.readInt16LE=function(a,b){b||t(a,2,this.length);var h=this[a]|this[a+1]<<8;return h&32768?h|4294901760:h};e.prototype.readInt16BE=function(a,b){b||t(a,2,this.length);var h=this[a+1]|this[a]<<8;return h&32768?h|4294901760:h};e.prototype.readInt32LE=function(a,b){b||t(a,4,this.length);return this[a]|this[a+1]<<8|this[a+2]<<16|this[a+3]<<24};e.prototype.readInt32BE=function(a,b){b||t(a,4,this.length);return this[a]<<24|this[a+1]<<16|this[a+2]<<8|this[a+3]};e.prototype.readFloatLE=function(a,
|
||||||
|
b){b||t(a,4,this.length);return v.read(this,a,!0,23,4)};e.prototype.readFloatBE=function(a,b){b||t(a,4,this.length);return v.read(this,a,!1,23,4)};e.prototype.readDoubleLE=function(a,b){b||t(a,8,this.length);return v.read(this,a,!0,52,8)};e.prototype.readDoubleBE=function(a,b){b||t(a,8,this.length);return v.read(this,a,!1,52,8)};e.prototype.writeUInt8=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,1,255,0);e.TYPED_ARRAY_SUPPORT||(a=Math.floor(a));this[b]=a;return b+1};e.prototype.writeUInt16LE=function(a,
|
||||||
|
b,h){a=+a;b>>>=0;h||m(this,a,b,2,65535,0);e.TYPED_ARRAY_SUPPORT?(this[b]=a,this[b+1]=a>>>8):f(this,a,b,!0);return b+2};e.prototype.writeUInt16BE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,2,65535,0);e.TYPED_ARRAY_SUPPORT?(this[b]=a>>>8,this[b+1]=a):f(this,a,b,!1);return b+2};e.prototype.writeUInt32LE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,4,4294967295,0);e.TYPED_ARRAY_SUPPORT?(this[b+3]=a>>>24,this[b+2]=a>>>16,this[b+1]=a>>>8,this[b]=a):c(this,a,b,!0);return b+4};e.prototype.writeUInt32BE=function(a,
|
||||||
|
b,h){a=+a;b>>>=0;h||m(this,a,b,4,4294967295,0);e.TYPED_ARRAY_SUPPORT?(this[b]=a>>>24,this[b+1]=a>>>16,this[b+2]=a>>>8,this[b+3]=a):c(this,a,b,!1);return b+4};e.prototype.writeInt8=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,1,127,-128);e.TYPED_ARRAY_SUPPORT||(a=Math.floor(a));0>a&&(a=255+a+1);this[b]=a;return b+1};e.prototype.writeInt16LE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,2,32767,-32768);e.TYPED_ARRAY_SUPPORT?(this[b]=a,this[b+1]=a>>>8):f(this,a,b,!0);return b+2};e.prototype.writeInt16BE=function(a,
|
||||||
|
b,h){a=+a;b>>>=0;h||m(this,a,b,2,32767,-32768);e.TYPED_ARRAY_SUPPORT?(this[b]=a>>>8,this[b+1]=a):f(this,a,b,!1);return b+2};e.prototype.writeInt32LE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,4,2147483647,-2147483648);e.TYPED_ARRAY_SUPPORT?(this[b]=a,this[b+1]=a>>>8,this[b+2]=a>>>16,this[b+3]=a>>>24):c(this,a,b,!0);return b+4};e.prototype.writeInt32BE=function(a,b,h){a=+a;b>>>=0;h||m(this,a,b,4,2147483647,-2147483648);0>a&&(a=4294967295+a+1);e.TYPED_ARRAY_SUPPORT?(this[b]=a>>>24,this[b+1]=a>>>16,this[b+
|
||||||
|
2]=a>>>8,this[b+3]=a):c(this,a,b,!1);return b+4};e.prototype.writeFloatLE=function(a,b,h){return q(this,a,b,!0,h)};e.prototype.writeFloatBE=function(a,b,h){return q(this,a,b,!1,h)};e.prototype.writeDoubleLE=function(a,b,h){return r(this,a,b,!0,h)};e.prototype.writeDoubleBE=function(a,b,h){return r(this,a,b,!1,h)};e.prototype.copy=function(a,b,h,w){h||(h=0);w||0===w||(w=this.length);b||(b=0);if(w!==h&&0!==a.length&&0!==this.length){if(w<h)throw new TypeError("sourceEnd < sourceStart");if(0>b||b>=a.length)throw new TypeError("targetStart out of bounds");
|
||||||
|
if(0>h||h>=this.length)throw new TypeError("sourceStart out of bounds");if(0>w||w>this.length)throw new TypeError("sourceEnd out of bounds");w>this.length&&(w=this.length);a.length-b<w-h&&(w=a.length-b+h);w-=h;if(1E3>w||!e.TYPED_ARRAY_SUPPORT)for(var y=0;y<w;y++)a[y+b]=this[y+h];else a._set(this.subarray(h,h+w),b)}};e.prototype.fill=function(a,b,h){a||(a=0);b||(b=0);h||(h=this.length);if(h<b)throw new TypeError("end < start");if(h!==b&&0!==this.length){if(0>b||b>=this.length)throw new TypeError("start out of bounds");
|
||||||
|
if(0>h||h>this.length)throw new TypeError("end out of bounds");if("number"===typeof a)for(;b<h;b++)this[b]=a;else{a=k(a.toString());for(var w=a.length;b<h;b++)this[b]=a[b%w]}return this}};e.prototype.toArrayBuffer=function(){if("undefined"!==typeof Uint8Array){if(e.TYPED_ARRAY_SUPPORT)return(new e(this)).buffer;for(var a=new Uint8Array(this.length),b=0,h=a.length;b<h;b+=1)a[b]=this[b];return a.buffer}throw new TypeError("Buffer.toArrayBuffer not supported in this browser");};var D=e.prototype;e._augment=
|
||||||
|
function(a){a.constructor=e;a._isBuffer=!0;a._get=a.get;a._set=a.set;a.get=D.get;a.set=D.set;a.write=D.write;a.toString=D.toString;a.toLocaleString=D.toString;a.toJSON=D.toJSON;a.equals=D.equals;a.compare=D.compare;a.copy=D.copy;a.slice=D.slice;a.readUInt8=D.readUInt8;a.readUInt16LE=D.readUInt16LE;a.readUInt16BE=D.readUInt16BE;a.readUInt32LE=D.readUInt32LE;a.readUInt32BE=D.readUInt32BE;a.readInt8=D.readInt8;a.readInt16LE=D.readInt16LE;a.readInt16BE=D.readInt16BE;a.readInt32LE=D.readInt32LE;a.readInt32BE=
|
||||||
|
D.readInt32BE;a.readFloatLE=D.readFloatLE;a.readFloatBE=D.readFloatBE;a.readDoubleLE=D.readDoubleLE;a.readDoubleBE=D.readDoubleBE;a.writeUInt8=D.writeUInt8;a.writeUInt16LE=D.writeUInt16LE;a.writeUInt16BE=D.writeUInt16BE;a.writeUInt32LE=D.writeUInt32LE;a.writeUInt32BE=D.writeUInt32BE;a.writeInt8=D.writeInt8;a.writeInt16LE=D.writeInt16LE;a.writeInt16BE=D.writeInt16BE;a.writeInt32LE=D.writeInt32LE;a.writeInt32BE=D.writeInt32BE;a.writeFloatLE=D.writeFloatLE;a.writeFloatBE=D.writeFloatBE;a.writeDoubleLE=
|
||||||
|
D.writeDoubleLE;a.writeDoubleBE=D.writeDoubleBE;a.fill=D.fill;a.inspect=D.inspect;a.toArrayBuffer=D.toArrayBuffer;return a};var L=/[^+\/0-9A-z]/g},{"base64-js":2,ieee754:6,"is-array":7}],6:[function(C,J,A){A.read=function(e,p,t,m,f){var c=8*f-m-1;var l=(1<<c)-1,q=l>>1,r=-7;f=t?f-1:0;var k=t?-1:1,u=e[p+f];f+=k;t=u&(1<<-r)-1;u>>=-r;for(r+=c;0<r;t=256*t+e[p+f],f+=k,r-=8);c=t&(1<<-r)-1;t>>=-r;for(r+=m;0<r;c=256*c+e[p+f],f+=k,r-=8);if(0===t)t=1-q;else{if(t===l)return c?NaN:Infinity*(u?-1:1);c+=Math.pow(2,
|
||||||
|
m);t-=q}return(u?-1:1)*c*Math.pow(2,t-m)};A.write=function(e,p,t,m,f,c){var l,q=8*c-f-1,r=(1<<q)-1,k=r>>1,u=23===f?Math.pow(2,-24)-Math.pow(2,-77):0;c=m?0:c-1;var d=m?1:-1,g=0>p||0===p&&0>1/p?1:0;p=Math.abs(p);isNaN(p)||Infinity===p?(p=isNaN(p)?1:0,m=r):(m=Math.floor(Math.log(p)/Math.LN2),1>p*(l=Math.pow(2,-m))&&(m--,l*=2),p=1<=m+k?p+u/l:p+u*Math.pow(2,1-k),2<=p*l&&(m++,l/=2),m+k>=r?(p=0,m=r):1<=m+k?(p=(p*l-1)*Math.pow(2,f),m+=k):(p=p*Math.pow(2,k-1)*Math.pow(2,f),m=0));for(;8<=f;e[t+c]=p&255,c+=
|
||||||
|
d,p/=256,f-=8);m=m<<f|p;for(q+=f;0<q;e[t+c]=m&255,c+=d,m/=256,q-=8);e[t+c-d]|=128*g}},{}],7:[function(C,J,A){var e=Object.prototype.toString;J.exports=Array.isArray||function(p){return!!p&&"[object Array]"==e.call(p)}},{}],8:[function(C,J,A){(function(e){function p(c,l){for(var q=0,r=c.length-1;0<=r;r--){var k=c[r];"."===k?c.splice(r,1):".."===k?(c.splice(r,1),q++):q&&(c.splice(r,1),q--)}if(l)for(;q--;q)c.unshift("..");return c}function t(c,l){if(c.filter)return c.filter(l);for(var q=[],r=0;r<c.length;r++)l(c[r],
|
||||||
|
r,c)&&q.push(c[r]);return q}var m=/^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;A.resolve=function(){for(var c="",l=!1,q=arguments.length-1;-1<=q&&!l;q--){var r=0<=q?arguments[q]:e.cwd();if("string"!==typeof r)throw new TypeError("Arguments to path.resolve must be strings");r&&(c=r+"/"+c,l="/"===r.charAt(0))}c=p(t(c.split("/"),function(k){return!!k}),!l).join("/");return(l?"/":"")+c||"."};A.normalize=function(c){var l=A.isAbsolute(c),q="/"===f(c,-1);(c=p(t(c.split("/"),function(r){return!!r}),
|
||||||
|
!l).join("/"))||l||(c=".");c&&q&&(c+="/");return(l?"/":"")+c};A.isAbsolute=function(c){return"/"===c.charAt(0)};A.join=function(){var c=Array.prototype.slice.call(arguments,0);return A.normalize(t(c,function(l,q){if("string"!==typeof l)throw new TypeError("Arguments to path.join must be strings");return l}).join("/"))};A.relative=function(c,l){function q(n){for(var v=0;v<n.length&&""===n[v];v++);for(var z=n.length-1;0<=z&&""===n[z];z--);return v>z?[]:n.slice(v,z-v+1)}c=A.resolve(c).substr(1);l=A.resolve(l).substr(1);
|
||||||
|
for(var r=q(c.split("/")),k=q(l.split("/")),u=Math.min(r.length,k.length),d=u,g=0;g<u;g++)if(r[g]!==k[g]){d=g;break}u=[];for(g=d;g<r.length;g++)u.push("..");u=u.concat(k.slice(d));return u.join("/")};A.sep="/";A.delimiter=":";A.dirname=function(c){var l=m.exec(c).slice(1);c=l[0];l=l[1];if(!c&&!l)return".";l&&(l=l.substr(0,l.length-1));return c+l};A.basename=function(c,l){var q=m.exec(c).slice(1)[2];l&&q.substr(-1*l.length)===l&&(q=q.substr(0,q.length-l.length));return q};A.extname=function(c){return m.exec(c).slice(1)[3]};
|
||||||
|
var f="b"==="ab".substr(-1)?function(c,l,q){return c.substr(l,q)}:function(c,l,q){0>l&&(l=c.length+l);return c.substr(l,q)}}).call(this,C("g5I+bs"))},{"g5I+bs":9}],9:[function(C,J,A){function e(){}C=J.exports={};C.nextTick=function(){if("undefined"!==typeof window&&window.setImmediate)return function(t){return window.setImmediate(t)};if("undefined"!==typeof window&&window.postMessage&&window.addEventListener){var p=[];window.addEventListener("message",function(t){var m=t.source;m!==window&&null!==
|
||||||
|
m||"process-tick"!==t.data||(t.stopPropagation(),0<p.length&&p.shift()())},!0);return function(t){p.push(t);window.postMessage("process-tick","*")}}return function(t){setTimeout(t,0)}}();C.title="browser";C.browser=!0;C.env={};C.argv=[];C.on=e;C.addListener=e;C.once=e;C.off=e;C.removeListener=e;C.removeAllListeners=e;C.emit=e;C.binding=function(p){throw Error("process.binding is not supported");};C.cwd=function(){return"/"};C.chdir=function(p){throw Error("process.chdir is not supported");}},{}],
|
||||||
|
10:[function(C,J,A){function e(){this._array=[];this._set=m?new Map:Object.create(null)}var p=C("./util"),t=Object.prototype.hasOwnProperty,m="undefined"!==typeof Map;e.fromArray=function(f,c){for(var l=new e,q=0,r=f.length;q<r;q++)l.add(f[q],c);return l};e.prototype.size=function(){return m?this._set.size:Object.getOwnPropertyNames(this._set).length};e.prototype.add=function(f,c){var l=m?f:p.toSetString(f),q=m?this.has(f):t.call(this._set,l),r=this._array.length;q&&!c||this._array.push(f);q||(m?
|
||||||
|
this._set.set(f,r):this._set[l]=r)};e.prototype.has=function(f){if(m)return this._set.has(f);f=p.toSetString(f);return t.call(this._set,f)};e.prototype.indexOf=function(f){if(m){var c=this._set.get(f);if(0<=c)return c}else if(c=p.toSetString(f),t.call(this._set,c))return this._set[c];throw Error('"'+f+'" is not in the set.');};e.prototype.at=function(f){if(0<=f&&f<this._array.length)return this._array[f];throw Error("No element indexed by "+f);};e.prototype.toArray=function(){return this._array.slice()};
|
||||||
|
A.ArraySet=e},{"./util":19}],11:[function(C,J,A){var e=C("./base64");A.encode=function(p){var t="",m=0>p?(-p<<1)+1:p<<1;do p=m&31,m>>>=5,0<m&&(p|=32),t+=e.encode(p);while(0<m);return t};A.decode=function(p,t,m){var f=p.length,c=0,l=0;do{if(t>=f)throw Error("Expected more digits in base 64 VLQ value.");var q=e.decode(p.charCodeAt(t++));if(-1===q)throw Error("Invalid base64 digit: "+p.charAt(t-1));var r=!!(q&32);q&=31;c+=q<<l;l+=5}while(r);p=c>>1;m.value=1===(c&1)?-p:p;m.rest=t}},{"./base64":12}],12:[function(C,
|
||||||
|
J,A){var e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");A.encode=function(p){if(0<=p&&p<e.length)return e[p];throw new TypeError("Must be between 0 and 63: "+p);};A.decode=function(p){return 65<=p&&90>=p?p-65:97<=p&&122>=p?p-97+26:48<=p&&57>=p?p-48+52:43==p?62:47==p?63:-1}},{}],13:[function(C,J,A){function e(p,t,m,f,c,l){var q=Math.floor((t-p)/2)+p,r=c(m,f[q],!0);return 0===r?q:0<r?1<t-q?e(q,t,m,f,c,l):l==A.LEAST_UPPER_BOUND?t<f.length?t:-1:q:1<q-p?e(p,q,m,f,c,l):l==
|
||||||
|
A.LEAST_UPPER_BOUND?q:0>p?-1:p}A.GREATEST_LOWER_BOUND=1;A.LEAST_UPPER_BOUND=2;A.search=function(p,t,m,f){if(0===t.length)return-1;p=e(-1,t.length,p,t,m,f||A.GREATEST_LOWER_BOUND);if(0>p)return-1;for(;0<=p-1&&0===m(t[p],t[p-1],!0);)--p;return p}},{}],14:[function(C,J,A){function e(){this._array=[];this._sorted=!0;this._last={generatedLine:-1,generatedColumn:0}}var p=C("./util");e.prototype.unsortedForEach=function(t,m){this._array.forEach(t,m)};e.prototype.add=function(t){var m=this._last,f=m.generatedLine,
|
||||||
|
c=t.generatedLine,l=m.generatedColumn,q=t.generatedColumn;c>f||c==f&&q>=l||0>=p.compareByGeneratedPositionsInflated(m,t)?this._last=t:this._sorted=!1;this._array.push(t)};e.prototype.toArray=function(){this._sorted||(this._array.sort(p.compareByGeneratedPositionsInflated),this._sorted=!0);return this._array};A.MappingList=e},{"./util":19}],15:[function(C,J,A){function e(t,m,f){var c=t[m];t[m]=t[f];t[f]=c}function p(t,m,f,c){if(f<c){var l=f-1;e(t,Math.round(f+Math.random()*(c-f)),c);for(var q=t[c],
|
||||||
|
r=f;r<c;r++)0>=m(t[r],q)&&(l+=1,e(t,l,r));e(t,l+1,r);l+=1;p(t,m,f,l-1);p(t,m,l+1,c)}}A.quickSort=function(t,m){p(t,m,0,t.length-1)}},{}],16:[function(C,J,A){function e(k,u){var d=k;"string"===typeof k&&(d=f.parseSourceMapInput(k));return null!=d.sections?new m(d,u):new p(d,u)}function p(k,u){var d=k;"string"===typeof k&&(d=f.parseSourceMapInput(k));var g=f.getArg(d,"version"),n=f.getArg(d,"sources"),v=f.getArg(d,"names",[]),z=f.getArg(d,"sourceRoot",null),G=f.getArg(d,"sourcesContent",null),D=f.getArg(d,
|
||||||
|
"mappings");d=f.getArg(d,"file",null);if(g!=this._version)throw Error("Unsupported version: "+g);z&&(z=f.normalize(z));n=n.map(String).map(f.normalize).map(function(L){return z&&f.isAbsolute(z)&&f.isAbsolute(L)?f.relative(z,L):L});this._names=l.fromArray(v.map(String),!0);this._sources=l.fromArray(n,!0);this.sourceRoot=z;this.sourcesContent=G;this._mappings=D;this._sourceMapURL=u;this.file=d}function t(){this.generatedColumn=this.generatedLine=0;this.name=this.originalColumn=this.originalLine=this.source=
|
||||||
|
null}function m(k,u){var d=k;"string"===typeof k&&(d=f.parseSourceMapInput(k));var g=f.getArg(d,"version");d=f.getArg(d,"sections");if(g!=this._version)throw Error("Unsupported version: "+g);this._sources=new l;this._names=new l;var n={line:-1,column:0};this._sections=d.map(function(v){if(v.url)throw Error("Support for url field in sections not implemented.");var z=f.getArg(v,"offset"),G=f.getArg(z,"line"),D=f.getArg(z,"column");if(G<n.line||G===n.line&&D<n.column)throw Error("Section offsets must be ordered and non-overlapping.");
|
||||||
|
n=z;return{generatedOffset:{generatedLine:G+1,generatedColumn:D+1},consumer:new e(f.getArg(v,"map"),u)}})}var f=C("./util"),c=C("./binary-search"),l=C("./array-set").ArraySet,q=C("./base64-vlq"),r=C("./quick-sort").quickSort;e.fromSourceMap=function(k){return p.fromSourceMap(k)};e.prototype._version=3;e.prototype.__generatedMappings=null;Object.defineProperty(e.prototype,"_generatedMappings",{configurable:!0,enumerable:!0,get:function(){this.__generatedMappings||this._parseMappings(this._mappings,
|
||||||
|
this.sourceRoot);return this.__generatedMappings}});e.prototype.__originalMappings=null;Object.defineProperty(e.prototype,"_originalMappings",{configurable:!0,enumerable:!0,get:function(){this.__originalMappings||this._parseMappings(this._mappings,this.sourceRoot);return this.__originalMappings}});e.prototype._charIsMappingSeparator=function(k,u){var d=k.charAt(u);return";"===d||","===d};e.prototype._parseMappings=function(k,u){throw Error("Subclasses must implement _parseMappings");};e.GENERATED_ORDER=
|
||||||
|
1;e.ORIGINAL_ORDER=2;e.GREATEST_LOWER_BOUND=1;e.LEAST_UPPER_BOUND=2;e.prototype.eachMapping=function(k,u,d){u=u||null;switch(d||e.GENERATED_ORDER){case e.GENERATED_ORDER:d=this._generatedMappings;break;case e.ORIGINAL_ORDER:d=this._originalMappings;break;default:throw Error("Unknown order of iteration.");}var g=this.sourceRoot;d.map(function(n){var v=null===n.source?null:this._sources.at(n.source);v=f.computeSourceURL(g,v,this._sourceMapURL);return{source:v,generatedLine:n.generatedLine,generatedColumn:n.generatedColumn,
|
||||||
|
originalLine:n.originalLine,originalColumn:n.originalColumn,name:null===n.name?null:this._names.at(n.name)}},this).forEach(k,u)};e.prototype.allGeneratedPositionsFor=function(k){var u=f.getArg(k,"line"),d={source:f.getArg(k,"source"),originalLine:u,originalColumn:f.getArg(k,"column",0)};null!=this.sourceRoot&&(d.source=f.relative(this.sourceRoot,d.source));if(!this._sources.has(d.source))return[];d.source=this._sources.indexOf(d.source);var g=[];d=this._findMapping(d,this._originalMappings,"originalLine",
|
||||||
|
"originalColumn",f.compareByOriginalPositions,c.LEAST_UPPER_BOUND);if(0<=d){var n=this._originalMappings[d];if(void 0===k.column)for(u=n.originalLine;n&&n.originalLine===u;)g.push({line:f.getArg(n,"generatedLine",null),column:f.getArg(n,"generatedColumn",null),lastColumn:f.getArg(n,"lastGeneratedColumn",null)}),n=this._originalMappings[++d];else for(k=n.originalColumn;n&&n.originalLine===u&&n.originalColumn==k;)g.push({line:f.getArg(n,"generatedLine",null),column:f.getArg(n,"generatedColumn",null),
|
||||||
|
lastColumn:f.getArg(n,"lastGeneratedColumn",null)}),n=this._originalMappings[++d]}return g};A.SourceMapConsumer=e;p.prototype=Object.create(e.prototype);p.prototype.consumer=e;p.fromSourceMap=function(k,u){var d=Object.create(p.prototype),g=d._names=l.fromArray(k._names.toArray(),!0),n=d._sources=l.fromArray(k._sources.toArray(),!0);d.sourceRoot=k._sourceRoot;d.sourcesContent=k._generateSourcesContent(d._sources.toArray(),d.sourceRoot);d.file=k._file;d._sourceMapURL=u;for(var v=k._mappings.toArray().slice(),
|
||||||
|
z=d.__generatedMappings=[],G=d.__originalMappings=[],D=0,L=v.length;D<L;D++){var a=v[D],b=new t;b.generatedLine=a.generatedLine;b.generatedColumn=a.generatedColumn;a.source&&(b.source=n.indexOf(a.source),b.originalLine=a.originalLine,b.originalColumn=a.originalColumn,a.name&&(b.name=g.indexOf(a.name)),G.push(b));z.push(b)}r(d.__originalMappings,f.compareByOriginalPositions);return d};p.prototype._version=3;Object.defineProperty(p.prototype,"sources",{get:function(){return this._sources.toArray().map(function(k){return f.computeSourceURL(this.sourceRoot,
|
||||||
|
k,this._sourceMapURL)},this)}});p.prototype._parseMappings=function(k,u){for(var d=1,g=0,n=0,v=0,z=0,G=0,D=k.length,L=0,a={},b={},h=[],w=[],y,I,K,N,P;L<D;)if(";"===k.charAt(L))d++,L++,g=0;else if(","===k.charAt(L))L++;else{y=new t;y.generatedLine=d;for(N=L;N<D&&!this._charIsMappingSeparator(k,N);N++);I=k.slice(L,N);if(K=a[I])L+=I.length;else{for(K=[];L<N;)q.decode(k,L,b),P=b.value,L=b.rest,K.push(P);if(2===K.length)throw Error("Found a source, but no line and column");if(3===K.length)throw Error("Found a source and line, but no column");
|
||||||
|
a[I]=K}y.generatedColumn=g+K[0];g=y.generatedColumn;1<K.length&&(y.source=z+K[1],z+=K[1],y.originalLine=n+K[2],n=y.originalLine,y.originalLine+=1,y.originalColumn=v+K[3],v=y.originalColumn,4<K.length&&(y.name=G+K[4],G+=K[4]));w.push(y);"number"===typeof y.originalLine&&h.push(y)}r(w,f.compareByGeneratedPositionsDeflated);this.__generatedMappings=w;r(h,f.compareByOriginalPositions);this.__originalMappings=h};p.prototype._findMapping=function(k,u,d,g,n,v){if(0>=k[d])throw new TypeError("Line must be greater than or equal to 1, got "+
|
||||||
|
k[d]);if(0>k[g])throw new TypeError("Column must be greater than or equal to 0, got "+k[g]);return c.search(k,u,n,v)};p.prototype.computeColumnSpans=function(){for(var k=0;k<this._generatedMappings.length;++k){var u=this._generatedMappings[k];if(k+1<this._generatedMappings.length){var d=this._generatedMappings[k+1];if(u.generatedLine===d.generatedLine){u.lastGeneratedColumn=d.generatedColumn-1;continue}}u.lastGeneratedColumn=Infinity}};p.prototype.originalPositionFor=function(k){var u={generatedLine:f.getArg(k,
|
||||||
|
"line"),generatedColumn:f.getArg(k,"column")};k=this._findMapping(u,this._generatedMappings,"generatedLine","generatedColumn",f.compareByGeneratedPositionsDeflated,f.getArg(k,"bias",e.GREATEST_LOWER_BOUND));if(0<=k&&(k=this._generatedMappings[k],k.generatedLine===u.generatedLine)){u=f.getArg(k,"source",null);null!==u&&(u=this._sources.at(u),u=f.computeSourceURL(this.sourceRoot,u,this._sourceMapURL));var d=f.getArg(k,"name",null);null!==d&&(d=this._names.at(d));return{source:u,line:f.getArg(k,"originalLine",
|
||||||
|
null),column:f.getArg(k,"originalColumn",null),name:d}}return{source:null,line:null,column:null,name:null}};p.prototype.hasContentsOfAllSources=function(){return this.sourcesContent?this.sourcesContent.length>=this._sources.size()&&!this.sourcesContent.some(function(k){return null==k}):!1};p.prototype.sourceContentFor=function(k,u){if(!this.sourcesContent)return null;var d=k;null!=this.sourceRoot&&(d=f.relative(this.sourceRoot,d));if(this._sources.has(d))return this.sourcesContent[this._sources.indexOf(d)];
|
||||||
|
var g=this.sources,n;for(n=0;n<g.length;++n)if(g[n]==k)return this.sourcesContent[n];var v;if(null!=this.sourceRoot&&(v=f.urlParse(this.sourceRoot))){g=d.replace(/^file:\/\//,"");if("file"==v.scheme&&this._sources.has(g))return this.sourcesContent[this._sources.indexOf(g)];if((!v.path||"/"==v.path)&&this._sources.has("/"+d))return this.sourcesContent[this._sources.indexOf("/"+d)]}if(u)return null;throw Error('"'+d+'" is not in the SourceMap.');};p.prototype.generatedPositionFor=function(k){var u=
|
||||||
|
f.getArg(k,"source");null!=this.sourceRoot&&(u=f.relative(this.sourceRoot,u));if(!this._sources.has(u))return{line:null,column:null,lastColumn:null};u=this._sources.indexOf(u);u={source:u,originalLine:f.getArg(k,"line"),originalColumn:f.getArg(k,"column")};k=this._findMapping(u,this._originalMappings,"originalLine","originalColumn",f.compareByOriginalPositions,f.getArg(k,"bias",e.GREATEST_LOWER_BOUND));return 0<=k&&(k=this._originalMappings[k],k.source===u.source)?{line:f.getArg(k,"generatedLine",
|
||||||
|
null),column:f.getArg(k,"generatedColumn",null),lastColumn:f.getArg(k,"lastGeneratedColumn",null)}:{line:null,column:null,lastColumn:null}};A.BasicSourceMapConsumer=p;m.prototype=Object.create(e.prototype);m.prototype.constructor=e;m.prototype._version=3;Object.defineProperty(m.prototype,"sources",{get:function(){for(var k=[],u=0;u<this._sections.length;u++)for(var d=0;d<this._sections[u].consumer.sources.length;d++)k.push(this._sections[u].consumer.sources[d]);return k}});m.prototype.originalPositionFor=
|
||||||
|
function(k){var u={generatedLine:f.getArg(k,"line"),generatedColumn:f.getArg(k,"column")},d=c.search(u,this._sections,function(g,n){var v=g.generatedLine-n.generatedOffset.generatedLine;return v?v:g.generatedColumn-n.generatedOffset.generatedColumn});return(d=this._sections[d])?d.consumer.originalPositionFor({line:u.generatedLine-(d.generatedOffset.generatedLine-1),column:u.generatedColumn-(d.generatedOffset.generatedLine===u.generatedLine?d.generatedOffset.generatedColumn-1:0),bias:k.bias}):{source:null,
|
||||||
|
line:null,column:null,name:null}};m.prototype.hasContentsOfAllSources=function(){return this._sections.every(function(k){return k.consumer.hasContentsOfAllSources()})};m.prototype.sourceContentFor=function(k,u){for(var d=0;d<this._sections.length;d++){var g=this._sections[d].consumer.sourceContentFor(k,!0);if(g)return g}if(u)return null;throw Error('"'+k+'" is not in the SourceMap.');};m.prototype.generatedPositionFor=function(k){for(var u=0;u<this._sections.length;u++){var d=this._sections[u];if(-1!==
|
||||||
|
d.consumer.sources.indexOf(f.getArg(k,"source"))){var g=d.consumer.generatedPositionFor(k);if(g)return{line:g.line+(d.generatedOffset.generatedLine-1),column:g.column+(d.generatedOffset.generatedLine===g.line?d.generatedOffset.generatedColumn-1:0)}}}return{line:null,column:null}};m.prototype._parseMappings=function(k,u){this.__generatedMappings=[];this.__originalMappings=[];for(var d=0;d<this._sections.length;d++)for(var g=this._sections[d],n=g.consumer._generatedMappings,v=0;v<n.length;v++){var z=
|
||||||
|
n[v],G=g.consumer._sources.at(z.source);G=f.computeSourceURL(g.consumer.sourceRoot,G,this._sourceMapURL);this._sources.add(G);G=this._sources.indexOf(G);var D=null;z.name&&(D=g.consumer._names.at(z.name),this._names.add(D),D=this._names.indexOf(D));z={source:G,generatedLine:z.generatedLine+(g.generatedOffset.generatedLine-1),generatedColumn:z.generatedColumn+(g.generatedOffset.generatedLine===z.generatedLine?g.generatedOffset.generatedColumn-1:0),originalLine:z.originalLine,originalColumn:z.originalColumn,
|
||||||
|
name:D};this.__generatedMappings.push(z);"number"===typeof z.originalLine&&this.__originalMappings.push(z)}r(this.__generatedMappings,f.compareByGeneratedPositionsDeflated);r(this.__originalMappings,f.compareByOriginalPositions)};A.IndexedSourceMapConsumer=m},{"./array-set":10,"./base64-vlq":11,"./binary-search":13,"./quick-sort":15,"./util":19}],17:[function(C,J,A){function e(c){c||(c={});this._file=t.getArg(c,"file",null);this._sourceRoot=t.getArg(c,"sourceRoot",null);this._skipValidation=t.getArg(c,
|
||||||
|
"skipValidation",!1);this._sources=new m;this._names=new m;this._mappings=new f;this._sourcesContents=null}var p=C("./base64-vlq"),t=C("./util"),m=C("./array-set").ArraySet,f=C("./mapping-list").MappingList;e.prototype._version=3;e.fromSourceMap=function(c){var l=c.sourceRoot,q=new e({file:c.file,sourceRoot:l});c.eachMapping(function(r){var k={generated:{line:r.generatedLine,column:r.generatedColumn}};null!=r.source&&(k.source=r.source,null!=l&&(k.source=t.relative(l,k.source)),k.original={line:r.originalLine,
|
||||||
|
column:r.originalColumn},null!=r.name&&(k.name=r.name));q.addMapping(k)});c.sources.forEach(function(r){var k=r;null!==l&&(k=t.relative(l,r));q._sources.has(k)||q._sources.add(k);k=c.sourceContentFor(r);null!=k&&q.setSourceContent(r,k)});return q};e.prototype.addMapping=function(c){var l=t.getArg(c,"generated"),q=t.getArg(c,"original",null),r=t.getArg(c,"source",null);c=t.getArg(c,"name",null);this._skipValidation||this._validateMapping(l,q,r,c);null!=r&&(r=String(r),this._sources.has(r)||this._sources.add(r));
|
||||||
|
null!=c&&(c=String(c),this._names.has(c)||this._names.add(c));this._mappings.add({generatedLine:l.line,generatedColumn:l.column,originalLine:null!=q&&q.line,originalColumn:null!=q&&q.column,source:r,name:c})};e.prototype.setSourceContent=function(c,l){var q=c;null!=this._sourceRoot&&(q=t.relative(this._sourceRoot,q));null!=l?(this._sourcesContents||(this._sourcesContents=Object.create(null)),this._sourcesContents[t.toSetString(q)]=l):this._sourcesContents&&(delete this._sourcesContents[t.toSetString(q)],
|
||||||
|
0===Object.keys(this._sourcesContents).length&&(this._sourcesContents=null))};e.prototype.applySourceMap=function(c,l,q){var r=l;if(null==l){if(null==c.file)throw Error('SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map\'s "file" property. Both were omitted.');r=c.file}var k=this._sourceRoot;null!=k&&(r=t.relative(k,r));var u=new m,d=new m;this._mappings.unsortedForEach(function(g){if(g.source===r&&null!=g.originalLine){var n=c.originalPositionFor({line:g.originalLine,
|
||||||
|
column:g.originalColumn});null!=n.source&&(g.source=n.source,null!=q&&(g.source=t.join(q,g.source)),null!=k&&(g.source=t.relative(k,g.source)),g.originalLine=n.line,g.originalColumn=n.column,null!=n.name&&(g.name=n.name))}n=g.source;null==n||u.has(n)||u.add(n);g=g.name;null==g||d.has(g)||d.add(g)},this);this._sources=u;this._names=d;c.sources.forEach(function(g){var n=c.sourceContentFor(g);null!=n&&(null!=q&&(g=t.join(q,g)),null!=k&&(g=t.relative(k,g)),this.setSourceContent(g,n))},this)};e.prototype._validateMapping=
|
||||||
|
function(c,l,q,r){if(l&&"number"!==typeof l.line&&"number"!==typeof l.column)throw Error("original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.");if(!(c&&"line"in c&&"column"in c&&0<c.line&&0<=c.column&&!l&&!q&&!r||c&&"line"in c&&"column"in c&&l&&"line"in l&&"column"in l&&0<c.line&&0<=c.column&&0<l.line&&0<=l.column&&
|
||||||
|
q))throw Error("Invalid mapping: "+JSON.stringify({generated:c,source:q,original:l,name:r}));};e.prototype._serializeMappings=function(){for(var c=0,l=1,q=0,r=0,k=0,u=0,d="",g,n,v,z=this._mappings.toArray(),G=0,D=z.length;G<D;G++){n=z[G];g="";if(n.generatedLine!==l)for(c=0;n.generatedLine!==l;)g+=";",l++;else if(0<G){if(!t.compareByGeneratedPositionsInflated(n,z[G-1]))continue;g+=","}g+=p.encode(n.generatedColumn-c);c=n.generatedColumn;null!=n.source&&(v=this._sources.indexOf(n.source),g+=p.encode(v-
|
||||||
|
u),u=v,g+=p.encode(n.originalLine-1-r),r=n.originalLine-1,g+=p.encode(n.originalColumn-q),q=n.originalColumn,null!=n.name&&(n=this._names.indexOf(n.name),g+=p.encode(n-k),k=n));d+=g}return d};e.prototype._generateSourcesContent=function(c,l){return c.map(function(q){if(!this._sourcesContents)return null;null!=l&&(q=t.relative(l,q));q=t.toSetString(q);return Object.prototype.hasOwnProperty.call(this._sourcesContents,q)?this._sourcesContents[q]:null},this)};e.prototype.toJSON=function(){var c={version:this._version,
|
||||||
|
sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};null!=this._file&&(c.file=this._file);null!=this._sourceRoot&&(c.sourceRoot=this._sourceRoot);this._sourcesContents&&(c.sourcesContent=this._generateSourcesContent(c.sources,c.sourceRoot));return c};e.prototype.toString=function(){return JSON.stringify(this.toJSON())};A.SourceMapGenerator=e},{"./array-set":10,"./base64-vlq":11,"./mapping-list":14,"./util":19}],18:[function(C,J,A){function e(f,c,l,q,r){this.children=
|
||||||
|
[];this.sourceContents={};this.line=null==f?null:f;this.column=null==c?null:c;this.source=null==l?null:l;this.name=null==r?null:r;this.$$$isSourceNode$$$=!0;null!=q&&this.add(q)}var p=C("./source-map-generator").SourceMapGenerator,t=C("./util"),m=/(\r?\n)/;e.fromStringWithSourceMap=function(f,c,l){function q(z,G){if(null===z||void 0===z.source)r.add(G);else{var D=l?t.join(l,z.source):z.source;r.add(new e(z.originalLine,z.originalColumn,D,G,z.name))}}var r=new e,k=f.split(m),u=0,d=function(){var z=
|
||||||
|
u<k.length?k[u++]:void 0,G=(u<k.length?k[u++]:void 0)||"";return z+G},g=1,n=0,v=null;c.eachMapping(function(z){if(null!==v)if(g<z.generatedLine)q(v,d()),g++,n=0;else{var G=k[u]||"",D=G.substr(0,z.generatedColumn-n);k[u]=G.substr(z.generatedColumn-n);n=z.generatedColumn;q(v,D);v=z;return}for(;g<z.generatedLine;)r.add(d()),g++;n<z.generatedColumn&&(G=k[u]||"",r.add(G.substr(0,z.generatedColumn)),k[u]=G.substr(z.generatedColumn),n=z.generatedColumn);v=z},this);u<k.length&&(v&&q(v,d()),r.add(k.splice(u).join("")));
|
||||||
|
c.sources.forEach(function(z){var G=c.sourceContentFor(z);null!=G&&(null!=l&&(z=t.join(l,z)),r.setSourceContent(z,G))});return r};e.prototype.add=function(f){if(Array.isArray(f))f.forEach(function(c){this.add(c)},this);else if(f.$$$isSourceNode$$$||"string"===typeof f)f&&this.children.push(f);else throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+f);return this};e.prototype.prepend=function(f){if(Array.isArray(f))for(var c=f.length-1;0<=c;c--)this.prepend(f[c]);
|
||||||
|
else if(f.$$$isSourceNode$$$||"string"===typeof f)this.children.unshift(f);else throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+f);return this};e.prototype.walk=function(f){for(var c,l=0,q=this.children.length;l<q;l++)c=this.children[l],c.$$$isSourceNode$$$?c.walk(f):""!==c&&f(c,{source:this.source,line:this.line,column:this.column,name:this.name})};e.prototype.join=function(f){var c,l=this.children.length;if(0<l){var q=[];for(c=0;c<l-1;c++)q.push(this.children[c]),
|
||||||
|
q.push(f);q.push(this.children[c]);this.children=q}return this};e.prototype.replaceRight=function(f,c){var l=this.children[this.children.length-1];l.$$$isSourceNode$$$?l.replaceRight(f,c):"string"===typeof l?this.children[this.children.length-1]=l.replace(f,c):this.children.push("".replace(f,c));return this};e.prototype.setSourceContent=function(f,c){this.sourceContents[t.toSetString(f)]=c};e.prototype.walkSourceContents=function(f){for(var c=0,l=this.children.length;c<l;c++)this.children[c].$$$isSourceNode$$$&&
|
||||||
|
this.children[c].walkSourceContents(f);var q=Object.keys(this.sourceContents);c=0;for(l=q.length;c<l;c++)f(t.fromSetString(q[c]),this.sourceContents[q[c]])};e.prototype.toString=function(){var f="";this.walk(function(c){f+=c});return f};e.prototype.toStringWithSourceMap=function(f){var c="",l=1,q=0,r=new p(f),k=!1,u=null,d=null,g=null,n=null;this.walk(function(v,z){c+=v;null!==z.source&&null!==z.line&&null!==z.column?(u===z.source&&d===z.line&&g===z.column&&n===z.name||r.addMapping({source:z.source,
|
||||||
|
original:{line:z.line,column:z.column},generated:{line:l,column:q},name:z.name}),u=z.source,d=z.line,g=z.column,n=z.name,k=!0):k&&(r.addMapping({generated:{line:l,column:q}}),u=null,k=!1);for(var G=0,D=v.length;G<D;G++)10===v.charCodeAt(G)?(l++,q=0,G+1===D?(u=null,k=!1):k&&r.addMapping({source:z.source,original:{line:z.line,column:z.column},generated:{line:l,column:q},name:z.name})):q++});this.walkSourceContents(function(v,z){r.setSourceContent(v,z)});return{code:c,map:r}};A.SourceNode=e},{"./source-map-generator":17,
|
||||||
|
"./util":19}],19:[function(C,J,A){function e(d){return(d=d.match(k))?{scheme:d[1],auth:d[2],host:d[3],port:d[4],path:d[5]}:null}function p(d){var g="";d.scheme&&(g+=d.scheme+":");g+="//";d.auth&&(g+=d.auth+"@");d.host&&(g+=d.host);d.port&&(g+=":"+d.port);d.path&&(g+=d.path);return g}function t(d){var g=d,n=e(d);if(n){if(!n.path)return d;g=n.path}d=A.isAbsolute(g);g=g.split(/\/+/);for(var v,z=0,G=g.length-1;0<=G;G--)v=g[G],"."===v?g.splice(G,1):".."===v?z++:0<z&&(""===v?(g.splice(G+1,z),z=0):(g.splice(G,
|
||||||
|
2),z--));g=g.join("/");""===g&&(g=d?"/":".");return n?(n.path=g,p(n)):g}function m(d,g){""===d&&(d=".");""===g&&(g=".");var n=e(g),v=e(d);v&&(d=v.path||"/");if(n&&!n.scheme)return v&&(n.scheme=v.scheme),p(n);if(n||g.match(u))return g;if(v&&!v.host&&!v.path)return v.host=g,p(v);n="/"===g.charAt(0)?g:t(d.replace(/\/+$/,"")+"/"+g);return v?(v.path=n,p(v)):n}function f(d){return d}function c(d){return q(d)?"$"+d:d}function l(d){return q(d)?d.slice(1):d}function q(d){if(!d)return!1;var g=d.length;if(9>
|
||||||
|
g||95!==d.charCodeAt(g-1)||95!==d.charCodeAt(g-2)||111!==d.charCodeAt(g-3)||116!==d.charCodeAt(g-4)||111!==d.charCodeAt(g-5)||114!==d.charCodeAt(g-6)||112!==d.charCodeAt(g-7)||95!==d.charCodeAt(g-8)||95!==d.charCodeAt(g-9))return!1;for(g-=10;0<=g;g--)if(36!==d.charCodeAt(g))return!1;return!0}function r(d,g){return d===g?0:null===d?1:null===g?-1:d>g?1:-1}A.getArg=function(d,g,n){if(g in d)return d[g];if(3===arguments.length)return n;throw Error('"'+g+'" is a required argument.');};var k=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/,
|
||||||
|
u=/^data:.+,.+$/;A.urlParse=e;A.urlGenerate=p;A.normalize=t;A.join=m;A.isAbsolute=function(d){return"/"===d.charAt(0)||k.test(d)};A.relative=function(d,g){""===d&&(d=".");d=d.replace(/\/$/,"");for(var n=0;0!==g.indexOf(d+"/");){var v=d.lastIndexOf("/");if(0>v)return g;d=d.slice(0,v);if(d.match(/^([^\/]+:\/)?\/*$/))return g;++n}return Array(n+1).join("../")+g.substr(d.length+1)};C=!("__proto__"in Object.create(null));A.toSetString=C?f:c;A.fromSetString=C?f:l;A.compareByOriginalPositions=function(d,
|
||||||
|
g,n){var v=r(d.source,g.source);if(0!==v)return v;v=d.originalLine-g.originalLine;if(0!==v)return v;v=d.originalColumn-g.originalColumn;if(0!==v||n)return v;v=d.generatedColumn-g.generatedColumn;if(0!==v)return v;v=d.generatedLine-g.generatedLine;return 0!==v?v:r(d.name,g.name)};A.compareByGeneratedPositionsDeflated=function(d,g,n){var v=d.generatedLine-g.generatedLine;if(0!==v)return v;v=d.generatedColumn-g.generatedColumn;if(0!==v||n)return v;v=r(d.source,g.source);if(0!==v)return v;v=d.originalLine-
|
||||||
|
g.originalLine;if(0!==v)return v;v=d.originalColumn-g.originalColumn;return 0!==v?v:r(d.name,g.name)};A.compareByGeneratedPositionsInflated=function(d,g){var n=d.generatedLine-g.generatedLine;if(0!==n)return n;n=d.generatedColumn-g.generatedColumn;if(0!==n)return n;n=r(d.source,g.source);if(0!==n)return n;n=d.originalLine-g.originalLine;if(0!==n)return n;n=d.originalColumn-g.originalColumn;return 0!==n?n:r(d.name,g.name)};A.parseSourceMapInput=function(d){return JSON.parse(d.replace(/^\)]}'[^\n]*\n/,
|
||||||
|
""))};A.computeSourceURL=function(d,g,n){g=g||"";d&&("/"!==d[d.length-1]&&"/"!==g[0]&&(d+="/"),g=d+g);if(n){d=e(n);if(!d)throw Error("sourceMapURL could not be parsed");d.path&&(n=d.path.lastIndexOf("/"),0<=n&&(d.path=d.path.substring(0,n+1)));g=m(p(d),g)}return t(g)}},{}],20:[function(C,J,A){A.SourceMapGenerator=C("./lib/source-map-generator").SourceMapGenerator;A.SourceMapConsumer=C("./lib/source-map-consumer").SourceMapConsumer;A.SourceNode=C("./lib/source-node").SourceNode},{"./lib/source-map-consumer":16,
|
||||||
|
"./lib/source-map-generator":17,"./lib/source-node":18}],21:[function(C,J,A){(function(e){function p(){return"browser"===a?!0:"node"===a?!1:"undefined"!==typeof window&&"function"===typeof XMLHttpRequest&&!(window.require&&window.module&&window.process&&"renderer"===window.process.type)}function t(x){return function(B){for(var F=0;F<x.length;F++){var E=x[F](B);if(E)return E}return null}}function m(x,B){if(!x)return B;var F=n.dirname(x),E=/^\w+:\/\/[^\/]*/.exec(F);E=E?E[0]:"";var H=F.slice(E.length);
|
||||||
|
return E&&/^\/\w:/.test(H)?(E+="/",E+n.resolve(F.slice(E.length),B).replace(/\\/g,"/")):E+n.resolve(F.slice(E.length),B)}function f(x){var B=h[x.source];if(!B){var F=N(x.source);F?(B=h[x.source]={url:F.url,map:new g(F.map)},B.map.sourcesContent&&B.map.sources.forEach(function(E,H){var M=B.map.sourcesContent[H];if(M){var S=m(B.url,E);b[S]=M}})):B=h[x.source]={url:null,map:null}}return B&&B.map&&"function"===typeof B.map.originalPositionFor&&(F=B.map.originalPositionFor(x),null!==F.source)?(F.source=
|
||||||
|
m(B.url,F.source),F):x}function c(x){var B=/^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(x);return B?(x=f({source:B[2],line:+B[3],column:B[4]-1}),"eval at "+B[1]+" ("+x.source+":"+x.line+":"+(x.column+1)+")"):(B=/^eval at ([^(]+) \((.+)\)$/.exec(x))?"eval at "+B[1]+" ("+c(B[2])+")":x}function l(){var x="";if(this.isNative())x="native";else{var B=this.getScriptNameOrSourceURL();!B&&this.isEval()&&(x=this.getEvalOrigin(),x+=", ");x=B?x+B:x+"<anonymous>";B=this.getLineNumber();null!=B&&(x+=":"+B,(B=
|
||||||
|
this.getColumnNumber())&&(x+=":"+B))}B="";var F=this.getFunctionName(),E=!0,H=this.isConstructor();if(this.isToplevel()||H)H?B+="new "+(F||"<anonymous>"):F?B+=F:(B+=x,E=!1);else{H=this.getTypeName();"[object Object]"===H&&(H="null");var M=this.getMethodName();F?(H&&0!=F.indexOf(H)&&(B+=H+"."),B+=F,M&&F.indexOf("."+M)!=F.length-M.length-1&&(B+=" [as "+M+"]")):B+=H+"."+(M||"<anonymous>")}E&&(B+=" ("+x+")");return B}function q(x){var B={};Object.getOwnPropertyNames(Object.getPrototypeOf(x)).forEach(function(F){B[F]=
|
||||||
|
/^(?:is|get)/.test(F)?function(){return x[F].call(x)}:x[F]});B.toString=l;return B}function r(x,B){void 0===B&&(B={nextPosition:null,curPosition:null});if(x.isNative())return B.curPosition=null,x;var F=x.getFileName()||x.getScriptNameOrSourceURL();if(F){var E=x.getLineNumber(),H=x.getColumnNumber()-1,M=/^v(10\.1[6-9]|10\.[2-9][0-9]|10\.[0-9]{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/,S=M.test;var V="object"===typeof e&&null!==e?e.version:"";M=S.call(M,V)?0:62;1===E&&H>M&&!p()&&!x.isEval()&&(H-=M);var O=
|
||||||
|
f({source:F,line:E,column:H});B.curPosition=O;x=q(x);var T=x.getFunctionName;x.getFunctionName=function(){return null==B.nextPosition?T():B.nextPosition.name||T()};x.getFileName=function(){return O.source};x.getLineNumber=function(){return O.line};x.getColumnNumber=function(){return O.column+1};x.getScriptNameOrSourceURL=function(){return O.source};return x}var Q=x.isEval()&&x.getEvalOrigin();Q&&(Q=c(Q),x=q(x),x.getEvalOrigin=function(){return Q});return x}function k(x,B){L&&(b={},h={});for(var F=
|
||||||
|
(x.name||"Error")+": "+(x.message||""),E={nextPosition:null,curPosition:null},H=[],M=B.length-1;0<=M;M--)H.push("\n at "+r(B[M],E)),E.nextPosition=E.curPosition;E.curPosition=E.nextPosition=null;return F+H.reverse().join("")}function u(x){var B=/\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(x.stack);if(B){x=B[1];var F=+B[2];B=+B[3];var E=b[x];if(!E&&v&&v.existsSync(x))try{E=v.readFileSync(x,"utf8")}catch(H){E=""}if(E&&(E=E.split(/(?:\r\n|\r|\n)/)[F-1]))return x+":"+F+"\n"+E+"\n"+Array(B).join(" ")+
|
||||||
|
"^"}return null}function d(){var x=e.emit;e.emit=function(B){if("uncaughtException"===B){var F=arguments[1]&&arguments[1].stack,E=0<this.listeners(B).length;if(F&&!E){F=arguments[1];E=u(F);var H="object"===typeof e&&null!==e?e.stderr:void 0;H&&H._handle&&H._handle.setBlocking&&H._handle.setBlocking(!0);E&&(console.error(),console.error(E));console.error(F.stack);"object"===typeof e&&null!==e&&"function"===typeof e.exit&&e.exit(1);return}}return x.apply(this,arguments)}}var g=C("source-map").SourceMapConsumer,
|
||||||
|
n=C("path");try{var v=C("fs");v.existsSync&&v.readFileSync||(v=null)}catch(x){}var z=C("buffer-from"),G=!1,D=!1,L=!1,a="auto",b={},h={},w=/^data:application\/json[^,]+base64,/,y=[],I=[],K=t(y);y.push(function(x){x=x.trim();/^file:/.test(x)&&(x=x.replace(/file:\/\/\/(\w:)?/,function(E,H){return H?"":"/"}));if(x in b)return b[x];var B="";try{if(v)v.existsSync(x)&&(B=v.readFileSync(x,"utf8"));else{var F=new XMLHttpRequest;F.open("GET",x,!1);F.send(null);4===F.readyState&&200===F.status&&(B=F.responseText)}}catch(E){}return b[x]=
|
||||||
|
B});var N=t(I);I.push(function(x){a:{if(p())try{var B=new XMLHttpRequest;B.open("GET",x,!1);B.send(null);var F=B.getResponseHeader("SourceMap")||B.getResponseHeader("X-SourceMap");if(F){var E=F;break a}}catch(M){}E=K(x);B=/(?:\/\/[@#][\s]*sourceMappingURL=([^\s'"]+)[\s]*$)|(?:\/\*[@#][\s]*sourceMappingURL=([^\s*'"]+)[\s]*(?:\*\/)[\s]*$)/mg;for(var H;F=B.exec(E);)H=F;E=H?H[1]:null}if(!E)return null;w.test(E)?(H=E.slice(E.indexOf(",")+1),H=z(H,"base64").toString(),E=x):(E=m(x,E),H=K(E));return H?{url:E,
|
||||||
|
map:H}:null});var P=y.slice(0),W=I.slice(0);A.wrapCallSite=r;A.getErrorSource=u;A.mapSourcePosition=f;A.retrieveSourceMap=N;A.install=function(x){x=x||{};if(x.environment&&(a=x.environment,-1===["node","browser","auto"].indexOf(a)))throw Error("environment "+a+" was unknown. Available options are {auto, browser, node}");x.retrieveFile&&(x.overrideRetrieveFile&&(y.length=0),y.unshift(x.retrieveFile));x.retrieveSourceMap&&(x.overrideRetrieveSourceMap&&(I.length=0),I.unshift(x.retrieveSourceMap));if(x.hookRequire&&
|
||||||
|
!p()){var B=J.require("module"),F=B.prototype._compile;F.__sourceMapSupport||(B.prototype._compile=function(E,H){b[H]=E;h[H]=void 0;return F.call(this,E,H)},B.prototype._compile.__sourceMapSupport=!0)}L||(L="emptyCacheBetweenOperations"in x?x.emptyCacheBetweenOperations:!1);G||(G=!0,Error.prepareStackTrace=k);if(!D){x="handleUncaughtExceptions"in x?x.handleUncaughtExceptions:!0;try{!1===J.require("worker_threads").isMainThread&&(x=!1)}catch(E){}x&&"object"===typeof e&&null!==e&&"function"===typeof e.on&&
|
||||||
|
(D=!0,d())}};A.resetRetrieveHandlers=function(){y.length=0;I.length=0;y=P.slice(0);I=W.slice(0);N=t(I);K=t(y)}}).call(this,C("g5I+bs"))},{"buffer-from":4,fs:3,"g5I+bs":9,path:8,"source-map":20}]},{},[1]);return R});
|
||||||
50
node_modules/@cspotcode/source-map-support/package.json
generated
vendored
Normal file
50
node_modules/@cspotcode/source-map-support/package.json
generated
vendored
Normal file
@@ -0,0 +1,50 @@
|
|||||||
|
{
|
||||||
|
"name": "@cspotcode/source-map-support",
|
||||||
|
"description": "Fixes stack traces for files with source maps",
|
||||||
|
"version": "0.8.1",
|
||||||
|
"main": "./source-map-support.js",
|
||||||
|
"types": "./source-map-support.d.ts",
|
||||||
|
"scripts": {
|
||||||
|
"build": "node build.js",
|
||||||
|
"serve-tests": "http-server -p 1336",
|
||||||
|
"test": "mocha"
|
||||||
|
},
|
||||||
|
"files": [
|
||||||
|
"/register.d.ts",
|
||||||
|
"/register.js",
|
||||||
|
"/register-hook-require.d.ts",
|
||||||
|
"/register-hook-require.js",
|
||||||
|
"/source-map-support.d.ts",
|
||||||
|
"/source-map-support.js",
|
||||||
|
"/browser-source-map-support.js"
|
||||||
|
],
|
||||||
|
"dependencies": {
|
||||||
|
"@jridgewell/trace-mapping": "0.3.9"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@types/lodash": "^4.14.182",
|
||||||
|
"browserify": "^4.2.3",
|
||||||
|
"coffeescript": "^1.12.7",
|
||||||
|
"http-server": "^0.11.1",
|
||||||
|
"lodash": "^4.17.21",
|
||||||
|
"mocha": "^3.5.3",
|
||||||
|
"semver": "^7.3.7",
|
||||||
|
"source-map": "0.6.1",
|
||||||
|
"webpack": "^1.15.0"
|
||||||
|
},
|
||||||
|
"repository": {
|
||||||
|
"type": "git",
|
||||||
|
"url": "https://github.com/cspotcode/node-source-map-support"
|
||||||
|
},
|
||||||
|
"bugs": {
|
||||||
|
"url": "https://github.com/cspotcode/node-source-map-support/issues"
|
||||||
|
},
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=12"
|
||||||
|
},
|
||||||
|
"volta": {
|
||||||
|
"node": "16.11.0",
|
||||||
|
"npm": "7.24.2"
|
||||||
|
}
|
||||||
|
}
|
||||||
7
node_modules/@cspotcode/source-map-support/register-hook-require.d.ts
generated
vendored
Executable file
7
node_modules/@cspotcode/source-map-support/register-hook-require.d.ts
generated
vendored
Executable file
@@ -0,0 +1,7 @@
|
|||||||
|
// tslint:disable:no-useless-files
|
||||||
|
|
||||||
|
// For following usage:
|
||||||
|
// import '@cspotcode/source-map-support/register-hook-require'
|
||||||
|
// Instead of:
|
||||||
|
// import sourceMapSupport from '@cspotcode/source-map-support'
|
||||||
|
// sourceMapSupport.install({hookRequire: true})
|
||||||
3
node_modules/@cspotcode/source-map-support/register-hook-require.js
generated
vendored
Normal file
3
node_modules/@cspotcode/source-map-support/register-hook-require.js
generated
vendored
Normal file
@@ -0,0 +1,3 @@
|
|||||||
|
require('./').install({
|
||||||
|
hookRequire: true
|
||||||
|
});
|
||||||
7
node_modules/@cspotcode/source-map-support/register.d.ts
generated
vendored
Executable file
7
node_modules/@cspotcode/source-map-support/register.d.ts
generated
vendored
Executable file
@@ -0,0 +1,7 @@
|
|||||||
|
// tslint:disable:no-useless-files
|
||||||
|
|
||||||
|
// For following usage:
|
||||||
|
// import '@cspotcode/source-map-support/register'
|
||||||
|
// Instead of:
|
||||||
|
// import sourceMapSupport from '@cspotcode/source-map-support'
|
||||||
|
// sourceMapSupport.install()
|
||||||
1
node_modules/@cspotcode/source-map-support/register.js
generated
vendored
Normal file
1
node_modules/@cspotcode/source-map-support/register.js
generated
vendored
Normal file
@@ -0,0 +1 @@
|
|||||||
|
require('./').install();
|
||||||
76
node_modules/@cspotcode/source-map-support/source-map-support.d.ts
generated
vendored
Executable file
76
node_modules/@cspotcode/source-map-support/source-map-support.d.ts
generated
vendored
Executable file
@@ -0,0 +1,76 @@
|
|||||||
|
// Type definitions for source-map-support 0.5
|
||||||
|
// Project: https://github.com/evanw/node-source-map-support
|
||||||
|
// Definitions by: Bart van der Schoor <https://github.com/Bartvds>
|
||||||
|
// Jason Cheatham <https://github.com/jason0x43>
|
||||||
|
// Alcedo Nathaniel De Guzman Jr <https://github.com/natealcedo>
|
||||||
|
// Griffin Yourick <https://github.com/tough-griff>
|
||||||
|
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
|
||||||
|
|
||||||
|
export interface RawSourceMap {
|
||||||
|
version: 3;
|
||||||
|
sources: string[];
|
||||||
|
names: string[];
|
||||||
|
sourceRoot?: string;
|
||||||
|
sourcesContent?: string[];
|
||||||
|
mappings: string;
|
||||||
|
file: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Output of retrieveSourceMap().
|
||||||
|
* From source-map-support:
|
||||||
|
* The map field may be either a string or the parsed JSON object (i.e.,
|
||||||
|
* it must be a valid argument to the SourceMapConsumer constructor).
|
||||||
|
*/
|
||||||
|
export interface UrlAndMap {
|
||||||
|
url: string;
|
||||||
|
map: string | RawSourceMap;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Options to install().
|
||||||
|
*/
|
||||||
|
export interface Options {
|
||||||
|
handleUncaughtExceptions?: boolean | undefined;
|
||||||
|
hookRequire?: boolean | undefined;
|
||||||
|
emptyCacheBetweenOperations?: boolean | undefined;
|
||||||
|
environment?: 'auto' | 'browser' | 'node' | undefined;
|
||||||
|
overrideRetrieveFile?: boolean | undefined;
|
||||||
|
overrideRetrieveSourceMap?: boolean | undefined;
|
||||||
|
retrieveFile?(path: string): string;
|
||||||
|
retrieveSourceMap?(source: string): UrlAndMap | null;
|
||||||
|
/**
|
||||||
|
* Set false to disable redirection of require / import `source-map-support` to `@cspotcode/source-map-support`
|
||||||
|
*/
|
||||||
|
redirectConflictingLibrary?: boolean;
|
||||||
|
/**
|
||||||
|
* Callback will be called every time we redirect due to `redirectConflictingLibrary`
|
||||||
|
* This allows consumers to log helpful warnings if they choose.
|
||||||
|
* @param parent NodeJS.Module which made the require() or require.resolve() call
|
||||||
|
* @param options options object internally passed to node's `_resolveFilename` hook
|
||||||
|
*/
|
||||||
|
onConflictingLibraryRedirect?: (request: string, parent: any, isMain: boolean, options: any, redirectedRequest: string) => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Position {
|
||||||
|
source: string;
|
||||||
|
line: number;
|
||||||
|
column: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function wrapCallSite(frame: any /* StackFrame */): any /* StackFrame */;
|
||||||
|
export function getErrorSource(error: Error): string | null;
|
||||||
|
export function mapSourcePosition(position: Position): Position;
|
||||||
|
export function retrieveSourceMap(source: string): UrlAndMap | null;
|
||||||
|
export function resetRetrieveHandlers(): void;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Install SourceMap support.
|
||||||
|
* @param options Can be used to e.g. disable uncaughtException handler.
|
||||||
|
*/
|
||||||
|
export function install(options?: Options): void;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Uninstall SourceMap support.
|
||||||
|
*/
|
||||||
|
export function uninstall(): void;
|
||||||
938
node_modules/@cspotcode/source-map-support/source-map-support.js
generated
vendored
Normal file
938
node_modules/@cspotcode/source-map-support/source-map-support.js
generated
vendored
Normal file
@@ -0,0 +1,938 @@
|
|||||||
|
const { TraceMap, originalPositionFor, AnyMap } = require('@jridgewell/trace-mapping');
|
||||||
|
var path = require('path');
|
||||||
|
const { fileURLToPath, pathToFileURL } = require('url');
|
||||||
|
var util = require('util');
|
||||||
|
|
||||||
|
var fs;
|
||||||
|
try {
|
||||||
|
fs = require('fs');
|
||||||
|
if (!fs.existsSync || !fs.readFileSync) {
|
||||||
|
// fs doesn't have all methods we need
|
||||||
|
fs = null;
|
||||||
|
}
|
||||||
|
} catch (err) {
|
||||||
|
/* nop */
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Requires a module which is protected against bundler minification.
|
||||||
|
*
|
||||||
|
* @param {NodeModule} mod
|
||||||
|
* @param {string} request
|
||||||
|
*/
|
||||||
|
function dynamicRequire(mod, request) {
|
||||||
|
return mod.require(request);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @typedef {{
|
||||||
|
* enabled: boolean;
|
||||||
|
* originalValue: any;
|
||||||
|
* installedValue: any;
|
||||||
|
* }} HookState
|
||||||
|
* Used for installing and uninstalling hooks
|
||||||
|
*/
|
||||||
|
|
||||||
|
// Increment this if the format of sharedData changes in a breaking way.
|
||||||
|
var sharedDataVersion = 1;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @template T
|
||||||
|
* @param {T} defaults
|
||||||
|
* @returns {T}
|
||||||
|
*/
|
||||||
|
function initializeSharedData(defaults) {
|
||||||
|
var sharedDataKey = 'source-map-support/sharedData';
|
||||||
|
if (typeof Symbol !== 'undefined') {
|
||||||
|
sharedDataKey = Symbol.for(sharedDataKey);
|
||||||
|
}
|
||||||
|
var sharedData = this[sharedDataKey];
|
||||||
|
if (!sharedData) {
|
||||||
|
sharedData = { version: sharedDataVersion };
|
||||||
|
if (Object.defineProperty) {
|
||||||
|
Object.defineProperty(this, sharedDataKey, { value: sharedData });
|
||||||
|
} else {
|
||||||
|
this[sharedDataKey] = sharedData;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (sharedDataVersion !== sharedData.version) {
|
||||||
|
throw new Error("Multiple incompatible instances of source-map-support were loaded");
|
||||||
|
}
|
||||||
|
for (var key in defaults) {
|
||||||
|
if (!(key in sharedData)) {
|
||||||
|
sharedData[key] = defaults[key];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return sharedData;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If multiple instances of source-map-support are loaded into the same
|
||||||
|
// context, they shouldn't overwrite each other. By storing handlers, caches,
|
||||||
|
// and other state on a shared object, different instances of
|
||||||
|
// source-map-support can work together in a limited way. This does require
|
||||||
|
// that future versions of source-map-support continue to support the fields on
|
||||||
|
// this object. If this internal contract ever needs to be broken, increment
|
||||||
|
// sharedDataVersion. (This version number is not the same as any of the
|
||||||
|
// package's version numbers, which should reflect the *external* API of
|
||||||
|
// source-map-support.)
|
||||||
|
var sharedData = initializeSharedData({
|
||||||
|
|
||||||
|
// Only install once if called multiple times
|
||||||
|
// Remember how the environment looked before installation so we can restore if able
|
||||||
|
/** @type {HookState} */
|
||||||
|
errorPrepareStackTraceHook: undefined,
|
||||||
|
/** @type {HookState} */
|
||||||
|
processEmitHook: undefined,
|
||||||
|
/** @type {HookState} */
|
||||||
|
moduleResolveFilenameHook: undefined,
|
||||||
|
|
||||||
|
/** @type {Array<(request: string, parent: any, isMain: boolean, options: any, redirectedRequest: string) => void>} */
|
||||||
|
onConflictingLibraryRedirectArr: [],
|
||||||
|
|
||||||
|
// If true, the caches are reset before a stack trace formatting operation
|
||||||
|
emptyCacheBetweenOperations: false,
|
||||||
|
|
||||||
|
// Maps a file path to a string containing the file contents
|
||||||
|
fileContentsCache: Object.create(null),
|
||||||
|
|
||||||
|
// Maps a file path to a source map for that file
|
||||||
|
/** @type {Record<string, {url: string, map: TraceMap}} */
|
||||||
|
sourceMapCache: Object.create(null),
|
||||||
|
|
||||||
|
// Priority list of retrieve handlers
|
||||||
|
retrieveFileHandlers: [],
|
||||||
|
retrieveMapHandlers: [],
|
||||||
|
|
||||||
|
// Priority list of internally-implemented handlers.
|
||||||
|
// When resetting state, we must keep these.
|
||||||
|
internalRetrieveFileHandlers: [],
|
||||||
|
internalRetrieveMapHandlers: [],
|
||||||
|
|
||||||
|
});
|
||||||
|
|
||||||
|
// Supports {browser, node, auto}
|
||||||
|
var environment = "auto";
|
||||||
|
|
||||||
|
// Regex for detecting source maps
|
||||||
|
var reSourceMap = /^data:application\/json[^,]+base64,/;
|
||||||
|
|
||||||
|
function isInBrowser() {
|
||||||
|
if (environment === "browser")
|
||||||
|
return true;
|
||||||
|
if (environment === "node")
|
||||||
|
return false;
|
||||||
|
return ((typeof window !== 'undefined') && (typeof XMLHttpRequest === 'function') && !(window.require && window.module && window.process && window.process.type === "renderer"));
|
||||||
|
}
|
||||||
|
|
||||||
|
function hasGlobalProcessEventEmitter() {
|
||||||
|
return ((typeof process === 'object') && (process !== null) && (typeof process.on === 'function'));
|
||||||
|
}
|
||||||
|
|
||||||
|
function tryFileURLToPath(v) {
|
||||||
|
if(isFileUrl(v)) {
|
||||||
|
return fileURLToPath(v);
|
||||||
|
}
|
||||||
|
return v;
|
||||||
|
}
|
||||||
|
|
||||||
|
// TODO un-copy these from resolve-uri; see if they can be exported from that lib
|
||||||
|
function isFileUrl(input) {
|
||||||
|
return input.startsWith('file:');
|
||||||
|
}
|
||||||
|
function isAbsoluteUrl(input) {
|
||||||
|
return schemeRegex.test(input);
|
||||||
|
}
|
||||||
|
// Matches the scheme of a URL, eg "http://"
|
||||||
|
const schemeRegex = /^[\w+.-]+:\/\//;
|
||||||
|
function isSchemeRelativeUrl(input) {
|
||||||
|
return input.startsWith('//');
|
||||||
|
}
|
||||||
|
|
||||||
|
// #region Caches
|
||||||
|
/** @param {string} pathOrFileUrl */
|
||||||
|
function getCacheKey(pathOrFileUrl) {
|
||||||
|
if(pathOrFileUrl.startsWith('node:')) return pathOrFileUrl;
|
||||||
|
if(isFileUrl(pathOrFileUrl)) {
|
||||||
|
// Must normalize spaces to %20, stuff like that
|
||||||
|
return new URL(pathOrFileUrl).toString();
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
return pathToFileURL(pathOrFileUrl).toString();
|
||||||
|
} catch {
|
||||||
|
return pathOrFileUrl;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function getFileContentsCache(key) {
|
||||||
|
return sharedData.fileContentsCache[getCacheKey(key)];
|
||||||
|
}
|
||||||
|
function hasFileContentsCacheFromKey(key) {
|
||||||
|
return Object.prototype.hasOwnProperty.call(sharedData.fileContentsCache, key);
|
||||||
|
}
|
||||||
|
function getFileContentsCacheFromKey(key) {
|
||||||
|
return sharedData.fileContentsCache[key];
|
||||||
|
}
|
||||||
|
function setFileContentsCache(key, value) {
|
||||||
|
return sharedData.fileContentsCache[getCacheKey(key)] = value;
|
||||||
|
}
|
||||||
|
function getSourceMapCache(key) {
|
||||||
|
return sharedData.sourceMapCache[getCacheKey(key)];
|
||||||
|
}
|
||||||
|
function setSourceMapCache(key, value) {
|
||||||
|
return sharedData.sourceMapCache[getCacheKey(key)] = value;
|
||||||
|
}
|
||||||
|
function clearCaches() {
|
||||||
|
sharedData.fileContentsCache = Object.create(null);
|
||||||
|
sharedData.sourceMapCache = Object.create(null);
|
||||||
|
}
|
||||||
|
// #endregion Caches
|
||||||
|
|
||||||
|
function handlerExec(list, internalList) {
|
||||||
|
return function(arg) {
|
||||||
|
for (var i = 0; i < list.length; i++) {
|
||||||
|
var ret = list[i](arg);
|
||||||
|
if (ret) {
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (var i = 0; i < internalList.length; i++) {
|
||||||
|
var ret = internalList[i](arg);
|
||||||
|
if (ret) {
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
var retrieveFile = handlerExec(sharedData.retrieveFileHandlers, sharedData.internalRetrieveFileHandlers);
|
||||||
|
|
||||||
|
sharedData.internalRetrieveFileHandlers.push(function(path) {
|
||||||
|
// Trim the path to make sure there is no extra whitespace.
|
||||||
|
path = path.trim();
|
||||||
|
if (/^file:/.test(path)) {
|
||||||
|
// existsSync/readFileSync can't handle file protocol, but once stripped, it works
|
||||||
|
path = path.replace(/file:\/\/\/(\w:)?/, function(protocol, drive) {
|
||||||
|
return drive ?
|
||||||
|
'' : // file:///C:/dir/file -> C:/dir/file
|
||||||
|
'/'; // file:///root-dir/file -> /root-dir/file
|
||||||
|
});
|
||||||
|
}
|
||||||
|
const key = getCacheKey(path);
|
||||||
|
if(hasFileContentsCacheFromKey(key)) {
|
||||||
|
return getFileContentsCacheFromKey(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
var contents = '';
|
||||||
|
try {
|
||||||
|
if (!fs) {
|
||||||
|
// Use SJAX if we are in the browser
|
||||||
|
var xhr = new XMLHttpRequest();
|
||||||
|
xhr.open('GET', path, /** async */ false);
|
||||||
|
xhr.send(null);
|
||||||
|
if (xhr.readyState === 4 && xhr.status === 200) {
|
||||||
|
contents = xhr.responseText;
|
||||||
|
}
|
||||||
|
} else if (fs.existsSync(path)) {
|
||||||
|
// Otherwise, use the filesystem
|
||||||
|
contents = fs.readFileSync(path, 'utf8');
|
||||||
|
}
|
||||||
|
} catch (er) {
|
||||||
|
/* ignore any errors */
|
||||||
|
}
|
||||||
|
|
||||||
|
return setFileContentsCache(path, contents);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Support URLs relative to a directory, but be careful about a protocol prefix
|
||||||
|
// in case we are in the browser (i.e. directories may start with "http://" or "file:///")
|
||||||
|
function supportRelativeURL(file, url) {
|
||||||
|
if(!file) return url;
|
||||||
|
// given that this happens within error formatting codepath, probably best to
|
||||||
|
// fallback instead of throwing if anything goes wrong
|
||||||
|
try {
|
||||||
|
// if should output a URL
|
||||||
|
if(isAbsoluteUrl(file) || isSchemeRelativeUrl(file)) {
|
||||||
|
if(isAbsoluteUrl(url) || isSchemeRelativeUrl(url)) {
|
||||||
|
return new URL(url, file).toString();
|
||||||
|
}
|
||||||
|
if(path.isAbsolute(url)) {
|
||||||
|
return new URL(pathToFileURL(url), file).toString();
|
||||||
|
}
|
||||||
|
// url is relative path or URL
|
||||||
|
return new URL(url.replace(/\\/g, '/'), file).toString();
|
||||||
|
}
|
||||||
|
// if should output a path (unless URL is something like https://)
|
||||||
|
if(path.isAbsolute(file)) {
|
||||||
|
if(isFileUrl(url)) {
|
||||||
|
return fileURLToPath(url);
|
||||||
|
}
|
||||||
|
if(isSchemeRelativeUrl(url)) {
|
||||||
|
return fileURLToPath(new URL(url, 'file://'));
|
||||||
|
}
|
||||||
|
if(isAbsoluteUrl(url)) {
|
||||||
|
// url is a non-file URL
|
||||||
|
// Go with the URL
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
if(path.isAbsolute(url)) {
|
||||||
|
// Normalize at all? decodeURI or normalize slashes?
|
||||||
|
return path.normalize(url);
|
||||||
|
}
|
||||||
|
// url is relative path or URL
|
||||||
|
return path.join(file, '..', decodeURI(url));
|
||||||
|
}
|
||||||
|
// If we get here, file is relative.
|
||||||
|
// Shouldn't happen since node identifies modules with absolute paths or URLs.
|
||||||
|
// But we can take a stab at returning something meaningful anyway.
|
||||||
|
if(isAbsoluteUrl(url) || isSchemeRelativeUrl(url)) {
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
return path.join(file, '..', url);
|
||||||
|
} catch(e) {
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Return pathOrUrl in the same style as matchStyleOf: either a file URL or a native path
|
||||||
|
function matchStyleOfPathOrUrl(matchStyleOf, pathOrUrl) {
|
||||||
|
try {
|
||||||
|
if(isAbsoluteUrl(matchStyleOf) || isSchemeRelativeUrl(matchStyleOf)) {
|
||||||
|
if(isAbsoluteUrl(pathOrUrl) || isSchemeRelativeUrl(pathOrUrl)) return pathOrUrl;
|
||||||
|
if(path.isAbsolute(pathOrUrl)) return pathToFileURL(pathOrUrl).toString();
|
||||||
|
} else if(path.isAbsolute(matchStyleOf)) {
|
||||||
|
if(isAbsoluteUrl(pathOrUrl) || isSchemeRelativeUrl(pathOrUrl)) {
|
||||||
|
return fileURLToPath(new URL(pathOrUrl, 'file://'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return pathOrUrl;
|
||||||
|
} catch(e) {
|
||||||
|
return pathOrUrl;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function retrieveSourceMapURL(source) {
|
||||||
|
var fileData;
|
||||||
|
|
||||||
|
if (isInBrowser()) {
|
||||||
|
try {
|
||||||
|
var xhr = new XMLHttpRequest();
|
||||||
|
xhr.open('GET', source, false);
|
||||||
|
xhr.send(null);
|
||||||
|
fileData = xhr.readyState === 4 ? xhr.responseText : null;
|
||||||
|
|
||||||
|
// Support providing a sourceMappingURL via the SourceMap header
|
||||||
|
var sourceMapHeader = xhr.getResponseHeader("SourceMap") ||
|
||||||
|
xhr.getResponseHeader("X-SourceMap");
|
||||||
|
if (sourceMapHeader) {
|
||||||
|
return sourceMapHeader;
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get the URL of the source map
|
||||||
|
fileData = retrieveFile(tryFileURLToPath(source));
|
||||||
|
var re = /(?:\/\/[@#][\s]*sourceMappingURL=([^\s'"]+)[\s]*$)|(?:\/\*[@#][\s]*sourceMappingURL=([^\s*'"]+)[\s]*(?:\*\/)[\s]*$)/mg;
|
||||||
|
// Keep executing the search to find the *last* sourceMappingURL to avoid
|
||||||
|
// picking up sourceMappingURLs from comments, strings, etc.
|
||||||
|
var lastMatch, match;
|
||||||
|
while (match = re.exec(fileData)) lastMatch = match;
|
||||||
|
if (!lastMatch) return null;
|
||||||
|
return lastMatch[1];
|
||||||
|
};
|
||||||
|
|
||||||
|
// Can be overridden by the retrieveSourceMap option to install. Takes a
|
||||||
|
// generated source filename; returns a {map, optional url} object, or null if
|
||||||
|
// there is no source map. The map field may be either a string or the parsed
|
||||||
|
// JSON object (ie, it must be a valid argument to the SourceMapConsumer
|
||||||
|
// constructor).
|
||||||
|
/** @type {(source: string) => import('./source-map-support').UrlAndMap | null} */
|
||||||
|
var retrieveSourceMap = handlerExec(sharedData.retrieveMapHandlers, sharedData.internalRetrieveMapHandlers);
|
||||||
|
sharedData.internalRetrieveMapHandlers.push(function(source) {
|
||||||
|
var sourceMappingURL = retrieveSourceMapURL(source);
|
||||||
|
if (!sourceMappingURL) return null;
|
||||||
|
|
||||||
|
// Read the contents of the source map
|
||||||
|
var sourceMapData;
|
||||||
|
if (reSourceMap.test(sourceMappingURL)) {
|
||||||
|
// Support source map URL as a data url
|
||||||
|
var rawData = sourceMappingURL.slice(sourceMappingURL.indexOf(',') + 1);
|
||||||
|
sourceMapData = Buffer.from(rawData, "base64").toString();
|
||||||
|
sourceMappingURL = source;
|
||||||
|
} else {
|
||||||
|
// Support source map URLs relative to the source URL
|
||||||
|
sourceMappingURL = supportRelativeURL(source, sourceMappingURL);
|
||||||
|
sourceMapData = retrieveFile(tryFileURLToPath(sourceMappingURL));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!sourceMapData) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
url: sourceMappingURL,
|
||||||
|
map: sourceMapData
|
||||||
|
};
|
||||||
|
});
|
||||||
|
|
||||||
|
function mapSourcePosition(position) {
|
||||||
|
var sourceMap = getSourceMapCache(position.source);
|
||||||
|
if (!sourceMap) {
|
||||||
|
// Call the (overrideable) retrieveSourceMap function to get the source map.
|
||||||
|
var urlAndMap = retrieveSourceMap(position.source);
|
||||||
|
if (urlAndMap) {
|
||||||
|
sourceMap = setSourceMapCache(position.source, {
|
||||||
|
url: urlAndMap.url,
|
||||||
|
map: new AnyMap(urlAndMap.map, urlAndMap.url)
|
||||||
|
});
|
||||||
|
|
||||||
|
// Overwrite trace-mapping's resolutions, because they do not handle
|
||||||
|
// Windows paths the way we want.
|
||||||
|
// TODO Remove now that windows path support was added to resolve-uri and thus trace-mapping?
|
||||||
|
sourceMap.map.resolvedSources = sourceMap.map.sources.map(s => supportRelativeURL(sourceMap.url, s));
|
||||||
|
|
||||||
|
// Load all sources stored inline with the source map into the file cache
|
||||||
|
// to pretend like they are already loaded. They may not exist on disk.
|
||||||
|
if (sourceMap.map.sourcesContent) {
|
||||||
|
sourceMap.map.resolvedSources.forEach(function(resolvedSource, i) {
|
||||||
|
var contents = sourceMap.map.sourcesContent[i];
|
||||||
|
if (contents) {
|
||||||
|
setFileContentsCache(resolvedSource, contents);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
sourceMap = setSourceMapCache(position.source, {
|
||||||
|
url: null,
|
||||||
|
map: null
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Resolve the source URL relative to the URL of the source map
|
||||||
|
if (sourceMap && sourceMap.map) {
|
||||||
|
var originalPosition = originalPositionFor(sourceMap.map, position);
|
||||||
|
|
||||||
|
// Only return the original position if a matching line was found. If no
|
||||||
|
// matching line is found then we return position instead, which will cause
|
||||||
|
// the stack trace to print the path and line for the compiled file. It is
|
||||||
|
// better to give a precise location in the compiled file than a vague
|
||||||
|
// location in the original file.
|
||||||
|
if (originalPosition.source !== null) {
|
||||||
|
// originalPosition.source has *already* been resolved against sourceMap.url
|
||||||
|
// so is *already* as absolute as possible.
|
||||||
|
// However, we want to ensure we output in same format as input: URL or native path
|
||||||
|
originalPosition.source = matchStyleOfPathOrUrl(
|
||||||
|
position.source, originalPosition.source);
|
||||||
|
return originalPosition;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return position;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parses code generated by FormatEvalOrigin(), a function inside V8:
|
||||||
|
// https://code.google.com/p/v8/source/browse/trunk/src/messages.js
|
||||||
|
function mapEvalOrigin(origin) {
|
||||||
|
// Most eval() calls are in this format
|
||||||
|
var match = /^eval at ([^(]+) \((.+):(\d+):(\d+)\)$/.exec(origin);
|
||||||
|
if (match) {
|
||||||
|
var position = mapSourcePosition({
|
||||||
|
source: match[2],
|
||||||
|
line: +match[3],
|
||||||
|
column: match[4] - 1
|
||||||
|
});
|
||||||
|
return 'eval at ' + match[1] + ' (' + position.source + ':' +
|
||||||
|
position.line + ':' + (position.column + 1) + ')';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse nested eval() calls using recursion
|
||||||
|
match = /^eval at ([^(]+) \((.+)\)$/.exec(origin);
|
||||||
|
if (match) {
|
||||||
|
return 'eval at ' + match[1] + ' (' + mapEvalOrigin(match[2]) + ')';
|
||||||
|
}
|
||||||
|
|
||||||
|
// Make sure we still return useful information if we didn't find anything
|
||||||
|
return origin;
|
||||||
|
}
|
||||||
|
|
||||||
|
// This is copied almost verbatim from the V8 source code at
|
||||||
|
// https://code.google.com/p/v8/source/browse/trunk/src/messages.js
|
||||||
|
// Update 2022-04-29:
|
||||||
|
// https://github.com/v8/v8/blob/98f6f100c5ab8e390e51422747c4ef644d5ac6f2/src/builtins/builtins-callsite.cc#L175-L179
|
||||||
|
// https://github.com/v8/v8/blob/98f6f100c5ab8e390e51422747c4ef644d5ac6f2/src/objects/call-site-info.cc#L795-L804
|
||||||
|
// https://github.com/v8/v8/blob/98f6f100c5ab8e390e51422747c4ef644d5ac6f2/src/objects/call-site-info.cc#L717-L750
|
||||||
|
// The implementation of wrapCallSite() used to just forward to the actual source
|
||||||
|
// code of CallSite.prototype.toString but unfortunately a new release of V8
|
||||||
|
// did something to the prototype chain and broke the shim. The only fix I
|
||||||
|
// could find was copy/paste.
|
||||||
|
function CallSiteToString() {
|
||||||
|
var fileName;
|
||||||
|
var fileLocation = "";
|
||||||
|
if (this.isNative()) {
|
||||||
|
fileLocation = "native";
|
||||||
|
} else {
|
||||||
|
fileName = this.getScriptNameOrSourceURL();
|
||||||
|
if (!fileName && this.isEval()) {
|
||||||
|
fileLocation = this.getEvalOrigin();
|
||||||
|
fileLocation += ", "; // Expecting source position to follow.
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fileName) {
|
||||||
|
fileLocation += fileName;
|
||||||
|
} else {
|
||||||
|
// Source code does not originate from a file and is not native, but we
|
||||||
|
// can still get the source position inside the source string, e.g. in
|
||||||
|
// an eval string.
|
||||||
|
fileLocation += "<anonymous>";
|
||||||
|
}
|
||||||
|
var lineNumber = this.getLineNumber();
|
||||||
|
if (lineNumber != null) {
|
||||||
|
fileLocation += ":" + lineNumber;
|
||||||
|
var columnNumber = this.getColumnNumber();
|
||||||
|
if (columnNumber) {
|
||||||
|
fileLocation += ":" + columnNumber;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
var line = "";
|
||||||
|
var isAsync = this.isAsync ? this.isAsync() : false;
|
||||||
|
if(isAsync) {
|
||||||
|
line += 'async ';
|
||||||
|
var isPromiseAll = this.isPromiseAll ? this.isPromiseAll() : false;
|
||||||
|
var isPromiseAny = this.isPromiseAny ? this.isPromiseAny() : false;
|
||||||
|
if(isPromiseAny || isPromiseAll) {
|
||||||
|
line += isPromiseAll ? 'Promise.all (index ' : 'Promise.any (index ';
|
||||||
|
var promiseIndex = this.getPromiseIndex();
|
||||||
|
line += promiseIndex + ')';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
var functionName = this.getFunctionName();
|
||||||
|
var addSuffix = true;
|
||||||
|
var isConstructor = this.isConstructor();
|
||||||
|
var isMethodCall = !(this.isToplevel() || isConstructor);
|
||||||
|
if (isMethodCall) {
|
||||||
|
var typeName = this.getTypeName();
|
||||||
|
// Fixes shim to be backward compatable with Node v0 to v4
|
||||||
|
if (typeName === "[object Object]") {
|
||||||
|
typeName = "null";
|
||||||
|
}
|
||||||
|
var methodName = this.getMethodName();
|
||||||
|
if (functionName) {
|
||||||
|
if (typeName && functionName.indexOf(typeName) != 0) {
|
||||||
|
line += typeName + ".";
|
||||||
|
}
|
||||||
|
line += functionName;
|
||||||
|
if (methodName && functionName.indexOf("." + methodName) != functionName.length - methodName.length - 1) {
|
||||||
|
line += " [as " + methodName + "]";
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
line += typeName + "." + (methodName || "<anonymous>");
|
||||||
|
}
|
||||||
|
} else if (isConstructor) {
|
||||||
|
line += "new " + (functionName || "<anonymous>");
|
||||||
|
} else if (functionName) {
|
||||||
|
line += functionName;
|
||||||
|
} else {
|
||||||
|
line += fileLocation;
|
||||||
|
addSuffix = false;
|
||||||
|
}
|
||||||
|
if (addSuffix) {
|
||||||
|
line += " (" + fileLocation + ")";
|
||||||
|
}
|
||||||
|
return line;
|
||||||
|
}
|
||||||
|
|
||||||
|
function cloneCallSite(frame) {
|
||||||
|
var object = {};
|
||||||
|
Object.getOwnPropertyNames(Object.getPrototypeOf(frame)).forEach(function(name) {
|
||||||
|
object[name] = /^(?:is|get)/.test(name) ? function() { return frame[name].call(frame); } : frame[name];
|
||||||
|
});
|
||||||
|
object.toString = CallSiteToString;
|
||||||
|
return object;
|
||||||
|
}
|
||||||
|
|
||||||
|
function wrapCallSite(frame, state) {
|
||||||
|
// provides interface backward compatibility
|
||||||
|
if (state === undefined) {
|
||||||
|
state = { nextPosition: null, curPosition: null }
|
||||||
|
}
|
||||||
|
if(frame.isNative()) {
|
||||||
|
state.curPosition = null;
|
||||||
|
return frame;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Most call sites will return the source file from getFileName(), but code
|
||||||
|
// passed to eval() ending in "//# sourceURL=..." will return the source file
|
||||||
|
// from getScriptNameOrSourceURL() instead
|
||||||
|
var source = frame.getFileName() || frame.getScriptNameOrSourceURL();
|
||||||
|
if (source) {
|
||||||
|
// v8 does not expose its internal isWasm, etc methods, so we do this instead.
|
||||||
|
if(source.startsWith('wasm://')) {
|
||||||
|
state.curPosition = null;
|
||||||
|
return frame;
|
||||||
|
}
|
||||||
|
|
||||||
|
var line = frame.getLineNumber();
|
||||||
|
var column = frame.getColumnNumber() - 1;
|
||||||
|
|
||||||
|
// Fix position in Node where some (internal) code is prepended.
|
||||||
|
// See https://github.com/evanw/node-source-map-support/issues/36
|
||||||
|
// Header removed in node at ^10.16 || >=11.11.0
|
||||||
|
// v11 is not an LTS candidate, we can just test the one version with it.
|
||||||
|
// Test node versions for: 10.16-19, 10.20+, 12-19, 20-99, 100+, or 11.11
|
||||||
|
var noHeader = /^v(10\.1[6-9]|10\.[2-9][0-9]|10\.[0-9]{3,}|1[2-9]\d*|[2-9]\d|\d{3,}|11\.11)/;
|
||||||
|
var headerLength = noHeader.test(process.version) ? 0 : 62;
|
||||||
|
if (line === 1 && column > headerLength && !isInBrowser() && !frame.isEval()) {
|
||||||
|
column -= headerLength;
|
||||||
|
}
|
||||||
|
|
||||||
|
var position = mapSourcePosition({
|
||||||
|
source: source,
|
||||||
|
line: line,
|
||||||
|
column: column
|
||||||
|
});
|
||||||
|
state.curPosition = position;
|
||||||
|
frame = cloneCallSite(frame);
|
||||||
|
var originalFunctionName = frame.getFunctionName;
|
||||||
|
frame.getFunctionName = function() {
|
||||||
|
if (state.nextPosition == null) {
|
||||||
|
return originalFunctionName();
|
||||||
|
}
|
||||||
|
return state.nextPosition.name || originalFunctionName();
|
||||||
|
};
|
||||||
|
frame.getFileName = function() { return position.source; };
|
||||||
|
frame.getLineNumber = function() { return position.line; };
|
||||||
|
frame.getColumnNumber = function() { return position.column + 1; };
|
||||||
|
frame.getScriptNameOrSourceURL = function() { return position.source; };
|
||||||
|
return frame;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Code called using eval() needs special handling
|
||||||
|
var origin = frame.isEval() && frame.getEvalOrigin();
|
||||||
|
if (origin) {
|
||||||
|
origin = mapEvalOrigin(origin);
|
||||||
|
frame = cloneCallSite(frame);
|
||||||
|
frame.getEvalOrigin = function() { return origin; };
|
||||||
|
return frame;
|
||||||
|
}
|
||||||
|
|
||||||
|
// If we get here then we were unable to change the source position
|
||||||
|
return frame;
|
||||||
|
}
|
||||||
|
|
||||||
|
var kIsNodeError = undefined;
|
||||||
|
try {
|
||||||
|
// Get a deliberate ERR_INVALID_ARG_TYPE
|
||||||
|
// TODO is there a better way to reliably get an instance of NodeError?
|
||||||
|
path.resolve(123);
|
||||||
|
} catch(e) {
|
||||||
|
const symbols = Object.getOwnPropertySymbols(e);
|
||||||
|
const symbol = symbols.find(function (s) {return s.toString().indexOf('kIsNodeError') >= 0});
|
||||||
|
if(symbol) kIsNodeError = symbol;
|
||||||
|
}
|
||||||
|
|
||||||
|
const ErrorPrototypeToString = (err) =>Error.prototype.toString.call(err);
|
||||||
|
|
||||||
|
/** @param {HookState} hookState */
|
||||||
|
function createPrepareStackTrace(hookState) {
|
||||||
|
return prepareStackTrace;
|
||||||
|
|
||||||
|
// This function is part of the V8 stack trace API, for more info see:
|
||||||
|
// https://v8.dev/docs/stack-trace-api
|
||||||
|
function prepareStackTrace(error, stack) {
|
||||||
|
if(!hookState.enabled) return hookState.originalValue.apply(this, arguments);
|
||||||
|
|
||||||
|
if (sharedData.emptyCacheBetweenOperations) {
|
||||||
|
clearCaches();
|
||||||
|
}
|
||||||
|
|
||||||
|
// node gives its own errors special treatment. Mimic that behavior
|
||||||
|
// https://github.com/nodejs/node/blob/3cbaabc4622df1b4009b9d026a1a970bdbae6e89/lib/internal/errors.js#L118-L128
|
||||||
|
// https://github.com/nodejs/node/pull/39182
|
||||||
|
var errorString;
|
||||||
|
if (kIsNodeError) {
|
||||||
|
if(kIsNodeError in error) {
|
||||||
|
errorString = `${error.name} [${error.code}]: ${error.message}`;
|
||||||
|
} else {
|
||||||
|
errorString = ErrorPrototypeToString(error);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
var name = error.name || 'Error';
|
||||||
|
var message = error.message || '';
|
||||||
|
errorString = message ? name + ": " + message : name;
|
||||||
|
}
|
||||||
|
|
||||||
|
var state = { nextPosition: null, curPosition: null };
|
||||||
|
var processedStack = [];
|
||||||
|
for (var i = stack.length - 1; i >= 0; i--) {
|
||||||
|
processedStack.push('\n at ' + wrapCallSite(stack[i], state));
|
||||||
|
state.nextPosition = state.curPosition;
|
||||||
|
}
|
||||||
|
state.curPosition = state.nextPosition = null;
|
||||||
|
return errorString + processedStack.reverse().join('');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generate position and snippet of original source with pointer
|
||||||
|
function getErrorSource(error) {
|
||||||
|
var match = /\n at [^(]+ \((.*):(\d+):(\d+)\)/.exec(error.stack);
|
||||||
|
if (match) {
|
||||||
|
var source = match[1];
|
||||||
|
var line = +match[2];
|
||||||
|
var column = +match[3];
|
||||||
|
|
||||||
|
// Support the inline sourceContents inside the source map
|
||||||
|
var contents = getFileContentsCache(source);
|
||||||
|
|
||||||
|
const sourceAsPath = tryFileURLToPath(source);
|
||||||
|
|
||||||
|
// Support files on disk
|
||||||
|
if (!contents && fs && fs.existsSync(sourceAsPath)) {
|
||||||
|
try {
|
||||||
|
contents = fs.readFileSync(sourceAsPath, 'utf8');
|
||||||
|
} catch (er) {
|
||||||
|
contents = '';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Format the line from the original source code like node does
|
||||||
|
if (contents) {
|
||||||
|
var code = contents.split(/(?:\r\n|\r|\n)/)[line - 1];
|
||||||
|
if (code) {
|
||||||
|
return source + ':' + line + '\n' + code + '\n' +
|
||||||
|
new Array(column).join(' ') + '^';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function printFatalErrorUponExit (error) {
|
||||||
|
var source = getErrorSource(error);
|
||||||
|
|
||||||
|
// Ensure error is printed synchronously and not truncated
|
||||||
|
if (process.stderr._handle && process.stderr._handle.setBlocking) {
|
||||||
|
process.stderr._handle.setBlocking(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (source) {
|
||||||
|
console.error(source);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Matches node's behavior for colorized output
|
||||||
|
console.error(
|
||||||
|
util.inspect(error, {
|
||||||
|
customInspect: false,
|
||||||
|
colors: process.stderr.isTTY
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function shimEmitUncaughtException () {
|
||||||
|
const originalValue = process.emit;
|
||||||
|
var hook = sharedData.processEmitHook = {
|
||||||
|
enabled: true,
|
||||||
|
originalValue,
|
||||||
|
installedValue: undefined
|
||||||
|
};
|
||||||
|
var isTerminatingDueToFatalException = false;
|
||||||
|
var fatalException;
|
||||||
|
|
||||||
|
process.emit = sharedData.processEmitHook.installedValue = function (type) {
|
||||||
|
const hadListeners = originalValue.apply(this, arguments);
|
||||||
|
if(hook.enabled) {
|
||||||
|
if (type === 'uncaughtException' && !hadListeners) {
|
||||||
|
isTerminatingDueToFatalException = true;
|
||||||
|
fatalException = arguments[1];
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
if (type === 'exit' && isTerminatingDueToFatalException) {
|
||||||
|
printFatalErrorUponExit(fatalException);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return hadListeners;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
var originalRetrieveFileHandlers = sharedData.retrieveFileHandlers.slice(0);
|
||||||
|
var originalRetrieveMapHandlers = sharedData.retrieveMapHandlers.slice(0);
|
||||||
|
|
||||||
|
exports.wrapCallSite = wrapCallSite;
|
||||||
|
exports.getErrorSource = getErrorSource;
|
||||||
|
exports.mapSourcePosition = mapSourcePosition;
|
||||||
|
exports.retrieveSourceMap = retrieveSourceMap;
|
||||||
|
|
||||||
|
exports.install = function(options) {
|
||||||
|
options = options || {};
|
||||||
|
|
||||||
|
if (options.environment) {
|
||||||
|
environment = options.environment;
|
||||||
|
if (["node", "browser", "auto"].indexOf(environment) === -1) {
|
||||||
|
throw new Error("environment " + environment + " was unknown. Available options are {auto, browser, node}")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Use dynamicRequire to avoid including in browser bundles
|
||||||
|
var Module = dynamicRequire(module, 'module');
|
||||||
|
|
||||||
|
// Redirect subsequent imports of "source-map-support"
|
||||||
|
// to this package
|
||||||
|
const {redirectConflictingLibrary = true, onConflictingLibraryRedirect} = options;
|
||||||
|
if(redirectConflictingLibrary) {
|
||||||
|
if (!sharedData.moduleResolveFilenameHook) {
|
||||||
|
const originalValue = Module._resolveFilename;
|
||||||
|
const moduleResolveFilenameHook = sharedData.moduleResolveFilenameHook = {
|
||||||
|
enabled: true,
|
||||||
|
originalValue,
|
||||||
|
installedValue: undefined,
|
||||||
|
}
|
||||||
|
Module._resolveFilename = sharedData.moduleResolveFilenameHook.installedValue = function (request, parent, isMain, options) {
|
||||||
|
if (moduleResolveFilenameHook.enabled) {
|
||||||
|
// Match all source-map-support entrypoints: source-map-support, source-map-support/register
|
||||||
|
let requestRedirect;
|
||||||
|
if (request === 'source-map-support') {
|
||||||
|
requestRedirect = './';
|
||||||
|
} else if (request === 'source-map-support/register') {
|
||||||
|
requestRedirect = './register';
|
||||||
|
}
|
||||||
|
|
||||||
|
if (requestRedirect !== undefined) {
|
||||||
|
const newRequest = require.resolve(requestRedirect);
|
||||||
|
for (const cb of sharedData.onConflictingLibraryRedirectArr) {
|
||||||
|
cb(request, parent, isMain, options, newRequest);
|
||||||
|
}
|
||||||
|
request = newRequest;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return originalValue.call(this, request, parent, isMain, options);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (onConflictingLibraryRedirect) {
|
||||||
|
sharedData.onConflictingLibraryRedirectArr.push(onConflictingLibraryRedirect);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Allow sources to be found by methods other than reading the files
|
||||||
|
// directly from disk.
|
||||||
|
if (options.retrieveFile) {
|
||||||
|
if (options.overrideRetrieveFile) {
|
||||||
|
sharedData.retrieveFileHandlers.length = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
sharedData.retrieveFileHandlers.unshift(options.retrieveFile);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Allow source maps to be found by methods other than reading the files
|
||||||
|
// directly from disk.
|
||||||
|
if (options.retrieveSourceMap) {
|
||||||
|
if (options.overrideRetrieveSourceMap) {
|
||||||
|
sharedData.retrieveMapHandlers.length = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
sharedData.retrieveMapHandlers.unshift(options.retrieveSourceMap);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Support runtime transpilers that include inline source maps
|
||||||
|
if (options.hookRequire && !isInBrowser()) {
|
||||||
|
var $compile = Module.prototype._compile;
|
||||||
|
|
||||||
|
if (!$compile.__sourceMapSupport) {
|
||||||
|
Module.prototype._compile = function(content, filename) {
|
||||||
|
setFileContentsCache(filename, content);
|
||||||
|
setSourceMapCache(filename, undefined);
|
||||||
|
return $compile.call(this, content, filename);
|
||||||
|
};
|
||||||
|
|
||||||
|
Module.prototype._compile.__sourceMapSupport = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Configure options
|
||||||
|
if (!sharedData.emptyCacheBetweenOperations) {
|
||||||
|
sharedData.emptyCacheBetweenOperations = 'emptyCacheBetweenOperations' in options ?
|
||||||
|
options.emptyCacheBetweenOperations : false;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
// Install the error reformatter
|
||||||
|
if (!sharedData.errorPrepareStackTraceHook) {
|
||||||
|
const originalValue = Error.prepareStackTrace;
|
||||||
|
sharedData.errorPrepareStackTraceHook = {
|
||||||
|
enabled: true,
|
||||||
|
originalValue,
|
||||||
|
installedValue: undefined
|
||||||
|
};
|
||||||
|
Error.prepareStackTrace = sharedData.errorPrepareStackTraceHook.installedValue = createPrepareStackTrace(sharedData.errorPrepareStackTraceHook);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!sharedData.processEmitHook) {
|
||||||
|
var installHandler = 'handleUncaughtExceptions' in options ?
|
||||||
|
options.handleUncaughtExceptions : true;
|
||||||
|
|
||||||
|
// Do not override 'uncaughtException' with our own handler in Node.js
|
||||||
|
// Worker threads. Workers pass the error to the main thread as an event,
|
||||||
|
// rather than printing something to stderr and exiting.
|
||||||
|
try {
|
||||||
|
// We need to use `dynamicRequire` because `require` on it's own will be optimized by WebPack/Browserify.
|
||||||
|
var worker_threads = dynamicRequire(module, 'worker_threads');
|
||||||
|
if (worker_threads.isMainThread === false) {
|
||||||
|
installHandler = false;
|
||||||
|
}
|
||||||
|
} catch(e) {}
|
||||||
|
|
||||||
|
// Provide the option to not install the uncaught exception handler. This is
|
||||||
|
// to support other uncaught exception handlers (in test frameworks, for
|
||||||
|
// example). If this handler is not installed and there are no other uncaught
|
||||||
|
// exception handlers, uncaught exceptions will be caught by node's built-in
|
||||||
|
// exception handler and the process will still be terminated. However, the
|
||||||
|
// generated JavaScript code will be shown above the stack trace instead of
|
||||||
|
// the original source code.
|
||||||
|
if (installHandler && hasGlobalProcessEventEmitter()) {
|
||||||
|
shimEmitUncaughtException();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
exports.uninstall = function() {
|
||||||
|
if(sharedData.processEmitHook) {
|
||||||
|
// Disable behavior
|
||||||
|
sharedData.processEmitHook.enabled = false;
|
||||||
|
// If possible, remove our hook function. May not be possible if subsequent third-party hooks have wrapped around us.
|
||||||
|
if(process.emit === sharedData.processEmitHook.installedValue) {
|
||||||
|
process.emit = sharedData.processEmitHook.originalValue;
|
||||||
|
}
|
||||||
|
sharedData.processEmitHook = undefined;
|
||||||
|
}
|
||||||
|
if(sharedData.errorPrepareStackTraceHook) {
|
||||||
|
// Disable behavior
|
||||||
|
sharedData.errorPrepareStackTraceHook.enabled = false;
|
||||||
|
// If possible or necessary, remove our hook function.
|
||||||
|
// In vanilla environments, prepareStackTrace is `undefined`.
|
||||||
|
// We cannot delegate to `undefined` the way we can to a function w/`.apply()`; our only option is to remove the function.
|
||||||
|
// If we are the *first* hook installed, and another was installed on top of us, we have no choice but to remove both.
|
||||||
|
if(Error.prepareStackTrace === sharedData.errorPrepareStackTraceHook.installedValue || typeof sharedData.errorPrepareStackTraceHook.originalValue !== 'function') {
|
||||||
|
Error.prepareStackTrace = sharedData.errorPrepareStackTraceHook.originalValue;
|
||||||
|
}
|
||||||
|
sharedData.errorPrepareStackTraceHook = undefined;
|
||||||
|
}
|
||||||
|
if (sharedData.moduleResolveFilenameHook) {
|
||||||
|
// Disable behavior
|
||||||
|
sharedData.moduleResolveFilenameHook.enabled = false;
|
||||||
|
// If possible, remove our hook function. May not be possible if subsequent third-party hooks have wrapped around us.
|
||||||
|
var Module = dynamicRequire(module, 'module');
|
||||||
|
if(Module._resolveFilename === sharedData.moduleResolveFilenameHook.installedValue) {
|
||||||
|
Module._resolveFilename = sharedData.moduleResolveFilenameHook.originalValue;
|
||||||
|
}
|
||||||
|
sharedData.moduleResolveFilenameHook = undefined;
|
||||||
|
}
|
||||||
|
sharedData.onConflictingLibraryRedirectArr.length = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
exports.resetRetrieveHandlers = function() {
|
||||||
|
sharedData.retrieveFileHandlers.length = 0;
|
||||||
|
sharedData.retrieveMapHandlers.length = 0;
|
||||||
|
}
|
||||||
21
node_modules/@hono/node-server/LICENSE
generated
vendored
Normal file
21
node_modules/@hono/node-server/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2022 - present, Yusuke Wada and Hono contributors
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
358
node_modules/@hono/node-server/README.md
generated
vendored
Normal file
358
node_modules/@hono/node-server/README.md
generated
vendored
Normal file
@@ -0,0 +1,358 @@
|
|||||||
|
# Node.js Adapter for Hono
|
||||||
|
|
||||||
|
This adapter `@hono/node-server` allows you to run your Hono application on Node.js.
|
||||||
|
Initially, Hono wasn't designed for Node.js, but with this adapter, you can now use Hono on Node.js.
|
||||||
|
It utilizes web standard APIs implemented in Node.js version 18 or higher.
|
||||||
|
|
||||||
|
## Benchmarks
|
||||||
|
|
||||||
|
Hono is 3.5 times faster than Express.
|
||||||
|
|
||||||
|
Express:
|
||||||
|
|
||||||
|
```txt
|
||||||
|
$ bombardier -d 10s --fasthttp http://localhost:3000/
|
||||||
|
|
||||||
|
Statistics Avg Stdev Max
|
||||||
|
Reqs/sec 16438.94 1603.39 19155.47
|
||||||
|
Latency 7.60ms 7.51ms 559.89ms
|
||||||
|
HTTP codes:
|
||||||
|
1xx - 0, 2xx - 164494, 3xx - 0, 4xx - 0, 5xx - 0
|
||||||
|
others - 0
|
||||||
|
Throughput: 4.55MB/s
|
||||||
|
```
|
||||||
|
|
||||||
|
Hono + `@hono/node-server`:
|
||||||
|
|
||||||
|
```txt
|
||||||
|
$ bombardier -d 10s --fasthttp http://localhost:3000/
|
||||||
|
|
||||||
|
Statistics Avg Stdev Max
|
||||||
|
Reqs/sec 58296.56 5512.74 74403.56
|
||||||
|
Latency 2.14ms 1.46ms 190.92ms
|
||||||
|
HTTP codes:
|
||||||
|
1xx - 0, 2xx - 583059, 3xx - 0, 4xx - 0, 5xx - 0
|
||||||
|
others - 0
|
||||||
|
Throughput: 12.56MB/s
|
||||||
|
```
|
||||||
|
|
||||||
|
## Requirements
|
||||||
|
|
||||||
|
It works on Node.js versions greater than 18.x. The specific required Node.js versions are as follows:
|
||||||
|
|
||||||
|
- 18.x => 18.14.1+
|
||||||
|
- 19.x => 19.7.0+
|
||||||
|
- 20.x => 20.0.0+
|
||||||
|
|
||||||
|
Essentially, you can simply use the latest version of each major release.
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
You can install it from the npm registry with `npm` command:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
npm install @hono/node-server
|
||||||
|
```
|
||||||
|
|
||||||
|
Or use `yarn`:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
yarn add @hono/node-server
|
||||||
|
```
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
Just import `@hono/node-server` at the top and write the code as usual.
|
||||||
|
The same code that runs on Cloudflare Workers, Deno, and Bun will work.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { serve } from '@hono/node-server'
|
||||||
|
import { Hono } from 'hono'
|
||||||
|
|
||||||
|
const app = new Hono()
|
||||||
|
app.get('/', (c) => c.text('Hono meets Node.js'))
|
||||||
|
|
||||||
|
serve(app, (info) => {
|
||||||
|
console.log(`Listening on http://localhost:${info.port}`) // Listening on http://localhost:3000
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
For example, run it using `ts-node`. Then an HTTP server will be launched. The default port is `3000`.
|
||||||
|
|
||||||
|
```sh
|
||||||
|
ts-node ./index.ts
|
||||||
|
```
|
||||||
|
|
||||||
|
Open `http://localhost:3000` with your browser.
|
||||||
|
|
||||||
|
## Options
|
||||||
|
|
||||||
|
### `port`
|
||||||
|
|
||||||
|
```ts
|
||||||
|
serve({
|
||||||
|
fetch: app.fetch,
|
||||||
|
port: 8787, // Port number, default is 3000
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
### `createServer`
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { createServer } from 'node:https'
|
||||||
|
import fs from 'node:fs'
|
||||||
|
|
||||||
|
//...
|
||||||
|
|
||||||
|
serve({
|
||||||
|
fetch: app.fetch,
|
||||||
|
createServer: createServer,
|
||||||
|
serverOptions: {
|
||||||
|
key: fs.readFileSync('test/fixtures/keys/agent1-key.pem'),
|
||||||
|
cert: fs.readFileSync('test/fixtures/keys/agent1-cert.pem'),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
### `overrideGlobalObjects`
|
||||||
|
|
||||||
|
The default value is `true`. The Node.js Adapter rewrites the global Request/Response and uses a lightweight Request/Response to improve performance. If you don't want to do that, set `false`.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
serve({
|
||||||
|
fetch: app.fetch,
|
||||||
|
overrideGlobalObjects: false,
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
### `autoCleanupIncoming`
|
||||||
|
|
||||||
|
The default value is `true`. The Node.js Adapter automatically cleans up (explicitly call `destroy()` method) if application is not finished to consume the incoming request. If you don't want to do that, set `false`.
|
||||||
|
|
||||||
|
If the application accepts connections from arbitrary clients, this cleanup must be done otherwise incomplete requests from clients may cause the application to stop responding. If your application only accepts connections from trusted clients, such as in a reverse proxy environment and there is no process that returns a response without reading the body of the POST request all the way through, you can improve performance by setting it to `false`.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
serve({
|
||||||
|
fetch: app.fetch,
|
||||||
|
autoCleanupIncoming: false,
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Middleware
|
||||||
|
|
||||||
|
Most built-in middleware also works with Node.js.
|
||||||
|
Read [the documentation](https://hono.dev/middleware/builtin/basic-auth) and use the Middleware of your liking.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { serve } from '@hono/node-server'
|
||||||
|
import { Hono } from 'hono'
|
||||||
|
import { prettyJSON } from 'hono/pretty-json'
|
||||||
|
|
||||||
|
const app = new Hono()
|
||||||
|
|
||||||
|
app.get('*', prettyJSON())
|
||||||
|
app.get('/', (c) => c.json({ 'Hono meets': 'Node.js' }))
|
||||||
|
|
||||||
|
serve(app)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Serve Static Middleware
|
||||||
|
|
||||||
|
Use Serve Static Middleware that has been created for Node.js.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { serveStatic } from '@hono/node-server/serve-static'
|
||||||
|
|
||||||
|
//...
|
||||||
|
|
||||||
|
app.use('/static/*', serveStatic({ root: './' }))
|
||||||
|
```
|
||||||
|
|
||||||
|
If using a relative path, `root` will be relative to the current working directory from which the app was started.
|
||||||
|
|
||||||
|
This can cause confusion when running your application locally.
|
||||||
|
|
||||||
|
Imagine your project structure is:
|
||||||
|
|
||||||
|
```
|
||||||
|
my-hono-project/
|
||||||
|
src/
|
||||||
|
index.ts
|
||||||
|
static/
|
||||||
|
index.html
|
||||||
|
```
|
||||||
|
|
||||||
|
Typically, you would run your app from the project's root directory (`my-hono-project`),
|
||||||
|
so you would need the following code to serve the `static` folder:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
app.use('/static/*', serveStatic({ root: './static' }))
|
||||||
|
```
|
||||||
|
|
||||||
|
Notice that `root` here is not relative to `src/index.ts`, rather to `my-hono-project`.
|
||||||
|
|
||||||
|
### Options
|
||||||
|
|
||||||
|
#### `rewriteRequestPath`
|
||||||
|
|
||||||
|
If you want to serve files in `./.foojs` with the request path `/__foo/*`, you can write like the following.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
app.use(
|
||||||
|
'/__foo/*',
|
||||||
|
serveStatic({
|
||||||
|
root: './.foojs/',
|
||||||
|
rewriteRequestPath: (path: string) => path.replace(/^\/__foo/, ''),
|
||||||
|
})
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
#### `onFound`
|
||||||
|
|
||||||
|
You can specify handling when the requested file is found with `onFound`.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
app.use(
|
||||||
|
'/static/*',
|
||||||
|
serveStatic({
|
||||||
|
// ...
|
||||||
|
onFound: (_path, c) => {
|
||||||
|
c.header('Cache-Control', `public, immutable, max-age=31536000`)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
#### `onNotFound`
|
||||||
|
|
||||||
|
The `onNotFound` is useful for debugging. You can write a handle for when a file is not found.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
app.use(
|
||||||
|
'/static/*',
|
||||||
|
serveStatic({
|
||||||
|
root: './non-existent-dir',
|
||||||
|
onNotFound: (path, c) => {
|
||||||
|
console.log(`${path} is not found, request to ${c.req.path}`)
|
||||||
|
},
|
||||||
|
})
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
#### `precompressed`
|
||||||
|
|
||||||
|
The `precompressed` option checks if files with extensions like `.br` or `.gz` are available and serves them based on the `Accept-Encoding` header. It prioritizes Brotli, then Zstd, and Gzip. If none are available, it serves the original file.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
app.use(
|
||||||
|
'/static/*',
|
||||||
|
serveStatic({
|
||||||
|
precompressed: true,
|
||||||
|
})
|
||||||
|
)
|
||||||
|
```
|
||||||
|
|
||||||
|
## ConnInfo Helper
|
||||||
|
|
||||||
|
You can use the [ConnInfo Helper](https://hono.dev/docs/helpers/conninfo) by importing `getConnInfo` from `@hono/node-server/conninfo`.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { getConnInfo } from '@hono/node-server/conninfo'
|
||||||
|
|
||||||
|
app.get('/', (c) => {
|
||||||
|
const info = getConnInfo(c) // info is `ConnInfo`
|
||||||
|
return c.text(`Your remote address is ${info.remote.address}`)
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Accessing Node.js API
|
||||||
|
|
||||||
|
You can access the Node.js API from `c.env` in Node.js. For example, if you want to specify a type, you can write the following.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { serve } from '@hono/node-server'
|
||||||
|
import type { HttpBindings } from '@hono/node-server'
|
||||||
|
import { Hono } from 'hono'
|
||||||
|
|
||||||
|
const app = new Hono<{ Bindings: HttpBindings }>()
|
||||||
|
|
||||||
|
app.get('/', (c) => {
|
||||||
|
return c.json({
|
||||||
|
remoteAddress: c.env.incoming.socket.remoteAddress,
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
serve(app)
|
||||||
|
```
|
||||||
|
|
||||||
|
The APIs that you can get from `c.env` are as follows.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
type HttpBindings = {
|
||||||
|
incoming: IncomingMessage
|
||||||
|
outgoing: ServerResponse
|
||||||
|
}
|
||||||
|
|
||||||
|
type Http2Bindings = {
|
||||||
|
incoming: Http2ServerRequest
|
||||||
|
outgoing: Http2ServerResponse
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Direct response from Node.js API
|
||||||
|
|
||||||
|
You can directly respond to the client from the Node.js API.
|
||||||
|
In that case, the response from Hono should be ignored, so return `RESPONSE_ALREADY_SENT`.
|
||||||
|
|
||||||
|
> [!NOTE]
|
||||||
|
> This feature can be used when migrating existing Node.js applications to Hono, but we recommend using Hono's API for new applications.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { serve } from '@hono/node-server'
|
||||||
|
import type { HttpBindings } from '@hono/node-server'
|
||||||
|
import { RESPONSE_ALREADY_SENT } from '@hono/node-server/utils/response'
|
||||||
|
import { Hono } from 'hono'
|
||||||
|
|
||||||
|
const app = new Hono<{ Bindings: HttpBindings }>()
|
||||||
|
|
||||||
|
app.get('/', (c) => {
|
||||||
|
const { outgoing } = c.env
|
||||||
|
outgoing.writeHead(200, { 'Content-Type': 'text/plain' })
|
||||||
|
outgoing.end('Hello World\n')
|
||||||
|
|
||||||
|
return RESPONSE_ALREADY_SENT
|
||||||
|
})
|
||||||
|
|
||||||
|
serve(app)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Listen to a UNIX domain socket
|
||||||
|
|
||||||
|
You can configure the HTTP server to listen to a UNIX domain socket instead of a TCP port.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { createAdaptorServer } from '@hono/node-server'
|
||||||
|
|
||||||
|
// ...
|
||||||
|
|
||||||
|
const socketPath = '/tmp/example.sock'
|
||||||
|
|
||||||
|
const server = createAdaptorServer(app)
|
||||||
|
server.listen(socketPath, () => {
|
||||||
|
console.log(`Listening on ${socketPath}`)
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Related projects
|
||||||
|
|
||||||
|
- Hono - <https://hono.dev>
|
||||||
|
- Hono GitHub repository - <https://github.com/honojs/hono>
|
||||||
|
|
||||||
|
## Authors
|
||||||
|
|
||||||
|
- Yusuke Wada <https://github.com/yusukebe>
|
||||||
|
- Taku Amano <https://github.com/usualoma>
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
MIT
|
||||||
10
node_modules/@hono/node-server/dist/conninfo.d.mts
generated
vendored
Normal file
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';
|
||||||
702
node_modules/@hono/node-server/dist/index.js
generated
vendored
Normal file
702
node_modules/@hono/node-server/dist/index.js
generated
vendored
Normal file
@@ -0,0 +1,702 @@
|
|||||||
|
"use strict";
|
||||||
|
var __create = Object.create;
|
||||||
|
var __defProp = Object.defineProperty;
|
||||||
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||||
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||||
|
var __getProtoOf = Object.getPrototypeOf;
|
||||||
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||||
|
var __export = (target, all) => {
|
||||||
|
for (var name in all)
|
||||||
|
__defProp(target, name, { get: all[name], enumerable: true });
|
||||||
|
};
|
||||||
|
var __copyProps = (to, from, except, desc) => {
|
||||||
|
if (from && typeof from === "object" || typeof from === "function") {
|
||||||
|
for (let key of __getOwnPropNames(from))
|
||||||
|
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||||
|
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||||
|
}
|
||||||
|
return to;
|
||||||
|
};
|
||||||
|
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
||||||
|
// If the importer is in node compatibility mode or this is not an ESM
|
||||||
|
// file that has been converted to a CommonJS file using a Babel-
|
||||||
|
// compatible transform (i.e. "__esModule" has not been set), then set
|
||||||
|
// "default" to the CommonJS "module.exports" for node compatibility.
|
||||||
|
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
||||||
|
mod
|
||||||
|
));
|
||||||
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||||
|
|
||||||
|
// src/index.ts
|
||||||
|
var src_exports = {};
|
||||||
|
__export(src_exports, {
|
||||||
|
RequestError: () => RequestError,
|
||||||
|
createAdaptorServer: () => createAdaptorServer,
|
||||||
|
getRequestListener: () => getRequestListener,
|
||||||
|
serve: () => serve
|
||||||
|
});
|
||||||
|
module.exports = __toCommonJS(src_exports);
|
||||||
|
|
||||||
|
// src/server.ts
|
||||||
|
var import_node_http = require("http");
|
||||||
|
|
||||||
|
// src/listener.ts
|
||||||
|
var import_node_http22 = require("http2");
|
||||||
|
|
||||||
|
// src/request.ts
|
||||||
|
var import_node_http2 = require("http2");
|
||||||
|
var import_node_stream = require("stream");
|
||||||
|
var RequestError = class extends Error {
|
||||||
|
constructor(message, options) {
|
||||||
|
super(message, options);
|
||||||
|
this.name = "RequestError";
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var toRequestError = (e) => {
|
||||||
|
if (e instanceof RequestError) {
|
||||||
|
return e;
|
||||||
|
}
|
||||||
|
return new RequestError(e.message, { cause: e });
|
||||||
|
};
|
||||||
|
var GlobalRequest = global.Request;
|
||||||
|
var Request = class extends GlobalRequest {
|
||||||
|
constructor(input, options) {
|
||||||
|
if (typeof input === "object" && getRequestCache in input) {
|
||||||
|
input = input[getRequestCache]();
|
||||||
|
}
|
||||||
|
if (typeof options?.body?.getReader !== "undefined") {
|
||||||
|
;
|
||||||
|
options.duplex ??= "half";
|
||||||
|
}
|
||||||
|
super(input, options);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var newHeadersFromIncoming = (incoming) => {
|
||||||
|
const headerRecord = [];
|
||||||
|
const rawHeaders = incoming.rawHeaders;
|
||||||
|
for (let i = 0; i < rawHeaders.length; i += 2) {
|
||||||
|
const { [i]: key, [i + 1]: value } = rawHeaders;
|
||||||
|
if (key.charCodeAt(0) !== /*:*/
|
||||||
|
58) {
|
||||||
|
headerRecord.push([key, value]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new Headers(headerRecord);
|
||||||
|
};
|
||||||
|
var wrapBodyStream = Symbol("wrapBodyStream");
|
||||||
|
var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
|
||||||
|
const init = {
|
||||||
|
method,
|
||||||
|
headers,
|
||||||
|
signal: abortController.signal
|
||||||
|
};
|
||||||
|
if (method === "TRACE") {
|
||||||
|
init.method = "GET";
|
||||||
|
const req = new Request(url, init);
|
||||||
|
Object.defineProperty(req, "method", {
|
||||||
|
get() {
|
||||||
|
return "TRACE";
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return req;
|
||||||
|
}
|
||||||
|
if (!(method === "GET" || method === "HEAD")) {
|
||||||
|
if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
|
||||||
|
init.body = new ReadableStream({
|
||||||
|
start(controller) {
|
||||||
|
controller.enqueue(incoming.rawBody);
|
||||||
|
controller.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else if (incoming[wrapBodyStream]) {
|
||||||
|
let reader;
|
||||||
|
init.body = new ReadableStream({
|
||||||
|
async pull(controller) {
|
||||||
|
try {
|
||||||
|
reader ||= import_node_stream.Readable.toWeb(incoming).getReader();
|
||||||
|
const { done, value } = await reader.read();
|
||||||
|
if (done) {
|
||||||
|
controller.close();
|
||||||
|
} else {
|
||||||
|
controller.enqueue(value);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
controller.error(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
init.body = import_node_stream.Readable.toWeb(incoming);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new Request(url, init);
|
||||||
|
};
|
||||||
|
var getRequestCache = Symbol("getRequestCache");
|
||||||
|
var requestCache = Symbol("requestCache");
|
||||||
|
var incomingKey = Symbol("incomingKey");
|
||||||
|
var urlKey = Symbol("urlKey");
|
||||||
|
var headersKey = Symbol("headersKey");
|
||||||
|
var abortControllerKey = Symbol("abortControllerKey");
|
||||||
|
var getAbortController = Symbol("getAbortController");
|
||||||
|
var requestPrototype = {
|
||||||
|
get method() {
|
||||||
|
return this[incomingKey].method || "GET";
|
||||||
|
},
|
||||||
|
get url() {
|
||||||
|
return this[urlKey];
|
||||||
|
},
|
||||||
|
get headers() {
|
||||||
|
return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
|
||||||
|
},
|
||||||
|
[getAbortController]() {
|
||||||
|
this[getRequestCache]();
|
||||||
|
return this[abortControllerKey];
|
||||||
|
},
|
||||||
|
[getRequestCache]() {
|
||||||
|
this[abortControllerKey] ||= new AbortController();
|
||||||
|
return this[requestCache] ||= newRequestFromIncoming(
|
||||||
|
this.method,
|
||||||
|
this[urlKey],
|
||||||
|
this.headers,
|
||||||
|
this[incomingKey],
|
||||||
|
this[abortControllerKey]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
[
|
||||||
|
"body",
|
||||||
|
"bodyUsed",
|
||||||
|
"cache",
|
||||||
|
"credentials",
|
||||||
|
"destination",
|
||||||
|
"integrity",
|
||||||
|
"mode",
|
||||||
|
"redirect",
|
||||||
|
"referrer",
|
||||||
|
"referrerPolicy",
|
||||||
|
"signal",
|
||||||
|
"keepalive"
|
||||||
|
].forEach((k) => {
|
||||||
|
Object.defineProperty(requestPrototype, k, {
|
||||||
|
get() {
|
||||||
|
return this[getRequestCache]()[k];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
|
||||||
|
Object.defineProperty(requestPrototype, k, {
|
||||||
|
value: function() {
|
||||||
|
return this[getRequestCache]()[k]();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), {
|
||||||
|
value: function(depth, options, inspectFn) {
|
||||||
|
const props = {
|
||||||
|
method: this.method,
|
||||||
|
url: this.url,
|
||||||
|
headers: this.headers,
|
||||||
|
nativeRequest: this[requestCache]
|
||||||
|
};
|
||||||
|
return `Request (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Object.setPrototypeOf(requestPrototype, Request.prototype);
|
||||||
|
var newRequest = (incoming, defaultHostname) => {
|
||||||
|
const req = Object.create(requestPrototype);
|
||||||
|
req[incomingKey] = incoming;
|
||||||
|
const incomingUrl = incoming.url || "";
|
||||||
|
if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
|
||||||
|
(incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
|
||||||
|
if (incoming instanceof import_node_http2.Http2ServerRequest) {
|
||||||
|
throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const url2 = new URL(incomingUrl);
|
||||||
|
req[urlKey] = url2.href;
|
||||||
|
} catch (e) {
|
||||||
|
throw new RequestError("Invalid absolute URL", { cause: e });
|
||||||
|
}
|
||||||
|
return req;
|
||||||
|
}
|
||||||
|
const host = (incoming instanceof import_node_http2.Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
|
||||||
|
if (!host) {
|
||||||
|
throw new RequestError("Missing host header");
|
||||||
|
}
|
||||||
|
let scheme;
|
||||||
|
if (incoming instanceof import_node_http2.Http2ServerRequest) {
|
||||||
|
scheme = incoming.scheme;
|
||||||
|
if (!(scheme === "http" || scheme === "https")) {
|
||||||
|
throw new RequestError("Unsupported scheme");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
|
||||||
|
}
|
||||||
|
const url = new URL(`${scheme}://${host}${incomingUrl}`);
|
||||||
|
if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
|
||||||
|
throw new RequestError("Invalid host header");
|
||||||
|
}
|
||||||
|
req[urlKey] = url.href;
|
||||||
|
return req;
|
||||||
|
};
|
||||||
|
|
||||||
|
// src/response.ts
|
||||||
|
var responseCache = Symbol("responseCache");
|
||||||
|
var getResponseCache = Symbol("getResponseCache");
|
||||||
|
var cacheKey = Symbol("cache");
|
||||||
|
var GlobalResponse = global.Response;
|
||||||
|
var Response2 = class _Response {
|
||||||
|
#body;
|
||||||
|
#init;
|
||||||
|
[getResponseCache]() {
|
||||||
|
delete this[cacheKey];
|
||||||
|
return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
|
||||||
|
}
|
||||||
|
constructor(body, init) {
|
||||||
|
let headers;
|
||||||
|
this.#body = body;
|
||||||
|
if (init instanceof _Response) {
|
||||||
|
const cachedGlobalResponse = init[responseCache];
|
||||||
|
if (cachedGlobalResponse) {
|
||||||
|
this.#init = cachedGlobalResponse;
|
||||||
|
this[getResponseCache]();
|
||||||
|
return;
|
||||||
|
} else {
|
||||||
|
this.#init = init.#init;
|
||||||
|
headers = new Headers(init.#init.headers);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
this.#init = init;
|
||||||
|
}
|
||||||
|
if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
|
||||||
|
;
|
||||||
|
this[cacheKey] = [init?.status || 200, body, headers || init?.headers];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
get headers() {
|
||||||
|
const cache = this[cacheKey];
|
||||||
|
if (cache) {
|
||||||
|
if (!(cache[2] instanceof Headers)) {
|
||||||
|
cache[2] = new Headers(
|
||||||
|
cache[2] || { "content-type": "text/plain; charset=UTF-8" }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return cache[2];
|
||||||
|
}
|
||||||
|
return this[getResponseCache]().headers;
|
||||||
|
}
|
||||||
|
get status() {
|
||||||
|
return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
|
||||||
|
}
|
||||||
|
get ok() {
|
||||||
|
const status = this.status;
|
||||||
|
return status >= 200 && status < 300;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
|
||||||
|
Object.defineProperty(Response2.prototype, k, {
|
||||||
|
get() {
|
||||||
|
return this[getResponseCache]()[k];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
|
||||||
|
Object.defineProperty(Response2.prototype, k, {
|
||||||
|
value: function() {
|
||||||
|
return this[getResponseCache]()[k]();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
Object.defineProperty(Response2.prototype, Symbol.for("nodejs.util.inspect.custom"), {
|
||||||
|
value: function(depth, options, inspectFn) {
|
||||||
|
const props = {
|
||||||
|
status: this.status,
|
||||||
|
headers: this.headers,
|
||||||
|
ok: this.ok,
|
||||||
|
nativeResponse: this[responseCache]
|
||||||
|
};
|
||||||
|
return `Response (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Object.setPrototypeOf(Response2, GlobalResponse);
|
||||||
|
Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
|
||||||
|
|
||||||
|
// src/utils.ts
|
||||||
|
async function readWithoutBlocking(readPromise) {
|
||||||
|
return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
|
||||||
|
}
|
||||||
|
function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
|
||||||
|
const cancel = (error) => {
|
||||||
|
reader.cancel(error).catch(() => {
|
||||||
|
});
|
||||||
|
};
|
||||||
|
writable.on("close", cancel);
|
||||||
|
writable.on("error", cancel);
|
||||||
|
(currentReadPromise ?? reader.read()).then(flow, handleStreamError);
|
||||||
|
return reader.closed.finally(() => {
|
||||||
|
writable.off("close", cancel);
|
||||||
|
writable.off("error", cancel);
|
||||||
|
});
|
||||||
|
function handleStreamError(error) {
|
||||||
|
if (error) {
|
||||||
|
writable.destroy(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function onDrain() {
|
||||||
|
reader.read().then(flow, handleStreamError);
|
||||||
|
}
|
||||||
|
function flow({ done, value }) {
|
||||||
|
try {
|
||||||
|
if (done) {
|
||||||
|
writable.end();
|
||||||
|
} else if (!writable.write(value)) {
|
||||||
|
writable.once("drain", onDrain);
|
||||||
|
} else {
|
||||||
|
return reader.read().then(flow, handleStreamError);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
handleStreamError(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function writeFromReadableStream(stream, writable) {
|
||||||
|
if (stream.locked) {
|
||||||
|
throw new TypeError("ReadableStream is locked.");
|
||||||
|
} else if (writable.destroyed) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
|
||||||
|
}
|
||||||
|
var buildOutgoingHttpHeaders = (headers) => {
|
||||||
|
const res = {};
|
||||||
|
if (!(headers instanceof Headers)) {
|
||||||
|
headers = new Headers(headers ?? void 0);
|
||||||
|
}
|
||||||
|
const cookies = [];
|
||||||
|
for (const [k, v] of headers) {
|
||||||
|
if (k === "set-cookie") {
|
||||||
|
cookies.push(v);
|
||||||
|
} else {
|
||||||
|
res[k] = v;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (cookies.length > 0) {
|
||||||
|
res["set-cookie"] = cookies;
|
||||||
|
}
|
||||||
|
res["content-type"] ??= "text/plain; charset=UTF-8";
|
||||||
|
return res;
|
||||||
|
};
|
||||||
|
|
||||||
|
// src/utils/response/constants.ts
|
||||||
|
var X_ALREADY_SENT = "x-hono-already-sent";
|
||||||
|
|
||||||
|
// src/globals.ts
|
||||||
|
var import_node_crypto = __toESM(require("crypto"));
|
||||||
|
if (typeof global.crypto === "undefined") {
|
||||||
|
global.crypto = import_node_crypto.default;
|
||||||
|
}
|
||||||
|
|
||||||
|
// src/listener.ts
|
||||||
|
var outgoingEnded = Symbol("outgoingEnded");
|
||||||
|
var incomingDraining = Symbol("incomingDraining");
|
||||||
|
var DRAIN_TIMEOUT_MS = 500;
|
||||||
|
var MAX_DRAIN_BYTES = 64 * 1024 * 1024;
|
||||||
|
var drainIncoming = (incoming) => {
|
||||||
|
const incomingWithDrainState = incoming;
|
||||||
|
if (incoming.destroyed || incomingWithDrainState[incomingDraining]) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
incomingWithDrainState[incomingDraining] = true;
|
||||||
|
if (incoming instanceof import_node_http22.Http2ServerRequest) {
|
||||||
|
try {
|
||||||
|
;
|
||||||
|
incoming.stream?.close?.(import_node_http22.constants.NGHTTP2_NO_ERROR);
|
||||||
|
} catch {
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let bytesRead = 0;
|
||||||
|
const cleanup = () => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
incoming.off("data", onData);
|
||||||
|
incoming.off("end", cleanup);
|
||||||
|
incoming.off("error", cleanup);
|
||||||
|
};
|
||||||
|
const forceClose = () => {
|
||||||
|
cleanup();
|
||||||
|
const socket = incoming.socket;
|
||||||
|
if (socket && !socket.destroyed) {
|
||||||
|
socket.destroySoon();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
|
||||||
|
timer.unref?.();
|
||||||
|
const onData = (chunk) => {
|
||||||
|
bytesRead += chunk.length;
|
||||||
|
if (bytesRead > MAX_DRAIN_BYTES) {
|
||||||
|
forceClose();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
incoming.on("data", onData);
|
||||||
|
incoming.on("end", cleanup);
|
||||||
|
incoming.on("error", cleanup);
|
||||||
|
incoming.resume();
|
||||||
|
};
|
||||||
|
var handleRequestError = () => new Response(null, {
|
||||||
|
status: 400
|
||||||
|
});
|
||||||
|
var handleFetchError = (e) => new Response(null, {
|
||||||
|
status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
|
||||||
|
});
|
||||||
|
var handleResponseError = (e, outgoing) => {
|
||||||
|
const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
|
||||||
|
if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
|
||||||
|
console.info("The user aborted a request.");
|
||||||
|
} else {
|
||||||
|
console.error(e);
|
||||||
|
if (!outgoing.headersSent) {
|
||||||
|
outgoing.writeHead(500, { "Content-Type": "text/plain" });
|
||||||
|
}
|
||||||
|
outgoing.end(`Error: ${err.message}`);
|
||||||
|
outgoing.destroy(err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var flushHeaders = (outgoing) => {
|
||||||
|
if ("flushHeaders" in outgoing && outgoing.writable) {
|
||||||
|
outgoing.flushHeaders();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var responseViaCache = async (res, outgoing) => {
|
||||||
|
let [status, body, header] = res[cacheKey];
|
||||||
|
let hasContentLength = false;
|
||||||
|
if (!header) {
|
||||||
|
header = { "content-type": "text/plain; charset=UTF-8" };
|
||||||
|
} else if (header instanceof Headers) {
|
||||||
|
hasContentLength = header.has("content-length");
|
||||||
|
header = buildOutgoingHttpHeaders(header);
|
||||||
|
} else if (Array.isArray(header)) {
|
||||||
|
const headerObj = new Headers(header);
|
||||||
|
hasContentLength = headerObj.has("content-length");
|
||||||
|
header = buildOutgoingHttpHeaders(headerObj);
|
||||||
|
} else {
|
||||||
|
for (const key in header) {
|
||||||
|
if (key.length === 14 && key.toLowerCase() === "content-length") {
|
||||||
|
hasContentLength = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!hasContentLength) {
|
||||||
|
if (typeof body === "string") {
|
||||||
|
header["Content-Length"] = Buffer.byteLength(body);
|
||||||
|
} else if (body instanceof Uint8Array) {
|
||||||
|
header["Content-Length"] = body.byteLength;
|
||||||
|
} else if (body instanceof Blob) {
|
||||||
|
header["Content-Length"] = body.size;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
outgoing.writeHead(status, header);
|
||||||
|
if (typeof body === "string" || body instanceof Uint8Array) {
|
||||||
|
outgoing.end(body);
|
||||||
|
} else if (body instanceof Blob) {
|
||||||
|
outgoing.end(new Uint8Array(await body.arrayBuffer()));
|
||||||
|
} else {
|
||||||
|
flushHeaders(outgoing);
|
||||||
|
await writeFromReadableStream(body, outgoing)?.catch(
|
||||||
|
(e) => handleResponseError(e, outgoing)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
;
|
||||||
|
outgoing[outgoingEnded]?.();
|
||||||
|
};
|
||||||
|
var isPromise = (res) => typeof res.then === "function";
|
||||||
|
var responseViaResponseObject = async (res, outgoing, options = {}) => {
|
||||||
|
if (isPromise(res)) {
|
||||||
|
if (options.errorHandler) {
|
||||||
|
try {
|
||||||
|
res = await res;
|
||||||
|
} catch (err) {
|
||||||
|
const errRes = await options.errorHandler(err);
|
||||||
|
if (!errRes) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
res = errRes;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
res = await res.catch(handleFetchError);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (cacheKey in res) {
|
||||||
|
return responseViaCache(res, outgoing);
|
||||||
|
}
|
||||||
|
const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
|
||||||
|
if (res.body) {
|
||||||
|
const reader = res.body.getReader();
|
||||||
|
const values = [];
|
||||||
|
let done = false;
|
||||||
|
let currentReadPromise = void 0;
|
||||||
|
if (resHeaderRecord["transfer-encoding"] !== "chunked") {
|
||||||
|
let maxReadCount = 2;
|
||||||
|
for (let i = 0; i < maxReadCount; i++) {
|
||||||
|
currentReadPromise ||= reader.read();
|
||||||
|
const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
|
||||||
|
console.error(e);
|
||||||
|
done = true;
|
||||||
|
});
|
||||||
|
if (!chunk) {
|
||||||
|
if (i === 1) {
|
||||||
|
await new Promise((resolve) => setTimeout(resolve));
|
||||||
|
maxReadCount = 3;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
currentReadPromise = void 0;
|
||||||
|
if (chunk.value) {
|
||||||
|
values.push(chunk.value);
|
||||||
|
}
|
||||||
|
if (chunk.done) {
|
||||||
|
done = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (done && !("content-length" in resHeaderRecord)) {
|
||||||
|
resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
outgoing.writeHead(res.status, resHeaderRecord);
|
||||||
|
values.forEach((value) => {
|
||||||
|
;
|
||||||
|
outgoing.write(value);
|
||||||
|
});
|
||||||
|
if (done) {
|
||||||
|
outgoing.end();
|
||||||
|
} else {
|
||||||
|
if (values.length === 0) {
|
||||||
|
flushHeaders(outgoing);
|
||||||
|
}
|
||||||
|
await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
|
||||||
|
}
|
||||||
|
} else if (resHeaderRecord[X_ALREADY_SENT]) {
|
||||||
|
} else {
|
||||||
|
outgoing.writeHead(res.status, resHeaderRecord);
|
||||||
|
outgoing.end();
|
||||||
|
}
|
||||||
|
;
|
||||||
|
outgoing[outgoingEnded]?.();
|
||||||
|
};
|
||||||
|
var getRequestListener = (fetchCallback, options = {}) => {
|
||||||
|
const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
|
||||||
|
if (options.overrideGlobalObjects !== false && global.Request !== Request) {
|
||||||
|
Object.defineProperty(global, "Request", {
|
||||||
|
value: Request
|
||||||
|
});
|
||||||
|
Object.defineProperty(global, "Response", {
|
||||||
|
value: Response2
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return async (incoming, outgoing) => {
|
||||||
|
let res, req;
|
||||||
|
try {
|
||||||
|
req = newRequest(incoming, options.hostname);
|
||||||
|
let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
|
||||||
|
if (!incomingEnded) {
|
||||||
|
;
|
||||||
|
incoming[wrapBodyStream] = true;
|
||||||
|
incoming.on("end", () => {
|
||||||
|
incomingEnded = true;
|
||||||
|
});
|
||||||
|
if (incoming instanceof import_node_http22.Http2ServerRequest) {
|
||||||
|
;
|
||||||
|
outgoing[outgoingEnded] = () => {
|
||||||
|
if (!incomingEnded) {
|
||||||
|
setTimeout(() => {
|
||||||
|
if (!incomingEnded) {
|
||||||
|
setTimeout(() => {
|
||||||
|
drainIncoming(incoming);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
outgoing.on("finish", () => {
|
||||||
|
if (!incomingEnded) {
|
||||||
|
drainIncoming(incoming);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
outgoing.on("close", () => {
|
||||||
|
const abortController = req[abortControllerKey];
|
||||||
|
if (abortController) {
|
||||||
|
if (incoming.errored) {
|
||||||
|
req[abortControllerKey].abort(incoming.errored.toString());
|
||||||
|
} else if (!outgoing.writableFinished) {
|
||||||
|
req[abortControllerKey].abort("Client connection prematurely closed.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!incomingEnded) {
|
||||||
|
setTimeout(() => {
|
||||||
|
if (!incomingEnded) {
|
||||||
|
setTimeout(() => {
|
||||||
|
drainIncoming(incoming);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
res = fetchCallback(req, { incoming, outgoing });
|
||||||
|
if (cacheKey in res) {
|
||||||
|
return responseViaCache(res, outgoing);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
if (!res) {
|
||||||
|
if (options.errorHandler) {
|
||||||
|
res = await options.errorHandler(req ? e : toRequestError(e));
|
||||||
|
if (!res) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} else if (!req) {
|
||||||
|
res = handleRequestError();
|
||||||
|
} else {
|
||||||
|
res = handleFetchError(e);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return handleResponseError(e, outgoing);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return await responseViaResponseObject(res, outgoing, options);
|
||||||
|
} catch (e) {
|
||||||
|
return handleResponseError(e, outgoing);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
// src/server.ts
|
||||||
|
var createAdaptorServer = (options) => {
|
||||||
|
const fetchCallback = options.fetch;
|
||||||
|
const requestListener = getRequestListener(fetchCallback, {
|
||||||
|
hostname: options.hostname,
|
||||||
|
overrideGlobalObjects: options.overrideGlobalObjects,
|
||||||
|
autoCleanupIncoming: options.autoCleanupIncoming
|
||||||
|
});
|
||||||
|
const createServer = options.createServer || import_node_http.createServer;
|
||||||
|
const server = createServer(options.serverOptions || {}, requestListener);
|
||||||
|
return server;
|
||||||
|
};
|
||||||
|
var serve = (options, listeningListener) => {
|
||||||
|
const server = createAdaptorServer(options);
|
||||||
|
server.listen(options?.port ?? 3e3, options.hostname, () => {
|
||||||
|
const serverInfo = server.address();
|
||||||
|
listeningListener && listeningListener(serverInfo);
|
||||||
|
});
|
||||||
|
return server;
|
||||||
|
};
|
||||||
|
// Annotate the CommonJS export names for ESM import in node:
|
||||||
|
0 && (module.exports = {
|
||||||
|
RequestError,
|
||||||
|
createAdaptorServer,
|
||||||
|
getRequestListener,
|
||||||
|
serve
|
||||||
|
});
|
||||||
662
node_modules/@hono/node-server/dist/index.mjs
generated
vendored
Normal file
662
node_modules/@hono/node-server/dist/index.mjs
generated
vendored
Normal file
@@ -0,0 +1,662 @@
|
|||||||
|
// src/server.ts
|
||||||
|
import { createServer as createServerHTTP } from "http";
|
||||||
|
|
||||||
|
// src/listener.ts
|
||||||
|
import { Http2ServerRequest as Http2ServerRequest2, constants as h2constants } from "http2";
|
||||||
|
|
||||||
|
// src/request.ts
|
||||||
|
import { Http2ServerRequest } from "http2";
|
||||||
|
import { Readable } from "stream";
|
||||||
|
var RequestError = class extends Error {
|
||||||
|
constructor(message, options) {
|
||||||
|
super(message, options);
|
||||||
|
this.name = "RequestError";
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var toRequestError = (e) => {
|
||||||
|
if (e instanceof RequestError) {
|
||||||
|
return e;
|
||||||
|
}
|
||||||
|
return new RequestError(e.message, { cause: e });
|
||||||
|
};
|
||||||
|
var GlobalRequest = global.Request;
|
||||||
|
var Request = class extends GlobalRequest {
|
||||||
|
constructor(input, options) {
|
||||||
|
if (typeof input === "object" && getRequestCache in input) {
|
||||||
|
input = input[getRequestCache]();
|
||||||
|
}
|
||||||
|
if (typeof options?.body?.getReader !== "undefined") {
|
||||||
|
;
|
||||||
|
options.duplex ??= "half";
|
||||||
|
}
|
||||||
|
super(input, options);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var newHeadersFromIncoming = (incoming) => {
|
||||||
|
const headerRecord = [];
|
||||||
|
const rawHeaders = incoming.rawHeaders;
|
||||||
|
for (let i = 0; i < rawHeaders.length; i += 2) {
|
||||||
|
const { [i]: key, [i + 1]: value } = rawHeaders;
|
||||||
|
if (key.charCodeAt(0) !== /*:*/
|
||||||
|
58) {
|
||||||
|
headerRecord.push([key, value]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new Headers(headerRecord);
|
||||||
|
};
|
||||||
|
var wrapBodyStream = Symbol("wrapBodyStream");
|
||||||
|
var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
|
||||||
|
const init = {
|
||||||
|
method,
|
||||||
|
headers,
|
||||||
|
signal: abortController.signal
|
||||||
|
};
|
||||||
|
if (method === "TRACE") {
|
||||||
|
init.method = "GET";
|
||||||
|
const req = new Request(url, init);
|
||||||
|
Object.defineProperty(req, "method", {
|
||||||
|
get() {
|
||||||
|
return "TRACE";
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return req;
|
||||||
|
}
|
||||||
|
if (!(method === "GET" || method === "HEAD")) {
|
||||||
|
if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
|
||||||
|
init.body = new ReadableStream({
|
||||||
|
start(controller) {
|
||||||
|
controller.enqueue(incoming.rawBody);
|
||||||
|
controller.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else if (incoming[wrapBodyStream]) {
|
||||||
|
let reader;
|
||||||
|
init.body = new ReadableStream({
|
||||||
|
async pull(controller) {
|
||||||
|
try {
|
||||||
|
reader ||= Readable.toWeb(incoming).getReader();
|
||||||
|
const { done, value } = await reader.read();
|
||||||
|
if (done) {
|
||||||
|
controller.close();
|
||||||
|
} else {
|
||||||
|
controller.enqueue(value);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
controller.error(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
init.body = Readable.toWeb(incoming);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new Request(url, init);
|
||||||
|
};
|
||||||
|
var getRequestCache = Symbol("getRequestCache");
|
||||||
|
var requestCache = Symbol("requestCache");
|
||||||
|
var incomingKey = Symbol("incomingKey");
|
||||||
|
var urlKey = Symbol("urlKey");
|
||||||
|
var headersKey = Symbol("headersKey");
|
||||||
|
var abortControllerKey = Symbol("abortControllerKey");
|
||||||
|
var getAbortController = Symbol("getAbortController");
|
||||||
|
var requestPrototype = {
|
||||||
|
get method() {
|
||||||
|
return this[incomingKey].method || "GET";
|
||||||
|
},
|
||||||
|
get url() {
|
||||||
|
return this[urlKey];
|
||||||
|
},
|
||||||
|
get headers() {
|
||||||
|
return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
|
||||||
|
},
|
||||||
|
[getAbortController]() {
|
||||||
|
this[getRequestCache]();
|
||||||
|
return this[abortControllerKey];
|
||||||
|
},
|
||||||
|
[getRequestCache]() {
|
||||||
|
this[abortControllerKey] ||= new AbortController();
|
||||||
|
return this[requestCache] ||= newRequestFromIncoming(
|
||||||
|
this.method,
|
||||||
|
this[urlKey],
|
||||||
|
this.headers,
|
||||||
|
this[incomingKey],
|
||||||
|
this[abortControllerKey]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
[
|
||||||
|
"body",
|
||||||
|
"bodyUsed",
|
||||||
|
"cache",
|
||||||
|
"credentials",
|
||||||
|
"destination",
|
||||||
|
"integrity",
|
||||||
|
"mode",
|
||||||
|
"redirect",
|
||||||
|
"referrer",
|
||||||
|
"referrerPolicy",
|
||||||
|
"signal",
|
||||||
|
"keepalive"
|
||||||
|
].forEach((k) => {
|
||||||
|
Object.defineProperty(requestPrototype, k, {
|
||||||
|
get() {
|
||||||
|
return this[getRequestCache]()[k];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
|
||||||
|
Object.defineProperty(requestPrototype, k, {
|
||||||
|
value: function() {
|
||||||
|
return this[getRequestCache]()[k]();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), {
|
||||||
|
value: function(depth, options, inspectFn) {
|
||||||
|
const props = {
|
||||||
|
method: this.method,
|
||||||
|
url: this.url,
|
||||||
|
headers: this.headers,
|
||||||
|
nativeRequest: this[requestCache]
|
||||||
|
};
|
||||||
|
return `Request (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Object.setPrototypeOf(requestPrototype, Request.prototype);
|
||||||
|
var newRequest = (incoming, defaultHostname) => {
|
||||||
|
const req = Object.create(requestPrototype);
|
||||||
|
req[incomingKey] = incoming;
|
||||||
|
const incomingUrl = incoming.url || "";
|
||||||
|
if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
|
||||||
|
(incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
|
||||||
|
if (incoming instanceof Http2ServerRequest) {
|
||||||
|
throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const url2 = new URL(incomingUrl);
|
||||||
|
req[urlKey] = url2.href;
|
||||||
|
} catch (e) {
|
||||||
|
throw new RequestError("Invalid absolute URL", { cause: e });
|
||||||
|
}
|
||||||
|
return req;
|
||||||
|
}
|
||||||
|
const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
|
||||||
|
if (!host) {
|
||||||
|
throw new RequestError("Missing host header");
|
||||||
|
}
|
||||||
|
let scheme;
|
||||||
|
if (incoming instanceof Http2ServerRequest) {
|
||||||
|
scheme = incoming.scheme;
|
||||||
|
if (!(scheme === "http" || scheme === "https")) {
|
||||||
|
throw new RequestError("Unsupported scheme");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
|
||||||
|
}
|
||||||
|
const url = new URL(`${scheme}://${host}${incomingUrl}`);
|
||||||
|
if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
|
||||||
|
throw new RequestError("Invalid host header");
|
||||||
|
}
|
||||||
|
req[urlKey] = url.href;
|
||||||
|
return req;
|
||||||
|
};
|
||||||
|
|
||||||
|
// src/response.ts
|
||||||
|
var responseCache = Symbol("responseCache");
|
||||||
|
var getResponseCache = Symbol("getResponseCache");
|
||||||
|
var cacheKey = Symbol("cache");
|
||||||
|
var GlobalResponse = global.Response;
|
||||||
|
var Response2 = class _Response {
|
||||||
|
#body;
|
||||||
|
#init;
|
||||||
|
[getResponseCache]() {
|
||||||
|
delete this[cacheKey];
|
||||||
|
return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
|
||||||
|
}
|
||||||
|
constructor(body, init) {
|
||||||
|
let headers;
|
||||||
|
this.#body = body;
|
||||||
|
if (init instanceof _Response) {
|
||||||
|
const cachedGlobalResponse = init[responseCache];
|
||||||
|
if (cachedGlobalResponse) {
|
||||||
|
this.#init = cachedGlobalResponse;
|
||||||
|
this[getResponseCache]();
|
||||||
|
return;
|
||||||
|
} else {
|
||||||
|
this.#init = init.#init;
|
||||||
|
headers = new Headers(init.#init.headers);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
this.#init = init;
|
||||||
|
}
|
||||||
|
if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
|
||||||
|
;
|
||||||
|
this[cacheKey] = [init?.status || 200, body, headers || init?.headers];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
get headers() {
|
||||||
|
const cache = this[cacheKey];
|
||||||
|
if (cache) {
|
||||||
|
if (!(cache[2] instanceof Headers)) {
|
||||||
|
cache[2] = new Headers(
|
||||||
|
cache[2] || { "content-type": "text/plain; charset=UTF-8" }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return cache[2];
|
||||||
|
}
|
||||||
|
return this[getResponseCache]().headers;
|
||||||
|
}
|
||||||
|
get status() {
|
||||||
|
return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
|
||||||
|
}
|
||||||
|
get ok() {
|
||||||
|
const status = this.status;
|
||||||
|
return status >= 200 && status < 300;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
|
||||||
|
Object.defineProperty(Response2.prototype, k, {
|
||||||
|
get() {
|
||||||
|
return this[getResponseCache]()[k];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
|
||||||
|
Object.defineProperty(Response2.prototype, k, {
|
||||||
|
value: function() {
|
||||||
|
return this[getResponseCache]()[k]();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
Object.defineProperty(Response2.prototype, Symbol.for("nodejs.util.inspect.custom"), {
|
||||||
|
value: function(depth, options, inspectFn) {
|
||||||
|
const props = {
|
||||||
|
status: this.status,
|
||||||
|
headers: this.headers,
|
||||||
|
ok: this.ok,
|
||||||
|
nativeResponse: this[responseCache]
|
||||||
|
};
|
||||||
|
return `Response (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Object.setPrototypeOf(Response2, GlobalResponse);
|
||||||
|
Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
|
||||||
|
|
||||||
|
// src/utils.ts
|
||||||
|
async function readWithoutBlocking(readPromise) {
|
||||||
|
return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
|
||||||
|
}
|
||||||
|
function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
|
||||||
|
const cancel = (error) => {
|
||||||
|
reader.cancel(error).catch(() => {
|
||||||
|
});
|
||||||
|
};
|
||||||
|
writable.on("close", cancel);
|
||||||
|
writable.on("error", cancel);
|
||||||
|
(currentReadPromise ?? reader.read()).then(flow, handleStreamError);
|
||||||
|
return reader.closed.finally(() => {
|
||||||
|
writable.off("close", cancel);
|
||||||
|
writable.off("error", cancel);
|
||||||
|
});
|
||||||
|
function handleStreamError(error) {
|
||||||
|
if (error) {
|
||||||
|
writable.destroy(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function onDrain() {
|
||||||
|
reader.read().then(flow, handleStreamError);
|
||||||
|
}
|
||||||
|
function flow({ done, value }) {
|
||||||
|
try {
|
||||||
|
if (done) {
|
||||||
|
writable.end();
|
||||||
|
} else if (!writable.write(value)) {
|
||||||
|
writable.once("drain", onDrain);
|
||||||
|
} else {
|
||||||
|
return reader.read().then(flow, handleStreamError);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
handleStreamError(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function writeFromReadableStream(stream, writable) {
|
||||||
|
if (stream.locked) {
|
||||||
|
throw new TypeError("ReadableStream is locked.");
|
||||||
|
} else if (writable.destroyed) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
|
||||||
|
}
|
||||||
|
var buildOutgoingHttpHeaders = (headers) => {
|
||||||
|
const res = {};
|
||||||
|
if (!(headers instanceof Headers)) {
|
||||||
|
headers = new Headers(headers ?? void 0);
|
||||||
|
}
|
||||||
|
const cookies = [];
|
||||||
|
for (const [k, v] of headers) {
|
||||||
|
if (k === "set-cookie") {
|
||||||
|
cookies.push(v);
|
||||||
|
} else {
|
||||||
|
res[k] = v;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (cookies.length > 0) {
|
||||||
|
res["set-cookie"] = cookies;
|
||||||
|
}
|
||||||
|
res["content-type"] ??= "text/plain; charset=UTF-8";
|
||||||
|
return res;
|
||||||
|
};
|
||||||
|
|
||||||
|
// src/utils/response/constants.ts
|
||||||
|
var X_ALREADY_SENT = "x-hono-already-sent";
|
||||||
|
|
||||||
|
// src/globals.ts
|
||||||
|
import crypto from "crypto";
|
||||||
|
if (typeof global.crypto === "undefined") {
|
||||||
|
global.crypto = crypto;
|
||||||
|
}
|
||||||
|
|
||||||
|
// src/listener.ts
|
||||||
|
var outgoingEnded = Symbol("outgoingEnded");
|
||||||
|
var incomingDraining = Symbol("incomingDraining");
|
||||||
|
var DRAIN_TIMEOUT_MS = 500;
|
||||||
|
var MAX_DRAIN_BYTES = 64 * 1024 * 1024;
|
||||||
|
var drainIncoming = (incoming) => {
|
||||||
|
const incomingWithDrainState = incoming;
|
||||||
|
if (incoming.destroyed || incomingWithDrainState[incomingDraining]) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
incomingWithDrainState[incomingDraining] = true;
|
||||||
|
if (incoming instanceof Http2ServerRequest2) {
|
||||||
|
try {
|
||||||
|
;
|
||||||
|
incoming.stream?.close?.(h2constants.NGHTTP2_NO_ERROR);
|
||||||
|
} catch {
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let bytesRead = 0;
|
||||||
|
const cleanup = () => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
incoming.off("data", onData);
|
||||||
|
incoming.off("end", cleanup);
|
||||||
|
incoming.off("error", cleanup);
|
||||||
|
};
|
||||||
|
const forceClose = () => {
|
||||||
|
cleanup();
|
||||||
|
const socket = incoming.socket;
|
||||||
|
if (socket && !socket.destroyed) {
|
||||||
|
socket.destroySoon();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
|
||||||
|
timer.unref?.();
|
||||||
|
const onData = (chunk) => {
|
||||||
|
bytesRead += chunk.length;
|
||||||
|
if (bytesRead > MAX_DRAIN_BYTES) {
|
||||||
|
forceClose();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
incoming.on("data", onData);
|
||||||
|
incoming.on("end", cleanup);
|
||||||
|
incoming.on("error", cleanup);
|
||||||
|
incoming.resume();
|
||||||
|
};
|
||||||
|
var handleRequestError = () => new Response(null, {
|
||||||
|
status: 400
|
||||||
|
});
|
||||||
|
var handleFetchError = (e) => new Response(null, {
|
||||||
|
status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
|
||||||
|
});
|
||||||
|
var handleResponseError = (e, outgoing) => {
|
||||||
|
const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
|
||||||
|
if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
|
||||||
|
console.info("The user aborted a request.");
|
||||||
|
} else {
|
||||||
|
console.error(e);
|
||||||
|
if (!outgoing.headersSent) {
|
||||||
|
outgoing.writeHead(500, { "Content-Type": "text/plain" });
|
||||||
|
}
|
||||||
|
outgoing.end(`Error: ${err.message}`);
|
||||||
|
outgoing.destroy(err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var flushHeaders = (outgoing) => {
|
||||||
|
if ("flushHeaders" in outgoing && outgoing.writable) {
|
||||||
|
outgoing.flushHeaders();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var responseViaCache = async (res, outgoing) => {
|
||||||
|
let [status, body, header] = res[cacheKey];
|
||||||
|
let hasContentLength = false;
|
||||||
|
if (!header) {
|
||||||
|
header = { "content-type": "text/plain; charset=UTF-8" };
|
||||||
|
} else if (header instanceof Headers) {
|
||||||
|
hasContentLength = header.has("content-length");
|
||||||
|
header = buildOutgoingHttpHeaders(header);
|
||||||
|
} else if (Array.isArray(header)) {
|
||||||
|
const headerObj = new Headers(header);
|
||||||
|
hasContentLength = headerObj.has("content-length");
|
||||||
|
header = buildOutgoingHttpHeaders(headerObj);
|
||||||
|
} else {
|
||||||
|
for (const key in header) {
|
||||||
|
if (key.length === 14 && key.toLowerCase() === "content-length") {
|
||||||
|
hasContentLength = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!hasContentLength) {
|
||||||
|
if (typeof body === "string") {
|
||||||
|
header["Content-Length"] = Buffer.byteLength(body);
|
||||||
|
} else if (body instanceof Uint8Array) {
|
||||||
|
header["Content-Length"] = body.byteLength;
|
||||||
|
} else if (body instanceof Blob) {
|
||||||
|
header["Content-Length"] = body.size;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
outgoing.writeHead(status, header);
|
||||||
|
if (typeof body === "string" || body instanceof Uint8Array) {
|
||||||
|
outgoing.end(body);
|
||||||
|
} else if (body instanceof Blob) {
|
||||||
|
outgoing.end(new Uint8Array(await body.arrayBuffer()));
|
||||||
|
} else {
|
||||||
|
flushHeaders(outgoing);
|
||||||
|
await writeFromReadableStream(body, outgoing)?.catch(
|
||||||
|
(e) => handleResponseError(e, outgoing)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
;
|
||||||
|
outgoing[outgoingEnded]?.();
|
||||||
|
};
|
||||||
|
var isPromise = (res) => typeof res.then === "function";
|
||||||
|
var responseViaResponseObject = async (res, outgoing, options = {}) => {
|
||||||
|
if (isPromise(res)) {
|
||||||
|
if (options.errorHandler) {
|
||||||
|
try {
|
||||||
|
res = await res;
|
||||||
|
} catch (err) {
|
||||||
|
const errRes = await options.errorHandler(err);
|
||||||
|
if (!errRes) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
res = errRes;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
res = await res.catch(handleFetchError);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (cacheKey in res) {
|
||||||
|
return responseViaCache(res, outgoing);
|
||||||
|
}
|
||||||
|
const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
|
||||||
|
if (res.body) {
|
||||||
|
const reader = res.body.getReader();
|
||||||
|
const values = [];
|
||||||
|
let done = false;
|
||||||
|
let currentReadPromise = void 0;
|
||||||
|
if (resHeaderRecord["transfer-encoding"] !== "chunked") {
|
||||||
|
let maxReadCount = 2;
|
||||||
|
for (let i = 0; i < maxReadCount; i++) {
|
||||||
|
currentReadPromise ||= reader.read();
|
||||||
|
const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
|
||||||
|
console.error(e);
|
||||||
|
done = true;
|
||||||
|
});
|
||||||
|
if (!chunk) {
|
||||||
|
if (i === 1) {
|
||||||
|
await new Promise((resolve) => setTimeout(resolve));
|
||||||
|
maxReadCount = 3;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
currentReadPromise = void 0;
|
||||||
|
if (chunk.value) {
|
||||||
|
values.push(chunk.value);
|
||||||
|
}
|
||||||
|
if (chunk.done) {
|
||||||
|
done = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (done && !("content-length" in resHeaderRecord)) {
|
||||||
|
resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
outgoing.writeHead(res.status, resHeaderRecord);
|
||||||
|
values.forEach((value) => {
|
||||||
|
;
|
||||||
|
outgoing.write(value);
|
||||||
|
});
|
||||||
|
if (done) {
|
||||||
|
outgoing.end();
|
||||||
|
} else {
|
||||||
|
if (values.length === 0) {
|
||||||
|
flushHeaders(outgoing);
|
||||||
|
}
|
||||||
|
await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
|
||||||
|
}
|
||||||
|
} else if (resHeaderRecord[X_ALREADY_SENT]) {
|
||||||
|
} else {
|
||||||
|
outgoing.writeHead(res.status, resHeaderRecord);
|
||||||
|
outgoing.end();
|
||||||
|
}
|
||||||
|
;
|
||||||
|
outgoing[outgoingEnded]?.();
|
||||||
|
};
|
||||||
|
var getRequestListener = (fetchCallback, options = {}) => {
|
||||||
|
const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
|
||||||
|
if (options.overrideGlobalObjects !== false && global.Request !== Request) {
|
||||||
|
Object.defineProperty(global, "Request", {
|
||||||
|
value: Request
|
||||||
|
});
|
||||||
|
Object.defineProperty(global, "Response", {
|
||||||
|
value: Response2
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return async (incoming, outgoing) => {
|
||||||
|
let res, req;
|
||||||
|
try {
|
||||||
|
req = newRequest(incoming, options.hostname);
|
||||||
|
let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
|
||||||
|
if (!incomingEnded) {
|
||||||
|
;
|
||||||
|
incoming[wrapBodyStream] = true;
|
||||||
|
incoming.on("end", () => {
|
||||||
|
incomingEnded = true;
|
||||||
|
});
|
||||||
|
if (incoming instanceof Http2ServerRequest2) {
|
||||||
|
;
|
||||||
|
outgoing[outgoingEnded] = () => {
|
||||||
|
if (!incomingEnded) {
|
||||||
|
setTimeout(() => {
|
||||||
|
if (!incomingEnded) {
|
||||||
|
setTimeout(() => {
|
||||||
|
drainIncoming(incoming);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
outgoing.on("finish", () => {
|
||||||
|
if (!incomingEnded) {
|
||||||
|
drainIncoming(incoming);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
outgoing.on("close", () => {
|
||||||
|
const abortController = req[abortControllerKey];
|
||||||
|
if (abortController) {
|
||||||
|
if (incoming.errored) {
|
||||||
|
req[abortControllerKey].abort(incoming.errored.toString());
|
||||||
|
} else if (!outgoing.writableFinished) {
|
||||||
|
req[abortControllerKey].abort("Client connection prematurely closed.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!incomingEnded) {
|
||||||
|
setTimeout(() => {
|
||||||
|
if (!incomingEnded) {
|
||||||
|
setTimeout(() => {
|
||||||
|
drainIncoming(incoming);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
res = fetchCallback(req, { incoming, outgoing });
|
||||||
|
if (cacheKey in res) {
|
||||||
|
return responseViaCache(res, outgoing);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
if (!res) {
|
||||||
|
if (options.errorHandler) {
|
||||||
|
res = await options.errorHandler(req ? e : toRequestError(e));
|
||||||
|
if (!res) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} else if (!req) {
|
||||||
|
res = handleRequestError();
|
||||||
|
} else {
|
||||||
|
res = handleFetchError(e);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return handleResponseError(e, outgoing);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return await responseViaResponseObject(res, outgoing, options);
|
||||||
|
} catch (e) {
|
||||||
|
return handleResponseError(e, outgoing);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
// src/server.ts
|
||||||
|
var createAdaptorServer = (options) => {
|
||||||
|
const fetchCallback = options.fetch;
|
||||||
|
const requestListener = getRequestListener(fetchCallback, {
|
||||||
|
hostname: options.hostname,
|
||||||
|
overrideGlobalObjects: options.overrideGlobalObjects,
|
||||||
|
autoCleanupIncoming: options.autoCleanupIncoming
|
||||||
|
});
|
||||||
|
const createServer = options.createServer || createServerHTTP;
|
||||||
|
const server = createServer(options.serverOptions || {}, requestListener);
|
||||||
|
return server;
|
||||||
|
};
|
||||||
|
var serve = (options, listeningListener) => {
|
||||||
|
const server = createAdaptorServer(options);
|
||||||
|
server.listen(options?.port ?? 3e3, options.hostname, () => {
|
||||||
|
const serverInfo = server.address();
|
||||||
|
listeningListener && listeningListener(serverInfo);
|
||||||
|
});
|
||||||
|
return server;
|
||||||
|
};
|
||||||
|
export {
|
||||||
|
RequestError,
|
||||||
|
createAdaptorServer,
|
||||||
|
getRequestListener,
|
||||||
|
serve
|
||||||
|
};
|
||||||
13
node_modules/@hono/node-server/dist/listener.d.mts
generated
vendored
Normal file
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 };
|
||||||
670
node_modules/@hono/node-server/dist/listener.js
generated
vendored
Normal file
670
node_modules/@hono/node-server/dist/listener.js
generated
vendored
Normal file
@@ -0,0 +1,670 @@
|
|||||||
|
"use strict";
|
||||||
|
var __create = Object.create;
|
||||||
|
var __defProp = Object.defineProperty;
|
||||||
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||||
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||||
|
var __getProtoOf = Object.getPrototypeOf;
|
||||||
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||||
|
var __export = (target, all) => {
|
||||||
|
for (var name in all)
|
||||||
|
__defProp(target, name, { get: all[name], enumerable: true });
|
||||||
|
};
|
||||||
|
var __copyProps = (to, from, except, desc) => {
|
||||||
|
if (from && typeof from === "object" || typeof from === "function") {
|
||||||
|
for (let key of __getOwnPropNames(from))
|
||||||
|
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||||
|
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||||
|
}
|
||||||
|
return to;
|
||||||
|
};
|
||||||
|
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
||||||
|
// If the importer is in node compatibility mode or this is not an ESM
|
||||||
|
// file that has been converted to a CommonJS file using a Babel-
|
||||||
|
// compatible transform (i.e. "__esModule" has not been set), then set
|
||||||
|
// "default" to the CommonJS "module.exports" for node compatibility.
|
||||||
|
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
||||||
|
mod
|
||||||
|
));
|
||||||
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||||
|
|
||||||
|
// src/listener.ts
|
||||||
|
var listener_exports = {};
|
||||||
|
__export(listener_exports, {
|
||||||
|
getRequestListener: () => getRequestListener
|
||||||
|
});
|
||||||
|
module.exports = __toCommonJS(listener_exports);
|
||||||
|
var import_node_http22 = require("http2");
|
||||||
|
|
||||||
|
// src/request.ts
|
||||||
|
var import_node_http2 = require("http2");
|
||||||
|
var import_node_stream = require("stream");
|
||||||
|
var RequestError = class extends Error {
|
||||||
|
constructor(message, options) {
|
||||||
|
super(message, options);
|
||||||
|
this.name = "RequestError";
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var toRequestError = (e) => {
|
||||||
|
if (e instanceof RequestError) {
|
||||||
|
return e;
|
||||||
|
}
|
||||||
|
return new RequestError(e.message, { cause: e });
|
||||||
|
};
|
||||||
|
var GlobalRequest = global.Request;
|
||||||
|
var Request = class extends GlobalRequest {
|
||||||
|
constructor(input, options) {
|
||||||
|
if (typeof input === "object" && getRequestCache in input) {
|
||||||
|
input = input[getRequestCache]();
|
||||||
|
}
|
||||||
|
if (typeof options?.body?.getReader !== "undefined") {
|
||||||
|
;
|
||||||
|
options.duplex ??= "half";
|
||||||
|
}
|
||||||
|
super(input, options);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var newHeadersFromIncoming = (incoming) => {
|
||||||
|
const headerRecord = [];
|
||||||
|
const rawHeaders = incoming.rawHeaders;
|
||||||
|
for (let i = 0; i < rawHeaders.length; i += 2) {
|
||||||
|
const { [i]: key, [i + 1]: value } = rawHeaders;
|
||||||
|
if (key.charCodeAt(0) !== /*:*/
|
||||||
|
58) {
|
||||||
|
headerRecord.push([key, value]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new Headers(headerRecord);
|
||||||
|
};
|
||||||
|
var wrapBodyStream = Symbol("wrapBodyStream");
|
||||||
|
var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
|
||||||
|
const init = {
|
||||||
|
method,
|
||||||
|
headers,
|
||||||
|
signal: abortController.signal
|
||||||
|
};
|
||||||
|
if (method === "TRACE") {
|
||||||
|
init.method = "GET";
|
||||||
|
const req = new Request(url, init);
|
||||||
|
Object.defineProperty(req, "method", {
|
||||||
|
get() {
|
||||||
|
return "TRACE";
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return req;
|
||||||
|
}
|
||||||
|
if (!(method === "GET" || method === "HEAD")) {
|
||||||
|
if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
|
||||||
|
init.body = new ReadableStream({
|
||||||
|
start(controller) {
|
||||||
|
controller.enqueue(incoming.rawBody);
|
||||||
|
controller.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else if (incoming[wrapBodyStream]) {
|
||||||
|
let reader;
|
||||||
|
init.body = new ReadableStream({
|
||||||
|
async pull(controller) {
|
||||||
|
try {
|
||||||
|
reader ||= import_node_stream.Readable.toWeb(incoming).getReader();
|
||||||
|
const { done, value } = await reader.read();
|
||||||
|
if (done) {
|
||||||
|
controller.close();
|
||||||
|
} else {
|
||||||
|
controller.enqueue(value);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
controller.error(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
init.body = import_node_stream.Readable.toWeb(incoming);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new Request(url, init);
|
||||||
|
};
|
||||||
|
var getRequestCache = Symbol("getRequestCache");
|
||||||
|
var requestCache = Symbol("requestCache");
|
||||||
|
var incomingKey = Symbol("incomingKey");
|
||||||
|
var urlKey = Symbol("urlKey");
|
||||||
|
var headersKey = Symbol("headersKey");
|
||||||
|
var abortControllerKey = Symbol("abortControllerKey");
|
||||||
|
var getAbortController = Symbol("getAbortController");
|
||||||
|
var requestPrototype = {
|
||||||
|
get method() {
|
||||||
|
return this[incomingKey].method || "GET";
|
||||||
|
},
|
||||||
|
get url() {
|
||||||
|
return this[urlKey];
|
||||||
|
},
|
||||||
|
get headers() {
|
||||||
|
return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
|
||||||
|
},
|
||||||
|
[getAbortController]() {
|
||||||
|
this[getRequestCache]();
|
||||||
|
return this[abortControllerKey];
|
||||||
|
},
|
||||||
|
[getRequestCache]() {
|
||||||
|
this[abortControllerKey] ||= new AbortController();
|
||||||
|
return this[requestCache] ||= newRequestFromIncoming(
|
||||||
|
this.method,
|
||||||
|
this[urlKey],
|
||||||
|
this.headers,
|
||||||
|
this[incomingKey],
|
||||||
|
this[abortControllerKey]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
[
|
||||||
|
"body",
|
||||||
|
"bodyUsed",
|
||||||
|
"cache",
|
||||||
|
"credentials",
|
||||||
|
"destination",
|
||||||
|
"integrity",
|
||||||
|
"mode",
|
||||||
|
"redirect",
|
||||||
|
"referrer",
|
||||||
|
"referrerPolicy",
|
||||||
|
"signal",
|
||||||
|
"keepalive"
|
||||||
|
].forEach((k) => {
|
||||||
|
Object.defineProperty(requestPrototype, k, {
|
||||||
|
get() {
|
||||||
|
return this[getRequestCache]()[k];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
|
||||||
|
Object.defineProperty(requestPrototype, k, {
|
||||||
|
value: function() {
|
||||||
|
return this[getRequestCache]()[k]();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), {
|
||||||
|
value: function(depth, options, inspectFn) {
|
||||||
|
const props = {
|
||||||
|
method: this.method,
|
||||||
|
url: this.url,
|
||||||
|
headers: this.headers,
|
||||||
|
nativeRequest: this[requestCache]
|
||||||
|
};
|
||||||
|
return `Request (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Object.setPrototypeOf(requestPrototype, Request.prototype);
|
||||||
|
var newRequest = (incoming, defaultHostname) => {
|
||||||
|
const req = Object.create(requestPrototype);
|
||||||
|
req[incomingKey] = incoming;
|
||||||
|
const incomingUrl = incoming.url || "";
|
||||||
|
if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
|
||||||
|
(incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
|
||||||
|
if (incoming instanceof import_node_http2.Http2ServerRequest) {
|
||||||
|
throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const url2 = new URL(incomingUrl);
|
||||||
|
req[urlKey] = url2.href;
|
||||||
|
} catch (e) {
|
||||||
|
throw new RequestError("Invalid absolute URL", { cause: e });
|
||||||
|
}
|
||||||
|
return req;
|
||||||
|
}
|
||||||
|
const host = (incoming instanceof import_node_http2.Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
|
||||||
|
if (!host) {
|
||||||
|
throw new RequestError("Missing host header");
|
||||||
|
}
|
||||||
|
let scheme;
|
||||||
|
if (incoming instanceof import_node_http2.Http2ServerRequest) {
|
||||||
|
scheme = incoming.scheme;
|
||||||
|
if (!(scheme === "http" || scheme === "https")) {
|
||||||
|
throw new RequestError("Unsupported scheme");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
|
||||||
|
}
|
||||||
|
const url = new URL(`${scheme}://${host}${incomingUrl}`);
|
||||||
|
if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
|
||||||
|
throw new RequestError("Invalid host header");
|
||||||
|
}
|
||||||
|
req[urlKey] = url.href;
|
||||||
|
return req;
|
||||||
|
};
|
||||||
|
|
||||||
|
// src/response.ts
|
||||||
|
var responseCache = Symbol("responseCache");
|
||||||
|
var getResponseCache = Symbol("getResponseCache");
|
||||||
|
var cacheKey = Symbol("cache");
|
||||||
|
var GlobalResponse = global.Response;
|
||||||
|
var Response2 = class _Response {
|
||||||
|
#body;
|
||||||
|
#init;
|
||||||
|
[getResponseCache]() {
|
||||||
|
delete this[cacheKey];
|
||||||
|
return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
|
||||||
|
}
|
||||||
|
constructor(body, init) {
|
||||||
|
let headers;
|
||||||
|
this.#body = body;
|
||||||
|
if (init instanceof _Response) {
|
||||||
|
const cachedGlobalResponse = init[responseCache];
|
||||||
|
if (cachedGlobalResponse) {
|
||||||
|
this.#init = cachedGlobalResponse;
|
||||||
|
this[getResponseCache]();
|
||||||
|
return;
|
||||||
|
} else {
|
||||||
|
this.#init = init.#init;
|
||||||
|
headers = new Headers(init.#init.headers);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
this.#init = init;
|
||||||
|
}
|
||||||
|
if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
|
||||||
|
;
|
||||||
|
this[cacheKey] = [init?.status || 200, body, headers || init?.headers];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
get headers() {
|
||||||
|
const cache = this[cacheKey];
|
||||||
|
if (cache) {
|
||||||
|
if (!(cache[2] instanceof Headers)) {
|
||||||
|
cache[2] = new Headers(
|
||||||
|
cache[2] || { "content-type": "text/plain; charset=UTF-8" }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return cache[2];
|
||||||
|
}
|
||||||
|
return this[getResponseCache]().headers;
|
||||||
|
}
|
||||||
|
get status() {
|
||||||
|
return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
|
||||||
|
}
|
||||||
|
get ok() {
|
||||||
|
const status = this.status;
|
||||||
|
return status >= 200 && status < 300;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
|
||||||
|
Object.defineProperty(Response2.prototype, k, {
|
||||||
|
get() {
|
||||||
|
return this[getResponseCache]()[k];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
|
||||||
|
Object.defineProperty(Response2.prototype, k, {
|
||||||
|
value: function() {
|
||||||
|
return this[getResponseCache]()[k]();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
Object.defineProperty(Response2.prototype, Symbol.for("nodejs.util.inspect.custom"), {
|
||||||
|
value: function(depth, options, inspectFn) {
|
||||||
|
const props = {
|
||||||
|
status: this.status,
|
||||||
|
headers: this.headers,
|
||||||
|
ok: this.ok,
|
||||||
|
nativeResponse: this[responseCache]
|
||||||
|
};
|
||||||
|
return `Response (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Object.setPrototypeOf(Response2, GlobalResponse);
|
||||||
|
Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
|
||||||
|
|
||||||
|
// src/utils.ts
|
||||||
|
async function readWithoutBlocking(readPromise) {
|
||||||
|
return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
|
||||||
|
}
|
||||||
|
function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
|
||||||
|
const cancel = (error) => {
|
||||||
|
reader.cancel(error).catch(() => {
|
||||||
|
});
|
||||||
|
};
|
||||||
|
writable.on("close", cancel);
|
||||||
|
writable.on("error", cancel);
|
||||||
|
(currentReadPromise ?? reader.read()).then(flow, handleStreamError);
|
||||||
|
return reader.closed.finally(() => {
|
||||||
|
writable.off("close", cancel);
|
||||||
|
writable.off("error", cancel);
|
||||||
|
});
|
||||||
|
function handleStreamError(error) {
|
||||||
|
if (error) {
|
||||||
|
writable.destroy(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function onDrain() {
|
||||||
|
reader.read().then(flow, handleStreamError);
|
||||||
|
}
|
||||||
|
function flow({ done, value }) {
|
||||||
|
try {
|
||||||
|
if (done) {
|
||||||
|
writable.end();
|
||||||
|
} else if (!writable.write(value)) {
|
||||||
|
writable.once("drain", onDrain);
|
||||||
|
} else {
|
||||||
|
return reader.read().then(flow, handleStreamError);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
handleStreamError(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function writeFromReadableStream(stream, writable) {
|
||||||
|
if (stream.locked) {
|
||||||
|
throw new TypeError("ReadableStream is locked.");
|
||||||
|
} else if (writable.destroyed) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
|
||||||
|
}
|
||||||
|
var buildOutgoingHttpHeaders = (headers) => {
|
||||||
|
const res = {};
|
||||||
|
if (!(headers instanceof Headers)) {
|
||||||
|
headers = new Headers(headers ?? void 0);
|
||||||
|
}
|
||||||
|
const cookies = [];
|
||||||
|
for (const [k, v] of headers) {
|
||||||
|
if (k === "set-cookie") {
|
||||||
|
cookies.push(v);
|
||||||
|
} else {
|
||||||
|
res[k] = v;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (cookies.length > 0) {
|
||||||
|
res["set-cookie"] = cookies;
|
||||||
|
}
|
||||||
|
res["content-type"] ??= "text/plain; charset=UTF-8";
|
||||||
|
return res;
|
||||||
|
};
|
||||||
|
|
||||||
|
// src/utils/response/constants.ts
|
||||||
|
var X_ALREADY_SENT = "x-hono-already-sent";
|
||||||
|
|
||||||
|
// src/globals.ts
|
||||||
|
var import_node_crypto = __toESM(require("crypto"));
|
||||||
|
if (typeof global.crypto === "undefined") {
|
||||||
|
global.crypto = import_node_crypto.default;
|
||||||
|
}
|
||||||
|
|
||||||
|
// src/listener.ts
|
||||||
|
var outgoingEnded = Symbol("outgoingEnded");
|
||||||
|
var incomingDraining = Symbol("incomingDraining");
|
||||||
|
var DRAIN_TIMEOUT_MS = 500;
|
||||||
|
var MAX_DRAIN_BYTES = 64 * 1024 * 1024;
|
||||||
|
var drainIncoming = (incoming) => {
|
||||||
|
const incomingWithDrainState = incoming;
|
||||||
|
if (incoming.destroyed || incomingWithDrainState[incomingDraining]) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
incomingWithDrainState[incomingDraining] = true;
|
||||||
|
if (incoming instanceof import_node_http22.Http2ServerRequest) {
|
||||||
|
try {
|
||||||
|
;
|
||||||
|
incoming.stream?.close?.(import_node_http22.constants.NGHTTP2_NO_ERROR);
|
||||||
|
} catch {
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let bytesRead = 0;
|
||||||
|
const cleanup = () => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
incoming.off("data", onData);
|
||||||
|
incoming.off("end", cleanup);
|
||||||
|
incoming.off("error", cleanup);
|
||||||
|
};
|
||||||
|
const forceClose = () => {
|
||||||
|
cleanup();
|
||||||
|
const socket = incoming.socket;
|
||||||
|
if (socket && !socket.destroyed) {
|
||||||
|
socket.destroySoon();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
|
||||||
|
timer.unref?.();
|
||||||
|
const onData = (chunk) => {
|
||||||
|
bytesRead += chunk.length;
|
||||||
|
if (bytesRead > MAX_DRAIN_BYTES) {
|
||||||
|
forceClose();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
incoming.on("data", onData);
|
||||||
|
incoming.on("end", cleanup);
|
||||||
|
incoming.on("error", cleanup);
|
||||||
|
incoming.resume();
|
||||||
|
};
|
||||||
|
var handleRequestError = () => new Response(null, {
|
||||||
|
status: 400
|
||||||
|
});
|
||||||
|
var handleFetchError = (e) => new Response(null, {
|
||||||
|
status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
|
||||||
|
});
|
||||||
|
var handleResponseError = (e, outgoing) => {
|
||||||
|
const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
|
||||||
|
if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
|
||||||
|
console.info("The user aborted a request.");
|
||||||
|
} else {
|
||||||
|
console.error(e);
|
||||||
|
if (!outgoing.headersSent) {
|
||||||
|
outgoing.writeHead(500, { "Content-Type": "text/plain" });
|
||||||
|
}
|
||||||
|
outgoing.end(`Error: ${err.message}`);
|
||||||
|
outgoing.destroy(err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var flushHeaders = (outgoing) => {
|
||||||
|
if ("flushHeaders" in outgoing && outgoing.writable) {
|
||||||
|
outgoing.flushHeaders();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var responseViaCache = async (res, outgoing) => {
|
||||||
|
let [status, body, header] = res[cacheKey];
|
||||||
|
let hasContentLength = false;
|
||||||
|
if (!header) {
|
||||||
|
header = { "content-type": "text/plain; charset=UTF-8" };
|
||||||
|
} else if (header instanceof Headers) {
|
||||||
|
hasContentLength = header.has("content-length");
|
||||||
|
header = buildOutgoingHttpHeaders(header);
|
||||||
|
} else if (Array.isArray(header)) {
|
||||||
|
const headerObj = new Headers(header);
|
||||||
|
hasContentLength = headerObj.has("content-length");
|
||||||
|
header = buildOutgoingHttpHeaders(headerObj);
|
||||||
|
} else {
|
||||||
|
for (const key in header) {
|
||||||
|
if (key.length === 14 && key.toLowerCase() === "content-length") {
|
||||||
|
hasContentLength = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!hasContentLength) {
|
||||||
|
if (typeof body === "string") {
|
||||||
|
header["Content-Length"] = Buffer.byteLength(body);
|
||||||
|
} else if (body instanceof Uint8Array) {
|
||||||
|
header["Content-Length"] = body.byteLength;
|
||||||
|
} else if (body instanceof Blob) {
|
||||||
|
header["Content-Length"] = body.size;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
outgoing.writeHead(status, header);
|
||||||
|
if (typeof body === "string" || body instanceof Uint8Array) {
|
||||||
|
outgoing.end(body);
|
||||||
|
} else if (body instanceof Blob) {
|
||||||
|
outgoing.end(new Uint8Array(await body.arrayBuffer()));
|
||||||
|
} else {
|
||||||
|
flushHeaders(outgoing);
|
||||||
|
await writeFromReadableStream(body, outgoing)?.catch(
|
||||||
|
(e) => handleResponseError(e, outgoing)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
;
|
||||||
|
outgoing[outgoingEnded]?.();
|
||||||
|
};
|
||||||
|
var isPromise = (res) => typeof res.then === "function";
|
||||||
|
var responseViaResponseObject = async (res, outgoing, options = {}) => {
|
||||||
|
if (isPromise(res)) {
|
||||||
|
if (options.errorHandler) {
|
||||||
|
try {
|
||||||
|
res = await res;
|
||||||
|
} catch (err) {
|
||||||
|
const errRes = await options.errorHandler(err);
|
||||||
|
if (!errRes) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
res = errRes;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
res = await res.catch(handleFetchError);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (cacheKey in res) {
|
||||||
|
return responseViaCache(res, outgoing);
|
||||||
|
}
|
||||||
|
const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
|
||||||
|
if (res.body) {
|
||||||
|
const reader = res.body.getReader();
|
||||||
|
const values = [];
|
||||||
|
let done = false;
|
||||||
|
let currentReadPromise = void 0;
|
||||||
|
if (resHeaderRecord["transfer-encoding"] !== "chunked") {
|
||||||
|
let maxReadCount = 2;
|
||||||
|
for (let i = 0; i < maxReadCount; i++) {
|
||||||
|
currentReadPromise ||= reader.read();
|
||||||
|
const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
|
||||||
|
console.error(e);
|
||||||
|
done = true;
|
||||||
|
});
|
||||||
|
if (!chunk) {
|
||||||
|
if (i === 1) {
|
||||||
|
await new Promise((resolve) => setTimeout(resolve));
|
||||||
|
maxReadCount = 3;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
currentReadPromise = void 0;
|
||||||
|
if (chunk.value) {
|
||||||
|
values.push(chunk.value);
|
||||||
|
}
|
||||||
|
if (chunk.done) {
|
||||||
|
done = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (done && !("content-length" in resHeaderRecord)) {
|
||||||
|
resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
outgoing.writeHead(res.status, resHeaderRecord);
|
||||||
|
values.forEach((value) => {
|
||||||
|
;
|
||||||
|
outgoing.write(value);
|
||||||
|
});
|
||||||
|
if (done) {
|
||||||
|
outgoing.end();
|
||||||
|
} else {
|
||||||
|
if (values.length === 0) {
|
||||||
|
flushHeaders(outgoing);
|
||||||
|
}
|
||||||
|
await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
|
||||||
|
}
|
||||||
|
} else if (resHeaderRecord[X_ALREADY_SENT]) {
|
||||||
|
} else {
|
||||||
|
outgoing.writeHead(res.status, resHeaderRecord);
|
||||||
|
outgoing.end();
|
||||||
|
}
|
||||||
|
;
|
||||||
|
outgoing[outgoingEnded]?.();
|
||||||
|
};
|
||||||
|
var getRequestListener = (fetchCallback, options = {}) => {
|
||||||
|
const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
|
||||||
|
if (options.overrideGlobalObjects !== false && global.Request !== Request) {
|
||||||
|
Object.defineProperty(global, "Request", {
|
||||||
|
value: Request
|
||||||
|
});
|
||||||
|
Object.defineProperty(global, "Response", {
|
||||||
|
value: Response2
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return async (incoming, outgoing) => {
|
||||||
|
let res, req;
|
||||||
|
try {
|
||||||
|
req = newRequest(incoming, options.hostname);
|
||||||
|
let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
|
||||||
|
if (!incomingEnded) {
|
||||||
|
;
|
||||||
|
incoming[wrapBodyStream] = true;
|
||||||
|
incoming.on("end", () => {
|
||||||
|
incomingEnded = true;
|
||||||
|
});
|
||||||
|
if (incoming instanceof import_node_http22.Http2ServerRequest) {
|
||||||
|
;
|
||||||
|
outgoing[outgoingEnded] = () => {
|
||||||
|
if (!incomingEnded) {
|
||||||
|
setTimeout(() => {
|
||||||
|
if (!incomingEnded) {
|
||||||
|
setTimeout(() => {
|
||||||
|
drainIncoming(incoming);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
outgoing.on("finish", () => {
|
||||||
|
if (!incomingEnded) {
|
||||||
|
drainIncoming(incoming);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
outgoing.on("close", () => {
|
||||||
|
const abortController = req[abortControllerKey];
|
||||||
|
if (abortController) {
|
||||||
|
if (incoming.errored) {
|
||||||
|
req[abortControllerKey].abort(incoming.errored.toString());
|
||||||
|
} else if (!outgoing.writableFinished) {
|
||||||
|
req[abortControllerKey].abort("Client connection prematurely closed.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!incomingEnded) {
|
||||||
|
setTimeout(() => {
|
||||||
|
if (!incomingEnded) {
|
||||||
|
setTimeout(() => {
|
||||||
|
drainIncoming(incoming);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
res = fetchCallback(req, { incoming, outgoing });
|
||||||
|
if (cacheKey in res) {
|
||||||
|
return responseViaCache(res, outgoing);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
if (!res) {
|
||||||
|
if (options.errorHandler) {
|
||||||
|
res = await options.errorHandler(req ? e : toRequestError(e));
|
||||||
|
if (!res) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} else if (!req) {
|
||||||
|
res = handleRequestError();
|
||||||
|
} else {
|
||||||
|
res = handleFetchError(e);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return handleResponseError(e, outgoing);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return await responseViaResponseObject(res, outgoing, options);
|
||||||
|
} catch (e) {
|
||||||
|
return handleResponseError(e, outgoing);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
};
|
||||||
|
// Annotate the CommonJS export names for ESM import in node:
|
||||||
|
0 && (module.exports = {
|
||||||
|
getRequestListener
|
||||||
|
});
|
||||||
635
node_modules/@hono/node-server/dist/listener.mjs
generated
vendored
Normal file
635
node_modules/@hono/node-server/dist/listener.mjs
generated
vendored
Normal file
@@ -0,0 +1,635 @@
|
|||||||
|
// src/listener.ts
|
||||||
|
import { Http2ServerRequest as Http2ServerRequest2, constants as h2constants } from "http2";
|
||||||
|
|
||||||
|
// src/request.ts
|
||||||
|
import { Http2ServerRequest } from "http2";
|
||||||
|
import { Readable } from "stream";
|
||||||
|
var RequestError = class extends Error {
|
||||||
|
constructor(message, options) {
|
||||||
|
super(message, options);
|
||||||
|
this.name = "RequestError";
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var toRequestError = (e) => {
|
||||||
|
if (e instanceof RequestError) {
|
||||||
|
return e;
|
||||||
|
}
|
||||||
|
return new RequestError(e.message, { cause: e });
|
||||||
|
};
|
||||||
|
var GlobalRequest = global.Request;
|
||||||
|
var Request = class extends GlobalRequest {
|
||||||
|
constructor(input, options) {
|
||||||
|
if (typeof input === "object" && getRequestCache in input) {
|
||||||
|
input = input[getRequestCache]();
|
||||||
|
}
|
||||||
|
if (typeof options?.body?.getReader !== "undefined") {
|
||||||
|
;
|
||||||
|
options.duplex ??= "half";
|
||||||
|
}
|
||||||
|
super(input, options);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var newHeadersFromIncoming = (incoming) => {
|
||||||
|
const headerRecord = [];
|
||||||
|
const rawHeaders = incoming.rawHeaders;
|
||||||
|
for (let i = 0; i < rawHeaders.length; i += 2) {
|
||||||
|
const { [i]: key, [i + 1]: value } = rawHeaders;
|
||||||
|
if (key.charCodeAt(0) !== /*:*/
|
||||||
|
58) {
|
||||||
|
headerRecord.push([key, value]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new Headers(headerRecord);
|
||||||
|
};
|
||||||
|
var wrapBodyStream = Symbol("wrapBodyStream");
|
||||||
|
var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
|
||||||
|
const init = {
|
||||||
|
method,
|
||||||
|
headers,
|
||||||
|
signal: abortController.signal
|
||||||
|
};
|
||||||
|
if (method === "TRACE") {
|
||||||
|
init.method = "GET";
|
||||||
|
const req = new Request(url, init);
|
||||||
|
Object.defineProperty(req, "method", {
|
||||||
|
get() {
|
||||||
|
return "TRACE";
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return req;
|
||||||
|
}
|
||||||
|
if (!(method === "GET" || method === "HEAD")) {
|
||||||
|
if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
|
||||||
|
init.body = new ReadableStream({
|
||||||
|
start(controller) {
|
||||||
|
controller.enqueue(incoming.rawBody);
|
||||||
|
controller.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else if (incoming[wrapBodyStream]) {
|
||||||
|
let reader;
|
||||||
|
init.body = new ReadableStream({
|
||||||
|
async pull(controller) {
|
||||||
|
try {
|
||||||
|
reader ||= Readable.toWeb(incoming).getReader();
|
||||||
|
const { done, value } = await reader.read();
|
||||||
|
if (done) {
|
||||||
|
controller.close();
|
||||||
|
} else {
|
||||||
|
controller.enqueue(value);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
controller.error(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
init.body = Readable.toWeb(incoming);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new Request(url, init);
|
||||||
|
};
|
||||||
|
var getRequestCache = Symbol("getRequestCache");
|
||||||
|
var requestCache = Symbol("requestCache");
|
||||||
|
var incomingKey = Symbol("incomingKey");
|
||||||
|
var urlKey = Symbol("urlKey");
|
||||||
|
var headersKey = Symbol("headersKey");
|
||||||
|
var abortControllerKey = Symbol("abortControllerKey");
|
||||||
|
var getAbortController = Symbol("getAbortController");
|
||||||
|
var requestPrototype = {
|
||||||
|
get method() {
|
||||||
|
return this[incomingKey].method || "GET";
|
||||||
|
},
|
||||||
|
get url() {
|
||||||
|
return this[urlKey];
|
||||||
|
},
|
||||||
|
get headers() {
|
||||||
|
return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
|
||||||
|
},
|
||||||
|
[getAbortController]() {
|
||||||
|
this[getRequestCache]();
|
||||||
|
return this[abortControllerKey];
|
||||||
|
},
|
||||||
|
[getRequestCache]() {
|
||||||
|
this[abortControllerKey] ||= new AbortController();
|
||||||
|
return this[requestCache] ||= newRequestFromIncoming(
|
||||||
|
this.method,
|
||||||
|
this[urlKey],
|
||||||
|
this.headers,
|
||||||
|
this[incomingKey],
|
||||||
|
this[abortControllerKey]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
[
|
||||||
|
"body",
|
||||||
|
"bodyUsed",
|
||||||
|
"cache",
|
||||||
|
"credentials",
|
||||||
|
"destination",
|
||||||
|
"integrity",
|
||||||
|
"mode",
|
||||||
|
"redirect",
|
||||||
|
"referrer",
|
||||||
|
"referrerPolicy",
|
||||||
|
"signal",
|
||||||
|
"keepalive"
|
||||||
|
].forEach((k) => {
|
||||||
|
Object.defineProperty(requestPrototype, k, {
|
||||||
|
get() {
|
||||||
|
return this[getRequestCache]()[k];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
|
||||||
|
Object.defineProperty(requestPrototype, k, {
|
||||||
|
value: function() {
|
||||||
|
return this[getRequestCache]()[k]();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), {
|
||||||
|
value: function(depth, options, inspectFn) {
|
||||||
|
const props = {
|
||||||
|
method: this.method,
|
||||||
|
url: this.url,
|
||||||
|
headers: this.headers,
|
||||||
|
nativeRequest: this[requestCache]
|
||||||
|
};
|
||||||
|
return `Request (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Object.setPrototypeOf(requestPrototype, Request.prototype);
|
||||||
|
var newRequest = (incoming, defaultHostname) => {
|
||||||
|
const req = Object.create(requestPrototype);
|
||||||
|
req[incomingKey] = incoming;
|
||||||
|
const incomingUrl = incoming.url || "";
|
||||||
|
if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
|
||||||
|
(incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
|
||||||
|
if (incoming instanceof Http2ServerRequest) {
|
||||||
|
throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const url2 = new URL(incomingUrl);
|
||||||
|
req[urlKey] = url2.href;
|
||||||
|
} catch (e) {
|
||||||
|
throw new RequestError("Invalid absolute URL", { cause: e });
|
||||||
|
}
|
||||||
|
return req;
|
||||||
|
}
|
||||||
|
const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
|
||||||
|
if (!host) {
|
||||||
|
throw new RequestError("Missing host header");
|
||||||
|
}
|
||||||
|
let scheme;
|
||||||
|
if (incoming instanceof Http2ServerRequest) {
|
||||||
|
scheme = incoming.scheme;
|
||||||
|
if (!(scheme === "http" || scheme === "https")) {
|
||||||
|
throw new RequestError("Unsupported scheme");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
|
||||||
|
}
|
||||||
|
const url = new URL(`${scheme}://${host}${incomingUrl}`);
|
||||||
|
if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
|
||||||
|
throw new RequestError("Invalid host header");
|
||||||
|
}
|
||||||
|
req[urlKey] = url.href;
|
||||||
|
return req;
|
||||||
|
};
|
||||||
|
|
||||||
|
// src/response.ts
|
||||||
|
var responseCache = Symbol("responseCache");
|
||||||
|
var getResponseCache = Symbol("getResponseCache");
|
||||||
|
var cacheKey = Symbol("cache");
|
||||||
|
var GlobalResponse = global.Response;
|
||||||
|
var Response2 = class _Response {
|
||||||
|
#body;
|
||||||
|
#init;
|
||||||
|
[getResponseCache]() {
|
||||||
|
delete this[cacheKey];
|
||||||
|
return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
|
||||||
|
}
|
||||||
|
constructor(body, init) {
|
||||||
|
let headers;
|
||||||
|
this.#body = body;
|
||||||
|
if (init instanceof _Response) {
|
||||||
|
const cachedGlobalResponse = init[responseCache];
|
||||||
|
if (cachedGlobalResponse) {
|
||||||
|
this.#init = cachedGlobalResponse;
|
||||||
|
this[getResponseCache]();
|
||||||
|
return;
|
||||||
|
} else {
|
||||||
|
this.#init = init.#init;
|
||||||
|
headers = new Headers(init.#init.headers);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
this.#init = init;
|
||||||
|
}
|
||||||
|
if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
|
||||||
|
;
|
||||||
|
this[cacheKey] = [init?.status || 200, body, headers || init?.headers];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
get headers() {
|
||||||
|
const cache = this[cacheKey];
|
||||||
|
if (cache) {
|
||||||
|
if (!(cache[2] instanceof Headers)) {
|
||||||
|
cache[2] = new Headers(
|
||||||
|
cache[2] || { "content-type": "text/plain; charset=UTF-8" }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return cache[2];
|
||||||
|
}
|
||||||
|
return this[getResponseCache]().headers;
|
||||||
|
}
|
||||||
|
get status() {
|
||||||
|
return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
|
||||||
|
}
|
||||||
|
get ok() {
|
||||||
|
const status = this.status;
|
||||||
|
return status >= 200 && status < 300;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
|
||||||
|
Object.defineProperty(Response2.prototype, k, {
|
||||||
|
get() {
|
||||||
|
return this[getResponseCache]()[k];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
|
||||||
|
Object.defineProperty(Response2.prototype, k, {
|
||||||
|
value: function() {
|
||||||
|
return this[getResponseCache]()[k]();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
Object.defineProperty(Response2.prototype, Symbol.for("nodejs.util.inspect.custom"), {
|
||||||
|
value: function(depth, options, inspectFn) {
|
||||||
|
const props = {
|
||||||
|
status: this.status,
|
||||||
|
headers: this.headers,
|
||||||
|
ok: this.ok,
|
||||||
|
nativeResponse: this[responseCache]
|
||||||
|
};
|
||||||
|
return `Response (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Object.setPrototypeOf(Response2, GlobalResponse);
|
||||||
|
Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
|
||||||
|
|
||||||
|
// src/utils.ts
|
||||||
|
async function readWithoutBlocking(readPromise) {
|
||||||
|
return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
|
||||||
|
}
|
||||||
|
function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
|
||||||
|
const cancel = (error) => {
|
||||||
|
reader.cancel(error).catch(() => {
|
||||||
|
});
|
||||||
|
};
|
||||||
|
writable.on("close", cancel);
|
||||||
|
writable.on("error", cancel);
|
||||||
|
(currentReadPromise ?? reader.read()).then(flow, handleStreamError);
|
||||||
|
return reader.closed.finally(() => {
|
||||||
|
writable.off("close", cancel);
|
||||||
|
writable.off("error", cancel);
|
||||||
|
});
|
||||||
|
function handleStreamError(error) {
|
||||||
|
if (error) {
|
||||||
|
writable.destroy(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function onDrain() {
|
||||||
|
reader.read().then(flow, handleStreamError);
|
||||||
|
}
|
||||||
|
function flow({ done, value }) {
|
||||||
|
try {
|
||||||
|
if (done) {
|
||||||
|
writable.end();
|
||||||
|
} else if (!writable.write(value)) {
|
||||||
|
writable.once("drain", onDrain);
|
||||||
|
} else {
|
||||||
|
return reader.read().then(flow, handleStreamError);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
handleStreamError(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function writeFromReadableStream(stream, writable) {
|
||||||
|
if (stream.locked) {
|
||||||
|
throw new TypeError("ReadableStream is locked.");
|
||||||
|
} else if (writable.destroyed) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
|
||||||
|
}
|
||||||
|
var buildOutgoingHttpHeaders = (headers) => {
|
||||||
|
const res = {};
|
||||||
|
if (!(headers instanceof Headers)) {
|
||||||
|
headers = new Headers(headers ?? void 0);
|
||||||
|
}
|
||||||
|
const cookies = [];
|
||||||
|
for (const [k, v] of headers) {
|
||||||
|
if (k === "set-cookie") {
|
||||||
|
cookies.push(v);
|
||||||
|
} else {
|
||||||
|
res[k] = v;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (cookies.length > 0) {
|
||||||
|
res["set-cookie"] = cookies;
|
||||||
|
}
|
||||||
|
res["content-type"] ??= "text/plain; charset=UTF-8";
|
||||||
|
return res;
|
||||||
|
};
|
||||||
|
|
||||||
|
// src/utils/response/constants.ts
|
||||||
|
var X_ALREADY_SENT = "x-hono-already-sent";
|
||||||
|
|
||||||
|
// src/globals.ts
|
||||||
|
import crypto from "crypto";
|
||||||
|
if (typeof global.crypto === "undefined") {
|
||||||
|
global.crypto = crypto;
|
||||||
|
}
|
||||||
|
|
||||||
|
// src/listener.ts
|
||||||
|
var outgoingEnded = Symbol("outgoingEnded");
|
||||||
|
var incomingDraining = Symbol("incomingDraining");
|
||||||
|
var DRAIN_TIMEOUT_MS = 500;
|
||||||
|
var MAX_DRAIN_BYTES = 64 * 1024 * 1024;
|
||||||
|
var drainIncoming = (incoming) => {
|
||||||
|
const incomingWithDrainState = incoming;
|
||||||
|
if (incoming.destroyed || incomingWithDrainState[incomingDraining]) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
incomingWithDrainState[incomingDraining] = true;
|
||||||
|
if (incoming instanceof Http2ServerRequest2) {
|
||||||
|
try {
|
||||||
|
;
|
||||||
|
incoming.stream?.close?.(h2constants.NGHTTP2_NO_ERROR);
|
||||||
|
} catch {
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let bytesRead = 0;
|
||||||
|
const cleanup = () => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
incoming.off("data", onData);
|
||||||
|
incoming.off("end", cleanup);
|
||||||
|
incoming.off("error", cleanup);
|
||||||
|
};
|
||||||
|
const forceClose = () => {
|
||||||
|
cleanup();
|
||||||
|
const socket = incoming.socket;
|
||||||
|
if (socket && !socket.destroyed) {
|
||||||
|
socket.destroySoon();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
|
||||||
|
timer.unref?.();
|
||||||
|
const onData = (chunk) => {
|
||||||
|
bytesRead += chunk.length;
|
||||||
|
if (bytesRead > MAX_DRAIN_BYTES) {
|
||||||
|
forceClose();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
incoming.on("data", onData);
|
||||||
|
incoming.on("end", cleanup);
|
||||||
|
incoming.on("error", cleanup);
|
||||||
|
incoming.resume();
|
||||||
|
};
|
||||||
|
var handleRequestError = () => new Response(null, {
|
||||||
|
status: 400
|
||||||
|
});
|
||||||
|
var handleFetchError = (e) => new Response(null, {
|
||||||
|
status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
|
||||||
|
});
|
||||||
|
var handleResponseError = (e, outgoing) => {
|
||||||
|
const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
|
||||||
|
if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
|
||||||
|
console.info("The user aborted a request.");
|
||||||
|
} else {
|
||||||
|
console.error(e);
|
||||||
|
if (!outgoing.headersSent) {
|
||||||
|
outgoing.writeHead(500, { "Content-Type": "text/plain" });
|
||||||
|
}
|
||||||
|
outgoing.end(`Error: ${err.message}`);
|
||||||
|
outgoing.destroy(err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var flushHeaders = (outgoing) => {
|
||||||
|
if ("flushHeaders" in outgoing && outgoing.writable) {
|
||||||
|
outgoing.flushHeaders();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var responseViaCache = async (res, outgoing) => {
|
||||||
|
let [status, body, header] = res[cacheKey];
|
||||||
|
let hasContentLength = false;
|
||||||
|
if (!header) {
|
||||||
|
header = { "content-type": "text/plain; charset=UTF-8" };
|
||||||
|
} else if (header instanceof Headers) {
|
||||||
|
hasContentLength = header.has("content-length");
|
||||||
|
header = buildOutgoingHttpHeaders(header);
|
||||||
|
} else if (Array.isArray(header)) {
|
||||||
|
const headerObj = new Headers(header);
|
||||||
|
hasContentLength = headerObj.has("content-length");
|
||||||
|
header = buildOutgoingHttpHeaders(headerObj);
|
||||||
|
} else {
|
||||||
|
for (const key in header) {
|
||||||
|
if (key.length === 14 && key.toLowerCase() === "content-length") {
|
||||||
|
hasContentLength = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!hasContentLength) {
|
||||||
|
if (typeof body === "string") {
|
||||||
|
header["Content-Length"] = Buffer.byteLength(body);
|
||||||
|
} else if (body instanceof Uint8Array) {
|
||||||
|
header["Content-Length"] = body.byteLength;
|
||||||
|
} else if (body instanceof Blob) {
|
||||||
|
header["Content-Length"] = body.size;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
outgoing.writeHead(status, header);
|
||||||
|
if (typeof body === "string" || body instanceof Uint8Array) {
|
||||||
|
outgoing.end(body);
|
||||||
|
} else if (body instanceof Blob) {
|
||||||
|
outgoing.end(new Uint8Array(await body.arrayBuffer()));
|
||||||
|
} else {
|
||||||
|
flushHeaders(outgoing);
|
||||||
|
await writeFromReadableStream(body, outgoing)?.catch(
|
||||||
|
(e) => handleResponseError(e, outgoing)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
;
|
||||||
|
outgoing[outgoingEnded]?.();
|
||||||
|
};
|
||||||
|
var isPromise = (res) => typeof res.then === "function";
|
||||||
|
var responseViaResponseObject = async (res, outgoing, options = {}) => {
|
||||||
|
if (isPromise(res)) {
|
||||||
|
if (options.errorHandler) {
|
||||||
|
try {
|
||||||
|
res = await res;
|
||||||
|
} catch (err) {
|
||||||
|
const errRes = await options.errorHandler(err);
|
||||||
|
if (!errRes) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
res = errRes;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
res = await res.catch(handleFetchError);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (cacheKey in res) {
|
||||||
|
return responseViaCache(res, outgoing);
|
||||||
|
}
|
||||||
|
const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
|
||||||
|
if (res.body) {
|
||||||
|
const reader = res.body.getReader();
|
||||||
|
const values = [];
|
||||||
|
let done = false;
|
||||||
|
let currentReadPromise = void 0;
|
||||||
|
if (resHeaderRecord["transfer-encoding"] !== "chunked") {
|
||||||
|
let maxReadCount = 2;
|
||||||
|
for (let i = 0; i < maxReadCount; i++) {
|
||||||
|
currentReadPromise ||= reader.read();
|
||||||
|
const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
|
||||||
|
console.error(e);
|
||||||
|
done = true;
|
||||||
|
});
|
||||||
|
if (!chunk) {
|
||||||
|
if (i === 1) {
|
||||||
|
await new Promise((resolve) => setTimeout(resolve));
|
||||||
|
maxReadCount = 3;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
currentReadPromise = void 0;
|
||||||
|
if (chunk.value) {
|
||||||
|
values.push(chunk.value);
|
||||||
|
}
|
||||||
|
if (chunk.done) {
|
||||||
|
done = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (done && !("content-length" in resHeaderRecord)) {
|
||||||
|
resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
outgoing.writeHead(res.status, resHeaderRecord);
|
||||||
|
values.forEach((value) => {
|
||||||
|
;
|
||||||
|
outgoing.write(value);
|
||||||
|
});
|
||||||
|
if (done) {
|
||||||
|
outgoing.end();
|
||||||
|
} else {
|
||||||
|
if (values.length === 0) {
|
||||||
|
flushHeaders(outgoing);
|
||||||
|
}
|
||||||
|
await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
|
||||||
|
}
|
||||||
|
} else if (resHeaderRecord[X_ALREADY_SENT]) {
|
||||||
|
} else {
|
||||||
|
outgoing.writeHead(res.status, resHeaderRecord);
|
||||||
|
outgoing.end();
|
||||||
|
}
|
||||||
|
;
|
||||||
|
outgoing[outgoingEnded]?.();
|
||||||
|
};
|
||||||
|
var getRequestListener = (fetchCallback, options = {}) => {
|
||||||
|
const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
|
||||||
|
if (options.overrideGlobalObjects !== false && global.Request !== Request) {
|
||||||
|
Object.defineProperty(global, "Request", {
|
||||||
|
value: Request
|
||||||
|
});
|
||||||
|
Object.defineProperty(global, "Response", {
|
||||||
|
value: Response2
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return async (incoming, outgoing) => {
|
||||||
|
let res, req;
|
||||||
|
try {
|
||||||
|
req = newRequest(incoming, options.hostname);
|
||||||
|
let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
|
||||||
|
if (!incomingEnded) {
|
||||||
|
;
|
||||||
|
incoming[wrapBodyStream] = true;
|
||||||
|
incoming.on("end", () => {
|
||||||
|
incomingEnded = true;
|
||||||
|
});
|
||||||
|
if (incoming instanceof Http2ServerRequest2) {
|
||||||
|
;
|
||||||
|
outgoing[outgoingEnded] = () => {
|
||||||
|
if (!incomingEnded) {
|
||||||
|
setTimeout(() => {
|
||||||
|
if (!incomingEnded) {
|
||||||
|
setTimeout(() => {
|
||||||
|
drainIncoming(incoming);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
outgoing.on("finish", () => {
|
||||||
|
if (!incomingEnded) {
|
||||||
|
drainIncoming(incoming);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
outgoing.on("close", () => {
|
||||||
|
const abortController = req[abortControllerKey];
|
||||||
|
if (abortController) {
|
||||||
|
if (incoming.errored) {
|
||||||
|
req[abortControllerKey].abort(incoming.errored.toString());
|
||||||
|
} else if (!outgoing.writableFinished) {
|
||||||
|
req[abortControllerKey].abort("Client connection prematurely closed.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!incomingEnded) {
|
||||||
|
setTimeout(() => {
|
||||||
|
if (!incomingEnded) {
|
||||||
|
setTimeout(() => {
|
||||||
|
drainIncoming(incoming);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
res = fetchCallback(req, { incoming, outgoing });
|
||||||
|
if (cacheKey in res) {
|
||||||
|
return responseViaCache(res, outgoing);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
if (!res) {
|
||||||
|
if (options.errorHandler) {
|
||||||
|
res = await options.errorHandler(req ? e : toRequestError(e));
|
||||||
|
if (!res) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} else if (!req) {
|
||||||
|
res = handleRequestError();
|
||||||
|
} else {
|
||||||
|
res = handleFetchError(e);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return handleResponseError(e, outgoing);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return await responseViaResponseObject(res, outgoing, options);
|
||||||
|
} catch (e) {
|
||||||
|
return handleResponseError(e, outgoing);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
};
|
||||||
|
export {
|
||||||
|
getRequestListener
|
||||||
|
};
|
||||||
25
node_modules/@hono/node-server/dist/request.d.mts
generated
vendored
Normal file
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, type 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, type IncomingMessageWithWrapBodyStream, Request, RequestError, abortControllerKey, getAbortController, newRequest, toRequestError, wrapBodyStream };
|
||||||
238
node_modules/@hono/node-server/dist/request.js
generated
vendored
Normal file
238
node_modules/@hono/node-server/dist/request.js
generated
vendored
Normal file
@@ -0,0 +1,238 @@
|
|||||||
|
"use strict";
|
||||||
|
var __defProp = Object.defineProperty;
|
||||||
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||||
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||||
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||||
|
var __export = (target, all) => {
|
||||||
|
for (var name in all)
|
||||||
|
__defProp(target, name, { get: all[name], enumerable: true });
|
||||||
|
};
|
||||||
|
var __copyProps = (to, from, except, desc) => {
|
||||||
|
if (from && typeof from === "object" || typeof from === "function") {
|
||||||
|
for (let key of __getOwnPropNames(from))
|
||||||
|
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||||
|
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||||
|
}
|
||||||
|
return to;
|
||||||
|
};
|
||||||
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||||
|
|
||||||
|
// src/request.ts
|
||||||
|
var request_exports = {};
|
||||||
|
__export(request_exports, {
|
||||||
|
GlobalRequest: () => GlobalRequest,
|
||||||
|
Request: () => Request,
|
||||||
|
RequestError: () => RequestError,
|
||||||
|
abortControllerKey: () => abortControllerKey,
|
||||||
|
getAbortController: () => getAbortController,
|
||||||
|
newRequest: () => newRequest,
|
||||||
|
toRequestError: () => toRequestError,
|
||||||
|
wrapBodyStream: () => wrapBodyStream
|
||||||
|
});
|
||||||
|
module.exports = __toCommonJS(request_exports);
|
||||||
|
var import_node_http2 = require("http2");
|
||||||
|
var import_node_stream = require("stream");
|
||||||
|
var RequestError = class extends Error {
|
||||||
|
constructor(message, options) {
|
||||||
|
super(message, options);
|
||||||
|
this.name = "RequestError";
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var toRequestError = (e) => {
|
||||||
|
if (e instanceof RequestError) {
|
||||||
|
return e;
|
||||||
|
}
|
||||||
|
return new RequestError(e.message, { cause: e });
|
||||||
|
};
|
||||||
|
var GlobalRequest = global.Request;
|
||||||
|
var Request = class extends GlobalRequest {
|
||||||
|
constructor(input, options) {
|
||||||
|
if (typeof input === "object" && getRequestCache in input) {
|
||||||
|
input = input[getRequestCache]();
|
||||||
|
}
|
||||||
|
if (typeof options?.body?.getReader !== "undefined") {
|
||||||
|
;
|
||||||
|
options.duplex ??= "half";
|
||||||
|
}
|
||||||
|
super(input, options);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var newHeadersFromIncoming = (incoming) => {
|
||||||
|
const headerRecord = [];
|
||||||
|
const rawHeaders = incoming.rawHeaders;
|
||||||
|
for (let i = 0; i < rawHeaders.length; i += 2) {
|
||||||
|
const { [i]: key, [i + 1]: value } = rawHeaders;
|
||||||
|
if (key.charCodeAt(0) !== /*:*/
|
||||||
|
58) {
|
||||||
|
headerRecord.push([key, value]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new Headers(headerRecord);
|
||||||
|
};
|
||||||
|
var wrapBodyStream = Symbol("wrapBodyStream");
|
||||||
|
var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
|
||||||
|
const init = {
|
||||||
|
method,
|
||||||
|
headers,
|
||||||
|
signal: abortController.signal
|
||||||
|
};
|
||||||
|
if (method === "TRACE") {
|
||||||
|
init.method = "GET";
|
||||||
|
const req = new Request(url, init);
|
||||||
|
Object.defineProperty(req, "method", {
|
||||||
|
get() {
|
||||||
|
return "TRACE";
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return req;
|
||||||
|
}
|
||||||
|
if (!(method === "GET" || method === "HEAD")) {
|
||||||
|
if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
|
||||||
|
init.body = new ReadableStream({
|
||||||
|
start(controller) {
|
||||||
|
controller.enqueue(incoming.rawBody);
|
||||||
|
controller.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else if (incoming[wrapBodyStream]) {
|
||||||
|
let reader;
|
||||||
|
init.body = new ReadableStream({
|
||||||
|
async pull(controller) {
|
||||||
|
try {
|
||||||
|
reader ||= import_node_stream.Readable.toWeb(incoming).getReader();
|
||||||
|
const { done, value } = await reader.read();
|
||||||
|
if (done) {
|
||||||
|
controller.close();
|
||||||
|
} else {
|
||||||
|
controller.enqueue(value);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
controller.error(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
init.body = import_node_stream.Readable.toWeb(incoming);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new Request(url, init);
|
||||||
|
};
|
||||||
|
var getRequestCache = Symbol("getRequestCache");
|
||||||
|
var requestCache = Symbol("requestCache");
|
||||||
|
var incomingKey = Symbol("incomingKey");
|
||||||
|
var urlKey = Symbol("urlKey");
|
||||||
|
var headersKey = Symbol("headersKey");
|
||||||
|
var abortControllerKey = Symbol("abortControllerKey");
|
||||||
|
var getAbortController = Symbol("getAbortController");
|
||||||
|
var requestPrototype = {
|
||||||
|
get method() {
|
||||||
|
return this[incomingKey].method || "GET";
|
||||||
|
},
|
||||||
|
get url() {
|
||||||
|
return this[urlKey];
|
||||||
|
},
|
||||||
|
get headers() {
|
||||||
|
return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
|
||||||
|
},
|
||||||
|
[getAbortController]() {
|
||||||
|
this[getRequestCache]();
|
||||||
|
return this[abortControllerKey];
|
||||||
|
},
|
||||||
|
[getRequestCache]() {
|
||||||
|
this[abortControllerKey] ||= new AbortController();
|
||||||
|
return this[requestCache] ||= newRequestFromIncoming(
|
||||||
|
this.method,
|
||||||
|
this[urlKey],
|
||||||
|
this.headers,
|
||||||
|
this[incomingKey],
|
||||||
|
this[abortControllerKey]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
[
|
||||||
|
"body",
|
||||||
|
"bodyUsed",
|
||||||
|
"cache",
|
||||||
|
"credentials",
|
||||||
|
"destination",
|
||||||
|
"integrity",
|
||||||
|
"mode",
|
||||||
|
"redirect",
|
||||||
|
"referrer",
|
||||||
|
"referrerPolicy",
|
||||||
|
"signal",
|
||||||
|
"keepalive"
|
||||||
|
].forEach((k) => {
|
||||||
|
Object.defineProperty(requestPrototype, k, {
|
||||||
|
get() {
|
||||||
|
return this[getRequestCache]()[k];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
|
||||||
|
Object.defineProperty(requestPrototype, k, {
|
||||||
|
value: function() {
|
||||||
|
return this[getRequestCache]()[k]();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), {
|
||||||
|
value: function(depth, options, inspectFn) {
|
||||||
|
const props = {
|
||||||
|
method: this.method,
|
||||||
|
url: this.url,
|
||||||
|
headers: this.headers,
|
||||||
|
nativeRequest: this[requestCache]
|
||||||
|
};
|
||||||
|
return `Request (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Object.setPrototypeOf(requestPrototype, Request.prototype);
|
||||||
|
var newRequest = (incoming, defaultHostname) => {
|
||||||
|
const req = Object.create(requestPrototype);
|
||||||
|
req[incomingKey] = incoming;
|
||||||
|
const incomingUrl = incoming.url || "";
|
||||||
|
if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
|
||||||
|
(incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
|
||||||
|
if (incoming instanceof import_node_http2.Http2ServerRequest) {
|
||||||
|
throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const url2 = new URL(incomingUrl);
|
||||||
|
req[urlKey] = url2.href;
|
||||||
|
} catch (e) {
|
||||||
|
throw new RequestError("Invalid absolute URL", { cause: e });
|
||||||
|
}
|
||||||
|
return req;
|
||||||
|
}
|
||||||
|
const host = (incoming instanceof import_node_http2.Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
|
||||||
|
if (!host) {
|
||||||
|
throw new RequestError("Missing host header");
|
||||||
|
}
|
||||||
|
let scheme;
|
||||||
|
if (incoming instanceof import_node_http2.Http2ServerRequest) {
|
||||||
|
scheme = incoming.scheme;
|
||||||
|
if (!(scheme === "http" || scheme === "https")) {
|
||||||
|
throw new RequestError("Unsupported scheme");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
|
||||||
|
}
|
||||||
|
const url = new URL(`${scheme}://${host}${incomingUrl}`);
|
||||||
|
if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
|
||||||
|
throw new RequestError("Invalid host header");
|
||||||
|
}
|
||||||
|
req[urlKey] = url.href;
|
||||||
|
return req;
|
||||||
|
};
|
||||||
|
// Annotate the CommonJS export names for ESM import in node:
|
||||||
|
0 && (module.exports = {
|
||||||
|
GlobalRequest,
|
||||||
|
Request,
|
||||||
|
RequestError,
|
||||||
|
abortControllerKey,
|
||||||
|
getAbortController,
|
||||||
|
newRequest,
|
||||||
|
toRequestError,
|
||||||
|
wrapBodyStream
|
||||||
|
});
|
||||||
206
node_modules/@hono/node-server/dist/request.mjs
generated
vendored
Normal file
206
node_modules/@hono/node-server/dist/request.mjs
generated
vendored
Normal file
@@ -0,0 +1,206 @@
|
|||||||
|
// src/request.ts
|
||||||
|
import { Http2ServerRequest } from "http2";
|
||||||
|
import { Readable } from "stream";
|
||||||
|
var RequestError = class extends Error {
|
||||||
|
constructor(message, options) {
|
||||||
|
super(message, options);
|
||||||
|
this.name = "RequestError";
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var toRequestError = (e) => {
|
||||||
|
if (e instanceof RequestError) {
|
||||||
|
return e;
|
||||||
|
}
|
||||||
|
return new RequestError(e.message, { cause: e });
|
||||||
|
};
|
||||||
|
var GlobalRequest = global.Request;
|
||||||
|
var Request = class extends GlobalRequest {
|
||||||
|
constructor(input, options) {
|
||||||
|
if (typeof input === "object" && getRequestCache in input) {
|
||||||
|
input = input[getRequestCache]();
|
||||||
|
}
|
||||||
|
if (typeof options?.body?.getReader !== "undefined") {
|
||||||
|
;
|
||||||
|
options.duplex ??= "half";
|
||||||
|
}
|
||||||
|
super(input, options);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var newHeadersFromIncoming = (incoming) => {
|
||||||
|
const headerRecord = [];
|
||||||
|
const rawHeaders = incoming.rawHeaders;
|
||||||
|
for (let i = 0; i < rawHeaders.length; i += 2) {
|
||||||
|
const { [i]: key, [i + 1]: value } = rawHeaders;
|
||||||
|
if (key.charCodeAt(0) !== /*:*/
|
||||||
|
58) {
|
||||||
|
headerRecord.push([key, value]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new Headers(headerRecord);
|
||||||
|
};
|
||||||
|
var wrapBodyStream = Symbol("wrapBodyStream");
|
||||||
|
var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
|
||||||
|
const init = {
|
||||||
|
method,
|
||||||
|
headers,
|
||||||
|
signal: abortController.signal
|
||||||
|
};
|
||||||
|
if (method === "TRACE") {
|
||||||
|
init.method = "GET";
|
||||||
|
const req = new Request(url, init);
|
||||||
|
Object.defineProperty(req, "method", {
|
||||||
|
get() {
|
||||||
|
return "TRACE";
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return req;
|
||||||
|
}
|
||||||
|
if (!(method === "GET" || method === "HEAD")) {
|
||||||
|
if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
|
||||||
|
init.body = new ReadableStream({
|
||||||
|
start(controller) {
|
||||||
|
controller.enqueue(incoming.rawBody);
|
||||||
|
controller.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else if (incoming[wrapBodyStream]) {
|
||||||
|
let reader;
|
||||||
|
init.body = new ReadableStream({
|
||||||
|
async pull(controller) {
|
||||||
|
try {
|
||||||
|
reader ||= Readable.toWeb(incoming).getReader();
|
||||||
|
const { done, value } = await reader.read();
|
||||||
|
if (done) {
|
||||||
|
controller.close();
|
||||||
|
} else {
|
||||||
|
controller.enqueue(value);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
controller.error(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
init.body = Readable.toWeb(incoming);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new Request(url, init);
|
||||||
|
};
|
||||||
|
var getRequestCache = Symbol("getRequestCache");
|
||||||
|
var requestCache = Symbol("requestCache");
|
||||||
|
var incomingKey = Symbol("incomingKey");
|
||||||
|
var urlKey = Symbol("urlKey");
|
||||||
|
var headersKey = Symbol("headersKey");
|
||||||
|
var abortControllerKey = Symbol("abortControllerKey");
|
||||||
|
var getAbortController = Symbol("getAbortController");
|
||||||
|
var requestPrototype = {
|
||||||
|
get method() {
|
||||||
|
return this[incomingKey].method || "GET";
|
||||||
|
},
|
||||||
|
get url() {
|
||||||
|
return this[urlKey];
|
||||||
|
},
|
||||||
|
get headers() {
|
||||||
|
return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
|
||||||
|
},
|
||||||
|
[getAbortController]() {
|
||||||
|
this[getRequestCache]();
|
||||||
|
return this[abortControllerKey];
|
||||||
|
},
|
||||||
|
[getRequestCache]() {
|
||||||
|
this[abortControllerKey] ||= new AbortController();
|
||||||
|
return this[requestCache] ||= newRequestFromIncoming(
|
||||||
|
this.method,
|
||||||
|
this[urlKey],
|
||||||
|
this.headers,
|
||||||
|
this[incomingKey],
|
||||||
|
this[abortControllerKey]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
[
|
||||||
|
"body",
|
||||||
|
"bodyUsed",
|
||||||
|
"cache",
|
||||||
|
"credentials",
|
||||||
|
"destination",
|
||||||
|
"integrity",
|
||||||
|
"mode",
|
||||||
|
"redirect",
|
||||||
|
"referrer",
|
||||||
|
"referrerPolicy",
|
||||||
|
"signal",
|
||||||
|
"keepalive"
|
||||||
|
].forEach((k) => {
|
||||||
|
Object.defineProperty(requestPrototype, k, {
|
||||||
|
get() {
|
||||||
|
return this[getRequestCache]()[k];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
|
||||||
|
Object.defineProperty(requestPrototype, k, {
|
||||||
|
value: function() {
|
||||||
|
return this[getRequestCache]()[k]();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), {
|
||||||
|
value: function(depth, options, inspectFn) {
|
||||||
|
const props = {
|
||||||
|
method: this.method,
|
||||||
|
url: this.url,
|
||||||
|
headers: this.headers,
|
||||||
|
nativeRequest: this[requestCache]
|
||||||
|
};
|
||||||
|
return `Request (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Object.setPrototypeOf(requestPrototype, Request.prototype);
|
||||||
|
var newRequest = (incoming, defaultHostname) => {
|
||||||
|
const req = Object.create(requestPrototype);
|
||||||
|
req[incomingKey] = incoming;
|
||||||
|
const incomingUrl = incoming.url || "";
|
||||||
|
if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
|
||||||
|
(incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
|
||||||
|
if (incoming instanceof Http2ServerRequest) {
|
||||||
|
throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const url2 = new URL(incomingUrl);
|
||||||
|
req[urlKey] = url2.href;
|
||||||
|
} catch (e) {
|
||||||
|
throw new RequestError("Invalid absolute URL", { cause: e });
|
||||||
|
}
|
||||||
|
return req;
|
||||||
|
}
|
||||||
|
const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
|
||||||
|
if (!host) {
|
||||||
|
throw new RequestError("Missing host header");
|
||||||
|
}
|
||||||
|
let scheme;
|
||||||
|
if (incoming instanceof Http2ServerRequest) {
|
||||||
|
scheme = incoming.scheme;
|
||||||
|
if (!(scheme === "http" || scheme === "https")) {
|
||||||
|
throw new RequestError("Unsupported scheme");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
|
||||||
|
}
|
||||||
|
const url = new URL(`${scheme}://${host}${incomingUrl}`);
|
||||||
|
if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
|
||||||
|
throw new RequestError("Invalid host header");
|
||||||
|
}
|
||||||
|
req[urlKey] = url.href;
|
||||||
|
return req;
|
||||||
|
};
|
||||||
|
export {
|
||||||
|
GlobalRequest,
|
||||||
|
Request,
|
||||||
|
RequestError,
|
||||||
|
abortControllerKey,
|
||||||
|
getAbortController,
|
||||||
|
newRequest,
|
||||||
|
toRequestError,
|
||||||
|
wrapBodyStream
|
||||||
|
};
|
||||||
26
node_modules/@hono/node-server/dist/response.d.mts
generated
vendored
Normal file
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> | [string, string][] | Headers | OutgoingHttpHeaders | undefined
|
||||||
|
];
|
||||||
|
declare const GlobalResponse: {
|
||||||
|
new (body?: BodyInit | null, init?: ResponseInit): globalThis.Response;
|
||||||
|
prototype: globalThis.Response;
|
||||||
|
error(): globalThis.Response;
|
||||||
|
json(data: any, init?: ResponseInit): globalThis.Response;
|
||||||
|
redirect(url: string | URL, status?: number): globalThis.Response;
|
||||||
|
};
|
||||||
|
declare class Response {
|
||||||
|
#private;
|
||||||
|
[getResponseCache](): globalThis.Response;
|
||||||
|
constructor(body?: BodyInit | null, init?: ResponseInit);
|
||||||
|
get headers(): Headers;
|
||||||
|
get status(): number;
|
||||||
|
get ok(): boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export { GlobalResponse, type InternalCache, Response, cacheKey };
|
||||||
26
node_modules/@hono/node-server/dist/response.d.ts
generated
vendored
Normal file
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> | [string, string][] | Headers | OutgoingHttpHeaders | undefined
|
||||||
|
];
|
||||||
|
declare const GlobalResponse: {
|
||||||
|
new (body?: BodyInit | null, init?: ResponseInit): globalThis.Response;
|
||||||
|
prototype: globalThis.Response;
|
||||||
|
error(): globalThis.Response;
|
||||||
|
json(data: any, init?: ResponseInit): globalThis.Response;
|
||||||
|
redirect(url: string | URL, status?: number): globalThis.Response;
|
||||||
|
};
|
||||||
|
declare class Response {
|
||||||
|
#private;
|
||||||
|
[getResponseCache](): globalThis.Response;
|
||||||
|
constructor(body?: BodyInit | null, init?: ResponseInit);
|
||||||
|
get headers(): Headers;
|
||||||
|
get status(): number;
|
||||||
|
get ok(): boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export { GlobalResponse, type InternalCache, Response, cacheKey };
|
||||||
112
node_modules/@hono/node-server/dist/response.js
generated
vendored
Normal file
112
node_modules/@hono/node-server/dist/response.js
generated
vendored
Normal file
@@ -0,0 +1,112 @@
|
|||||||
|
"use strict";
|
||||||
|
var __defProp = Object.defineProperty;
|
||||||
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||||
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||||
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||||
|
var __export = (target, all) => {
|
||||||
|
for (var name in all)
|
||||||
|
__defProp(target, name, { get: all[name], enumerable: true });
|
||||||
|
};
|
||||||
|
var __copyProps = (to, from, except, desc) => {
|
||||||
|
if (from && typeof from === "object" || typeof from === "function") {
|
||||||
|
for (let key of __getOwnPropNames(from))
|
||||||
|
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||||
|
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||||
|
}
|
||||||
|
return to;
|
||||||
|
};
|
||||||
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||||
|
|
||||||
|
// src/response.ts
|
||||||
|
var response_exports = {};
|
||||||
|
__export(response_exports, {
|
||||||
|
GlobalResponse: () => GlobalResponse,
|
||||||
|
Response: () => Response,
|
||||||
|
cacheKey: () => cacheKey
|
||||||
|
});
|
||||||
|
module.exports = __toCommonJS(response_exports);
|
||||||
|
var responseCache = Symbol("responseCache");
|
||||||
|
var getResponseCache = Symbol("getResponseCache");
|
||||||
|
var cacheKey = Symbol("cache");
|
||||||
|
var GlobalResponse = global.Response;
|
||||||
|
var Response = class _Response {
|
||||||
|
#body;
|
||||||
|
#init;
|
||||||
|
[getResponseCache]() {
|
||||||
|
delete this[cacheKey];
|
||||||
|
return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
|
||||||
|
}
|
||||||
|
constructor(body, init) {
|
||||||
|
let headers;
|
||||||
|
this.#body = body;
|
||||||
|
if (init instanceof _Response) {
|
||||||
|
const cachedGlobalResponse = init[responseCache];
|
||||||
|
if (cachedGlobalResponse) {
|
||||||
|
this.#init = cachedGlobalResponse;
|
||||||
|
this[getResponseCache]();
|
||||||
|
return;
|
||||||
|
} else {
|
||||||
|
this.#init = init.#init;
|
||||||
|
headers = new Headers(init.#init.headers);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
this.#init = init;
|
||||||
|
}
|
||||||
|
if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
|
||||||
|
;
|
||||||
|
this[cacheKey] = [init?.status || 200, body, headers || init?.headers];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
get headers() {
|
||||||
|
const cache = this[cacheKey];
|
||||||
|
if (cache) {
|
||||||
|
if (!(cache[2] instanceof Headers)) {
|
||||||
|
cache[2] = new Headers(
|
||||||
|
cache[2] || { "content-type": "text/plain; charset=UTF-8" }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return cache[2];
|
||||||
|
}
|
||||||
|
return this[getResponseCache]().headers;
|
||||||
|
}
|
||||||
|
get status() {
|
||||||
|
return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
|
||||||
|
}
|
||||||
|
get ok() {
|
||||||
|
const status = this.status;
|
||||||
|
return status >= 200 && status < 300;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
|
||||||
|
Object.defineProperty(Response.prototype, k, {
|
||||||
|
get() {
|
||||||
|
return this[getResponseCache]()[k];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
|
||||||
|
Object.defineProperty(Response.prototype, k, {
|
||||||
|
value: function() {
|
||||||
|
return this[getResponseCache]()[k]();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
Object.defineProperty(Response.prototype, Symbol.for("nodejs.util.inspect.custom"), {
|
||||||
|
value: function(depth, options, inspectFn) {
|
||||||
|
const props = {
|
||||||
|
status: this.status,
|
||||||
|
headers: this.headers,
|
||||||
|
ok: this.ok,
|
||||||
|
nativeResponse: this[responseCache]
|
||||||
|
};
|
||||||
|
return `Response (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Object.setPrototypeOf(Response, GlobalResponse);
|
||||||
|
Object.setPrototypeOf(Response.prototype, GlobalResponse.prototype);
|
||||||
|
// Annotate the CommonJS export names for ESM import in node:
|
||||||
|
0 && (module.exports = {
|
||||||
|
GlobalResponse,
|
||||||
|
Response,
|
||||||
|
cacheKey
|
||||||
|
});
|
||||||
85
node_modules/@hono/node-server/dist/response.mjs
generated
vendored
Normal file
85
node_modules/@hono/node-server/dist/response.mjs
generated
vendored
Normal file
@@ -0,0 +1,85 @@
|
|||||||
|
// src/response.ts
|
||||||
|
var responseCache = Symbol("responseCache");
|
||||||
|
var getResponseCache = Symbol("getResponseCache");
|
||||||
|
var cacheKey = Symbol("cache");
|
||||||
|
var GlobalResponse = global.Response;
|
||||||
|
var Response = class _Response {
|
||||||
|
#body;
|
||||||
|
#init;
|
||||||
|
[getResponseCache]() {
|
||||||
|
delete this[cacheKey];
|
||||||
|
return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
|
||||||
|
}
|
||||||
|
constructor(body, init) {
|
||||||
|
let headers;
|
||||||
|
this.#body = body;
|
||||||
|
if (init instanceof _Response) {
|
||||||
|
const cachedGlobalResponse = init[responseCache];
|
||||||
|
if (cachedGlobalResponse) {
|
||||||
|
this.#init = cachedGlobalResponse;
|
||||||
|
this[getResponseCache]();
|
||||||
|
return;
|
||||||
|
} else {
|
||||||
|
this.#init = init.#init;
|
||||||
|
headers = new Headers(init.#init.headers);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
this.#init = init;
|
||||||
|
}
|
||||||
|
if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
|
||||||
|
;
|
||||||
|
this[cacheKey] = [init?.status || 200, body, headers || init?.headers];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
get headers() {
|
||||||
|
const cache = this[cacheKey];
|
||||||
|
if (cache) {
|
||||||
|
if (!(cache[2] instanceof Headers)) {
|
||||||
|
cache[2] = new Headers(
|
||||||
|
cache[2] || { "content-type": "text/plain; charset=UTF-8" }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return cache[2];
|
||||||
|
}
|
||||||
|
return this[getResponseCache]().headers;
|
||||||
|
}
|
||||||
|
get status() {
|
||||||
|
return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
|
||||||
|
}
|
||||||
|
get ok() {
|
||||||
|
const status = this.status;
|
||||||
|
return status >= 200 && status < 300;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
|
||||||
|
Object.defineProperty(Response.prototype, k, {
|
||||||
|
get() {
|
||||||
|
return this[getResponseCache]()[k];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
|
||||||
|
Object.defineProperty(Response.prototype, k, {
|
||||||
|
value: function() {
|
||||||
|
return this[getResponseCache]()[k]();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
Object.defineProperty(Response.prototype, Symbol.for("nodejs.util.inspect.custom"), {
|
||||||
|
value: function(depth, options, inspectFn) {
|
||||||
|
const props = {
|
||||||
|
status: this.status,
|
||||||
|
headers: this.headers,
|
||||||
|
ok: this.ok,
|
||||||
|
nativeResponse: this[responseCache]
|
||||||
|
};
|
||||||
|
return `Response (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Object.setPrototypeOf(Response, GlobalResponse);
|
||||||
|
Object.setPrototypeOf(Response.prototype, GlobalResponse.prototype);
|
||||||
|
export {
|
||||||
|
GlobalResponse,
|
||||||
|
Response,
|
||||||
|
cacheKey
|
||||||
|
};
|
||||||
17
node_modules/@hono/node-server/dist/serve-static.d.mts
generated
vendored
Normal file
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 { type 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 { type ServeStaticOptions, serveStatic };
|
||||||
177
node_modules/@hono/node-server/dist/serve-static.js
generated
vendored
Normal file
177
node_modules/@hono/node-server/dist/serve-static.js
generated
vendored
Normal file
@@ -0,0 +1,177 @@
|
|||||||
|
"use strict";
|
||||||
|
var __defProp = Object.defineProperty;
|
||||||
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||||
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||||
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||||
|
var __export = (target, all) => {
|
||||||
|
for (var name in all)
|
||||||
|
__defProp(target, name, { get: all[name], enumerable: true });
|
||||||
|
};
|
||||||
|
var __copyProps = (to, from, except, desc) => {
|
||||||
|
if (from && typeof from === "object" || typeof from === "function") {
|
||||||
|
for (let key of __getOwnPropNames(from))
|
||||||
|
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||||
|
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||||
|
}
|
||||||
|
return to;
|
||||||
|
};
|
||||||
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||||
|
|
||||||
|
// src/serve-static.ts
|
||||||
|
var serve_static_exports = {};
|
||||||
|
__export(serve_static_exports, {
|
||||||
|
serveStatic: () => serveStatic
|
||||||
|
});
|
||||||
|
module.exports = __toCommonJS(serve_static_exports);
|
||||||
|
var import_mime = require("hono/utils/mime");
|
||||||
|
var import_node_fs = require("fs");
|
||||||
|
var import_node_path = require("path");
|
||||||
|
var import_node_process = require("process");
|
||||||
|
var import_node_stream = require("stream");
|
||||||
|
var COMPRESSIBLE_CONTENT_TYPE_REGEX = /^\s*(?:text\/[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i;
|
||||||
|
var ENCODINGS = {
|
||||||
|
br: ".br",
|
||||||
|
zstd: ".zst",
|
||||||
|
gzip: ".gz"
|
||||||
|
};
|
||||||
|
var ENCODINGS_ORDERED_KEYS = Object.keys(ENCODINGS);
|
||||||
|
var pr54206Applied = () => {
|
||||||
|
const [major, minor] = import_node_process.versions.node.split(".").map((component) => parseInt(component));
|
||||||
|
return major >= 23 || major === 22 && minor >= 7 || major === 20 && minor >= 18;
|
||||||
|
};
|
||||||
|
var useReadableToWeb = pr54206Applied();
|
||||||
|
var createStreamBody = (stream) => {
|
||||||
|
if (useReadableToWeb) {
|
||||||
|
return import_node_stream.Readable.toWeb(stream);
|
||||||
|
}
|
||||||
|
const body = new ReadableStream({
|
||||||
|
start(controller) {
|
||||||
|
stream.on("data", (chunk) => {
|
||||||
|
controller.enqueue(chunk);
|
||||||
|
});
|
||||||
|
stream.on("error", (err) => {
|
||||||
|
controller.error(err);
|
||||||
|
});
|
||||||
|
stream.on("end", () => {
|
||||||
|
controller.close();
|
||||||
|
});
|
||||||
|
},
|
||||||
|
cancel() {
|
||||||
|
stream.destroy();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return body;
|
||||||
|
};
|
||||||
|
var getStats = (path) => {
|
||||||
|
let stats;
|
||||||
|
try {
|
||||||
|
stats = (0, import_node_fs.statSync)(path);
|
||||||
|
} catch {
|
||||||
|
}
|
||||||
|
return stats;
|
||||||
|
};
|
||||||
|
var tryDecode = (str, decoder) => {
|
||||||
|
try {
|
||||||
|
return decoder(str);
|
||||||
|
} catch {
|
||||||
|
return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {
|
||||||
|
try {
|
||||||
|
return decoder(match);
|
||||||
|
} catch {
|
||||||
|
return match;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var tryDecodeURI = (str) => tryDecode(str, decodeURI);
|
||||||
|
var serveStatic = (options = { root: "" }) => {
|
||||||
|
const root = options.root || "";
|
||||||
|
const optionPath = options.path;
|
||||||
|
if (root !== "" && !(0, import_node_fs.existsSync)(root)) {
|
||||||
|
console.error(`serveStatic: root path '${root}' is not found, are you sure it's correct?`);
|
||||||
|
}
|
||||||
|
return async (c, next) => {
|
||||||
|
if (c.finalized) {
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
let filename;
|
||||||
|
if (optionPath) {
|
||||||
|
filename = optionPath;
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
filename = tryDecodeURI(c.req.path);
|
||||||
|
if (/(?:^|[\/\\])\.{1,2}(?:$|[\/\\])|[\/\\]{2,}/.test(filename)) {
|
||||||
|
throw new Error();
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
await options.onNotFound?.(c.req.path, c);
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let path = (0, import_node_path.join)(
|
||||||
|
root,
|
||||||
|
!optionPath && options.rewriteRequestPath ? options.rewriteRequestPath(filename, c) : filename
|
||||||
|
);
|
||||||
|
let stats = getStats(path);
|
||||||
|
if (stats && stats.isDirectory()) {
|
||||||
|
const indexFile = options.index ?? "index.html";
|
||||||
|
path = (0, import_node_path.join)(path, indexFile);
|
||||||
|
stats = getStats(path);
|
||||||
|
}
|
||||||
|
if (!stats) {
|
||||||
|
await options.onNotFound?.(path, c);
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
const mimeType = (0, import_mime.getMimeType)(path);
|
||||||
|
c.header("Content-Type", mimeType || "application/octet-stream");
|
||||||
|
if (options.precompressed && (!mimeType || COMPRESSIBLE_CONTENT_TYPE_REGEX.test(mimeType))) {
|
||||||
|
const acceptEncodingSet = new Set(
|
||||||
|
c.req.header("Accept-Encoding")?.split(",").map((encoding) => encoding.trim())
|
||||||
|
);
|
||||||
|
for (const encoding of ENCODINGS_ORDERED_KEYS) {
|
||||||
|
if (!acceptEncodingSet.has(encoding)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const precompressedStats = getStats(path + ENCODINGS[encoding]);
|
||||||
|
if (precompressedStats) {
|
||||||
|
c.header("Content-Encoding", encoding);
|
||||||
|
c.header("Vary", "Accept-Encoding", { append: true });
|
||||||
|
stats = precompressedStats;
|
||||||
|
path = path + ENCODINGS[encoding];
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let result;
|
||||||
|
const size = stats.size;
|
||||||
|
const range = c.req.header("range") || "";
|
||||||
|
if (c.req.method == "HEAD" || c.req.method == "OPTIONS") {
|
||||||
|
c.header("Content-Length", size.toString());
|
||||||
|
c.status(200);
|
||||||
|
result = c.body(null);
|
||||||
|
} else if (!range) {
|
||||||
|
c.header("Content-Length", size.toString());
|
||||||
|
result = c.body(createStreamBody((0, import_node_fs.createReadStream)(path)), 200);
|
||||||
|
} else {
|
||||||
|
c.header("Accept-Ranges", "bytes");
|
||||||
|
c.header("Date", stats.birthtime.toUTCString());
|
||||||
|
const parts = range.replace(/bytes=/, "").split("-", 2);
|
||||||
|
const start = parseInt(parts[0], 10) || 0;
|
||||||
|
let end = parseInt(parts[1], 10) || size - 1;
|
||||||
|
if (size < end - start + 1) {
|
||||||
|
end = size - 1;
|
||||||
|
}
|
||||||
|
const chunksize = end - start + 1;
|
||||||
|
const stream = (0, import_node_fs.createReadStream)(path, { start, end });
|
||||||
|
c.header("Content-Length", chunksize.toString());
|
||||||
|
c.header("Content-Range", `bytes ${start}-${end}/${stats.size}`);
|
||||||
|
result = c.body(createStreamBody(stream), 206);
|
||||||
|
}
|
||||||
|
await options.onFound?.(path, c);
|
||||||
|
return result;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
// Annotate the CommonJS export names for ESM import in node:
|
||||||
|
0 && (module.exports = {
|
||||||
|
serveStatic
|
||||||
|
});
|
||||||
152
node_modules/@hono/node-server/dist/serve-static.mjs
generated
vendored
Normal file
152
node_modules/@hono/node-server/dist/serve-static.mjs
generated
vendored
Normal file
@@ -0,0 +1,152 @@
|
|||||||
|
// src/serve-static.ts
|
||||||
|
import { getMimeType } from "hono/utils/mime";
|
||||||
|
import { createReadStream, statSync, existsSync } from "fs";
|
||||||
|
import { join } from "path";
|
||||||
|
import { versions } from "process";
|
||||||
|
import { Readable } from "stream";
|
||||||
|
var COMPRESSIBLE_CONTENT_TYPE_REGEX = /^\s*(?:text\/[^;\s]+|application\/(?:javascript|json|xml|xml-dtd|ecmascript|dart|postscript|rtf|tar|toml|vnd\.dart|vnd\.ms-fontobject|vnd\.ms-opentype|wasm|x-httpd-php|x-javascript|x-ns-proxy-autoconfig|x-sh|x-tar|x-virtualbox-hdd|x-virtualbox-ova|x-virtualbox-ovf|x-virtualbox-vbox|x-virtualbox-vdi|x-virtualbox-vhd|x-virtualbox-vmdk|x-www-form-urlencoded)|font\/(?:otf|ttf)|image\/(?:bmp|vnd\.adobe\.photoshop|vnd\.microsoft\.icon|vnd\.ms-dds|x-icon|x-ms-bmp)|message\/rfc822|model\/gltf-binary|x-shader\/x-fragment|x-shader\/x-vertex|[^;\s]+?\+(?:json|text|xml|yaml))(?:[;\s]|$)/i;
|
||||||
|
var ENCODINGS = {
|
||||||
|
br: ".br",
|
||||||
|
zstd: ".zst",
|
||||||
|
gzip: ".gz"
|
||||||
|
};
|
||||||
|
var ENCODINGS_ORDERED_KEYS = Object.keys(ENCODINGS);
|
||||||
|
var pr54206Applied = () => {
|
||||||
|
const [major, minor] = versions.node.split(".").map((component) => parseInt(component));
|
||||||
|
return major >= 23 || major === 22 && minor >= 7 || major === 20 && minor >= 18;
|
||||||
|
};
|
||||||
|
var useReadableToWeb = pr54206Applied();
|
||||||
|
var createStreamBody = (stream) => {
|
||||||
|
if (useReadableToWeb) {
|
||||||
|
return Readable.toWeb(stream);
|
||||||
|
}
|
||||||
|
const body = new ReadableStream({
|
||||||
|
start(controller) {
|
||||||
|
stream.on("data", (chunk) => {
|
||||||
|
controller.enqueue(chunk);
|
||||||
|
});
|
||||||
|
stream.on("error", (err) => {
|
||||||
|
controller.error(err);
|
||||||
|
});
|
||||||
|
stream.on("end", () => {
|
||||||
|
controller.close();
|
||||||
|
});
|
||||||
|
},
|
||||||
|
cancel() {
|
||||||
|
stream.destroy();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return body;
|
||||||
|
};
|
||||||
|
var getStats = (path) => {
|
||||||
|
let stats;
|
||||||
|
try {
|
||||||
|
stats = statSync(path);
|
||||||
|
} catch {
|
||||||
|
}
|
||||||
|
return stats;
|
||||||
|
};
|
||||||
|
var tryDecode = (str, decoder) => {
|
||||||
|
try {
|
||||||
|
return decoder(str);
|
||||||
|
} catch {
|
||||||
|
return str.replace(/(?:%[0-9A-Fa-f]{2})+/g, (match) => {
|
||||||
|
try {
|
||||||
|
return decoder(match);
|
||||||
|
} catch {
|
||||||
|
return match;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var tryDecodeURI = (str) => tryDecode(str, decodeURI);
|
||||||
|
var serveStatic = (options = { root: "" }) => {
|
||||||
|
const root = options.root || "";
|
||||||
|
const optionPath = options.path;
|
||||||
|
if (root !== "" && !existsSync(root)) {
|
||||||
|
console.error(`serveStatic: root path '${root}' is not found, are you sure it's correct?`);
|
||||||
|
}
|
||||||
|
return async (c, next) => {
|
||||||
|
if (c.finalized) {
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
let filename;
|
||||||
|
if (optionPath) {
|
||||||
|
filename = optionPath;
|
||||||
|
} else {
|
||||||
|
try {
|
||||||
|
filename = tryDecodeURI(c.req.path);
|
||||||
|
if (/(?:^|[\/\\])\.{1,2}(?:$|[\/\\])|[\/\\]{2,}/.test(filename)) {
|
||||||
|
throw new Error();
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
await options.onNotFound?.(c.req.path, c);
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let path = join(
|
||||||
|
root,
|
||||||
|
!optionPath && options.rewriteRequestPath ? options.rewriteRequestPath(filename, c) : filename
|
||||||
|
);
|
||||||
|
let stats = getStats(path);
|
||||||
|
if (stats && stats.isDirectory()) {
|
||||||
|
const indexFile = options.index ?? "index.html";
|
||||||
|
path = join(path, indexFile);
|
||||||
|
stats = getStats(path);
|
||||||
|
}
|
||||||
|
if (!stats) {
|
||||||
|
await options.onNotFound?.(path, c);
|
||||||
|
return next();
|
||||||
|
}
|
||||||
|
const mimeType = getMimeType(path);
|
||||||
|
c.header("Content-Type", mimeType || "application/octet-stream");
|
||||||
|
if (options.precompressed && (!mimeType || COMPRESSIBLE_CONTENT_TYPE_REGEX.test(mimeType))) {
|
||||||
|
const acceptEncodingSet = new Set(
|
||||||
|
c.req.header("Accept-Encoding")?.split(",").map((encoding) => encoding.trim())
|
||||||
|
);
|
||||||
|
for (const encoding of ENCODINGS_ORDERED_KEYS) {
|
||||||
|
if (!acceptEncodingSet.has(encoding)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const precompressedStats = getStats(path + ENCODINGS[encoding]);
|
||||||
|
if (precompressedStats) {
|
||||||
|
c.header("Content-Encoding", encoding);
|
||||||
|
c.header("Vary", "Accept-Encoding", { append: true });
|
||||||
|
stats = precompressedStats;
|
||||||
|
path = path + ENCODINGS[encoding];
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let result;
|
||||||
|
const size = stats.size;
|
||||||
|
const range = c.req.header("range") || "";
|
||||||
|
if (c.req.method == "HEAD" || c.req.method == "OPTIONS") {
|
||||||
|
c.header("Content-Length", size.toString());
|
||||||
|
c.status(200);
|
||||||
|
result = c.body(null);
|
||||||
|
} else if (!range) {
|
||||||
|
c.header("Content-Length", size.toString());
|
||||||
|
result = c.body(createStreamBody(createReadStream(path)), 200);
|
||||||
|
} else {
|
||||||
|
c.header("Accept-Ranges", "bytes");
|
||||||
|
c.header("Date", stats.birthtime.toUTCString());
|
||||||
|
const parts = range.replace(/bytes=/, "").split("-", 2);
|
||||||
|
const start = parseInt(parts[0], 10) || 0;
|
||||||
|
let end = parseInt(parts[1], 10) || size - 1;
|
||||||
|
if (size < end - start + 1) {
|
||||||
|
end = size - 1;
|
||||||
|
}
|
||||||
|
const chunksize = end - start + 1;
|
||||||
|
const stream = createReadStream(path, { start, end });
|
||||||
|
c.header("Content-Length", chunksize.toString());
|
||||||
|
c.header("Content-Range", `bytes ${start}-${end}/${stats.size}`);
|
||||||
|
result = c.body(createStreamBody(stream), 206);
|
||||||
|
}
|
||||||
|
await options.onFound?.(path, c);
|
||||||
|
return result;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
export {
|
||||||
|
serveStatic
|
||||||
|
};
|
||||||
10
node_modules/@hono/node-server/dist/server.d.mts
generated
vendored
Normal file
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 };
|
||||||
696
node_modules/@hono/node-server/dist/server.js
generated
vendored
Normal file
696
node_modules/@hono/node-server/dist/server.js
generated
vendored
Normal file
@@ -0,0 +1,696 @@
|
|||||||
|
"use strict";
|
||||||
|
var __create = Object.create;
|
||||||
|
var __defProp = Object.defineProperty;
|
||||||
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||||
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||||
|
var __getProtoOf = Object.getPrototypeOf;
|
||||||
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||||
|
var __export = (target, all) => {
|
||||||
|
for (var name in all)
|
||||||
|
__defProp(target, name, { get: all[name], enumerable: true });
|
||||||
|
};
|
||||||
|
var __copyProps = (to, from, except, desc) => {
|
||||||
|
if (from && typeof from === "object" || typeof from === "function") {
|
||||||
|
for (let key of __getOwnPropNames(from))
|
||||||
|
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||||
|
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||||
|
}
|
||||||
|
return to;
|
||||||
|
};
|
||||||
|
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
||||||
|
// If the importer is in node compatibility mode or this is not an ESM
|
||||||
|
// file that has been converted to a CommonJS file using a Babel-
|
||||||
|
// compatible transform (i.e. "__esModule" has not been set), then set
|
||||||
|
// "default" to the CommonJS "module.exports" for node compatibility.
|
||||||
|
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
||||||
|
mod
|
||||||
|
));
|
||||||
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||||
|
|
||||||
|
// src/server.ts
|
||||||
|
var server_exports = {};
|
||||||
|
__export(server_exports, {
|
||||||
|
createAdaptorServer: () => createAdaptorServer,
|
||||||
|
serve: () => serve
|
||||||
|
});
|
||||||
|
module.exports = __toCommonJS(server_exports);
|
||||||
|
var import_node_http = require("http");
|
||||||
|
|
||||||
|
// src/listener.ts
|
||||||
|
var import_node_http22 = require("http2");
|
||||||
|
|
||||||
|
// src/request.ts
|
||||||
|
var import_node_http2 = require("http2");
|
||||||
|
var import_node_stream = require("stream");
|
||||||
|
var RequestError = class extends Error {
|
||||||
|
constructor(message, options) {
|
||||||
|
super(message, options);
|
||||||
|
this.name = "RequestError";
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var toRequestError = (e) => {
|
||||||
|
if (e instanceof RequestError) {
|
||||||
|
return e;
|
||||||
|
}
|
||||||
|
return new RequestError(e.message, { cause: e });
|
||||||
|
};
|
||||||
|
var GlobalRequest = global.Request;
|
||||||
|
var Request = class extends GlobalRequest {
|
||||||
|
constructor(input, options) {
|
||||||
|
if (typeof input === "object" && getRequestCache in input) {
|
||||||
|
input = input[getRequestCache]();
|
||||||
|
}
|
||||||
|
if (typeof options?.body?.getReader !== "undefined") {
|
||||||
|
;
|
||||||
|
options.duplex ??= "half";
|
||||||
|
}
|
||||||
|
super(input, options);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var newHeadersFromIncoming = (incoming) => {
|
||||||
|
const headerRecord = [];
|
||||||
|
const rawHeaders = incoming.rawHeaders;
|
||||||
|
for (let i = 0; i < rawHeaders.length; i += 2) {
|
||||||
|
const { [i]: key, [i + 1]: value } = rawHeaders;
|
||||||
|
if (key.charCodeAt(0) !== /*:*/
|
||||||
|
58) {
|
||||||
|
headerRecord.push([key, value]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new Headers(headerRecord);
|
||||||
|
};
|
||||||
|
var wrapBodyStream = Symbol("wrapBodyStream");
|
||||||
|
var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
|
||||||
|
const init = {
|
||||||
|
method,
|
||||||
|
headers,
|
||||||
|
signal: abortController.signal
|
||||||
|
};
|
||||||
|
if (method === "TRACE") {
|
||||||
|
init.method = "GET";
|
||||||
|
const req = new Request(url, init);
|
||||||
|
Object.defineProperty(req, "method", {
|
||||||
|
get() {
|
||||||
|
return "TRACE";
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return req;
|
||||||
|
}
|
||||||
|
if (!(method === "GET" || method === "HEAD")) {
|
||||||
|
if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
|
||||||
|
init.body = new ReadableStream({
|
||||||
|
start(controller) {
|
||||||
|
controller.enqueue(incoming.rawBody);
|
||||||
|
controller.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else if (incoming[wrapBodyStream]) {
|
||||||
|
let reader;
|
||||||
|
init.body = new ReadableStream({
|
||||||
|
async pull(controller) {
|
||||||
|
try {
|
||||||
|
reader ||= import_node_stream.Readable.toWeb(incoming).getReader();
|
||||||
|
const { done, value } = await reader.read();
|
||||||
|
if (done) {
|
||||||
|
controller.close();
|
||||||
|
} else {
|
||||||
|
controller.enqueue(value);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
controller.error(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
init.body = import_node_stream.Readable.toWeb(incoming);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new Request(url, init);
|
||||||
|
};
|
||||||
|
var getRequestCache = Symbol("getRequestCache");
|
||||||
|
var requestCache = Symbol("requestCache");
|
||||||
|
var incomingKey = Symbol("incomingKey");
|
||||||
|
var urlKey = Symbol("urlKey");
|
||||||
|
var headersKey = Symbol("headersKey");
|
||||||
|
var abortControllerKey = Symbol("abortControllerKey");
|
||||||
|
var getAbortController = Symbol("getAbortController");
|
||||||
|
var requestPrototype = {
|
||||||
|
get method() {
|
||||||
|
return this[incomingKey].method || "GET";
|
||||||
|
},
|
||||||
|
get url() {
|
||||||
|
return this[urlKey];
|
||||||
|
},
|
||||||
|
get headers() {
|
||||||
|
return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
|
||||||
|
},
|
||||||
|
[getAbortController]() {
|
||||||
|
this[getRequestCache]();
|
||||||
|
return this[abortControllerKey];
|
||||||
|
},
|
||||||
|
[getRequestCache]() {
|
||||||
|
this[abortControllerKey] ||= new AbortController();
|
||||||
|
return this[requestCache] ||= newRequestFromIncoming(
|
||||||
|
this.method,
|
||||||
|
this[urlKey],
|
||||||
|
this.headers,
|
||||||
|
this[incomingKey],
|
||||||
|
this[abortControllerKey]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
[
|
||||||
|
"body",
|
||||||
|
"bodyUsed",
|
||||||
|
"cache",
|
||||||
|
"credentials",
|
||||||
|
"destination",
|
||||||
|
"integrity",
|
||||||
|
"mode",
|
||||||
|
"redirect",
|
||||||
|
"referrer",
|
||||||
|
"referrerPolicy",
|
||||||
|
"signal",
|
||||||
|
"keepalive"
|
||||||
|
].forEach((k) => {
|
||||||
|
Object.defineProperty(requestPrototype, k, {
|
||||||
|
get() {
|
||||||
|
return this[getRequestCache]()[k];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
|
||||||
|
Object.defineProperty(requestPrototype, k, {
|
||||||
|
value: function() {
|
||||||
|
return this[getRequestCache]()[k]();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), {
|
||||||
|
value: function(depth, options, inspectFn) {
|
||||||
|
const props = {
|
||||||
|
method: this.method,
|
||||||
|
url: this.url,
|
||||||
|
headers: this.headers,
|
||||||
|
nativeRequest: this[requestCache]
|
||||||
|
};
|
||||||
|
return `Request (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Object.setPrototypeOf(requestPrototype, Request.prototype);
|
||||||
|
var newRequest = (incoming, defaultHostname) => {
|
||||||
|
const req = Object.create(requestPrototype);
|
||||||
|
req[incomingKey] = incoming;
|
||||||
|
const incomingUrl = incoming.url || "";
|
||||||
|
if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
|
||||||
|
(incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
|
||||||
|
if (incoming instanceof import_node_http2.Http2ServerRequest) {
|
||||||
|
throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const url2 = new URL(incomingUrl);
|
||||||
|
req[urlKey] = url2.href;
|
||||||
|
} catch (e) {
|
||||||
|
throw new RequestError("Invalid absolute URL", { cause: e });
|
||||||
|
}
|
||||||
|
return req;
|
||||||
|
}
|
||||||
|
const host = (incoming instanceof import_node_http2.Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
|
||||||
|
if (!host) {
|
||||||
|
throw new RequestError("Missing host header");
|
||||||
|
}
|
||||||
|
let scheme;
|
||||||
|
if (incoming instanceof import_node_http2.Http2ServerRequest) {
|
||||||
|
scheme = incoming.scheme;
|
||||||
|
if (!(scheme === "http" || scheme === "https")) {
|
||||||
|
throw new RequestError("Unsupported scheme");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
|
||||||
|
}
|
||||||
|
const url = new URL(`${scheme}://${host}${incomingUrl}`);
|
||||||
|
if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
|
||||||
|
throw new RequestError("Invalid host header");
|
||||||
|
}
|
||||||
|
req[urlKey] = url.href;
|
||||||
|
return req;
|
||||||
|
};
|
||||||
|
|
||||||
|
// src/response.ts
|
||||||
|
var responseCache = Symbol("responseCache");
|
||||||
|
var getResponseCache = Symbol("getResponseCache");
|
||||||
|
var cacheKey = Symbol("cache");
|
||||||
|
var GlobalResponse = global.Response;
|
||||||
|
var Response2 = class _Response {
|
||||||
|
#body;
|
||||||
|
#init;
|
||||||
|
[getResponseCache]() {
|
||||||
|
delete this[cacheKey];
|
||||||
|
return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
|
||||||
|
}
|
||||||
|
constructor(body, init) {
|
||||||
|
let headers;
|
||||||
|
this.#body = body;
|
||||||
|
if (init instanceof _Response) {
|
||||||
|
const cachedGlobalResponse = init[responseCache];
|
||||||
|
if (cachedGlobalResponse) {
|
||||||
|
this.#init = cachedGlobalResponse;
|
||||||
|
this[getResponseCache]();
|
||||||
|
return;
|
||||||
|
} else {
|
||||||
|
this.#init = init.#init;
|
||||||
|
headers = new Headers(init.#init.headers);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
this.#init = init;
|
||||||
|
}
|
||||||
|
if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
|
||||||
|
;
|
||||||
|
this[cacheKey] = [init?.status || 200, body, headers || init?.headers];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
get headers() {
|
||||||
|
const cache = this[cacheKey];
|
||||||
|
if (cache) {
|
||||||
|
if (!(cache[2] instanceof Headers)) {
|
||||||
|
cache[2] = new Headers(
|
||||||
|
cache[2] || { "content-type": "text/plain; charset=UTF-8" }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return cache[2];
|
||||||
|
}
|
||||||
|
return this[getResponseCache]().headers;
|
||||||
|
}
|
||||||
|
get status() {
|
||||||
|
return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
|
||||||
|
}
|
||||||
|
get ok() {
|
||||||
|
const status = this.status;
|
||||||
|
return status >= 200 && status < 300;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
|
||||||
|
Object.defineProperty(Response2.prototype, k, {
|
||||||
|
get() {
|
||||||
|
return this[getResponseCache]()[k];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
|
||||||
|
Object.defineProperty(Response2.prototype, k, {
|
||||||
|
value: function() {
|
||||||
|
return this[getResponseCache]()[k]();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
Object.defineProperty(Response2.prototype, Symbol.for("nodejs.util.inspect.custom"), {
|
||||||
|
value: function(depth, options, inspectFn) {
|
||||||
|
const props = {
|
||||||
|
status: this.status,
|
||||||
|
headers: this.headers,
|
||||||
|
ok: this.ok,
|
||||||
|
nativeResponse: this[responseCache]
|
||||||
|
};
|
||||||
|
return `Response (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Object.setPrototypeOf(Response2, GlobalResponse);
|
||||||
|
Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
|
||||||
|
|
||||||
|
// src/utils.ts
|
||||||
|
async function readWithoutBlocking(readPromise) {
|
||||||
|
return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
|
||||||
|
}
|
||||||
|
function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
|
||||||
|
const cancel = (error) => {
|
||||||
|
reader.cancel(error).catch(() => {
|
||||||
|
});
|
||||||
|
};
|
||||||
|
writable.on("close", cancel);
|
||||||
|
writable.on("error", cancel);
|
||||||
|
(currentReadPromise ?? reader.read()).then(flow, handleStreamError);
|
||||||
|
return reader.closed.finally(() => {
|
||||||
|
writable.off("close", cancel);
|
||||||
|
writable.off("error", cancel);
|
||||||
|
});
|
||||||
|
function handleStreamError(error) {
|
||||||
|
if (error) {
|
||||||
|
writable.destroy(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function onDrain() {
|
||||||
|
reader.read().then(flow, handleStreamError);
|
||||||
|
}
|
||||||
|
function flow({ done, value }) {
|
||||||
|
try {
|
||||||
|
if (done) {
|
||||||
|
writable.end();
|
||||||
|
} else if (!writable.write(value)) {
|
||||||
|
writable.once("drain", onDrain);
|
||||||
|
} else {
|
||||||
|
return reader.read().then(flow, handleStreamError);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
handleStreamError(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function writeFromReadableStream(stream, writable) {
|
||||||
|
if (stream.locked) {
|
||||||
|
throw new TypeError("ReadableStream is locked.");
|
||||||
|
} else if (writable.destroyed) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
|
||||||
|
}
|
||||||
|
var buildOutgoingHttpHeaders = (headers) => {
|
||||||
|
const res = {};
|
||||||
|
if (!(headers instanceof Headers)) {
|
||||||
|
headers = new Headers(headers ?? void 0);
|
||||||
|
}
|
||||||
|
const cookies = [];
|
||||||
|
for (const [k, v] of headers) {
|
||||||
|
if (k === "set-cookie") {
|
||||||
|
cookies.push(v);
|
||||||
|
} else {
|
||||||
|
res[k] = v;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (cookies.length > 0) {
|
||||||
|
res["set-cookie"] = cookies;
|
||||||
|
}
|
||||||
|
res["content-type"] ??= "text/plain; charset=UTF-8";
|
||||||
|
return res;
|
||||||
|
};
|
||||||
|
|
||||||
|
// src/utils/response/constants.ts
|
||||||
|
var X_ALREADY_SENT = "x-hono-already-sent";
|
||||||
|
|
||||||
|
// src/globals.ts
|
||||||
|
var import_node_crypto = __toESM(require("crypto"));
|
||||||
|
if (typeof global.crypto === "undefined") {
|
||||||
|
global.crypto = import_node_crypto.default;
|
||||||
|
}
|
||||||
|
|
||||||
|
// src/listener.ts
|
||||||
|
var outgoingEnded = Symbol("outgoingEnded");
|
||||||
|
var incomingDraining = Symbol("incomingDraining");
|
||||||
|
var DRAIN_TIMEOUT_MS = 500;
|
||||||
|
var MAX_DRAIN_BYTES = 64 * 1024 * 1024;
|
||||||
|
var drainIncoming = (incoming) => {
|
||||||
|
const incomingWithDrainState = incoming;
|
||||||
|
if (incoming.destroyed || incomingWithDrainState[incomingDraining]) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
incomingWithDrainState[incomingDraining] = true;
|
||||||
|
if (incoming instanceof import_node_http22.Http2ServerRequest) {
|
||||||
|
try {
|
||||||
|
;
|
||||||
|
incoming.stream?.close?.(import_node_http22.constants.NGHTTP2_NO_ERROR);
|
||||||
|
} catch {
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let bytesRead = 0;
|
||||||
|
const cleanup = () => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
incoming.off("data", onData);
|
||||||
|
incoming.off("end", cleanup);
|
||||||
|
incoming.off("error", cleanup);
|
||||||
|
};
|
||||||
|
const forceClose = () => {
|
||||||
|
cleanup();
|
||||||
|
const socket = incoming.socket;
|
||||||
|
if (socket && !socket.destroyed) {
|
||||||
|
socket.destroySoon();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
|
||||||
|
timer.unref?.();
|
||||||
|
const onData = (chunk) => {
|
||||||
|
bytesRead += chunk.length;
|
||||||
|
if (bytesRead > MAX_DRAIN_BYTES) {
|
||||||
|
forceClose();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
incoming.on("data", onData);
|
||||||
|
incoming.on("end", cleanup);
|
||||||
|
incoming.on("error", cleanup);
|
||||||
|
incoming.resume();
|
||||||
|
};
|
||||||
|
var handleRequestError = () => new Response(null, {
|
||||||
|
status: 400
|
||||||
|
});
|
||||||
|
var handleFetchError = (e) => new Response(null, {
|
||||||
|
status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
|
||||||
|
});
|
||||||
|
var handleResponseError = (e, outgoing) => {
|
||||||
|
const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
|
||||||
|
if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
|
||||||
|
console.info("The user aborted a request.");
|
||||||
|
} else {
|
||||||
|
console.error(e);
|
||||||
|
if (!outgoing.headersSent) {
|
||||||
|
outgoing.writeHead(500, { "Content-Type": "text/plain" });
|
||||||
|
}
|
||||||
|
outgoing.end(`Error: ${err.message}`);
|
||||||
|
outgoing.destroy(err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var flushHeaders = (outgoing) => {
|
||||||
|
if ("flushHeaders" in outgoing && outgoing.writable) {
|
||||||
|
outgoing.flushHeaders();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var responseViaCache = async (res, outgoing) => {
|
||||||
|
let [status, body, header] = res[cacheKey];
|
||||||
|
let hasContentLength = false;
|
||||||
|
if (!header) {
|
||||||
|
header = { "content-type": "text/plain; charset=UTF-8" };
|
||||||
|
} else if (header instanceof Headers) {
|
||||||
|
hasContentLength = header.has("content-length");
|
||||||
|
header = buildOutgoingHttpHeaders(header);
|
||||||
|
} else if (Array.isArray(header)) {
|
||||||
|
const headerObj = new Headers(header);
|
||||||
|
hasContentLength = headerObj.has("content-length");
|
||||||
|
header = buildOutgoingHttpHeaders(headerObj);
|
||||||
|
} else {
|
||||||
|
for (const key in header) {
|
||||||
|
if (key.length === 14 && key.toLowerCase() === "content-length") {
|
||||||
|
hasContentLength = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!hasContentLength) {
|
||||||
|
if (typeof body === "string") {
|
||||||
|
header["Content-Length"] = Buffer.byteLength(body);
|
||||||
|
} else if (body instanceof Uint8Array) {
|
||||||
|
header["Content-Length"] = body.byteLength;
|
||||||
|
} else if (body instanceof Blob) {
|
||||||
|
header["Content-Length"] = body.size;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
outgoing.writeHead(status, header);
|
||||||
|
if (typeof body === "string" || body instanceof Uint8Array) {
|
||||||
|
outgoing.end(body);
|
||||||
|
} else if (body instanceof Blob) {
|
||||||
|
outgoing.end(new Uint8Array(await body.arrayBuffer()));
|
||||||
|
} else {
|
||||||
|
flushHeaders(outgoing);
|
||||||
|
await writeFromReadableStream(body, outgoing)?.catch(
|
||||||
|
(e) => handleResponseError(e, outgoing)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
;
|
||||||
|
outgoing[outgoingEnded]?.();
|
||||||
|
};
|
||||||
|
var isPromise = (res) => typeof res.then === "function";
|
||||||
|
var responseViaResponseObject = async (res, outgoing, options = {}) => {
|
||||||
|
if (isPromise(res)) {
|
||||||
|
if (options.errorHandler) {
|
||||||
|
try {
|
||||||
|
res = await res;
|
||||||
|
} catch (err) {
|
||||||
|
const errRes = await options.errorHandler(err);
|
||||||
|
if (!errRes) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
res = errRes;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
res = await res.catch(handleFetchError);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (cacheKey in res) {
|
||||||
|
return responseViaCache(res, outgoing);
|
||||||
|
}
|
||||||
|
const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
|
||||||
|
if (res.body) {
|
||||||
|
const reader = res.body.getReader();
|
||||||
|
const values = [];
|
||||||
|
let done = false;
|
||||||
|
let currentReadPromise = void 0;
|
||||||
|
if (resHeaderRecord["transfer-encoding"] !== "chunked") {
|
||||||
|
let maxReadCount = 2;
|
||||||
|
for (let i = 0; i < maxReadCount; i++) {
|
||||||
|
currentReadPromise ||= reader.read();
|
||||||
|
const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
|
||||||
|
console.error(e);
|
||||||
|
done = true;
|
||||||
|
});
|
||||||
|
if (!chunk) {
|
||||||
|
if (i === 1) {
|
||||||
|
await new Promise((resolve) => setTimeout(resolve));
|
||||||
|
maxReadCount = 3;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
currentReadPromise = void 0;
|
||||||
|
if (chunk.value) {
|
||||||
|
values.push(chunk.value);
|
||||||
|
}
|
||||||
|
if (chunk.done) {
|
||||||
|
done = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (done && !("content-length" in resHeaderRecord)) {
|
||||||
|
resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
outgoing.writeHead(res.status, resHeaderRecord);
|
||||||
|
values.forEach((value) => {
|
||||||
|
;
|
||||||
|
outgoing.write(value);
|
||||||
|
});
|
||||||
|
if (done) {
|
||||||
|
outgoing.end();
|
||||||
|
} else {
|
||||||
|
if (values.length === 0) {
|
||||||
|
flushHeaders(outgoing);
|
||||||
|
}
|
||||||
|
await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
|
||||||
|
}
|
||||||
|
} else if (resHeaderRecord[X_ALREADY_SENT]) {
|
||||||
|
} else {
|
||||||
|
outgoing.writeHead(res.status, resHeaderRecord);
|
||||||
|
outgoing.end();
|
||||||
|
}
|
||||||
|
;
|
||||||
|
outgoing[outgoingEnded]?.();
|
||||||
|
};
|
||||||
|
var getRequestListener = (fetchCallback, options = {}) => {
|
||||||
|
const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
|
||||||
|
if (options.overrideGlobalObjects !== false && global.Request !== Request) {
|
||||||
|
Object.defineProperty(global, "Request", {
|
||||||
|
value: Request
|
||||||
|
});
|
||||||
|
Object.defineProperty(global, "Response", {
|
||||||
|
value: Response2
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return async (incoming, outgoing) => {
|
||||||
|
let res, req;
|
||||||
|
try {
|
||||||
|
req = newRequest(incoming, options.hostname);
|
||||||
|
let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
|
||||||
|
if (!incomingEnded) {
|
||||||
|
;
|
||||||
|
incoming[wrapBodyStream] = true;
|
||||||
|
incoming.on("end", () => {
|
||||||
|
incomingEnded = true;
|
||||||
|
});
|
||||||
|
if (incoming instanceof import_node_http22.Http2ServerRequest) {
|
||||||
|
;
|
||||||
|
outgoing[outgoingEnded] = () => {
|
||||||
|
if (!incomingEnded) {
|
||||||
|
setTimeout(() => {
|
||||||
|
if (!incomingEnded) {
|
||||||
|
setTimeout(() => {
|
||||||
|
drainIncoming(incoming);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
outgoing.on("finish", () => {
|
||||||
|
if (!incomingEnded) {
|
||||||
|
drainIncoming(incoming);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
outgoing.on("close", () => {
|
||||||
|
const abortController = req[abortControllerKey];
|
||||||
|
if (abortController) {
|
||||||
|
if (incoming.errored) {
|
||||||
|
req[abortControllerKey].abort(incoming.errored.toString());
|
||||||
|
} else if (!outgoing.writableFinished) {
|
||||||
|
req[abortControllerKey].abort("Client connection prematurely closed.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!incomingEnded) {
|
||||||
|
setTimeout(() => {
|
||||||
|
if (!incomingEnded) {
|
||||||
|
setTimeout(() => {
|
||||||
|
drainIncoming(incoming);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
res = fetchCallback(req, { incoming, outgoing });
|
||||||
|
if (cacheKey in res) {
|
||||||
|
return responseViaCache(res, outgoing);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
if (!res) {
|
||||||
|
if (options.errorHandler) {
|
||||||
|
res = await options.errorHandler(req ? e : toRequestError(e));
|
||||||
|
if (!res) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} else if (!req) {
|
||||||
|
res = handleRequestError();
|
||||||
|
} else {
|
||||||
|
res = handleFetchError(e);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return handleResponseError(e, outgoing);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return await responseViaResponseObject(res, outgoing, options);
|
||||||
|
} catch (e) {
|
||||||
|
return handleResponseError(e, outgoing);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
// src/server.ts
|
||||||
|
var createAdaptorServer = (options) => {
|
||||||
|
const fetchCallback = options.fetch;
|
||||||
|
const requestListener = getRequestListener(fetchCallback, {
|
||||||
|
hostname: options.hostname,
|
||||||
|
overrideGlobalObjects: options.overrideGlobalObjects,
|
||||||
|
autoCleanupIncoming: options.autoCleanupIncoming
|
||||||
|
});
|
||||||
|
const createServer = options.createServer || import_node_http.createServer;
|
||||||
|
const server = createServer(options.serverOptions || {}, requestListener);
|
||||||
|
return server;
|
||||||
|
};
|
||||||
|
var serve = (options, listeningListener) => {
|
||||||
|
const server = createAdaptorServer(options);
|
||||||
|
server.listen(options?.port ?? 3e3, options.hostname, () => {
|
||||||
|
const serverInfo = server.address();
|
||||||
|
listeningListener && listeningListener(serverInfo);
|
||||||
|
});
|
||||||
|
return server;
|
||||||
|
};
|
||||||
|
// Annotate the CommonJS export names for ESM import in node:
|
||||||
|
0 && (module.exports = {
|
||||||
|
createAdaptorServer,
|
||||||
|
serve
|
||||||
|
});
|
||||||
660
node_modules/@hono/node-server/dist/server.mjs
generated
vendored
Normal file
660
node_modules/@hono/node-server/dist/server.mjs
generated
vendored
Normal file
@@ -0,0 +1,660 @@
|
|||||||
|
// src/server.ts
|
||||||
|
import { createServer as createServerHTTP } from "http";
|
||||||
|
|
||||||
|
// src/listener.ts
|
||||||
|
import { Http2ServerRequest as Http2ServerRequest2, constants as h2constants } from "http2";
|
||||||
|
|
||||||
|
// src/request.ts
|
||||||
|
import { Http2ServerRequest } from "http2";
|
||||||
|
import { Readable } from "stream";
|
||||||
|
var RequestError = class extends Error {
|
||||||
|
constructor(message, options) {
|
||||||
|
super(message, options);
|
||||||
|
this.name = "RequestError";
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var toRequestError = (e) => {
|
||||||
|
if (e instanceof RequestError) {
|
||||||
|
return e;
|
||||||
|
}
|
||||||
|
return new RequestError(e.message, { cause: e });
|
||||||
|
};
|
||||||
|
var GlobalRequest = global.Request;
|
||||||
|
var Request = class extends GlobalRequest {
|
||||||
|
constructor(input, options) {
|
||||||
|
if (typeof input === "object" && getRequestCache in input) {
|
||||||
|
input = input[getRequestCache]();
|
||||||
|
}
|
||||||
|
if (typeof options?.body?.getReader !== "undefined") {
|
||||||
|
;
|
||||||
|
options.duplex ??= "half";
|
||||||
|
}
|
||||||
|
super(input, options);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var newHeadersFromIncoming = (incoming) => {
|
||||||
|
const headerRecord = [];
|
||||||
|
const rawHeaders = incoming.rawHeaders;
|
||||||
|
for (let i = 0; i < rawHeaders.length; i += 2) {
|
||||||
|
const { [i]: key, [i + 1]: value } = rawHeaders;
|
||||||
|
if (key.charCodeAt(0) !== /*:*/
|
||||||
|
58) {
|
||||||
|
headerRecord.push([key, value]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new Headers(headerRecord);
|
||||||
|
};
|
||||||
|
var wrapBodyStream = Symbol("wrapBodyStream");
|
||||||
|
var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
|
||||||
|
const init = {
|
||||||
|
method,
|
||||||
|
headers,
|
||||||
|
signal: abortController.signal
|
||||||
|
};
|
||||||
|
if (method === "TRACE") {
|
||||||
|
init.method = "GET";
|
||||||
|
const req = new Request(url, init);
|
||||||
|
Object.defineProperty(req, "method", {
|
||||||
|
get() {
|
||||||
|
return "TRACE";
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return req;
|
||||||
|
}
|
||||||
|
if (!(method === "GET" || method === "HEAD")) {
|
||||||
|
if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
|
||||||
|
init.body = new ReadableStream({
|
||||||
|
start(controller) {
|
||||||
|
controller.enqueue(incoming.rawBody);
|
||||||
|
controller.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else if (incoming[wrapBodyStream]) {
|
||||||
|
let reader;
|
||||||
|
init.body = new ReadableStream({
|
||||||
|
async pull(controller) {
|
||||||
|
try {
|
||||||
|
reader ||= Readable.toWeb(incoming).getReader();
|
||||||
|
const { done, value } = await reader.read();
|
||||||
|
if (done) {
|
||||||
|
controller.close();
|
||||||
|
} else {
|
||||||
|
controller.enqueue(value);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
controller.error(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
init.body = Readable.toWeb(incoming);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new Request(url, init);
|
||||||
|
};
|
||||||
|
var getRequestCache = Symbol("getRequestCache");
|
||||||
|
var requestCache = Symbol("requestCache");
|
||||||
|
var incomingKey = Symbol("incomingKey");
|
||||||
|
var urlKey = Symbol("urlKey");
|
||||||
|
var headersKey = Symbol("headersKey");
|
||||||
|
var abortControllerKey = Symbol("abortControllerKey");
|
||||||
|
var getAbortController = Symbol("getAbortController");
|
||||||
|
var requestPrototype = {
|
||||||
|
get method() {
|
||||||
|
return this[incomingKey].method || "GET";
|
||||||
|
},
|
||||||
|
get url() {
|
||||||
|
return this[urlKey];
|
||||||
|
},
|
||||||
|
get headers() {
|
||||||
|
return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
|
||||||
|
},
|
||||||
|
[getAbortController]() {
|
||||||
|
this[getRequestCache]();
|
||||||
|
return this[abortControllerKey];
|
||||||
|
},
|
||||||
|
[getRequestCache]() {
|
||||||
|
this[abortControllerKey] ||= new AbortController();
|
||||||
|
return this[requestCache] ||= newRequestFromIncoming(
|
||||||
|
this.method,
|
||||||
|
this[urlKey],
|
||||||
|
this.headers,
|
||||||
|
this[incomingKey],
|
||||||
|
this[abortControllerKey]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
[
|
||||||
|
"body",
|
||||||
|
"bodyUsed",
|
||||||
|
"cache",
|
||||||
|
"credentials",
|
||||||
|
"destination",
|
||||||
|
"integrity",
|
||||||
|
"mode",
|
||||||
|
"redirect",
|
||||||
|
"referrer",
|
||||||
|
"referrerPolicy",
|
||||||
|
"signal",
|
||||||
|
"keepalive"
|
||||||
|
].forEach((k) => {
|
||||||
|
Object.defineProperty(requestPrototype, k, {
|
||||||
|
get() {
|
||||||
|
return this[getRequestCache]()[k];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
|
||||||
|
Object.defineProperty(requestPrototype, k, {
|
||||||
|
value: function() {
|
||||||
|
return this[getRequestCache]()[k]();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), {
|
||||||
|
value: function(depth, options, inspectFn) {
|
||||||
|
const props = {
|
||||||
|
method: this.method,
|
||||||
|
url: this.url,
|
||||||
|
headers: this.headers,
|
||||||
|
nativeRequest: this[requestCache]
|
||||||
|
};
|
||||||
|
return `Request (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Object.setPrototypeOf(requestPrototype, Request.prototype);
|
||||||
|
var newRequest = (incoming, defaultHostname) => {
|
||||||
|
const req = Object.create(requestPrototype);
|
||||||
|
req[incomingKey] = incoming;
|
||||||
|
const incomingUrl = incoming.url || "";
|
||||||
|
if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
|
||||||
|
(incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
|
||||||
|
if (incoming instanceof Http2ServerRequest) {
|
||||||
|
throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const url2 = new URL(incomingUrl);
|
||||||
|
req[urlKey] = url2.href;
|
||||||
|
} catch (e) {
|
||||||
|
throw new RequestError("Invalid absolute URL", { cause: e });
|
||||||
|
}
|
||||||
|
return req;
|
||||||
|
}
|
||||||
|
const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
|
||||||
|
if (!host) {
|
||||||
|
throw new RequestError("Missing host header");
|
||||||
|
}
|
||||||
|
let scheme;
|
||||||
|
if (incoming instanceof Http2ServerRequest) {
|
||||||
|
scheme = incoming.scheme;
|
||||||
|
if (!(scheme === "http" || scheme === "https")) {
|
||||||
|
throw new RequestError("Unsupported scheme");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
|
||||||
|
}
|
||||||
|
const url = new URL(`${scheme}://${host}${incomingUrl}`);
|
||||||
|
if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
|
||||||
|
throw new RequestError("Invalid host header");
|
||||||
|
}
|
||||||
|
req[urlKey] = url.href;
|
||||||
|
return req;
|
||||||
|
};
|
||||||
|
|
||||||
|
// src/response.ts
|
||||||
|
var responseCache = Symbol("responseCache");
|
||||||
|
var getResponseCache = Symbol("getResponseCache");
|
||||||
|
var cacheKey = Symbol("cache");
|
||||||
|
var GlobalResponse = global.Response;
|
||||||
|
var Response2 = class _Response {
|
||||||
|
#body;
|
||||||
|
#init;
|
||||||
|
[getResponseCache]() {
|
||||||
|
delete this[cacheKey];
|
||||||
|
return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
|
||||||
|
}
|
||||||
|
constructor(body, init) {
|
||||||
|
let headers;
|
||||||
|
this.#body = body;
|
||||||
|
if (init instanceof _Response) {
|
||||||
|
const cachedGlobalResponse = init[responseCache];
|
||||||
|
if (cachedGlobalResponse) {
|
||||||
|
this.#init = cachedGlobalResponse;
|
||||||
|
this[getResponseCache]();
|
||||||
|
return;
|
||||||
|
} else {
|
||||||
|
this.#init = init.#init;
|
||||||
|
headers = new Headers(init.#init.headers);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
this.#init = init;
|
||||||
|
}
|
||||||
|
if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
|
||||||
|
;
|
||||||
|
this[cacheKey] = [init?.status || 200, body, headers || init?.headers];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
get headers() {
|
||||||
|
const cache = this[cacheKey];
|
||||||
|
if (cache) {
|
||||||
|
if (!(cache[2] instanceof Headers)) {
|
||||||
|
cache[2] = new Headers(
|
||||||
|
cache[2] || { "content-type": "text/plain; charset=UTF-8" }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return cache[2];
|
||||||
|
}
|
||||||
|
return this[getResponseCache]().headers;
|
||||||
|
}
|
||||||
|
get status() {
|
||||||
|
return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
|
||||||
|
}
|
||||||
|
get ok() {
|
||||||
|
const status = this.status;
|
||||||
|
return status >= 200 && status < 300;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
|
||||||
|
Object.defineProperty(Response2.prototype, k, {
|
||||||
|
get() {
|
||||||
|
return this[getResponseCache]()[k];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
|
||||||
|
Object.defineProperty(Response2.prototype, k, {
|
||||||
|
value: function() {
|
||||||
|
return this[getResponseCache]()[k]();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
Object.defineProperty(Response2.prototype, Symbol.for("nodejs.util.inspect.custom"), {
|
||||||
|
value: function(depth, options, inspectFn) {
|
||||||
|
const props = {
|
||||||
|
status: this.status,
|
||||||
|
headers: this.headers,
|
||||||
|
ok: this.ok,
|
||||||
|
nativeResponse: this[responseCache]
|
||||||
|
};
|
||||||
|
return `Response (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Object.setPrototypeOf(Response2, GlobalResponse);
|
||||||
|
Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
|
||||||
|
|
||||||
|
// src/utils.ts
|
||||||
|
async function readWithoutBlocking(readPromise) {
|
||||||
|
return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
|
||||||
|
}
|
||||||
|
function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
|
||||||
|
const cancel = (error) => {
|
||||||
|
reader.cancel(error).catch(() => {
|
||||||
|
});
|
||||||
|
};
|
||||||
|
writable.on("close", cancel);
|
||||||
|
writable.on("error", cancel);
|
||||||
|
(currentReadPromise ?? reader.read()).then(flow, handleStreamError);
|
||||||
|
return reader.closed.finally(() => {
|
||||||
|
writable.off("close", cancel);
|
||||||
|
writable.off("error", cancel);
|
||||||
|
});
|
||||||
|
function handleStreamError(error) {
|
||||||
|
if (error) {
|
||||||
|
writable.destroy(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function onDrain() {
|
||||||
|
reader.read().then(flow, handleStreamError);
|
||||||
|
}
|
||||||
|
function flow({ done, value }) {
|
||||||
|
try {
|
||||||
|
if (done) {
|
||||||
|
writable.end();
|
||||||
|
} else if (!writable.write(value)) {
|
||||||
|
writable.once("drain", onDrain);
|
||||||
|
} else {
|
||||||
|
return reader.read().then(flow, handleStreamError);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
handleStreamError(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function writeFromReadableStream(stream, writable) {
|
||||||
|
if (stream.locked) {
|
||||||
|
throw new TypeError("ReadableStream is locked.");
|
||||||
|
} else if (writable.destroyed) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
|
||||||
|
}
|
||||||
|
var buildOutgoingHttpHeaders = (headers) => {
|
||||||
|
const res = {};
|
||||||
|
if (!(headers instanceof Headers)) {
|
||||||
|
headers = new Headers(headers ?? void 0);
|
||||||
|
}
|
||||||
|
const cookies = [];
|
||||||
|
for (const [k, v] of headers) {
|
||||||
|
if (k === "set-cookie") {
|
||||||
|
cookies.push(v);
|
||||||
|
} else {
|
||||||
|
res[k] = v;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (cookies.length > 0) {
|
||||||
|
res["set-cookie"] = cookies;
|
||||||
|
}
|
||||||
|
res["content-type"] ??= "text/plain; charset=UTF-8";
|
||||||
|
return res;
|
||||||
|
};
|
||||||
|
|
||||||
|
// src/utils/response/constants.ts
|
||||||
|
var X_ALREADY_SENT = "x-hono-already-sent";
|
||||||
|
|
||||||
|
// src/globals.ts
|
||||||
|
import crypto from "crypto";
|
||||||
|
if (typeof global.crypto === "undefined") {
|
||||||
|
global.crypto = crypto;
|
||||||
|
}
|
||||||
|
|
||||||
|
// src/listener.ts
|
||||||
|
var outgoingEnded = Symbol("outgoingEnded");
|
||||||
|
var incomingDraining = Symbol("incomingDraining");
|
||||||
|
var DRAIN_TIMEOUT_MS = 500;
|
||||||
|
var MAX_DRAIN_BYTES = 64 * 1024 * 1024;
|
||||||
|
var drainIncoming = (incoming) => {
|
||||||
|
const incomingWithDrainState = incoming;
|
||||||
|
if (incoming.destroyed || incomingWithDrainState[incomingDraining]) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
incomingWithDrainState[incomingDraining] = true;
|
||||||
|
if (incoming instanceof Http2ServerRequest2) {
|
||||||
|
try {
|
||||||
|
;
|
||||||
|
incoming.stream?.close?.(h2constants.NGHTTP2_NO_ERROR);
|
||||||
|
} catch {
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let bytesRead = 0;
|
||||||
|
const cleanup = () => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
incoming.off("data", onData);
|
||||||
|
incoming.off("end", cleanup);
|
||||||
|
incoming.off("error", cleanup);
|
||||||
|
};
|
||||||
|
const forceClose = () => {
|
||||||
|
cleanup();
|
||||||
|
const socket = incoming.socket;
|
||||||
|
if (socket && !socket.destroyed) {
|
||||||
|
socket.destroySoon();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
|
||||||
|
timer.unref?.();
|
||||||
|
const onData = (chunk) => {
|
||||||
|
bytesRead += chunk.length;
|
||||||
|
if (bytesRead > MAX_DRAIN_BYTES) {
|
||||||
|
forceClose();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
incoming.on("data", onData);
|
||||||
|
incoming.on("end", cleanup);
|
||||||
|
incoming.on("error", cleanup);
|
||||||
|
incoming.resume();
|
||||||
|
};
|
||||||
|
var handleRequestError = () => new Response(null, {
|
||||||
|
status: 400
|
||||||
|
});
|
||||||
|
var handleFetchError = (e) => new Response(null, {
|
||||||
|
status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
|
||||||
|
});
|
||||||
|
var handleResponseError = (e, outgoing) => {
|
||||||
|
const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
|
||||||
|
if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
|
||||||
|
console.info("The user aborted a request.");
|
||||||
|
} else {
|
||||||
|
console.error(e);
|
||||||
|
if (!outgoing.headersSent) {
|
||||||
|
outgoing.writeHead(500, { "Content-Type": "text/plain" });
|
||||||
|
}
|
||||||
|
outgoing.end(`Error: ${err.message}`);
|
||||||
|
outgoing.destroy(err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var flushHeaders = (outgoing) => {
|
||||||
|
if ("flushHeaders" in outgoing && outgoing.writable) {
|
||||||
|
outgoing.flushHeaders();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var responseViaCache = async (res, outgoing) => {
|
||||||
|
let [status, body, header] = res[cacheKey];
|
||||||
|
let hasContentLength = false;
|
||||||
|
if (!header) {
|
||||||
|
header = { "content-type": "text/plain; charset=UTF-8" };
|
||||||
|
} else if (header instanceof Headers) {
|
||||||
|
hasContentLength = header.has("content-length");
|
||||||
|
header = buildOutgoingHttpHeaders(header);
|
||||||
|
} else if (Array.isArray(header)) {
|
||||||
|
const headerObj = new Headers(header);
|
||||||
|
hasContentLength = headerObj.has("content-length");
|
||||||
|
header = buildOutgoingHttpHeaders(headerObj);
|
||||||
|
} else {
|
||||||
|
for (const key in header) {
|
||||||
|
if (key.length === 14 && key.toLowerCase() === "content-length") {
|
||||||
|
hasContentLength = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!hasContentLength) {
|
||||||
|
if (typeof body === "string") {
|
||||||
|
header["Content-Length"] = Buffer.byteLength(body);
|
||||||
|
} else if (body instanceof Uint8Array) {
|
||||||
|
header["Content-Length"] = body.byteLength;
|
||||||
|
} else if (body instanceof Blob) {
|
||||||
|
header["Content-Length"] = body.size;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
outgoing.writeHead(status, header);
|
||||||
|
if (typeof body === "string" || body instanceof Uint8Array) {
|
||||||
|
outgoing.end(body);
|
||||||
|
} else if (body instanceof Blob) {
|
||||||
|
outgoing.end(new Uint8Array(await body.arrayBuffer()));
|
||||||
|
} else {
|
||||||
|
flushHeaders(outgoing);
|
||||||
|
await writeFromReadableStream(body, outgoing)?.catch(
|
||||||
|
(e) => handleResponseError(e, outgoing)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
;
|
||||||
|
outgoing[outgoingEnded]?.();
|
||||||
|
};
|
||||||
|
var isPromise = (res) => typeof res.then === "function";
|
||||||
|
var responseViaResponseObject = async (res, outgoing, options = {}) => {
|
||||||
|
if (isPromise(res)) {
|
||||||
|
if (options.errorHandler) {
|
||||||
|
try {
|
||||||
|
res = await res;
|
||||||
|
} catch (err) {
|
||||||
|
const errRes = await options.errorHandler(err);
|
||||||
|
if (!errRes) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
res = errRes;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
res = await res.catch(handleFetchError);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (cacheKey in res) {
|
||||||
|
return responseViaCache(res, outgoing);
|
||||||
|
}
|
||||||
|
const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
|
||||||
|
if (res.body) {
|
||||||
|
const reader = res.body.getReader();
|
||||||
|
const values = [];
|
||||||
|
let done = false;
|
||||||
|
let currentReadPromise = void 0;
|
||||||
|
if (resHeaderRecord["transfer-encoding"] !== "chunked") {
|
||||||
|
let maxReadCount = 2;
|
||||||
|
for (let i = 0; i < maxReadCount; i++) {
|
||||||
|
currentReadPromise ||= reader.read();
|
||||||
|
const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
|
||||||
|
console.error(e);
|
||||||
|
done = true;
|
||||||
|
});
|
||||||
|
if (!chunk) {
|
||||||
|
if (i === 1) {
|
||||||
|
await new Promise((resolve) => setTimeout(resolve));
|
||||||
|
maxReadCount = 3;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
currentReadPromise = void 0;
|
||||||
|
if (chunk.value) {
|
||||||
|
values.push(chunk.value);
|
||||||
|
}
|
||||||
|
if (chunk.done) {
|
||||||
|
done = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (done && !("content-length" in resHeaderRecord)) {
|
||||||
|
resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
outgoing.writeHead(res.status, resHeaderRecord);
|
||||||
|
values.forEach((value) => {
|
||||||
|
;
|
||||||
|
outgoing.write(value);
|
||||||
|
});
|
||||||
|
if (done) {
|
||||||
|
outgoing.end();
|
||||||
|
} else {
|
||||||
|
if (values.length === 0) {
|
||||||
|
flushHeaders(outgoing);
|
||||||
|
}
|
||||||
|
await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
|
||||||
|
}
|
||||||
|
} else if (resHeaderRecord[X_ALREADY_SENT]) {
|
||||||
|
} else {
|
||||||
|
outgoing.writeHead(res.status, resHeaderRecord);
|
||||||
|
outgoing.end();
|
||||||
|
}
|
||||||
|
;
|
||||||
|
outgoing[outgoingEnded]?.();
|
||||||
|
};
|
||||||
|
var getRequestListener = (fetchCallback, options = {}) => {
|
||||||
|
const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
|
||||||
|
if (options.overrideGlobalObjects !== false && global.Request !== Request) {
|
||||||
|
Object.defineProperty(global, "Request", {
|
||||||
|
value: Request
|
||||||
|
});
|
||||||
|
Object.defineProperty(global, "Response", {
|
||||||
|
value: Response2
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return async (incoming, outgoing) => {
|
||||||
|
let res, req;
|
||||||
|
try {
|
||||||
|
req = newRequest(incoming, options.hostname);
|
||||||
|
let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
|
||||||
|
if (!incomingEnded) {
|
||||||
|
;
|
||||||
|
incoming[wrapBodyStream] = true;
|
||||||
|
incoming.on("end", () => {
|
||||||
|
incomingEnded = true;
|
||||||
|
});
|
||||||
|
if (incoming instanceof Http2ServerRequest2) {
|
||||||
|
;
|
||||||
|
outgoing[outgoingEnded] = () => {
|
||||||
|
if (!incomingEnded) {
|
||||||
|
setTimeout(() => {
|
||||||
|
if (!incomingEnded) {
|
||||||
|
setTimeout(() => {
|
||||||
|
drainIncoming(incoming);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
outgoing.on("finish", () => {
|
||||||
|
if (!incomingEnded) {
|
||||||
|
drainIncoming(incoming);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
outgoing.on("close", () => {
|
||||||
|
const abortController = req[abortControllerKey];
|
||||||
|
if (abortController) {
|
||||||
|
if (incoming.errored) {
|
||||||
|
req[abortControllerKey].abort(incoming.errored.toString());
|
||||||
|
} else if (!outgoing.writableFinished) {
|
||||||
|
req[abortControllerKey].abort("Client connection prematurely closed.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!incomingEnded) {
|
||||||
|
setTimeout(() => {
|
||||||
|
if (!incomingEnded) {
|
||||||
|
setTimeout(() => {
|
||||||
|
drainIncoming(incoming);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
res = fetchCallback(req, { incoming, outgoing });
|
||||||
|
if (cacheKey in res) {
|
||||||
|
return responseViaCache(res, outgoing);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
if (!res) {
|
||||||
|
if (options.errorHandler) {
|
||||||
|
res = await options.errorHandler(req ? e : toRequestError(e));
|
||||||
|
if (!res) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} else if (!req) {
|
||||||
|
res = handleRequestError();
|
||||||
|
} else {
|
||||||
|
res = handleFetchError(e);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return handleResponseError(e, outgoing);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return await responseViaResponseObject(res, outgoing, options);
|
||||||
|
} catch (e) {
|
||||||
|
return handleResponseError(e, outgoing);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
// src/server.ts
|
||||||
|
var createAdaptorServer = (options) => {
|
||||||
|
const fetchCallback = options.fetch;
|
||||||
|
const requestListener = getRequestListener(fetchCallback, {
|
||||||
|
hostname: options.hostname,
|
||||||
|
overrideGlobalObjects: options.overrideGlobalObjects,
|
||||||
|
autoCleanupIncoming: options.autoCleanupIncoming
|
||||||
|
});
|
||||||
|
const createServer = options.createServer || createServerHTTP;
|
||||||
|
const server = createServer(options.serverOptions || {}, requestListener);
|
||||||
|
return server;
|
||||||
|
};
|
||||||
|
var serve = (options, listeningListener) => {
|
||||||
|
const server = createAdaptorServer(options);
|
||||||
|
server.listen(options?.port ?? 3e3, options.hostname, () => {
|
||||||
|
const serverInfo = server.address();
|
||||||
|
listeningListener && listeningListener(serverInfo);
|
||||||
|
});
|
||||||
|
return server;
|
||||||
|
};
|
||||||
|
export {
|
||||||
|
createAdaptorServer,
|
||||||
|
serve
|
||||||
|
};
|
||||||
44
node_modules/@hono/node-server/dist/types.d.mts
generated
vendored
Normal file
44
node_modules/@hono/node-server/dist/types.d.mts
generated
vendored
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
import { IncomingMessage, ServerResponse, ServerOptions as ServerOptions$1, createServer, Server } from 'node:http';
|
||||||
|
import { Http2ServerRequest, Http2ServerResponse, ServerOptions as ServerOptions$3, createServer as createServer$2, SecureServerOptions, createSecureServer, Http2Server, Http2SecureServer } from 'node:http2';
|
||||||
|
import { ServerOptions as ServerOptions$2, createServer as createServer$1 } from 'node:https';
|
||||||
|
|
||||||
|
type HttpBindings = {
|
||||||
|
incoming: IncomingMessage;
|
||||||
|
outgoing: ServerResponse;
|
||||||
|
};
|
||||||
|
type Http2Bindings = {
|
||||||
|
incoming: Http2ServerRequest;
|
||||||
|
outgoing: Http2ServerResponse;
|
||||||
|
};
|
||||||
|
type FetchCallback = (request: Request, env: HttpBindings | Http2Bindings) => Promise<unknown> | unknown;
|
||||||
|
type NextHandlerOption = {
|
||||||
|
fetch: FetchCallback;
|
||||||
|
};
|
||||||
|
type ServerType = Server | Http2Server | Http2SecureServer;
|
||||||
|
type createHttpOptions = {
|
||||||
|
serverOptions?: ServerOptions$1;
|
||||||
|
createServer?: typeof createServer;
|
||||||
|
};
|
||||||
|
type createHttpsOptions = {
|
||||||
|
serverOptions?: ServerOptions$2;
|
||||||
|
createServer?: typeof createServer$1;
|
||||||
|
};
|
||||||
|
type createHttp2Options = {
|
||||||
|
serverOptions?: ServerOptions$3;
|
||||||
|
createServer?: typeof createServer$2;
|
||||||
|
};
|
||||||
|
type createSecureHttp2Options = {
|
||||||
|
serverOptions?: SecureServerOptions;
|
||||||
|
createServer?: typeof createSecureServer;
|
||||||
|
};
|
||||||
|
type ServerOptions = createHttpOptions | createHttpsOptions | createHttp2Options | createSecureHttp2Options;
|
||||||
|
type Options = {
|
||||||
|
fetch: FetchCallback;
|
||||||
|
overrideGlobalObjects?: boolean;
|
||||||
|
autoCleanupIncoming?: boolean;
|
||||||
|
port?: number;
|
||||||
|
hostname?: string;
|
||||||
|
} & ServerOptions;
|
||||||
|
type CustomErrorHandler = (err: unknown) => void | Response | Promise<void | Response>;
|
||||||
|
|
||||||
|
export type { CustomErrorHandler, FetchCallback, Http2Bindings, HttpBindings, NextHandlerOption, Options, ServerOptions, ServerType };
|
||||||
44
node_modules/@hono/node-server/dist/types.d.ts
generated
vendored
Normal file
44
node_modules/@hono/node-server/dist/types.d.ts
generated
vendored
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
import { IncomingMessage, ServerResponse, ServerOptions as ServerOptions$1, createServer, Server } from 'node:http';
|
||||||
|
import { Http2ServerRequest, Http2ServerResponse, ServerOptions as ServerOptions$3, createServer as createServer$2, SecureServerOptions, createSecureServer, Http2Server, Http2SecureServer } from 'node:http2';
|
||||||
|
import { ServerOptions as ServerOptions$2, createServer as createServer$1 } from 'node:https';
|
||||||
|
|
||||||
|
type HttpBindings = {
|
||||||
|
incoming: IncomingMessage;
|
||||||
|
outgoing: ServerResponse;
|
||||||
|
};
|
||||||
|
type Http2Bindings = {
|
||||||
|
incoming: Http2ServerRequest;
|
||||||
|
outgoing: Http2ServerResponse;
|
||||||
|
};
|
||||||
|
type FetchCallback = (request: Request, env: HttpBindings | Http2Bindings) => Promise<unknown> | unknown;
|
||||||
|
type NextHandlerOption = {
|
||||||
|
fetch: FetchCallback;
|
||||||
|
};
|
||||||
|
type ServerType = Server | Http2Server | Http2SecureServer;
|
||||||
|
type createHttpOptions = {
|
||||||
|
serverOptions?: ServerOptions$1;
|
||||||
|
createServer?: typeof createServer;
|
||||||
|
};
|
||||||
|
type createHttpsOptions = {
|
||||||
|
serverOptions?: ServerOptions$2;
|
||||||
|
createServer?: typeof createServer$1;
|
||||||
|
};
|
||||||
|
type createHttp2Options = {
|
||||||
|
serverOptions?: ServerOptions$3;
|
||||||
|
createServer?: typeof createServer$2;
|
||||||
|
};
|
||||||
|
type createSecureHttp2Options = {
|
||||||
|
serverOptions?: SecureServerOptions;
|
||||||
|
createServer?: typeof createSecureServer;
|
||||||
|
};
|
||||||
|
type ServerOptions = createHttpOptions | createHttpsOptions | createHttp2Options | createSecureHttp2Options;
|
||||||
|
type Options = {
|
||||||
|
fetch: FetchCallback;
|
||||||
|
overrideGlobalObjects?: boolean;
|
||||||
|
autoCleanupIncoming?: boolean;
|
||||||
|
port?: number;
|
||||||
|
hostname?: string;
|
||||||
|
} & ServerOptions;
|
||||||
|
type CustomErrorHandler = (err: unknown) => void | Response | Promise<void | Response>;
|
||||||
|
|
||||||
|
export type { CustomErrorHandler, FetchCallback, Http2Bindings, HttpBindings, NextHandlerOption, Options, ServerOptions, ServerType };
|
||||||
18
node_modules/@hono/node-server/dist/types.js
generated
vendored
Normal file
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<undefined>;
|
||||||
|
declare function writeFromReadableStream(stream: ReadableStream<Uint8Array>, writable: Writable): Promise<undefined> | undefined;
|
||||||
|
declare const buildOutgoingHttpHeaders: (headers: Headers | HeadersInit | null | undefined) => OutgoingHttpHeaders;
|
||||||
|
|
||||||
|
export { buildOutgoingHttpHeaders, readWithoutBlocking, writeFromReadableStream, writeFromReadableStreamDefaultReader };
|
||||||
9
node_modules/@hono/node-server/dist/utils.d.ts
generated
vendored
Normal file
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<undefined>;
|
||||||
|
declare function writeFromReadableStream(stream: ReadableStream<Uint8Array>, writable: Writable): Promise<undefined> | undefined;
|
||||||
|
declare const buildOutgoingHttpHeaders: (headers: Headers | HeadersInit | null | undefined) => OutgoingHttpHeaders;
|
||||||
|
|
||||||
|
export { buildOutgoingHttpHeaders, readWithoutBlocking, writeFromReadableStream, writeFromReadableStreamDefaultReader };
|
||||||
99
node_modules/@hono/node-server/dist/utils.js
generated
vendored
Normal file
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 };
|
||||||
677
node_modules/@hono/node-server/dist/vercel.js
generated
vendored
Normal file
677
node_modules/@hono/node-server/dist/vercel.js
generated
vendored
Normal file
@@ -0,0 +1,677 @@
|
|||||||
|
"use strict";
|
||||||
|
var __create = Object.create;
|
||||||
|
var __defProp = Object.defineProperty;
|
||||||
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
||||||
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
||||||
|
var __getProtoOf = Object.getPrototypeOf;
|
||||||
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
||||||
|
var __export = (target, all) => {
|
||||||
|
for (var name in all)
|
||||||
|
__defProp(target, name, { get: all[name], enumerable: true });
|
||||||
|
};
|
||||||
|
var __copyProps = (to, from, except, desc) => {
|
||||||
|
if (from && typeof from === "object" || typeof from === "function") {
|
||||||
|
for (let key of __getOwnPropNames(from))
|
||||||
|
if (!__hasOwnProp.call(to, key) && key !== except)
|
||||||
|
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
||||||
|
}
|
||||||
|
return to;
|
||||||
|
};
|
||||||
|
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
||||||
|
// If the importer is in node compatibility mode or this is not an ESM
|
||||||
|
// file that has been converted to a CommonJS file using a Babel-
|
||||||
|
// compatible transform (i.e. "__esModule" has not been set), then set
|
||||||
|
// "default" to the CommonJS "module.exports" for node compatibility.
|
||||||
|
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
||||||
|
mod
|
||||||
|
));
|
||||||
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
||||||
|
|
||||||
|
// src/vercel.ts
|
||||||
|
var vercel_exports = {};
|
||||||
|
__export(vercel_exports, {
|
||||||
|
handle: () => handle
|
||||||
|
});
|
||||||
|
module.exports = __toCommonJS(vercel_exports);
|
||||||
|
|
||||||
|
// src/listener.ts
|
||||||
|
var import_node_http22 = require("http2");
|
||||||
|
|
||||||
|
// src/request.ts
|
||||||
|
var import_node_http2 = require("http2");
|
||||||
|
var import_node_stream = require("stream");
|
||||||
|
var RequestError = class extends Error {
|
||||||
|
constructor(message, options) {
|
||||||
|
super(message, options);
|
||||||
|
this.name = "RequestError";
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var toRequestError = (e) => {
|
||||||
|
if (e instanceof RequestError) {
|
||||||
|
return e;
|
||||||
|
}
|
||||||
|
return new RequestError(e.message, { cause: e });
|
||||||
|
};
|
||||||
|
var GlobalRequest = global.Request;
|
||||||
|
var Request = class extends GlobalRequest {
|
||||||
|
constructor(input, options) {
|
||||||
|
if (typeof input === "object" && getRequestCache in input) {
|
||||||
|
input = input[getRequestCache]();
|
||||||
|
}
|
||||||
|
if (typeof options?.body?.getReader !== "undefined") {
|
||||||
|
;
|
||||||
|
options.duplex ??= "half";
|
||||||
|
}
|
||||||
|
super(input, options);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var newHeadersFromIncoming = (incoming) => {
|
||||||
|
const headerRecord = [];
|
||||||
|
const rawHeaders = incoming.rawHeaders;
|
||||||
|
for (let i = 0; i < rawHeaders.length; i += 2) {
|
||||||
|
const { [i]: key, [i + 1]: value } = rawHeaders;
|
||||||
|
if (key.charCodeAt(0) !== /*:*/
|
||||||
|
58) {
|
||||||
|
headerRecord.push([key, value]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new Headers(headerRecord);
|
||||||
|
};
|
||||||
|
var wrapBodyStream = Symbol("wrapBodyStream");
|
||||||
|
var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
|
||||||
|
const init = {
|
||||||
|
method,
|
||||||
|
headers,
|
||||||
|
signal: abortController.signal
|
||||||
|
};
|
||||||
|
if (method === "TRACE") {
|
||||||
|
init.method = "GET";
|
||||||
|
const req = new Request(url, init);
|
||||||
|
Object.defineProperty(req, "method", {
|
||||||
|
get() {
|
||||||
|
return "TRACE";
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return req;
|
||||||
|
}
|
||||||
|
if (!(method === "GET" || method === "HEAD")) {
|
||||||
|
if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
|
||||||
|
init.body = new ReadableStream({
|
||||||
|
start(controller) {
|
||||||
|
controller.enqueue(incoming.rawBody);
|
||||||
|
controller.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else if (incoming[wrapBodyStream]) {
|
||||||
|
let reader;
|
||||||
|
init.body = new ReadableStream({
|
||||||
|
async pull(controller) {
|
||||||
|
try {
|
||||||
|
reader ||= import_node_stream.Readable.toWeb(incoming).getReader();
|
||||||
|
const { done, value } = await reader.read();
|
||||||
|
if (done) {
|
||||||
|
controller.close();
|
||||||
|
} else {
|
||||||
|
controller.enqueue(value);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
controller.error(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
init.body = import_node_stream.Readable.toWeb(incoming);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new Request(url, init);
|
||||||
|
};
|
||||||
|
var getRequestCache = Symbol("getRequestCache");
|
||||||
|
var requestCache = Symbol("requestCache");
|
||||||
|
var incomingKey = Symbol("incomingKey");
|
||||||
|
var urlKey = Symbol("urlKey");
|
||||||
|
var headersKey = Symbol("headersKey");
|
||||||
|
var abortControllerKey = Symbol("abortControllerKey");
|
||||||
|
var getAbortController = Symbol("getAbortController");
|
||||||
|
var requestPrototype = {
|
||||||
|
get method() {
|
||||||
|
return this[incomingKey].method || "GET";
|
||||||
|
},
|
||||||
|
get url() {
|
||||||
|
return this[urlKey];
|
||||||
|
},
|
||||||
|
get headers() {
|
||||||
|
return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
|
||||||
|
},
|
||||||
|
[getAbortController]() {
|
||||||
|
this[getRequestCache]();
|
||||||
|
return this[abortControllerKey];
|
||||||
|
},
|
||||||
|
[getRequestCache]() {
|
||||||
|
this[abortControllerKey] ||= new AbortController();
|
||||||
|
return this[requestCache] ||= newRequestFromIncoming(
|
||||||
|
this.method,
|
||||||
|
this[urlKey],
|
||||||
|
this.headers,
|
||||||
|
this[incomingKey],
|
||||||
|
this[abortControllerKey]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
[
|
||||||
|
"body",
|
||||||
|
"bodyUsed",
|
||||||
|
"cache",
|
||||||
|
"credentials",
|
||||||
|
"destination",
|
||||||
|
"integrity",
|
||||||
|
"mode",
|
||||||
|
"redirect",
|
||||||
|
"referrer",
|
||||||
|
"referrerPolicy",
|
||||||
|
"signal",
|
||||||
|
"keepalive"
|
||||||
|
].forEach((k) => {
|
||||||
|
Object.defineProperty(requestPrototype, k, {
|
||||||
|
get() {
|
||||||
|
return this[getRequestCache]()[k];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
|
||||||
|
Object.defineProperty(requestPrototype, k, {
|
||||||
|
value: function() {
|
||||||
|
return this[getRequestCache]()[k]();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), {
|
||||||
|
value: function(depth, options, inspectFn) {
|
||||||
|
const props = {
|
||||||
|
method: this.method,
|
||||||
|
url: this.url,
|
||||||
|
headers: this.headers,
|
||||||
|
nativeRequest: this[requestCache]
|
||||||
|
};
|
||||||
|
return `Request (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Object.setPrototypeOf(requestPrototype, Request.prototype);
|
||||||
|
var newRequest = (incoming, defaultHostname) => {
|
||||||
|
const req = Object.create(requestPrototype);
|
||||||
|
req[incomingKey] = incoming;
|
||||||
|
const incomingUrl = incoming.url || "";
|
||||||
|
if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
|
||||||
|
(incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
|
||||||
|
if (incoming instanceof import_node_http2.Http2ServerRequest) {
|
||||||
|
throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const url2 = new URL(incomingUrl);
|
||||||
|
req[urlKey] = url2.href;
|
||||||
|
} catch (e) {
|
||||||
|
throw new RequestError("Invalid absolute URL", { cause: e });
|
||||||
|
}
|
||||||
|
return req;
|
||||||
|
}
|
||||||
|
const host = (incoming instanceof import_node_http2.Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
|
||||||
|
if (!host) {
|
||||||
|
throw new RequestError("Missing host header");
|
||||||
|
}
|
||||||
|
let scheme;
|
||||||
|
if (incoming instanceof import_node_http2.Http2ServerRequest) {
|
||||||
|
scheme = incoming.scheme;
|
||||||
|
if (!(scheme === "http" || scheme === "https")) {
|
||||||
|
throw new RequestError("Unsupported scheme");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
|
||||||
|
}
|
||||||
|
const url = new URL(`${scheme}://${host}${incomingUrl}`);
|
||||||
|
if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
|
||||||
|
throw new RequestError("Invalid host header");
|
||||||
|
}
|
||||||
|
req[urlKey] = url.href;
|
||||||
|
return req;
|
||||||
|
};
|
||||||
|
|
||||||
|
// src/response.ts
|
||||||
|
var responseCache = Symbol("responseCache");
|
||||||
|
var getResponseCache = Symbol("getResponseCache");
|
||||||
|
var cacheKey = Symbol("cache");
|
||||||
|
var GlobalResponse = global.Response;
|
||||||
|
var Response2 = class _Response {
|
||||||
|
#body;
|
||||||
|
#init;
|
||||||
|
[getResponseCache]() {
|
||||||
|
delete this[cacheKey];
|
||||||
|
return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
|
||||||
|
}
|
||||||
|
constructor(body, init) {
|
||||||
|
let headers;
|
||||||
|
this.#body = body;
|
||||||
|
if (init instanceof _Response) {
|
||||||
|
const cachedGlobalResponse = init[responseCache];
|
||||||
|
if (cachedGlobalResponse) {
|
||||||
|
this.#init = cachedGlobalResponse;
|
||||||
|
this[getResponseCache]();
|
||||||
|
return;
|
||||||
|
} else {
|
||||||
|
this.#init = init.#init;
|
||||||
|
headers = new Headers(init.#init.headers);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
this.#init = init;
|
||||||
|
}
|
||||||
|
if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
|
||||||
|
;
|
||||||
|
this[cacheKey] = [init?.status || 200, body, headers || init?.headers];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
get headers() {
|
||||||
|
const cache = this[cacheKey];
|
||||||
|
if (cache) {
|
||||||
|
if (!(cache[2] instanceof Headers)) {
|
||||||
|
cache[2] = new Headers(
|
||||||
|
cache[2] || { "content-type": "text/plain; charset=UTF-8" }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return cache[2];
|
||||||
|
}
|
||||||
|
return this[getResponseCache]().headers;
|
||||||
|
}
|
||||||
|
get status() {
|
||||||
|
return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
|
||||||
|
}
|
||||||
|
get ok() {
|
||||||
|
const status = this.status;
|
||||||
|
return status >= 200 && status < 300;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
|
||||||
|
Object.defineProperty(Response2.prototype, k, {
|
||||||
|
get() {
|
||||||
|
return this[getResponseCache]()[k];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
|
||||||
|
Object.defineProperty(Response2.prototype, k, {
|
||||||
|
value: function() {
|
||||||
|
return this[getResponseCache]()[k]();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
Object.defineProperty(Response2.prototype, Symbol.for("nodejs.util.inspect.custom"), {
|
||||||
|
value: function(depth, options, inspectFn) {
|
||||||
|
const props = {
|
||||||
|
status: this.status,
|
||||||
|
headers: this.headers,
|
||||||
|
ok: this.ok,
|
||||||
|
nativeResponse: this[responseCache]
|
||||||
|
};
|
||||||
|
return `Response (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Object.setPrototypeOf(Response2, GlobalResponse);
|
||||||
|
Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
|
||||||
|
|
||||||
|
// src/utils.ts
|
||||||
|
async function readWithoutBlocking(readPromise) {
|
||||||
|
return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
|
||||||
|
}
|
||||||
|
function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
|
||||||
|
const cancel = (error) => {
|
||||||
|
reader.cancel(error).catch(() => {
|
||||||
|
});
|
||||||
|
};
|
||||||
|
writable.on("close", cancel);
|
||||||
|
writable.on("error", cancel);
|
||||||
|
(currentReadPromise ?? reader.read()).then(flow, handleStreamError);
|
||||||
|
return reader.closed.finally(() => {
|
||||||
|
writable.off("close", cancel);
|
||||||
|
writable.off("error", cancel);
|
||||||
|
});
|
||||||
|
function handleStreamError(error) {
|
||||||
|
if (error) {
|
||||||
|
writable.destroy(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function onDrain() {
|
||||||
|
reader.read().then(flow, handleStreamError);
|
||||||
|
}
|
||||||
|
function flow({ done, value }) {
|
||||||
|
try {
|
||||||
|
if (done) {
|
||||||
|
writable.end();
|
||||||
|
} else if (!writable.write(value)) {
|
||||||
|
writable.once("drain", onDrain);
|
||||||
|
} else {
|
||||||
|
return reader.read().then(flow, handleStreamError);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
handleStreamError(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function writeFromReadableStream(stream, writable) {
|
||||||
|
if (stream.locked) {
|
||||||
|
throw new TypeError("ReadableStream is locked.");
|
||||||
|
} else if (writable.destroyed) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
|
||||||
|
}
|
||||||
|
var buildOutgoingHttpHeaders = (headers) => {
|
||||||
|
const res = {};
|
||||||
|
if (!(headers instanceof Headers)) {
|
||||||
|
headers = new Headers(headers ?? void 0);
|
||||||
|
}
|
||||||
|
const cookies = [];
|
||||||
|
for (const [k, v] of headers) {
|
||||||
|
if (k === "set-cookie") {
|
||||||
|
cookies.push(v);
|
||||||
|
} else {
|
||||||
|
res[k] = v;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (cookies.length > 0) {
|
||||||
|
res["set-cookie"] = cookies;
|
||||||
|
}
|
||||||
|
res["content-type"] ??= "text/plain; charset=UTF-8";
|
||||||
|
return res;
|
||||||
|
};
|
||||||
|
|
||||||
|
// src/utils/response/constants.ts
|
||||||
|
var X_ALREADY_SENT = "x-hono-already-sent";
|
||||||
|
|
||||||
|
// src/globals.ts
|
||||||
|
var import_node_crypto = __toESM(require("crypto"));
|
||||||
|
if (typeof global.crypto === "undefined") {
|
||||||
|
global.crypto = import_node_crypto.default;
|
||||||
|
}
|
||||||
|
|
||||||
|
// src/listener.ts
|
||||||
|
var outgoingEnded = Symbol("outgoingEnded");
|
||||||
|
var incomingDraining = Symbol("incomingDraining");
|
||||||
|
var DRAIN_TIMEOUT_MS = 500;
|
||||||
|
var MAX_DRAIN_BYTES = 64 * 1024 * 1024;
|
||||||
|
var drainIncoming = (incoming) => {
|
||||||
|
const incomingWithDrainState = incoming;
|
||||||
|
if (incoming.destroyed || incomingWithDrainState[incomingDraining]) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
incomingWithDrainState[incomingDraining] = true;
|
||||||
|
if (incoming instanceof import_node_http22.Http2ServerRequest) {
|
||||||
|
try {
|
||||||
|
;
|
||||||
|
incoming.stream?.close?.(import_node_http22.constants.NGHTTP2_NO_ERROR);
|
||||||
|
} catch {
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let bytesRead = 0;
|
||||||
|
const cleanup = () => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
incoming.off("data", onData);
|
||||||
|
incoming.off("end", cleanup);
|
||||||
|
incoming.off("error", cleanup);
|
||||||
|
};
|
||||||
|
const forceClose = () => {
|
||||||
|
cleanup();
|
||||||
|
const socket = incoming.socket;
|
||||||
|
if (socket && !socket.destroyed) {
|
||||||
|
socket.destroySoon();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
|
||||||
|
timer.unref?.();
|
||||||
|
const onData = (chunk) => {
|
||||||
|
bytesRead += chunk.length;
|
||||||
|
if (bytesRead > MAX_DRAIN_BYTES) {
|
||||||
|
forceClose();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
incoming.on("data", onData);
|
||||||
|
incoming.on("end", cleanup);
|
||||||
|
incoming.on("error", cleanup);
|
||||||
|
incoming.resume();
|
||||||
|
};
|
||||||
|
var handleRequestError = () => new Response(null, {
|
||||||
|
status: 400
|
||||||
|
});
|
||||||
|
var handleFetchError = (e) => new Response(null, {
|
||||||
|
status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
|
||||||
|
});
|
||||||
|
var handleResponseError = (e, outgoing) => {
|
||||||
|
const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
|
||||||
|
if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
|
||||||
|
console.info("The user aborted a request.");
|
||||||
|
} else {
|
||||||
|
console.error(e);
|
||||||
|
if (!outgoing.headersSent) {
|
||||||
|
outgoing.writeHead(500, { "Content-Type": "text/plain" });
|
||||||
|
}
|
||||||
|
outgoing.end(`Error: ${err.message}`);
|
||||||
|
outgoing.destroy(err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var flushHeaders = (outgoing) => {
|
||||||
|
if ("flushHeaders" in outgoing && outgoing.writable) {
|
||||||
|
outgoing.flushHeaders();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var responseViaCache = async (res, outgoing) => {
|
||||||
|
let [status, body, header] = res[cacheKey];
|
||||||
|
let hasContentLength = false;
|
||||||
|
if (!header) {
|
||||||
|
header = { "content-type": "text/plain; charset=UTF-8" };
|
||||||
|
} else if (header instanceof Headers) {
|
||||||
|
hasContentLength = header.has("content-length");
|
||||||
|
header = buildOutgoingHttpHeaders(header);
|
||||||
|
} else if (Array.isArray(header)) {
|
||||||
|
const headerObj = new Headers(header);
|
||||||
|
hasContentLength = headerObj.has("content-length");
|
||||||
|
header = buildOutgoingHttpHeaders(headerObj);
|
||||||
|
} else {
|
||||||
|
for (const key in header) {
|
||||||
|
if (key.length === 14 && key.toLowerCase() === "content-length") {
|
||||||
|
hasContentLength = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!hasContentLength) {
|
||||||
|
if (typeof body === "string") {
|
||||||
|
header["Content-Length"] = Buffer.byteLength(body);
|
||||||
|
} else if (body instanceof Uint8Array) {
|
||||||
|
header["Content-Length"] = body.byteLength;
|
||||||
|
} else if (body instanceof Blob) {
|
||||||
|
header["Content-Length"] = body.size;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
outgoing.writeHead(status, header);
|
||||||
|
if (typeof body === "string" || body instanceof Uint8Array) {
|
||||||
|
outgoing.end(body);
|
||||||
|
} else if (body instanceof Blob) {
|
||||||
|
outgoing.end(new Uint8Array(await body.arrayBuffer()));
|
||||||
|
} else {
|
||||||
|
flushHeaders(outgoing);
|
||||||
|
await writeFromReadableStream(body, outgoing)?.catch(
|
||||||
|
(e) => handleResponseError(e, outgoing)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
;
|
||||||
|
outgoing[outgoingEnded]?.();
|
||||||
|
};
|
||||||
|
var isPromise = (res) => typeof res.then === "function";
|
||||||
|
var responseViaResponseObject = async (res, outgoing, options = {}) => {
|
||||||
|
if (isPromise(res)) {
|
||||||
|
if (options.errorHandler) {
|
||||||
|
try {
|
||||||
|
res = await res;
|
||||||
|
} catch (err) {
|
||||||
|
const errRes = await options.errorHandler(err);
|
||||||
|
if (!errRes) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
res = errRes;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
res = await res.catch(handleFetchError);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (cacheKey in res) {
|
||||||
|
return responseViaCache(res, outgoing);
|
||||||
|
}
|
||||||
|
const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
|
||||||
|
if (res.body) {
|
||||||
|
const reader = res.body.getReader();
|
||||||
|
const values = [];
|
||||||
|
let done = false;
|
||||||
|
let currentReadPromise = void 0;
|
||||||
|
if (resHeaderRecord["transfer-encoding"] !== "chunked") {
|
||||||
|
let maxReadCount = 2;
|
||||||
|
for (let i = 0; i < maxReadCount; i++) {
|
||||||
|
currentReadPromise ||= reader.read();
|
||||||
|
const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
|
||||||
|
console.error(e);
|
||||||
|
done = true;
|
||||||
|
});
|
||||||
|
if (!chunk) {
|
||||||
|
if (i === 1) {
|
||||||
|
await new Promise((resolve) => setTimeout(resolve));
|
||||||
|
maxReadCount = 3;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
currentReadPromise = void 0;
|
||||||
|
if (chunk.value) {
|
||||||
|
values.push(chunk.value);
|
||||||
|
}
|
||||||
|
if (chunk.done) {
|
||||||
|
done = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (done && !("content-length" in resHeaderRecord)) {
|
||||||
|
resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
outgoing.writeHead(res.status, resHeaderRecord);
|
||||||
|
values.forEach((value) => {
|
||||||
|
;
|
||||||
|
outgoing.write(value);
|
||||||
|
});
|
||||||
|
if (done) {
|
||||||
|
outgoing.end();
|
||||||
|
} else {
|
||||||
|
if (values.length === 0) {
|
||||||
|
flushHeaders(outgoing);
|
||||||
|
}
|
||||||
|
await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
|
||||||
|
}
|
||||||
|
} else if (resHeaderRecord[X_ALREADY_SENT]) {
|
||||||
|
} else {
|
||||||
|
outgoing.writeHead(res.status, resHeaderRecord);
|
||||||
|
outgoing.end();
|
||||||
|
}
|
||||||
|
;
|
||||||
|
outgoing[outgoingEnded]?.();
|
||||||
|
};
|
||||||
|
var getRequestListener = (fetchCallback, options = {}) => {
|
||||||
|
const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
|
||||||
|
if (options.overrideGlobalObjects !== false && global.Request !== Request) {
|
||||||
|
Object.defineProperty(global, "Request", {
|
||||||
|
value: Request
|
||||||
|
});
|
||||||
|
Object.defineProperty(global, "Response", {
|
||||||
|
value: Response2
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return async (incoming, outgoing) => {
|
||||||
|
let res, req;
|
||||||
|
try {
|
||||||
|
req = newRequest(incoming, options.hostname);
|
||||||
|
let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
|
||||||
|
if (!incomingEnded) {
|
||||||
|
;
|
||||||
|
incoming[wrapBodyStream] = true;
|
||||||
|
incoming.on("end", () => {
|
||||||
|
incomingEnded = true;
|
||||||
|
});
|
||||||
|
if (incoming instanceof import_node_http22.Http2ServerRequest) {
|
||||||
|
;
|
||||||
|
outgoing[outgoingEnded] = () => {
|
||||||
|
if (!incomingEnded) {
|
||||||
|
setTimeout(() => {
|
||||||
|
if (!incomingEnded) {
|
||||||
|
setTimeout(() => {
|
||||||
|
drainIncoming(incoming);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
outgoing.on("finish", () => {
|
||||||
|
if (!incomingEnded) {
|
||||||
|
drainIncoming(incoming);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
outgoing.on("close", () => {
|
||||||
|
const abortController = req[abortControllerKey];
|
||||||
|
if (abortController) {
|
||||||
|
if (incoming.errored) {
|
||||||
|
req[abortControllerKey].abort(incoming.errored.toString());
|
||||||
|
} else if (!outgoing.writableFinished) {
|
||||||
|
req[abortControllerKey].abort("Client connection prematurely closed.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!incomingEnded) {
|
||||||
|
setTimeout(() => {
|
||||||
|
if (!incomingEnded) {
|
||||||
|
setTimeout(() => {
|
||||||
|
drainIncoming(incoming);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
res = fetchCallback(req, { incoming, outgoing });
|
||||||
|
if (cacheKey in res) {
|
||||||
|
return responseViaCache(res, outgoing);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
if (!res) {
|
||||||
|
if (options.errorHandler) {
|
||||||
|
res = await options.errorHandler(req ? e : toRequestError(e));
|
||||||
|
if (!res) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} else if (!req) {
|
||||||
|
res = handleRequestError();
|
||||||
|
} else {
|
||||||
|
res = handleFetchError(e);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return handleResponseError(e, outgoing);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return await responseViaResponseObject(res, outgoing, options);
|
||||||
|
} catch (e) {
|
||||||
|
return handleResponseError(e, outgoing);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
// src/vercel.ts
|
||||||
|
var handle = (app) => {
|
||||||
|
return getRequestListener(app.fetch);
|
||||||
|
};
|
||||||
|
// Annotate the CommonJS export names for ESM import in node:
|
||||||
|
0 && (module.exports = {
|
||||||
|
handle
|
||||||
|
});
|
||||||
640
node_modules/@hono/node-server/dist/vercel.mjs
generated
vendored
Normal file
640
node_modules/@hono/node-server/dist/vercel.mjs
generated
vendored
Normal file
@@ -0,0 +1,640 @@
|
|||||||
|
// src/listener.ts
|
||||||
|
import { Http2ServerRequest as Http2ServerRequest2, constants as h2constants } from "http2";
|
||||||
|
|
||||||
|
// src/request.ts
|
||||||
|
import { Http2ServerRequest } from "http2";
|
||||||
|
import { Readable } from "stream";
|
||||||
|
var RequestError = class extends Error {
|
||||||
|
constructor(message, options) {
|
||||||
|
super(message, options);
|
||||||
|
this.name = "RequestError";
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var toRequestError = (e) => {
|
||||||
|
if (e instanceof RequestError) {
|
||||||
|
return e;
|
||||||
|
}
|
||||||
|
return new RequestError(e.message, { cause: e });
|
||||||
|
};
|
||||||
|
var GlobalRequest = global.Request;
|
||||||
|
var Request = class extends GlobalRequest {
|
||||||
|
constructor(input, options) {
|
||||||
|
if (typeof input === "object" && getRequestCache in input) {
|
||||||
|
input = input[getRequestCache]();
|
||||||
|
}
|
||||||
|
if (typeof options?.body?.getReader !== "undefined") {
|
||||||
|
;
|
||||||
|
options.duplex ??= "half";
|
||||||
|
}
|
||||||
|
super(input, options);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var newHeadersFromIncoming = (incoming) => {
|
||||||
|
const headerRecord = [];
|
||||||
|
const rawHeaders = incoming.rawHeaders;
|
||||||
|
for (let i = 0; i < rawHeaders.length; i += 2) {
|
||||||
|
const { [i]: key, [i + 1]: value } = rawHeaders;
|
||||||
|
if (key.charCodeAt(0) !== /*:*/
|
||||||
|
58) {
|
||||||
|
headerRecord.push([key, value]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new Headers(headerRecord);
|
||||||
|
};
|
||||||
|
var wrapBodyStream = Symbol("wrapBodyStream");
|
||||||
|
var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
|
||||||
|
const init = {
|
||||||
|
method,
|
||||||
|
headers,
|
||||||
|
signal: abortController.signal
|
||||||
|
};
|
||||||
|
if (method === "TRACE") {
|
||||||
|
init.method = "GET";
|
||||||
|
const req = new Request(url, init);
|
||||||
|
Object.defineProperty(req, "method", {
|
||||||
|
get() {
|
||||||
|
return "TRACE";
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return req;
|
||||||
|
}
|
||||||
|
if (!(method === "GET" || method === "HEAD")) {
|
||||||
|
if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
|
||||||
|
init.body = new ReadableStream({
|
||||||
|
start(controller) {
|
||||||
|
controller.enqueue(incoming.rawBody);
|
||||||
|
controller.close();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else if (incoming[wrapBodyStream]) {
|
||||||
|
let reader;
|
||||||
|
init.body = new ReadableStream({
|
||||||
|
async pull(controller) {
|
||||||
|
try {
|
||||||
|
reader ||= Readable.toWeb(incoming).getReader();
|
||||||
|
const { done, value } = await reader.read();
|
||||||
|
if (done) {
|
||||||
|
controller.close();
|
||||||
|
} else {
|
||||||
|
controller.enqueue(value);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
controller.error(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
init.body = Readable.toWeb(incoming);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return new Request(url, init);
|
||||||
|
};
|
||||||
|
var getRequestCache = Symbol("getRequestCache");
|
||||||
|
var requestCache = Symbol("requestCache");
|
||||||
|
var incomingKey = Symbol("incomingKey");
|
||||||
|
var urlKey = Symbol("urlKey");
|
||||||
|
var headersKey = Symbol("headersKey");
|
||||||
|
var abortControllerKey = Symbol("abortControllerKey");
|
||||||
|
var getAbortController = Symbol("getAbortController");
|
||||||
|
var requestPrototype = {
|
||||||
|
get method() {
|
||||||
|
return this[incomingKey].method || "GET";
|
||||||
|
},
|
||||||
|
get url() {
|
||||||
|
return this[urlKey];
|
||||||
|
},
|
||||||
|
get headers() {
|
||||||
|
return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
|
||||||
|
},
|
||||||
|
[getAbortController]() {
|
||||||
|
this[getRequestCache]();
|
||||||
|
return this[abortControllerKey];
|
||||||
|
},
|
||||||
|
[getRequestCache]() {
|
||||||
|
this[abortControllerKey] ||= new AbortController();
|
||||||
|
return this[requestCache] ||= newRequestFromIncoming(
|
||||||
|
this.method,
|
||||||
|
this[urlKey],
|
||||||
|
this.headers,
|
||||||
|
this[incomingKey],
|
||||||
|
this[abortControllerKey]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
[
|
||||||
|
"body",
|
||||||
|
"bodyUsed",
|
||||||
|
"cache",
|
||||||
|
"credentials",
|
||||||
|
"destination",
|
||||||
|
"integrity",
|
||||||
|
"mode",
|
||||||
|
"redirect",
|
||||||
|
"referrer",
|
||||||
|
"referrerPolicy",
|
||||||
|
"signal",
|
||||||
|
"keepalive"
|
||||||
|
].forEach((k) => {
|
||||||
|
Object.defineProperty(requestPrototype, k, {
|
||||||
|
get() {
|
||||||
|
return this[getRequestCache]()[k];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
|
||||||
|
Object.defineProperty(requestPrototype, k, {
|
||||||
|
value: function() {
|
||||||
|
return this[getRequestCache]()[k]();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
Object.defineProperty(requestPrototype, Symbol.for("nodejs.util.inspect.custom"), {
|
||||||
|
value: function(depth, options, inspectFn) {
|
||||||
|
const props = {
|
||||||
|
method: this.method,
|
||||||
|
url: this.url,
|
||||||
|
headers: this.headers,
|
||||||
|
nativeRequest: this[requestCache]
|
||||||
|
};
|
||||||
|
return `Request (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Object.setPrototypeOf(requestPrototype, Request.prototype);
|
||||||
|
var newRequest = (incoming, defaultHostname) => {
|
||||||
|
const req = Object.create(requestPrototype);
|
||||||
|
req[incomingKey] = incoming;
|
||||||
|
const incomingUrl = incoming.url || "";
|
||||||
|
if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
|
||||||
|
(incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
|
||||||
|
if (incoming instanceof Http2ServerRequest) {
|
||||||
|
throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const url2 = new URL(incomingUrl);
|
||||||
|
req[urlKey] = url2.href;
|
||||||
|
} catch (e) {
|
||||||
|
throw new RequestError("Invalid absolute URL", { cause: e });
|
||||||
|
}
|
||||||
|
return req;
|
||||||
|
}
|
||||||
|
const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
|
||||||
|
if (!host) {
|
||||||
|
throw new RequestError("Missing host header");
|
||||||
|
}
|
||||||
|
let scheme;
|
||||||
|
if (incoming instanceof Http2ServerRequest) {
|
||||||
|
scheme = incoming.scheme;
|
||||||
|
if (!(scheme === "http" || scheme === "https")) {
|
||||||
|
throw new RequestError("Unsupported scheme");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
|
||||||
|
}
|
||||||
|
const url = new URL(`${scheme}://${host}${incomingUrl}`);
|
||||||
|
if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
|
||||||
|
throw new RequestError("Invalid host header");
|
||||||
|
}
|
||||||
|
req[urlKey] = url.href;
|
||||||
|
return req;
|
||||||
|
};
|
||||||
|
|
||||||
|
// src/response.ts
|
||||||
|
var responseCache = Symbol("responseCache");
|
||||||
|
var getResponseCache = Symbol("getResponseCache");
|
||||||
|
var cacheKey = Symbol("cache");
|
||||||
|
var GlobalResponse = global.Response;
|
||||||
|
var Response2 = class _Response {
|
||||||
|
#body;
|
||||||
|
#init;
|
||||||
|
[getResponseCache]() {
|
||||||
|
delete this[cacheKey];
|
||||||
|
return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
|
||||||
|
}
|
||||||
|
constructor(body, init) {
|
||||||
|
let headers;
|
||||||
|
this.#body = body;
|
||||||
|
if (init instanceof _Response) {
|
||||||
|
const cachedGlobalResponse = init[responseCache];
|
||||||
|
if (cachedGlobalResponse) {
|
||||||
|
this.#init = cachedGlobalResponse;
|
||||||
|
this[getResponseCache]();
|
||||||
|
return;
|
||||||
|
} else {
|
||||||
|
this.#init = init.#init;
|
||||||
|
headers = new Headers(init.#init.headers);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
this.#init = init;
|
||||||
|
}
|
||||||
|
if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
|
||||||
|
;
|
||||||
|
this[cacheKey] = [init?.status || 200, body, headers || init?.headers];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
get headers() {
|
||||||
|
const cache = this[cacheKey];
|
||||||
|
if (cache) {
|
||||||
|
if (!(cache[2] instanceof Headers)) {
|
||||||
|
cache[2] = new Headers(
|
||||||
|
cache[2] || { "content-type": "text/plain; charset=UTF-8" }
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return cache[2];
|
||||||
|
}
|
||||||
|
return this[getResponseCache]().headers;
|
||||||
|
}
|
||||||
|
get status() {
|
||||||
|
return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
|
||||||
|
}
|
||||||
|
get ok() {
|
||||||
|
const status = this.status;
|
||||||
|
return status >= 200 && status < 300;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
|
||||||
|
Object.defineProperty(Response2.prototype, k, {
|
||||||
|
get() {
|
||||||
|
return this[getResponseCache]()[k];
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
|
||||||
|
Object.defineProperty(Response2.prototype, k, {
|
||||||
|
value: function() {
|
||||||
|
return this[getResponseCache]()[k]();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
Object.defineProperty(Response2.prototype, Symbol.for("nodejs.util.inspect.custom"), {
|
||||||
|
value: function(depth, options, inspectFn) {
|
||||||
|
const props = {
|
||||||
|
status: this.status,
|
||||||
|
headers: this.headers,
|
||||||
|
ok: this.ok,
|
||||||
|
nativeResponse: this[responseCache]
|
||||||
|
};
|
||||||
|
return `Response (lightweight) ${inspectFn(props, { ...options, depth: depth == null ? null : depth - 1 })}`;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
Object.setPrototypeOf(Response2, GlobalResponse);
|
||||||
|
Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
|
||||||
|
|
||||||
|
// src/utils.ts
|
||||||
|
async function readWithoutBlocking(readPromise) {
|
||||||
|
return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
|
||||||
|
}
|
||||||
|
function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
|
||||||
|
const cancel = (error) => {
|
||||||
|
reader.cancel(error).catch(() => {
|
||||||
|
});
|
||||||
|
};
|
||||||
|
writable.on("close", cancel);
|
||||||
|
writable.on("error", cancel);
|
||||||
|
(currentReadPromise ?? reader.read()).then(flow, handleStreamError);
|
||||||
|
return reader.closed.finally(() => {
|
||||||
|
writable.off("close", cancel);
|
||||||
|
writable.off("error", cancel);
|
||||||
|
});
|
||||||
|
function handleStreamError(error) {
|
||||||
|
if (error) {
|
||||||
|
writable.destroy(error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function onDrain() {
|
||||||
|
reader.read().then(flow, handleStreamError);
|
||||||
|
}
|
||||||
|
function flow({ done, value }) {
|
||||||
|
try {
|
||||||
|
if (done) {
|
||||||
|
writable.end();
|
||||||
|
} else if (!writable.write(value)) {
|
||||||
|
writable.once("drain", onDrain);
|
||||||
|
} else {
|
||||||
|
return reader.read().then(flow, handleStreamError);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
handleStreamError(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
function writeFromReadableStream(stream, writable) {
|
||||||
|
if (stream.locked) {
|
||||||
|
throw new TypeError("ReadableStream is locked.");
|
||||||
|
} else if (writable.destroyed) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
|
||||||
|
}
|
||||||
|
var buildOutgoingHttpHeaders = (headers) => {
|
||||||
|
const res = {};
|
||||||
|
if (!(headers instanceof Headers)) {
|
||||||
|
headers = new Headers(headers ?? void 0);
|
||||||
|
}
|
||||||
|
const cookies = [];
|
||||||
|
for (const [k, v] of headers) {
|
||||||
|
if (k === "set-cookie") {
|
||||||
|
cookies.push(v);
|
||||||
|
} else {
|
||||||
|
res[k] = v;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (cookies.length > 0) {
|
||||||
|
res["set-cookie"] = cookies;
|
||||||
|
}
|
||||||
|
res["content-type"] ??= "text/plain; charset=UTF-8";
|
||||||
|
return res;
|
||||||
|
};
|
||||||
|
|
||||||
|
// src/utils/response/constants.ts
|
||||||
|
var X_ALREADY_SENT = "x-hono-already-sent";
|
||||||
|
|
||||||
|
// src/globals.ts
|
||||||
|
import crypto from "crypto";
|
||||||
|
if (typeof global.crypto === "undefined") {
|
||||||
|
global.crypto = crypto;
|
||||||
|
}
|
||||||
|
|
||||||
|
// src/listener.ts
|
||||||
|
var outgoingEnded = Symbol("outgoingEnded");
|
||||||
|
var incomingDraining = Symbol("incomingDraining");
|
||||||
|
var DRAIN_TIMEOUT_MS = 500;
|
||||||
|
var MAX_DRAIN_BYTES = 64 * 1024 * 1024;
|
||||||
|
var drainIncoming = (incoming) => {
|
||||||
|
const incomingWithDrainState = incoming;
|
||||||
|
if (incoming.destroyed || incomingWithDrainState[incomingDraining]) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
incomingWithDrainState[incomingDraining] = true;
|
||||||
|
if (incoming instanceof Http2ServerRequest2) {
|
||||||
|
try {
|
||||||
|
;
|
||||||
|
incoming.stream?.close?.(h2constants.NGHTTP2_NO_ERROR);
|
||||||
|
} catch {
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
let bytesRead = 0;
|
||||||
|
const cleanup = () => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
incoming.off("data", onData);
|
||||||
|
incoming.off("end", cleanup);
|
||||||
|
incoming.off("error", cleanup);
|
||||||
|
};
|
||||||
|
const forceClose = () => {
|
||||||
|
cleanup();
|
||||||
|
const socket = incoming.socket;
|
||||||
|
if (socket && !socket.destroyed) {
|
||||||
|
socket.destroySoon();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const timer = setTimeout(forceClose, DRAIN_TIMEOUT_MS);
|
||||||
|
timer.unref?.();
|
||||||
|
const onData = (chunk) => {
|
||||||
|
bytesRead += chunk.length;
|
||||||
|
if (bytesRead > MAX_DRAIN_BYTES) {
|
||||||
|
forceClose();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
incoming.on("data", onData);
|
||||||
|
incoming.on("end", cleanup);
|
||||||
|
incoming.on("error", cleanup);
|
||||||
|
incoming.resume();
|
||||||
|
};
|
||||||
|
var handleRequestError = () => new Response(null, {
|
||||||
|
status: 400
|
||||||
|
});
|
||||||
|
var handleFetchError = (e) => new Response(null, {
|
||||||
|
status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
|
||||||
|
});
|
||||||
|
var handleResponseError = (e, outgoing) => {
|
||||||
|
const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
|
||||||
|
if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
|
||||||
|
console.info("The user aborted a request.");
|
||||||
|
} else {
|
||||||
|
console.error(e);
|
||||||
|
if (!outgoing.headersSent) {
|
||||||
|
outgoing.writeHead(500, { "Content-Type": "text/plain" });
|
||||||
|
}
|
||||||
|
outgoing.end(`Error: ${err.message}`);
|
||||||
|
outgoing.destroy(err);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var flushHeaders = (outgoing) => {
|
||||||
|
if ("flushHeaders" in outgoing && outgoing.writable) {
|
||||||
|
outgoing.flushHeaders();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var responseViaCache = async (res, outgoing) => {
|
||||||
|
let [status, body, header] = res[cacheKey];
|
||||||
|
let hasContentLength = false;
|
||||||
|
if (!header) {
|
||||||
|
header = { "content-type": "text/plain; charset=UTF-8" };
|
||||||
|
} else if (header instanceof Headers) {
|
||||||
|
hasContentLength = header.has("content-length");
|
||||||
|
header = buildOutgoingHttpHeaders(header);
|
||||||
|
} else if (Array.isArray(header)) {
|
||||||
|
const headerObj = new Headers(header);
|
||||||
|
hasContentLength = headerObj.has("content-length");
|
||||||
|
header = buildOutgoingHttpHeaders(headerObj);
|
||||||
|
} else {
|
||||||
|
for (const key in header) {
|
||||||
|
if (key.length === 14 && key.toLowerCase() === "content-length") {
|
||||||
|
hasContentLength = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!hasContentLength) {
|
||||||
|
if (typeof body === "string") {
|
||||||
|
header["Content-Length"] = Buffer.byteLength(body);
|
||||||
|
} else if (body instanceof Uint8Array) {
|
||||||
|
header["Content-Length"] = body.byteLength;
|
||||||
|
} else if (body instanceof Blob) {
|
||||||
|
header["Content-Length"] = body.size;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
outgoing.writeHead(status, header);
|
||||||
|
if (typeof body === "string" || body instanceof Uint8Array) {
|
||||||
|
outgoing.end(body);
|
||||||
|
} else if (body instanceof Blob) {
|
||||||
|
outgoing.end(new Uint8Array(await body.arrayBuffer()));
|
||||||
|
} else {
|
||||||
|
flushHeaders(outgoing);
|
||||||
|
await writeFromReadableStream(body, outgoing)?.catch(
|
||||||
|
(e) => handleResponseError(e, outgoing)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
;
|
||||||
|
outgoing[outgoingEnded]?.();
|
||||||
|
};
|
||||||
|
var isPromise = (res) => typeof res.then === "function";
|
||||||
|
var responseViaResponseObject = async (res, outgoing, options = {}) => {
|
||||||
|
if (isPromise(res)) {
|
||||||
|
if (options.errorHandler) {
|
||||||
|
try {
|
||||||
|
res = await res;
|
||||||
|
} catch (err) {
|
||||||
|
const errRes = await options.errorHandler(err);
|
||||||
|
if (!errRes) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
res = errRes;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
res = await res.catch(handleFetchError);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (cacheKey in res) {
|
||||||
|
return responseViaCache(res, outgoing);
|
||||||
|
}
|
||||||
|
const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
|
||||||
|
if (res.body) {
|
||||||
|
const reader = res.body.getReader();
|
||||||
|
const values = [];
|
||||||
|
let done = false;
|
||||||
|
let currentReadPromise = void 0;
|
||||||
|
if (resHeaderRecord["transfer-encoding"] !== "chunked") {
|
||||||
|
let maxReadCount = 2;
|
||||||
|
for (let i = 0; i < maxReadCount; i++) {
|
||||||
|
currentReadPromise ||= reader.read();
|
||||||
|
const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
|
||||||
|
console.error(e);
|
||||||
|
done = true;
|
||||||
|
});
|
||||||
|
if (!chunk) {
|
||||||
|
if (i === 1) {
|
||||||
|
await new Promise((resolve) => setTimeout(resolve));
|
||||||
|
maxReadCount = 3;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
currentReadPromise = void 0;
|
||||||
|
if (chunk.value) {
|
||||||
|
values.push(chunk.value);
|
||||||
|
}
|
||||||
|
if (chunk.done) {
|
||||||
|
done = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (done && !("content-length" in resHeaderRecord)) {
|
||||||
|
resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
outgoing.writeHead(res.status, resHeaderRecord);
|
||||||
|
values.forEach((value) => {
|
||||||
|
;
|
||||||
|
outgoing.write(value);
|
||||||
|
});
|
||||||
|
if (done) {
|
||||||
|
outgoing.end();
|
||||||
|
} else {
|
||||||
|
if (values.length === 0) {
|
||||||
|
flushHeaders(outgoing);
|
||||||
|
}
|
||||||
|
await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
|
||||||
|
}
|
||||||
|
} else if (resHeaderRecord[X_ALREADY_SENT]) {
|
||||||
|
} else {
|
||||||
|
outgoing.writeHead(res.status, resHeaderRecord);
|
||||||
|
outgoing.end();
|
||||||
|
}
|
||||||
|
;
|
||||||
|
outgoing[outgoingEnded]?.();
|
||||||
|
};
|
||||||
|
var getRequestListener = (fetchCallback, options = {}) => {
|
||||||
|
const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
|
||||||
|
if (options.overrideGlobalObjects !== false && global.Request !== Request) {
|
||||||
|
Object.defineProperty(global, "Request", {
|
||||||
|
value: Request
|
||||||
|
});
|
||||||
|
Object.defineProperty(global, "Response", {
|
||||||
|
value: Response2
|
||||||
|
});
|
||||||
|
}
|
||||||
|
return async (incoming, outgoing) => {
|
||||||
|
let res, req;
|
||||||
|
try {
|
||||||
|
req = newRequest(incoming, options.hostname);
|
||||||
|
let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
|
||||||
|
if (!incomingEnded) {
|
||||||
|
;
|
||||||
|
incoming[wrapBodyStream] = true;
|
||||||
|
incoming.on("end", () => {
|
||||||
|
incomingEnded = true;
|
||||||
|
});
|
||||||
|
if (incoming instanceof Http2ServerRequest2) {
|
||||||
|
;
|
||||||
|
outgoing[outgoingEnded] = () => {
|
||||||
|
if (!incomingEnded) {
|
||||||
|
setTimeout(() => {
|
||||||
|
if (!incomingEnded) {
|
||||||
|
setTimeout(() => {
|
||||||
|
drainIncoming(incoming);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
outgoing.on("finish", () => {
|
||||||
|
if (!incomingEnded) {
|
||||||
|
drainIncoming(incoming);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
outgoing.on("close", () => {
|
||||||
|
const abortController = req[abortControllerKey];
|
||||||
|
if (abortController) {
|
||||||
|
if (incoming.errored) {
|
||||||
|
req[abortControllerKey].abort(incoming.errored.toString());
|
||||||
|
} else if (!outgoing.writableFinished) {
|
||||||
|
req[abortControllerKey].abort("Client connection prematurely closed.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!incomingEnded) {
|
||||||
|
setTimeout(() => {
|
||||||
|
if (!incomingEnded) {
|
||||||
|
setTimeout(() => {
|
||||||
|
drainIncoming(incoming);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
res = fetchCallback(req, { incoming, outgoing });
|
||||||
|
if (cacheKey in res) {
|
||||||
|
return responseViaCache(res, outgoing);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
if (!res) {
|
||||||
|
if (options.errorHandler) {
|
||||||
|
res = await options.errorHandler(req ? e : toRequestError(e));
|
||||||
|
if (!res) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} else if (!req) {
|
||||||
|
res = handleRequestError();
|
||||||
|
} else {
|
||||||
|
res = handleFetchError(e);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return handleResponseError(e, outgoing);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
return await responseViaResponseObject(res, outgoing, options);
|
||||||
|
} catch (e) {
|
||||||
|
return handleResponseError(e, outgoing);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
// src/vercel.ts
|
||||||
|
var handle = (app) => {
|
||||||
|
return getRequestListener(app.fetch);
|
||||||
|
};
|
||||||
|
export {
|
||||||
|
handle
|
||||||
|
};
|
||||||
103
node_modules/@hono/node-server/package.json
generated
vendored
Normal file
103
node_modules/@hono/node-server/package.json
generated
vendored
Normal file
@@ -0,0 +1,103 @@
|
|||||||
|
{
|
||||||
|
"name": "@hono/node-server",
|
||||||
|
"version": "1.19.14",
|
||||||
|
"description": "Node.js Adapter for Hono",
|
||||||
|
"main": "dist/index.js",
|
||||||
|
"types": "dist/index.d.ts",
|
||||||
|
"files": [
|
||||||
|
"dist"
|
||||||
|
],
|
||||||
|
"exports": {
|
||||||
|
".": {
|
||||||
|
"types": "./dist/index.d.ts",
|
||||||
|
"require": "./dist/index.js",
|
||||||
|
"import": "./dist/index.mjs"
|
||||||
|
},
|
||||||
|
"./serve-static": {
|
||||||
|
"types": "./dist/serve-static.d.ts",
|
||||||
|
"require": "./dist/serve-static.js",
|
||||||
|
"import": "./dist/serve-static.mjs"
|
||||||
|
},
|
||||||
|
"./vercel": {
|
||||||
|
"types": "./dist/vercel.d.ts",
|
||||||
|
"require": "./dist/vercel.js",
|
||||||
|
"import": "./dist/vercel.mjs"
|
||||||
|
},
|
||||||
|
"./utils/*": {
|
||||||
|
"types": "./dist/utils/*.d.ts",
|
||||||
|
"require": "./dist/utils/*.js",
|
||||||
|
"import": "./dist/utils/*.mjs"
|
||||||
|
},
|
||||||
|
"./conninfo": {
|
||||||
|
"types": "./dist/conninfo.d.ts",
|
||||||
|
"require": "./dist/conninfo.js",
|
||||||
|
"import": "./dist/conninfo.mjs"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"typesVersions": {
|
||||||
|
"*": {
|
||||||
|
".": [
|
||||||
|
"./dist/index.d.ts"
|
||||||
|
],
|
||||||
|
"serve-static": [
|
||||||
|
"./dist/serve-static.d.ts"
|
||||||
|
],
|
||||||
|
"vercel": [
|
||||||
|
"./dist/vercel.d.ts"
|
||||||
|
],
|
||||||
|
"utils/*": [
|
||||||
|
"./dist/utils/*.d.ts"
|
||||||
|
],
|
||||||
|
"conninfo": [
|
||||||
|
"./dist/conninfo.d.ts"
|
||||||
|
]
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"scripts": {
|
||||||
|
"test": "node --expose-gc node_modules/jest/bin/jest.js",
|
||||||
|
"build": "tsup --external hono",
|
||||||
|
"watch": "tsup --watch",
|
||||||
|
"postbuild": "publint",
|
||||||
|
"prerelease": "bun run build && bun run test",
|
||||||
|
"release": "np",
|
||||||
|
"lint": "eslint src test",
|
||||||
|
"lint:fix": "eslint src test --fix",
|
||||||
|
"format": "prettier --check \"src/**/*.{js,ts}\" \"test/**/*.{js,ts}\"",
|
||||||
|
"format:fix": "prettier --write \"src/**/*.{js,ts}\" \"test/**/*.{js,ts}\""
|
||||||
|
},
|
||||||
|
"license": "MIT",
|
||||||
|
"repository": {
|
||||||
|
"type": "git",
|
||||||
|
"url": "https://github.com/honojs/node-server.git"
|
||||||
|
},
|
||||||
|
"homepage": "https://github.com/honojs/node-server",
|
||||||
|
"author": "Yusuke Wada <yusuke@kamawada.com> (https://github.com/yusukebe)",
|
||||||
|
"publishConfig": {
|
||||||
|
"registry": "https://registry.npmjs.org",
|
||||||
|
"access": "public"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18.14.1"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@hono/eslint-config": "^1.0.1",
|
||||||
|
"@types/jest": "^29.5.3",
|
||||||
|
"@types/node": "^20.10.0",
|
||||||
|
"@types/supertest": "^2.0.12",
|
||||||
|
"@whatwg-node/fetch": "^0.9.14",
|
||||||
|
"eslint": "^9.10.0",
|
||||||
|
"hono": "^4.4.10",
|
||||||
|
"jest": "^29.6.1",
|
||||||
|
"np": "^7.7.0",
|
||||||
|
"prettier": "^3.2.4",
|
||||||
|
"publint": "^0.1.16",
|
||||||
|
"supertest": "^6.3.3",
|
||||||
|
"ts-jest": "^29.1.1",
|
||||||
|
"tsup": "^7.2.0",
|
||||||
|
"typescript": "^5.3.2"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"hono": "^4"
|
||||||
|
},
|
||||||
|
"packageManager": "bun@1.2.20"
|
||||||
|
}
|
||||||
19
node_modules/@jridgewell/resolve-uri/LICENSE
generated
vendored
Normal file
19
node_modules/@jridgewell/resolve-uri/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
Copyright 2019 Justin Ridgewell <jridgewell@google.com>
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in
|
||||||
|
all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
40
node_modules/@jridgewell/resolve-uri/README.md
generated
vendored
Normal file
40
node_modules/@jridgewell/resolve-uri/README.md
generated
vendored
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
# @jridgewell/resolve-uri
|
||||||
|
|
||||||
|
> Resolve a URI relative to an optional base URI
|
||||||
|
|
||||||
|
Resolve any combination of absolute URIs, protocol-realtive URIs, absolute paths, or relative paths.
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
```sh
|
||||||
|
npm install @jridgewell/resolve-uri
|
||||||
|
```
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
function resolve(input: string, base?: string): string;
|
||||||
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
import resolve from '@jridgewell/resolve-uri';
|
||||||
|
|
||||||
|
resolve('foo', 'https://example.com'); // => 'https://example.com/foo'
|
||||||
|
```
|
||||||
|
|
||||||
|
| Input | Base | Resolution | Explanation |
|
||||||
|
|-----------------------|-------------------------|--------------------------------|--------------------------------------------------------------|
|
||||||
|
| `https://example.com` | _any_ | `https://example.com/` | Input is normalized only |
|
||||||
|
| `//example.com` | `https://base.com/` | `https://example.com/` | Input inherits the base's protocol |
|
||||||
|
| `//example.com` | _rest_ | `//example.com/` | Input is normalized only |
|
||||||
|
| `/example` | `https://base.com/` | `https://base.com/example` | Input inherits the base's origin |
|
||||||
|
| `/example` | `//base.com/` | `//base.com/example` | Input inherits the base's host and remains protocol relative |
|
||||||
|
| `/example` | _rest_ | `/example` | Input is normalized only |
|
||||||
|
| `example` | `https://base.com/dir/` | `https://base.com/dir/example` | Input is joined with the base |
|
||||||
|
| `example` | `https://base.com/file` | `https://base.com/example` | Input is joined with the base without its file |
|
||||||
|
| `example` | `//base.com/dir/` | `//base.com/dir/example` | Input is joined with the base's last directory |
|
||||||
|
| `example` | `//base.com/file` | `//base.com/example` | Input is joined with the base without its file |
|
||||||
|
| `example` | `/base/dir/` | `/base/dir/example` | Input is joined with the base's last directory |
|
||||||
|
| `example` | `/base/file` | `/base/example` | Input is joined with the base without its file |
|
||||||
|
| `example` | `base/dir/` | `base/dir/example` | Input is joined with the base's last directory |
|
||||||
|
| `example` | `base/file` | `base/example` | Input is joined with the base without its file |
|
||||||
232
node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs
generated
vendored
Normal file
232
node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs
generated
vendored
Normal file
@@ -0,0 +1,232 @@
|
|||||||
|
// Matches the scheme of a URL, eg "http://"
|
||||||
|
const schemeRegex = /^[\w+.-]+:\/\//;
|
||||||
|
/**
|
||||||
|
* Matches the parts of a URL:
|
||||||
|
* 1. Scheme, including ":", guaranteed.
|
||||||
|
* 2. User/password, including "@", optional.
|
||||||
|
* 3. Host, guaranteed.
|
||||||
|
* 4. Port, including ":", optional.
|
||||||
|
* 5. Path, including "/", optional.
|
||||||
|
* 6. Query, including "?", optional.
|
||||||
|
* 7. Hash, including "#", optional.
|
||||||
|
*/
|
||||||
|
const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
|
||||||
|
/**
|
||||||
|
* File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start
|
||||||
|
* with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).
|
||||||
|
*
|
||||||
|
* 1. Host, optional.
|
||||||
|
* 2. Path, which may include "/", guaranteed.
|
||||||
|
* 3. Query, including "?", optional.
|
||||||
|
* 4. Hash, including "#", optional.
|
||||||
|
*/
|
||||||
|
const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;
|
||||||
|
function isAbsoluteUrl(input) {
|
||||||
|
return schemeRegex.test(input);
|
||||||
|
}
|
||||||
|
function isSchemeRelativeUrl(input) {
|
||||||
|
return input.startsWith('//');
|
||||||
|
}
|
||||||
|
function isAbsolutePath(input) {
|
||||||
|
return input.startsWith('/');
|
||||||
|
}
|
||||||
|
function isFileUrl(input) {
|
||||||
|
return input.startsWith('file:');
|
||||||
|
}
|
||||||
|
function isRelative(input) {
|
||||||
|
return /^[.?#]/.test(input);
|
||||||
|
}
|
||||||
|
function parseAbsoluteUrl(input) {
|
||||||
|
const match = urlRegex.exec(input);
|
||||||
|
return makeUrl(match[1], match[2] || '', match[3], match[4] || '', match[5] || '/', match[6] || '', match[7] || '');
|
||||||
|
}
|
||||||
|
function parseFileUrl(input) {
|
||||||
|
const match = fileRegex.exec(input);
|
||||||
|
const path = match[2];
|
||||||
|
return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path, match[3] || '', match[4] || '');
|
||||||
|
}
|
||||||
|
function makeUrl(scheme, user, host, port, path, query, hash) {
|
||||||
|
return {
|
||||||
|
scheme,
|
||||||
|
user,
|
||||||
|
host,
|
||||||
|
port,
|
||||||
|
path,
|
||||||
|
query,
|
||||||
|
hash,
|
||||||
|
type: 7 /* Absolute */,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
function parseUrl(input) {
|
||||||
|
if (isSchemeRelativeUrl(input)) {
|
||||||
|
const url = parseAbsoluteUrl('http:' + input);
|
||||||
|
url.scheme = '';
|
||||||
|
url.type = 6 /* SchemeRelative */;
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
if (isAbsolutePath(input)) {
|
||||||
|
const url = parseAbsoluteUrl('http://foo.com' + input);
|
||||||
|
url.scheme = '';
|
||||||
|
url.host = '';
|
||||||
|
url.type = 5 /* AbsolutePath */;
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
if (isFileUrl(input))
|
||||||
|
return parseFileUrl(input);
|
||||||
|
if (isAbsoluteUrl(input))
|
||||||
|
return parseAbsoluteUrl(input);
|
||||||
|
const url = parseAbsoluteUrl('http://foo.com/' + input);
|
||||||
|
url.scheme = '';
|
||||||
|
url.host = '';
|
||||||
|
url.type = input
|
||||||
|
? input.startsWith('?')
|
||||||
|
? 3 /* Query */
|
||||||
|
: input.startsWith('#')
|
||||||
|
? 2 /* Hash */
|
||||||
|
: 4 /* RelativePath */
|
||||||
|
: 1 /* Empty */;
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
function stripPathFilename(path) {
|
||||||
|
// If a path ends with a parent directory "..", then it's a relative path with excess parent
|
||||||
|
// paths. It's not a file, so we can't strip it.
|
||||||
|
if (path.endsWith('/..'))
|
||||||
|
return path;
|
||||||
|
const index = path.lastIndexOf('/');
|
||||||
|
return path.slice(0, index + 1);
|
||||||
|
}
|
||||||
|
function mergePaths(url, base) {
|
||||||
|
normalizePath(base, base.type);
|
||||||
|
// If the path is just a "/", then it was an empty path to begin with (remember, we're a relative
|
||||||
|
// path).
|
||||||
|
if (url.path === '/') {
|
||||||
|
url.path = base.path;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
// Resolution happens relative to the base path's directory, not the file.
|
||||||
|
url.path = stripPathFilename(base.path) + url.path;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* The path can have empty directories "//", unneeded parents "foo/..", or current directory
|
||||||
|
* "foo/.". We need to normalize to a standard representation.
|
||||||
|
*/
|
||||||
|
function normalizePath(url, type) {
|
||||||
|
const rel = type <= 4 /* RelativePath */;
|
||||||
|
const pieces = url.path.split('/');
|
||||||
|
// We need to preserve the first piece always, so that we output a leading slash. The item at
|
||||||
|
// pieces[0] is an empty string.
|
||||||
|
let pointer = 1;
|
||||||
|
// Positive is the number of real directories we've output, used for popping a parent directory.
|
||||||
|
// Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo".
|
||||||
|
let positive = 0;
|
||||||
|
// We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will
|
||||||
|
// generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a
|
||||||
|
// real directory, we won't need to append, unless the other conditions happen again.
|
||||||
|
let addTrailingSlash = false;
|
||||||
|
for (let i = 1; i < pieces.length; i++) {
|
||||||
|
const piece = pieces[i];
|
||||||
|
// An empty directory, could be a trailing slash, or just a double "//" in the path.
|
||||||
|
if (!piece) {
|
||||||
|
addTrailingSlash = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// If we encounter a real directory, then we don't need to append anymore.
|
||||||
|
addTrailingSlash = false;
|
||||||
|
// A current directory, which we can always drop.
|
||||||
|
if (piece === '.')
|
||||||
|
continue;
|
||||||
|
// A parent directory, we need to see if there are any real directories we can pop. Else, we
|
||||||
|
// have an excess of parents, and we'll need to keep the "..".
|
||||||
|
if (piece === '..') {
|
||||||
|
if (positive) {
|
||||||
|
addTrailingSlash = true;
|
||||||
|
positive--;
|
||||||
|
pointer--;
|
||||||
|
}
|
||||||
|
else if (rel) {
|
||||||
|
// If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute
|
||||||
|
// URL, protocol relative URL, or an absolute path, we don't need to keep excess.
|
||||||
|
pieces[pointer++] = piece;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// We've encountered a real directory. Move it to the next insertion pointer, which accounts for
|
||||||
|
// any popped or dropped directories.
|
||||||
|
pieces[pointer++] = piece;
|
||||||
|
positive++;
|
||||||
|
}
|
||||||
|
let path = '';
|
||||||
|
for (let i = 1; i < pointer; i++) {
|
||||||
|
path += '/' + pieces[i];
|
||||||
|
}
|
||||||
|
if (!path || (addTrailingSlash && !path.endsWith('/..'))) {
|
||||||
|
path += '/';
|
||||||
|
}
|
||||||
|
url.path = path;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Attempts to resolve `input` URL/path relative to `base`.
|
||||||
|
*/
|
||||||
|
function resolve(input, base) {
|
||||||
|
if (!input && !base)
|
||||||
|
return '';
|
||||||
|
const url = parseUrl(input);
|
||||||
|
let inputType = url.type;
|
||||||
|
if (base && inputType !== 7 /* Absolute */) {
|
||||||
|
const baseUrl = parseUrl(base);
|
||||||
|
const baseType = baseUrl.type;
|
||||||
|
switch (inputType) {
|
||||||
|
case 1 /* Empty */:
|
||||||
|
url.hash = baseUrl.hash;
|
||||||
|
// fall through
|
||||||
|
case 2 /* Hash */:
|
||||||
|
url.query = baseUrl.query;
|
||||||
|
// fall through
|
||||||
|
case 3 /* Query */:
|
||||||
|
case 4 /* RelativePath */:
|
||||||
|
mergePaths(url, baseUrl);
|
||||||
|
// fall through
|
||||||
|
case 5 /* AbsolutePath */:
|
||||||
|
// The host, user, and port are joined, you can't copy one without the others.
|
||||||
|
url.user = baseUrl.user;
|
||||||
|
url.host = baseUrl.host;
|
||||||
|
url.port = baseUrl.port;
|
||||||
|
// fall through
|
||||||
|
case 6 /* SchemeRelative */:
|
||||||
|
// The input doesn't have a schema at least, so we need to copy at least that over.
|
||||||
|
url.scheme = baseUrl.scheme;
|
||||||
|
}
|
||||||
|
if (baseType > inputType)
|
||||||
|
inputType = baseType;
|
||||||
|
}
|
||||||
|
normalizePath(url, inputType);
|
||||||
|
const queryHash = url.query + url.hash;
|
||||||
|
switch (inputType) {
|
||||||
|
// This is impossible, because of the empty checks at the start of the function.
|
||||||
|
// case UrlType.Empty:
|
||||||
|
case 2 /* Hash */:
|
||||||
|
case 3 /* Query */:
|
||||||
|
return queryHash;
|
||||||
|
case 4 /* RelativePath */: {
|
||||||
|
// The first char is always a "/", and we need it to be relative.
|
||||||
|
const path = url.path.slice(1);
|
||||||
|
if (!path)
|
||||||
|
return queryHash || '.';
|
||||||
|
if (isRelative(base || input) && !isRelative(path)) {
|
||||||
|
// If base started with a leading ".", or there is no base and input started with a ".",
|
||||||
|
// then we need to ensure that the relative path starts with a ".". We don't know if
|
||||||
|
// relative starts with a "..", though, so check before prepending.
|
||||||
|
return './' + path + queryHash;
|
||||||
|
}
|
||||||
|
return path + queryHash;
|
||||||
|
}
|
||||||
|
case 5 /* AbsolutePath */:
|
||||||
|
return url.path + queryHash;
|
||||||
|
default:
|
||||||
|
return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export { resolve as default };
|
||||||
|
//# sourceMappingURL=resolve-uri.mjs.map
|
||||||
1
node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs.map
generated
vendored
Normal file
1
node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
240
node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js
generated
vendored
Normal file
240
node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js
generated
vendored
Normal file
@@ -0,0 +1,240 @@
|
|||||||
|
(function (global, factory) {
|
||||||
|
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
|
||||||
|
typeof define === 'function' && define.amd ? define(factory) :
|
||||||
|
(global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.resolveURI = factory());
|
||||||
|
})(this, (function () { 'use strict';
|
||||||
|
|
||||||
|
// Matches the scheme of a URL, eg "http://"
|
||||||
|
const schemeRegex = /^[\w+.-]+:\/\//;
|
||||||
|
/**
|
||||||
|
* Matches the parts of a URL:
|
||||||
|
* 1. Scheme, including ":", guaranteed.
|
||||||
|
* 2. User/password, including "@", optional.
|
||||||
|
* 3. Host, guaranteed.
|
||||||
|
* 4. Port, including ":", optional.
|
||||||
|
* 5. Path, including "/", optional.
|
||||||
|
* 6. Query, including "?", optional.
|
||||||
|
* 7. Hash, including "#", optional.
|
||||||
|
*/
|
||||||
|
const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/;
|
||||||
|
/**
|
||||||
|
* File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start
|
||||||
|
* with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).
|
||||||
|
*
|
||||||
|
* 1. Host, optional.
|
||||||
|
* 2. Path, which may include "/", guaranteed.
|
||||||
|
* 3. Query, including "?", optional.
|
||||||
|
* 4. Hash, including "#", optional.
|
||||||
|
*/
|
||||||
|
const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;
|
||||||
|
function isAbsoluteUrl(input) {
|
||||||
|
return schemeRegex.test(input);
|
||||||
|
}
|
||||||
|
function isSchemeRelativeUrl(input) {
|
||||||
|
return input.startsWith('//');
|
||||||
|
}
|
||||||
|
function isAbsolutePath(input) {
|
||||||
|
return input.startsWith('/');
|
||||||
|
}
|
||||||
|
function isFileUrl(input) {
|
||||||
|
return input.startsWith('file:');
|
||||||
|
}
|
||||||
|
function isRelative(input) {
|
||||||
|
return /^[.?#]/.test(input);
|
||||||
|
}
|
||||||
|
function parseAbsoluteUrl(input) {
|
||||||
|
const match = urlRegex.exec(input);
|
||||||
|
return makeUrl(match[1], match[2] || '', match[3], match[4] || '', match[5] || '/', match[6] || '', match[7] || '');
|
||||||
|
}
|
||||||
|
function parseFileUrl(input) {
|
||||||
|
const match = fileRegex.exec(input);
|
||||||
|
const path = match[2];
|
||||||
|
return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path, match[3] || '', match[4] || '');
|
||||||
|
}
|
||||||
|
function makeUrl(scheme, user, host, port, path, query, hash) {
|
||||||
|
return {
|
||||||
|
scheme,
|
||||||
|
user,
|
||||||
|
host,
|
||||||
|
port,
|
||||||
|
path,
|
||||||
|
query,
|
||||||
|
hash,
|
||||||
|
type: 7 /* Absolute */,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
function parseUrl(input) {
|
||||||
|
if (isSchemeRelativeUrl(input)) {
|
||||||
|
const url = parseAbsoluteUrl('http:' + input);
|
||||||
|
url.scheme = '';
|
||||||
|
url.type = 6 /* SchemeRelative */;
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
if (isAbsolutePath(input)) {
|
||||||
|
const url = parseAbsoluteUrl('http://foo.com' + input);
|
||||||
|
url.scheme = '';
|
||||||
|
url.host = '';
|
||||||
|
url.type = 5 /* AbsolutePath */;
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
if (isFileUrl(input))
|
||||||
|
return parseFileUrl(input);
|
||||||
|
if (isAbsoluteUrl(input))
|
||||||
|
return parseAbsoluteUrl(input);
|
||||||
|
const url = parseAbsoluteUrl('http://foo.com/' + input);
|
||||||
|
url.scheme = '';
|
||||||
|
url.host = '';
|
||||||
|
url.type = input
|
||||||
|
? input.startsWith('?')
|
||||||
|
? 3 /* Query */
|
||||||
|
: input.startsWith('#')
|
||||||
|
? 2 /* Hash */
|
||||||
|
: 4 /* RelativePath */
|
||||||
|
: 1 /* Empty */;
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
function stripPathFilename(path) {
|
||||||
|
// If a path ends with a parent directory "..", then it's a relative path with excess parent
|
||||||
|
// paths. It's not a file, so we can't strip it.
|
||||||
|
if (path.endsWith('/..'))
|
||||||
|
return path;
|
||||||
|
const index = path.lastIndexOf('/');
|
||||||
|
return path.slice(0, index + 1);
|
||||||
|
}
|
||||||
|
function mergePaths(url, base) {
|
||||||
|
normalizePath(base, base.type);
|
||||||
|
// If the path is just a "/", then it was an empty path to begin with (remember, we're a relative
|
||||||
|
// path).
|
||||||
|
if (url.path === '/') {
|
||||||
|
url.path = base.path;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
// Resolution happens relative to the base path's directory, not the file.
|
||||||
|
url.path = stripPathFilename(base.path) + url.path;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* The path can have empty directories "//", unneeded parents "foo/..", or current directory
|
||||||
|
* "foo/.". We need to normalize to a standard representation.
|
||||||
|
*/
|
||||||
|
function normalizePath(url, type) {
|
||||||
|
const rel = type <= 4 /* RelativePath */;
|
||||||
|
const pieces = url.path.split('/');
|
||||||
|
// We need to preserve the first piece always, so that we output a leading slash. The item at
|
||||||
|
// pieces[0] is an empty string.
|
||||||
|
let pointer = 1;
|
||||||
|
// Positive is the number of real directories we've output, used for popping a parent directory.
|
||||||
|
// Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo".
|
||||||
|
let positive = 0;
|
||||||
|
// We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will
|
||||||
|
// generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a
|
||||||
|
// real directory, we won't need to append, unless the other conditions happen again.
|
||||||
|
let addTrailingSlash = false;
|
||||||
|
for (let i = 1; i < pieces.length; i++) {
|
||||||
|
const piece = pieces[i];
|
||||||
|
// An empty directory, could be a trailing slash, or just a double "//" in the path.
|
||||||
|
if (!piece) {
|
||||||
|
addTrailingSlash = true;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// If we encounter a real directory, then we don't need to append anymore.
|
||||||
|
addTrailingSlash = false;
|
||||||
|
// A current directory, which we can always drop.
|
||||||
|
if (piece === '.')
|
||||||
|
continue;
|
||||||
|
// A parent directory, we need to see if there are any real directories we can pop. Else, we
|
||||||
|
// have an excess of parents, and we'll need to keep the "..".
|
||||||
|
if (piece === '..') {
|
||||||
|
if (positive) {
|
||||||
|
addTrailingSlash = true;
|
||||||
|
positive--;
|
||||||
|
pointer--;
|
||||||
|
}
|
||||||
|
else if (rel) {
|
||||||
|
// If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute
|
||||||
|
// URL, protocol relative URL, or an absolute path, we don't need to keep excess.
|
||||||
|
pieces[pointer++] = piece;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
// We've encountered a real directory. Move it to the next insertion pointer, which accounts for
|
||||||
|
// any popped or dropped directories.
|
||||||
|
pieces[pointer++] = piece;
|
||||||
|
positive++;
|
||||||
|
}
|
||||||
|
let path = '';
|
||||||
|
for (let i = 1; i < pointer; i++) {
|
||||||
|
path += '/' + pieces[i];
|
||||||
|
}
|
||||||
|
if (!path || (addTrailingSlash && !path.endsWith('/..'))) {
|
||||||
|
path += '/';
|
||||||
|
}
|
||||||
|
url.path = path;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Attempts to resolve `input` URL/path relative to `base`.
|
||||||
|
*/
|
||||||
|
function resolve(input, base) {
|
||||||
|
if (!input && !base)
|
||||||
|
return '';
|
||||||
|
const url = parseUrl(input);
|
||||||
|
let inputType = url.type;
|
||||||
|
if (base && inputType !== 7 /* Absolute */) {
|
||||||
|
const baseUrl = parseUrl(base);
|
||||||
|
const baseType = baseUrl.type;
|
||||||
|
switch (inputType) {
|
||||||
|
case 1 /* Empty */:
|
||||||
|
url.hash = baseUrl.hash;
|
||||||
|
// fall through
|
||||||
|
case 2 /* Hash */:
|
||||||
|
url.query = baseUrl.query;
|
||||||
|
// fall through
|
||||||
|
case 3 /* Query */:
|
||||||
|
case 4 /* RelativePath */:
|
||||||
|
mergePaths(url, baseUrl);
|
||||||
|
// fall through
|
||||||
|
case 5 /* AbsolutePath */:
|
||||||
|
// The host, user, and port are joined, you can't copy one without the others.
|
||||||
|
url.user = baseUrl.user;
|
||||||
|
url.host = baseUrl.host;
|
||||||
|
url.port = baseUrl.port;
|
||||||
|
// fall through
|
||||||
|
case 6 /* SchemeRelative */:
|
||||||
|
// The input doesn't have a schema at least, so we need to copy at least that over.
|
||||||
|
url.scheme = baseUrl.scheme;
|
||||||
|
}
|
||||||
|
if (baseType > inputType)
|
||||||
|
inputType = baseType;
|
||||||
|
}
|
||||||
|
normalizePath(url, inputType);
|
||||||
|
const queryHash = url.query + url.hash;
|
||||||
|
switch (inputType) {
|
||||||
|
// This is impossible, because of the empty checks at the start of the function.
|
||||||
|
// case UrlType.Empty:
|
||||||
|
case 2 /* Hash */:
|
||||||
|
case 3 /* Query */:
|
||||||
|
return queryHash;
|
||||||
|
case 4 /* RelativePath */: {
|
||||||
|
// The first char is always a "/", and we need it to be relative.
|
||||||
|
const path = url.path.slice(1);
|
||||||
|
if (!path)
|
||||||
|
return queryHash || '.';
|
||||||
|
if (isRelative(base || input) && !isRelative(path)) {
|
||||||
|
// If base started with a leading ".", or there is no base and input started with a ".",
|
||||||
|
// then we need to ensure that the relative path starts with a ".". We don't know if
|
||||||
|
// relative starts with a "..", though, so check before prepending.
|
||||||
|
return './' + path + queryHash;
|
||||||
|
}
|
||||||
|
return path + queryHash;
|
||||||
|
}
|
||||||
|
case 5 /* AbsolutePath */:
|
||||||
|
return url.path + queryHash;
|
||||||
|
default:
|
||||||
|
return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return resolve;
|
||||||
|
|
||||||
|
}));
|
||||||
|
//# sourceMappingURL=resolve-uri.umd.js.map
|
||||||
1
node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js.map
generated
vendored
Normal file
1
node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
4
node_modules/@jridgewell/resolve-uri/dist/types/resolve-uri.d.ts
generated
vendored
Normal file
4
node_modules/@jridgewell/resolve-uri/dist/types/resolve-uri.d.ts
generated
vendored
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
/**
|
||||||
|
* Attempts to resolve `input` URL/path relative to `base`.
|
||||||
|
*/
|
||||||
|
export default function resolve(input: string, base: string | undefined): string;
|
||||||
69
node_modules/@jridgewell/resolve-uri/package.json
generated
vendored
Normal file
69
node_modules/@jridgewell/resolve-uri/package.json
generated
vendored
Normal file
@@ -0,0 +1,69 @@
|
|||||||
|
{
|
||||||
|
"name": "@jridgewell/resolve-uri",
|
||||||
|
"version": "3.1.2",
|
||||||
|
"description": "Resolve a URI relative to an optional base URI",
|
||||||
|
"keywords": [
|
||||||
|
"resolve",
|
||||||
|
"uri",
|
||||||
|
"url",
|
||||||
|
"path"
|
||||||
|
],
|
||||||
|
"author": "Justin Ridgewell <justin@ridgewell.name>",
|
||||||
|
"license": "MIT",
|
||||||
|
"repository": "https://github.com/jridgewell/resolve-uri",
|
||||||
|
"main": "dist/resolve-uri.umd.js",
|
||||||
|
"module": "dist/resolve-uri.mjs",
|
||||||
|
"types": "dist/types/resolve-uri.d.ts",
|
||||||
|
"exports": {
|
||||||
|
".": [
|
||||||
|
{
|
||||||
|
"types": "./dist/types/resolve-uri.d.ts",
|
||||||
|
"browser": "./dist/resolve-uri.umd.js",
|
||||||
|
"require": "./dist/resolve-uri.umd.js",
|
||||||
|
"import": "./dist/resolve-uri.mjs"
|
||||||
|
},
|
||||||
|
"./dist/resolve-uri.umd.js"
|
||||||
|
],
|
||||||
|
"./package.json": "./package.json"
|
||||||
|
},
|
||||||
|
"files": [
|
||||||
|
"dist"
|
||||||
|
],
|
||||||
|
"engines": {
|
||||||
|
"node": ">=6.0.0"
|
||||||
|
},
|
||||||
|
"scripts": {
|
||||||
|
"prebuild": "rm -rf dist",
|
||||||
|
"build": "run-s -n build:*",
|
||||||
|
"build:rollup": "rollup -c rollup.config.js",
|
||||||
|
"build:ts": "tsc --project tsconfig.build.json",
|
||||||
|
"lint": "run-s -n lint:*",
|
||||||
|
"lint:prettier": "npm run test:lint:prettier -- --write",
|
||||||
|
"lint:ts": "npm run test:lint:ts -- --fix",
|
||||||
|
"pretest": "run-s build:rollup",
|
||||||
|
"test": "run-s -n test:lint test:only",
|
||||||
|
"test:debug": "mocha --inspect-brk",
|
||||||
|
"test:lint": "run-s -n test:lint:*",
|
||||||
|
"test:lint:prettier": "prettier --check '{src,test}/**/*.ts'",
|
||||||
|
"test:lint:ts": "eslint '{src,test}/**/*.ts'",
|
||||||
|
"test:only": "mocha",
|
||||||
|
"test:coverage": "c8 mocha",
|
||||||
|
"test:watch": "mocha --watch",
|
||||||
|
"prepublishOnly": "npm run preversion",
|
||||||
|
"preversion": "run-s test build"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@jridgewell/resolve-uri-latest": "npm:@jridgewell/resolve-uri@*",
|
||||||
|
"@rollup/plugin-typescript": "8.3.0",
|
||||||
|
"@typescript-eslint/eslint-plugin": "5.10.0",
|
||||||
|
"@typescript-eslint/parser": "5.10.0",
|
||||||
|
"c8": "7.11.0",
|
||||||
|
"eslint": "8.7.0",
|
||||||
|
"eslint-config-prettier": "8.3.0",
|
||||||
|
"mocha": "9.2.0",
|
||||||
|
"npm-run-all": "4.1.5",
|
||||||
|
"prettier": "2.5.1",
|
||||||
|
"rollup": "2.66.0",
|
||||||
|
"typescript": "4.5.5"
|
||||||
|
}
|
||||||
|
}
|
||||||
19
node_modules/@jridgewell/sourcemap-codec/LICENSE
generated
vendored
Normal file
19
node_modules/@jridgewell/sourcemap-codec/LICENSE
generated
vendored
Normal file
@@ -0,0 +1,19 @@
|
|||||||
|
Copyright 2024 Justin Ridgewell <justin@ridgewell.name>
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in
|
||||||
|
all copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
264
node_modules/@jridgewell/sourcemap-codec/README.md
generated
vendored
Normal file
264
node_modules/@jridgewell/sourcemap-codec/README.md
generated
vendored
Normal file
@@ -0,0 +1,264 @@
|
|||||||
|
# @jridgewell/sourcemap-codec
|
||||||
|
|
||||||
|
Encode/decode the `mappings` property of a [sourcemap](https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit).
|
||||||
|
|
||||||
|
|
||||||
|
## Why?
|
||||||
|
|
||||||
|
Sourcemaps are difficult to generate and manipulate, because the `mappings` property – the part that actually links the generated code back to the original source – is encoded using an obscure method called [Variable-length quantity](https://en.wikipedia.org/wiki/Variable-length_quantity). On top of that, each segment in the mapping contains offsets rather than absolute indices, which means that you can't look at a segment in isolation – you have to understand the whole sourcemap.
|
||||||
|
|
||||||
|
This package makes the process slightly easier.
|
||||||
|
|
||||||
|
|
||||||
|
## Installation
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install @jridgewell/sourcemap-codec
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
```js
|
||||||
|
import { encode, decode } from '@jridgewell/sourcemap-codec';
|
||||||
|
|
||||||
|
var decoded = decode( ';EAEEA,EAAE,EAAC,CAAE;ECQY,UACC' );
|
||||||
|
|
||||||
|
assert.deepEqual( decoded, [
|
||||||
|
// the first line (of the generated code) has no mappings,
|
||||||
|
// as shown by the starting semi-colon (which separates lines)
|
||||||
|
[],
|
||||||
|
|
||||||
|
// the second line contains four (comma-separated) segments
|
||||||
|
[
|
||||||
|
// segments are encoded as you'd expect:
|
||||||
|
// [ generatedCodeColumn, sourceIndex, sourceCodeLine, sourceCodeColumn, nameIndex ]
|
||||||
|
|
||||||
|
// i.e. the first segment begins at column 2, and maps back to the second column
|
||||||
|
// of the second line (both zero-based) of the 0th source, and uses the 0th
|
||||||
|
// name in the `map.names` array
|
||||||
|
[ 2, 0, 2, 2, 0 ],
|
||||||
|
|
||||||
|
// the remaining segments are 4-length rather than 5-length,
|
||||||
|
// because they don't map a name
|
||||||
|
[ 4, 0, 2, 4 ],
|
||||||
|
[ 6, 0, 2, 5 ],
|
||||||
|
[ 7, 0, 2, 7 ]
|
||||||
|
],
|
||||||
|
|
||||||
|
// the final line contains two segments
|
||||||
|
[
|
||||||
|
[ 2, 1, 10, 19 ],
|
||||||
|
[ 12, 1, 11, 20 ]
|
||||||
|
]
|
||||||
|
]);
|
||||||
|
|
||||||
|
var encoded = encode( decoded );
|
||||||
|
assert.equal( encoded, ';EAEEA,EAAE,EAAC,CAAE;ECQY,UACC' );
|
||||||
|
```
|
||||||
|
|
||||||
|
## Benchmarks
|
||||||
|
|
||||||
|
```
|
||||||
|
node v20.10.0
|
||||||
|
|
||||||
|
amp.js.map - 45120 segments
|
||||||
|
|
||||||
|
Decode Memory Usage:
|
||||||
|
local code 5815135 bytes
|
||||||
|
@jridgewell/sourcemap-codec 1.4.15 5868160 bytes
|
||||||
|
sourcemap-codec 5492584 bytes
|
||||||
|
source-map-0.6.1 13569984 bytes
|
||||||
|
source-map-0.8.0 6390584 bytes
|
||||||
|
chrome dev tools 8011136 bytes
|
||||||
|
Smallest memory usage is sourcemap-codec
|
||||||
|
|
||||||
|
Decode speed:
|
||||||
|
decode: local code x 492 ops/sec ±1.22% (90 runs sampled)
|
||||||
|
decode: @jridgewell/sourcemap-codec 1.4.15 x 499 ops/sec ±1.16% (89 runs sampled)
|
||||||
|
decode: sourcemap-codec x 376 ops/sec ±1.66% (89 runs sampled)
|
||||||
|
decode: source-map-0.6.1 x 34.99 ops/sec ±0.94% (48 runs sampled)
|
||||||
|
decode: source-map-0.8.0 x 351 ops/sec ±0.07% (95 runs sampled)
|
||||||
|
chrome dev tools x 165 ops/sec ±0.91% (86 runs sampled)
|
||||||
|
Fastest is decode: @jridgewell/sourcemap-codec 1.4.15
|
||||||
|
|
||||||
|
Encode Memory Usage:
|
||||||
|
local code 444248 bytes
|
||||||
|
@jridgewell/sourcemap-codec 1.4.15 623024 bytes
|
||||||
|
sourcemap-codec 8696280 bytes
|
||||||
|
source-map-0.6.1 8745176 bytes
|
||||||
|
source-map-0.8.0 8736624 bytes
|
||||||
|
Smallest memory usage is local code
|
||||||
|
|
||||||
|
Encode speed:
|
||||||
|
encode: local code x 796 ops/sec ±0.11% (97 runs sampled)
|
||||||
|
encode: @jridgewell/sourcemap-codec 1.4.15 x 795 ops/sec ±0.25% (98 runs sampled)
|
||||||
|
encode: sourcemap-codec x 231 ops/sec ±0.83% (86 runs sampled)
|
||||||
|
encode: source-map-0.6.1 x 166 ops/sec ±0.57% (86 runs sampled)
|
||||||
|
encode: source-map-0.8.0 x 203 ops/sec ±0.45% (88 runs sampled)
|
||||||
|
Fastest is encode: local code,encode: @jridgewell/sourcemap-codec 1.4.15
|
||||||
|
|
||||||
|
|
||||||
|
***
|
||||||
|
|
||||||
|
|
||||||
|
babel.min.js.map - 347793 segments
|
||||||
|
|
||||||
|
Decode Memory Usage:
|
||||||
|
local code 35424960 bytes
|
||||||
|
@jridgewell/sourcemap-codec 1.4.15 35424696 bytes
|
||||||
|
sourcemap-codec 36033464 bytes
|
||||||
|
source-map-0.6.1 62253704 bytes
|
||||||
|
source-map-0.8.0 43843920 bytes
|
||||||
|
chrome dev tools 45111400 bytes
|
||||||
|
Smallest memory usage is @jridgewell/sourcemap-codec 1.4.15
|
||||||
|
|
||||||
|
Decode speed:
|
||||||
|
decode: local code x 38.18 ops/sec ±5.44% (52 runs sampled)
|
||||||
|
decode: @jridgewell/sourcemap-codec 1.4.15 x 38.36 ops/sec ±5.02% (52 runs sampled)
|
||||||
|
decode: sourcemap-codec x 34.05 ops/sec ±4.45% (47 runs sampled)
|
||||||
|
decode: source-map-0.6.1 x 4.31 ops/sec ±2.76% (15 runs sampled)
|
||||||
|
decode: source-map-0.8.0 x 55.60 ops/sec ±0.13% (73 runs sampled)
|
||||||
|
chrome dev tools x 16.94 ops/sec ±3.78% (46 runs sampled)
|
||||||
|
Fastest is decode: source-map-0.8.0
|
||||||
|
|
||||||
|
Encode Memory Usage:
|
||||||
|
local code 2606016 bytes
|
||||||
|
@jridgewell/sourcemap-codec 1.4.15 2626440 bytes
|
||||||
|
sourcemap-codec 21152576 bytes
|
||||||
|
source-map-0.6.1 25023928 bytes
|
||||||
|
source-map-0.8.0 25256448 bytes
|
||||||
|
Smallest memory usage is local code
|
||||||
|
|
||||||
|
Encode speed:
|
||||||
|
encode: local code x 127 ops/sec ±0.18% (83 runs sampled)
|
||||||
|
encode: @jridgewell/sourcemap-codec 1.4.15 x 128 ops/sec ±0.26% (83 runs sampled)
|
||||||
|
encode: sourcemap-codec x 29.31 ops/sec ±2.55% (53 runs sampled)
|
||||||
|
encode: source-map-0.6.1 x 18.85 ops/sec ±3.19% (36 runs sampled)
|
||||||
|
encode: source-map-0.8.0 x 19.34 ops/sec ±1.97% (36 runs sampled)
|
||||||
|
Fastest is encode: @jridgewell/sourcemap-codec 1.4.15
|
||||||
|
|
||||||
|
|
||||||
|
***
|
||||||
|
|
||||||
|
|
||||||
|
preact.js.map - 1992 segments
|
||||||
|
|
||||||
|
Decode Memory Usage:
|
||||||
|
local code 261696 bytes
|
||||||
|
@jridgewell/sourcemap-codec 1.4.15 244296 bytes
|
||||||
|
sourcemap-codec 302816 bytes
|
||||||
|
source-map-0.6.1 939176 bytes
|
||||||
|
source-map-0.8.0 336 bytes
|
||||||
|
chrome dev tools 587368 bytes
|
||||||
|
Smallest memory usage is source-map-0.8.0
|
||||||
|
|
||||||
|
Decode speed:
|
||||||
|
decode: local code x 17,782 ops/sec ±0.32% (97 runs sampled)
|
||||||
|
decode: @jridgewell/sourcemap-codec 1.4.15 x 17,863 ops/sec ±0.40% (100 runs sampled)
|
||||||
|
decode: sourcemap-codec x 12,453 ops/sec ±0.27% (101 runs sampled)
|
||||||
|
decode: source-map-0.6.1 x 1,288 ops/sec ±1.05% (96 runs sampled)
|
||||||
|
decode: source-map-0.8.0 x 9,289 ops/sec ±0.27% (101 runs sampled)
|
||||||
|
chrome dev tools x 4,769 ops/sec ±0.18% (100 runs sampled)
|
||||||
|
Fastest is decode: @jridgewell/sourcemap-codec 1.4.15
|
||||||
|
|
||||||
|
Encode Memory Usage:
|
||||||
|
local code 262944 bytes
|
||||||
|
@jridgewell/sourcemap-codec 1.4.15 25544 bytes
|
||||||
|
sourcemap-codec 323048 bytes
|
||||||
|
source-map-0.6.1 507808 bytes
|
||||||
|
source-map-0.8.0 507480 bytes
|
||||||
|
Smallest memory usage is @jridgewell/sourcemap-codec 1.4.15
|
||||||
|
|
||||||
|
Encode speed:
|
||||||
|
encode: local code x 24,207 ops/sec ±0.79% (95 runs sampled)
|
||||||
|
encode: @jridgewell/sourcemap-codec 1.4.15 x 24,288 ops/sec ±0.48% (96 runs sampled)
|
||||||
|
encode: sourcemap-codec x 6,761 ops/sec ±0.21% (100 runs sampled)
|
||||||
|
encode: source-map-0.6.1 x 5,374 ops/sec ±0.17% (99 runs sampled)
|
||||||
|
encode: source-map-0.8.0 x 5,633 ops/sec ±0.32% (99 runs sampled)
|
||||||
|
Fastest is encode: @jridgewell/sourcemap-codec 1.4.15,encode: local code
|
||||||
|
|
||||||
|
|
||||||
|
***
|
||||||
|
|
||||||
|
|
||||||
|
react.js.map - 5726 segments
|
||||||
|
|
||||||
|
Decode Memory Usage:
|
||||||
|
local code 678816 bytes
|
||||||
|
@jridgewell/sourcemap-codec 1.4.15 678816 bytes
|
||||||
|
sourcemap-codec 816400 bytes
|
||||||
|
source-map-0.6.1 2288864 bytes
|
||||||
|
source-map-0.8.0 721360 bytes
|
||||||
|
chrome dev tools 1012512 bytes
|
||||||
|
Smallest memory usage is local code
|
||||||
|
|
||||||
|
Decode speed:
|
||||||
|
decode: local code x 6,178 ops/sec ±0.19% (98 runs sampled)
|
||||||
|
decode: @jridgewell/sourcemap-codec 1.4.15 x 6,261 ops/sec ±0.22% (100 runs sampled)
|
||||||
|
decode: sourcemap-codec x 4,472 ops/sec ±0.90% (99 runs sampled)
|
||||||
|
decode: source-map-0.6.1 x 449 ops/sec ±0.31% (95 runs sampled)
|
||||||
|
decode: source-map-0.8.0 x 3,219 ops/sec ±0.13% (100 runs sampled)
|
||||||
|
chrome dev tools x 1,743 ops/sec ±0.20% (99 runs sampled)
|
||||||
|
Fastest is decode: @jridgewell/sourcemap-codec 1.4.15
|
||||||
|
|
||||||
|
Encode Memory Usage:
|
||||||
|
local code 140960 bytes
|
||||||
|
@jridgewell/sourcemap-codec 1.4.15 159808 bytes
|
||||||
|
sourcemap-codec 969304 bytes
|
||||||
|
source-map-0.6.1 930520 bytes
|
||||||
|
source-map-0.8.0 930248 bytes
|
||||||
|
Smallest memory usage is local code
|
||||||
|
|
||||||
|
Encode speed:
|
||||||
|
encode: local code x 8,013 ops/sec ±0.19% (100 runs sampled)
|
||||||
|
encode: @jridgewell/sourcemap-codec 1.4.15 x 7,989 ops/sec ±0.20% (101 runs sampled)
|
||||||
|
encode: sourcemap-codec x 2,472 ops/sec ±0.21% (99 runs sampled)
|
||||||
|
encode: source-map-0.6.1 x 2,200 ops/sec ±0.17% (99 runs sampled)
|
||||||
|
encode: source-map-0.8.0 x 2,220 ops/sec ±0.37% (99 runs sampled)
|
||||||
|
Fastest is encode: local code
|
||||||
|
|
||||||
|
|
||||||
|
***
|
||||||
|
|
||||||
|
|
||||||
|
vscode.map - 2141001 segments
|
||||||
|
|
||||||
|
Decode Memory Usage:
|
||||||
|
local code 198955264 bytes
|
||||||
|
@jridgewell/sourcemap-codec 1.4.15 199175352 bytes
|
||||||
|
sourcemap-codec 199102688 bytes
|
||||||
|
source-map-0.6.1 386323432 bytes
|
||||||
|
source-map-0.8.0 244116432 bytes
|
||||||
|
chrome dev tools 293734280 bytes
|
||||||
|
Smallest memory usage is local code
|
||||||
|
|
||||||
|
Decode speed:
|
||||||
|
decode: local code x 3.90 ops/sec ±22.21% (15 runs sampled)
|
||||||
|
decode: @jridgewell/sourcemap-codec 1.4.15 x 3.95 ops/sec ±23.53% (15 runs sampled)
|
||||||
|
decode: sourcemap-codec x 3.82 ops/sec ±17.94% (14 runs sampled)
|
||||||
|
decode: source-map-0.6.1 x 0.61 ops/sec ±7.81% (6 runs sampled)
|
||||||
|
decode: source-map-0.8.0 x 9.54 ops/sec ±0.28% (28 runs sampled)
|
||||||
|
chrome dev tools x 2.18 ops/sec ±10.58% (10 runs sampled)
|
||||||
|
Fastest is decode: source-map-0.8.0
|
||||||
|
|
||||||
|
Encode Memory Usage:
|
||||||
|
local code 13509880 bytes
|
||||||
|
@jridgewell/sourcemap-codec 1.4.15 13537648 bytes
|
||||||
|
sourcemap-codec 32540104 bytes
|
||||||
|
source-map-0.6.1 127531040 bytes
|
||||||
|
source-map-0.8.0 127535312 bytes
|
||||||
|
Smallest memory usage is local code
|
||||||
|
|
||||||
|
Encode speed:
|
||||||
|
encode: local code x 20.10 ops/sec ±0.19% (38 runs sampled)
|
||||||
|
encode: @jridgewell/sourcemap-codec 1.4.15 x 20.26 ops/sec ±0.32% (38 runs sampled)
|
||||||
|
encode: sourcemap-codec x 5.44 ops/sec ±1.64% (18 runs sampled)
|
||||||
|
encode: source-map-0.6.1 x 2.30 ops/sec ±4.79% (10 runs sampled)
|
||||||
|
encode: source-map-0.8.0 x 2.46 ops/sec ±6.53% (10 runs sampled)
|
||||||
|
Fastest is encode: @jridgewell/sourcemap-codec 1.4.15
|
||||||
|
```
|
||||||
|
|
||||||
|
# License
|
||||||
|
|
||||||
|
MIT
|
||||||
423
node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
generated
vendored
Normal file
423
node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs
generated
vendored
Normal file
@@ -0,0 +1,423 @@
|
|||||||
|
// src/vlq.ts
|
||||||
|
var comma = ",".charCodeAt(0);
|
||||||
|
var semicolon = ";".charCodeAt(0);
|
||||||
|
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||||
|
var intToChar = new Uint8Array(64);
|
||||||
|
var charToInt = new Uint8Array(128);
|
||||||
|
for (let i = 0; i < chars.length; i++) {
|
||||||
|
const c = chars.charCodeAt(i);
|
||||||
|
intToChar[i] = c;
|
||||||
|
charToInt[c] = i;
|
||||||
|
}
|
||||||
|
function decodeInteger(reader, relative) {
|
||||||
|
let value = 0;
|
||||||
|
let shift = 0;
|
||||||
|
let integer = 0;
|
||||||
|
do {
|
||||||
|
const c = reader.next();
|
||||||
|
integer = charToInt[c];
|
||||||
|
value |= (integer & 31) << shift;
|
||||||
|
shift += 5;
|
||||||
|
} while (integer & 32);
|
||||||
|
const shouldNegate = value & 1;
|
||||||
|
value >>>= 1;
|
||||||
|
if (shouldNegate) {
|
||||||
|
value = -2147483648 | -value;
|
||||||
|
}
|
||||||
|
return relative + value;
|
||||||
|
}
|
||||||
|
function encodeInteger(builder, num, relative) {
|
||||||
|
let delta = num - relative;
|
||||||
|
delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
|
||||||
|
do {
|
||||||
|
let clamped = delta & 31;
|
||||||
|
delta >>>= 5;
|
||||||
|
if (delta > 0) clamped |= 32;
|
||||||
|
builder.write(intToChar[clamped]);
|
||||||
|
} while (delta > 0);
|
||||||
|
return num;
|
||||||
|
}
|
||||||
|
function hasMoreVlq(reader, max) {
|
||||||
|
if (reader.pos >= max) return false;
|
||||||
|
return reader.peek() !== comma;
|
||||||
|
}
|
||||||
|
|
||||||
|
// src/strings.ts
|
||||||
|
var bufLength = 1024 * 16;
|
||||||
|
var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? {
|
||||||
|
decode(buf) {
|
||||||
|
const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
|
||||||
|
return out.toString();
|
||||||
|
}
|
||||||
|
} : {
|
||||||
|
decode(buf) {
|
||||||
|
let out = "";
|
||||||
|
for (let i = 0; i < buf.length; i++) {
|
||||||
|
out += String.fromCharCode(buf[i]);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var StringWriter = class {
|
||||||
|
constructor() {
|
||||||
|
this.pos = 0;
|
||||||
|
this.out = "";
|
||||||
|
this.buffer = new Uint8Array(bufLength);
|
||||||
|
}
|
||||||
|
write(v) {
|
||||||
|
const { buffer } = this;
|
||||||
|
buffer[this.pos++] = v;
|
||||||
|
if (this.pos === bufLength) {
|
||||||
|
this.out += td.decode(buffer);
|
||||||
|
this.pos = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
flush() {
|
||||||
|
const { buffer, out, pos } = this;
|
||||||
|
return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var StringReader = class {
|
||||||
|
constructor(buffer) {
|
||||||
|
this.pos = 0;
|
||||||
|
this.buffer = buffer;
|
||||||
|
}
|
||||||
|
next() {
|
||||||
|
return this.buffer.charCodeAt(this.pos++);
|
||||||
|
}
|
||||||
|
peek() {
|
||||||
|
return this.buffer.charCodeAt(this.pos);
|
||||||
|
}
|
||||||
|
indexOf(char) {
|
||||||
|
const { buffer, pos } = this;
|
||||||
|
const idx = buffer.indexOf(char, pos);
|
||||||
|
return idx === -1 ? buffer.length : idx;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// src/scopes.ts
|
||||||
|
var EMPTY = [];
|
||||||
|
function decodeOriginalScopes(input) {
|
||||||
|
const { length } = input;
|
||||||
|
const reader = new StringReader(input);
|
||||||
|
const scopes = [];
|
||||||
|
const stack = [];
|
||||||
|
let line = 0;
|
||||||
|
for (; reader.pos < length; reader.pos++) {
|
||||||
|
line = decodeInteger(reader, line);
|
||||||
|
const column = decodeInteger(reader, 0);
|
||||||
|
if (!hasMoreVlq(reader, length)) {
|
||||||
|
const last = stack.pop();
|
||||||
|
last[2] = line;
|
||||||
|
last[3] = column;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const kind = decodeInteger(reader, 0);
|
||||||
|
const fields = decodeInteger(reader, 0);
|
||||||
|
const hasName = fields & 1;
|
||||||
|
const scope = hasName ? [line, column, 0, 0, kind, decodeInteger(reader, 0)] : [line, column, 0, 0, kind];
|
||||||
|
let vars = EMPTY;
|
||||||
|
if (hasMoreVlq(reader, length)) {
|
||||||
|
vars = [];
|
||||||
|
do {
|
||||||
|
const varsIndex = decodeInteger(reader, 0);
|
||||||
|
vars.push(varsIndex);
|
||||||
|
} while (hasMoreVlq(reader, length));
|
||||||
|
}
|
||||||
|
scope.vars = vars;
|
||||||
|
scopes.push(scope);
|
||||||
|
stack.push(scope);
|
||||||
|
}
|
||||||
|
return scopes;
|
||||||
|
}
|
||||||
|
function encodeOriginalScopes(scopes) {
|
||||||
|
const writer = new StringWriter();
|
||||||
|
for (let i = 0; i < scopes.length; ) {
|
||||||
|
i = _encodeOriginalScopes(scopes, i, writer, [0]);
|
||||||
|
}
|
||||||
|
return writer.flush();
|
||||||
|
}
|
||||||
|
function _encodeOriginalScopes(scopes, index, writer, state) {
|
||||||
|
const scope = scopes[index];
|
||||||
|
const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, 4: kind, vars } = scope;
|
||||||
|
if (index > 0) writer.write(comma);
|
||||||
|
state[0] = encodeInteger(writer, startLine, state[0]);
|
||||||
|
encodeInteger(writer, startColumn, 0);
|
||||||
|
encodeInteger(writer, kind, 0);
|
||||||
|
const fields = scope.length === 6 ? 1 : 0;
|
||||||
|
encodeInteger(writer, fields, 0);
|
||||||
|
if (scope.length === 6) encodeInteger(writer, scope[5], 0);
|
||||||
|
for (const v of vars) {
|
||||||
|
encodeInteger(writer, v, 0);
|
||||||
|
}
|
||||||
|
for (index++; index < scopes.length; ) {
|
||||||
|
const next = scopes[index];
|
||||||
|
const { 0: l, 1: c } = next;
|
||||||
|
if (l > endLine || l === endLine && c >= endColumn) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
index = _encodeOriginalScopes(scopes, index, writer, state);
|
||||||
|
}
|
||||||
|
writer.write(comma);
|
||||||
|
state[0] = encodeInteger(writer, endLine, state[0]);
|
||||||
|
encodeInteger(writer, endColumn, 0);
|
||||||
|
return index;
|
||||||
|
}
|
||||||
|
function decodeGeneratedRanges(input) {
|
||||||
|
const { length } = input;
|
||||||
|
const reader = new StringReader(input);
|
||||||
|
const ranges = [];
|
||||||
|
const stack = [];
|
||||||
|
let genLine = 0;
|
||||||
|
let definitionSourcesIndex = 0;
|
||||||
|
let definitionScopeIndex = 0;
|
||||||
|
let callsiteSourcesIndex = 0;
|
||||||
|
let callsiteLine = 0;
|
||||||
|
let callsiteColumn = 0;
|
||||||
|
let bindingLine = 0;
|
||||||
|
let bindingColumn = 0;
|
||||||
|
do {
|
||||||
|
const semi = reader.indexOf(";");
|
||||||
|
let genColumn = 0;
|
||||||
|
for (; reader.pos < semi; reader.pos++) {
|
||||||
|
genColumn = decodeInteger(reader, genColumn);
|
||||||
|
if (!hasMoreVlq(reader, semi)) {
|
||||||
|
const last = stack.pop();
|
||||||
|
last[2] = genLine;
|
||||||
|
last[3] = genColumn;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const fields = decodeInteger(reader, 0);
|
||||||
|
const hasDefinition = fields & 1;
|
||||||
|
const hasCallsite = fields & 2;
|
||||||
|
const hasScope = fields & 4;
|
||||||
|
let callsite = null;
|
||||||
|
let bindings = EMPTY;
|
||||||
|
let range;
|
||||||
|
if (hasDefinition) {
|
||||||
|
const defSourcesIndex = decodeInteger(reader, definitionSourcesIndex);
|
||||||
|
definitionScopeIndex = decodeInteger(
|
||||||
|
reader,
|
||||||
|
definitionSourcesIndex === defSourcesIndex ? definitionScopeIndex : 0
|
||||||
|
);
|
||||||
|
definitionSourcesIndex = defSourcesIndex;
|
||||||
|
range = [genLine, genColumn, 0, 0, defSourcesIndex, definitionScopeIndex];
|
||||||
|
} else {
|
||||||
|
range = [genLine, genColumn, 0, 0];
|
||||||
|
}
|
||||||
|
range.isScope = !!hasScope;
|
||||||
|
if (hasCallsite) {
|
||||||
|
const prevCsi = callsiteSourcesIndex;
|
||||||
|
const prevLine = callsiteLine;
|
||||||
|
callsiteSourcesIndex = decodeInteger(reader, callsiteSourcesIndex);
|
||||||
|
const sameSource = prevCsi === callsiteSourcesIndex;
|
||||||
|
callsiteLine = decodeInteger(reader, sameSource ? callsiteLine : 0);
|
||||||
|
callsiteColumn = decodeInteger(
|
||||||
|
reader,
|
||||||
|
sameSource && prevLine === callsiteLine ? callsiteColumn : 0
|
||||||
|
);
|
||||||
|
callsite = [callsiteSourcesIndex, callsiteLine, callsiteColumn];
|
||||||
|
}
|
||||||
|
range.callsite = callsite;
|
||||||
|
if (hasMoreVlq(reader, semi)) {
|
||||||
|
bindings = [];
|
||||||
|
do {
|
||||||
|
bindingLine = genLine;
|
||||||
|
bindingColumn = genColumn;
|
||||||
|
const expressionsCount = decodeInteger(reader, 0);
|
||||||
|
let expressionRanges;
|
||||||
|
if (expressionsCount < -1) {
|
||||||
|
expressionRanges = [[decodeInteger(reader, 0)]];
|
||||||
|
for (let i = -1; i > expressionsCount; i--) {
|
||||||
|
const prevBl = bindingLine;
|
||||||
|
bindingLine = decodeInteger(reader, bindingLine);
|
||||||
|
bindingColumn = decodeInteger(reader, bindingLine === prevBl ? bindingColumn : 0);
|
||||||
|
const expression = decodeInteger(reader, 0);
|
||||||
|
expressionRanges.push([expression, bindingLine, bindingColumn]);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
expressionRanges = [[expressionsCount]];
|
||||||
|
}
|
||||||
|
bindings.push(expressionRanges);
|
||||||
|
} while (hasMoreVlq(reader, semi));
|
||||||
|
}
|
||||||
|
range.bindings = bindings;
|
||||||
|
ranges.push(range);
|
||||||
|
stack.push(range);
|
||||||
|
}
|
||||||
|
genLine++;
|
||||||
|
reader.pos = semi + 1;
|
||||||
|
} while (reader.pos < length);
|
||||||
|
return ranges;
|
||||||
|
}
|
||||||
|
function encodeGeneratedRanges(ranges) {
|
||||||
|
if (ranges.length === 0) return "";
|
||||||
|
const writer = new StringWriter();
|
||||||
|
for (let i = 0; i < ranges.length; ) {
|
||||||
|
i = _encodeGeneratedRanges(ranges, i, writer, [0, 0, 0, 0, 0, 0, 0]);
|
||||||
|
}
|
||||||
|
return writer.flush();
|
||||||
|
}
|
||||||
|
function _encodeGeneratedRanges(ranges, index, writer, state) {
|
||||||
|
const range = ranges[index];
|
||||||
|
const {
|
||||||
|
0: startLine,
|
||||||
|
1: startColumn,
|
||||||
|
2: endLine,
|
||||||
|
3: endColumn,
|
||||||
|
isScope,
|
||||||
|
callsite,
|
||||||
|
bindings
|
||||||
|
} = range;
|
||||||
|
if (state[0] < startLine) {
|
||||||
|
catchupLine(writer, state[0], startLine);
|
||||||
|
state[0] = startLine;
|
||||||
|
state[1] = 0;
|
||||||
|
} else if (index > 0) {
|
||||||
|
writer.write(comma);
|
||||||
|
}
|
||||||
|
state[1] = encodeInteger(writer, range[1], state[1]);
|
||||||
|
const fields = (range.length === 6 ? 1 : 0) | (callsite ? 2 : 0) | (isScope ? 4 : 0);
|
||||||
|
encodeInteger(writer, fields, 0);
|
||||||
|
if (range.length === 6) {
|
||||||
|
const { 4: sourcesIndex, 5: scopesIndex } = range;
|
||||||
|
if (sourcesIndex !== state[2]) {
|
||||||
|
state[3] = 0;
|
||||||
|
}
|
||||||
|
state[2] = encodeInteger(writer, sourcesIndex, state[2]);
|
||||||
|
state[3] = encodeInteger(writer, scopesIndex, state[3]);
|
||||||
|
}
|
||||||
|
if (callsite) {
|
||||||
|
const { 0: sourcesIndex, 1: callLine, 2: callColumn } = range.callsite;
|
||||||
|
if (sourcesIndex !== state[4]) {
|
||||||
|
state[5] = 0;
|
||||||
|
state[6] = 0;
|
||||||
|
} else if (callLine !== state[5]) {
|
||||||
|
state[6] = 0;
|
||||||
|
}
|
||||||
|
state[4] = encodeInteger(writer, sourcesIndex, state[4]);
|
||||||
|
state[5] = encodeInteger(writer, callLine, state[5]);
|
||||||
|
state[6] = encodeInteger(writer, callColumn, state[6]);
|
||||||
|
}
|
||||||
|
if (bindings) {
|
||||||
|
for (const binding of bindings) {
|
||||||
|
if (binding.length > 1) encodeInteger(writer, -binding.length, 0);
|
||||||
|
const expression = binding[0][0];
|
||||||
|
encodeInteger(writer, expression, 0);
|
||||||
|
let bindingStartLine = startLine;
|
||||||
|
let bindingStartColumn = startColumn;
|
||||||
|
for (let i = 1; i < binding.length; i++) {
|
||||||
|
const expRange = binding[i];
|
||||||
|
bindingStartLine = encodeInteger(writer, expRange[1], bindingStartLine);
|
||||||
|
bindingStartColumn = encodeInteger(writer, expRange[2], bindingStartColumn);
|
||||||
|
encodeInteger(writer, expRange[0], 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (index++; index < ranges.length; ) {
|
||||||
|
const next = ranges[index];
|
||||||
|
const { 0: l, 1: c } = next;
|
||||||
|
if (l > endLine || l === endLine && c >= endColumn) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
index = _encodeGeneratedRanges(ranges, index, writer, state);
|
||||||
|
}
|
||||||
|
if (state[0] < endLine) {
|
||||||
|
catchupLine(writer, state[0], endLine);
|
||||||
|
state[0] = endLine;
|
||||||
|
state[1] = 0;
|
||||||
|
} else {
|
||||||
|
writer.write(comma);
|
||||||
|
}
|
||||||
|
state[1] = encodeInteger(writer, endColumn, state[1]);
|
||||||
|
return index;
|
||||||
|
}
|
||||||
|
function catchupLine(writer, lastLine, line) {
|
||||||
|
do {
|
||||||
|
writer.write(semicolon);
|
||||||
|
} while (++lastLine < line);
|
||||||
|
}
|
||||||
|
|
||||||
|
// src/sourcemap-codec.ts
|
||||||
|
function decode(mappings) {
|
||||||
|
const { length } = mappings;
|
||||||
|
const reader = new StringReader(mappings);
|
||||||
|
const decoded = [];
|
||||||
|
let genColumn = 0;
|
||||||
|
let sourcesIndex = 0;
|
||||||
|
let sourceLine = 0;
|
||||||
|
let sourceColumn = 0;
|
||||||
|
let namesIndex = 0;
|
||||||
|
do {
|
||||||
|
const semi = reader.indexOf(";");
|
||||||
|
const line = [];
|
||||||
|
let sorted = true;
|
||||||
|
let lastCol = 0;
|
||||||
|
genColumn = 0;
|
||||||
|
while (reader.pos < semi) {
|
||||||
|
let seg;
|
||||||
|
genColumn = decodeInteger(reader, genColumn);
|
||||||
|
if (genColumn < lastCol) sorted = false;
|
||||||
|
lastCol = genColumn;
|
||||||
|
if (hasMoreVlq(reader, semi)) {
|
||||||
|
sourcesIndex = decodeInteger(reader, sourcesIndex);
|
||||||
|
sourceLine = decodeInteger(reader, sourceLine);
|
||||||
|
sourceColumn = decodeInteger(reader, sourceColumn);
|
||||||
|
if (hasMoreVlq(reader, semi)) {
|
||||||
|
namesIndex = decodeInteger(reader, namesIndex);
|
||||||
|
seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex];
|
||||||
|
} else {
|
||||||
|
seg = [genColumn, sourcesIndex, sourceLine, sourceColumn];
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
seg = [genColumn];
|
||||||
|
}
|
||||||
|
line.push(seg);
|
||||||
|
reader.pos++;
|
||||||
|
}
|
||||||
|
if (!sorted) sort(line);
|
||||||
|
decoded.push(line);
|
||||||
|
reader.pos = semi + 1;
|
||||||
|
} while (reader.pos <= length);
|
||||||
|
return decoded;
|
||||||
|
}
|
||||||
|
function sort(line) {
|
||||||
|
line.sort(sortComparator);
|
||||||
|
}
|
||||||
|
function sortComparator(a, b) {
|
||||||
|
return a[0] - b[0];
|
||||||
|
}
|
||||||
|
function encode(decoded) {
|
||||||
|
const writer = new StringWriter();
|
||||||
|
let sourcesIndex = 0;
|
||||||
|
let sourceLine = 0;
|
||||||
|
let sourceColumn = 0;
|
||||||
|
let namesIndex = 0;
|
||||||
|
for (let i = 0; i < decoded.length; i++) {
|
||||||
|
const line = decoded[i];
|
||||||
|
if (i > 0) writer.write(semicolon);
|
||||||
|
if (line.length === 0) continue;
|
||||||
|
let genColumn = 0;
|
||||||
|
for (let j = 0; j < line.length; j++) {
|
||||||
|
const segment = line[j];
|
||||||
|
if (j > 0) writer.write(comma);
|
||||||
|
genColumn = encodeInteger(writer, segment[0], genColumn);
|
||||||
|
if (segment.length === 1) continue;
|
||||||
|
sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
|
||||||
|
sourceLine = encodeInteger(writer, segment[2], sourceLine);
|
||||||
|
sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
|
||||||
|
if (segment.length === 4) continue;
|
||||||
|
namesIndex = encodeInteger(writer, segment[4], namesIndex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return writer.flush();
|
||||||
|
}
|
||||||
|
export {
|
||||||
|
decode,
|
||||||
|
decodeGeneratedRanges,
|
||||||
|
decodeOriginalScopes,
|
||||||
|
encode,
|
||||||
|
encodeGeneratedRanges,
|
||||||
|
encodeOriginalScopes
|
||||||
|
};
|
||||||
|
//# sourceMappingURL=sourcemap-codec.mjs.map
|
||||||
6
node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map
generated
vendored
Normal file
6
node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
464
node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js
generated
vendored
Normal file
464
node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js
generated
vendored
Normal file
@@ -0,0 +1,464 @@
|
|||||||
|
(function (global, factory) {
|
||||||
|
if (typeof exports === 'object' && typeof module !== 'undefined') {
|
||||||
|
factory(module);
|
||||||
|
module.exports = def(module);
|
||||||
|
} else if (typeof define === 'function' && define.amd) {
|
||||||
|
define(['module'], function(mod) {
|
||||||
|
factory.apply(this, arguments);
|
||||||
|
mod.exports = def(mod);
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
const mod = { exports: {} };
|
||||||
|
factory(mod);
|
||||||
|
global = typeof globalThis !== 'undefined' ? globalThis : global || self;
|
||||||
|
global.sourcemapCodec = def(mod);
|
||||||
|
}
|
||||||
|
function def(m) { return 'default' in m.exports ? m.exports.default : m.exports; }
|
||||||
|
})(this, (function (module) {
|
||||||
|
"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/sourcemap-codec.ts
|
||||||
|
var sourcemap_codec_exports = {};
|
||||||
|
__export(sourcemap_codec_exports, {
|
||||||
|
decode: () => decode,
|
||||||
|
decodeGeneratedRanges: () => decodeGeneratedRanges,
|
||||||
|
decodeOriginalScopes: () => decodeOriginalScopes,
|
||||||
|
encode: () => encode,
|
||||||
|
encodeGeneratedRanges: () => encodeGeneratedRanges,
|
||||||
|
encodeOriginalScopes: () => encodeOriginalScopes
|
||||||
|
});
|
||||||
|
module.exports = __toCommonJS(sourcemap_codec_exports);
|
||||||
|
|
||||||
|
// src/vlq.ts
|
||||||
|
var comma = ",".charCodeAt(0);
|
||||||
|
var semicolon = ";".charCodeAt(0);
|
||||||
|
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||||
|
var intToChar = new Uint8Array(64);
|
||||||
|
var charToInt = new Uint8Array(128);
|
||||||
|
for (let i = 0; i < chars.length; i++) {
|
||||||
|
const c = chars.charCodeAt(i);
|
||||||
|
intToChar[i] = c;
|
||||||
|
charToInt[c] = i;
|
||||||
|
}
|
||||||
|
function decodeInteger(reader, relative) {
|
||||||
|
let value = 0;
|
||||||
|
let shift = 0;
|
||||||
|
let integer = 0;
|
||||||
|
do {
|
||||||
|
const c = reader.next();
|
||||||
|
integer = charToInt[c];
|
||||||
|
value |= (integer & 31) << shift;
|
||||||
|
shift += 5;
|
||||||
|
} while (integer & 32);
|
||||||
|
const shouldNegate = value & 1;
|
||||||
|
value >>>= 1;
|
||||||
|
if (shouldNegate) {
|
||||||
|
value = -2147483648 | -value;
|
||||||
|
}
|
||||||
|
return relative + value;
|
||||||
|
}
|
||||||
|
function encodeInteger(builder, num, relative) {
|
||||||
|
let delta = num - relative;
|
||||||
|
delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
|
||||||
|
do {
|
||||||
|
let clamped = delta & 31;
|
||||||
|
delta >>>= 5;
|
||||||
|
if (delta > 0) clamped |= 32;
|
||||||
|
builder.write(intToChar[clamped]);
|
||||||
|
} while (delta > 0);
|
||||||
|
return num;
|
||||||
|
}
|
||||||
|
function hasMoreVlq(reader, max) {
|
||||||
|
if (reader.pos >= max) return false;
|
||||||
|
return reader.peek() !== comma;
|
||||||
|
}
|
||||||
|
|
||||||
|
// src/strings.ts
|
||||||
|
var bufLength = 1024 * 16;
|
||||||
|
var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? {
|
||||||
|
decode(buf) {
|
||||||
|
const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
|
||||||
|
return out.toString();
|
||||||
|
}
|
||||||
|
} : {
|
||||||
|
decode(buf) {
|
||||||
|
let out = "";
|
||||||
|
for (let i = 0; i < buf.length; i++) {
|
||||||
|
out += String.fromCharCode(buf[i]);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var StringWriter = class {
|
||||||
|
constructor() {
|
||||||
|
this.pos = 0;
|
||||||
|
this.out = "";
|
||||||
|
this.buffer = new Uint8Array(bufLength);
|
||||||
|
}
|
||||||
|
write(v) {
|
||||||
|
const { buffer } = this;
|
||||||
|
buffer[this.pos++] = v;
|
||||||
|
if (this.pos === bufLength) {
|
||||||
|
this.out += td.decode(buffer);
|
||||||
|
this.pos = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
flush() {
|
||||||
|
const { buffer, out, pos } = this;
|
||||||
|
return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
var StringReader = class {
|
||||||
|
constructor(buffer) {
|
||||||
|
this.pos = 0;
|
||||||
|
this.buffer = buffer;
|
||||||
|
}
|
||||||
|
next() {
|
||||||
|
return this.buffer.charCodeAt(this.pos++);
|
||||||
|
}
|
||||||
|
peek() {
|
||||||
|
return this.buffer.charCodeAt(this.pos);
|
||||||
|
}
|
||||||
|
indexOf(char) {
|
||||||
|
const { buffer, pos } = this;
|
||||||
|
const idx = buffer.indexOf(char, pos);
|
||||||
|
return idx === -1 ? buffer.length : idx;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// src/scopes.ts
|
||||||
|
var EMPTY = [];
|
||||||
|
function decodeOriginalScopes(input) {
|
||||||
|
const { length } = input;
|
||||||
|
const reader = new StringReader(input);
|
||||||
|
const scopes = [];
|
||||||
|
const stack = [];
|
||||||
|
let line = 0;
|
||||||
|
for (; reader.pos < length; reader.pos++) {
|
||||||
|
line = decodeInteger(reader, line);
|
||||||
|
const column = decodeInteger(reader, 0);
|
||||||
|
if (!hasMoreVlq(reader, length)) {
|
||||||
|
const last = stack.pop();
|
||||||
|
last[2] = line;
|
||||||
|
last[3] = column;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const kind = decodeInteger(reader, 0);
|
||||||
|
const fields = decodeInteger(reader, 0);
|
||||||
|
const hasName = fields & 1;
|
||||||
|
const scope = hasName ? [line, column, 0, 0, kind, decodeInteger(reader, 0)] : [line, column, 0, 0, kind];
|
||||||
|
let vars = EMPTY;
|
||||||
|
if (hasMoreVlq(reader, length)) {
|
||||||
|
vars = [];
|
||||||
|
do {
|
||||||
|
const varsIndex = decodeInteger(reader, 0);
|
||||||
|
vars.push(varsIndex);
|
||||||
|
} while (hasMoreVlq(reader, length));
|
||||||
|
}
|
||||||
|
scope.vars = vars;
|
||||||
|
scopes.push(scope);
|
||||||
|
stack.push(scope);
|
||||||
|
}
|
||||||
|
return scopes;
|
||||||
|
}
|
||||||
|
function encodeOriginalScopes(scopes) {
|
||||||
|
const writer = new StringWriter();
|
||||||
|
for (let i = 0; i < scopes.length; ) {
|
||||||
|
i = _encodeOriginalScopes(scopes, i, writer, [0]);
|
||||||
|
}
|
||||||
|
return writer.flush();
|
||||||
|
}
|
||||||
|
function _encodeOriginalScopes(scopes, index, writer, state) {
|
||||||
|
const scope = scopes[index];
|
||||||
|
const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, 4: kind, vars } = scope;
|
||||||
|
if (index > 0) writer.write(comma);
|
||||||
|
state[0] = encodeInteger(writer, startLine, state[0]);
|
||||||
|
encodeInteger(writer, startColumn, 0);
|
||||||
|
encodeInteger(writer, kind, 0);
|
||||||
|
const fields = scope.length === 6 ? 1 : 0;
|
||||||
|
encodeInteger(writer, fields, 0);
|
||||||
|
if (scope.length === 6) encodeInteger(writer, scope[5], 0);
|
||||||
|
for (const v of vars) {
|
||||||
|
encodeInteger(writer, v, 0);
|
||||||
|
}
|
||||||
|
for (index++; index < scopes.length; ) {
|
||||||
|
const next = scopes[index];
|
||||||
|
const { 0: l, 1: c } = next;
|
||||||
|
if (l > endLine || l === endLine && c >= endColumn) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
index = _encodeOriginalScopes(scopes, index, writer, state);
|
||||||
|
}
|
||||||
|
writer.write(comma);
|
||||||
|
state[0] = encodeInteger(writer, endLine, state[0]);
|
||||||
|
encodeInteger(writer, endColumn, 0);
|
||||||
|
return index;
|
||||||
|
}
|
||||||
|
function decodeGeneratedRanges(input) {
|
||||||
|
const { length } = input;
|
||||||
|
const reader = new StringReader(input);
|
||||||
|
const ranges = [];
|
||||||
|
const stack = [];
|
||||||
|
let genLine = 0;
|
||||||
|
let definitionSourcesIndex = 0;
|
||||||
|
let definitionScopeIndex = 0;
|
||||||
|
let callsiteSourcesIndex = 0;
|
||||||
|
let callsiteLine = 0;
|
||||||
|
let callsiteColumn = 0;
|
||||||
|
let bindingLine = 0;
|
||||||
|
let bindingColumn = 0;
|
||||||
|
do {
|
||||||
|
const semi = reader.indexOf(";");
|
||||||
|
let genColumn = 0;
|
||||||
|
for (; reader.pos < semi; reader.pos++) {
|
||||||
|
genColumn = decodeInteger(reader, genColumn);
|
||||||
|
if (!hasMoreVlq(reader, semi)) {
|
||||||
|
const last = stack.pop();
|
||||||
|
last[2] = genLine;
|
||||||
|
last[3] = genColumn;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const fields = decodeInteger(reader, 0);
|
||||||
|
const hasDefinition = fields & 1;
|
||||||
|
const hasCallsite = fields & 2;
|
||||||
|
const hasScope = fields & 4;
|
||||||
|
let callsite = null;
|
||||||
|
let bindings = EMPTY;
|
||||||
|
let range;
|
||||||
|
if (hasDefinition) {
|
||||||
|
const defSourcesIndex = decodeInteger(reader, definitionSourcesIndex);
|
||||||
|
definitionScopeIndex = decodeInteger(
|
||||||
|
reader,
|
||||||
|
definitionSourcesIndex === defSourcesIndex ? definitionScopeIndex : 0
|
||||||
|
);
|
||||||
|
definitionSourcesIndex = defSourcesIndex;
|
||||||
|
range = [genLine, genColumn, 0, 0, defSourcesIndex, definitionScopeIndex];
|
||||||
|
} else {
|
||||||
|
range = [genLine, genColumn, 0, 0];
|
||||||
|
}
|
||||||
|
range.isScope = !!hasScope;
|
||||||
|
if (hasCallsite) {
|
||||||
|
const prevCsi = callsiteSourcesIndex;
|
||||||
|
const prevLine = callsiteLine;
|
||||||
|
callsiteSourcesIndex = decodeInteger(reader, callsiteSourcesIndex);
|
||||||
|
const sameSource = prevCsi === callsiteSourcesIndex;
|
||||||
|
callsiteLine = decodeInteger(reader, sameSource ? callsiteLine : 0);
|
||||||
|
callsiteColumn = decodeInteger(
|
||||||
|
reader,
|
||||||
|
sameSource && prevLine === callsiteLine ? callsiteColumn : 0
|
||||||
|
);
|
||||||
|
callsite = [callsiteSourcesIndex, callsiteLine, callsiteColumn];
|
||||||
|
}
|
||||||
|
range.callsite = callsite;
|
||||||
|
if (hasMoreVlq(reader, semi)) {
|
||||||
|
bindings = [];
|
||||||
|
do {
|
||||||
|
bindingLine = genLine;
|
||||||
|
bindingColumn = genColumn;
|
||||||
|
const expressionsCount = decodeInteger(reader, 0);
|
||||||
|
let expressionRanges;
|
||||||
|
if (expressionsCount < -1) {
|
||||||
|
expressionRanges = [[decodeInteger(reader, 0)]];
|
||||||
|
for (let i = -1; i > expressionsCount; i--) {
|
||||||
|
const prevBl = bindingLine;
|
||||||
|
bindingLine = decodeInteger(reader, bindingLine);
|
||||||
|
bindingColumn = decodeInteger(reader, bindingLine === prevBl ? bindingColumn : 0);
|
||||||
|
const expression = decodeInteger(reader, 0);
|
||||||
|
expressionRanges.push([expression, bindingLine, bindingColumn]);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
expressionRanges = [[expressionsCount]];
|
||||||
|
}
|
||||||
|
bindings.push(expressionRanges);
|
||||||
|
} while (hasMoreVlq(reader, semi));
|
||||||
|
}
|
||||||
|
range.bindings = bindings;
|
||||||
|
ranges.push(range);
|
||||||
|
stack.push(range);
|
||||||
|
}
|
||||||
|
genLine++;
|
||||||
|
reader.pos = semi + 1;
|
||||||
|
} while (reader.pos < length);
|
||||||
|
return ranges;
|
||||||
|
}
|
||||||
|
function encodeGeneratedRanges(ranges) {
|
||||||
|
if (ranges.length === 0) return "";
|
||||||
|
const writer = new StringWriter();
|
||||||
|
for (let i = 0; i < ranges.length; ) {
|
||||||
|
i = _encodeGeneratedRanges(ranges, i, writer, [0, 0, 0, 0, 0, 0, 0]);
|
||||||
|
}
|
||||||
|
return writer.flush();
|
||||||
|
}
|
||||||
|
function _encodeGeneratedRanges(ranges, index, writer, state) {
|
||||||
|
const range = ranges[index];
|
||||||
|
const {
|
||||||
|
0: startLine,
|
||||||
|
1: startColumn,
|
||||||
|
2: endLine,
|
||||||
|
3: endColumn,
|
||||||
|
isScope,
|
||||||
|
callsite,
|
||||||
|
bindings
|
||||||
|
} = range;
|
||||||
|
if (state[0] < startLine) {
|
||||||
|
catchupLine(writer, state[0], startLine);
|
||||||
|
state[0] = startLine;
|
||||||
|
state[1] = 0;
|
||||||
|
} else if (index > 0) {
|
||||||
|
writer.write(comma);
|
||||||
|
}
|
||||||
|
state[1] = encodeInteger(writer, range[1], state[1]);
|
||||||
|
const fields = (range.length === 6 ? 1 : 0) | (callsite ? 2 : 0) | (isScope ? 4 : 0);
|
||||||
|
encodeInteger(writer, fields, 0);
|
||||||
|
if (range.length === 6) {
|
||||||
|
const { 4: sourcesIndex, 5: scopesIndex } = range;
|
||||||
|
if (sourcesIndex !== state[2]) {
|
||||||
|
state[3] = 0;
|
||||||
|
}
|
||||||
|
state[2] = encodeInteger(writer, sourcesIndex, state[2]);
|
||||||
|
state[3] = encodeInteger(writer, scopesIndex, state[3]);
|
||||||
|
}
|
||||||
|
if (callsite) {
|
||||||
|
const { 0: sourcesIndex, 1: callLine, 2: callColumn } = range.callsite;
|
||||||
|
if (sourcesIndex !== state[4]) {
|
||||||
|
state[5] = 0;
|
||||||
|
state[6] = 0;
|
||||||
|
} else if (callLine !== state[5]) {
|
||||||
|
state[6] = 0;
|
||||||
|
}
|
||||||
|
state[4] = encodeInteger(writer, sourcesIndex, state[4]);
|
||||||
|
state[5] = encodeInteger(writer, callLine, state[5]);
|
||||||
|
state[6] = encodeInteger(writer, callColumn, state[6]);
|
||||||
|
}
|
||||||
|
if (bindings) {
|
||||||
|
for (const binding of bindings) {
|
||||||
|
if (binding.length > 1) encodeInteger(writer, -binding.length, 0);
|
||||||
|
const expression = binding[0][0];
|
||||||
|
encodeInteger(writer, expression, 0);
|
||||||
|
let bindingStartLine = startLine;
|
||||||
|
let bindingStartColumn = startColumn;
|
||||||
|
for (let i = 1; i < binding.length; i++) {
|
||||||
|
const expRange = binding[i];
|
||||||
|
bindingStartLine = encodeInteger(writer, expRange[1], bindingStartLine);
|
||||||
|
bindingStartColumn = encodeInteger(writer, expRange[2], bindingStartColumn);
|
||||||
|
encodeInteger(writer, expRange[0], 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (index++; index < ranges.length; ) {
|
||||||
|
const next = ranges[index];
|
||||||
|
const { 0: l, 1: c } = next;
|
||||||
|
if (l > endLine || l === endLine && c >= endColumn) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
index = _encodeGeneratedRanges(ranges, index, writer, state);
|
||||||
|
}
|
||||||
|
if (state[0] < endLine) {
|
||||||
|
catchupLine(writer, state[0], endLine);
|
||||||
|
state[0] = endLine;
|
||||||
|
state[1] = 0;
|
||||||
|
} else {
|
||||||
|
writer.write(comma);
|
||||||
|
}
|
||||||
|
state[1] = encodeInteger(writer, endColumn, state[1]);
|
||||||
|
return index;
|
||||||
|
}
|
||||||
|
function catchupLine(writer, lastLine, line) {
|
||||||
|
do {
|
||||||
|
writer.write(semicolon);
|
||||||
|
} while (++lastLine < line);
|
||||||
|
}
|
||||||
|
|
||||||
|
// src/sourcemap-codec.ts
|
||||||
|
function decode(mappings) {
|
||||||
|
const { length } = mappings;
|
||||||
|
const reader = new StringReader(mappings);
|
||||||
|
const decoded = [];
|
||||||
|
let genColumn = 0;
|
||||||
|
let sourcesIndex = 0;
|
||||||
|
let sourceLine = 0;
|
||||||
|
let sourceColumn = 0;
|
||||||
|
let namesIndex = 0;
|
||||||
|
do {
|
||||||
|
const semi = reader.indexOf(";");
|
||||||
|
const line = [];
|
||||||
|
let sorted = true;
|
||||||
|
let lastCol = 0;
|
||||||
|
genColumn = 0;
|
||||||
|
while (reader.pos < semi) {
|
||||||
|
let seg;
|
||||||
|
genColumn = decodeInteger(reader, genColumn);
|
||||||
|
if (genColumn < lastCol) sorted = false;
|
||||||
|
lastCol = genColumn;
|
||||||
|
if (hasMoreVlq(reader, semi)) {
|
||||||
|
sourcesIndex = decodeInteger(reader, sourcesIndex);
|
||||||
|
sourceLine = decodeInteger(reader, sourceLine);
|
||||||
|
sourceColumn = decodeInteger(reader, sourceColumn);
|
||||||
|
if (hasMoreVlq(reader, semi)) {
|
||||||
|
namesIndex = decodeInteger(reader, namesIndex);
|
||||||
|
seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex];
|
||||||
|
} else {
|
||||||
|
seg = [genColumn, sourcesIndex, sourceLine, sourceColumn];
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
seg = [genColumn];
|
||||||
|
}
|
||||||
|
line.push(seg);
|
||||||
|
reader.pos++;
|
||||||
|
}
|
||||||
|
if (!sorted) sort(line);
|
||||||
|
decoded.push(line);
|
||||||
|
reader.pos = semi + 1;
|
||||||
|
} while (reader.pos <= length);
|
||||||
|
return decoded;
|
||||||
|
}
|
||||||
|
function sort(line) {
|
||||||
|
line.sort(sortComparator);
|
||||||
|
}
|
||||||
|
function sortComparator(a, b) {
|
||||||
|
return a[0] - b[0];
|
||||||
|
}
|
||||||
|
function encode(decoded) {
|
||||||
|
const writer = new StringWriter();
|
||||||
|
let sourcesIndex = 0;
|
||||||
|
let sourceLine = 0;
|
||||||
|
let sourceColumn = 0;
|
||||||
|
let namesIndex = 0;
|
||||||
|
for (let i = 0; i < decoded.length; i++) {
|
||||||
|
const line = decoded[i];
|
||||||
|
if (i > 0) writer.write(semicolon);
|
||||||
|
if (line.length === 0) continue;
|
||||||
|
let genColumn = 0;
|
||||||
|
for (let j = 0; j < line.length; j++) {
|
||||||
|
const segment = line[j];
|
||||||
|
if (j > 0) writer.write(comma);
|
||||||
|
genColumn = encodeInteger(writer, segment[0], genColumn);
|
||||||
|
if (segment.length === 1) continue;
|
||||||
|
sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
|
||||||
|
sourceLine = encodeInteger(writer, segment[2], sourceLine);
|
||||||
|
sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
|
||||||
|
if (segment.length === 4) continue;
|
||||||
|
namesIndex = encodeInteger(writer, segment[4], namesIndex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return writer.flush();
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
//# sourceMappingURL=sourcemap-codec.umd.js.map
|
||||||
6
node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map
generated
vendored
Normal file
6
node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map
generated
vendored
Normal file
File diff suppressed because one or more lines are too long
63
node_modules/@jridgewell/sourcemap-codec/package.json
generated
vendored
Normal file
63
node_modules/@jridgewell/sourcemap-codec/package.json
generated
vendored
Normal file
@@ -0,0 +1,63 @@
|
|||||||
|
{
|
||||||
|
"name": "@jridgewell/sourcemap-codec",
|
||||||
|
"version": "1.5.5",
|
||||||
|
"description": "Encode/decode sourcemap mappings",
|
||||||
|
"keywords": [
|
||||||
|
"sourcemap",
|
||||||
|
"vlq"
|
||||||
|
],
|
||||||
|
"main": "dist/sourcemap-codec.umd.js",
|
||||||
|
"module": "dist/sourcemap-codec.mjs",
|
||||||
|
"types": "types/sourcemap-codec.d.cts",
|
||||||
|
"files": [
|
||||||
|
"dist",
|
||||||
|
"src",
|
||||||
|
"types"
|
||||||
|
],
|
||||||
|
"exports": {
|
||||||
|
".": [
|
||||||
|
{
|
||||||
|
"import": {
|
||||||
|
"types": "./types/sourcemap-codec.d.mts",
|
||||||
|
"default": "./dist/sourcemap-codec.mjs"
|
||||||
|
},
|
||||||
|
"default": {
|
||||||
|
"types": "./types/sourcemap-codec.d.cts",
|
||||||
|
"default": "./dist/sourcemap-codec.umd.js"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"./dist/sourcemap-codec.umd.js"
|
||||||
|
],
|
||||||
|
"./package.json": "./package.json"
|
||||||
|
},
|
||||||
|
"scripts": {
|
||||||
|
"benchmark": "run-s build:code benchmark:*",
|
||||||
|
"benchmark:install": "cd benchmark && npm install",
|
||||||
|
"benchmark:only": "node --expose-gc benchmark/index.js",
|
||||||
|
"build": "run-s -n build:code build:types",
|
||||||
|
"build:code": "node ../../esbuild.mjs sourcemap-codec.ts",
|
||||||
|
"build:types": "run-s build:types:force build:types:emit build:types:mts",
|
||||||
|
"build:types:force": "rimraf tsconfig.build.tsbuildinfo",
|
||||||
|
"build:types:emit": "tsc --project tsconfig.build.json",
|
||||||
|
"build:types:mts": "node ../../mts-types.mjs",
|
||||||
|
"clean": "run-s -n clean:code clean:types",
|
||||||
|
"clean:code": "tsc --build --clean tsconfig.build.json",
|
||||||
|
"clean:types": "rimraf dist types",
|
||||||
|
"test": "run-s -n test:types test:only test:format",
|
||||||
|
"test:format": "prettier --check '{src,test}/**/*.ts'",
|
||||||
|
"test:only": "mocha",
|
||||||
|
"test:types": "eslint '{src,test}/**/*.ts'",
|
||||||
|
"lint": "run-s -n lint:types lint:format",
|
||||||
|
"lint:format": "npm run test:format -- --write",
|
||||||
|
"lint:types": "npm run test:types -- --fix",
|
||||||
|
"prepublishOnly": "npm run-s -n build test"
|
||||||
|
},
|
||||||
|
"homepage": "https://github.com/jridgewell/sourcemaps/tree/main/packages/sourcemap-codec",
|
||||||
|
"repository": {
|
||||||
|
"type": "git",
|
||||||
|
"url": "git+https://github.com/jridgewell/sourcemaps.git",
|
||||||
|
"directory": "packages/sourcemap-codec"
|
||||||
|
},
|
||||||
|
"author": "Justin Ridgewell <justin@ridgewell.name>",
|
||||||
|
"license": "MIT"
|
||||||
|
}
|
||||||
345
node_modules/@jridgewell/sourcemap-codec/src/scopes.ts
generated
vendored
Normal file
345
node_modules/@jridgewell/sourcemap-codec/src/scopes.ts
generated
vendored
Normal file
@@ -0,0 +1,345 @@
|
|||||||
|
import { StringReader, StringWriter } from './strings';
|
||||||
|
import { comma, decodeInteger, encodeInteger, hasMoreVlq, semicolon } from './vlq';
|
||||||
|
|
||||||
|
const EMPTY: any[] = [];
|
||||||
|
|
||||||
|
type Line = number;
|
||||||
|
type Column = number;
|
||||||
|
type Kind = number;
|
||||||
|
type Name = number;
|
||||||
|
type Var = number;
|
||||||
|
type SourcesIndex = number;
|
||||||
|
type ScopesIndex = number;
|
||||||
|
|
||||||
|
type Mix<A, B, O> = (A & O) | (B & O);
|
||||||
|
|
||||||
|
export type OriginalScope = Mix<
|
||||||
|
[Line, Column, Line, Column, Kind],
|
||||||
|
[Line, Column, Line, Column, Kind, Name],
|
||||||
|
{ vars: Var[] }
|
||||||
|
>;
|
||||||
|
|
||||||
|
export type GeneratedRange = Mix<
|
||||||
|
[Line, Column, Line, Column],
|
||||||
|
[Line, Column, Line, Column, SourcesIndex, ScopesIndex],
|
||||||
|
{
|
||||||
|
callsite: CallSite | null;
|
||||||
|
bindings: Binding[];
|
||||||
|
isScope: boolean;
|
||||||
|
}
|
||||||
|
>;
|
||||||
|
export type CallSite = [SourcesIndex, Line, Column];
|
||||||
|
type Binding = BindingExpressionRange[];
|
||||||
|
export type BindingExpressionRange = [Name] | [Name, Line, Column];
|
||||||
|
|
||||||
|
export function decodeOriginalScopes(input: string): OriginalScope[] {
|
||||||
|
const { length } = input;
|
||||||
|
const reader = new StringReader(input);
|
||||||
|
const scopes: OriginalScope[] = [];
|
||||||
|
const stack: OriginalScope[] = [];
|
||||||
|
let line = 0;
|
||||||
|
|
||||||
|
for (; reader.pos < length; reader.pos++) {
|
||||||
|
line = decodeInteger(reader, line);
|
||||||
|
const column = decodeInteger(reader, 0);
|
||||||
|
|
||||||
|
if (!hasMoreVlq(reader, length)) {
|
||||||
|
const last = stack.pop()!;
|
||||||
|
last[2] = line;
|
||||||
|
last[3] = column;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const kind = decodeInteger(reader, 0);
|
||||||
|
const fields = decodeInteger(reader, 0);
|
||||||
|
const hasName = fields & 0b0001;
|
||||||
|
|
||||||
|
const scope: OriginalScope = (
|
||||||
|
hasName ? [line, column, 0, 0, kind, decodeInteger(reader, 0)] : [line, column, 0, 0, kind]
|
||||||
|
) as OriginalScope;
|
||||||
|
|
||||||
|
let vars: Var[] = EMPTY;
|
||||||
|
if (hasMoreVlq(reader, length)) {
|
||||||
|
vars = [];
|
||||||
|
do {
|
||||||
|
const varsIndex = decodeInteger(reader, 0);
|
||||||
|
vars.push(varsIndex);
|
||||||
|
} while (hasMoreVlq(reader, length));
|
||||||
|
}
|
||||||
|
scope.vars = vars;
|
||||||
|
|
||||||
|
scopes.push(scope);
|
||||||
|
stack.push(scope);
|
||||||
|
}
|
||||||
|
|
||||||
|
return scopes;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function encodeOriginalScopes(scopes: OriginalScope[]): string {
|
||||||
|
const writer = new StringWriter();
|
||||||
|
|
||||||
|
for (let i = 0; i < scopes.length; ) {
|
||||||
|
i = _encodeOriginalScopes(scopes, i, writer, [0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return writer.flush();
|
||||||
|
}
|
||||||
|
|
||||||
|
function _encodeOriginalScopes(
|
||||||
|
scopes: OriginalScope[],
|
||||||
|
index: number,
|
||||||
|
writer: StringWriter,
|
||||||
|
state: [
|
||||||
|
number, // GenColumn
|
||||||
|
],
|
||||||
|
): number {
|
||||||
|
const scope = scopes[index];
|
||||||
|
const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, 4: kind, vars } = scope;
|
||||||
|
|
||||||
|
if (index > 0) writer.write(comma);
|
||||||
|
|
||||||
|
state[0] = encodeInteger(writer, startLine, state[0]);
|
||||||
|
encodeInteger(writer, startColumn, 0);
|
||||||
|
encodeInteger(writer, kind, 0);
|
||||||
|
|
||||||
|
const fields = scope.length === 6 ? 0b0001 : 0;
|
||||||
|
encodeInteger(writer, fields, 0);
|
||||||
|
if (scope.length === 6) encodeInteger(writer, scope[5], 0);
|
||||||
|
|
||||||
|
for (const v of vars) {
|
||||||
|
encodeInteger(writer, v, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (index++; index < scopes.length; ) {
|
||||||
|
const next = scopes[index];
|
||||||
|
const { 0: l, 1: c } = next;
|
||||||
|
if (l > endLine || (l === endLine && c >= endColumn)) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
index = _encodeOriginalScopes(scopes, index, writer, state);
|
||||||
|
}
|
||||||
|
|
||||||
|
writer.write(comma);
|
||||||
|
state[0] = encodeInteger(writer, endLine, state[0]);
|
||||||
|
encodeInteger(writer, endColumn, 0);
|
||||||
|
|
||||||
|
return index;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function decodeGeneratedRanges(input: string): GeneratedRange[] {
|
||||||
|
const { length } = input;
|
||||||
|
const reader = new StringReader(input);
|
||||||
|
const ranges: GeneratedRange[] = [];
|
||||||
|
const stack: GeneratedRange[] = [];
|
||||||
|
|
||||||
|
let genLine = 0;
|
||||||
|
let definitionSourcesIndex = 0;
|
||||||
|
let definitionScopeIndex = 0;
|
||||||
|
let callsiteSourcesIndex = 0;
|
||||||
|
let callsiteLine = 0;
|
||||||
|
let callsiteColumn = 0;
|
||||||
|
let bindingLine = 0;
|
||||||
|
let bindingColumn = 0;
|
||||||
|
|
||||||
|
do {
|
||||||
|
const semi = reader.indexOf(';');
|
||||||
|
let genColumn = 0;
|
||||||
|
|
||||||
|
for (; reader.pos < semi; reader.pos++) {
|
||||||
|
genColumn = decodeInteger(reader, genColumn);
|
||||||
|
|
||||||
|
if (!hasMoreVlq(reader, semi)) {
|
||||||
|
const last = stack.pop()!;
|
||||||
|
last[2] = genLine;
|
||||||
|
last[3] = genColumn;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const fields = decodeInteger(reader, 0);
|
||||||
|
const hasDefinition = fields & 0b0001;
|
||||||
|
const hasCallsite = fields & 0b0010;
|
||||||
|
const hasScope = fields & 0b0100;
|
||||||
|
|
||||||
|
let callsite: CallSite | null = null;
|
||||||
|
let bindings: Binding[] = EMPTY;
|
||||||
|
let range: GeneratedRange;
|
||||||
|
if (hasDefinition) {
|
||||||
|
const defSourcesIndex = decodeInteger(reader, definitionSourcesIndex);
|
||||||
|
definitionScopeIndex = decodeInteger(
|
||||||
|
reader,
|
||||||
|
definitionSourcesIndex === defSourcesIndex ? definitionScopeIndex : 0,
|
||||||
|
);
|
||||||
|
|
||||||
|
definitionSourcesIndex = defSourcesIndex;
|
||||||
|
range = [genLine, genColumn, 0, 0, defSourcesIndex, definitionScopeIndex] as GeneratedRange;
|
||||||
|
} else {
|
||||||
|
range = [genLine, genColumn, 0, 0] as GeneratedRange;
|
||||||
|
}
|
||||||
|
|
||||||
|
range.isScope = !!hasScope;
|
||||||
|
|
||||||
|
if (hasCallsite) {
|
||||||
|
const prevCsi = callsiteSourcesIndex;
|
||||||
|
const prevLine = callsiteLine;
|
||||||
|
callsiteSourcesIndex = decodeInteger(reader, callsiteSourcesIndex);
|
||||||
|
const sameSource = prevCsi === callsiteSourcesIndex;
|
||||||
|
callsiteLine = decodeInteger(reader, sameSource ? callsiteLine : 0);
|
||||||
|
callsiteColumn = decodeInteger(
|
||||||
|
reader,
|
||||||
|
sameSource && prevLine === callsiteLine ? callsiteColumn : 0,
|
||||||
|
);
|
||||||
|
|
||||||
|
callsite = [callsiteSourcesIndex, callsiteLine, callsiteColumn];
|
||||||
|
}
|
||||||
|
range.callsite = callsite;
|
||||||
|
|
||||||
|
if (hasMoreVlq(reader, semi)) {
|
||||||
|
bindings = [];
|
||||||
|
do {
|
||||||
|
bindingLine = genLine;
|
||||||
|
bindingColumn = genColumn;
|
||||||
|
const expressionsCount = decodeInteger(reader, 0);
|
||||||
|
let expressionRanges: BindingExpressionRange[];
|
||||||
|
if (expressionsCount < -1) {
|
||||||
|
expressionRanges = [[decodeInteger(reader, 0)]];
|
||||||
|
for (let i = -1; i > expressionsCount; i--) {
|
||||||
|
const prevBl = bindingLine;
|
||||||
|
bindingLine = decodeInteger(reader, bindingLine);
|
||||||
|
bindingColumn = decodeInteger(reader, bindingLine === prevBl ? bindingColumn : 0);
|
||||||
|
const expression = decodeInteger(reader, 0);
|
||||||
|
expressionRanges.push([expression, bindingLine, bindingColumn]);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
expressionRanges = [[expressionsCount]];
|
||||||
|
}
|
||||||
|
bindings.push(expressionRanges);
|
||||||
|
} while (hasMoreVlq(reader, semi));
|
||||||
|
}
|
||||||
|
range.bindings = bindings;
|
||||||
|
|
||||||
|
ranges.push(range);
|
||||||
|
stack.push(range);
|
||||||
|
}
|
||||||
|
|
||||||
|
genLine++;
|
||||||
|
reader.pos = semi + 1;
|
||||||
|
} while (reader.pos < length);
|
||||||
|
|
||||||
|
return ranges;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function encodeGeneratedRanges(ranges: GeneratedRange[]): string {
|
||||||
|
if (ranges.length === 0) return '';
|
||||||
|
|
||||||
|
const writer = new StringWriter();
|
||||||
|
|
||||||
|
for (let i = 0; i < ranges.length; ) {
|
||||||
|
i = _encodeGeneratedRanges(ranges, i, writer, [0, 0, 0, 0, 0, 0, 0]);
|
||||||
|
}
|
||||||
|
|
||||||
|
return writer.flush();
|
||||||
|
}
|
||||||
|
|
||||||
|
function _encodeGeneratedRanges(
|
||||||
|
ranges: GeneratedRange[],
|
||||||
|
index: number,
|
||||||
|
writer: StringWriter,
|
||||||
|
state: [
|
||||||
|
number, // GenLine
|
||||||
|
number, // GenColumn
|
||||||
|
number, // DefSourcesIndex
|
||||||
|
number, // DefScopesIndex
|
||||||
|
number, // CallSourcesIndex
|
||||||
|
number, // CallLine
|
||||||
|
number, // CallColumn
|
||||||
|
],
|
||||||
|
): number {
|
||||||
|
const range = ranges[index];
|
||||||
|
const {
|
||||||
|
0: startLine,
|
||||||
|
1: startColumn,
|
||||||
|
2: endLine,
|
||||||
|
3: endColumn,
|
||||||
|
isScope,
|
||||||
|
callsite,
|
||||||
|
bindings,
|
||||||
|
} = range;
|
||||||
|
|
||||||
|
if (state[0] < startLine) {
|
||||||
|
catchupLine(writer, state[0], startLine);
|
||||||
|
state[0] = startLine;
|
||||||
|
state[1] = 0;
|
||||||
|
} else if (index > 0) {
|
||||||
|
writer.write(comma);
|
||||||
|
}
|
||||||
|
|
||||||
|
state[1] = encodeInteger(writer, range[1], state[1]);
|
||||||
|
|
||||||
|
const fields =
|
||||||
|
(range.length === 6 ? 0b0001 : 0) | (callsite ? 0b0010 : 0) | (isScope ? 0b0100 : 0);
|
||||||
|
encodeInteger(writer, fields, 0);
|
||||||
|
|
||||||
|
if (range.length === 6) {
|
||||||
|
const { 4: sourcesIndex, 5: scopesIndex } = range;
|
||||||
|
if (sourcesIndex !== state[2]) {
|
||||||
|
state[3] = 0;
|
||||||
|
}
|
||||||
|
state[2] = encodeInteger(writer, sourcesIndex, state[2]);
|
||||||
|
state[3] = encodeInteger(writer, scopesIndex, state[3]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (callsite) {
|
||||||
|
const { 0: sourcesIndex, 1: callLine, 2: callColumn } = range.callsite!;
|
||||||
|
if (sourcesIndex !== state[4]) {
|
||||||
|
state[5] = 0;
|
||||||
|
state[6] = 0;
|
||||||
|
} else if (callLine !== state[5]) {
|
||||||
|
state[6] = 0;
|
||||||
|
}
|
||||||
|
state[4] = encodeInteger(writer, sourcesIndex, state[4]);
|
||||||
|
state[5] = encodeInteger(writer, callLine, state[5]);
|
||||||
|
state[6] = encodeInteger(writer, callColumn, state[6]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (bindings) {
|
||||||
|
for (const binding of bindings) {
|
||||||
|
if (binding.length > 1) encodeInteger(writer, -binding.length, 0);
|
||||||
|
const expression = binding[0][0];
|
||||||
|
encodeInteger(writer, expression, 0);
|
||||||
|
let bindingStartLine = startLine;
|
||||||
|
let bindingStartColumn = startColumn;
|
||||||
|
for (let i = 1; i < binding.length; i++) {
|
||||||
|
const expRange = binding[i];
|
||||||
|
bindingStartLine = encodeInteger(writer, expRange[1]!, bindingStartLine);
|
||||||
|
bindingStartColumn = encodeInteger(writer, expRange[2]!, bindingStartColumn);
|
||||||
|
encodeInteger(writer, expRange[0]!, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (index++; index < ranges.length; ) {
|
||||||
|
const next = ranges[index];
|
||||||
|
const { 0: l, 1: c } = next;
|
||||||
|
if (l > endLine || (l === endLine && c >= endColumn)) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
index = _encodeGeneratedRanges(ranges, index, writer, state);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (state[0] < endLine) {
|
||||||
|
catchupLine(writer, state[0], endLine);
|
||||||
|
state[0] = endLine;
|
||||||
|
state[1] = 0;
|
||||||
|
} else {
|
||||||
|
writer.write(comma);
|
||||||
|
}
|
||||||
|
state[1] = encodeInteger(writer, endColumn, state[1]);
|
||||||
|
|
||||||
|
return index;
|
||||||
|
}
|
||||||
|
|
||||||
|
function catchupLine(writer: StringWriter, lastLine: number, line: number) {
|
||||||
|
do {
|
||||||
|
writer.write(semicolon);
|
||||||
|
} while (++lastLine < line);
|
||||||
|
}
|
||||||
111
node_modules/@jridgewell/sourcemap-codec/src/sourcemap-codec.ts
generated
vendored
Normal file
111
node_modules/@jridgewell/sourcemap-codec/src/sourcemap-codec.ts
generated
vendored
Normal file
@@ -0,0 +1,111 @@
|
|||||||
|
import { comma, decodeInteger, encodeInteger, hasMoreVlq, semicolon } from './vlq';
|
||||||
|
import { StringWriter, StringReader } from './strings';
|
||||||
|
|
||||||
|
export {
|
||||||
|
decodeOriginalScopes,
|
||||||
|
encodeOriginalScopes,
|
||||||
|
decodeGeneratedRanges,
|
||||||
|
encodeGeneratedRanges,
|
||||||
|
} from './scopes';
|
||||||
|
export type { OriginalScope, GeneratedRange, CallSite, BindingExpressionRange } from './scopes';
|
||||||
|
|
||||||
|
export type SourceMapSegment =
|
||||||
|
| [number]
|
||||||
|
| [number, number, number, number]
|
||||||
|
| [number, number, number, number, number];
|
||||||
|
export type SourceMapLine = SourceMapSegment[];
|
||||||
|
export type SourceMapMappings = SourceMapLine[];
|
||||||
|
|
||||||
|
export function decode(mappings: string): SourceMapMappings {
|
||||||
|
const { length } = mappings;
|
||||||
|
const reader = new StringReader(mappings);
|
||||||
|
const decoded: SourceMapMappings = [];
|
||||||
|
let genColumn = 0;
|
||||||
|
let sourcesIndex = 0;
|
||||||
|
let sourceLine = 0;
|
||||||
|
let sourceColumn = 0;
|
||||||
|
let namesIndex = 0;
|
||||||
|
|
||||||
|
do {
|
||||||
|
const semi = reader.indexOf(';');
|
||||||
|
const line: SourceMapLine = [];
|
||||||
|
let sorted = true;
|
||||||
|
let lastCol = 0;
|
||||||
|
genColumn = 0;
|
||||||
|
|
||||||
|
while (reader.pos < semi) {
|
||||||
|
let seg: SourceMapSegment;
|
||||||
|
|
||||||
|
genColumn = decodeInteger(reader, genColumn);
|
||||||
|
if (genColumn < lastCol) sorted = false;
|
||||||
|
lastCol = genColumn;
|
||||||
|
|
||||||
|
if (hasMoreVlq(reader, semi)) {
|
||||||
|
sourcesIndex = decodeInteger(reader, sourcesIndex);
|
||||||
|
sourceLine = decodeInteger(reader, sourceLine);
|
||||||
|
sourceColumn = decodeInteger(reader, sourceColumn);
|
||||||
|
|
||||||
|
if (hasMoreVlq(reader, semi)) {
|
||||||
|
namesIndex = decodeInteger(reader, namesIndex);
|
||||||
|
seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex];
|
||||||
|
} else {
|
||||||
|
seg = [genColumn, sourcesIndex, sourceLine, sourceColumn];
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
seg = [genColumn];
|
||||||
|
}
|
||||||
|
|
||||||
|
line.push(seg);
|
||||||
|
reader.pos++;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!sorted) sort(line);
|
||||||
|
decoded.push(line);
|
||||||
|
reader.pos = semi + 1;
|
||||||
|
} while (reader.pos <= length);
|
||||||
|
|
||||||
|
return decoded;
|
||||||
|
}
|
||||||
|
|
||||||
|
function sort(line: SourceMapSegment[]) {
|
||||||
|
line.sort(sortComparator);
|
||||||
|
}
|
||||||
|
|
||||||
|
function sortComparator(a: SourceMapSegment, b: SourceMapSegment): number {
|
||||||
|
return a[0] - b[0];
|
||||||
|
}
|
||||||
|
|
||||||
|
export function encode(decoded: SourceMapMappings): string;
|
||||||
|
export function encode(decoded: Readonly<SourceMapMappings>): string;
|
||||||
|
export function encode(decoded: Readonly<SourceMapMappings>): string {
|
||||||
|
const writer = new StringWriter();
|
||||||
|
let sourcesIndex = 0;
|
||||||
|
let sourceLine = 0;
|
||||||
|
let sourceColumn = 0;
|
||||||
|
let namesIndex = 0;
|
||||||
|
|
||||||
|
for (let i = 0; i < decoded.length; i++) {
|
||||||
|
const line = decoded[i];
|
||||||
|
if (i > 0) writer.write(semicolon);
|
||||||
|
if (line.length === 0) continue;
|
||||||
|
|
||||||
|
let genColumn = 0;
|
||||||
|
|
||||||
|
for (let j = 0; j < line.length; j++) {
|
||||||
|
const segment = line[j];
|
||||||
|
if (j > 0) writer.write(comma);
|
||||||
|
|
||||||
|
genColumn = encodeInteger(writer, segment[0], genColumn);
|
||||||
|
|
||||||
|
if (segment.length === 1) continue;
|
||||||
|
sourcesIndex = encodeInteger(writer, segment[1], sourcesIndex);
|
||||||
|
sourceLine = encodeInteger(writer, segment[2], sourceLine);
|
||||||
|
sourceColumn = encodeInteger(writer, segment[3], sourceColumn);
|
||||||
|
|
||||||
|
if (segment.length === 4) continue;
|
||||||
|
namesIndex = encodeInteger(writer, segment[4], namesIndex);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return writer.flush();
|
||||||
|
}
|
||||||
65
node_modules/@jridgewell/sourcemap-codec/src/strings.ts
generated
vendored
Normal file
65
node_modules/@jridgewell/sourcemap-codec/src/strings.ts
generated
vendored
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
const bufLength = 1024 * 16;
|
||||||
|
|
||||||
|
// Provide a fallback for older environments.
|
||||||
|
const td =
|
||||||
|
typeof TextDecoder !== 'undefined'
|
||||||
|
? /* #__PURE__ */ new TextDecoder()
|
||||||
|
: typeof Buffer !== 'undefined'
|
||||||
|
? {
|
||||||
|
decode(buf: Uint8Array): string {
|
||||||
|
const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength);
|
||||||
|
return out.toString();
|
||||||
|
},
|
||||||
|
}
|
||||||
|
: {
|
||||||
|
decode(buf: Uint8Array): string {
|
||||||
|
let out = '';
|
||||||
|
for (let i = 0; i < buf.length; i++) {
|
||||||
|
out += String.fromCharCode(buf[i]);
|
||||||
|
}
|
||||||
|
return out;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export class StringWriter {
|
||||||
|
pos = 0;
|
||||||
|
private out = '';
|
||||||
|
private buffer = new Uint8Array(bufLength);
|
||||||
|
|
||||||
|
write(v: number): void {
|
||||||
|
const { buffer } = this;
|
||||||
|
buffer[this.pos++] = v;
|
||||||
|
if (this.pos === bufLength) {
|
||||||
|
this.out += td.decode(buffer);
|
||||||
|
this.pos = 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
flush(): string {
|
||||||
|
const { buffer, out, pos } = this;
|
||||||
|
return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class StringReader {
|
||||||
|
pos = 0;
|
||||||
|
declare private buffer: string;
|
||||||
|
|
||||||
|
constructor(buffer: string) {
|
||||||
|
this.buffer = buffer;
|
||||||
|
}
|
||||||
|
|
||||||
|
next(): number {
|
||||||
|
return this.buffer.charCodeAt(this.pos++);
|
||||||
|
}
|
||||||
|
|
||||||
|
peek(): number {
|
||||||
|
return this.buffer.charCodeAt(this.pos);
|
||||||
|
}
|
||||||
|
|
||||||
|
indexOf(char: string): number {
|
||||||
|
const { buffer, pos } = this;
|
||||||
|
const idx = buffer.indexOf(char, pos);
|
||||||
|
return idx === -1 ? buffer.length : idx;
|
||||||
|
}
|
||||||
|
}
|
||||||
55
node_modules/@jridgewell/sourcemap-codec/src/vlq.ts
generated
vendored
Normal file
55
node_modules/@jridgewell/sourcemap-codec/src/vlq.ts
generated
vendored
Normal file
@@ -0,0 +1,55 @@
|
|||||||
|
import type { StringReader, StringWriter } from './strings';
|
||||||
|
|
||||||
|
export const comma = ','.charCodeAt(0);
|
||||||
|
export const semicolon = ';'.charCodeAt(0);
|
||||||
|
|
||||||
|
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
|
||||||
|
const intToChar = new Uint8Array(64); // 64 possible chars.
|
||||||
|
const charToInt = new Uint8Array(128); // z is 122 in ASCII
|
||||||
|
|
||||||
|
for (let i = 0; i < chars.length; i++) {
|
||||||
|
const c = chars.charCodeAt(i);
|
||||||
|
intToChar[i] = c;
|
||||||
|
charToInt[c] = i;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function decodeInteger(reader: StringReader, relative: number): number {
|
||||||
|
let value = 0;
|
||||||
|
let shift = 0;
|
||||||
|
let integer = 0;
|
||||||
|
|
||||||
|
do {
|
||||||
|
const c = reader.next();
|
||||||
|
integer = charToInt[c];
|
||||||
|
value |= (integer & 31) << shift;
|
||||||
|
shift += 5;
|
||||||
|
} while (integer & 32);
|
||||||
|
|
||||||
|
const shouldNegate = value & 1;
|
||||||
|
value >>>= 1;
|
||||||
|
|
||||||
|
if (shouldNegate) {
|
||||||
|
value = -0x80000000 | -value;
|
||||||
|
}
|
||||||
|
|
||||||
|
return relative + value;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function encodeInteger(builder: StringWriter, num: number, relative: number): number {
|
||||||
|
let delta = num - relative;
|
||||||
|
|
||||||
|
delta = delta < 0 ? (-delta << 1) | 1 : delta << 1;
|
||||||
|
do {
|
||||||
|
let clamped = delta & 0b011111;
|
||||||
|
delta >>>= 5;
|
||||||
|
if (delta > 0) clamped |= 0b100000;
|
||||||
|
builder.write(intToChar[clamped]);
|
||||||
|
} while (delta > 0);
|
||||||
|
|
||||||
|
return num;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function hasMoreVlq(reader: StringReader, max: number) {
|
||||||
|
if (reader.pos >= max) return false;
|
||||||
|
return reader.peek() !== comma;
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user