network.ts 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import type { Argv, InferredOptionTypes } from "yargs"
  2. import { Config } from "../config/config"
  3. const options = {
  4. port: {
  5. type: "number" as const,
  6. describe: "port to listen on",
  7. default: 0,
  8. },
  9. hostname: {
  10. type: "string" as const,
  11. describe: "hostname to listen on",
  12. default: "127.0.0.1",
  13. },
  14. mdns: {
  15. type: "boolean" as const,
  16. describe: "enable mDNS service discovery (defaults hostname to 0.0.0.0)",
  17. default: false,
  18. },
  19. cors: {
  20. type: "string" as const,
  21. array: true,
  22. describe: "additional domains to allow for CORS",
  23. default: [] as string[],
  24. },
  25. }
  26. export type NetworkOptions = InferredOptionTypes<typeof options>
  27. export function withNetworkOptions<T>(yargs: Argv<T>) {
  28. return yargs.options(options)
  29. }
  30. export async function resolveNetworkOptions(args: NetworkOptions) {
  31. const config = await Config.global()
  32. const portExplicitlySet = process.argv.includes("--port")
  33. const hostnameExplicitlySet = process.argv.includes("--hostname")
  34. const mdnsExplicitlySet = process.argv.includes("--mdns")
  35. const corsExplicitlySet = process.argv.includes("--cors")
  36. const mdns = mdnsExplicitlySet ? args.mdns : (config?.server?.mdns ?? args.mdns)
  37. const port = portExplicitlySet ? args.port : (config?.server?.port ?? args.port)
  38. const hostname = hostnameExplicitlySet
  39. ? args.hostname
  40. : mdns && !config?.server?.hostname
  41. ? "0.0.0.0"
  42. : (config?.server?.hostname ?? args.hostname)
  43. const configCors = config?.server?.cors ?? []
  44. const argsCors = Array.isArray(args.cors) ? args.cors : args.cors ? [args.cors] : []
  45. const cors = [...configCors, ...argsCors]
  46. return { hostname, port, mdns, cors }
  47. }