@prisma-next/sql-runtime 0.1.0-dev.14 → 0.1.0-dev.16
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/accelerate-EEKAFGN3-SHR4XFVV.js +137863 -0
- package/dist/accelerate-EEKAFGN3-SHR4XFVV.js.map +1 -0
- package/dist/amcheck-24VY6X5V.js +13 -0
- package/dist/amcheck-24VY6X5V.js.map +1 -0
- package/dist/bloom-VS74NLHT.js +13 -0
- package/dist/bloom-VS74NLHT.js.map +1 -0
- package/dist/btree_gin-WBC4EAAI.js +13 -0
- package/dist/btree_gin-WBC4EAAI.js.map +1 -0
- package/dist/btree_gist-UNC6QD3M.js +13 -0
- package/dist/btree_gist-UNC6QD3M.js.map +1 -0
- package/dist/chunk-3KTOEDFX.js +49 -0
- package/dist/chunk-3KTOEDFX.js.map +1 -0
- package/dist/chunk-47DZBRQC.js +1280 -0
- package/dist/chunk-47DZBRQC.js.map +1 -0
- package/dist/chunk-52N6AFZM.js +133 -0
- package/dist/chunk-52N6AFZM.js.map +1 -0
- package/dist/chunk-7D4SUZUM.js +38 -0
- package/dist/chunk-7D4SUZUM.js.map +1 -0
- package/dist/chunk-7UNP42HJ.js +455 -0
- package/dist/chunk-7UNP42HJ.js.map +1 -0
- package/dist/chunk-ECWIHLAT.js +37 -0
- package/dist/chunk-ECWIHLAT.js.map +1 -0
- package/dist/chunk-EI626SDC.js +105 -0
- package/dist/chunk-EI626SDC.js.map +1 -0
- package/dist/chunk-UKKOYUGL.js +578 -0
- package/dist/chunk-UKKOYUGL.js.map +1 -0
- package/dist/chunk-XPLNMXQV.js +1537 -0
- package/dist/chunk-XPLNMXQV.js.map +1 -0
- package/dist/citext-T7MXGUY7.js +13 -0
- package/dist/citext-T7MXGUY7.js.map +1 -0
- package/dist/client-5FENX6AW.js +299 -0
- package/dist/client-5FENX6AW.js.map +1 -0
- package/dist/cube-TFDQBZCI.js +13 -0
- package/dist/cube-TFDQBZCI.js.map +1 -0
- package/dist/dict_int-AEUOPGWP.js +13 -0
- package/dist/dict_int-AEUOPGWP.js.map +1 -0
- package/dist/dict_xsyn-DAAYX3FL.js +13 -0
- package/dist/dict_xsyn-DAAYX3FL.js.map +1 -0
- package/dist/dist-LBVX6BJW.js +189 -0
- package/dist/dist-LBVX6BJW.js.map +1 -0
- package/dist/dist-LCVVJCGI.js +570 -0
- package/dist/dist-LCVVJCGI.js.map +1 -0
- package/dist/dist-WLKUVDN2.js +5127 -0
- package/dist/dist-WLKUVDN2.js.map +1 -0
- package/dist/earthdistance-KIGTF4LE.js +13 -0
- package/dist/earthdistance-KIGTF4LE.js.map +1 -0
- package/dist/file_fdw-5N55UP6I.js +13 -0
- package/dist/file_fdw-5N55UP6I.js.map +1 -0
- package/dist/fuzzystrmatch-KN3YWBFP.js +13 -0
- package/dist/fuzzystrmatch-KN3YWBFP.js.map +1 -0
- package/dist/hstore-YX726NKN.js +13 -0
- package/dist/hstore-YX726NKN.js.map +1 -0
- package/dist/http-exception-FZY2H4OF.js +8 -0
- package/dist/http-exception-FZY2H4OF.js.map +1 -0
- package/dist/index.d.ts +7 -59
- package/dist/index.js +15 -439
- package/dist/index.js.map +1 -1
- package/dist/intarray-NKVXNO2D.js +13 -0
- package/dist/intarray-NKVXNO2D.js.map +1 -0
- package/dist/isn-FTEMJGEV.js +13 -0
- package/dist/isn-FTEMJGEV.js.map +1 -0
- package/dist/lo-DB7L4NGI.js +13 -0
- package/dist/lo-DB7L4NGI.js.map +1 -0
- package/dist/logger-WQ7SHNDD.js +68 -0
- package/dist/logger-WQ7SHNDD.js.map +1 -0
- package/dist/ltree-Z32TZT6W.js +13 -0
- package/dist/ltree-Z32TZT6W.js.map +1 -0
- package/dist/nodefs-NM46ACH7.js +31 -0
- package/dist/nodefs-NM46ACH7.js.map +1 -0
- package/dist/opfs-ahp-NJO33LVZ.js +332 -0
- package/dist/opfs-ahp-NJO33LVZ.js.map +1 -0
- package/dist/pageinspect-YP3IZR4X.js +13 -0
- package/dist/pageinspect-YP3IZR4X.js.map +1 -0
- package/dist/pg_buffercache-7TD5J2FB.js +13 -0
- package/dist/pg_buffercache-7TD5J2FB.js.map +1 -0
- package/dist/pg_dump-SG4KYBUB.js +2492 -0
- package/dist/pg_dump-SG4KYBUB.js.map +1 -0
- package/dist/pg_freespacemap-DZDNCPZK.js +13 -0
- package/dist/pg_freespacemap-DZDNCPZK.js.map +1 -0
- package/dist/pg_surgery-J2MUEWEP.js +13 -0
- package/dist/pg_surgery-J2MUEWEP.js.map +1 -0
- package/dist/pg_trgm-7VNQOYS6.js +13 -0
- package/dist/pg_trgm-7VNQOYS6.js.map +1 -0
- package/dist/pg_visibility-TTSIPHFL.js +13 -0
- package/dist/pg_visibility-TTSIPHFL.js.map +1 -0
- package/dist/pg_walinspect-KPFHSHRJ.js +13 -0
- package/dist/pg_walinspect-KPFHSHRJ.js.map +1 -0
- package/dist/proxy-signals-GUDAMDHV.js +39 -0
- package/dist/proxy-signals-GUDAMDHV.js.map +1 -0
- package/dist/seg-IYVDLE4O.js +13 -0
- package/dist/seg-IYVDLE4O.js.map +1 -0
- package/dist/sql-runtime-qPimiOqJ.d.ts +63 -0
- package/dist/tablefunc-EF4RCS7S.js +13 -0
- package/dist/tablefunc-EF4RCS7S.js.map +1 -0
- package/dist/tcn-3VT5BQYW.js +13 -0
- package/dist/tcn-3VT5BQYW.js.map +1 -0
- package/dist/test/utils.d.ts +60 -0
- package/dist/test/utils.js +24604 -0
- package/dist/test/utils.js.map +1 -0
- package/dist/tiny-CW6F4GX6.js +10 -0
- package/dist/tiny-CW6F4GX6.js.map +1 -0
- package/dist/tsm_system_rows-ES7KNUQH.js +13 -0
- package/dist/tsm_system_rows-ES7KNUQH.js.map +1 -0
- package/dist/tsm_system_time-76WEIMBG.js +13 -0
- package/dist/tsm_system_time-76WEIMBG.js.map +1 -0
- package/dist/unaccent-7RYF3R64.js +13 -0
- package/dist/unaccent-7RYF3R64.js.map +1 -0
- package/dist/utility-Q5A254LJ-J4HTKZPT.js +347 -0
- package/dist/utility-Q5A254LJ-J4HTKZPT.js.map +1 -0
- package/dist/uuid_ossp-4ETE4FPE.js +13 -0
- package/dist/uuid_ossp-4ETE4FPE.js.map +1 -0
- package/dist/vector-74GPNV7V.js +13 -0
- package/dist/vector-74GPNV7V.js.map +1 -0
- package/package.json +9 -9
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../../../node_modules/.pnpm/@electric-sql+pglite-socket@0.0.19_@electric-sql+pglite@0.3.14/node_modules/@electric-sql/pglite-socket/src/index.ts"],"sourcesContent":["import type { PGlite } from '@electric-sql/pglite'\nimport { createServer, Server, Socket } from 'net'\n\n// Connection queue timeout in milliseconds\nexport const CONNECTION_QUEUE_TIMEOUT = 60000 // 60 seconds\n\n/**\n * Options for creating a PGLiteSocketHandler\n */\nexport interface PGLiteSocketHandlerOptions {\n /** The PGlite database instance */\n db: PGlite\n /** Whether to close the socket when detached (default: false) */\n closeOnDetach?: boolean\n /** Print the incoming and outgoing data to the console in hex and ascii */\n inspect?: boolean\n /** Enable debug logging of method calls */\n debug?: boolean\n}\n\n/**\n * Low-level handler for a single socket connection to PGLite\n * Handles the raw protocol communication between a socket and PGLite\n */\nexport class PGLiteSocketHandler extends EventTarget {\n readonly db: PGlite\n private socket: Socket | null = null\n private active = false\n private closeOnDetach: boolean\n private resolveLock?: () => void\n private rejectLock?: (err: Error) => void\n private inspect: boolean\n private debug: boolean\n private readonly id: number\n\n // Static counter for generating unique handler IDs\n private static nextHandlerId = 1\n\n /**\n * Create a new PGLiteSocketHandler\n * @param options Options for the handler\n */\n constructor(options: PGLiteSocketHandlerOptions) {\n super()\n this.db = options.db\n this.closeOnDetach = options.closeOnDetach ?? false\n this.inspect = options.inspect ?? false\n this.debug = options.debug ?? false\n this.id = PGLiteSocketHandler.nextHandlerId++\n\n this.log('constructor: created new handler')\n }\n\n /**\n * Get the unique ID of this handler\n */\n public get handlerId(): number {\n return this.id\n }\n\n /**\n * Log a message if debug is enabled\n * @private\n */\n private log(message: string, ...args: any[]): void {\n if (this.debug) {\n console.log(`[PGLiteSocketHandler#${this.id}] ${message}`, ...args)\n }\n }\n\n /**\n * Attach a socket to this handler\n * @param socket The socket to attach\n * @returns this handler instance\n * @throws Error if a socket is already attached\n */\n public async attach(socket: Socket): Promise<PGLiteSocketHandler> {\n this.log(\n `attach: attaching socket from ${socket.remoteAddress}:${socket.remotePort}`,\n )\n\n if (this.socket) {\n throw new Error('Socket already attached')\n }\n\n this.socket = socket\n this.active = true\n\n // Ensure the PGlite instance is ready\n this.log(`attach: waiting for PGlite to be ready`)\n await this.db.waitReady\n\n // Hold the lock on the PGlite instance\n this.log(`attach: acquiring exclusive lock on PGlite instance`)\n await new Promise<void>((resolve) => {\n this.db.runExclusive(() => {\n // Ensure we have the lock on the PGlite instance\n resolve()\n\n // Use a promise to hold the lock on the PGlite instance\n // this can be resolved or rejected by the handler to release the lock\n return new Promise<void>((resolveLock, rejectLock) => {\n this.resolveLock = resolveLock\n this.rejectLock = rejectLock\n })\n })\n })\n\n // Setup event handlers\n this.log(`attach: setting up socket event handlers`)\n socket.on('data', async (data) => {\n try {\n const result = await this.handleData(data)\n this.log(`socket on data sent: ${result} bytes`)\n } catch (err) {\n this.log('socket on data error: ', err)\n }\n })\n socket.on('error', (err) => this.handleError(err))\n socket.on('close', () => this.handleClose())\n\n return this\n }\n\n /**\n * Detach the current socket from this handler\n * @param close Whether to close the socket when detaching (overrides constructor option)\n * @returns this handler instance\n */\n public detach(close?: boolean): PGLiteSocketHandler {\n this.log(`detach: detaching socket, close=${close ?? this.closeOnDetach}`)\n\n if (!this.socket) {\n this.log(`detach: no socket attached, nothing to do`)\n return this\n }\n\n // Remove all listeners\n this.socket.removeAllListeners('data')\n this.socket.removeAllListeners('error')\n this.socket.removeAllListeners('close')\n\n // Close the socket if requested\n if (close ?? this.closeOnDetach) {\n if (this.socket.writable) {\n this.log(`detach: closing socket`)\n this.socket.end()\n this.socket.destroy()\n }\n }\n\n // Release the lock on the PGlite instance\n this.log(`detach: releasing exclusive lock on PGlite instance`)\n this.resolveLock?.()\n\n this.socket = null\n this.active = false\n return this\n }\n\n /**\n * Check if a socket is currently attached\n */\n public get isAttached(): boolean {\n return this.socket !== null\n }\n\n /**\n * Handle incoming data from the socket\n */\n private async handleData(data: Buffer): Promise<number> {\n if (!this.socket || !this.active) {\n this.log(`handleData: no active socket, ignoring data`)\n return new Promise((_, reject) => reject(`no active socket`))\n }\n\n this.log(`handleData: received ${data.length} bytes`)\n\n // Print the incoming data to the console\n this.inspectData('incoming', data)\n\n try {\n // Process the raw protocol data\n this.log(`handleData: sending data to PGlite for processing`)\n const result = await this.db.execProtocolRaw(new Uint8Array(data))\n\n this.log(`handleData: received ${result.length} bytes from PGlite`)\n\n // Print the outgoing data to the console\n this.inspectData('outgoing', result)\n\n // Send the result back if the socket is still connected\n if (this.socket && this.socket.writable && this.active) {\n if (result.length <= 0) {\n this.log(`handleData: cowardly refusing to send empty packet`)\n return new Promise((_, reject) => reject('no data'))\n }\n\n const promise = new Promise<number>((resolve, reject) => {\n this.log(`handleData: writing response to socket`)\n if (this.socket) {\n this.socket.write(Buffer.from(result), (err?: Error) => {\n if (err) {\n reject(`Error while writing to the socket ${err.toString()}`)\n } else {\n resolve(result.length)\n }\n })\n } else {\n reject(`No socket`)\n }\n })\n\n // Emit data event with byte sizes\n this.dispatchEvent(\n new CustomEvent('data', {\n detail: { incoming: data.length, outgoing: result.length },\n }),\n )\n return promise\n } else {\n this.log(\n `handleData: socket no longer writable or active, discarding response`,\n )\n return new Promise((_, reject) =>\n reject(`No socket, not active or not writeable`),\n )\n }\n } catch (err) {\n this.log(`handleData: error processing data:`, err)\n this.handleError(err as Error)\n return new Promise((_, reject) =>\n reject(`Error while processing data ${(err as Error).toString()}`),\n )\n }\n }\n\n /**\n * Handle errors from the socket\n */\n private handleError(err: Error): void {\n this.log(`handleError:`, err)\n\n // Emit error event\n this.dispatchEvent(new CustomEvent('error', { detail: err }))\n\n // Reject the lock on the PGlite instance\n this.log(`handleError: rejecting exclusive lock on PGlite instance`)\n this.rejectLock?.(err)\n this.resolveLock = undefined\n this.rejectLock = undefined\n\n // Close the connection on error\n this.detach(true)\n }\n\n /**\n * Handle socket close event\n */\n private handleClose(): void {\n this.log(`handleClose: socket closed`)\n\n this.dispatchEvent(new CustomEvent('close'))\n this.detach(false) // Already closed, just clean up\n }\n\n /**\n * Print data in hex and ascii to the console\n */\n private inspectData(\n direction: 'incoming' | 'outgoing',\n data: Buffer | Uint8Array,\n ): void {\n if (!this.inspect) return\n console.log('-'.repeat(75))\n if (direction === 'incoming') {\n console.log('-> incoming', data.length, 'bytes')\n } else {\n console.log('<- outgoing', data.length, 'bytes')\n }\n\n // Process 16 bytes per line\n for (let offset = 0; offset < data.length; offset += 16) {\n // Calculate current chunk size (may be less than 16 for the last chunk)\n const chunkSize = Math.min(16, data.length - offset)\n\n // Build the hex representation\n let hexPart = ''\n for (let i = 0; i < 16; i++) {\n if (i < chunkSize) {\n const byte = data[offset + i]\n hexPart += byte.toString(16).padStart(2, '0') + ' '\n } else {\n hexPart += ' ' // 3 spaces for missing bytes\n }\n }\n\n // Build the ASCII representation\n let asciiPart = ''\n for (let i = 0; i < chunkSize; i++) {\n const byte = data[offset + i]\n // Use printable characters (32-126), replace others with a dot\n asciiPart += byte >= 32 && byte <= 126 ? String.fromCharCode(byte) : '.'\n }\n\n // Print the line with offset in hex, hex values, and ASCII representation\n console.log(\n `${offset.toString(16).padStart(8, '0')} ${hexPart} ${asciiPart}`,\n )\n }\n }\n}\n\n/**\n * Represents a queued connection with timeout\n */\ninterface QueuedConnection {\n socket: Socket\n clientInfo: {\n clientAddress: string\n clientPort: number\n }\n timeoutId: NodeJS.Timeout\n}\n\n/**\n * Options for creating a PGLiteSocketServer\n */\nexport interface PGLiteSocketServerOptions {\n /** The PGlite database instance */\n db: PGlite\n /** The port to listen on (default: 5432) */\n port?: number\n /** The host to bind to (default: 127.0.0.1) */\n host?: string\n /** Unix socket path to bind to (default: undefined). If specified, takes precedence over host:port */\n path?: string\n /** Print the incoming and outgoing data to the console in hex and ascii */\n inspect?: boolean\n /** Connection queue timeout in milliseconds (default: 10000) */\n connectionQueueTimeout?: number\n /** Enable debug logging of method calls */\n debug?: boolean\n}\n\n/**\n * High-level server that manages socket connections to PGLite\n * Creates and manages a TCP server and handles client connections\n */\nexport class PGLiteSocketServer extends EventTarget {\n readonly db: PGlite\n private server: Server | null = null\n private port?: number\n private host?: string\n private path?: string\n private active = false\n private inspect: boolean\n private debug: boolean\n private connectionQueueTimeout: number\n private activeHandler: PGLiteSocketHandler | null = null\n private connectionQueue: QueuedConnection[] = []\n private handlerCount: number = 0\n\n /**\n * Create a new PGLiteSocketServer\n * @param options Options for the server\n */\n constructor(options: PGLiteSocketServerOptions) {\n super()\n this.db = options.db\n if (options.path) {\n this.path = options.path\n } else {\n if (typeof options.port === 'number') {\n // Keep port undefined on port 0, will be set by the OS when we start the server.\n this.port = options.port ?? options.port\n } else {\n this.port = 5432\n }\n this.host = options.host || '127.0.0.1'\n }\n this.inspect = options.inspect ?? false\n this.debug = options.debug ?? false\n this.connectionQueueTimeout =\n options.connectionQueueTimeout ?? CONNECTION_QUEUE_TIMEOUT\n\n this.log(`constructor: created server on ${this.host}:${this.port}`)\n this.log(\n `constructor: connection queue timeout: ${this.connectionQueueTimeout}ms`,\n )\n }\n\n /**\n * Log a message if debug is enabled\n * @private\n */\n private log(message: string, ...args: any[]): void {\n if (this.debug) {\n console.log(`[PGLiteSocketServer] ${message}`, ...args)\n }\n }\n\n /**\n * Start the socket server\n * @returns Promise that resolves when the server is listening\n */\n public async start(): Promise<void> {\n this.log(`start: starting server on ${this.getServerConn()}`)\n\n if (this.server) {\n throw new Error('Socket server already started')\n }\n\n this.active = true\n this.server = createServer((socket) => this.handleConnection(socket))\n\n return new Promise<void>((resolve, reject) => {\n if (!this.server) return reject(new Error('Server not initialized'))\n\n this.server.on('error', (err) => {\n this.log(`start: server error:`, err)\n this.dispatchEvent(new CustomEvent('error', { detail: err }))\n reject(err)\n })\n\n if (this.path) {\n this.server.listen(this.path, () => {\n this.log(`start: server listening on ${this.getServerConn()}`)\n this.dispatchEvent(\n new CustomEvent('listening', {\n detail: { path: this.path },\n }),\n )\n resolve()\n })\n } else {\n const server = this.server\n server.listen(this.port, this.host, () => {\n const address = server.address()\n // We are not using pipes, so return type should be AddressInfo\n if (address === null || typeof address !== 'object') {\n throw Error('Expected address info')\n }\n // Assign the new port number\n this.port = address.port\n this.log(`start: server listening on ${this.getServerConn()}`)\n this.dispatchEvent(\n new CustomEvent('listening', {\n detail: { port: this.port, host: this.host },\n }),\n )\n resolve()\n })\n }\n })\n }\n\n public getServerConn(): string {\n if (this.path) return this.path\n return `${this.host}:${this.port}`\n }\n\n /**\n * Stop the socket server\n * @returns Promise that resolves when the server is closed\n */\n public async stop(): Promise<void> {\n this.log(`stop: stopping server`)\n\n this.active = false\n\n // Clear connection queue\n this.log(\n `stop: clearing connection queue (${this.connectionQueue.length} connections)`,\n )\n\n this.connectionQueue.forEach((queuedConn) => {\n clearTimeout(queuedConn.timeoutId)\n if (queuedConn.socket.writable) {\n this.log(\n `stop: closing queued connection from ${queuedConn.clientInfo.clientAddress}:${queuedConn.clientInfo.clientPort}`,\n )\n queuedConn.socket.end()\n }\n })\n this.connectionQueue = []\n\n // Detach active handler if exists\n if (this.activeHandler) {\n this.log(`stop: detaching active handler #${this.activeHandlerId}`)\n this.activeHandler.detach(true)\n this.activeHandler = null\n }\n\n if (!this.server) {\n this.log(`stop: server not running, nothing to do`)\n return Promise.resolve()\n }\n\n return new Promise<void>((resolve) => {\n if (!this.server) return resolve()\n\n this.server.close(() => {\n this.log(`stop: server closed`)\n this.server = null\n this.dispatchEvent(new CustomEvent('close'))\n resolve()\n })\n })\n }\n\n /**\n * Get the active handler ID, or null if no active handler\n */\n private get activeHandlerId(): number | null {\n return this.activeHandler?.handlerId ?? null\n }\n\n /**\n * Handle a new client connection\n */\n private async handleConnection(socket: Socket): Promise<void> {\n const clientInfo = {\n clientAddress: socket.remoteAddress || 'unknown',\n clientPort: socket.remotePort || 0,\n }\n\n this.log(\n `handleConnection: new connection from ${clientInfo.clientAddress}:${clientInfo.clientPort}`,\n )\n\n // If server is not active, close the connection immediately\n if (!this.active) {\n this.log(`handleConnection: server not active, closing connection`)\n socket.end()\n return\n }\n\n // If we don't have an active handler or it's not attached, we can use this connection immediately\n if (!this.activeHandler || !this.activeHandler.isAttached) {\n this.log(`handleConnection: no active handler, attaching socket directly`)\n this.dispatchEvent(new CustomEvent('connection', { detail: clientInfo }))\n await this.attachSocketToNewHandler(socket, clientInfo)\n return\n }\n\n // Otherwise, queue the connection\n this.log(\n `handleConnection: active handler #${this.activeHandlerId} exists, queueing connection`,\n )\n this.enqueueConnection(socket, clientInfo)\n }\n\n /**\n * Add a connection to the queue\n */\n private enqueueConnection(\n socket: Socket,\n clientInfo: { clientAddress: string; clientPort: number },\n ): void {\n this.log(\n `enqueueConnection: queueing connection from ${clientInfo.clientAddress}:${clientInfo.clientPort}, timeout: ${this.connectionQueueTimeout}ms`,\n )\n\n // Set a timeout for this queued connection\n const timeoutId = setTimeout(() => {\n this.log(\n `enqueueConnection: timeout for connection from ${clientInfo.clientAddress}:${clientInfo.clientPort}`,\n )\n\n // Remove from queue\n this.connectionQueue = this.connectionQueue.filter(\n (queuedConn) => queuedConn.socket !== socket,\n )\n\n // End the connection if it's still open\n if (socket.writable) {\n this.log(`enqueueConnection: closing timed out connection`)\n socket.end()\n }\n\n this.dispatchEvent(\n new CustomEvent('queueTimeout', {\n detail: { ...clientInfo, queueSize: this.connectionQueue.length },\n }),\n )\n }, this.connectionQueueTimeout)\n\n // Add to queue\n this.connectionQueue.push({ socket, clientInfo, timeoutId })\n\n this.log(\n `enqueueConnection: connection queued, queue size: ${this.connectionQueue.length}`,\n )\n\n this.dispatchEvent(\n new CustomEvent('queuedConnection', {\n detail: { ...clientInfo, queueSize: this.connectionQueue.length },\n }),\n )\n }\n\n /**\n * Process the next connection in the queue\n */\n private processNextInQueue(): void {\n this.log(\n `processNextInQueue: processing next connection, queue size: ${this.connectionQueue.length}`,\n )\n\n // No connections in queue or server not active\n if (this.connectionQueue.length === 0 || !this.active) {\n this.log(\n `processNextInQueue: no connections in queue or server not active, nothing to do`,\n )\n return\n }\n\n // Get the next connection\n const nextConn = this.connectionQueue.shift()\n if (!nextConn) return\n\n this.log(\n `processNextInQueue: processing connection from ${nextConn.clientInfo.clientAddress}:${nextConn.clientInfo.clientPort}`,\n )\n\n // Clear the timeout\n clearTimeout(nextConn.timeoutId)\n\n // Check if the socket is still valid\n if (!nextConn.socket.writable) {\n this.log(\n `processNextInQueue: socket no longer writable, skipping to next connection`,\n )\n // Socket closed while waiting, process next in queue\n this.processNextInQueue()\n return\n }\n\n // Attach this socket to a new handler\n this.attachSocketToNewHandler(nextConn.socket, nextConn.clientInfo).catch(\n (err) => {\n this.log(`processNextInQueue: error attaching socket:`, err)\n this.dispatchEvent(new CustomEvent('error', { detail: err }))\n // Try the next connection\n this.processNextInQueue()\n },\n )\n }\n\n /**\n * Attach a socket to a new handler\n */\n private async attachSocketToNewHandler(\n socket: Socket,\n clientInfo: { clientAddress: string; clientPort: number },\n ): Promise<void> {\n this.handlerCount++\n\n this.log(\n `attachSocketToNewHandler: creating new handler for ${clientInfo.clientAddress}:${clientInfo.clientPort} (handler #${this.handlerCount})`,\n )\n\n // Create a new handler for this connection\n const handler = new PGLiteSocketHandler({\n db: this.db,\n closeOnDetach: true,\n inspect: this.inspect,\n debug: this.debug,\n })\n\n // Forward error events from the handler\n handler.addEventListener('error', (event) => {\n this.log(\n `handler #${handler.handlerId}: error from handler:`,\n (event as CustomEvent<Error>).detail,\n )\n this.dispatchEvent(\n new CustomEvent('error', {\n detail: (event as CustomEvent<Error>).detail,\n }),\n )\n })\n\n // Handle close event to process next queued connection\n handler.addEventListener('close', () => {\n this.log(`handler #${handler.handlerId}: closed`)\n\n // If this is our active handler, clear it\n if (this.activeHandler === handler) {\n this.log(\n `handler #${handler.handlerId}: was active handler, processing next connection in queue`,\n )\n this.activeHandler = null\n // Process next connection in queue\n this.processNextInQueue()\n }\n })\n\n try {\n // Set as active handler\n this.activeHandler = handler\n\n this.log(`handler #${handler.handlerId}: attaching socket`)\n\n // Attach the socket to the handler\n await handler.attach(socket)\n\n this.dispatchEvent(new CustomEvent('connection', { detail: clientInfo }))\n } catch (err) {\n // If there was an error attaching, clean up\n this.log(`handler #${handler.handlerId}: error attaching socket:`, err)\n this.activeHandler = null\n if (socket.writable) {\n socket.end()\n }\n throw err\n }\n }\n}\n"],"mappings":";;;AACA,SAAS,gBAAAA,SAAoC;AAGtC,IAAMC,IAA2B;AAAjC,IAoBMC,IAAN,MAAMA,WAA4B,YAAY;EAkBnD,YAAYC,GAAqC;AAC/C,UAAM;AAjBR,SAAQ,SAAwB;AAChC,SAAQ,SAAS;AAiBf,SAAK,KAAKA,EAAQ,IAClB,KAAK,gBAAgBA,EAAQ,iBAAiB,OAC9C,KAAK,UAAUA,EAAQ,WAAW,OAClC,KAAK,QAAQA,EAAQ,SAAS,OAC9B,KAAK,KAAKD,GAAoB,iBAE9B,KAAK,IAAI,kCAAkC;EAC7C;EAKA,IAAW,YAAoB;AAC7B,WAAO,KAAK;EACd;EAMQ,IAAIE,MAAoBC,GAAmB;AAC7C,SAAK,SACP,QAAQ,IAAI,wBAAwB,KAAK,EAAE,KAAKD,CAAO,IAAI,GAAGC,CAAI;EAEtE;EAQA,MAAa,OAAOC,GAA8C;AAKhE,QAJA,KAAK,IACH,iCAAiCA,EAAO,aAAa,IAAIA,EAAO,UAAU,EAC5E,GAEI,KAAK,OACP,OAAM,IAAI,MAAM,yBAAyB;AAG3C,WAAA,KAAK,SAASA,GACd,KAAK,SAAS,MAGd,KAAK,IAAI,wCAAwC,GACjD,MAAM,KAAK,GAAG,WAGd,KAAK,IAAI,qDAAqD,GAC9D,MAAM,IAAI,QAAeC,OAAY;AACnC,WAAK,GAAG,a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S,2DAC/B,GACA,KAAK,gBAAgB,MAErB,KAAK,mBAAmB;IAE5B,CAAC;AAED,QAAI;AAEF,WAAK,gBAAgBA,GAErB,KAAK,IAAI,YAAYA,EAAQ,SAAS,oBAAoB,GAG1D,MAAMA,EAAQ,OAAO1B,CAAM,GAE3B,KAAK,cAAc,IAAI,YAAY,cAAc,EAAE,QAAQuB,EAAW,CAAC,CAAC;IAC1E,SAASjB,GAAK;AAEZ,YAAA,KAAK,IAAI,YAAYoB,EAAQ,SAAS,6BAA6BpB,CAAG,GACtE,KAAK,gBAAgB,MACjBN,EAAO,YACTA,EAAO,IAAI,GAEPM;IACR;EACF;AACF;","names":["createServer","CONNECTION_QUEUE_TIMEOUT","_PGLiteSocketHandler","options","message","args","socket","resolve","resolveLock","rejectLock","data","result","err","close","_","reject","promise","direction","offset","chunkSize","hexPart","i","byte","asciiPart","PGLiteSocketHandler","PGLiteSocketServer","server","address","queuedConn","clientInfo","timeoutId","nextConn","handler","event"]}
|
|
@@ -0,0 +1,570 @@
|
|
|
1
|
+
import "./chunk-7D4SUZUM.js";
|
|
2
|
+
|
|
3
|
+
// ../../../node_modules/.pnpm/@hono+node-server@1.19.7_hono@4.11.1/node_modules/@hono/node-server/dist/index.mjs
|
|
4
|
+
import { createServer as createServerHTTP } from "http";
|
|
5
|
+
import { Http2ServerRequest as Http2ServerRequest2 } from "http2";
|
|
6
|
+
import { Http2ServerRequest } from "http2";
|
|
7
|
+
import { Readable } from "stream";
|
|
8
|
+
import crypto from "crypto";
|
|
9
|
+
var RequestError = class extends Error {
|
|
10
|
+
constructor(message, options) {
|
|
11
|
+
super(message, options);
|
|
12
|
+
this.name = "RequestError";
|
|
13
|
+
}
|
|
14
|
+
};
|
|
15
|
+
var toRequestError = (e) => {
|
|
16
|
+
if (e instanceof RequestError) {
|
|
17
|
+
return e;
|
|
18
|
+
}
|
|
19
|
+
return new RequestError(e.message, { cause: e });
|
|
20
|
+
};
|
|
21
|
+
var GlobalRequest = global.Request;
|
|
22
|
+
var Request = class extends GlobalRequest {
|
|
23
|
+
constructor(input, options) {
|
|
24
|
+
if (typeof input === "object" && getRequestCache in input) {
|
|
25
|
+
input = input[getRequestCache]();
|
|
26
|
+
}
|
|
27
|
+
if (typeof options?.body?.getReader !== "undefined") {
|
|
28
|
+
;
|
|
29
|
+
options.duplex ??= "half";
|
|
30
|
+
}
|
|
31
|
+
super(input, options);
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
var newHeadersFromIncoming = (incoming) => {
|
|
35
|
+
const headerRecord = [];
|
|
36
|
+
const rawHeaders = incoming.rawHeaders;
|
|
37
|
+
for (let i = 0; i < rawHeaders.length; i += 2) {
|
|
38
|
+
const { [i]: key, [i + 1]: value } = rawHeaders;
|
|
39
|
+
if (key.charCodeAt(0) !== /*:*/
|
|
40
|
+
58) {
|
|
41
|
+
headerRecord.push([key, value]);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
return new Headers(headerRecord);
|
|
45
|
+
};
|
|
46
|
+
var wrapBodyStream = Symbol("wrapBodyStream");
|
|
47
|
+
var newRequestFromIncoming = (method, url, headers, incoming, abortController) => {
|
|
48
|
+
const init = {
|
|
49
|
+
method,
|
|
50
|
+
headers,
|
|
51
|
+
signal: abortController.signal
|
|
52
|
+
};
|
|
53
|
+
if (method === "TRACE") {
|
|
54
|
+
init.method = "GET";
|
|
55
|
+
const req = new Request(url, init);
|
|
56
|
+
Object.defineProperty(req, "method", {
|
|
57
|
+
get() {
|
|
58
|
+
return "TRACE";
|
|
59
|
+
}
|
|
60
|
+
});
|
|
61
|
+
return req;
|
|
62
|
+
}
|
|
63
|
+
if (!(method === "GET" || method === "HEAD")) {
|
|
64
|
+
if ("rawBody" in incoming && incoming.rawBody instanceof Buffer) {
|
|
65
|
+
init.body = new ReadableStream({
|
|
66
|
+
start(controller) {
|
|
67
|
+
controller.enqueue(incoming.rawBody);
|
|
68
|
+
controller.close();
|
|
69
|
+
}
|
|
70
|
+
});
|
|
71
|
+
} else if (incoming[wrapBodyStream]) {
|
|
72
|
+
let reader;
|
|
73
|
+
init.body = new ReadableStream({
|
|
74
|
+
async pull(controller) {
|
|
75
|
+
try {
|
|
76
|
+
reader ||= Readable.toWeb(incoming).getReader();
|
|
77
|
+
const { done, value } = await reader.read();
|
|
78
|
+
if (done) {
|
|
79
|
+
controller.close();
|
|
80
|
+
} else {
|
|
81
|
+
controller.enqueue(value);
|
|
82
|
+
}
|
|
83
|
+
} catch (error) {
|
|
84
|
+
controller.error(error);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
});
|
|
88
|
+
} else {
|
|
89
|
+
init.body = Readable.toWeb(incoming);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return new Request(url, init);
|
|
93
|
+
};
|
|
94
|
+
var getRequestCache = Symbol("getRequestCache");
|
|
95
|
+
var requestCache = Symbol("requestCache");
|
|
96
|
+
var incomingKey = Symbol("incomingKey");
|
|
97
|
+
var urlKey = Symbol("urlKey");
|
|
98
|
+
var headersKey = Symbol("headersKey");
|
|
99
|
+
var abortControllerKey = Symbol("abortControllerKey");
|
|
100
|
+
var getAbortController = Symbol("getAbortController");
|
|
101
|
+
var requestPrototype = {
|
|
102
|
+
get method() {
|
|
103
|
+
return this[incomingKey].method || "GET";
|
|
104
|
+
},
|
|
105
|
+
get url() {
|
|
106
|
+
return this[urlKey];
|
|
107
|
+
},
|
|
108
|
+
get headers() {
|
|
109
|
+
return this[headersKey] ||= newHeadersFromIncoming(this[incomingKey]);
|
|
110
|
+
},
|
|
111
|
+
[getAbortController]() {
|
|
112
|
+
this[getRequestCache]();
|
|
113
|
+
return this[abortControllerKey];
|
|
114
|
+
},
|
|
115
|
+
[getRequestCache]() {
|
|
116
|
+
this[abortControllerKey] ||= new AbortController();
|
|
117
|
+
return this[requestCache] ||= newRequestFromIncoming(
|
|
118
|
+
this.method,
|
|
119
|
+
this[urlKey],
|
|
120
|
+
this.headers,
|
|
121
|
+
this[incomingKey],
|
|
122
|
+
this[abortControllerKey]
|
|
123
|
+
);
|
|
124
|
+
}
|
|
125
|
+
};
|
|
126
|
+
[
|
|
127
|
+
"body",
|
|
128
|
+
"bodyUsed",
|
|
129
|
+
"cache",
|
|
130
|
+
"credentials",
|
|
131
|
+
"destination",
|
|
132
|
+
"integrity",
|
|
133
|
+
"mode",
|
|
134
|
+
"redirect",
|
|
135
|
+
"referrer",
|
|
136
|
+
"referrerPolicy",
|
|
137
|
+
"signal",
|
|
138
|
+
"keepalive"
|
|
139
|
+
].forEach((k) => {
|
|
140
|
+
Object.defineProperty(requestPrototype, k, {
|
|
141
|
+
get() {
|
|
142
|
+
return this[getRequestCache]()[k];
|
|
143
|
+
}
|
|
144
|
+
});
|
|
145
|
+
});
|
|
146
|
+
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
|
|
147
|
+
Object.defineProperty(requestPrototype, k, {
|
|
148
|
+
value: function() {
|
|
149
|
+
return this[getRequestCache]()[k]();
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
});
|
|
153
|
+
Object.setPrototypeOf(requestPrototype, Request.prototype);
|
|
154
|
+
var newRequest = (incoming, defaultHostname) => {
|
|
155
|
+
const req = Object.create(requestPrototype);
|
|
156
|
+
req[incomingKey] = incoming;
|
|
157
|
+
const incomingUrl = incoming.url || "";
|
|
158
|
+
if (incomingUrl[0] !== "/" && // short-circuit for performance. most requests are relative URL.
|
|
159
|
+
(incomingUrl.startsWith("http://") || incomingUrl.startsWith("https://"))) {
|
|
160
|
+
if (incoming instanceof Http2ServerRequest) {
|
|
161
|
+
throw new RequestError("Absolute URL for :path is not allowed in HTTP/2");
|
|
162
|
+
}
|
|
163
|
+
try {
|
|
164
|
+
const url2 = new URL(incomingUrl);
|
|
165
|
+
req[urlKey] = url2.href;
|
|
166
|
+
} catch (e) {
|
|
167
|
+
throw new RequestError("Invalid absolute URL", { cause: e });
|
|
168
|
+
}
|
|
169
|
+
return req;
|
|
170
|
+
}
|
|
171
|
+
const host = (incoming instanceof Http2ServerRequest ? incoming.authority : incoming.headers.host) || defaultHostname;
|
|
172
|
+
if (!host) {
|
|
173
|
+
throw new RequestError("Missing host header");
|
|
174
|
+
}
|
|
175
|
+
let scheme;
|
|
176
|
+
if (incoming instanceof Http2ServerRequest) {
|
|
177
|
+
scheme = incoming.scheme;
|
|
178
|
+
if (!(scheme === "http" || scheme === "https")) {
|
|
179
|
+
throw new RequestError("Unsupported scheme");
|
|
180
|
+
}
|
|
181
|
+
} else {
|
|
182
|
+
scheme = incoming.socket && incoming.socket.encrypted ? "https" : "http";
|
|
183
|
+
}
|
|
184
|
+
const url = new URL(`${scheme}://${host}${incomingUrl}`);
|
|
185
|
+
if (url.hostname.length !== host.length && url.hostname !== host.replace(/:\d+$/, "")) {
|
|
186
|
+
throw new RequestError("Invalid host header");
|
|
187
|
+
}
|
|
188
|
+
req[urlKey] = url.href;
|
|
189
|
+
return req;
|
|
190
|
+
};
|
|
191
|
+
var responseCache = Symbol("responseCache");
|
|
192
|
+
var getResponseCache = Symbol("getResponseCache");
|
|
193
|
+
var cacheKey = Symbol("cache");
|
|
194
|
+
var GlobalResponse = global.Response;
|
|
195
|
+
var Response2 = class _Response {
|
|
196
|
+
#body;
|
|
197
|
+
#init;
|
|
198
|
+
[getResponseCache]() {
|
|
199
|
+
delete this[cacheKey];
|
|
200
|
+
return this[responseCache] ||= new GlobalResponse(this.#body, this.#init);
|
|
201
|
+
}
|
|
202
|
+
constructor(body, init) {
|
|
203
|
+
let headers;
|
|
204
|
+
this.#body = body;
|
|
205
|
+
if (init instanceof _Response) {
|
|
206
|
+
const cachedGlobalResponse = init[responseCache];
|
|
207
|
+
if (cachedGlobalResponse) {
|
|
208
|
+
this.#init = cachedGlobalResponse;
|
|
209
|
+
this[getResponseCache]();
|
|
210
|
+
return;
|
|
211
|
+
} else {
|
|
212
|
+
this.#init = init.#init;
|
|
213
|
+
headers = new Headers(init.#init.headers);
|
|
214
|
+
}
|
|
215
|
+
} else {
|
|
216
|
+
this.#init = init;
|
|
217
|
+
}
|
|
218
|
+
if (typeof body === "string" || typeof body?.getReader !== "undefined" || body instanceof Blob || body instanceof Uint8Array) {
|
|
219
|
+
headers ||= init?.headers || { "content-type": "text/plain; charset=UTF-8" };
|
|
220
|
+
this[cacheKey] = [init?.status || 200, body, headers];
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
get headers() {
|
|
224
|
+
const cache = this[cacheKey];
|
|
225
|
+
if (cache) {
|
|
226
|
+
if (!(cache[2] instanceof Headers)) {
|
|
227
|
+
cache[2] = new Headers(cache[2]);
|
|
228
|
+
}
|
|
229
|
+
return cache[2];
|
|
230
|
+
}
|
|
231
|
+
return this[getResponseCache]().headers;
|
|
232
|
+
}
|
|
233
|
+
get status() {
|
|
234
|
+
return this[cacheKey]?.[0] ?? this[getResponseCache]().status;
|
|
235
|
+
}
|
|
236
|
+
get ok() {
|
|
237
|
+
const status = this.status;
|
|
238
|
+
return status >= 200 && status < 300;
|
|
239
|
+
}
|
|
240
|
+
};
|
|
241
|
+
["body", "bodyUsed", "redirected", "statusText", "trailers", "type", "url"].forEach((k) => {
|
|
242
|
+
Object.defineProperty(Response2.prototype, k, {
|
|
243
|
+
get() {
|
|
244
|
+
return this[getResponseCache]()[k];
|
|
245
|
+
}
|
|
246
|
+
});
|
|
247
|
+
});
|
|
248
|
+
["arrayBuffer", "blob", "clone", "formData", "json", "text"].forEach((k) => {
|
|
249
|
+
Object.defineProperty(Response2.prototype, k, {
|
|
250
|
+
value: function() {
|
|
251
|
+
return this[getResponseCache]()[k]();
|
|
252
|
+
}
|
|
253
|
+
});
|
|
254
|
+
});
|
|
255
|
+
Object.setPrototypeOf(Response2, GlobalResponse);
|
|
256
|
+
Object.setPrototypeOf(Response2.prototype, GlobalResponse.prototype);
|
|
257
|
+
async function readWithoutBlocking(readPromise) {
|
|
258
|
+
return Promise.race([readPromise, Promise.resolve().then(() => Promise.resolve(void 0))]);
|
|
259
|
+
}
|
|
260
|
+
function writeFromReadableStreamDefaultReader(reader, writable, currentReadPromise) {
|
|
261
|
+
const cancel = (error) => {
|
|
262
|
+
reader.cancel(error).catch(() => {
|
|
263
|
+
});
|
|
264
|
+
};
|
|
265
|
+
writable.on("close", cancel);
|
|
266
|
+
writable.on("error", cancel);
|
|
267
|
+
(currentReadPromise ?? reader.read()).then(flow, handleStreamError);
|
|
268
|
+
return reader.closed.finally(() => {
|
|
269
|
+
writable.off("close", cancel);
|
|
270
|
+
writable.off("error", cancel);
|
|
271
|
+
});
|
|
272
|
+
function handleStreamError(error) {
|
|
273
|
+
if (error) {
|
|
274
|
+
writable.destroy(error);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
function onDrain() {
|
|
278
|
+
reader.read().then(flow, handleStreamError);
|
|
279
|
+
}
|
|
280
|
+
function flow({ done, value }) {
|
|
281
|
+
try {
|
|
282
|
+
if (done) {
|
|
283
|
+
writable.end();
|
|
284
|
+
} else if (!writable.write(value)) {
|
|
285
|
+
writable.once("drain", onDrain);
|
|
286
|
+
} else {
|
|
287
|
+
return reader.read().then(flow, handleStreamError);
|
|
288
|
+
}
|
|
289
|
+
} catch (e) {
|
|
290
|
+
handleStreamError(e);
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
function writeFromReadableStream(stream, writable) {
|
|
295
|
+
if (stream.locked) {
|
|
296
|
+
throw new TypeError("ReadableStream is locked.");
|
|
297
|
+
} else if (writable.destroyed) {
|
|
298
|
+
return;
|
|
299
|
+
}
|
|
300
|
+
return writeFromReadableStreamDefaultReader(stream.getReader(), writable);
|
|
301
|
+
}
|
|
302
|
+
var buildOutgoingHttpHeaders = (headers) => {
|
|
303
|
+
const res = {};
|
|
304
|
+
if (!(headers instanceof Headers)) {
|
|
305
|
+
headers = new Headers(headers ?? void 0);
|
|
306
|
+
}
|
|
307
|
+
const cookies = [];
|
|
308
|
+
for (const [k, v] of headers) {
|
|
309
|
+
if (k === "set-cookie") {
|
|
310
|
+
cookies.push(v);
|
|
311
|
+
} else {
|
|
312
|
+
res[k] = v;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
if (cookies.length > 0) {
|
|
316
|
+
res["set-cookie"] = cookies;
|
|
317
|
+
}
|
|
318
|
+
res["content-type"] ??= "text/plain; charset=UTF-8";
|
|
319
|
+
return res;
|
|
320
|
+
};
|
|
321
|
+
var X_ALREADY_SENT = "x-hono-already-sent";
|
|
322
|
+
var webFetch = global.fetch;
|
|
323
|
+
if (typeof global.crypto === "undefined") {
|
|
324
|
+
global.crypto = crypto;
|
|
325
|
+
}
|
|
326
|
+
global.fetch = (info, init) => {
|
|
327
|
+
init = {
|
|
328
|
+
// Disable compression handling so people can return the result of a fetch
|
|
329
|
+
// directly in the loader without messing with the Content-Encoding header.
|
|
330
|
+
compress: false,
|
|
331
|
+
...init
|
|
332
|
+
};
|
|
333
|
+
return webFetch(info, init);
|
|
334
|
+
};
|
|
335
|
+
var outgoingEnded = Symbol("outgoingEnded");
|
|
336
|
+
var handleRequestError = () => new Response(null, {
|
|
337
|
+
status: 400
|
|
338
|
+
});
|
|
339
|
+
var handleFetchError = (e) => new Response(null, {
|
|
340
|
+
status: e instanceof Error && (e.name === "TimeoutError" || e.constructor.name === "TimeoutError") ? 504 : 500
|
|
341
|
+
});
|
|
342
|
+
var handleResponseError = (e, outgoing) => {
|
|
343
|
+
const err = e instanceof Error ? e : new Error("unknown error", { cause: e });
|
|
344
|
+
if (err.code === "ERR_STREAM_PREMATURE_CLOSE") {
|
|
345
|
+
console.info("The user aborted a request.");
|
|
346
|
+
} else {
|
|
347
|
+
console.error(e);
|
|
348
|
+
if (!outgoing.headersSent) {
|
|
349
|
+
outgoing.writeHead(500, { "Content-Type": "text/plain" });
|
|
350
|
+
}
|
|
351
|
+
outgoing.end(`Error: ${err.message}`);
|
|
352
|
+
outgoing.destroy(err);
|
|
353
|
+
}
|
|
354
|
+
};
|
|
355
|
+
var flushHeaders = (outgoing) => {
|
|
356
|
+
if ("flushHeaders" in outgoing && outgoing.writable) {
|
|
357
|
+
outgoing.flushHeaders();
|
|
358
|
+
}
|
|
359
|
+
};
|
|
360
|
+
var responseViaCache = async (res, outgoing) => {
|
|
361
|
+
let [status, body, header] = res[cacheKey];
|
|
362
|
+
if (header instanceof Headers) {
|
|
363
|
+
header = buildOutgoingHttpHeaders(header);
|
|
364
|
+
}
|
|
365
|
+
if (typeof body === "string") {
|
|
366
|
+
header["Content-Length"] = Buffer.byteLength(body);
|
|
367
|
+
} else if (body instanceof Uint8Array) {
|
|
368
|
+
header["Content-Length"] = body.byteLength;
|
|
369
|
+
} else if (body instanceof Blob) {
|
|
370
|
+
header["Content-Length"] = body.size;
|
|
371
|
+
}
|
|
372
|
+
outgoing.writeHead(status, header);
|
|
373
|
+
if (typeof body === "string" || body instanceof Uint8Array) {
|
|
374
|
+
outgoing.end(body);
|
|
375
|
+
} else if (body instanceof Blob) {
|
|
376
|
+
outgoing.end(new Uint8Array(await body.arrayBuffer()));
|
|
377
|
+
} else {
|
|
378
|
+
flushHeaders(outgoing);
|
|
379
|
+
await writeFromReadableStream(body, outgoing)?.catch(
|
|
380
|
+
(e) => handleResponseError(e, outgoing)
|
|
381
|
+
);
|
|
382
|
+
}
|
|
383
|
+
;
|
|
384
|
+
outgoing[outgoingEnded]?.();
|
|
385
|
+
};
|
|
386
|
+
var isPromise = (res) => typeof res.then === "function";
|
|
387
|
+
var responseViaResponseObject = async (res, outgoing, options = {}) => {
|
|
388
|
+
if (isPromise(res)) {
|
|
389
|
+
if (options.errorHandler) {
|
|
390
|
+
try {
|
|
391
|
+
res = await res;
|
|
392
|
+
} catch (err) {
|
|
393
|
+
const errRes = await options.errorHandler(err);
|
|
394
|
+
if (!errRes) {
|
|
395
|
+
return;
|
|
396
|
+
}
|
|
397
|
+
res = errRes;
|
|
398
|
+
}
|
|
399
|
+
} else {
|
|
400
|
+
res = await res.catch(handleFetchError);
|
|
401
|
+
}
|
|
402
|
+
}
|
|
403
|
+
if (cacheKey in res) {
|
|
404
|
+
return responseViaCache(res, outgoing);
|
|
405
|
+
}
|
|
406
|
+
const resHeaderRecord = buildOutgoingHttpHeaders(res.headers);
|
|
407
|
+
if (res.body) {
|
|
408
|
+
const reader = res.body.getReader();
|
|
409
|
+
const values = [];
|
|
410
|
+
let done = false;
|
|
411
|
+
let currentReadPromise = void 0;
|
|
412
|
+
if (resHeaderRecord["transfer-encoding"] !== "chunked") {
|
|
413
|
+
let maxReadCount = 2;
|
|
414
|
+
for (let i = 0; i < maxReadCount; i++) {
|
|
415
|
+
currentReadPromise ||= reader.read();
|
|
416
|
+
const chunk = await readWithoutBlocking(currentReadPromise).catch((e) => {
|
|
417
|
+
console.error(e);
|
|
418
|
+
done = true;
|
|
419
|
+
});
|
|
420
|
+
if (!chunk) {
|
|
421
|
+
if (i === 1) {
|
|
422
|
+
await new Promise((resolve) => setTimeout(resolve));
|
|
423
|
+
maxReadCount = 3;
|
|
424
|
+
continue;
|
|
425
|
+
}
|
|
426
|
+
break;
|
|
427
|
+
}
|
|
428
|
+
currentReadPromise = void 0;
|
|
429
|
+
if (chunk.value) {
|
|
430
|
+
values.push(chunk.value);
|
|
431
|
+
}
|
|
432
|
+
if (chunk.done) {
|
|
433
|
+
done = true;
|
|
434
|
+
break;
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
if (done && !("content-length" in resHeaderRecord)) {
|
|
438
|
+
resHeaderRecord["content-length"] = values.reduce((acc, value) => acc + value.length, 0);
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
outgoing.writeHead(res.status, resHeaderRecord);
|
|
442
|
+
values.forEach((value) => {
|
|
443
|
+
;
|
|
444
|
+
outgoing.write(value);
|
|
445
|
+
});
|
|
446
|
+
if (done) {
|
|
447
|
+
outgoing.end();
|
|
448
|
+
} else {
|
|
449
|
+
if (values.length === 0) {
|
|
450
|
+
flushHeaders(outgoing);
|
|
451
|
+
}
|
|
452
|
+
await writeFromReadableStreamDefaultReader(reader, outgoing, currentReadPromise);
|
|
453
|
+
}
|
|
454
|
+
} else if (resHeaderRecord[X_ALREADY_SENT]) {
|
|
455
|
+
} else {
|
|
456
|
+
outgoing.writeHead(res.status, resHeaderRecord);
|
|
457
|
+
outgoing.end();
|
|
458
|
+
}
|
|
459
|
+
;
|
|
460
|
+
outgoing[outgoingEnded]?.();
|
|
461
|
+
};
|
|
462
|
+
var getRequestListener = (fetchCallback, options = {}) => {
|
|
463
|
+
const autoCleanupIncoming = options.autoCleanupIncoming ?? true;
|
|
464
|
+
if (options.overrideGlobalObjects !== false && global.Request !== Request) {
|
|
465
|
+
Object.defineProperty(global, "Request", {
|
|
466
|
+
value: Request
|
|
467
|
+
});
|
|
468
|
+
Object.defineProperty(global, "Response", {
|
|
469
|
+
value: Response2
|
|
470
|
+
});
|
|
471
|
+
}
|
|
472
|
+
return async (incoming, outgoing) => {
|
|
473
|
+
let res, req;
|
|
474
|
+
try {
|
|
475
|
+
req = newRequest(incoming, options.hostname);
|
|
476
|
+
let incomingEnded = !autoCleanupIncoming || incoming.method === "GET" || incoming.method === "HEAD";
|
|
477
|
+
if (!incomingEnded) {
|
|
478
|
+
;
|
|
479
|
+
incoming[wrapBodyStream] = true;
|
|
480
|
+
incoming.on("end", () => {
|
|
481
|
+
incomingEnded = true;
|
|
482
|
+
});
|
|
483
|
+
if (incoming instanceof Http2ServerRequest2) {
|
|
484
|
+
;
|
|
485
|
+
outgoing[outgoingEnded] = () => {
|
|
486
|
+
if (!incomingEnded) {
|
|
487
|
+
setTimeout(() => {
|
|
488
|
+
if (!incomingEnded) {
|
|
489
|
+
setTimeout(() => {
|
|
490
|
+
incoming.destroy();
|
|
491
|
+
outgoing.destroy();
|
|
492
|
+
});
|
|
493
|
+
}
|
|
494
|
+
});
|
|
495
|
+
}
|
|
496
|
+
};
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
outgoing.on("close", () => {
|
|
500
|
+
const abortController = req[abortControllerKey];
|
|
501
|
+
if (abortController) {
|
|
502
|
+
if (incoming.errored) {
|
|
503
|
+
req[abortControllerKey].abort(incoming.errored.toString());
|
|
504
|
+
} else if (!outgoing.writableFinished) {
|
|
505
|
+
req[abortControllerKey].abort("Client connection prematurely closed.");
|
|
506
|
+
}
|
|
507
|
+
}
|
|
508
|
+
if (!incomingEnded) {
|
|
509
|
+
setTimeout(() => {
|
|
510
|
+
if (!incomingEnded) {
|
|
511
|
+
setTimeout(() => {
|
|
512
|
+
incoming.destroy();
|
|
513
|
+
});
|
|
514
|
+
}
|
|
515
|
+
});
|
|
516
|
+
}
|
|
517
|
+
});
|
|
518
|
+
res = fetchCallback(req, { incoming, outgoing });
|
|
519
|
+
if (cacheKey in res) {
|
|
520
|
+
return responseViaCache(res, outgoing);
|
|
521
|
+
}
|
|
522
|
+
} catch (e) {
|
|
523
|
+
if (!res) {
|
|
524
|
+
if (options.errorHandler) {
|
|
525
|
+
res = await options.errorHandler(req ? e : toRequestError(e));
|
|
526
|
+
if (!res) {
|
|
527
|
+
return;
|
|
528
|
+
}
|
|
529
|
+
} else if (!req) {
|
|
530
|
+
res = handleRequestError();
|
|
531
|
+
} else {
|
|
532
|
+
res = handleFetchError(e);
|
|
533
|
+
}
|
|
534
|
+
} else {
|
|
535
|
+
return handleResponseError(e, outgoing);
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
try {
|
|
539
|
+
return await responseViaResponseObject(res, outgoing, options);
|
|
540
|
+
} catch (e) {
|
|
541
|
+
return handleResponseError(e, outgoing);
|
|
542
|
+
}
|
|
543
|
+
};
|
|
544
|
+
};
|
|
545
|
+
var createAdaptorServer = (options) => {
|
|
546
|
+
const fetchCallback = options.fetch;
|
|
547
|
+
const requestListener = getRequestListener(fetchCallback, {
|
|
548
|
+
hostname: options.hostname,
|
|
549
|
+
overrideGlobalObjects: options.overrideGlobalObjects,
|
|
550
|
+
autoCleanupIncoming: options.autoCleanupIncoming
|
|
551
|
+
});
|
|
552
|
+
const createServer = options.createServer || createServerHTTP;
|
|
553
|
+
const server = createServer(options.serverOptions || {}, requestListener);
|
|
554
|
+
return server;
|
|
555
|
+
};
|
|
556
|
+
var serve = (options, listeningListener) => {
|
|
557
|
+
const server = createAdaptorServer(options);
|
|
558
|
+
server.listen(options?.port ?? 3e3, options.hostname, () => {
|
|
559
|
+
const serverInfo = server.address();
|
|
560
|
+
listeningListener && listeningListener(serverInfo);
|
|
561
|
+
});
|
|
562
|
+
return server;
|
|
563
|
+
};
|
|
564
|
+
export {
|
|
565
|
+
RequestError,
|
|
566
|
+
createAdaptorServer,
|
|
567
|
+
getRequestListener,
|
|
568
|
+
serve
|
|
569
|
+
};
|
|
570
|
+
//# sourceMappingURL=dist-LCVVJCGI.js.map
|