File
Blob: src/node/https.ts
| 1 | // Copyright (c) 2017-2022 Cloudflare, Inc. |
| 2 | // Licensed under the Apache 2.0 license found in the LICENSE file or at: |
| 3 | // https://opensource.org/licenses/Apache-2.0 |
| 4 | // Copyright Joyent and Node contributors. All rights reserved. MIT license. |
| 5 | |
| 6 | import { urlToHttpOptions, isURL } from 'node-internal:internal_url'; |
| 7 | import { ClientRequest } from 'node-internal:internal_http_client'; |
| 8 | import { Agent, globalAgent } from 'node-internal:internal_https_agent'; |
| 9 | import { ERR_METHOD_NOT_IMPLEMENTED } from 'node-internal:internal_errors'; |
| 10 | import { Server } from 'node-internal:internal_https_server'; |
| 11 | import type { IncomingMessageCallback } from 'node-internal:internal_http_util'; |
| 12 | import type { RequestOptions, RequestListener } from 'node:http'; |
| 13 | import type { ServerOptions } from 'node:https'; |
| 14 | |
| 15 | const enableNodejsHttpServerModules = |
| 16 | !!Cloudflare.compatibilityFlags['enable_nodejs_http_server_modules']; |
| 17 | |
| 18 | export function request( |
| 19 | url: string | URL | RequestOptions, |
| 20 | options?: RequestOptions | IncomingMessageCallback, |
| 21 | cb?: IncomingMessageCallback |
| 22 | ): ClientRequest; |
| 23 | export function request(...args: unknown[]): ClientRequest { |
| 24 | let options: RequestOptions = {}; |
| 25 | |
| 26 | if (typeof args[0] === 'string') { |
| 27 | const urlStr = args.shift() as string; |
| 28 | options = urlToHttpOptions(new URL(urlStr)); |
| 29 | } else if (isURL(args[0])) { |
| 30 | options = urlToHttpOptions(args.shift() as URL); |
| 31 | } |
| 32 | |
| 33 | if (args.length > 0 && typeof args[0] !== 'function') { |
| 34 | Object.assign(options, args.shift()); |
| 35 | } |
| 36 | |
| 37 | options._defaultAgent = globalAgent; |
| 38 | args.unshift(options); |
| 39 | |
| 40 | // @ts-expect-error TS2556 This is OK. |
| 41 | return new ClientRequest(...args); |
| 42 | } |
| 43 | |
| 44 | export function get( |
| 45 | input: string | URL | RequestOptions, |
| 46 | options?: RequestOptions | IncomingMessageCallback, |
| 47 | cb?: IncomingMessageCallback |
| 48 | ): ClientRequest { |
| 49 | const req = request(input, options, cb); |
| 50 | req.end(); |
| 51 | return req; |
| 52 | } |
| 53 | |
| 54 | export function createServer( |
| 55 | options: ServerOptions, |
| 56 | handler: RequestListener |
| 57 | ): Server { |
| 58 | if (!enableNodejsHttpServerModules) { |
| 59 | throw new ERR_METHOD_NOT_IMPLEMENTED('createServer'); |
| 60 | } |
| 61 | |
| 62 | return new Server(options, handler); |
| 63 | } |
| 64 | |
| 65 | export { Agent, globalAgent, Server }; |
| 66 | |
| 67 | export default { |
| 68 | get, |
| 69 | request, |
| 70 | Agent, |
| 71 | globalAgent, |
| 72 | createServer, |
| 73 | Server, |
| 74 | }; |